repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
glenjamin/react-hotkey
index.js
handle
function handle(nativeEvent) { var event = SyntheticKeyboardEvent.getPooled({}, 'hotkey', nativeEvent); try { dispatchEvent(event, handlers); } finally { if (!event.isPersistent()) { event.constructor.release(event); } } }
javascript
function handle(nativeEvent) { var event = SyntheticKeyboardEvent.getPooled({}, 'hotkey', nativeEvent); try { dispatchEvent(event, handlers); } finally { if (!event.isPersistent()) { event.constructor.release(event); } } }
[ "function", "handle", "(", "nativeEvent", ")", "{", "var", "event", "=", "SyntheticKeyboardEvent", ".", "getPooled", "(", "{", "}", ",", "'hotkey'", ",", "nativeEvent", ")", ";", "try", "{", "dispatchEvent", "(", "event", ",", "handlers", ")", ";", "}", "finally", "{", "if", "(", "!", "event", ".", "isPersistent", "(", ")", ")", "{", "event", ".", "constructor", ".", "release", "(", "event", ")", ";", "}", "}", "}" ]
Create and dispatch an event object using React's object pool Cribbed from SimpleEventPlugin and EventPluginHub
[ "Create", "and", "dispatch", "an", "event", "object", "using", "React", "s", "object", "pool", "Cribbed", "from", "SimpleEventPlugin", "and", "EventPluginHub" ]
7cd9eec4f7f5c9f5a726c953591bcbb1c1668786
https://github.com/glenjamin/react-hotkey/blob/7cd9eec4f7f5c9f5a726c953591bcbb1c1668786/index.js#L73-L82
train
glenjamin/react-hotkey
index.js
dispatchEvent
function dispatchEvent(event, handlers) { for (var i = (handlers.length - 1); i >= 0; i--) { if (event.isPropagationStopped()) { break; } var returnValue = handlers[i](event); if (returnValue === false) { event.stopPropagation(); event.preventDefault(); } } }
javascript
function dispatchEvent(event, handlers) { for (var i = (handlers.length - 1); i >= 0; i--) { if (event.isPropagationStopped()) { break; } var returnValue = handlers[i](event); if (returnValue === false) { event.stopPropagation(); event.preventDefault(); } } }
[ "function", "dispatchEvent", "(", "event", ",", "handlers", ")", "{", "for", "(", "var", "i", "=", "(", "handlers", ".", "length", "-", "1", ")", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "event", ".", "isPropagationStopped", "(", ")", ")", "{", "break", ";", "}", "var", "returnValue", "=", "handlers", "[", "i", "]", "(", "event", ")", ";", "if", "(", "returnValue", "===", "false", ")", "{", "event", ".", "stopPropagation", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}", "}", "}" ]
Dispatch the event, in order, to all interested listeners The most recently mounted component is the first to receive the event Cribbed from a combination of SimpleEventPlugin and EventPluginUtils
[ "Dispatch", "the", "event", "in", "order", "to", "all", "interested", "listeners", "The", "most", "recently", "mounted", "component", "is", "the", "first", "to", "receive", "the", "event", "Cribbed", "from", "a", "combination", "of", "SimpleEventPlugin", "and", "EventPluginUtils" ]
7cd9eec4f7f5c9f5a726c953591bcbb1c1668786
https://github.com/glenjamin/react-hotkey/blob/7cd9eec4f7f5c9f5a726c953591bcbb1c1668786/index.js#L86-L97
train
cucumber-attic/gherkin-syntax-highlighters
shjs/shjs-0.6-src/scriptaculous-js-1.8.1/lib/prototype.js
function(nodes) { if (nodes.length == 0) return nodes; var results = [], n; for (var i = 0, l = nodes.length; i < l; i++) if (!(n = nodes[i])._counted) { n._counted = true; results.push(Element.extend(n)); } return Selector.handlers.unmark(results); }
javascript
function(nodes) { if (nodes.length == 0) return nodes; var results = [], n; for (var i = 0, l = nodes.length; i < l; i++) if (!(n = nodes[i])._counted) { n._counted = true; results.push(Element.extend(n)); } return Selector.handlers.unmark(results); }
[ "function", "(", "nodes", ")", "{", "if", "(", "nodes", ".", "length", "==", "0", ")", "return", "nodes", ";", "var", "results", "=", "[", "]", ",", "n", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "nodes", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "if", "(", "!", "(", "n", "=", "nodes", "[", "i", "]", ")", ".", "_counted", ")", "{", "n", ".", "_counted", "=", "true", ";", "results", ".", "push", "(", "Element", ".", "extend", "(", "n", ")", ")", ";", "}", "return", "Selector", ".", "handlers", ".", "unmark", "(", "results", ")", ";", "}" ]
filters out duplicates and extends all nodes
[ "filters", "out", "duplicates", "and", "extends", "all", "nodes" ]
0eb0eadc1bc274c86047d12f7267c6e905bd35be
https://github.com/cucumber-attic/gherkin-syntax-highlighters/blob/0eb0eadc1bc274c86047d12f7267c6e905bd35be/shjs/shjs-0.6-src/scriptaculous-js-1.8.1/lib/prototype.js#L3003-L3012
train
nwhetsell/csound-api
examples/log-json-syntax-tree.js
addNextNodesToASTObject
function addNextNodesToASTObject(ASTObject) { const ASTObjectsForDepths = [ASTObject]; function addNextNodes(ASTObject, depth) { const depthPlus1 = depth + 1; ASTObjectsForDepths[depthPlus1] = ASTObject; if (ASTObject.left) addNextNodes(ASTObject.left, depthPlus1); if (ASTObject.right) addNextNodes(ASTObject.right, depthPlus1); if (ASTObject.next) { const ASTObjectForDepth = ASTObjectsForDepths[depth]; if (ASTObjectForDepth.nextNodes) ASTObjectForDepth.nextNodes.push(ASTObject.next); else ASTObjectForDepth.nextNodes = [ASTObject.next]; addNextNodes(ASTObject.next, depth); } } addNextNodes(ASTObject, 0); }
javascript
function addNextNodesToASTObject(ASTObject) { const ASTObjectsForDepths = [ASTObject]; function addNextNodes(ASTObject, depth) { const depthPlus1 = depth + 1; ASTObjectsForDepths[depthPlus1] = ASTObject; if (ASTObject.left) addNextNodes(ASTObject.left, depthPlus1); if (ASTObject.right) addNextNodes(ASTObject.right, depthPlus1); if (ASTObject.next) { const ASTObjectForDepth = ASTObjectsForDepths[depth]; if (ASTObjectForDepth.nextNodes) ASTObjectForDepth.nextNodes.push(ASTObject.next); else ASTObjectForDepth.nextNodes = [ASTObject.next]; addNextNodes(ASTObject.next, depth); } } addNextNodes(ASTObject, 0); }
[ "function", "addNextNodesToASTObject", "(", "ASTObject", ")", "{", "const", "ASTObjectsForDepths", "=", "[", "ASTObject", "]", ";", "function", "addNextNodes", "(", "ASTObject", ",", "depth", ")", "{", "const", "depthPlus1", "=", "depth", "+", "1", ";", "ASTObjectsForDepths", "[", "depthPlus1", "]", "=", "ASTObject", ";", "if", "(", "ASTObject", ".", "left", ")", "addNextNodes", "(", "ASTObject", ".", "left", ",", "depthPlus1", ")", ";", "if", "(", "ASTObject", ".", "right", ")", "addNextNodes", "(", "ASTObject", ".", "right", ",", "depthPlus1", ")", ";", "if", "(", "ASTObject", ".", "next", ")", "{", "const", "ASTObjectForDepth", "=", "ASTObjectsForDepths", "[", "depth", "]", ";", "if", "(", "ASTObjectForDepth", ".", "nextNodes", ")", "ASTObjectForDepth", ".", "nextNodes", ".", "push", "(", "ASTObject", ".", "next", ")", ";", "else", "ASTObjectForDepth", ".", "nextNodes", "=", "[", "ASTObject", ".", "next", "]", ";", "addNextNodes", "(", "ASTObject", ".", "next", ",", "depth", ")", ";", "}", "}", "addNextNodes", "(", "ASTObject", ",", "0", ")", ";", "}" ]
The next property of an AST node seems to be for the second argument of an opcode, its next property for the third argument, and so on. Add nextNodes properties to AST objects to reflect this relationship.
[ "The", "next", "property", "of", "an", "AST", "node", "seems", "to", "be", "for", "the", "second", "argument", "of", "an", "opcode", "its", "next", "property", "for", "the", "third", "argument", "and", "so", "on", ".", "Add", "nextNodes", "properties", "to", "AST", "objects", "to", "reflect", "this", "relationship", "." ]
931d5b5ffe03f89f0269046e4306b444c6eb9393
https://github.com/nwhetsell/csound-api/blob/931d5b5ffe03f89f0269046e4306b444c6eb9393/examples/log-json-syntax-tree.js#L21-L40
train
bmancini55/node-trx
trx.js
Counter
function Counter() { this.total = 0; this.executed = 0; this.passed = 0; this.error = 0; this.failed = 0; this.timeout = 0; this.aborted = 0; this.inconclusive = 0; this.passedButRunAborted = 0; this.notRunnable = 0; this.notExecuted = 0; this.disconnected = 0; this.warning = 0; this.completed = 0; this.inProgress = 0; this.pending = 0; }
javascript
function Counter() { this.total = 0; this.executed = 0; this.passed = 0; this.error = 0; this.failed = 0; this.timeout = 0; this.aborted = 0; this.inconclusive = 0; this.passedButRunAborted = 0; this.notRunnable = 0; this.notExecuted = 0; this.disconnected = 0; this.warning = 0; this.completed = 0; this.inProgress = 0; this.pending = 0; }
[ "function", "Counter", "(", ")", "{", "this", ".", "total", "=", "0", ";", "this", ".", "executed", "=", "0", ";", "this", ".", "passed", "=", "0", ";", "this", ".", "error", "=", "0", ";", "this", ".", "failed", "=", "0", ";", "this", ".", "timeout", "=", "0", ";", "this", ".", "aborted", "=", "0", ";", "this", ".", "inconclusive", "=", "0", ";", "this", ".", "passedButRunAborted", "=", "0", ";", "this", ".", "notRunnable", "=", "0", ";", "this", ".", "notExecuted", "=", "0", ";", "this", ".", "disconnected", "=", "0", ";", "this", ".", "warning", "=", "0", ";", "this", ".", "completed", "=", "0", ";", "this", ".", "inProgress", "=", "0", ";", "this", ".", "pending", "=", "0", ";", "}" ]
Counter is defined by the XSD
[ "Counter", "is", "defined", "by", "the", "XSD" ]
139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281
https://github.com/bmancini55/node-trx/blob/139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281/trx.js#L137-L154
train
bmancini55/node-trx
trx.js
Times
function Times(params) { this.creation = params.creation; this.queuing = params.queuing; this.start = params.start; this.finish = params.finish; }
javascript
function Times(params) { this.creation = params.creation; this.queuing = params.queuing; this.start = params.start; this.finish = params.finish; }
[ "function", "Times", "(", "params", ")", "{", "this", ".", "creation", "=", "params", ".", "creation", ";", "this", ".", "queuing", "=", "params", ".", "queuing", ";", "this", ".", "start", "=", "params", ".", "start", ";", "this", ".", "finish", "=", "params", ".", "finish", ";", "}" ]
A Times as defined by the XSD type `Times` @param {object} params @config creation @config queuing @config start @config finish
[ "A", "Times", "as", "defined", "by", "the", "XSD", "type", "Times" ]
139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281
https://github.com/bmancini55/node-trx/blob/139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281/trx.js#L199-L204
train
bmancini55/node-trx
trx.js
Deployment
function Deployment(params) { this.runDeploymentRoot = params.runDeploymentRoot this.userDeploymentRoot = params.userDeploymentRoot this.deploySatelliteAssemblies = params.deploySatelliteAssemblies this.ignoredDependentAssemblies = params.ignoredDependentAssemblies this.enabled = params.enabled }
javascript
function Deployment(params) { this.runDeploymentRoot = params.runDeploymentRoot this.userDeploymentRoot = params.userDeploymentRoot this.deploySatelliteAssemblies = params.deploySatelliteAssemblies this.ignoredDependentAssemblies = params.ignoredDependentAssemblies this.enabled = params.enabled }
[ "function", "Deployment", "(", "params", ")", "{", "this", ".", "runDeploymentRoot", "=", "params", ".", "runDeploymentRoot", "this", ".", "userDeploymentRoot", "=", "params", ".", "userDeploymentRoot", "this", ".", "deploySatelliteAssemblies", "=", "params", ".", "deploySatelliteAssemblies", "this", ".", "ignoredDependentAssemblies", "=", "params", ".", "ignoredDependentAssemblies", "this", ".", "enabled", "=", "params", ".", "enabled", "}" ]
A Deployment element as defined by the XSD type `Deployment` @param {object} params @config {string} [runDeploymentRoot] - name of the folder where any files generated by the tests will be located @config {string} [userDeploymentRoot] @config {string} [deploySatelliteAssemblies] @config {string} [ignoredDependentAssemblies] @config {string} [enabled]
[ "A", "Deployment", "element", "as", "defined", "by", "the", "XSD", "type", "Deployment" ]
139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281
https://github.com/bmancini55/node-trx/blob/139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281/trx.js#L228-L234
train
claudio-silva/grunt-angular-builder
tasks/angular-builder.js
assembleMiddleware
function assembleMiddleware (middlewareStackClasses, context) { var middlewares = []; middlewareStackClasses.forEach (function (MiddlewareClass) { middlewares.push (new MiddlewareClass (context)); }); return middlewares; }
javascript
function assembleMiddleware (middlewareStackClasses, context) { var middlewares = []; middlewareStackClasses.forEach (function (MiddlewareClass) { middlewares.push (new MiddlewareClass (context)); }); return middlewares; }
[ "function", "assembleMiddleware", "(", "middlewareStackClasses", ",", "context", ")", "{", "var", "middlewares", "=", "[", "]", ";", "middlewareStackClasses", ".", "forEach", "(", "function", "(", "MiddlewareClass", ")", "{", "middlewares", ".", "push", "(", "new", "MiddlewareClass", "(", "context", ")", ")", ";", "}", ")", ";", "return", "middlewares", ";", "}" ]
Creates a new instance of each loaded middleware and assembles them into a sequential list. @param {MiddlewareInterface[]} middlewareStackClasses An ordered list of classes to be instantiated. @param {Context} context The build execution context. @returns {MiddlewareInterface[]}
[ "Creates", "a", "new", "instance", "of", "each", "loaded", "middleware", "and", "assembles", "them", "into", "a", "sequential", "list", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/angular-builder.js#L172-L180
train
claudio-silva/grunt-angular-builder
tasks/angular-builder.js
traceModule
function traceModule (moduleName, context, processHook) { var module = context.modules[moduleName]; if (!module) fatal ('Module <cyan>%</cyan> was not found.', moduleName); // Ignore the module if it's external. if (module.external) return; // Include required submodules first. context.trigger (ContextEvent.ON_BEFORE_DEPS, [module]); module.requires.forEach (function (modName) { traceModule (modName, context, processHook); }); // Ignore references to already loaded modules or to explicitly excluded modules. if (!context.loaded[module.name] && !~context.options.excludedModules.indexOf (module.name)) { info ('Including module <cyan>%</cyan>.', moduleName); context.loaded[module.name] = true; processHook (module); } }
javascript
function traceModule (moduleName, context, processHook) { var module = context.modules[moduleName]; if (!module) fatal ('Module <cyan>%</cyan> was not found.', moduleName); // Ignore the module if it's external. if (module.external) return; // Include required submodules first. context.trigger (ContextEvent.ON_BEFORE_DEPS, [module]); module.requires.forEach (function (modName) { traceModule (modName, context, processHook); }); // Ignore references to already loaded modules or to explicitly excluded modules. if (!context.loaded[module.name] && !~context.options.excludedModules.indexOf (module.name)) { info ('Including module <cyan>%</cyan>.', moduleName); context.loaded[module.name] = true; processHook (module); } }
[ "function", "traceModule", "(", "moduleName", ",", "context", ",", "processHook", ")", "{", "var", "module", "=", "context", ".", "modules", "[", "moduleName", "]", ";", "if", "(", "!", "module", ")", "fatal", "(", "'Module <cyan>%</cyan> was not found.'", ",", "moduleName", ")", ";", "if", "(", "module", ".", "external", ")", "return", ";", "context", ".", "trigger", "(", "ContextEvent", ".", "ON_BEFORE_DEPS", ",", "[", "module", "]", ")", ";", "module", ".", "requires", ".", "forEach", "(", "function", "(", "modName", ")", "{", "traceModule", "(", "modName", ",", "context", ",", "processHook", ")", ";", "}", ")", ";", "if", "(", "!", "context", ".", "loaded", "[", "module", ".", "name", "]", "&&", "!", "~", "context", ".", "options", ".", "excludedModules", ".", "indexOf", "(", "module", ".", "name", ")", ")", "{", "info", "(", "'Including module <cyan>%</cyan>.'", ",", "moduleName", ")", ";", "context", ".", "loaded", "[", "module", ".", "name", "]", "=", "true", ";", "processHook", "(", "module", ")", ";", "}", "}" ]
Traces a dependency graph for the specified module and calls the given callback to process each required module in the correct loading order. @param {string} moduleName @param {Context} context The execution context for the middleware stack. @param {function(ModuleDef)} processHook
[ "Traces", "a", "dependency", "graph", "for", "the", "specified", "module", "and", "calls", "the", "given", "callback", "to", "process", "each", "required", "module", "in", "the", "correct", "loading", "order", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/angular-builder.js#L189-L209
train
JamesMessinger/json-schema-lib
lib/util/safeCall.js
safeCall
function safeCall (fn, args, callback) { args = Array.prototype.slice.call(arguments, 1); callback = args.pop(); var callbackCalled; try { args.push(safeCallback); fn.apply(null, args); } catch (err) { if (callbackCalled) { throw err; } else { safeCallback(err); } } function safeCallback (err, result) { if (callbackCalled) { err = ono('Error in %s: callback was called multiple times', fn.name); } callbackCalled = true; callback(err, result); } }
javascript
function safeCall (fn, args, callback) { args = Array.prototype.slice.call(arguments, 1); callback = args.pop(); var callbackCalled; try { args.push(safeCallback); fn.apply(null, args); } catch (err) { if (callbackCalled) { throw err; } else { safeCallback(err); } } function safeCallback (err, result) { if (callbackCalled) { err = ono('Error in %s: callback was called multiple times', fn.name); } callbackCalled = true; callback(err, result); } }
[ "function", "safeCall", "(", "fn", ",", "args", ",", "callback", ")", "{", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "callback", "=", "args", ".", "pop", "(", ")", ";", "var", "callbackCalled", ";", "try", "{", "args", ".", "push", "(", "safeCallback", ")", ";", "fn", ".", "apply", "(", "null", ",", "args", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "callbackCalled", ")", "{", "throw", "err", ";", "}", "else", "{", "safeCallback", "(", "err", ")", ";", "}", "}", "function", "safeCallback", "(", "err", ",", "result", ")", "{", "if", "(", "callbackCalled", ")", "{", "err", "=", "ono", "(", "'Error in %s: callback was called multiple times'", ",", "fn", ".", "name", ")", ";", "}", "callbackCalled", "=", "true", ";", "callback", "(", "err", ",", "result", ")", ";", "}", "}" ]
Calls the specified function with the given arguments, ensuring that the callback is only called once, and that it's called even if an unhandled error occurs. @param {function} fn - The function to call @param {...*} [args] - The arguments to pass to the function @param {function} callback - The callback function
[ "Calls", "the", "specified", "function", "with", "the", "given", "arguments", "ensuring", "that", "the", "callback", "is", "only", "called", "once", "and", "that", "it", "s", "called", "even", "if", "an", "unhandled", "error", "occurs", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/safeCall.js#L15-L41
train
JamesMessinger/json-schema-lib
lib/api/JsonSchemaLib/read.js
readReferencedFiles
function readReferencedFiles (schema, callback) { var filesBeingRead = [], filesToRead = []; var file, i; // Check the state of all files in the schema for (i = 0; i < schema.files.length; i++) { file = schema.files[i]; if (file[__internal].state < STATE_READING) { filesToRead.push(file); } else if (file[__internal].state < STATE_READ) { filesBeingRead.push(file); } } // Have we finished reading everything? if (filesToRead.length === 0 && filesBeingRead.length === 0) { return safeCall(finished, schema, callback); } // In sync mode, just read the next file. // In async mode, start reading all files in the queue var numberOfFilesToRead = schema.config.sync ? 1 : filesToRead.length; for (i = 0; i < numberOfFilesToRead; i++) { file = filesToRead[i]; safeCall(readFile, file, callback); } }
javascript
function readReferencedFiles (schema, callback) { var filesBeingRead = [], filesToRead = []; var file, i; // Check the state of all files in the schema for (i = 0; i < schema.files.length; i++) { file = schema.files[i]; if (file[__internal].state < STATE_READING) { filesToRead.push(file); } else if (file[__internal].state < STATE_READ) { filesBeingRead.push(file); } } // Have we finished reading everything? if (filesToRead.length === 0 && filesBeingRead.length === 0) { return safeCall(finished, schema, callback); } // In sync mode, just read the next file. // In async mode, start reading all files in the queue var numberOfFilesToRead = schema.config.sync ? 1 : filesToRead.length; for (i = 0; i < numberOfFilesToRead; i++) { file = filesToRead[i]; safeCall(readFile, file, callback); } }
[ "function", "readReferencedFiles", "(", "schema", ",", "callback", ")", "{", "var", "filesBeingRead", "=", "[", "]", ",", "filesToRead", "=", "[", "]", ";", "var", "file", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "schema", ".", "files", ".", "length", ";", "i", "++", ")", "{", "file", "=", "schema", ".", "files", "[", "i", "]", ";", "if", "(", "file", "[", "__internal", "]", ".", "state", "<", "STATE_READING", ")", "{", "filesToRead", ".", "push", "(", "file", ")", ";", "}", "else", "if", "(", "file", "[", "__internal", "]", ".", "state", "<", "STATE_READ", ")", "{", "filesBeingRead", ".", "push", "(", "file", ")", ";", "}", "}", "if", "(", "filesToRead", ".", "length", "===", "0", "&&", "filesBeingRead", ".", "length", "===", "0", ")", "{", "return", "safeCall", "(", "finished", ",", "schema", ",", "callback", ")", ";", "}", "var", "numberOfFilesToRead", "=", "schema", ".", "config", ".", "sync", "?", "1", ":", "filesToRead", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "numberOfFilesToRead", ";", "i", "++", ")", "{", "file", "=", "filesToRead", "[", "i", "]", ";", "safeCall", "(", "readFile", ",", "file", ",", "callback", ")", ";", "}", "}" ]
Reads any files in the schema that haven't been read yet. @param {Schema} schema @param {function} callback
[ "Reads", "any", "files", "in", "the", "schema", "that", "haven", "t", "been", "read", "yet", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/JsonSchemaLib/read.js#L113-L142
train
JamesMessinger/json-schema-lib
lib/api/JsonSchemaLib/read.js
finished
function finished (schema, callback) { schema.plugins.finished(); delete schema.config.sync; callback(null, schema); }
javascript
function finished (schema, callback) { schema.plugins.finished(); delete schema.config.sync; callback(null, schema); }
[ "function", "finished", "(", "schema", ",", "callback", ")", "{", "schema", ".", "plugins", ".", "finished", "(", ")", ";", "delete", "schema", ".", "config", ".", "sync", ";", "callback", "(", "null", ",", "schema", ")", ";", "}" ]
Performs final cleanup steps on the schema after all files have been read successfully. @param {Schema} schema @param {function} callback
[ "Performs", "final", "cleanup", "steps", "on", "the", "schema", "after", "all", "files", "have", "been", "read", "successfully", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/JsonSchemaLib/read.js#L150-L154
train
matteodelabre/midijs
lib/file/parser/event.js
parseMetaEvent
function parseMetaEvent(delay, cursor) { var type, specs = {}, length, value, rates; rates = [24, 25, 30, 30]; type = cursor.readUInt8(); length = parseVarInt(cursor); switch (type) { case MetaEvent.TYPE.SEQUENCE_NUMBER: specs.number = cursor.readUInt16LE(); break; case MetaEvent.TYPE.TEXT: case MetaEvent.TYPE.COPYRIGHT_NOTICE: case MetaEvent.TYPE.SEQUENCE_NAME: case MetaEvent.TYPE.INSTRUMENT_NAME: case MetaEvent.TYPE.LYRICS: case MetaEvent.TYPE.MARKER: case MetaEvent.TYPE.CUE_POINT: case MetaEvent.TYPE.PROGRAM_NAME: case MetaEvent.TYPE.DEVICE_NAME: specs.text = cursor.toString('utf8', length); break; case MetaEvent.TYPE.MIDI_CHANNEL: specs.channel = cursor.readUInt8(); break; case MetaEvent.TYPE.MIDI_PORT: specs.port = cursor.readUInt8(); break; case MetaEvent.TYPE.END_OF_TRACK: break; case MetaEvent.TYPE.SET_TEMPO: specs.tempo = 60000000 / ((cursor.readUInt8() << 16) + (cursor.readUInt8() << 8) + cursor.readUInt8()); break; case MetaEvent.TYPE.SMPTE_OFFSET: value = cursor.readUInt8(); specs.rate = rates[value >> 6]; specs.hours = value & 0x3F; specs.minutes = cursor.readUInt8(); specs.seconds = cursor.readUInt8(); specs.frames = cursor.readUInt8(); specs.subframes = cursor.readUInt8(); break; case MetaEvent.TYPE.TIME_SIGNATURE: specs.numerator = cursor.readUInt8(); specs.denominator = Math.pow(2, cursor.readUInt8()); specs.metronome = cursor.readUInt8(); specs.clockSignalsPerBeat = (192 / cursor.readUInt8()); break; case MetaEvent.TYPE.KEY_SIGNATURE: specs.note = cursor.readInt8(); specs.major = !cursor.readUInt8(); break; case MetaEvent.TYPE.SEQUENCER_SPECIFIC: specs.data = cursor.slice(length).buffer; break; default: throw new error.MIDIParserError( type, 'known MetaEvent type', cursor.tell() ); } return new MetaEvent(type, specs, delay); }
javascript
function parseMetaEvent(delay, cursor) { var type, specs = {}, length, value, rates; rates = [24, 25, 30, 30]; type = cursor.readUInt8(); length = parseVarInt(cursor); switch (type) { case MetaEvent.TYPE.SEQUENCE_NUMBER: specs.number = cursor.readUInt16LE(); break; case MetaEvent.TYPE.TEXT: case MetaEvent.TYPE.COPYRIGHT_NOTICE: case MetaEvent.TYPE.SEQUENCE_NAME: case MetaEvent.TYPE.INSTRUMENT_NAME: case MetaEvent.TYPE.LYRICS: case MetaEvent.TYPE.MARKER: case MetaEvent.TYPE.CUE_POINT: case MetaEvent.TYPE.PROGRAM_NAME: case MetaEvent.TYPE.DEVICE_NAME: specs.text = cursor.toString('utf8', length); break; case MetaEvent.TYPE.MIDI_CHANNEL: specs.channel = cursor.readUInt8(); break; case MetaEvent.TYPE.MIDI_PORT: specs.port = cursor.readUInt8(); break; case MetaEvent.TYPE.END_OF_TRACK: break; case MetaEvent.TYPE.SET_TEMPO: specs.tempo = 60000000 / ((cursor.readUInt8() << 16) + (cursor.readUInt8() << 8) + cursor.readUInt8()); break; case MetaEvent.TYPE.SMPTE_OFFSET: value = cursor.readUInt8(); specs.rate = rates[value >> 6]; specs.hours = value & 0x3F; specs.minutes = cursor.readUInt8(); specs.seconds = cursor.readUInt8(); specs.frames = cursor.readUInt8(); specs.subframes = cursor.readUInt8(); break; case MetaEvent.TYPE.TIME_SIGNATURE: specs.numerator = cursor.readUInt8(); specs.denominator = Math.pow(2, cursor.readUInt8()); specs.metronome = cursor.readUInt8(); specs.clockSignalsPerBeat = (192 / cursor.readUInt8()); break; case MetaEvent.TYPE.KEY_SIGNATURE: specs.note = cursor.readInt8(); specs.major = !cursor.readUInt8(); break; case MetaEvent.TYPE.SEQUENCER_SPECIFIC: specs.data = cursor.slice(length).buffer; break; default: throw new error.MIDIParserError( type, 'known MetaEvent type', cursor.tell() ); } return new MetaEvent(type, specs, delay); }
[ "function", "parseMetaEvent", "(", "delay", ",", "cursor", ")", "{", "var", "type", ",", "specs", "=", "{", "}", ",", "length", ",", "value", ",", "rates", ";", "rates", "=", "[", "24", ",", "25", ",", "30", ",", "30", "]", ";", "type", "=", "cursor", ".", "readUInt8", "(", ")", ";", "length", "=", "parseVarInt", "(", "cursor", ")", ";", "switch", "(", "type", ")", "{", "case", "MetaEvent", ".", "TYPE", ".", "SEQUENCE_NUMBER", ":", "specs", ".", "number", "=", "cursor", ".", "readUInt16LE", "(", ")", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "TEXT", ":", "case", "MetaEvent", ".", "TYPE", ".", "COPYRIGHT_NOTICE", ":", "case", "MetaEvent", ".", "TYPE", ".", "SEQUENCE_NAME", ":", "case", "MetaEvent", ".", "TYPE", ".", "INSTRUMENT_NAME", ":", "case", "MetaEvent", ".", "TYPE", ".", "LYRICS", ":", "case", "MetaEvent", ".", "TYPE", ".", "MARKER", ":", "case", "MetaEvent", ".", "TYPE", ".", "CUE_POINT", ":", "case", "MetaEvent", ".", "TYPE", ".", "PROGRAM_NAME", ":", "case", "MetaEvent", ".", "TYPE", ".", "DEVICE_NAME", ":", "specs", ".", "text", "=", "cursor", ".", "toString", "(", "'utf8'", ",", "length", ")", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "MIDI_CHANNEL", ":", "specs", ".", "channel", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "MIDI_PORT", ":", "specs", ".", "port", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "END_OF_TRACK", ":", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "SET_TEMPO", ":", "specs", ".", "tempo", "=", "60000000", "/", "(", "(", "cursor", ".", "readUInt8", "(", ")", "<<", "16", ")", "+", "(", "cursor", ".", "readUInt8", "(", ")", "<<", "8", ")", "+", "cursor", ".", "readUInt8", "(", ")", ")", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "SMPTE_OFFSET", ":", "value", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "rate", "=", "rates", "[", "value", ">>", "6", "]", ";", "specs", ".", "hours", "=", "value", "&", "0x3F", ";", "specs", ".", "minutes", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "seconds", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "frames", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "subframes", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "TIME_SIGNATURE", ":", "specs", ".", "numerator", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "denominator", "=", "Math", ".", "pow", "(", "2", ",", "cursor", ".", "readUInt8", "(", ")", ")", ";", "specs", ".", "metronome", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "clockSignalsPerBeat", "=", "(", "192", "/", "cursor", ".", "readUInt8", "(", ")", ")", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "KEY_SIGNATURE", ":", "specs", ".", "note", "=", "cursor", ".", "readInt8", "(", ")", ";", "specs", ".", "major", "=", "!", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "SEQUENCER_SPECIFIC", ":", "specs", ".", "data", "=", "cursor", ".", "slice", "(", "length", ")", ".", "buffer", ";", "break", ";", "default", ":", "throw", "new", "error", ".", "MIDIParserError", "(", "type", ",", "'known MetaEvent type'", ",", "cursor", ".", "tell", "(", ")", ")", ";", "}", "return", "new", "MetaEvent", "(", "type", ",", "specs", ",", "delay", ")", ";", "}" ]
Parse a meta MIDI event @private @param {number} delay Event delay in ticks @param {module:buffercursor} cursor Buffer to parse @throws {module:midijs/lib/error~MIDIParserError} Failed to parse the meta event @return {module:midijs/lib/file/event~MetaEvent} Parsed meta event
[ "Parse", "a", "meta", "MIDI", "event" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/event.js#L40-L107
train
matteodelabre/midijs
lib/file/parser/event.js
parseSysexEvent
function parseSysexEvent(delay, type, cursor) { var data, length = parseVarInt(cursor); data = cursor.slice(length).buffer; return new SysexEvent(type, data, delay); }
javascript
function parseSysexEvent(delay, type, cursor) { var data, length = parseVarInt(cursor); data = cursor.slice(length).buffer; return new SysexEvent(type, data, delay); }
[ "function", "parseSysexEvent", "(", "delay", ",", "type", ",", "cursor", ")", "{", "var", "data", ",", "length", "=", "parseVarInt", "(", "cursor", ")", ";", "data", "=", "cursor", ".", "slice", "(", "length", ")", ".", "buffer", ";", "return", "new", "SysexEvent", "(", "type", ",", "data", ",", "delay", ")", ";", "}" ]
Parse a system exclusive MIDI event @private @param {number} delay Event delay in ticks @param {number} type Sysex type @param {module:buffercursor} cursor Buffer to parse @return {module:midijs/lib/file/event~SysexEvent} Parsed sysex event
[ "Parse", "a", "system", "exclusive", "MIDI", "event" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/event.js#L118-L123
train
matteodelabre/midijs
lib/file/parser/event.js
parseChannelEvent
function parseChannelEvent(delay, type, channel, cursor) { var specs = {}; switch (type) { case ChannelEvent.TYPE.NOTE_OFF: specs.note = cursor.readUInt8(); specs.velocity = cursor.readUInt8(); break; case ChannelEvent.TYPE.NOTE_ON: specs.note = cursor.readUInt8(); specs.velocity = cursor.readUInt8(); break; case ChannelEvent.TYPE.NOTE_AFTERTOUCH: specs.note = cursor.readUInt8(); specs.pressure = cursor.readUInt8(); break; case ChannelEvent.TYPE.CONTROLLER: specs.controller = cursor.readUInt8(); specs.value = cursor.readUInt8(); break; case ChannelEvent.TYPE.PROGRAM_CHANGE: specs.program = cursor.readUInt8(); break; case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH: specs.pressure = cursor.readUInt8(); break; case ChannelEvent.TYPE.PITCH_BEND: specs.value = cursor.readUInt8() + (cursor.readUInt8() << 7) - 8192; break; } return new ChannelEvent(type, specs, channel, delay); }
javascript
function parseChannelEvent(delay, type, channel, cursor) { var specs = {}; switch (type) { case ChannelEvent.TYPE.NOTE_OFF: specs.note = cursor.readUInt8(); specs.velocity = cursor.readUInt8(); break; case ChannelEvent.TYPE.NOTE_ON: specs.note = cursor.readUInt8(); specs.velocity = cursor.readUInt8(); break; case ChannelEvent.TYPE.NOTE_AFTERTOUCH: specs.note = cursor.readUInt8(); specs.pressure = cursor.readUInt8(); break; case ChannelEvent.TYPE.CONTROLLER: specs.controller = cursor.readUInt8(); specs.value = cursor.readUInt8(); break; case ChannelEvent.TYPE.PROGRAM_CHANGE: specs.program = cursor.readUInt8(); break; case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH: specs.pressure = cursor.readUInt8(); break; case ChannelEvent.TYPE.PITCH_BEND: specs.value = cursor.readUInt8() + (cursor.readUInt8() << 7) - 8192; break; } return new ChannelEvent(type, specs, channel, delay); }
[ "function", "parseChannelEvent", "(", "delay", ",", "type", ",", "channel", ",", "cursor", ")", "{", "var", "specs", "=", "{", "}", ";", "switch", "(", "type", ")", "{", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_OFF", ":", "specs", ".", "note", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "velocity", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_ON", ":", "specs", ".", "note", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "velocity", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_AFTERTOUCH", ":", "specs", ".", "note", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "pressure", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "CONTROLLER", ":", "specs", ".", "controller", "=", "cursor", ".", "readUInt8", "(", ")", ";", "specs", ".", "value", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "PROGRAM_CHANGE", ":", "specs", ".", "program", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "CHANNEL_AFTERTOUCH", ":", "specs", ".", "pressure", "=", "cursor", ".", "readUInt8", "(", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "PITCH_BEND", ":", "specs", ".", "value", "=", "cursor", ".", "readUInt8", "(", ")", "+", "(", "cursor", ".", "readUInt8", "(", ")", "<<", "7", ")", "-", "8192", ";", "break", ";", "}", "return", "new", "ChannelEvent", "(", "type", ",", "specs", ",", "channel", ",", "delay", ")", ";", "}" ]
Parse a channel event @private @param {number} delay Event delay in ticks @param {number} type Event subtype @param {number} channel Channel number @param {module:buffercursor} cursor Buffer to parse @return {module:midijs/lib/file/event~ChannelEvent} Parsed channel event
[ "Parse", "a", "channel", "event" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/event.js#L135-L168
train
matteodelabre/midijs
lib/file/parser/event.js
parseEvent
function parseEvent(cursor, runningStatus) { var delay, status, result; delay = parseVarInt(cursor); status = cursor.readUInt8(); // if the most significant bit is not set, // we use the last status if ((status & 0x80) === 0) { if (!runningStatus) { throw new error.MIDIParserError( 'undefined event status', cursor.tell() ); } status = runningStatus; cursor.seek(cursor.tell() - 1); } else { runningStatus = status; } if (status === 0xFF) { result = parseMetaEvent(delay, cursor); } else if (status === 0xF0 || status === 0xF7) { result = parseSysexEvent(delay, status & 0xF, cursor); } else if (status >= 0x80 && status < 0xF0) { result = parseChannelEvent(delay, status >> 4, status & 0xF, cursor); } else { throw new error.MIDIParserError( status, 'known status type', cursor.tell() ); } return { runningStatus: runningStatus, event: result }; }
javascript
function parseEvent(cursor, runningStatus) { var delay, status, result; delay = parseVarInt(cursor); status = cursor.readUInt8(); // if the most significant bit is not set, // we use the last status if ((status & 0x80) === 0) { if (!runningStatus) { throw new error.MIDIParserError( 'undefined event status', cursor.tell() ); } status = runningStatus; cursor.seek(cursor.tell() - 1); } else { runningStatus = status; } if (status === 0xFF) { result = parseMetaEvent(delay, cursor); } else if (status === 0xF0 || status === 0xF7) { result = parseSysexEvent(delay, status & 0xF, cursor); } else if (status >= 0x80 && status < 0xF0) { result = parseChannelEvent(delay, status >> 4, status & 0xF, cursor); } else { throw new error.MIDIParserError( status, 'known status type', cursor.tell() ); } return { runningStatus: runningStatus, event: result }; }
[ "function", "parseEvent", "(", "cursor", ",", "runningStatus", ")", "{", "var", "delay", ",", "status", ",", "result", ";", "delay", "=", "parseVarInt", "(", "cursor", ")", ";", "status", "=", "cursor", ".", "readUInt8", "(", ")", ";", "if", "(", "(", "status", "&", "0x80", ")", "===", "0", ")", "{", "if", "(", "!", "runningStatus", ")", "{", "throw", "new", "error", ".", "MIDIParserError", "(", "'undefined event status'", ",", "cursor", ".", "tell", "(", ")", ")", ";", "}", "status", "=", "runningStatus", ";", "cursor", ".", "seek", "(", "cursor", ".", "tell", "(", ")", "-", "1", ")", ";", "}", "else", "{", "runningStatus", "=", "status", ";", "}", "if", "(", "status", "===", "0xFF", ")", "{", "result", "=", "parseMetaEvent", "(", "delay", ",", "cursor", ")", ";", "}", "else", "if", "(", "status", "===", "0xF0", "||", "status", "===", "0xF7", ")", "{", "result", "=", "parseSysexEvent", "(", "delay", ",", "status", "&", "0xF", ",", "cursor", ")", ";", "}", "else", "if", "(", "status", ">=", "0x80", "&&", "status", "<", "0xF0", ")", "{", "result", "=", "parseChannelEvent", "(", "delay", ",", "status", ">>", "4", ",", "status", "&", "0xF", ",", "cursor", ")", ";", "}", "else", "{", "throw", "new", "error", ".", "MIDIParserError", "(", "status", ",", "'known status type'", ",", "cursor", ".", "tell", "(", ")", ")", ";", "}", "return", "{", "runningStatus", ":", "runningStatus", ",", "event", ":", "result", "}", ";", "}" ]
Parse any type of MIDI event @param {BufferCursor} cursor Buffer to parse @param {number} [runningStatus] Previous status if applicable @throws {module:midijs/lib/error~MIDIParserError} Unknown event status encountered or running status undefined while being requested by this event's data @return {Object} Parsed event and new running status
[ "Parse", "any", "type", "of", "MIDI", "event" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/event.js#L180-L220
train
matteodelabre/midijs
lib/file/encoder/event.js
encodeSysexEvent
function encodeSysexEvent(event) { var cursor, length; length = encodeVarInt(event.data.length); cursor = new BufferCursor(new buffer.Buffer( 1 + length.length + event.data.length )); cursor.writeUInt8(0xF0 | event.type); cursor.copy(length); cursor.copy(event.data); return cursor.buffer; }
javascript
function encodeSysexEvent(event) { var cursor, length; length = encodeVarInt(event.data.length); cursor = new BufferCursor(new buffer.Buffer( 1 + length.length + event.data.length )); cursor.writeUInt8(0xF0 | event.type); cursor.copy(length); cursor.copy(event.data); return cursor.buffer; }
[ "function", "encodeSysexEvent", "(", "event", ")", "{", "var", "cursor", ",", "length", ";", "length", "=", "encodeVarInt", "(", "event", ".", "data", ".", "length", ")", ";", "cursor", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "1", "+", "length", ".", "length", "+", "event", ".", "data", ".", "length", ")", ")", ";", "cursor", ".", "writeUInt8", "(", "0xF0", "|", "event", ".", "type", ")", ";", "cursor", ".", "copy", "(", "length", ")", ";", "cursor", ".", "copy", "(", "event", ".", "data", ")", ";", "return", "cursor", ".", "buffer", ";", "}" ]
Encode a system exclusive MIDI event @private @param {module:midijs/lib/file/event~SysexEvent} event Sysex event to encode @return {Buffer} Encoded sysex event
[ "Encode", "a", "system", "exclusive", "MIDI", "event" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/event.js#L150-L163
train
matteodelabre/midijs
lib/file/encoder/event.js
encodeChannelEvent
function encodeChannelEvent(event) { var cursor, eventData, value; switch (event.type) { case ChannelEvent.TYPE.NOTE_OFF: eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(event.note); eventData.writeUInt8(event.velocity); break; case ChannelEvent.TYPE.NOTE_ON: eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(event.note); eventData.writeUInt8(event.velocity); break; case ChannelEvent.TYPE.NOTE_AFTERTOUCH: eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(event.note); eventData.writeUInt8(event.pressure); break; case ChannelEvent.TYPE.CONTROLLER: eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(event.controller); eventData.writeUInt8(event.value); break; case ChannelEvent.TYPE.PROGRAM_CHANGE: eventData = new BufferCursor(new buffer.Buffer(1)); eventData.writeUInt8(event.program); break; case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH: eventData = new BufferCursor(new buffer.Buffer(1)); eventData.writeUInt8(event.pressure); break; case ChannelEvent.TYPE.PITCH_BEND: value = event.value + 8192; eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(value & 0x7F); eventData.writeUInt8(value >> 7); break; default: throw new error.MIDIEncoderError( event.type, 'known ChannelEvent type' ); } cursor = new BufferCursor(new buffer.Buffer( 1 + eventData.length )); cursor.writeUInt8((event.type << 4) + event.channel); cursor.copy(eventData.buffer); return cursor.buffer; }
javascript
function encodeChannelEvent(event) { var cursor, eventData, value; switch (event.type) { case ChannelEvent.TYPE.NOTE_OFF: eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(event.note); eventData.writeUInt8(event.velocity); break; case ChannelEvent.TYPE.NOTE_ON: eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(event.note); eventData.writeUInt8(event.velocity); break; case ChannelEvent.TYPE.NOTE_AFTERTOUCH: eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(event.note); eventData.writeUInt8(event.pressure); break; case ChannelEvent.TYPE.CONTROLLER: eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(event.controller); eventData.writeUInt8(event.value); break; case ChannelEvent.TYPE.PROGRAM_CHANGE: eventData = new BufferCursor(new buffer.Buffer(1)); eventData.writeUInt8(event.program); break; case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH: eventData = new BufferCursor(new buffer.Buffer(1)); eventData.writeUInt8(event.pressure); break; case ChannelEvent.TYPE.PITCH_BEND: value = event.value + 8192; eventData = new BufferCursor(new buffer.Buffer(2)); eventData.writeUInt8(value & 0x7F); eventData.writeUInt8(value >> 7); break; default: throw new error.MIDIEncoderError( event.type, 'known ChannelEvent type' ); } cursor = new BufferCursor(new buffer.Buffer( 1 + eventData.length )); cursor.writeUInt8((event.type << 4) + event.channel); cursor.copy(eventData.buffer); return cursor.buffer; }
[ "function", "encodeChannelEvent", "(", "event", ")", "{", "var", "cursor", ",", "eventData", ",", "value", ";", "switch", "(", "event", ".", "type", ")", "{", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_OFF", ":", "eventData", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "2", ")", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "note", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "velocity", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_ON", ":", "eventData", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "2", ")", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "note", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "velocity", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_AFTERTOUCH", ":", "eventData", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "2", ")", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "note", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "pressure", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "CONTROLLER", ":", "eventData", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "2", ")", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "controller", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "value", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "PROGRAM_CHANGE", ":", "eventData", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "1", ")", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "program", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "CHANNEL_AFTERTOUCH", ":", "eventData", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "1", ")", ")", ";", "eventData", ".", "writeUInt8", "(", "event", ".", "pressure", ")", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "PITCH_BEND", ":", "value", "=", "event", ".", "value", "+", "8192", ";", "eventData", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "2", ")", ")", ";", "eventData", ".", "writeUInt8", "(", "value", "&", "0x7F", ")", ";", "eventData", ".", "writeUInt8", "(", "value", ">>", "7", ")", ";", "break", ";", "default", ":", "throw", "new", "error", ".", "MIDIEncoderError", "(", "event", ".", "type", ",", "'known ChannelEvent type'", ")", ";", "}", "cursor", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "1", "+", "eventData", ".", "length", ")", ")", ";", "cursor", ".", "writeUInt8", "(", "(", "event", ".", "type", "<<", "4", ")", "+", "event", ".", "channel", ")", ";", "cursor", ".", "copy", "(", "eventData", ".", "buffer", ")", ";", "return", "cursor", ".", "buffer", ";", "}" ]
Encode a channel event @private @param {module:midijs/lib/file/event~ChannelEvent} event Channel event @throws {module:midijs/lib/error~MIDIEncoderError} Failed to encode the channel event @return {Buffer} Encoded channel event
[ "Encode", "a", "channel", "event" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/event.js#L174-L232
train
matteodelabre/midijs
lib/file/encoder/event.js
encodeEvent
function encodeEvent(event, runningStatus) { var delay, eventData, cursor; delay = encodeVarInt(event.delay); if (event instanceof MetaEvent) { eventData = encodeMetaEvent(event); } else if (event instanceof SysexEvent) { eventData = encodeSysexEvent(event); } else if (event instanceof ChannelEvent) { eventData = encodeChannelEvent(event); } else { throw new error.MIDIEncoderError( event.constructor.name, 'known Event type' ); } // if current type is the same as the last one, // we don't include it // (sysex events cancel the running status and // meta events ignore it) if (event instanceof ChannelEvent) { if (runningStatus === eventData[0]) { eventData = eventData.slice(1); } else { runningStatus = eventData[0]; } } else if (event instanceof SysexEvent) { runningStatus = null; } cursor = new BufferCursor(new buffer.Buffer( delay.length + eventData.length )); cursor.copy(delay); cursor.copy(eventData); return { runningStatus: runningStatus, data: cursor.buffer }; }
javascript
function encodeEvent(event, runningStatus) { var delay, eventData, cursor; delay = encodeVarInt(event.delay); if (event instanceof MetaEvent) { eventData = encodeMetaEvent(event); } else if (event instanceof SysexEvent) { eventData = encodeSysexEvent(event); } else if (event instanceof ChannelEvent) { eventData = encodeChannelEvent(event); } else { throw new error.MIDIEncoderError( event.constructor.name, 'known Event type' ); } // if current type is the same as the last one, // we don't include it // (sysex events cancel the running status and // meta events ignore it) if (event instanceof ChannelEvent) { if (runningStatus === eventData[0]) { eventData = eventData.slice(1); } else { runningStatus = eventData[0]; } } else if (event instanceof SysexEvent) { runningStatus = null; } cursor = new BufferCursor(new buffer.Buffer( delay.length + eventData.length )); cursor.copy(delay); cursor.copy(eventData); return { runningStatus: runningStatus, data: cursor.buffer }; }
[ "function", "encodeEvent", "(", "event", ",", "runningStatus", ")", "{", "var", "delay", ",", "eventData", ",", "cursor", ";", "delay", "=", "encodeVarInt", "(", "event", ".", "delay", ")", ";", "if", "(", "event", "instanceof", "MetaEvent", ")", "{", "eventData", "=", "encodeMetaEvent", "(", "event", ")", ";", "}", "else", "if", "(", "event", "instanceof", "SysexEvent", ")", "{", "eventData", "=", "encodeSysexEvent", "(", "event", ")", ";", "}", "else", "if", "(", "event", "instanceof", "ChannelEvent", ")", "{", "eventData", "=", "encodeChannelEvent", "(", "event", ")", ";", "}", "else", "{", "throw", "new", "error", ".", "MIDIEncoderError", "(", "event", ".", "constructor", ".", "name", ",", "'known Event type'", ")", ";", "}", "if", "(", "event", "instanceof", "ChannelEvent", ")", "{", "if", "(", "runningStatus", "===", "eventData", "[", "0", "]", ")", "{", "eventData", "=", "eventData", ".", "slice", "(", "1", ")", ";", "}", "else", "{", "runningStatus", "=", "eventData", "[", "0", "]", ";", "}", "}", "else", "if", "(", "event", "instanceof", "SysexEvent", ")", "{", "runningStatus", "=", "null", ";", "}", "cursor", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "delay", ".", "length", "+", "eventData", ".", "length", ")", ")", ";", "cursor", ".", "copy", "(", "delay", ")", ";", "cursor", ".", "copy", "(", "eventData", ")", ";", "return", "{", "runningStatus", ":", "runningStatus", ",", "data", ":", "cursor", ".", "buffer", "}", ";", "}" ]
Encode a MIDI event @param {module:midijs/lib/file/event~Event} event Event to encode @param {number} [runningStatus] Previous status if applicable @throws {module:midijs/lib/error~MIDIInvalidArgument} Unknown event encountered @return {Object} Encoded data and new running status
[ "Encode", "a", "MIDI", "event" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/event.js#L243-L286
train
claudio-silva/grunt-angular-builder
tasks/middleware/overrideDependencies.js
OverrideDependenciesMiddleware
function OverrideDependenciesMiddleware (context) { /* jshint unused: vars */ var options = context.options.overrideDependencies , enabled = options.dependencies && options.dependencies.length; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ if (!enabled) return; var mainModuleName = context.options.mainModule; var mainModule = context.modules[mainModuleName] = new ModuleDef (mainModuleName); mainModule.requires = options.dependencies; // Must set head to a non-empty string to mark the module as being initialized. mainModule.head = ' '; }; this.trace = function (module) { /* jshint unused: vars */ }; this.build = function (targetScript) { /* jshint unused: vars */ if (!enabled) return; if (context.options.debugBuild && context.options.debugBuild.enabled) { var declaration = sprintf ("angular.module('%',%);", context.options.mainModule, util.toQuotedList (options.dependencies) ); context.appendOutput += sprintf ('<script>%</script>', declaration); } }; }
javascript
function OverrideDependenciesMiddleware (context) { /* jshint unused: vars */ var options = context.options.overrideDependencies , enabled = options.dependencies && options.dependencies.length; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ if (!enabled) return; var mainModuleName = context.options.mainModule; var mainModule = context.modules[mainModuleName] = new ModuleDef (mainModuleName); mainModule.requires = options.dependencies; // Must set head to a non-empty string to mark the module as being initialized. mainModule.head = ' '; }; this.trace = function (module) { /* jshint unused: vars */ }; this.build = function (targetScript) { /* jshint unused: vars */ if (!enabled) return; if (context.options.debugBuild && context.options.debugBuild.enabled) { var declaration = sprintf ("angular.module('%',%);", context.options.mainModule, util.toQuotedList (options.dependencies) ); context.appendOutput += sprintf ('<script>%</script>', declaration); } }; }
[ "function", "OverrideDependenciesMiddleware", "(", "context", ")", "{", "var", "options", "=", "context", ".", "options", ".", "overrideDependencies", ",", "enabled", "=", "options", ".", "dependencies", "&&", "options", ".", "dependencies", ".", "length", ";", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "if", "(", "!", "enabled", ")", "return", ";", "var", "mainModuleName", "=", "context", ".", "options", ".", "mainModule", ";", "var", "mainModule", "=", "context", ".", "modules", "[", "mainModuleName", "]", "=", "new", "ModuleDef", "(", "mainModuleName", ")", ";", "mainModule", ".", "requires", "=", "options", ".", "dependencies", ";", "mainModule", ".", "head", "=", "' '", ";", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "if", "(", "!", "enabled", ")", "return", ";", "if", "(", "context", ".", "options", ".", "debugBuild", "&&", "context", ".", "options", ".", "debugBuild", ".", "enabled", ")", "{", "var", "declaration", "=", "sprintf", "(", "\"angular.module('%',%);\"", ",", "context", ".", "options", ".", "mainModule", ",", "util", ".", "toQuotedList", "(", "options", ".", "dependencies", ")", ")", ";", "context", ".", "appendOutput", "+=", "sprintf", "(", "'<script>%</script>'", ",", "declaration", ")", ";", "}", "}", ";", "}" ]
Allows the setting of the main module's dependencies via Grunt configuration options and synthetizes that module's declaration javascript code. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Allows", "the", "setting", "of", "the", "main", "module", "s", "dependencies", "via", "Grunt", "configuration", "options", "and", "synthetizes", "that", "module", "s", "declaration", "javascript", "code", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/overrideDependencies.js#L79-L119
train
matteodelabre/midijs
lib/file/header.js
Header
function Header(fileType, trackCount, ticksPerBeat) { this._fileType = fileType || Header.FILE_TYPE.SYNC_TRACKS; this._trackCount = trackCount || 0; this._ticksPerBeat = ticksPerBeat || 120; }
javascript
function Header(fileType, trackCount, ticksPerBeat) { this._fileType = fileType || Header.FILE_TYPE.SYNC_TRACKS; this._trackCount = trackCount || 0; this._ticksPerBeat = ticksPerBeat || 120; }
[ "function", "Header", "(", "fileType", ",", "trackCount", ",", "ticksPerBeat", ")", "{", "this", ".", "_fileType", "=", "fileType", "||", "Header", ".", "FILE_TYPE", ".", "SYNC_TRACKS", ";", "this", ".", "_trackCount", "=", "trackCount", "||", "0", ";", "this", ".", "_ticksPerBeat", "=", "ticksPerBeat", "||", "120", ";", "}" ]
Construct a new Header @class Header @classdesc A Standard MIDI File's header (contains various metadata) @param {module:midijs/lib/file/header~Header.FILE_TYPE} fileType File type @param {number} trackCount Amount of tracks in the file @param {number} ticksPerBeat Beats rate in ticks per beat
[ "Construct", "a", "new", "Header" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/header.js#L16-L20
train
claudio-silva/grunt-angular-builder
tasks/middleware/buildAssets.js
BuildAssetsMiddleware
function BuildAssetsMiddleware (context) { var grunt = context.grunt , options = context.options.assets; /** * Records which files have been already exported. * Prevents duplicate asset exports. * It's a map of absolute file names to boolean `true`. * @type {Object.<string,boolean>} */ var exportedAssets = {}; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { /* jshint unused: vars */ // Do nothing. }; this.build = function (targetScript) { if (!options.enabled) return; // Import file paths. var stylehseets = grunt.config (context.options.requiredStylesheets.exportToConfigProperty); if (!stylehseets) return; // No stylesheet sources are configured. var targetPath = path.dirname (targetScript); stylehseets.forEach (function (filePath) { var src = grunt.file.read (filePath); scan (path.dirname (filePath), targetPath, src); }); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Scans a stylesheet for asset URL references and copies the assets to the build folder. * @private * @param {string} basePath * @param {string} targetPath * @param {string} sourceCode */ function scan (basePath, targetPath, sourceCode) { var match; while ((match = MATCH_URLS.exec (sourceCode))) { var url = match[2]; if (!url.match (/^http/i) && url[0] !== '/') { // Skip absolute URLs var absSrcPath = path.resolve (basePath, url) , absDestPath = path.resolve (targetPath, options.targetDir, url) , relDestPath = path.relative (targetPath, absDestPath); if (relDestPath[0] === '.') return util.warn ('Relative asset url falls outside the build folder: <cyan>%</cyan>%', url, util.NL); if (exportedAssets[absDestPath]) // skip already exported asset continue; else exportedAssets[absDestPath] = true; var absTargetFolder = path.dirname (absDestPath); grunt.file.mkdir (absTargetFolder); if (options.symlink) fs.symlinkSync (absSrcPath, absDestPath); else grunt.file.copy (absSrcPath, absDestPath); } } } }
javascript
function BuildAssetsMiddleware (context) { var grunt = context.grunt , options = context.options.assets; /** * Records which files have been already exported. * Prevents duplicate asset exports. * It's a map of absolute file names to boolean `true`. * @type {Object.<string,boolean>} */ var exportedAssets = {}; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { /* jshint unused: vars */ // Do nothing. }; this.build = function (targetScript) { if (!options.enabled) return; // Import file paths. var stylehseets = grunt.config (context.options.requiredStylesheets.exportToConfigProperty); if (!stylehseets) return; // No stylesheet sources are configured. var targetPath = path.dirname (targetScript); stylehseets.forEach (function (filePath) { var src = grunt.file.read (filePath); scan (path.dirname (filePath), targetPath, src); }); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Scans a stylesheet for asset URL references and copies the assets to the build folder. * @private * @param {string} basePath * @param {string} targetPath * @param {string} sourceCode */ function scan (basePath, targetPath, sourceCode) { var match; while ((match = MATCH_URLS.exec (sourceCode))) { var url = match[2]; if (!url.match (/^http/i) && url[0] !== '/') { // Skip absolute URLs var absSrcPath = path.resolve (basePath, url) , absDestPath = path.resolve (targetPath, options.targetDir, url) , relDestPath = path.relative (targetPath, absDestPath); if (relDestPath[0] === '.') return util.warn ('Relative asset url falls outside the build folder: <cyan>%</cyan>%', url, util.NL); if (exportedAssets[absDestPath]) // skip already exported asset continue; else exportedAssets[absDestPath] = true; var absTargetFolder = path.dirname (absDestPath); grunt.file.mkdir (absTargetFolder); if (options.symlink) fs.symlinkSync (absSrcPath, absDestPath); else grunt.file.copy (absSrcPath, absDestPath); } } } }
[ "function", "BuildAssetsMiddleware", "(", "context", ")", "{", "var", "grunt", "=", "context", ".", "grunt", ",", "options", "=", "context", ".", "options", ".", "assets", ";", "var", "exportedAssets", "=", "{", "}", ";", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "if", "(", "!", "options", ".", "enabled", ")", "return", ";", "var", "stylehseets", "=", "grunt", ".", "config", "(", "context", ".", "options", ".", "requiredStylesheets", ".", "exportToConfigProperty", ")", ";", "if", "(", "!", "stylehseets", ")", "return", ";", "var", "targetPath", "=", "path", ".", "dirname", "(", "targetScript", ")", ";", "stylehseets", ".", "forEach", "(", "function", "(", "filePath", ")", "{", "var", "src", "=", "grunt", ".", "file", ".", "read", "(", "filePath", ")", ";", "scan", "(", "path", ".", "dirname", "(", "filePath", ")", ",", "targetPath", ",", "src", ")", ";", "}", ")", ";", "}", ";", "function", "scan", "(", "basePath", ",", "targetPath", ",", "sourceCode", ")", "{", "var", "match", ";", "while", "(", "(", "match", "=", "MATCH_URLS", ".", "exec", "(", "sourceCode", ")", ")", ")", "{", "var", "url", "=", "match", "[", "2", "]", ";", "if", "(", "!", "url", ".", "match", "(", "/", "^http", "/", "i", ")", "&&", "url", "[", "0", "]", "!==", "'/'", ")", "{", "var", "absSrcPath", "=", "path", ".", "resolve", "(", "basePath", ",", "url", ")", ",", "absDestPath", "=", "path", ".", "resolve", "(", "targetPath", ",", "options", ".", "targetDir", ",", "url", ")", ",", "relDestPath", "=", "path", ".", "relative", "(", "targetPath", ",", "absDestPath", ")", ";", "if", "(", "relDestPath", "[", "0", "]", "===", "'.'", ")", "return", "util", ".", "warn", "(", "'Relative asset url falls outside the build folder: <cyan>%</cyan>%'", ",", "url", ",", "util", ".", "NL", ")", ";", "if", "(", "exportedAssets", "[", "absDestPath", "]", ")", "continue", ";", "else", "exportedAssets", "[", "absDestPath", "]", "=", "true", ";", "var", "absTargetFolder", "=", "path", ".", "dirname", "(", "absDestPath", ")", ";", "grunt", ".", "file", ".", "mkdir", "(", "absTargetFolder", ")", ";", "if", "(", "options", ".", "symlink", ")", "fs", ".", "symlinkSync", "(", "absSrcPath", ",", "absDestPath", ")", ";", "else", "grunt", ".", "file", ".", "copy", "(", "absSrcPath", ",", "absDestPath", ")", ";", "}", "}", "}", "}" ]
Exports the assets required by the application's modules. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Exports", "the", "assets", "required", "by", "the", "application", "s", "modules", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/buildAssets.js#L79-L157
train
claudio-silva/grunt-angular-builder
tasks/middleware/makeDebugBuild.js
MakeDebugBuildMiddleware
function MakeDebugBuildMiddleware (context) { var options = context.options.debugBuild; /** @type {string[]} */ var traceOutput = []; //-------------------------------------------------------------------------------------------------------------------- // EVENTS //-------------------------------------------------------------------------------------------------------------------- context.listen (ContextEvent.ON_AFTER_ANALYZE, function () { if (options.enabled) { var space = context.verbose ? NL : ''; writeln ('%Generating the <cyan>debug</cyan> build...%', space, space); } }); //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (/*ModuleDef*/ module) { if (!options.enabled) return; var rep = options.rebaseDebugUrls; module.filePaths ().forEach (function (path) { if (context.outputtedFiles[path] && context.outputtedFiles[path] !== module.name) return; context.outputtedFiles[path] = true; if (rep) for (var i = 0, m = rep.length; i < m; ++i) path = path.replace (rep[i].match, rep[i].replaceWith); if (path) // Ignore empty path; it means that this middleware should not output a script tag. traceOutput.push (util.sprintf ('<script src=\"%\"></script>', path)); }); }; this.build = function (targetScript) { /* jshint unused: vars */ if (!options.enabled) return; /** @type {string[]} */ var output = ['document.write (\'']; if (context.prependOutput) output.push (context.prependOutput); // Output the modules (if any). util.arrayAppend (output, traceOutput); if (context.appendOutput) output.push (context.appendOutput); output.push ('\');'); util.writeFile (targetScript, output.join ('\\\n')); }; }
javascript
function MakeDebugBuildMiddleware (context) { var options = context.options.debugBuild; /** @type {string[]} */ var traceOutput = []; //-------------------------------------------------------------------------------------------------------------------- // EVENTS //-------------------------------------------------------------------------------------------------------------------- context.listen (ContextEvent.ON_AFTER_ANALYZE, function () { if (options.enabled) { var space = context.verbose ? NL : ''; writeln ('%Generating the <cyan>debug</cyan> build...%', space, space); } }); //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (/*ModuleDef*/ module) { if (!options.enabled) return; var rep = options.rebaseDebugUrls; module.filePaths ().forEach (function (path) { if (context.outputtedFiles[path] && context.outputtedFiles[path] !== module.name) return; context.outputtedFiles[path] = true; if (rep) for (var i = 0, m = rep.length; i < m; ++i) path = path.replace (rep[i].match, rep[i].replaceWith); if (path) // Ignore empty path; it means that this middleware should not output a script tag. traceOutput.push (util.sprintf ('<script src=\"%\"></script>', path)); }); }; this.build = function (targetScript) { /* jshint unused: vars */ if (!options.enabled) return; /** @type {string[]} */ var output = ['document.write (\'']; if (context.prependOutput) output.push (context.prependOutput); // Output the modules (if any). util.arrayAppend (output, traceOutput); if (context.appendOutput) output.push (context.appendOutput); output.push ('\');'); util.writeFile (targetScript, output.join ('\\\n')); }; }
[ "function", "MakeDebugBuildMiddleware", "(", "context", ")", "{", "var", "options", "=", "context", ".", "options", ".", "debugBuild", ";", "var", "traceOutput", "=", "[", "]", ";", "context", ".", "listen", "(", "ContextEvent", ".", "ON_AFTER_ANALYZE", ",", "function", "(", ")", "{", "if", "(", "options", ".", "enabled", ")", "{", "var", "space", "=", "context", ".", "verbose", "?", "NL", ":", "''", ";", "writeln", "(", "'%Generating the <cyan>debug</cyan> build...%'", ",", "space", ",", "space", ")", ";", "}", "}", ")", ";", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "if", "(", "!", "options", ".", "enabled", ")", "return", ";", "var", "rep", "=", "options", ".", "rebaseDebugUrls", ";", "module", ".", "filePaths", "(", ")", ".", "forEach", "(", "function", "(", "path", ")", "{", "if", "(", "context", ".", "outputtedFiles", "[", "path", "]", "&&", "context", ".", "outputtedFiles", "[", "path", "]", "!==", "module", ".", "name", ")", "return", ";", "context", ".", "outputtedFiles", "[", "path", "]", "=", "true", ";", "if", "(", "rep", ")", "for", "(", "var", "i", "=", "0", ",", "m", "=", "rep", ".", "length", ";", "i", "<", "m", ";", "++", "i", ")", "path", "=", "path", ".", "replace", "(", "rep", "[", "i", "]", ".", "match", ",", "rep", "[", "i", "]", ".", "replaceWith", ")", ";", "if", "(", "path", ")", "traceOutput", ".", "push", "(", "util", ".", "sprintf", "(", "'<script src=\\\"%\\\"></script>'", ",", "\\\"", ")", ")", ";", "}", ")", ";", "}", ";", "\\\"", "}" ]
Generates a script file that inserts SCRIPT tags to the head of the html document, which will load the original source scripts in the correct order. This is used on debug builds. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Generates", "a", "script", "file", "that", "inserts", "SCRIPT", "tags", "to", "the", "head", "of", "the", "html", "document", "which", "will", "load", "the", "original", "source", "scripts", "in", "the", "correct", "order", ".", "This", "is", "used", "on", "debug", "builds", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeDebugBuild.js#L75-L142
train
jhermsmeier/node-tle
lib/stream.js
Parser
function Parser( options ) { if( !(this instanceof Parser) ) return new Parser( options ) Stream.Transform.call( this, options ) this._readableState.objectMode = true this._buffer = '' }
javascript
function Parser( options ) { if( !(this instanceof Parser) ) return new Parser( options ) Stream.Transform.call( this, options ) this._readableState.objectMode = true this._buffer = '' }
[ "function", "Parser", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Parser", ")", ")", "return", "new", "Parser", "(", "options", ")", "Stream", ".", "Transform", ".", "call", "(", "this", ",", "options", ")", "this", ".", "_readableState", ".", "objectMode", "=", "true", "this", ".", "_buffer", "=", "''", "}" ]
TLE Parser Stream @constructor @param {Object} [options] @return {Parser}
[ "TLE", "Parser", "Stream" ]
0c0a57270cd6573b912f007a5b9da83f98eba775
https://github.com/jhermsmeier/node-tle/blob/0c0a57270cd6573b912f007a5b9da83f98eba775/lib/stream.js#L11-L21
train
JamesMessinger/json-schema-lib
lib/plugins/HttpPlugin.js
readFileAsync
function readFileAsync (args) { var file = args.file; var config = args.config; var next = args.next; var url = parseUrl(file.url); var transport; switch (url.protocol) { case 'http:': transport = followRedirects.http; break; case 'https:': transport = followRedirects.https; break; default: // It's not an HTTP or HTTPS URL, so let some other plugin handle it return next(); } var httpConfig = { hostname: url.hostname, port: url.port, path: url.pathname + url.search, headers: Object.assign({}, defaultHeaders, config.http.headers), timeout: config.http.timeout, followRedirects: !!config.http.maxRedirects, maxRedirects: config.http.maxRedirects, }; var req = transport.get(httpConfig); req.on('error', next); req.on('timeout', function handleTimeout () { req.abort(); }); req.once('response', function handleResponse (res) { var responseChunks = []; var chunksAreStrings = false; decompressResponse(res); setHttpMetadata(file, res); res.on('error', next); res.on('data', function handleResponseData (chunk) { // Keep track of whether ANY of the chunks are strings (as opposed to Buffers) if (typeof chunk === 'string') { chunksAreStrings = true; } responseChunks.push(chunk); }); res.on('end', function handleResponseEnd () { try { var response; if (chunksAreStrings) { // Return the response as a string response = responseChunks.join(''); } else { // Return the response as a Buffer (Uint8Array) response = Buffer.concat(responseChunks); } next(null, response); } catch (err) { next(err); } }); }); }
javascript
function readFileAsync (args) { var file = args.file; var config = args.config; var next = args.next; var url = parseUrl(file.url); var transport; switch (url.protocol) { case 'http:': transport = followRedirects.http; break; case 'https:': transport = followRedirects.https; break; default: // It's not an HTTP or HTTPS URL, so let some other plugin handle it return next(); } var httpConfig = { hostname: url.hostname, port: url.port, path: url.pathname + url.search, headers: Object.assign({}, defaultHeaders, config.http.headers), timeout: config.http.timeout, followRedirects: !!config.http.maxRedirects, maxRedirects: config.http.maxRedirects, }; var req = transport.get(httpConfig); req.on('error', next); req.on('timeout', function handleTimeout () { req.abort(); }); req.once('response', function handleResponse (res) { var responseChunks = []; var chunksAreStrings = false; decompressResponse(res); setHttpMetadata(file, res); res.on('error', next); res.on('data', function handleResponseData (chunk) { // Keep track of whether ANY of the chunks are strings (as opposed to Buffers) if (typeof chunk === 'string') { chunksAreStrings = true; } responseChunks.push(chunk); }); res.on('end', function handleResponseEnd () { try { var response; if (chunksAreStrings) { // Return the response as a string response = responseChunks.join(''); } else { // Return the response as a Buffer (Uint8Array) response = Buffer.concat(responseChunks); } next(null, response); } catch (err) { next(err); } }); }); }
[ "function", "readFileAsync", "(", "args", ")", "{", "var", "file", "=", "args", ".", "file", ";", "var", "config", "=", "args", ".", "config", ";", "var", "next", "=", "args", ".", "next", ";", "var", "url", "=", "parseUrl", "(", "file", ".", "url", ")", ";", "var", "transport", ";", "switch", "(", "url", ".", "protocol", ")", "{", "case", "'http:'", ":", "transport", "=", "followRedirects", ".", "http", ";", "break", ";", "case", "'https:'", ":", "transport", "=", "followRedirects", ".", "https", ";", "break", ";", "default", ":", "return", "next", "(", ")", ";", "}", "var", "httpConfig", "=", "{", "hostname", ":", "url", ".", "hostname", ",", "port", ":", "url", ".", "port", ",", "path", ":", "url", ".", "pathname", "+", "url", ".", "search", ",", "headers", ":", "Object", ".", "assign", "(", "{", "}", ",", "defaultHeaders", ",", "config", ".", "http", ".", "headers", ")", ",", "timeout", ":", "config", ".", "http", ".", "timeout", ",", "followRedirects", ":", "!", "!", "config", ".", "http", ".", "maxRedirects", ",", "maxRedirects", ":", "config", ".", "http", ".", "maxRedirects", ",", "}", ";", "var", "req", "=", "transport", ".", "get", "(", "httpConfig", ")", ";", "req", ".", "on", "(", "'error'", ",", "next", ")", ";", "req", ".", "on", "(", "'timeout'", ",", "function", "handleTimeout", "(", ")", "{", "req", ".", "abort", "(", ")", ";", "}", ")", ";", "req", ".", "once", "(", "'response'", ",", "function", "handleResponse", "(", "res", ")", "{", "var", "responseChunks", "=", "[", "]", ";", "var", "chunksAreStrings", "=", "false", ";", "decompressResponse", "(", "res", ")", ";", "setHttpMetadata", "(", "file", ",", "res", ")", ";", "res", ".", "on", "(", "'error'", ",", "next", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "handleResponseData", "(", "chunk", ")", "{", "if", "(", "typeof", "chunk", "===", "'string'", ")", "{", "chunksAreStrings", "=", "true", ";", "}", "responseChunks", ".", "push", "(", "chunk", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "handleResponseEnd", "(", ")", "{", "try", "{", "var", "response", ";", "if", "(", "chunksAreStrings", ")", "{", "response", "=", "responseChunks", ".", "join", "(", "''", ")", ";", "}", "else", "{", "response", "=", "Buffer", ".", "concat", "(", "responseChunks", ")", ";", "}", "next", "(", "null", ",", "response", ")", ";", "}", "catch", "(", "err", ")", "{", "next", "(", "err", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Asynchronously downlaods a file from an HTTP or HTTPS URL. @param {File} args.file - The {@link File} to read @param {function} args.next - Calls the next plugin, if the file is not a local filesystem file
[ "Asynchronously", "downlaods", "a", "file", "from", "an", "HTTP", "or", "HTTPS", "URL", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/HttpPlugin.js#L41-L116
train
JamesMessinger/json-schema-lib
lib/plugins/HttpPlugin.js
parseUrl
function parseUrl (url) { if (typeof URL === 'function') { // Use the new WHATWG URL API return new URL(url); } else { // Use the legacy url API var parsed = legacyURL.parse(url); // Replace nulls with default values, for compatibility with the WHATWG URL API parsed.pathname = parsed.pathname || '/'; parsed.search = parsed.search || ''; } }
javascript
function parseUrl (url) { if (typeof URL === 'function') { // Use the new WHATWG URL API return new URL(url); } else { // Use the legacy url API var parsed = legacyURL.parse(url); // Replace nulls with default values, for compatibility with the WHATWG URL API parsed.pathname = parsed.pathname || '/'; parsed.search = parsed.search || ''; } }
[ "function", "parseUrl", "(", "url", ")", "{", "if", "(", "typeof", "URL", "===", "'function'", ")", "{", "return", "new", "URL", "(", "url", ")", ";", "}", "else", "{", "var", "parsed", "=", "legacyURL", ".", "parse", "(", "url", ")", ";", "parsed", ".", "pathname", "=", "parsed", ".", "pathname", "||", "'/'", ";", "parsed", ".", "search", "=", "parsed", ".", "search", "||", "''", ";", "}", "}" ]
Parses the given URL, using either the legacy Node.js url API, or the WHATWG URL API. @param {string} url @returns {object}
[ "Parses", "the", "given", "URL", "using", "either", "the", "legacy", "Node", ".", "js", "url", "API", "or", "the", "WHATWG", "URL", "API", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/HttpPlugin.js#L125-L138
train
JamesMessinger/json-schema-lib
lib/plugins/HttpPlugin.js
decompressResponse
function decompressResponse (res) { var encoding = lowercase(res.headers['content-encoding']); var isCompressed = ['gzip', 'compress', 'deflate'].indexOf(encoding) >= 0; if (isCompressed) { // The response is compressed, so add decompression middleware to the stream res.pipe(zlib.createUnzip()); // Remove the content-encoding header, to prevent double-decoding delete res.headers['content-encoding']; } }
javascript
function decompressResponse (res) { var encoding = lowercase(res.headers['content-encoding']); var isCompressed = ['gzip', 'compress', 'deflate'].indexOf(encoding) >= 0; if (isCompressed) { // The response is compressed, so add decompression middleware to the stream res.pipe(zlib.createUnzip()); // Remove the content-encoding header, to prevent double-decoding delete res.headers['content-encoding']; } }
[ "function", "decompressResponse", "(", "res", ")", "{", "var", "encoding", "=", "lowercase", "(", "res", ".", "headers", "[", "'content-encoding'", "]", ")", ";", "var", "isCompressed", "=", "[", "'gzip'", ",", "'compress'", ",", "'deflate'", "]", ".", "indexOf", "(", "encoding", ")", ">=", "0", ";", "if", "(", "isCompressed", ")", "{", "res", ".", "pipe", "(", "zlib", ".", "createUnzip", "(", ")", ")", ";", "delete", "res", ".", "headers", "[", "'content-encoding'", "]", ";", "}", "}" ]
Adds decompression middleware to the response stream if necessary. @param {IncomingMessage} res
[ "Adds", "decompression", "middleware", "to", "the", "response", "stream", "if", "necessary", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/HttpPlugin.js#L145-L156
train
strues/boldr
project/server/services/authentication/authService.js
fromHeaderOrQuerystring
function fromHeaderOrQuerystring(req) { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { return req.headers.authorization.split(' ')[1]; } else if (req.query && req.query.token) { return req.query.token; } return false; }
javascript
function fromHeaderOrQuerystring(req) { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { return req.headers.authorization.split(' ')[1]; } else if (req.query && req.query.token) { return req.query.token; } return false; }
[ "function", "fromHeaderOrQuerystring", "(", "req", ")", "{", "if", "(", "req", ".", "headers", ".", "authorization", "&&", "req", ".", "headers", ".", "authorization", ".", "split", "(", "' '", ")", "[", "0", "]", "===", "'Bearer'", ")", "{", "return", "req", ".", "headers", ".", "authorization", ".", "split", "(", "' '", ")", "[", "1", "]", ";", "}", "else", "if", "(", "req", ".", "query", "&&", "req", ".", "query", ".", "token", ")", "{", "return", "req", ".", "query", ".", "token", ";", "}", "return", "false", ";", "}" ]
Extracts a JWT from a request header or query string @param {Object} req the request object @return {string} the token
[ "Extracts", "a", "JWT", "from", "a", "request", "header", "or", "query", "string" ]
21f1ed9a5ed754e01c50827249e89087b788e660
https://github.com/strues/boldr/blob/21f1ed9a5ed754e01c50827249e89087b788e660/project/server/services/authentication/authService.js#L14-L21
train
glayzzle/doc-parser
src/parser.js
function (a, b) { if (a) { if (Array.isArray(b)) { for (var i = 0; i < b.length; i++) { if (b[i]) { a[i] = extend(a[i], b[i]); } } return a; } else if (typeof b === 'object') { Object.getOwnPropertyNames(b).forEach(function (key) { a[key] = extend(a[key], b[key]); }); return a; } } return b; }
javascript
function (a, b) { if (a) { if (Array.isArray(b)) { for (var i = 0; i < b.length; i++) { if (b[i]) { a[i] = extend(a[i], b[i]); } } return a; } else if (typeof b === 'object') { Object.getOwnPropertyNames(b).forEach(function (key) { a[key] = extend(a[key], b[key]); }); return a; } } return b; }
[ "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", ")", "{", "if", "(", "Array", ".", "isArray", "(", "b", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "b", ".", "length", ";", "i", "++", ")", "{", "if", "(", "b", "[", "i", "]", ")", "{", "a", "[", "i", "]", "=", "extend", "(", "a", "[", "i", "]", ",", "b", "[", "i", "]", ")", ";", "}", "}", "return", "a", ";", "}", "else", "if", "(", "typeof", "b", "===", "'object'", ")", "{", "Object", ".", "getOwnPropertyNames", "(", "b", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "a", "[", "key", "]", "=", "extend", "(", "a", "[", "key", "]", ",", "b", "[", "key", "]", ")", ";", "}", ")", ";", "return", "a", ";", "}", "}", "return", "b", ";", "}" ]
Deep recursive merge
[ "Deep", "recursive", "merge" ]
4ed4d1d47a8da5b9baba7ec371b5e81b85efba25
https://github.com/glayzzle/doc-parser/blob/4ed4d1d47a8da5b9baba7ec371b5e81b85efba25/src/parser.js#L9-L26
train
GianlucaGuarini/allora
index.js
allora
function allora (parent, prop) { return new Proxy(prop ? parent[prop] : parent, { get: (target, property) => { // no function no need for promises in return if (isOnCallback(property)) { // detect properties like // window.onload.then(() => console.log('loaded')) return new Promise((resolve) => { target[property] = resolve }) } else if (typeof target[property] !== 'function') { return target[property] } else { // make proxy also the nested object properties return allora(target, property) } }, // this is cool to make promiseable event emitters // and many other native node methods apply: (target, thisArg, argumentsList) => { let returnValue const promise = new Promise((resolve, reject) => { // guessing the timer functions from the type of arguments passed to the method const isTimer = !argumentsList.length || typeof argumentsList[0] === 'number' // assuming the callback will be always the second argument argumentsList.splice(isTimer ? 0 : 1, 0, resolve) returnValue = Reflect.apply(target, parent, argumentsList) }) // Return the returnValue through valueOf promise.valueOf = () => returnValue promise.toString = () => returnValue return promise } }) }
javascript
function allora (parent, prop) { return new Proxy(prop ? parent[prop] : parent, { get: (target, property) => { // no function no need for promises in return if (isOnCallback(property)) { // detect properties like // window.onload.then(() => console.log('loaded')) return new Promise((resolve) => { target[property] = resolve }) } else if (typeof target[property] !== 'function') { return target[property] } else { // make proxy also the nested object properties return allora(target, property) } }, // this is cool to make promiseable event emitters // and many other native node methods apply: (target, thisArg, argumentsList) => { let returnValue const promise = new Promise((resolve, reject) => { // guessing the timer functions from the type of arguments passed to the method const isTimer = !argumentsList.length || typeof argumentsList[0] === 'number' // assuming the callback will be always the second argument argumentsList.splice(isTimer ? 0 : 1, 0, resolve) returnValue = Reflect.apply(target, parent, argumentsList) }) // Return the returnValue through valueOf promise.valueOf = () => returnValue promise.toString = () => returnValue return promise } }) }
[ "function", "allora", "(", "parent", ",", "prop", ")", "{", "return", "new", "Proxy", "(", "prop", "?", "parent", "[", "prop", "]", ":", "parent", ",", "{", "get", ":", "(", "target", ",", "property", ")", "=>", "{", "if", "(", "isOnCallback", "(", "property", ")", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ")", "=>", "{", "target", "[", "property", "]", "=", "resolve", "}", ")", "}", "else", "if", "(", "typeof", "target", "[", "property", "]", "!==", "'function'", ")", "{", "return", "target", "[", "property", "]", "}", "else", "{", "return", "allora", "(", "target", ",", "property", ")", "}", "}", ",", "apply", ":", "(", "target", ",", "thisArg", ",", "argumentsList", ")", "=>", "{", "let", "returnValue", "const", "promise", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "isTimer", "=", "!", "argumentsList", ".", "length", "||", "typeof", "argumentsList", "[", "0", "]", "===", "'number'", "argumentsList", ".", "splice", "(", "isTimer", "?", "0", ":", "1", ",", "0", ",", "resolve", ")", "returnValue", "=", "Reflect", ".", "apply", "(", "target", ",", "parent", ",", "argumentsList", ")", "}", ")", "promise", ".", "valueOf", "=", "(", ")", "=>", "returnValue", "promise", ".", "toString", "=", "(", ")", "=>", "returnValue", "return", "promise", "}", "}", ")", "}" ]
Function called recursively on all the object properties If a property is a function we make it promisable @param { Object } parent - context where the apply method will be triggered @param { String } prop - property we are trying to get from the parent object @returns { Proxy }
[ "Function", "called", "recursively", "on", "all", "the", "object", "properties", "If", "a", "property", "is", "a", "function", "we", "make", "it", "promisable" ]
99b396214477d4f444470290b25bc91381b657be
https://github.com/GianlucaGuarini/allora/blob/99b396214477d4f444470290b25bc91381b657be/index.js#L12-L46
train
EarthlingInteractive/aframe-geo-projection-component
src/system.js
renderToContext
function renderToContext (geoJson, projection) { var shapePath = new THREE.ShapePath(); var mapRenderContext = new ThreeJSRenderContext(shapePath); var mapPath = geoPath(projection, mapRenderContext); mapPath(geoJson); return mapRenderContext; }
javascript
function renderToContext (geoJson, projection) { var shapePath = new THREE.ShapePath(); var mapRenderContext = new ThreeJSRenderContext(shapePath); var mapPath = geoPath(projection, mapRenderContext); mapPath(geoJson); return mapRenderContext; }
[ "function", "renderToContext", "(", "geoJson", ",", "projection", ")", "{", "var", "shapePath", "=", "new", "THREE", ".", "ShapePath", "(", ")", ";", "var", "mapRenderContext", "=", "new", "ThreeJSRenderContext", "(", "shapePath", ")", ";", "var", "mapPath", "=", "geoPath", "(", "projection", ",", "mapRenderContext", ")", ";", "mapPath", "(", "geoJson", ")", ";", "return", "mapRenderContext", ";", "}" ]
Takes the input geoJson and uses the projection and D3 to draw it into a ThreeJSRenderContext. @param geoJson the geoJson object to render @param projection the projection to use for rendering @return ThreeJSRenderContext
[ "Takes", "the", "input", "geoJson", "and", "uses", "the", "projection", "and", "D3", "to", "draw", "it", "into", "a", "ThreeJSRenderContext", "." ]
687f023acfdab9810811c88a55d0aab00777de0c
https://github.com/EarthlingInteractive/aframe-geo-projection-component/blob/687f023acfdab9810811c88a55d0aab00777de0c/src/system.js#L15-L21
train
glennjones/elsewhere-profiles
lib/pages.js
function(callback){ var self = this; // if we have no pages just fire callback if(self.pageCollection.length === 0){ callback(self); } // this is called once a page is fully parsed whenPageIsFetched = function(){ self.completed ++; if(self.completed === self.pageCollection.length){ callback(self); } else { findUnfetchedPages(); } } findUnfetchedPages = function(){ _.each(self.pageCollection, function (page) { if (page.status === "unfetched") { page.fetch(whenPageIsFetched); } }); }, findUnfetchedPages(); }
javascript
function(callback){ var self = this; // if we have no pages just fire callback if(self.pageCollection.length === 0){ callback(self); } // this is called once a page is fully parsed whenPageIsFetched = function(){ self.completed ++; if(self.completed === self.pageCollection.length){ callback(self); } else { findUnfetchedPages(); } } findUnfetchedPages = function(){ _.each(self.pageCollection, function (page) { if (page.status === "unfetched") { page.fetch(whenPageIsFetched); } }); }, findUnfetchedPages(); }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "if", "(", "self", ".", "pageCollection", ".", "length", "===", "0", ")", "{", "callback", "(", "self", ")", ";", "}", "whenPageIsFetched", "=", "function", "(", ")", "{", "self", ".", "completed", "++", ";", "if", "(", "self", ".", "completed", "===", "self", ".", "pageCollection", ".", "length", ")", "{", "callback", "(", "self", ")", ";", "}", "else", "{", "findUnfetchedPages", "(", ")", ";", "}", "}", "findUnfetchedPages", "=", "function", "(", ")", "{", "_", ".", "each", "(", "self", ".", "pageCollection", ",", "function", "(", "page", ")", "{", "if", "(", "page", ".", "status", "===", "\"unfetched\"", ")", "{", "page", ".", "fetch", "(", "whenPageIsFetched", ")", ";", "}", "}", ")", ";", "}", ",", "findUnfetchedPages", "(", ")", ";", "}" ]
fetch all the pages
[ "fetch", "all", "the", "pages" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L129-L156
train
glennjones/elsewhere-profiles
lib/pages.js
function (){ var out = {} if(this.profiles.length !== 0){ out.profiles = this.profiles } if(this.noProfilesFound.length !== 0){ out.noProfilesFound = this.noProfilesFound; } if(utils.hasProperties(this.combinedProfile)){ out.combinedProfile = this.combinedProfile } return out; }
javascript
function (){ var out = {} if(this.profiles.length !== 0){ out.profiles = this.profiles } if(this.noProfilesFound.length !== 0){ out.noProfilesFound = this.noProfilesFound; } if(utils.hasProperties(this.combinedProfile)){ out.combinedProfile = this.combinedProfile } return out; }
[ "function", "(", ")", "{", "var", "out", "=", "{", "}", "if", "(", "this", ".", "profiles", ".", "length", "!==", "0", ")", "{", "out", ".", "profiles", "=", "this", ".", "profiles", "}", "if", "(", "this", ".", "noProfilesFound", ".", "length", "!==", "0", ")", "{", "out", ".", "noProfilesFound", "=", "this", ".", "noProfilesFound", ";", "}", "if", "(", "utils", ".", "hasProperties", "(", "this", ".", "combinedProfile", ")", ")", "{", "out", ".", "combinedProfile", "=", "this", ".", "combinedProfile", "}", "return", "out", ";", "}" ]
converts the data structure into a compact version for output
[ "converts", "the", "data", "structure", "into", "a", "compact", "version", "for", "output" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L160-L176
train
glennjones/elsewhere-profiles
lib/pages.js
commonUserName
function commonUserName(objs, logger){ logger.info('finding common username'); var i = objs.length, x = 0 usernames = [], highest = 0, out =''; while (x < i) { appendName(objs[x].userName); x++; } var i = usernames.length; while (i--) { if(usernames[i].count > highest){ highest = usernames[i].count; out = usernames[i].name; } } function appendName(userName){ var i = usernames.length; while (i--) { if(usernames[i].name === userName){ usernames[i].count ++; return; } } usernames.push({ 'name': userName, 'count': 1 }) } return out; }
javascript
function commonUserName(objs, logger){ logger.info('finding common username'); var i = objs.length, x = 0 usernames = [], highest = 0, out =''; while (x < i) { appendName(objs[x].userName); x++; } var i = usernames.length; while (i--) { if(usernames[i].count > highest){ highest = usernames[i].count; out = usernames[i].name; } } function appendName(userName){ var i = usernames.length; while (i--) { if(usernames[i].name === userName){ usernames[i].count ++; return; } } usernames.push({ 'name': userName, 'count': 1 }) } return out; }
[ "function", "commonUserName", "(", "objs", ",", "logger", ")", "{", "logger", ".", "info", "(", "'finding common username'", ")", ";", "var", "i", "=", "objs", ".", "length", ",", "x", "=", "0", "usernames", "=", "[", "]", ",", "highest", "=", "0", ",", "out", "=", "''", ";", "while", "(", "x", "<", "i", ")", "{", "appendName", "(", "objs", "[", "x", "]", ".", "userName", ")", ";", "x", "++", ";", "}", "var", "i", "=", "usernames", ".", "length", ";", "while", "(", "i", "--", ")", "{", "if", "(", "usernames", "[", "i", "]", ".", "count", ">", "highest", ")", "{", "highest", "=", "usernames", "[", "i", "]", ".", "count", ";", "out", "=", "usernames", "[", "i", "]", ".", "name", ";", "}", "}", "function", "appendName", "(", "userName", ")", "{", "var", "i", "=", "usernames", ".", "length", ";", "while", "(", "i", "--", ")", "{", "if", "(", "usernames", "[", "i", "]", ".", "name", "===", "userName", ")", "{", "usernames", "[", "i", "]", ".", "count", "++", ";", "return", ";", "}", "}", "usernames", ".", "push", "(", "{", "'name'", ":", "userName", ",", "'count'", ":", "1", "}", ")", "}", "return", "out", ";", "}" ]
find the most common username by freguency of use
[ "find", "the", "most", "common", "username", "by", "freguency", "of", "use" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L232-L268
train
glennjones/elsewhere-profiles
lib/pages.js
appendUrl
function appendUrl(url, urls) { var i = urls.length found = false; while (i--) { if (utils.compareUrl(urls[i], url)) found = true; } if (found === false && utils.isUrl(url)) urls.push(url); }
javascript
function appendUrl(url, urls) { var i = urls.length found = false; while (i--) { if (utils.compareUrl(urls[i], url)) found = true; } if (found === false && utils.isUrl(url)) urls.push(url); }
[ "function", "appendUrl", "(", "url", ",", "urls", ")", "{", "var", "i", "=", "urls", ".", "length", "found", "=", "false", ";", "while", "(", "i", "--", ")", "{", "if", "(", "utils", ".", "compareUrl", "(", "urls", "[", "i", "]", ",", "url", ")", ")", "found", "=", "true", ";", "}", "if", "(", "found", "===", "false", "&&", "utils", ".", "isUrl", "(", "url", ")", ")", "urls", ".", "push", "(", "url", ")", ";", "}" ]
append a url if it is not already in the urls array
[ "append", "a", "url", "if", "it", "is", "not", "already", "in", "the", "urls", "array" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L434-L443
train
glennjones/elsewhere-profiles
lib/pages.js
rateAddress
function rateAddress(addr){ var rating = 0; if(addr != undefined){ if (addr['extended-address']) rating++; if (addr['street-address']) rating++; if (addr.locality) rating++; if (addr.region) rating++; if (addr['postal-code']) rating++; if (addr['country-name']) rating++; } return rating; }
javascript
function rateAddress(addr){ var rating = 0; if(addr != undefined){ if (addr['extended-address']) rating++; if (addr['street-address']) rating++; if (addr.locality) rating++; if (addr.region) rating++; if (addr['postal-code']) rating++; if (addr['country-name']) rating++; } return rating; }
[ "function", "rateAddress", "(", "addr", ")", "{", "var", "rating", "=", "0", ";", "if", "(", "addr", "!=", "undefined", ")", "{", "if", "(", "addr", "[", "'extended-address'", "]", ")", "rating", "++", ";", "if", "(", "addr", "[", "'street-address'", "]", ")", "rating", "++", ";", "if", "(", "addr", ".", "locality", ")", "rating", "++", ";", "if", "(", "addr", ".", "region", ")", "rating", "++", ";", "if", "(", "addr", "[", "'postal-code'", "]", ")", "rating", "++", ";", "if", "(", "addr", "[", "'country-name'", "]", ")", "rating", "++", ";", "}", "return", "rating", ";", "}" ]
rates the fullness of a given address
[ "rates", "the", "fullness", "of", "a", "given", "address" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L463-L474
train
matteodelabre/midijs
lib/gm.js
checkFamily
function checkFamily(program, family) { var familyIndex = gm.families.indexOf(family.toLowerCase()); if (familyIndex === -1 || program < (familyIndex * 8) || program >= ((familyIndex + 1) * 8)) { return false; } return true; }
javascript
function checkFamily(program, family) { var familyIndex = gm.families.indexOf(family.toLowerCase()); if (familyIndex === -1 || program < (familyIndex * 8) || program >= ((familyIndex + 1) * 8)) { return false; } return true; }
[ "function", "checkFamily", "(", "program", ",", "family", ")", "{", "var", "familyIndex", "=", "gm", ".", "families", ".", "indexOf", "(", "family", ".", "toLowerCase", "(", ")", ")", ";", "if", "(", "familyIndex", "===", "-", "1", "||", "program", "<", "(", "familyIndex", "*", "8", ")", "||", "program", ">=", "(", "(", "familyIndex", "+", "1", ")", "*", "8", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if a program is in a family of instruments @private @param {number} program Program to test @param {string} family Family name @return {boolean} Whether the program belongs to the family
[ "Check", "if", "a", "program", "is", "in", "a", "family", "of", "instruments" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/gm.js#L13-L22
train
matteodelabre/midijs
lib/error.js
format
function format(arg) { if (typeof arg === 'number') { return '0x' + arg.toString(16).toUpperCase(); } if (typeof arg === 'string') { return '"' + arg + '"'; } return arg.toString(); }
javascript
function format(arg) { if (typeof arg === 'number') { return '0x' + arg.toString(16).toUpperCase(); } if (typeof arg === 'string') { return '"' + arg + '"'; } return arg.toString(); }
[ "function", "format", "(", "arg", ")", "{", "if", "(", "typeof", "arg", "===", "'number'", ")", "{", "return", "'0x'", "+", "arg", ".", "toString", "(", "16", ")", ".", "toUpperCase", "(", ")", ";", "}", "if", "(", "typeof", "arg", "===", "'string'", ")", "{", "return", "'\"'", "+", "arg", "+", "'\"'", ";", "}", "return", "arg", ".", "toString", "(", ")", ";", "}" ]
Format an argument to be displayed in the error message @private @param {*} arg Argument to format @return {string} Formatted argument
[ "Format", "an", "argument", "to", "be", "displayed", "in", "the", "error", "message" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L12-L22
train
matteodelabre/midijs
lib/error.js
MIDIParserError
function MIDIParserError(actual, expected, byte) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.actual = actual; this.expected = expected; actual = format(actual); expected = format(expected); this.message = 'Invalid MIDI file: expected ' + expected + ' but found ' + actual; if (byte !== undefined) { this.byte = byte; this.message += ' (at byte ' + byte + ')'; } }
javascript
function MIDIParserError(actual, expected, byte) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.actual = actual; this.expected = expected; actual = format(actual); expected = format(expected); this.message = 'Invalid MIDI file: expected ' + expected + ' but found ' + actual; if (byte !== undefined) { this.byte = byte; this.message += ' (at byte ' + byte + ')'; } }
[ "function", "MIDIParserError", "(", "actual", ",", "expected", ",", "byte", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "actual", "=", "actual", ";", "this", ".", "expected", "=", "expected", ";", "actual", "=", "format", "(", "actual", ")", ";", "expected", "=", "format", "(", "expected", ")", ";", "this", ".", "message", "=", "'Invalid MIDI file: expected '", "+", "expected", "+", "' but found '", "+", "actual", ";", "if", "(", "byte", "!==", "undefined", ")", "{", "this", ".", "byte", "=", "byte", ";", "this", ".", "message", "+=", "' (at byte '", "+", "byte", "+", "')'", ";", "}", "}" ]
Consruct a new MIDIParserError @class MIDIParserError @extends Error @classdesc An error that occured while parsing a MIDI file @param {*} actual Actual value @param {*} expected Expected value @param {number} [byte] The byte at which the error occured
[ "Consruct", "a", "new", "MIDIParserError" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L35-L53
train
matteodelabre/midijs
lib/error.js
MIDIEncoderError
function MIDIEncoderError(actual, expected) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.actual = actual; this.expected = expected; actual = format(actual); expected = format(expected); this.message = 'MIDI encoding error: expected ' + expected + ' but found ' + actual; }
javascript
function MIDIEncoderError(actual, expected) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.actual = actual; this.expected = expected; actual = format(actual); expected = format(expected); this.message = 'MIDI encoding error: expected ' + expected + ' but found ' + actual; }
[ "function", "MIDIEncoderError", "(", "actual", ",", "expected", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "actual", "=", "actual", ";", "this", ".", "expected", "=", "expected", ";", "actual", "=", "format", "(", "actual", ")", ";", "expected", "=", "format", "(", "expected", ")", ";", "this", ".", "message", "=", "'MIDI encoding error: expected '", "+", "expected", "+", "' but found '", "+", "actual", ";", "}" ]
Construct a new MIDIEncoderError @class MIDIEncoderError @extends Error @classdesc An error that occured while encoding a MIDI file @param {*} actual Actual value @param {*} expected Expected value
[ "Construct", "a", "new", "MIDIEncoderError" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L68-L81
train
matteodelabre/midijs
lib/error.js
MIDIInvalidEventError
function MIDIInvalidEventError(message) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; }
javascript
function MIDIInvalidEventError(message) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; }
[ "function", "MIDIInvalidEventError", "(", "message", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "message", "=", "message", ";", "}" ]
Construct a new MIDIInvalidEventError @class MIDIInvalidEventError @extends Error @classdesc An error that occured if an event was malformed @param {string} message Error message
[ "Construct", "a", "new", "MIDIInvalidEventError" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L95-L101
train
matteodelabre/midijs
lib/error.js
MIDIInvalidArgument
function MIDIInvalidArgument(message) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; }
javascript
function MIDIInvalidArgument(message) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; }
[ "function", "MIDIInvalidArgument", "(", "message", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "message", "=", "message", ";", "}" ]
Construct a new MIDIInvalidArgument @class MIDIInvalidArgument @extends Error @classdesc Generic invalid argument error @param {string} message Error message
[ "Construct", "a", "new", "MIDIInvalidArgument" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L115-L121
train
matteodelabre/midijs
lib/error.js
MIDINotMIDIError
function MIDINotMIDIError() { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = 'Not a valid MIDI file'; }
javascript
function MIDINotMIDIError() { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = 'Not a valid MIDI file'; }
[ "function", "MIDINotMIDIError", "(", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "message", "=", "'Not a valid MIDI file'", ";", "}" ]
Construct a new MIDINotMIDIError @class MIDINotMIDIError @extends Error @classdesc An error that indicates that the file is not a MIDI file
[ "Construct", "a", "new", "MIDINotMIDIError" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L133-L139
train
matteodelabre/midijs
lib/error.js
MIDINotSupportedError
function MIDINotSupportedError(message) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; }
javascript
function MIDINotSupportedError(message) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; }
[ "function", "MIDINotSupportedError", "(", "message", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "message", "=", "message", ";", "}" ]
Construct a new MIDINotSupportedError @class MIDINotSupportedError @extends Error @classdesc An error that indicates that you tried to use a MIDI feature that is not supported by this library @param {string} message Error message
[ "Construct", "a", "new", "MIDINotSupportedError" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L154-L160
train
LivePersonInc/chronosjs
src/courier/PostMessageChannel.js
postMessage
function postMessage(message, target, force) { var consumer; var parsed; if (!this.disposed) { try { if (message) { if (this.ready || force) { // Post the message consumer = target || this.receiver; parsed = _prepareMessage.call(this, message); consumer.postMessage(parsed); return true; } else if (this.maxConcurrency >= this.messageQueue.length) { // Need to delay/queue messages till target is ready this.messageQueue.push(message); return true; } else { return false; } } } catch(ex) { /* istanbul ignore next */ PostMessageUtilities.log("Error while trying to post the message", "ERROR", "PostMessageChannel"); return false; } } }
javascript
function postMessage(message, target, force) { var consumer; var parsed; if (!this.disposed) { try { if (message) { if (this.ready || force) { // Post the message consumer = target || this.receiver; parsed = _prepareMessage.call(this, message); consumer.postMessage(parsed); return true; } else if (this.maxConcurrency >= this.messageQueue.length) { // Need to delay/queue messages till target is ready this.messageQueue.push(message); return true; } else { return false; } } } catch(ex) { /* istanbul ignore next */ PostMessageUtilities.log("Error while trying to post the message", "ERROR", "PostMessageChannel"); return false; } } }
[ "function", "postMessage", "(", "message", ",", "target", ",", "force", ")", "{", "var", "consumer", ";", "var", "parsed", ";", "if", "(", "!", "this", ".", "disposed", ")", "{", "try", "{", "if", "(", "message", ")", "{", "if", "(", "this", ".", "ready", "||", "force", ")", "{", "consumer", "=", "target", "||", "this", ".", "receiver", ";", "parsed", "=", "_prepareMessage", ".", "call", "(", "this", ",", "message", ")", ";", "consumer", ".", "postMessage", "(", "parsed", ")", ";", "return", "true", ";", "}", "else", "if", "(", "this", ".", "maxConcurrency", ">=", "this", ".", "messageQueue", ".", "length", ")", "{", "this", ".", "messageQueue", ".", "push", "(", "message", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}", "catch", "(", "ex", ")", "{", "PostMessageUtilities", ".", "log", "(", "\"Error while trying to post the message\"", ",", "\"ERROR\"", ",", "\"PostMessageChannel\"", ")", ";", "return", "false", ";", "}", "}", "}" ]
Method to post the message to the target @param {Object} message - the message to post @param {Object} [target] - optional target for post @param {Boolean} [force = false] - force post even if not ready
[ "Method", "to", "post", "the", "message", "to", "the", "target" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L214-L244
train
LivePersonInc/chronosjs
src/courier/PostMessageChannel.js
_hookupMessageChannel
function _hookupMessageChannel(onmessage) { return function() { this.channel = new MessageChannel(); this.receiver = this.channel.port1; this.dispatcher = this.channel.port2; this.receiver.onmessage = onmessage; this.neutered = false; }.bind(this); }
javascript
function _hookupMessageChannel(onmessage) { return function() { this.channel = new MessageChannel(); this.receiver = this.channel.port1; this.dispatcher = this.channel.port2; this.receiver.onmessage = onmessage; this.neutered = false; }.bind(this); }
[ "function", "_hookupMessageChannel", "(", "onmessage", ")", "{", "return", "function", "(", ")", "{", "this", ".", "channel", "=", "new", "MessageChannel", "(", ")", ";", "this", ".", "receiver", "=", "this", ".", "channel", ".", "port1", ";", "this", ".", "dispatcher", "=", "this", ".", "channel", ".", "port2", ";", "this", ".", "receiver", ".", "onmessage", "=", "onmessage", ";", "this", ".", "neutered", "=", "false", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
Method to create and hookup message channel factory for further use @param {Function} onmessage - the message handler to be used with the channel @private
[ "Method", "to", "create", "and", "hookup", "message", "channel", "factory", "for", "further", "use" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L408-L416
train
LivePersonInc/chronosjs
src/courier/PostMessageChannel.js
_isHandshake
function _isHandshake(event) { return (event && event.data && "string" === typeof event.data && (0 === event.data.indexOf(TOKEN_PREFIX) || (HANSHAKE_PREFIX + this.token) === event.data)); }
javascript
function _isHandshake(event) { return (event && event.data && "string" === typeof event.data && (0 === event.data.indexOf(TOKEN_PREFIX) || (HANSHAKE_PREFIX + this.token) === event.data)); }
[ "function", "_isHandshake", "(", "event", ")", "{", "return", "(", "event", "&&", "event", ".", "data", "&&", "\"string\"", "===", "typeof", "event", ".", "data", "&&", "(", "0", "===", "event", ".", "data", ".", "indexOf", "(", "TOKEN_PREFIX", ")", "||", "(", "HANSHAKE_PREFIX", "+", "this", ".", "token", ")", "===", "event", ".", "data", ")", ")", ";", "}" ]
Method to validate whether an event is for handshake @param {Object} event - the event object on message @private
[ "Method", "to", "validate", "whether", "an", "event", "is", "for", "handshake" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L443-L445
train
LivePersonInc/chronosjs
src/courier/PostMessageChannel.js
_wrapReadyCallback
function _wrapReadyCallback(onready, target) { return function(err) { if (target && "function" === typeof target.callback) { target.callback.call(target.context, err, this.target); } if (onready) { if ("function" === typeof onready) { onready(err, this.target); } else if ("function" === typeof onready.callback) { onready.callback.call(onready.context, err, this.target); } } }; }
javascript
function _wrapReadyCallback(onready, target) { return function(err) { if (target && "function" === typeof target.callback) { target.callback.call(target.context, err, this.target); } if (onready) { if ("function" === typeof onready) { onready(err, this.target); } else if ("function" === typeof onready.callback) { onready.callback.call(onready.context, err, this.target); } } }; }
[ "function", "_wrapReadyCallback", "(", "onready", ",", "target", ")", "{", "return", "function", "(", "err", ")", "{", "if", "(", "target", "&&", "\"function\"", "===", "typeof", "target", ".", "callback", ")", "{", "target", ".", "callback", ".", "call", "(", "target", ".", "context", ",", "err", ",", "this", ".", "target", ")", ";", "}", "if", "(", "onready", ")", "{", "if", "(", "\"function\"", "===", "typeof", "onready", ")", "{", "onready", "(", "err", ",", "this", ".", "target", ")", ";", "}", "else", "if", "(", "\"function\"", "===", "typeof", "onready", ".", "callback", ")", "{", "onready", ".", "callback", ".", "call", "(", "onready", ".", "context", ",", "err", ",", "this", ".", "target", ")", ";", "}", "}", "}", ";", "}" ]
Method for wrapping the callback of iframe ready @param {Function} [onready] - the handler for iframe ready @param {Object} [target] - the target iframe configuration @returns {Function} handler function for messages @private
[ "Method", "for", "wrapping", "the", "callback", "of", "iframe", "ready" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L454-L468
train
LivePersonInc/chronosjs
src/courier/PostMessageChannel.js
_waitForBody
function _waitForBody(options) { options = options || {}; var onready = options.onready; var doc = options.doc || root.document; var delay = options.delay; function _ready() { if (doc.body) { onready(); } else { PostMessageUtilities.delay(_ready, delay || DEFAULT_BODY_LOAD_DELAY); } } PostMessageUtilities.delay(_ready, delay || false); }
javascript
function _waitForBody(options) { options = options || {}; var onready = options.onready; var doc = options.doc || root.document; var delay = options.delay; function _ready() { if (doc.body) { onready(); } else { PostMessageUtilities.delay(_ready, delay || DEFAULT_BODY_LOAD_DELAY); } } PostMessageUtilities.delay(_ready, delay || false); }
[ "function", "_waitForBody", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "onready", "=", "options", ".", "onready", ";", "var", "doc", "=", "options", ".", "doc", "||", "root", ".", "document", ";", "var", "delay", "=", "options", ".", "delay", ";", "function", "_ready", "(", ")", "{", "if", "(", "doc", ".", "body", ")", "{", "onready", "(", ")", ";", "}", "else", "{", "PostMessageUtilities", ".", "delay", "(", "_ready", ",", "delay", "||", "DEFAULT_BODY_LOAD_DELAY", ")", ";", "}", "}", "PostMessageUtilities", ".", "delay", "(", "_ready", ",", "delay", "||", "false", ")", ";", "}" ]
Method to enable running a callback once the document body is ready @param {Object} [options] Configuration options @param {Function} options.onready - the callback to run when ready @param {Object} [options.doc = root.document] - document to refer to @param {Number} [options.delay = 0] - milliseconds to delay the execution @private
[ "Method", "to", "enable", "running", "a", "callback", "once", "the", "document", "body", "is", "ready" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L611-L627
train
LivePersonInc/chronosjs
src/courier/PostMessageChannel.js
_createIFrame
function _createIFrame(options, container) { var frame = document.createElement("IFRAME"); var name = PostMessageUtilities.createUniqueSequence(IFRAME_PREFIX + PostMessageUtilities.SEQUENCE_FORMAT); var delay = options.delayLoad; var defaultAttributes = { "id": name, "name" :name, "tabindex": "-1", // To prevent it getting focus when tabbing through the page "aria-hidden": "true", // To prevent it being picked up by screen-readers "title": "", // Adding an empty title for accessibility "role": "presentation", // Adding a presentation role http://yahoodevelopers.tumblr.com/post/59489724815/easy-fixes-to-common-accessibility-problems "allowTransparency":"true" }; var defaultStyle = { width :"0px", height : "0px", position :"absolute", top : "-1000px", left : "-1000px" }; options.attributes = options.attributes || defaultAttributes; for (var key in options.attributes){ if (options.attributes.hasOwnProperty(key)) { frame.setAttribute(key, options.attributes[key]); } } options.style = options.style || defaultStyle; if (options.style) { for (var attr in options.style) { if (options.style.hasOwnProperty(attr)) { frame.style[attr] = options.style[attr]; } } } // Append and hookup after body tag opens _waitForBody({ delay: delay, onready: function() { (container || document.body).appendChild(frame); this.rmload = _addLoadHandler.call(this, frame); _setIFrameLocation.call(this, frame, options.url, (false !== options.bust)); }.bind(this) }); return frame; }
javascript
function _createIFrame(options, container) { var frame = document.createElement("IFRAME"); var name = PostMessageUtilities.createUniqueSequence(IFRAME_PREFIX + PostMessageUtilities.SEQUENCE_FORMAT); var delay = options.delayLoad; var defaultAttributes = { "id": name, "name" :name, "tabindex": "-1", // To prevent it getting focus when tabbing through the page "aria-hidden": "true", // To prevent it being picked up by screen-readers "title": "", // Adding an empty title for accessibility "role": "presentation", // Adding a presentation role http://yahoodevelopers.tumblr.com/post/59489724815/easy-fixes-to-common-accessibility-problems "allowTransparency":"true" }; var defaultStyle = { width :"0px", height : "0px", position :"absolute", top : "-1000px", left : "-1000px" }; options.attributes = options.attributes || defaultAttributes; for (var key in options.attributes){ if (options.attributes.hasOwnProperty(key)) { frame.setAttribute(key, options.attributes[key]); } } options.style = options.style || defaultStyle; if (options.style) { for (var attr in options.style) { if (options.style.hasOwnProperty(attr)) { frame.style[attr] = options.style[attr]; } } } // Append and hookup after body tag opens _waitForBody({ delay: delay, onready: function() { (container || document.body).appendChild(frame); this.rmload = _addLoadHandler.call(this, frame); _setIFrameLocation.call(this, frame, options.url, (false !== options.bust)); }.bind(this) }); return frame; }
[ "function", "_createIFrame", "(", "options", ",", "container", ")", "{", "var", "frame", "=", "document", ".", "createElement", "(", "\"IFRAME\"", ")", ";", "var", "name", "=", "PostMessageUtilities", ".", "createUniqueSequence", "(", "IFRAME_PREFIX", "+", "PostMessageUtilities", ".", "SEQUENCE_FORMAT", ")", ";", "var", "delay", "=", "options", ".", "delayLoad", ";", "var", "defaultAttributes", "=", "{", "\"id\"", ":", "name", ",", "\"name\"", ":", "name", ",", "\"tabindex\"", ":", "\"-1\"", ",", "\"aria-hidden\"", ":", "\"true\"", ",", "\"title\"", ":", "\"\"", ",", "\"role\"", ":", "\"presentation\"", ",", "\"allowTransparency\"", ":", "\"true\"", "}", ";", "var", "defaultStyle", "=", "{", "width", ":", "\"0px\"", ",", "height", ":", "\"0px\"", ",", "position", ":", "\"absolute\"", ",", "top", ":", "\"-1000px\"", ",", "left", ":", "\"-1000px\"", "}", ";", "options", ".", "attributes", "=", "options", ".", "attributes", "||", "defaultAttributes", ";", "for", "(", "var", "key", "in", "options", ".", "attributes", ")", "{", "if", "(", "options", ".", "attributes", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "frame", ".", "setAttribute", "(", "key", ",", "options", ".", "attributes", "[", "key", "]", ")", ";", "}", "}", "options", ".", "style", "=", "options", ".", "style", "||", "defaultStyle", ";", "if", "(", "options", ".", "style", ")", "{", "for", "(", "var", "attr", "in", "options", ".", "style", ")", "{", "if", "(", "options", ".", "style", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "frame", ".", "style", "[", "attr", "]", "=", "options", ".", "style", "[", "attr", "]", ";", "}", "}", "}", "_waitForBody", "(", "{", "delay", ":", "delay", ",", "onready", ":", "function", "(", ")", "{", "(", "container", "||", "document", ".", "body", ")", ".", "appendChild", "(", "frame", ")", ";", "this", ".", "rmload", "=", "_addLoadHandler", ".", "call", "(", "this", ",", "frame", ")", ";", "_setIFrameLocation", ".", "call", "(", "this", ",", "frame", ",", "options", ".", "url", ",", "(", "false", "!==", "options", ".", "bust", ")", ")", ";", "}", ".", "bind", "(", "this", ")", "}", ")", ";", "return", "frame", ";", "}" ]
Creates an iFrame in memory and sets the default attributes except the actual URL Does not attach to DOM at this point @param {Object} options a passed in configuration options @param {String} options.url - the url to load, @param {String} [options.style] - the CSS style to apply @param {String} [options.style.width] width of iframe @param {String} [options.style.height] height of iframe ..... @param {Boolean} [options.bust = true] - optional flag to indicate usage of cache buster when loading the iframe (default to true), @param {Function} [options.callback] - a callback to invoke after the iframe had been loaded, @param {Object} [options.context] - optional context for the callback @param {Object} [container] - the container in which the iframe should be created (if not supplied, document.body will be used) @returns {Element} the attached iFrame element @private
[ "Creates", "an", "iFrame", "in", "memory", "and", "sets", "the", "default", "attributes", "except", "the", "actual", "URL", "Does", "not", "attach", "to", "DOM", "at", "this", "point" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L645-L693
train
LivePersonInc/chronosjs
src/courier/PostMessageChannel.js
_addLoadHandler
function _addLoadHandler(frame) { var load = function() { this.loading = false; if (this.handshakeAttempts === this.handshakeAttemptsOrig) { // Probably a first try for handshake or a reload of the iframe, // Either way, we'll need to perform handshake, so ready flag should be set to false (if not already) this.ready = false; } _handshake.call(this, this.handshakeInterval); }.bind(this); PostMessageUtilities.addEventListener(frame, "load", load); return function() { _removeLoadHandler(frame, load); }; }
javascript
function _addLoadHandler(frame) { var load = function() { this.loading = false; if (this.handshakeAttempts === this.handshakeAttemptsOrig) { // Probably a first try for handshake or a reload of the iframe, // Either way, we'll need to perform handshake, so ready flag should be set to false (if not already) this.ready = false; } _handshake.call(this, this.handshakeInterval); }.bind(this); PostMessageUtilities.addEventListener(frame, "load", load); return function() { _removeLoadHandler(frame, load); }; }
[ "function", "_addLoadHandler", "(", "frame", ")", "{", "var", "load", "=", "function", "(", ")", "{", "this", ".", "loading", "=", "false", ";", "if", "(", "this", ".", "handshakeAttempts", "===", "this", ".", "handshakeAttemptsOrig", ")", "{", "this", ".", "ready", "=", "false", ";", "}", "_handshake", ".", "call", "(", "this", ",", "this", ".", "handshakeInterval", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "PostMessageUtilities", ".", "addEventListener", "(", "frame", ",", "\"load\"", ",", "load", ")", ";", "return", "function", "(", ")", "{", "_removeLoadHandler", "(", "frame", ",", "load", ")", ";", "}", ";", "}" ]
Add load handler for the iframe to make sure it is loaded @param {Object} frame - the actual DOM iframe @returns {Function} the remove handler function @private
[ "Add", "load", "handler", "for", "the", "iframe", "to", "make", "sure", "it", "is", "loaded" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L701-L719
train
LivePersonInc/chronosjs
src/courier/PostMessageChannel.js
_setIFrameLocation
function _setIFrameLocation(frame, src, bust){ src += (0 < src.indexOf("?") ? "&" : "?"); if (bust) { src += "bust="; src += (new Date()).getTime() + "&"; } src += ((this.hostParam ? "hostParam=" + this.hostParam + "&" + this.hostParam + "=" : "lpHost=") + encodeURIComponent(PostMessageUtilities.getHost(void 0, frame, true))); if (!_isNativeMessageChannelSupported.call(this)) { src += "&lpPMCPolyfill=true"; } if (false === this.useObjects) { src += "&lpPMDeSerialize=true"; } frame.setAttribute("src", src); }
javascript
function _setIFrameLocation(frame, src, bust){ src += (0 < src.indexOf("?") ? "&" : "?"); if (bust) { src += "bust="; src += (new Date()).getTime() + "&"; } src += ((this.hostParam ? "hostParam=" + this.hostParam + "&" + this.hostParam + "=" : "lpHost=") + encodeURIComponent(PostMessageUtilities.getHost(void 0, frame, true))); if (!_isNativeMessageChannelSupported.call(this)) { src += "&lpPMCPolyfill=true"; } if (false === this.useObjects) { src += "&lpPMDeSerialize=true"; } frame.setAttribute("src", src); }
[ "function", "_setIFrameLocation", "(", "frame", ",", "src", ",", "bust", ")", "{", "src", "+=", "(", "0", "<", "src", ".", "indexOf", "(", "\"?\"", ")", "?", "\"&\"", ":", "\"?\"", ")", ";", "if", "(", "bust", ")", "{", "src", "+=", "\"bust=\"", ";", "src", "+=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "+", "\"&\"", ";", "}", "src", "+=", "(", "(", "this", ".", "hostParam", "?", "\"hostParam=\"", "+", "this", ".", "hostParam", "+", "\"&\"", "+", "this", ".", "hostParam", "+", "\"=\"", ":", "\"lpHost=\"", ")", "+", "encodeURIComponent", "(", "PostMessageUtilities", ".", "getHost", "(", "void", "0", ",", "frame", ",", "true", ")", ")", ")", ";", "if", "(", "!", "_isNativeMessageChannelSupported", ".", "call", "(", "this", ")", ")", "{", "src", "+=", "\"&lpPMCPolyfill=true\"", ";", "}", "if", "(", "false", "===", "this", ".", "useObjects", ")", "{", "src", "+=", "\"&lpPMDeSerialize=true\"", ";", "}", "frame", ".", "setAttribute", "(", "\"src\"", ",", "src", ")", ";", "}" ]
Sets the iFrame location using a cache bust mechanism, making sure the iFrame is actually loaded and not from cache @param {Object} frame - the iframe DOM object @param {String} src - the source url for the iframe @param {Boolean} bust - flag to indicate usage of cache buster when loading the iframe @private
[ "Sets", "the", "iFrame", "location", "using", "a", "cache", "bust", "mechanism", "making", "sure", "the", "iFrame", "is", "actually", "loaded", "and", "not", "from", "cache" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L739-L758
train
matteodelabre/midijs
lib/connect/input.js
Input
function Input(native) { EventEmitter.call(this); this.native = native; this.id = native.id; this.manufacturer = native.manufacturer; this.name = native.name; this.version = native.version; native.onmidimessage = function (event) { var data, type, object; data = new BufferCursor(new buffer.Buffer(event.data)); type = data.readUInt8(); object = parseChannelEvent( event.receivedTime, type >> 4, type & 0xF, data ); this.emit('event', object); }.bind(this); }
javascript
function Input(native) { EventEmitter.call(this); this.native = native; this.id = native.id; this.manufacturer = native.manufacturer; this.name = native.name; this.version = native.version; native.onmidimessage = function (event) { var data, type, object; data = new BufferCursor(new buffer.Buffer(event.data)); type = data.readUInt8(); object = parseChannelEvent( event.receivedTime, type >> 4, type & 0xF, data ); this.emit('event', object); }.bind(this); }
[ "function", "Input", "(", "native", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "native", "=", "native", ";", "this", ".", "id", "=", "native", ".", "id", ";", "this", ".", "manufacturer", "=", "native", ".", "manufacturer", ";", "this", ".", "name", "=", "native", ".", "name", ";", "this", ".", "version", "=", "native", ".", "version", ";", "native", ".", "onmidimessage", "=", "function", "(", "event", ")", "{", "var", "data", ",", "type", ",", "object", ";", "data", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "event", ".", "data", ")", ")", ";", "type", "=", "data", ".", "readUInt8", "(", ")", ";", "object", "=", "parseChannelEvent", "(", "event", ".", "receivedTime", ",", "type", ">>", "4", ",", "type", "&", "0xF", ",", "data", ")", ";", "this", ".", "emit", "(", "'event'", ",", "object", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
Construct a new Input @class Input @classdesc An input device from which we can receive MIDI events @param {MIDIInput} native Native MIDI input
[ "Construct", "a", "new", "Input" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/connect/input.js#L18-L42
train
glennjones/elsewhere-profiles
plugins/lanyrd.js
fetch
function fetch(identity, options, callback){ var completed = 0 combinedProfile = {}; // this is called once a page is fully parsed function whenFetched(err, data){ completed ++; // combines the api and microformats data into one profile if(data){ if(data.fn) {combinedProfile.fn = data.fn}; if(data.n) {combinedProfile.n = data.n}; if(data.nickname) {combinedProfile.nickname = data.nickname}; if(data.photo) {combinedProfile.photo = data.photo}; if(data.note) {combinedProfile.note = data.note}; // for the moment exclude microformat url structures if(data.url && data.source === 'api') { if(!combinedProfile.url) {combinedProfile.url = []}; var i = data.url.length; while (i--) { appendUrls(data.url[i], combinedProfile.url); } }; } // once we have both bit of data fire callback if(completed === 2){ callback(combinedProfile); } } // get microformats data getUFData(identity.userName, identity, options, function(err,data){ whenFetched(err, data); }); // get api data getAPIData(identity.userName, options, function(err,data){ whenFetched(err, data); }); }
javascript
function fetch(identity, options, callback){ var completed = 0 combinedProfile = {}; // this is called once a page is fully parsed function whenFetched(err, data){ completed ++; // combines the api and microformats data into one profile if(data){ if(data.fn) {combinedProfile.fn = data.fn}; if(data.n) {combinedProfile.n = data.n}; if(data.nickname) {combinedProfile.nickname = data.nickname}; if(data.photo) {combinedProfile.photo = data.photo}; if(data.note) {combinedProfile.note = data.note}; // for the moment exclude microformat url structures if(data.url && data.source === 'api') { if(!combinedProfile.url) {combinedProfile.url = []}; var i = data.url.length; while (i--) { appendUrls(data.url[i], combinedProfile.url); } }; } // once we have both bit of data fire callback if(completed === 2){ callback(combinedProfile); } } // get microformats data getUFData(identity.userName, identity, options, function(err,data){ whenFetched(err, data); }); // get api data getAPIData(identity.userName, options, function(err,data){ whenFetched(err, data); }); }
[ "function", "fetch", "(", "identity", ",", "options", ",", "callback", ")", "{", "var", "completed", "=", "0", "combinedProfile", "=", "{", "}", ";", "function", "whenFetched", "(", "err", ",", "data", ")", "{", "completed", "++", ";", "if", "(", "data", ")", "{", "if", "(", "data", ".", "fn", ")", "{", "combinedProfile", ".", "fn", "=", "data", ".", "fn", "}", ";", "if", "(", "data", ".", "n", ")", "{", "combinedProfile", ".", "n", "=", "data", ".", "n", "}", ";", "if", "(", "data", ".", "nickname", ")", "{", "combinedProfile", ".", "nickname", "=", "data", ".", "nickname", "}", ";", "if", "(", "data", ".", "photo", ")", "{", "combinedProfile", ".", "photo", "=", "data", ".", "photo", "}", ";", "if", "(", "data", ".", "note", ")", "{", "combinedProfile", ".", "note", "=", "data", ".", "note", "}", ";", "if", "(", "data", ".", "url", "&&", "data", ".", "source", "===", "'api'", ")", "{", "if", "(", "!", "combinedProfile", ".", "url", ")", "{", "combinedProfile", ".", "url", "=", "[", "]", "}", ";", "var", "i", "=", "data", ".", "url", ".", "length", ";", "while", "(", "i", "--", ")", "{", "appendUrls", "(", "data", ".", "url", "[", "i", "]", ",", "combinedProfile", ".", "url", ")", ";", "}", "}", ";", "}", "if", "(", "completed", "===", "2", ")", "{", "callback", "(", "combinedProfile", ")", ";", "}", "}", "getUFData", "(", "identity", ".", "userName", ",", "identity", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "whenFetched", "(", "err", ",", "data", ")", ";", "}", ")", ";", "getAPIData", "(", "identity", ".", "userName", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "whenFetched", "(", "err", ",", "data", ")", ";", "}", ")", ";", "}" ]
fetch both api and microformats data and then mix together
[ "fetch", "both", "api", "and", "microformats", "data", "and", "then", "mix", "together" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L41-L81
train
glennjones/elsewhere-profiles
plugins/lanyrd.js
whenFetched
function whenFetched(err, data){ completed ++; // combines the api and microformats data into one profile if(data){ if(data.fn) {combinedProfile.fn = data.fn}; if(data.n) {combinedProfile.n = data.n}; if(data.nickname) {combinedProfile.nickname = data.nickname}; if(data.photo) {combinedProfile.photo = data.photo}; if(data.note) {combinedProfile.note = data.note}; // for the moment exclude microformat url structures if(data.url && data.source === 'api') { if(!combinedProfile.url) {combinedProfile.url = []}; var i = data.url.length; while (i--) { appendUrls(data.url[i], combinedProfile.url); } }; } // once we have both bit of data fire callback if(completed === 2){ callback(combinedProfile); } }
javascript
function whenFetched(err, data){ completed ++; // combines the api and microformats data into one profile if(data){ if(data.fn) {combinedProfile.fn = data.fn}; if(data.n) {combinedProfile.n = data.n}; if(data.nickname) {combinedProfile.nickname = data.nickname}; if(data.photo) {combinedProfile.photo = data.photo}; if(data.note) {combinedProfile.note = data.note}; // for the moment exclude microformat url structures if(data.url && data.source === 'api') { if(!combinedProfile.url) {combinedProfile.url = []}; var i = data.url.length; while (i--) { appendUrls(data.url[i], combinedProfile.url); } }; } // once we have both bit of data fire callback if(completed === 2){ callback(combinedProfile); } }
[ "function", "whenFetched", "(", "err", ",", "data", ")", "{", "completed", "++", ";", "if", "(", "data", ")", "{", "if", "(", "data", ".", "fn", ")", "{", "combinedProfile", ".", "fn", "=", "data", ".", "fn", "}", ";", "if", "(", "data", ".", "n", ")", "{", "combinedProfile", ".", "n", "=", "data", ".", "n", "}", ";", "if", "(", "data", ".", "nickname", ")", "{", "combinedProfile", ".", "nickname", "=", "data", ".", "nickname", "}", ";", "if", "(", "data", ".", "photo", ")", "{", "combinedProfile", ".", "photo", "=", "data", ".", "photo", "}", ";", "if", "(", "data", ".", "note", ")", "{", "combinedProfile", ".", "note", "=", "data", ".", "note", "}", ";", "if", "(", "data", ".", "url", "&&", "data", ".", "source", "===", "'api'", ")", "{", "if", "(", "!", "combinedProfile", ".", "url", ")", "{", "combinedProfile", ".", "url", "=", "[", "]", "}", ";", "var", "i", "=", "data", ".", "url", ".", "length", ";", "while", "(", "i", "--", ")", "{", "appendUrls", "(", "data", ".", "url", "[", "i", "]", ",", "combinedProfile", ".", "url", ")", ";", "}", "}", ";", "}", "if", "(", "completed", "===", "2", ")", "{", "callback", "(", "combinedProfile", ")", ";", "}", "}" ]
this is called once a page is fully parsed
[ "this", "is", "called", "once", "a", "page", "is", "fully", "parsed" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L46-L70
train
glennjones/elsewhere-profiles
plugins/lanyrd.js
appendUrls
function appendUrls(url, arr){ var i = arr.length, found = false; while (i--) { if(arr[i] === url){ found = true; break; } } if(!found) arr.push(url); }
javascript
function appendUrls(url, arr){ var i = arr.length, found = false; while (i--) { if(arr[i] === url){ found = true; break; } } if(!found) arr.push(url); }
[ "function", "appendUrls", "(", "url", ",", "arr", ")", "{", "var", "i", "=", "arr", ".", "length", ",", "found", "=", "false", ";", "while", "(", "i", "--", ")", "{", "if", "(", "arr", "[", "i", "]", "===", "url", ")", "{", "found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "found", ")", "arr", ".", "push", "(", "url", ")", ";", "}" ]
appends url if its not already in the array
[ "appends", "url", "if", "its", "not", "already", "in", "the", "array" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L86-L96
train
glennjones/elsewhere-profiles
plugins/lanyrd.js
getUFData
function getUFData(userName, identity, options, callback) { var url = 'http://lanyrd.com/people/' + userName, cache = options.cache, page = new Page(url, identity, null, options); page.fetchUrl(function(){ if(page.profile.hCards.length > 0){ page.profile.hCards[0].source = 'microformat'; callback(null, page.profile.hCards[0]); }else{ callback(null, {}); } }) }
javascript
function getUFData(userName, identity, options, callback) { var url = 'http://lanyrd.com/people/' + userName, cache = options.cache, page = new Page(url, identity, null, options); page.fetchUrl(function(){ if(page.profile.hCards.length > 0){ page.profile.hCards[0].source = 'microformat'; callback(null, page.profile.hCards[0]); }else{ callback(null, {}); } }) }
[ "function", "getUFData", "(", "userName", ",", "identity", ",", "options", ",", "callback", ")", "{", "var", "url", "=", "'http://lanyrd.com/people/'", "+", "userName", ",", "cache", "=", "options", ".", "cache", ",", "page", "=", "new", "Page", "(", "url", ",", "identity", ",", "null", ",", "options", ")", ";", "page", ".", "fetchUrl", "(", "function", "(", ")", "{", "if", "(", "page", ".", "profile", ".", "hCards", ".", "length", ">", "0", ")", "{", "page", ".", "profile", ".", "hCards", "[", "0", "]", ".", "source", "=", "'microformat'", ";", "callback", "(", "null", ",", "page", ".", "profile", ".", "hCards", "[", "0", "]", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "{", "}", ")", ";", "}", "}", ")", "}" ]
collect microfomats data from the lanyrd site
[ "collect", "microfomats", "data", "from", "the", "lanyrd", "site" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L101-L114
train
glennjones/elsewhere-profiles
plugins/lanyrd.js
getAPIData
function getAPIData(userName, options, callback){ if(process.env.LANYRD_API_URL) { var url = process.env.LANYRD_API_URL + 'people/' + userName, cache = options.cache, startedRequest = new Date(), requestObj = { uri: url, headers: options.httpHeaders }; // if url is in the cache use that if(cache && cache.has(url)){ options.logger.info('using cache for lanyrd API data'); callback(null, parse(cache.get(url))); }else{ // if not get the json from the api url request(requestObj, function(requestErrors, response, body){ options.logger.info('getting lanyrd API data from url'); if(!requestErrors && response.statusCode === 200){ var data = JSON.parse(body) var out = parse(data); // add to cache store if(cache){ cache.set(url, data); } var endedRequest = new Date(); var requestTime = endedRequest.getTime() - startedRequest.getTime(); options.logger.log('made API call to: ' + requestTime + 'ms - ' + url); callback(null, out); }else{ callback('error requesting Lanyrd API', {}); } }); } }else{ callback('LANYRD_API_URL not found', {}); } }
javascript
function getAPIData(userName, options, callback){ if(process.env.LANYRD_API_URL) { var url = process.env.LANYRD_API_URL + 'people/' + userName, cache = options.cache, startedRequest = new Date(), requestObj = { uri: url, headers: options.httpHeaders }; // if url is in the cache use that if(cache && cache.has(url)){ options.logger.info('using cache for lanyrd API data'); callback(null, parse(cache.get(url))); }else{ // if not get the json from the api url request(requestObj, function(requestErrors, response, body){ options.logger.info('getting lanyrd API data from url'); if(!requestErrors && response.statusCode === 200){ var data = JSON.parse(body) var out = parse(data); // add to cache store if(cache){ cache.set(url, data); } var endedRequest = new Date(); var requestTime = endedRequest.getTime() - startedRequest.getTime(); options.logger.log('made API call to: ' + requestTime + 'ms - ' + url); callback(null, out); }else{ callback('error requesting Lanyrd API', {}); } }); } }else{ callback('LANYRD_API_URL not found', {}); } }
[ "function", "getAPIData", "(", "userName", ",", "options", ",", "callback", ")", "{", "if", "(", "process", ".", "env", ".", "LANYRD_API_URL", ")", "{", "var", "url", "=", "process", ".", "env", ".", "LANYRD_API_URL", "+", "'people/'", "+", "userName", ",", "cache", "=", "options", ".", "cache", ",", "startedRequest", "=", "new", "Date", "(", ")", ",", "requestObj", "=", "{", "uri", ":", "url", ",", "headers", ":", "options", ".", "httpHeaders", "}", ";", "if", "(", "cache", "&&", "cache", ".", "has", "(", "url", ")", ")", "{", "options", ".", "logger", ".", "info", "(", "'using cache for lanyrd API data'", ")", ";", "callback", "(", "null", ",", "parse", "(", "cache", ".", "get", "(", "url", ")", ")", ")", ";", "}", "else", "{", "request", "(", "requestObj", ",", "function", "(", "requestErrors", ",", "response", ",", "body", ")", "{", "options", ".", "logger", ".", "info", "(", "'getting lanyrd API data from url'", ")", ";", "if", "(", "!", "requestErrors", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "var", "data", "=", "JSON", ".", "parse", "(", "body", ")", "var", "out", "=", "parse", "(", "data", ")", ";", "if", "(", "cache", ")", "{", "cache", ".", "set", "(", "url", ",", "data", ")", ";", "}", "var", "endedRequest", "=", "new", "Date", "(", ")", ";", "var", "requestTime", "=", "endedRequest", ".", "getTime", "(", ")", "-", "startedRequest", ".", "getTime", "(", ")", ";", "options", ".", "logger", ".", "log", "(", "'made API call to: '", "+", "requestTime", "+", "'ms - '", "+", "url", ")", ";", "callback", "(", "null", ",", "out", ")", ";", "}", "else", "{", "callback", "(", "'error requesting Lanyrd API'", ",", "{", "}", ")", ";", "}", "}", ")", ";", "}", "}", "else", "{", "callback", "(", "'LANYRD_API_URL not found'", ",", "{", "}", ")", ";", "}", "}" ]
use the lanyrd api to get data
[ "use", "the", "lanyrd", "api", "to", "get", "data" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L119-L161
train
mozilla/speaktome-node
index.js
record
function record(options) { return new Promise((res, rej) => { var micInstance = mic({ rate: "16000", channels: "1", debug: true, exitOnSilence: 3, }); var micInputStream = micInstance.getAudioStream(); // Encode the file as Opus in an Ogg container, to send to server. var rate = 16000; var channels = 1; var opusEncodeStream = new opus.Encoder(rate, channels); var oggEncoder = new ogg.Encoder(); micInputStream.pipe(opusEncodeStream).pipe(oggEncoder.stream()); var bufs = []; oggEncoder.on("data", function(buffer) { bufs.push(buffer); }); oggEncoder.on("end", function() { // Package up encoded recording into buffer to send // over the network to the API endpoint. var buffer = Buffer.concat(bufs); sendRecordingToServer(buffer, options) .then((results) => { res(results); }) .catch((err) => { console.error("ERR", err); rej(err); }); }); micInputStream.on("silence", function() { // Stop recording at first silence after speaking. micInstance.stop(); }); micInputStream.on("error", function(err) { console.error("Error in Input Stream: " + err); }); micInstance.start(); }); }
javascript
function record(options) { return new Promise((res, rej) => { var micInstance = mic({ rate: "16000", channels: "1", debug: true, exitOnSilence: 3, }); var micInputStream = micInstance.getAudioStream(); // Encode the file as Opus in an Ogg container, to send to server. var rate = 16000; var channels = 1; var opusEncodeStream = new opus.Encoder(rate, channels); var oggEncoder = new ogg.Encoder(); micInputStream.pipe(opusEncodeStream).pipe(oggEncoder.stream()); var bufs = []; oggEncoder.on("data", function(buffer) { bufs.push(buffer); }); oggEncoder.on("end", function() { // Package up encoded recording into buffer to send // over the network to the API endpoint. var buffer = Buffer.concat(bufs); sendRecordingToServer(buffer, options) .then((results) => { res(results); }) .catch((err) => { console.error("ERR", err); rej(err); }); }); micInputStream.on("silence", function() { // Stop recording at first silence after speaking. micInstance.stop(); }); micInputStream.on("error", function(err) { console.error("Error in Input Stream: " + err); }); micInstance.start(); }); }
[ "function", "record", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "res", ",", "rej", ")", "=>", "{", "var", "micInstance", "=", "mic", "(", "{", "rate", ":", "\"16000\"", ",", "channels", ":", "\"1\"", ",", "debug", ":", "true", ",", "exitOnSilence", ":", "3", ",", "}", ")", ";", "var", "micInputStream", "=", "micInstance", ".", "getAudioStream", "(", ")", ";", "var", "rate", "=", "16000", ";", "var", "channels", "=", "1", ";", "var", "opusEncodeStream", "=", "new", "opus", ".", "Encoder", "(", "rate", ",", "channels", ")", ";", "var", "oggEncoder", "=", "new", "ogg", ".", "Encoder", "(", ")", ";", "micInputStream", ".", "pipe", "(", "opusEncodeStream", ")", ".", "pipe", "(", "oggEncoder", ".", "stream", "(", ")", ")", ";", "var", "bufs", "=", "[", "]", ";", "oggEncoder", ".", "on", "(", "\"data\"", ",", "function", "(", "buffer", ")", "{", "bufs", ".", "push", "(", "buffer", ")", ";", "}", ")", ";", "oggEncoder", ".", "on", "(", "\"end\"", ",", "function", "(", ")", "{", "var", "buffer", "=", "Buffer", ".", "concat", "(", "bufs", ")", ";", "sendRecordingToServer", "(", "buffer", ",", "options", ")", ".", "then", "(", "(", "results", ")", "=>", "{", "res", "(", "results", ")", ";", "}", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "console", ".", "error", "(", "\"ERR\"", ",", "err", ")", ";", "rej", "(", "err", ")", ";", "}", ")", ";", "}", ")", ";", "micInputStream", ".", "on", "(", "\"silence\"", ",", "function", "(", ")", "{", "micInstance", ".", "stop", "(", ")", ";", "}", ")", ";", "micInputStream", ".", "on", "(", "\"error\"", ",", "function", "(", "err", ")", "{", "console", ".", "error", "(", "\"Error in Input Stream: \"", "+", "err", ")", ";", "}", ")", ";", "micInstance", ".", "start", "(", ")", ";", "}", ")", ";", "}" ]
Listen, record, send to server. Promise that returns array of results from server.
[ "Listen", "record", "send", "to", "server", ".", "Promise", "that", "returns", "array", "of", "results", "from", "server", "." ]
af95d9890aa39d01e60de1c66434c003e81a51a7
https://github.com/mozilla/speaktome-node/blob/af95d9890aa39d01e60de1c66434c003e81a51a7/index.js#L66-L117
train
JamesMessinger/json-schema-lib
lib/api/JsonSchemaLib/JsonSchemaLib.js
JsonSchemaLib
function JsonSchemaLib (config, plugins) { if (plugins === undefined && Array.isArray(config)) { plugins = config; config = undefined; } /** * The configuration for this instance of {@link JsonSchemaLib}. * * @type {Config} */ this.config = new Config(config); /** * The plugins that have been added to this instance of {@link JsonSchemaLib} * * @type {object[]} */ this.plugins = new PluginManager(plugins); }
javascript
function JsonSchemaLib (config, plugins) { if (plugins === undefined && Array.isArray(config)) { plugins = config; config = undefined; } /** * The configuration for this instance of {@link JsonSchemaLib}. * * @type {Config} */ this.config = new Config(config); /** * The plugins that have been added to this instance of {@link JsonSchemaLib} * * @type {object[]} */ this.plugins = new PluginManager(plugins); }
[ "function", "JsonSchemaLib", "(", "config", ",", "plugins", ")", "{", "if", "(", "plugins", "===", "undefined", "&&", "Array", ".", "isArray", "(", "config", ")", ")", "{", "plugins", "=", "config", ";", "config", "=", "undefined", ";", "}", "this", ".", "config", "=", "new", "Config", "(", "config", ")", ";", "this", ".", "plugins", "=", "new", "PluginManager", "(", "plugins", ")", ";", "}" ]
The public JsonSchemaLib API. @param {Config} [config] - The configuration to use. Can be overridden by {@link JsonSchemaLib#read} @param {object[]} [plugins] - The plugins to use. Additional plugins can be added via {@link JsonSchemaLib#use} @class
[ "The", "public", "JsonSchemaLib", "API", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/JsonSchemaLib/JsonSchemaLib.js#L18-L37
train
basti1302/repoman
lib/cli.js
_config
function _config(args) { var opts = {}; if(args.removeExtraneous){ opts.removeExtraneous = true; } if (args.bitbucketAuthUser || args.bitbucketAuthPass) { opts.bitbucket = { authUser: args.bitbucketAuthUser, authPass: args.bitbucketAuthPass }; } else if (args.githubUser || args.githubOrg || args.githubAuthUser || args.githubAuthPass) { opts.github = { user : args.githubUser, org : args.githubOrg, authUser: args.githubAuthUser, authPass: args.githubAuthPass, useSsh : args.githubUseSsh }; } else if (args.gitoriousUrl || args.gitoriousProject) { opts.gitorious = { url : args.gitoriousUrl, project: args.gitoriousProject }; } else if (args.local) { opts.local = { dir: process.cwd() }; } new Repoman().config(opts, bag.exit); }
javascript
function _config(args) { var opts = {}; if(args.removeExtraneous){ opts.removeExtraneous = true; } if (args.bitbucketAuthUser || args.bitbucketAuthPass) { opts.bitbucket = { authUser: args.bitbucketAuthUser, authPass: args.bitbucketAuthPass }; } else if (args.githubUser || args.githubOrg || args.githubAuthUser || args.githubAuthPass) { opts.github = { user : args.githubUser, org : args.githubOrg, authUser: args.githubAuthUser, authPass: args.githubAuthPass, useSsh : args.githubUseSsh }; } else if (args.gitoriousUrl || args.gitoriousProject) { opts.gitorious = { url : args.gitoriousUrl, project: args.gitoriousProject }; } else if (args.local) { opts.local = { dir: process.cwd() }; } new Repoman().config(opts, bag.exit); }
[ "function", "_config", "(", "args", ")", "{", "var", "opts", "=", "{", "}", ";", "if", "(", "args", ".", "removeExtraneous", ")", "{", "opts", ".", "removeExtraneous", "=", "true", ";", "}", "if", "(", "args", ".", "bitbucketAuthUser", "||", "args", ".", "bitbucketAuthPass", ")", "{", "opts", ".", "bitbucket", "=", "{", "authUser", ":", "args", ".", "bitbucketAuthUser", ",", "authPass", ":", "args", ".", "bitbucketAuthPass", "}", ";", "}", "else", "if", "(", "args", ".", "githubUser", "||", "args", ".", "githubOrg", "||", "args", ".", "githubAuthUser", "||", "args", ".", "githubAuthPass", ")", "{", "opts", ".", "github", "=", "{", "user", ":", "args", ".", "githubUser", ",", "org", ":", "args", ".", "githubOrg", ",", "authUser", ":", "args", ".", "githubAuthUser", ",", "authPass", ":", "args", ".", "githubAuthPass", ",", "useSsh", ":", "args", ".", "githubUseSsh", "}", ";", "}", "else", "if", "(", "args", ".", "gitoriousUrl", "||", "args", ".", "gitoriousProject", ")", "{", "opts", ".", "gitorious", "=", "{", "url", ":", "args", ".", "gitoriousUrl", ",", "project", ":", "args", ".", "gitoriousProject", "}", ";", "}", "else", "if", "(", "args", ".", "local", ")", "{", "opts", ".", "local", "=", "{", "dir", ":", "process", ".", "cwd", "(", ")", "}", ";", "}", "new", "Repoman", "(", ")", ".", "config", "(", "opts", ",", "bag", ".", "exit", ")", ";", "}" ]
Repoman CLI module. @module cli
[ "Repoman", "CLI", "module", "." ]
a1037015636d5744bcf764bc44a79961a93488da
https://github.com/basti1302/repoman/blob/a1037015636d5744bcf764bc44a79961a93488da/lib/cli.js#L14-L49
train
matteodelabre/midijs
lib/file/event.js
Event
function Event(props, defaults, delay) { var name; this.delay = delay || 0; props = props || {}; for (name in defaults) { if (defaults.hasOwnProperty(name)) { if (props.hasOwnProperty(name)) { this[name] = props[name]; } else { this[name] = defaults[name]; } } } }
javascript
function Event(props, defaults, delay) { var name; this.delay = delay || 0; props = props || {}; for (name in defaults) { if (defaults.hasOwnProperty(name)) { if (props.hasOwnProperty(name)) { this[name] = props[name]; } else { this[name] = defaults[name]; } } } }
[ "function", "Event", "(", "props", ",", "defaults", ",", "delay", ")", "{", "var", "name", ";", "this", ".", "delay", "=", "delay", "||", "0", ";", "props", "=", "props", "||", "{", "}", ";", "for", "(", "name", "in", "defaults", ")", "{", "if", "(", "defaults", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "if", "(", "props", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "this", "[", "name", "]", "=", "props", "[", "name", "]", ";", "}", "else", "{", "this", "[", "name", "]", "=", "defaults", "[", "name", "]", ";", "}", "}", "}", "}" ]
Construct a new Event @abstract @class Event @classdesc Any type of MIDI event @param {Object} [props={}] Event properties @param {number} [defaults={}] Default event properties @param {number} [delay=0] Event delay in ticks
[ "Construct", "a", "new", "Event" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/event.js#L18-L33
train
matteodelabre/midijs
lib/file/event.js
MetaEvent
function MetaEvent(type, props, delay) { var defaults = {}; switch (type) { case MetaEvent.TYPE.SEQUENCE_NUMBER: defaults.number = 0; break; case MetaEvent.TYPE.TEXT: case MetaEvent.TYPE.COPYRIGHT_NOTICE: case MetaEvent.TYPE.SEQUENCE_NAME: case MetaEvent.TYPE.INSTRUMENT_NAME: case MetaEvent.TYPE.LYRICS: case MetaEvent.TYPE.MARKER: case MetaEvent.TYPE.CUE_POINT: case MetaEvent.TYPE.PROGRAM_NAME: case MetaEvent.TYPE.DEVICE_NAME: defaults.text = ''; break; case MetaEvent.TYPE.MIDI_CHANNEL: defaults.channel = 0; break; case MetaEvent.TYPE.MIDI_PORT: defaults.port = 0; break; case MetaEvent.TYPE.END_OF_TRACK: break; case MetaEvent.TYPE.SET_TEMPO: defaults.tempo = 120; break; case MetaEvent.TYPE.SMPTE_OFFSET: defaults.rate = 24; defaults.hours = 0; defaults.minutes = 0; defaults.seconds = 0; defaults.frames = 0; defaults.subframes = 0; break; case MetaEvent.TYPE.TIME_SIGNATURE: defaults.numerator = 4; defaults.denominator = 4; defaults.metronome = 24; defaults.clockSignalsPerBeat = 24; break; case MetaEvent.TYPE.KEY_SIGNATURE: defaults.note = 0; defaults.major = true; break; case MetaEvent.TYPE.SEQUENCER_SPECIFIC: defaults.data = new buffer.Buffer(0); break; default: throw new error.MIDIInvalidEventError( 'Invalid MetaEvent type "' + type + '"' ); } this.type = type; Event.call(this, props, defaults, delay); }
javascript
function MetaEvent(type, props, delay) { var defaults = {}; switch (type) { case MetaEvent.TYPE.SEQUENCE_NUMBER: defaults.number = 0; break; case MetaEvent.TYPE.TEXT: case MetaEvent.TYPE.COPYRIGHT_NOTICE: case MetaEvent.TYPE.SEQUENCE_NAME: case MetaEvent.TYPE.INSTRUMENT_NAME: case MetaEvent.TYPE.LYRICS: case MetaEvent.TYPE.MARKER: case MetaEvent.TYPE.CUE_POINT: case MetaEvent.TYPE.PROGRAM_NAME: case MetaEvent.TYPE.DEVICE_NAME: defaults.text = ''; break; case MetaEvent.TYPE.MIDI_CHANNEL: defaults.channel = 0; break; case MetaEvent.TYPE.MIDI_PORT: defaults.port = 0; break; case MetaEvent.TYPE.END_OF_TRACK: break; case MetaEvent.TYPE.SET_TEMPO: defaults.tempo = 120; break; case MetaEvent.TYPE.SMPTE_OFFSET: defaults.rate = 24; defaults.hours = 0; defaults.minutes = 0; defaults.seconds = 0; defaults.frames = 0; defaults.subframes = 0; break; case MetaEvent.TYPE.TIME_SIGNATURE: defaults.numerator = 4; defaults.denominator = 4; defaults.metronome = 24; defaults.clockSignalsPerBeat = 24; break; case MetaEvent.TYPE.KEY_SIGNATURE: defaults.note = 0; defaults.major = true; break; case MetaEvent.TYPE.SEQUENCER_SPECIFIC: defaults.data = new buffer.Buffer(0); break; default: throw new error.MIDIInvalidEventError( 'Invalid MetaEvent type "' + type + '"' ); } this.type = type; Event.call(this, props, defaults, delay); }
[ "function", "MetaEvent", "(", "type", ",", "props", ",", "delay", ")", "{", "var", "defaults", "=", "{", "}", ";", "switch", "(", "type", ")", "{", "case", "MetaEvent", ".", "TYPE", ".", "SEQUENCE_NUMBER", ":", "defaults", ".", "number", "=", "0", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "TEXT", ":", "case", "MetaEvent", ".", "TYPE", ".", "COPYRIGHT_NOTICE", ":", "case", "MetaEvent", ".", "TYPE", ".", "SEQUENCE_NAME", ":", "case", "MetaEvent", ".", "TYPE", ".", "INSTRUMENT_NAME", ":", "case", "MetaEvent", ".", "TYPE", ".", "LYRICS", ":", "case", "MetaEvent", ".", "TYPE", ".", "MARKER", ":", "case", "MetaEvent", ".", "TYPE", ".", "CUE_POINT", ":", "case", "MetaEvent", ".", "TYPE", ".", "PROGRAM_NAME", ":", "case", "MetaEvent", ".", "TYPE", ".", "DEVICE_NAME", ":", "defaults", ".", "text", "=", "''", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "MIDI_CHANNEL", ":", "defaults", ".", "channel", "=", "0", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "MIDI_PORT", ":", "defaults", ".", "port", "=", "0", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "END_OF_TRACK", ":", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "SET_TEMPO", ":", "defaults", ".", "tempo", "=", "120", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "SMPTE_OFFSET", ":", "defaults", ".", "rate", "=", "24", ";", "defaults", ".", "hours", "=", "0", ";", "defaults", ".", "minutes", "=", "0", ";", "defaults", ".", "seconds", "=", "0", ";", "defaults", ".", "frames", "=", "0", ";", "defaults", ".", "subframes", "=", "0", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "TIME_SIGNATURE", ":", "defaults", ".", "numerator", "=", "4", ";", "defaults", ".", "denominator", "=", "4", ";", "defaults", ".", "metronome", "=", "24", ";", "defaults", ".", "clockSignalsPerBeat", "=", "24", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "KEY_SIGNATURE", ":", "defaults", ".", "note", "=", "0", ";", "defaults", ".", "major", "=", "true", ";", "break", ";", "case", "MetaEvent", ".", "TYPE", ".", "SEQUENCER_SPECIFIC", ":", "defaults", ".", "data", "=", "new", "buffer", ".", "Buffer", "(", "0", ")", ";", "break", ";", "default", ":", "throw", "new", "error", ".", "MIDIInvalidEventError", "(", "'Invalid MetaEvent type \"'", "+", "type", "+", "'\"'", ")", ";", "}", "this", ".", "type", "=", "type", ";", "Event", ".", "call", "(", "this", ",", "props", ",", "defaults", ",", "delay", ")", ";", "}" ]
Construct a new MetaEvent @class MetaEvent @extends Event @classdesc A meta MIDI event, only encountered in Standard MIDI files as holds information about the file @param {MetaEvent.TYPE} type Type of meta event @param {Object} [props={}] Event properties (@see MetaEvent.TYPE) @param {number} [delay=0] Meta info delay in ticks @throws {module:midijs/lib/error~MIDIInvalidEventError} Invalid meta event type
[ "Construct", "a", "new", "MetaEvent" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/event.js#L51-L109
train
matteodelabre/midijs
lib/file/event.js
SysexEvent
function SysexEvent(type, data, delay) { this.type = type; this.data = data; Event.call(this, {}, {}, delay); }
javascript
function SysexEvent(type, data, delay) { this.type = type; this.data = data; Event.call(this, {}, {}, delay); }
[ "function", "SysexEvent", "(", "type", ",", "data", ",", "delay", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "data", "=", "data", ";", "Event", ".", "call", "(", "this", ",", "{", "}", ",", "{", "}", ",", "delay", ")", ";", "}" ]
Construct a SysexEvent @class SysexEvent @extends Event @classdesc A system exclusive MIDI event. This kind of event is not formally defined by the specification and can hold any kind of data. Its contents depends on the manufacturer, thus, this API does not try to interpret them but only passes the data along @param {number} type Sysex type @param {Buffer} data Sysex data @param {number} delay Sysex message delay in ticks
[ "Construct", "a", "SysexEvent" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/event.js#L204-L208
train
matteodelabre/midijs
lib/file/event.js
ChannelEvent
function ChannelEvent(type, props, channel, delay) { var defaults = {}; switch (type) { case ChannelEvent.TYPE.NOTE_OFF: defaults.note = 0; defaults.velocity = 127; break; case ChannelEvent.TYPE.NOTE_ON: defaults.note = 0; defaults.velocity = 127; break; case ChannelEvent.TYPE.NOTE_AFTERTOUCH: defaults.note = 0; defaults.pressure = 0; break; case ChannelEvent.TYPE.CONTROLLER: defaults.controller = 0; defaults.value = 127; break; case ChannelEvent.TYPE.PROGRAM_CHANGE: defaults.program = 0; break; case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH: defaults.pressure = 0; break; case ChannelEvent.TYPE.PITCH_BEND: defaults.value = 0; break; default: throw new error.MIDIInvalidEventError( 'Invalid ChannelEvent type "' + type + '"' ); } this.type = type; this.channel = channel || 0; Event.call(this, props, defaults, delay); }
javascript
function ChannelEvent(type, props, channel, delay) { var defaults = {}; switch (type) { case ChannelEvent.TYPE.NOTE_OFF: defaults.note = 0; defaults.velocity = 127; break; case ChannelEvent.TYPE.NOTE_ON: defaults.note = 0; defaults.velocity = 127; break; case ChannelEvent.TYPE.NOTE_AFTERTOUCH: defaults.note = 0; defaults.pressure = 0; break; case ChannelEvent.TYPE.CONTROLLER: defaults.controller = 0; defaults.value = 127; break; case ChannelEvent.TYPE.PROGRAM_CHANGE: defaults.program = 0; break; case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH: defaults.pressure = 0; break; case ChannelEvent.TYPE.PITCH_BEND: defaults.value = 0; break; default: throw new error.MIDIInvalidEventError( 'Invalid ChannelEvent type "' + type + '"' ); } this.type = type; this.channel = channel || 0; Event.call(this, props, defaults, delay); }
[ "function", "ChannelEvent", "(", "type", ",", "props", ",", "channel", ",", "delay", ")", "{", "var", "defaults", "=", "{", "}", ";", "switch", "(", "type", ")", "{", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_OFF", ":", "defaults", ".", "note", "=", "0", ";", "defaults", ".", "velocity", "=", "127", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_ON", ":", "defaults", ".", "note", "=", "0", ";", "defaults", ".", "velocity", "=", "127", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "NOTE_AFTERTOUCH", ":", "defaults", ".", "note", "=", "0", ";", "defaults", ".", "pressure", "=", "0", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "CONTROLLER", ":", "defaults", ".", "controller", "=", "0", ";", "defaults", ".", "value", "=", "127", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "PROGRAM_CHANGE", ":", "defaults", ".", "program", "=", "0", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "CHANNEL_AFTERTOUCH", ":", "defaults", ".", "pressure", "=", "0", ";", "break", ";", "case", "ChannelEvent", ".", "TYPE", ".", "PITCH_BEND", ":", "defaults", ".", "value", "=", "0", ";", "break", ";", "default", ":", "throw", "new", "error", ".", "MIDIInvalidEventError", "(", "'Invalid ChannelEvent type \"'", "+", "type", "+", "'\"'", ")", ";", "}", "this", ".", "type", "=", "type", ";", "this", ".", "channel", "=", "channel", "||", "0", ";", "Event", ".", "call", "(", "this", ",", "props", ",", "defaults", ",", "delay", ")", ";", "}" ]
Construct a ChannelEvent @class ChannelEvent @extends Event @classdesc A channel MIDI event. This kind of event is the most important one, it describes the state of the instruments, relative to the previous state. Channel events can be transmitted between devices and can also be present in Standard MIDI files. @param {ChannelEvent.TYPE} type Type of channel event @param {Object} [props={}] Event properties @param {number} [channel=0] Channel to which the event applies @param {number} [delay=0] Channel event delay in ticks @throws {module:midijs/lib/error~MIDIInvalidEventError} Invalid channel event type
[ "Construct", "a", "ChannelEvent" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/event.js#L230-L268
train
stagnationlab/jumio
build/index.js
Jumio
function Jumio(config) { var _this = this; // setup configuration with defaults this.config = __assign({ version: "1.0.0", identityApiBaseUrl: exports.identityRegionApiUrlMap[config.region], documentApiBaseUrl: exports.documentRegionApiUrlMap[config.region], callbackWhitelist: exports.regionCallbackWhitelistMap[config.region], handleIdentityVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/]; }); }); }, handleDocumentVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/]; }); }); }, log: ts_log_1.dummyLogger }, config); // keep a shorter reference to the logger this.log = this.config.log; // build company-specific user agent var userAgent = this.config.company + "/" + this.config.version; // configure axios for making API requests to the identity verification api this.identityApi = axios_1.default.create({ baseURL: this.config.identityApiBaseUrl, auth: { username: this.config.apiToken, password: this.config.apiSecret }, headers: { "User-Agent": userAgent } }); // configure axios for making API requests to the document verification api this.documentApi = axios_1.default.create({ baseURL: this.config.documentApiBaseUrl, auth: { username: this.config.apiToken, password: this.config.apiSecret }, headers: { "User-Agent": userAgent } }); // log initialized this.log.info({ identityApiBaseUrl: this.config.identityApiBaseUrl, documentApiBaseUrl: this.config.documentApiBaseUrl, apiToken: this.config.apiToken, apiSecret: new Array(this.config.apiSecret.length + 1).join("x"), userAgent: userAgent }, "initialized"); }
javascript
function Jumio(config) { var _this = this; // setup configuration with defaults this.config = __assign({ version: "1.0.0", identityApiBaseUrl: exports.identityRegionApiUrlMap[config.region], documentApiBaseUrl: exports.documentRegionApiUrlMap[config.region], callbackWhitelist: exports.regionCallbackWhitelistMap[config.region], handleIdentityVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/]; }); }); }, handleDocumentVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/]; }); }); }, log: ts_log_1.dummyLogger }, config); // keep a shorter reference to the logger this.log = this.config.log; // build company-specific user agent var userAgent = this.config.company + "/" + this.config.version; // configure axios for making API requests to the identity verification api this.identityApi = axios_1.default.create({ baseURL: this.config.identityApiBaseUrl, auth: { username: this.config.apiToken, password: this.config.apiSecret }, headers: { "User-Agent": userAgent } }); // configure axios for making API requests to the document verification api this.documentApi = axios_1.default.create({ baseURL: this.config.documentApiBaseUrl, auth: { username: this.config.apiToken, password: this.config.apiSecret }, headers: { "User-Agent": userAgent } }); // log initialized this.log.info({ identityApiBaseUrl: this.config.identityApiBaseUrl, documentApiBaseUrl: this.config.documentApiBaseUrl, apiToken: this.config.apiToken, apiSecret: new Array(this.config.apiSecret.length + 1).join("x"), userAgent: userAgent }, "initialized"); }
[ "function", "Jumio", "(", "config", ")", "{", "var", "_this", "=", "this", ";", "this", ".", "config", "=", "__assign", "(", "{", "version", ":", "\"1.0.0\"", ",", "identityApiBaseUrl", ":", "exports", ".", "identityRegionApiUrlMap", "[", "config", ".", "region", "]", ",", "documentApiBaseUrl", ":", "exports", ".", "documentRegionApiUrlMap", "[", "config", ".", "region", "]", ",", "callbackWhitelist", ":", "exports", ".", "regionCallbackWhitelistMap", "[", "config", ".", "region", "]", ",", "handleIdentityVerification", ":", "function", "(", "_result", ")", "{", "return", "__awaiter", "(", "_this", ",", "void", "0", ",", "void", "0", ",", "function", "(", ")", "{", "return", "__generator", "(", "this", ",", "function", "(", "_a", ")", "{", "return", "[", "2", "]", ";", "}", ")", ";", "}", ")", ";", "}", ",", "handleDocumentVerification", ":", "function", "(", "_result", ")", "{", "return", "__awaiter", "(", "_this", ",", "void", "0", ",", "void", "0", ",", "function", "(", ")", "{", "return", "__generator", "(", "this", ",", "function", "(", "_a", ")", "{", "return", "[", "2", "]", ";", "}", ")", ";", "}", ")", ";", "}", ",", "log", ":", "ts_log_1", ".", "dummyLogger", "}", ",", "config", ")", ";", "this", ".", "log", "=", "this", ".", "config", ".", "log", ";", "var", "userAgent", "=", "this", ".", "config", ".", "company", "+", "\"/\"", "+", "this", ".", "config", ".", "version", ";", "this", ".", "identityApi", "=", "axios_1", ".", "default", ".", "create", "(", "{", "baseURL", ":", "this", ".", "config", ".", "identityApiBaseUrl", ",", "auth", ":", "{", "username", ":", "this", ".", "config", ".", "apiToken", ",", "password", ":", "this", ".", "config", ".", "apiSecret", "}", ",", "headers", ":", "{", "\"User-Agent\"", ":", "userAgent", "}", "}", ")", ";", "this", ".", "documentApi", "=", "axios_1", ".", "default", ".", "create", "(", "{", "baseURL", ":", "this", ".", "config", ".", "documentApiBaseUrl", ",", "auth", ":", "{", "username", ":", "this", ".", "config", ".", "apiToken", ",", "password", ":", "this", ".", "config", ".", "apiSecret", "}", ",", "headers", ":", "{", "\"User-Agent\"", ":", "userAgent", "}", "}", ")", ";", "this", ".", "log", ".", "info", "(", "{", "identityApiBaseUrl", ":", "this", ".", "config", ".", "identityApiBaseUrl", ",", "documentApiBaseUrl", ":", "this", ".", "config", ".", "documentApiBaseUrl", ",", "apiToken", ":", "this", ".", "config", ".", "apiToken", ",", "apiSecret", ":", "new", "Array", "(", "this", ".", "config", ".", "apiSecret", ".", "length", "+", "1", ")", ".", "join", "(", "\"x\"", ")", ",", "userAgent", ":", "userAgent", "}", ",", "\"initialized\"", ")", ";", "}" ]
Sets up the library. @param config Configuration
[ "Sets", "up", "the", "library", "." ]
2e9223bf057b5b2c889806958aeec4db41473922
https://github.com/stagnationlab/jumio/blob/2e9223bf057b5b2c889806958aeec4db41473922/build/index.js#L2517-L2559
train
JamesMessinger/json-schema-lib
lib/util/isTypedArray.js
isTypedArray
function isTypedArray (obj) { if (typeof obj === 'object') { for (var i = 0; i < supportedDataTypes.length; i++) { if (obj instanceof supportedDataTypes[i]) { return true; } } } }
javascript
function isTypedArray (obj) { if (typeof obj === 'object') { for (var i = 0; i < supportedDataTypes.length; i++) { if (obj instanceof supportedDataTypes[i]) { return true; } } } }
[ "function", "isTypedArray", "(", "obj", ")", "{", "if", "(", "typeof", "obj", "===", "'object'", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "supportedDataTypes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "obj", "instanceof", "supportedDataTypes", "[", "i", "]", ")", "{", "return", "true", ";", "}", "}", "}", "}" ]
Determines whether the given object is any of the TypedArray types. @param {*} obj @returns {boolean}
[ "Determines", "whether", "the", "given", "object", "is", "any", "of", "the", "TypedArray", "types", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/isTypedArray.js#L13-L21
train
JamesMessinger/json-schema-lib
lib/util/isTypedArray.js
getSupportedDataTypes
function getSupportedDataTypes () { var types = []; // NOTE: More frequently-used types come first, to improve lookup speed if (typeof Uint8Array === 'function') { types.push(Uint8Array); } if (typeof Uint16Array === 'function') { types.push(Uint16Array); } if (typeof ArrayBuffer === 'function') { types.push(ArrayBuffer); } if (typeof Uint32Array === 'function') { types.push(Uint32Array); } if (typeof Int8Array === 'function') { types.push(Int8Array); } if (typeof Int16Array === 'function') { types.push(Int16Array); } if (typeof Int32Array === 'function') { types.push(Int32Array); } if (typeof Uint8ClampedArray === 'function') { types.push(Uint8ClampedArray); } if (typeof Float32Array === 'function') { types.push(Float32Array); } if (typeof Float64Array === 'function') { types.push(Float64Array); } if (typeof DataView === 'function') { types.push(DataView); } return types; }
javascript
function getSupportedDataTypes () { var types = []; // NOTE: More frequently-used types come first, to improve lookup speed if (typeof Uint8Array === 'function') { types.push(Uint8Array); } if (typeof Uint16Array === 'function') { types.push(Uint16Array); } if (typeof ArrayBuffer === 'function') { types.push(ArrayBuffer); } if (typeof Uint32Array === 'function') { types.push(Uint32Array); } if (typeof Int8Array === 'function') { types.push(Int8Array); } if (typeof Int16Array === 'function') { types.push(Int16Array); } if (typeof Int32Array === 'function') { types.push(Int32Array); } if (typeof Uint8ClampedArray === 'function') { types.push(Uint8ClampedArray); } if (typeof Float32Array === 'function') { types.push(Float32Array); } if (typeof Float64Array === 'function') { types.push(Float64Array); } if (typeof DataView === 'function') { types.push(DataView); } return types; }
[ "function", "getSupportedDataTypes", "(", ")", "{", "var", "types", "=", "[", "]", ";", "if", "(", "typeof", "Uint8Array", "===", "'function'", ")", "{", "types", ".", "push", "(", "Uint8Array", ")", ";", "}", "if", "(", "typeof", "Uint16Array", "===", "'function'", ")", "{", "types", ".", "push", "(", "Uint16Array", ")", ";", "}", "if", "(", "typeof", "ArrayBuffer", "===", "'function'", ")", "{", "types", ".", "push", "(", "ArrayBuffer", ")", ";", "}", "if", "(", "typeof", "Uint32Array", "===", "'function'", ")", "{", "types", ".", "push", "(", "Uint32Array", ")", ";", "}", "if", "(", "typeof", "Int8Array", "===", "'function'", ")", "{", "types", ".", "push", "(", "Int8Array", ")", ";", "}", "if", "(", "typeof", "Int16Array", "===", "'function'", ")", "{", "types", ".", "push", "(", "Int16Array", ")", ";", "}", "if", "(", "typeof", "Int32Array", "===", "'function'", ")", "{", "types", ".", "push", "(", "Int32Array", ")", ";", "}", "if", "(", "typeof", "Uint8ClampedArray", "===", "'function'", ")", "{", "types", ".", "push", "(", "Uint8ClampedArray", ")", ";", "}", "if", "(", "typeof", "Float32Array", "===", "'function'", ")", "{", "types", ".", "push", "(", "Float32Array", ")", ";", "}", "if", "(", "typeof", "Float64Array", "===", "'function'", ")", "{", "types", ".", "push", "(", "Float64Array", ")", ";", "}", "if", "(", "typeof", "DataView", "===", "'function'", ")", "{", "types", ".", "push", "(", "DataView", ")", ";", "}", "return", "types", ";", "}" ]
Returns the TypedArray data types that are supported by the current runtime environment. @returns {function[]}
[ "Returns", "the", "TypedArray", "data", "types", "that", "are", "supported", "by", "the", "current", "runtime", "environment", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/isTypedArray.js#L28-L67
train
basti1302/repoman
lib/generator/bitbucket.js
Bitbucket
function Bitbucket(user, pass) { this.user = user; this.client = bitbucket.createClient({ username: user, password: pass }); }
javascript
function Bitbucket(user, pass) { this.user = user; this.client = bitbucket.createClient({ username: user, password: pass }); }
[ "function", "Bitbucket", "(", "user", ",", "pass", ")", "{", "this", ".", "user", "=", "user", ";", "this", ".", "client", "=", "bitbucket", ".", "createClient", "(", "{", "username", ":", "user", ",", "password", ":", "pass", "}", ")", ";", "}" ]
Configuration generator for remote Bitbucket repositories. @param {String} user Bitbucket username @param {String} pass Bitbucket password @class
[ "Configuration", "generator", "for", "remote", "Bitbucket", "repositories", "." ]
a1037015636d5744bcf764bc44a79961a93488da
https://github.com/basti1302/repoman/blob/a1037015636d5744bcf764bc44a79961a93488da/lib/generator/bitbucket.js#L12-L16
train
matteodelabre/midijs
lib/file/parser/chunk.js
parseChunk
function parseChunk(expected, cursor) { var type, length; type = cursor.toString('ascii', 4); length = cursor.readUInt32BE(); if (type !== expected) { throw new error.MIDIParserError( type, expected, cursor.tell() ); } return cursor.slice(length); }
javascript
function parseChunk(expected, cursor) { var type, length; type = cursor.toString('ascii', 4); length = cursor.readUInt32BE(); if (type !== expected) { throw new error.MIDIParserError( type, expected, cursor.tell() ); } return cursor.slice(length); }
[ "function", "parseChunk", "(", "expected", ",", "cursor", ")", "{", "var", "type", ",", "length", ";", "type", "=", "cursor", ".", "toString", "(", "'ascii'", ",", "4", ")", ";", "length", "=", "cursor", ".", "readUInt32BE", "(", ")", ";", "if", "(", "type", "!==", "expected", ")", "{", "throw", "new", "error", ".", "MIDIParserError", "(", "type", ",", "expected", ",", "cursor", ".", "tell", "(", ")", ")", ";", "}", "return", "cursor", ".", "slice", "(", "length", ")", ";", "}" ]
Parse a MIDI chunk @param {string} expected Expected type @param {module:buffercursor} cursor Buffer to parse @throws {module:midijs/lib/error~MIDIParserError} Type expectation failed @return {Buffer} Chunk data
[ "Parse", "a", "MIDI", "chunk" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/chunk.js#L14-L29
train
LivePersonInc/chronosjs
src/Events.js
unbind
function unbind(unbindObj) { if ("*" !== defaultAppName) { unbindObj.appName = unbindObj.appName || defaultAppName; } return evUtil.unbind({ unbindObj: unbindObj, attrName: attrName, loggerName: appName, lstnrs: lstnrs }); }
javascript
function unbind(unbindObj) { if ("*" !== defaultAppName) { unbindObj.appName = unbindObj.appName || defaultAppName; } return evUtil.unbind({ unbindObj: unbindObj, attrName: attrName, loggerName: appName, lstnrs: lstnrs }); }
[ "function", "unbind", "(", "unbindObj", ")", "{", "if", "(", "\"*\"", "!==", "defaultAppName", ")", "{", "unbindObj", ".", "appName", "=", "unbindObj", ".", "appName", "||", "defaultAppName", ";", "}", "return", "evUtil", ".", "unbind", "(", "{", "unbindObj", ":", "unbindObj", ",", "attrName", ":", "attrName", ",", "loggerName", ":", "appName", ",", "lstnrs", ":", "lstnrs", "}", ")", ";", "}" ]
This function allows unbinding according to a permutation of the three parameters @param unbindObj eventName - the eventName you want to unbind func - the pointer to the function you want to unbind context - the context you want to unbind appName - the specific appName we want to unbind OR - eventId @return {Boolean}
[ "This", "function", "allows", "unbinding", "according", "to", "a", "permutation", "of", "the", "three", "parameters" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/Events.js#L135-L145
train
LivePersonInc/chronosjs
src/Events.js
hasFired
function hasFired(app, evName) { if ("undefined" === typeof evName) { evName = app; app = defaultAppName; } return evUtil.hasFired(fired, app, evName); }
javascript
function hasFired(app, evName) { if ("undefined" === typeof evName) { evName = app; app = defaultAppName; } return evUtil.hasFired(fired, app, evName); }
[ "function", "hasFired", "(", "app", ",", "evName", ")", "{", "if", "(", "\"undefined\"", "===", "typeof", "evName", ")", "{", "evName", "=", "app", ";", "app", "=", "defaultAppName", ";", "}", "return", "evUtil", ".", "hasFired", "(", "fired", ",", "app", ",", "evName", ")", ";", "}" ]
firedEventData can pass two request parameters @param app name @param evName = event name @return {Array}
[ "firedEventData", "can", "pass", "two", "request", "parameters" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/Events.js#L153-L160
train
LivePersonInc/chronosjs
src/Events.js
_storeEventData
function _storeEventData(triggerData) { evUtil.storeEventData({ triggerData: triggerData, eventBufferLimit: eventBufferLimit, attrName: attrName, fired: fired, index: indexer }); }
javascript
function _storeEventData(triggerData) { evUtil.storeEventData({ triggerData: triggerData, eventBufferLimit: eventBufferLimit, attrName: attrName, fired: fired, index: indexer }); }
[ "function", "_storeEventData", "(", "triggerData", ")", "{", "evUtil", ".", "storeEventData", "(", "{", "triggerData", ":", "triggerData", ",", "eventBufferLimit", ":", "eventBufferLimit", ",", "attrName", ":", "attrName", ",", "fired", ":", "fired", ",", "index", ":", "indexer", "}", ")", ";", "}" ]
Stores events so we can later ask for them, can be set to a limited store by defaults on instantiation @param triggerData
[ "Stores", "events", "so", "we", "can", "later", "ask", "for", "them", "can", "be", "set", "to", "a", "limited", "store", "by", "defaults", "on", "instantiation" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/Events.js#L237-L245
train
graphology/graphology-shortest-path
unweighted.js
singleSource
function singleSource(graph, source) { if (!isGraph(graph)) throw new Error('graphology-shortest-path: invalid graphology instance.'); if (arguments.length < 2) throw new Error('graphology-shortest-path: invalid number of arguments. Expecting at least 2.'); if (!graph.hasNode(source)) throw new Error('graphology-shortest-path: the "' + source + '" source node does not exist in the given graph.'); source = '' + source; var nextLevel = {}, paths = {}, currentLevel, neighbors, v, w, i, l; nextLevel[source] = true; paths[source] = [source]; while (Object.keys(nextLevel).length) { currentLevel = nextLevel; nextLevel = {}; for (v in currentLevel) { neighbors = graph.outNeighbors(v); neighbors.push.apply(neighbors, graph.undirectedNeighbors(v)); for (i = 0, l = neighbors.length; i < l; i++) { w = neighbors[i]; if (!paths[w]) { paths[w] = paths[v].concat(w); nextLevel[w] = true; } } } } return paths; }
javascript
function singleSource(graph, source) { if (!isGraph(graph)) throw new Error('graphology-shortest-path: invalid graphology instance.'); if (arguments.length < 2) throw new Error('graphology-shortest-path: invalid number of arguments. Expecting at least 2.'); if (!graph.hasNode(source)) throw new Error('graphology-shortest-path: the "' + source + '" source node does not exist in the given graph.'); source = '' + source; var nextLevel = {}, paths = {}, currentLevel, neighbors, v, w, i, l; nextLevel[source] = true; paths[source] = [source]; while (Object.keys(nextLevel).length) { currentLevel = nextLevel; nextLevel = {}; for (v in currentLevel) { neighbors = graph.outNeighbors(v); neighbors.push.apply(neighbors, graph.undirectedNeighbors(v)); for (i = 0, l = neighbors.length; i < l; i++) { w = neighbors[i]; if (!paths[w]) { paths[w] = paths[v].concat(w); nextLevel[w] = true; } } } } return paths; }
[ "function", "singleSource", "(", "graph", ",", "source", ")", "{", "if", "(", "!", "isGraph", "(", "graph", ")", ")", "throw", "new", "Error", "(", "'graphology-shortest-path: invalid graphology instance.'", ")", ";", "if", "(", "arguments", ".", "length", "<", "2", ")", "throw", "new", "Error", "(", "'graphology-shortest-path: invalid number of arguments. Expecting at least 2.'", ")", ";", "if", "(", "!", "graph", ".", "hasNode", "(", "source", ")", ")", "throw", "new", "Error", "(", "'graphology-shortest-path: the \"'", "+", "source", "+", "'\" source node does not exist in the given graph.'", ")", ";", "source", "=", "''", "+", "source", ";", "var", "nextLevel", "=", "{", "}", ",", "paths", "=", "{", "}", ",", "currentLevel", ",", "neighbors", ",", "v", ",", "w", ",", "i", ",", "l", ";", "nextLevel", "[", "source", "]", "=", "true", ";", "paths", "[", "source", "]", "=", "[", "source", "]", ";", "while", "(", "Object", ".", "keys", "(", "nextLevel", ")", ".", "length", ")", "{", "currentLevel", "=", "nextLevel", ";", "nextLevel", "=", "{", "}", ";", "for", "(", "v", "in", "currentLevel", ")", "{", "neighbors", "=", "graph", ".", "outNeighbors", "(", "v", ")", ";", "neighbors", ".", "push", ".", "apply", "(", "neighbors", ",", "graph", ".", "undirectedNeighbors", "(", "v", ")", ")", ";", "for", "(", "i", "=", "0", ",", "l", "=", "neighbors", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "w", "=", "neighbors", "[", "i", "]", ";", "if", "(", "!", "paths", "[", "w", "]", ")", "{", "paths", "[", "w", "]", "=", "paths", "[", "v", "]", ".", "concat", "(", "w", ")", ";", "nextLevel", "[", "w", "]", "=", "true", ";", "}", "}", "}", "}", "return", "paths", ";", "}" ]
Function attempting to find the shortest path in the graph between the given source node & all the other nodes. @param {Graph} graph - Target graph. @param {any} source - Source node. @return {object} - The map of found paths. TODO: cutoff option
[ "Function", "attempting", "to", "find", "the", "shortest", "path", "in", "the", "graph", "between", "the", "given", "source", "node", "&", "all", "the", "other", "nodes", "." ]
d0c820c5242fc48738102f40b9cdf345a078248c
https://github.com/graphology/graphology-shortest-path/blob/d0c820c5242fc48738102f40b9cdf345a078248c/unweighted.js#L174-L218
train
JamesMessinger/json-schema-lib
lib/plugins/NodeUrlPlugin.js
resolveUrl
function resolveUrl (from, to) { if (typeof URL === 'function') { // Use the new WHATWG URL API return new URL(to, from).href; } else { // Use the legacy url API return legacyURL.resolve(from, to); } }
javascript
function resolveUrl (from, to) { if (typeof URL === 'function') { // Use the new WHATWG URL API return new URL(to, from).href; } else { // Use the legacy url API return legacyURL.resolve(from, to); } }
[ "function", "resolveUrl", "(", "from", ",", "to", ")", "{", "if", "(", "typeof", "URL", "===", "'function'", ")", "{", "return", "new", "URL", "(", "to", ",", "from", ")", ".", "href", ";", "}", "else", "{", "return", "legacyURL", ".", "resolve", "(", "from", ",", "to", ")", ";", "}", "}" ]
Resolve the given URL, using either the legacy Node.js url API, or the WHATWG URL API. @param {string} from @param {string} to @returns {string}
[ "Resolve", "the", "given", "URL", "using", "either", "the", "legacy", "Node", ".", "js", "url", "API", "or", "the", "WHATWG", "URL", "API", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/NodeUrlPlugin.js#L76-L85
train
graphology/graphology-shortest-path
dijkstra.js
abstractDijkstraMultisource
function abstractDijkstraMultisource( graph, sources, weightAttribute, cutoff, target, paths ) { if (!isGraph(graph)) throw new Error('graphology-shortest-path/dijkstra: invalid graphology instance.'); if (target && !graph.hasNode(target)) throw new Error('graphology-shortest-path/dijkstra: the "' + target + '" target node does not exist in the given graph.'); weightAttribute = weightAttribute || DEFAULTS.weightAttribute; // Building necessary functions var getWeight = function(edge) { return graph.getEdgeAttribute(edge, weightAttribute); }; var distances = {}, seen = {}, fringe = new Heap(DIJKSTRA_HEAP_COMPARATOR); var count = 0, edges, item, cost, v, u, e, d, i, j, l, m; for (i = 0, l = sources.length; i < l; i++) { v = sources[i]; seen[v] = 0; fringe.push([0, count++, v]); if (paths) paths[v] = [v]; } while (fringe.size) { item = fringe.pop(); d = item[0]; v = item[2]; if (v in distances) continue; distances[v] = d; if (v === target) break; edges = graph .undirectedEdges(v) .concat(graph.outEdges(v)); for (j = 0, m = edges.length; j < m; j++) { e = edges[j]; u = graph.opposite(v, e); cost = getWeight(e) + distances[v]; if (cutoff && cost > cutoff) continue; if (u in distances && cost < distances[u]) { throw Error('graphology-shortest-path/dijkstra: contradictory paths found. Do some of your edges have a negative weight?'); } else if (!(u in seen) || cost < seen[u]) { seen[u] = cost; fringe.push([cost, count++, u]); if (paths) paths[u] = paths[v].concat(u); } } } return distances; }
javascript
function abstractDijkstraMultisource( graph, sources, weightAttribute, cutoff, target, paths ) { if (!isGraph(graph)) throw new Error('graphology-shortest-path/dijkstra: invalid graphology instance.'); if (target && !graph.hasNode(target)) throw new Error('graphology-shortest-path/dijkstra: the "' + target + '" target node does not exist in the given graph.'); weightAttribute = weightAttribute || DEFAULTS.weightAttribute; // Building necessary functions var getWeight = function(edge) { return graph.getEdgeAttribute(edge, weightAttribute); }; var distances = {}, seen = {}, fringe = new Heap(DIJKSTRA_HEAP_COMPARATOR); var count = 0, edges, item, cost, v, u, e, d, i, j, l, m; for (i = 0, l = sources.length; i < l; i++) { v = sources[i]; seen[v] = 0; fringe.push([0, count++, v]); if (paths) paths[v] = [v]; } while (fringe.size) { item = fringe.pop(); d = item[0]; v = item[2]; if (v in distances) continue; distances[v] = d; if (v === target) break; edges = graph .undirectedEdges(v) .concat(graph.outEdges(v)); for (j = 0, m = edges.length; j < m; j++) { e = edges[j]; u = graph.opposite(v, e); cost = getWeight(e) + distances[v]; if (cutoff && cost > cutoff) continue; if (u in distances && cost < distances[u]) { throw Error('graphology-shortest-path/dijkstra: contradictory paths found. Do some of your edges have a negative weight?'); } else if (!(u in seen) || cost < seen[u]) { seen[u] = cost; fringe.push([cost, count++, u]); if (paths) paths[u] = paths[v].concat(u); } } } return distances; }
[ "function", "abstractDijkstraMultisource", "(", "graph", ",", "sources", ",", "weightAttribute", ",", "cutoff", ",", "target", ",", "paths", ")", "{", "if", "(", "!", "isGraph", "(", "graph", ")", ")", "throw", "new", "Error", "(", "'graphology-shortest-path/dijkstra: invalid graphology instance.'", ")", ";", "if", "(", "target", "&&", "!", "graph", ".", "hasNode", "(", "target", ")", ")", "throw", "new", "Error", "(", "'graphology-shortest-path/dijkstra: the \"'", "+", "target", "+", "'\" target node does not exist in the given graph.'", ")", ";", "weightAttribute", "=", "weightAttribute", "||", "DEFAULTS", ".", "weightAttribute", ";", "var", "getWeight", "=", "function", "(", "edge", ")", "{", "return", "graph", ".", "getEdgeAttribute", "(", "edge", ",", "weightAttribute", ")", ";", "}", ";", "var", "distances", "=", "{", "}", ",", "seen", "=", "{", "}", ",", "fringe", "=", "new", "Heap", "(", "DIJKSTRA_HEAP_COMPARATOR", ")", ";", "var", "count", "=", "0", ",", "edges", ",", "item", ",", "cost", ",", "v", ",", "u", ",", "e", ",", "d", ",", "i", ",", "j", ",", "l", ",", "m", ";", "for", "(", "i", "=", "0", ",", "l", "=", "sources", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "v", "=", "sources", "[", "i", "]", ";", "seen", "[", "v", "]", "=", "0", ";", "fringe", ".", "push", "(", "[", "0", ",", "count", "++", ",", "v", "]", ")", ";", "if", "(", "paths", ")", "paths", "[", "v", "]", "=", "[", "v", "]", ";", "}", "while", "(", "fringe", ".", "size", ")", "{", "item", "=", "fringe", ".", "pop", "(", ")", ";", "d", "=", "item", "[", "0", "]", ";", "v", "=", "item", "[", "2", "]", ";", "if", "(", "v", "in", "distances", ")", "continue", ";", "distances", "[", "v", "]", "=", "d", ";", "if", "(", "v", "===", "target", ")", "break", ";", "edges", "=", "graph", ".", "undirectedEdges", "(", "v", ")", ".", "concat", "(", "graph", ".", "outEdges", "(", "v", ")", ")", ";", "for", "(", "j", "=", "0", ",", "m", "=", "edges", ".", "length", ";", "j", "<", "m", ";", "j", "++", ")", "{", "e", "=", "edges", "[", "j", "]", ";", "u", "=", "graph", ".", "opposite", "(", "v", ",", "e", ")", ";", "cost", "=", "getWeight", "(", "e", ")", "+", "distances", "[", "v", "]", ";", "if", "(", "cutoff", "&&", "cost", ">", "cutoff", ")", "continue", ";", "if", "(", "u", "in", "distances", "&&", "cost", "<", "distances", "[", "u", "]", ")", "{", "throw", "Error", "(", "'graphology-shortest-path/dijkstra: contradictory paths found. Do some of your edges have a negative weight?'", ")", ";", "}", "else", "if", "(", "!", "(", "u", "in", "seen", ")", "||", "cost", "<", "seen", "[", "u", "]", ")", "{", "seen", "[", "u", "]", "=", "cost", ";", "fringe", ".", "push", "(", "[", "cost", ",", "count", "++", ",", "u", "]", ")", ";", "if", "(", "paths", ")", "paths", "[", "u", "]", "=", "paths", "[", "v", "]", ".", "concat", "(", "u", ")", ";", "}", "}", "}", "return", "distances", ";", "}" ]
Multisource Dijkstra shortest path abstract function. This function is the basis of the algorithm that every other will use. Note that this implementation was basically copied from networkx. TODO: it might be more performant to use a dedicated objet for the heap's items. @param {Graph} graph - The graphology instance. @param {array} sources - A list of sources. @param {string} weightAttribute - Name of the weight attribute. @param {number} cutoff - Maximum depth of the search. @param {string} target - Optional target to reach. @param {object} paths - Optional paths object to maintain. @return {object} - Returns the paths.
[ "Multisource", "Dijkstra", "shortest", "path", "abstract", "function", ".", "This", "function", "is", "the", "basis", "of", "the", "algorithm", "that", "every", "other", "will", "use", "." ]
d0c820c5242fc48738102f40b9cdf345a078248c
https://github.com/graphology/graphology-shortest-path/blob/d0c820c5242fc48738102f40b9cdf345a078248c/dijkstra.js#L190-L278
train
graphology/graphology-shortest-path
dijkstra.js
singleSourceDijkstra
function singleSourceDijkstra(graph, source, weightAttribute) { var paths = {}; abstractDijkstraMultisource( graph, [source], weightAttribute, 0, null, paths ); return paths; }
javascript
function singleSourceDijkstra(graph, source, weightAttribute) { var paths = {}; abstractDijkstraMultisource( graph, [source], weightAttribute, 0, null, paths ); return paths; }
[ "function", "singleSourceDijkstra", "(", "graph", ",", "source", ",", "weightAttribute", ")", "{", "var", "paths", "=", "{", "}", ";", "abstractDijkstraMultisource", "(", "graph", ",", "[", "source", "]", ",", "weightAttribute", ",", "0", ",", "null", ",", "paths", ")", ";", "return", "paths", ";", "}" ]
Single source Dijkstra shortest path between given node & other nodes in the graph. @param {Graph} graph - The graphology instance. @param {string} source - Source node. @param {string} weightAttribute - Name of the weight attribute. @return {object} - An object of found paths.
[ "Single", "source", "Dijkstra", "shortest", "path", "between", "given", "node", "&", "other", "nodes", "in", "the", "graph", "." ]
d0c820c5242fc48738102f40b9cdf345a078248c
https://github.com/graphology/graphology-shortest-path/blob/d0c820c5242fc48738102f40b9cdf345a078248c/dijkstra.js#L289-L302
train
JamesMessinger/json-schema-lib
lib/api/PluginHelper/PluginHelper.js
PluginHelper
function PluginHelper (plugins, schema) { validatePlugins(plugins); plugins = plugins || []; // Clone the array of plugins, and sort by priority var pluginHelper = plugins.slice().sort(sortByPriority); /** * Internal stuff. Use at your own risk! * * @private */ pluginHelper[__internal] = { /** * A reference to the {@link Schema} object */ schema: schema, }; // Return an array that "inherits" from PluginHelper return assign(pluginHelper, PluginHelper.prototype); }
javascript
function PluginHelper (plugins, schema) { validatePlugins(plugins); plugins = plugins || []; // Clone the array of plugins, and sort by priority var pluginHelper = plugins.slice().sort(sortByPriority); /** * Internal stuff. Use at your own risk! * * @private */ pluginHelper[__internal] = { /** * A reference to the {@link Schema} object */ schema: schema, }; // Return an array that "inherits" from PluginHelper return assign(pluginHelper, PluginHelper.prototype); }
[ "function", "PluginHelper", "(", "plugins", ",", "schema", ")", "{", "validatePlugins", "(", "plugins", ")", ";", "plugins", "=", "plugins", "||", "[", "]", ";", "var", "pluginHelper", "=", "plugins", ".", "slice", "(", ")", ".", "sort", "(", "sortByPriority", ")", ";", "pluginHelper", "[", "__internal", "]", "=", "{", "schema", ":", "schema", ",", "}", ";", "return", "assign", "(", "pluginHelper", ",", "PluginHelper", ".", "prototype", ")", ";", "}" ]
Helper methods for working with plugins. @param {object[]|null} plugins - The plugins to use @param {Schema} schema - The {@link Schema} to apply the plugins to @class @extends Array
[ "Helper", "methods", "for", "working", "with", "plugins", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginHelper/PluginHelper.js#L21-L42
train
matteodelabre/midijs
lib/file/encoder/chunk.js
encodeChunk
function encodeChunk(type, data) { var cursor = new BufferCursor(new buffer.Buffer( buffer.Buffer.byteLength(type) + 4 + data.length )); cursor.write(type); cursor.writeUInt32BE(data.length); cursor.copy(data); return cursor.buffer; }
javascript
function encodeChunk(type, data) { var cursor = new BufferCursor(new buffer.Buffer( buffer.Buffer.byteLength(type) + 4 + data.length )); cursor.write(type); cursor.writeUInt32BE(data.length); cursor.copy(data); return cursor.buffer; }
[ "function", "encodeChunk", "(", "type", ",", "data", ")", "{", "var", "cursor", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "buffer", ".", "Buffer", ".", "byteLength", "(", "type", ")", "+", "4", "+", "data", ".", "length", ")", ")", ";", "cursor", ".", "write", "(", "type", ")", ";", "cursor", ".", "writeUInt32BE", "(", "data", ".", "length", ")", ";", "cursor", ".", "copy", "(", "data", ")", ";", "return", "cursor", ".", "buffer", ";", "}" ]
Encode a MIDI chunk @param {string} type Chunk type @param {Buffer} data Chunk data @return {Buffer} Encoded chunk
[ "Encode", "a", "MIDI", "chunk" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/chunk.js#L13-L23
train
jhermsmeier/node-tle
lib/tle.js
function( value ) { var lines = TLE.trim( value + '' ).split( /\r?\n/g ) var line, checksum // Line 0 if (lines.length === 3) { this.name = TLE.trim( lines.shift() ) } // Line 1 line = lines.shift() checksum = TLE.check( line ) if( checksum != line.substring( 68, 69 ) ) { throw new Error( 'Line 1 checksum mismatch: ' + checksum + ' != ' + line.substring( 68, 69 ) + ': ' + line ) } this.number = TLE.parseFloat( line.substring( 2, 7 ) ) this.class = TLE.trim( line.substring( 7, 9 ) ) this.id = TLE.trim( line.substring( 9, 18 ) ) this.date = TLE.parseDate( line.substring( 18, 33 ) ) this.fdmm = TLE.parseFloat( line.substring( 33, 44 ) ) this.sdmm = TLE.parseFloat( line.substring( 44, 53 ) ) this.drag = TLE.parseDrag( line.substring( 53, 62 ) ) this.ephemeris = TLE.parseFloat( line.substring( 62, 64 ) ) this.esn = TLE.parseFloat( line.substring( 64, 68 ) ) // Line 2 line = lines.shift() checksum = TLE.check( line ) if( checksum != line.substring( 68, 69 ) ) { throw new Error( 'Line 2 checksum mismatch: ' + checksum + ' != ' + line.substring( 68, 69 ) + ': ' + line ) } this.inclination = TLE.parseFloat( line.substring( 8, 17 ) ) this.ascension = TLE.parseFloat( line.substring( 17, 26 ) ) this.eccentricity = TLE.parseFloat( '0.' + line.substring( 26, 34 ) ) this.perigee = TLE.parseFloat( line.substring( 34, 43 ) ) this.anomaly = TLE.parseFloat( line.substring( 43, 52 ) ) this.motion = TLE.parseFloat( line.substring( 52, 64 ) ) this.revolution = TLE.parseFloat( line.substring( 64, 68 ) ) return this }
javascript
function( value ) { var lines = TLE.trim( value + '' ).split( /\r?\n/g ) var line, checksum // Line 0 if (lines.length === 3) { this.name = TLE.trim( lines.shift() ) } // Line 1 line = lines.shift() checksum = TLE.check( line ) if( checksum != line.substring( 68, 69 ) ) { throw new Error( 'Line 1 checksum mismatch: ' + checksum + ' != ' + line.substring( 68, 69 ) + ': ' + line ) } this.number = TLE.parseFloat( line.substring( 2, 7 ) ) this.class = TLE.trim( line.substring( 7, 9 ) ) this.id = TLE.trim( line.substring( 9, 18 ) ) this.date = TLE.parseDate( line.substring( 18, 33 ) ) this.fdmm = TLE.parseFloat( line.substring( 33, 44 ) ) this.sdmm = TLE.parseFloat( line.substring( 44, 53 ) ) this.drag = TLE.parseDrag( line.substring( 53, 62 ) ) this.ephemeris = TLE.parseFloat( line.substring( 62, 64 ) ) this.esn = TLE.parseFloat( line.substring( 64, 68 ) ) // Line 2 line = lines.shift() checksum = TLE.check( line ) if( checksum != line.substring( 68, 69 ) ) { throw new Error( 'Line 2 checksum mismatch: ' + checksum + ' != ' + line.substring( 68, 69 ) + ': ' + line ) } this.inclination = TLE.parseFloat( line.substring( 8, 17 ) ) this.ascension = TLE.parseFloat( line.substring( 17, 26 ) ) this.eccentricity = TLE.parseFloat( '0.' + line.substring( 26, 34 ) ) this.perigee = TLE.parseFloat( line.substring( 34, 43 ) ) this.anomaly = TLE.parseFloat( line.substring( 43, 52 ) ) this.motion = TLE.parseFloat( line.substring( 52, 64 ) ) this.revolution = TLE.parseFloat( line.substring( 64, 68 ) ) return this }
[ "function", "(", "value", ")", "{", "var", "lines", "=", "TLE", ".", "trim", "(", "value", "+", "''", ")", ".", "split", "(", "/", "\\r?\\n", "/", "g", ")", "var", "line", ",", "checksum", "if", "(", "lines", ".", "length", "===", "3", ")", "{", "this", ".", "name", "=", "TLE", ".", "trim", "(", "lines", ".", "shift", "(", ")", ")", "}", "line", "=", "lines", ".", "shift", "(", ")", "checksum", "=", "TLE", ".", "check", "(", "line", ")", "if", "(", "checksum", "!=", "line", ".", "substring", "(", "68", ",", "69", ")", ")", "{", "throw", "new", "Error", "(", "'Line 1 checksum mismatch: '", "+", "checksum", "+", "' != '", "+", "line", ".", "substring", "(", "68", ",", "69", ")", "+", "': '", "+", "line", ")", "}", "this", ".", "number", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "2", ",", "7", ")", ")", "this", ".", "class", "=", "TLE", ".", "trim", "(", "line", ".", "substring", "(", "7", ",", "9", ")", ")", "this", ".", "id", "=", "TLE", ".", "trim", "(", "line", ".", "substring", "(", "9", ",", "18", ")", ")", "this", ".", "date", "=", "TLE", ".", "parseDate", "(", "line", ".", "substring", "(", "18", ",", "33", ")", ")", "this", ".", "fdmm", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "33", ",", "44", ")", ")", "this", ".", "sdmm", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "44", ",", "53", ")", ")", "this", ".", "drag", "=", "TLE", ".", "parseDrag", "(", "line", ".", "substring", "(", "53", ",", "62", ")", ")", "this", ".", "ephemeris", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "62", ",", "64", ")", ")", "this", ".", "esn", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "64", ",", "68", ")", ")", "line", "=", "lines", ".", "shift", "(", ")", "checksum", "=", "TLE", ".", "check", "(", "line", ")", "if", "(", "checksum", "!=", "line", ".", "substring", "(", "68", ",", "69", ")", ")", "{", "throw", "new", "Error", "(", "'Line 2 checksum mismatch: '", "+", "checksum", "+", "' != '", "+", "line", ".", "substring", "(", "68", ",", "69", ")", "+", "': '", "+", "line", ")", "}", "this", ".", "inclination", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "8", ",", "17", ")", ")", "this", ".", "ascension", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "17", ",", "26", ")", ")", "this", ".", "eccentricity", "=", "TLE", ".", "parseFloat", "(", "'0.'", "+", "line", ".", "substring", "(", "26", ",", "34", ")", ")", "this", ".", "perigee", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "34", ",", "43", ")", ")", "this", ".", "anomaly", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "43", ",", "52", ")", ")", "this", ".", "motion", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "52", ",", "64", ")", ")", "this", ".", "revolution", "=", "TLE", ".", "parseFloat", "(", "line", ".", "substring", "(", "64", ",", "68", ")", ")", "return", "this", "}" ]
Parse a TLE's string representation @param {String} value @return {TLE}
[ "Parse", "a", "TLE", "s", "string", "representation" ]
0c0a57270cd6573b912f007a5b9da83f98eba775
https://github.com/jhermsmeier/node-tle/blob/0c0a57270cd6573b912f007a5b9da83f98eba775/lib/tle.js#L199-L251
train
JamesMessinger/json-schema-lib
lib/api/PluginHelper/callSyncPlugin.js
callSyncPlugin
function callSyncPlugin (pluginHelper, methodName, args) { var plugins = pluginHelper.filter(filterByMethod(methodName)); args.schema = pluginHelper[__internal].schema; args.config = args.schema.config; return callNextPlugin(plugins, methodName, args); }
javascript
function callSyncPlugin (pluginHelper, methodName, args) { var plugins = pluginHelper.filter(filterByMethod(methodName)); args.schema = pluginHelper[__internal].schema; args.config = args.schema.config; return callNextPlugin(plugins, methodName, args); }
[ "function", "callSyncPlugin", "(", "pluginHelper", ",", "methodName", ",", "args", ")", "{", "var", "plugins", "=", "pluginHelper", ".", "filter", "(", "filterByMethod", "(", "methodName", ")", ")", ";", "args", ".", "schema", "=", "pluginHelper", "[", "__internal", "]", ".", "schema", ";", "args", ".", "config", "=", "args", ".", "schema", ".", "config", ";", "return", "callNextPlugin", "(", "plugins", ",", "methodName", ",", "args", ")", ";", "}" ]
Calls a synchronous plugin method with the given arguments. @param {PluginHelper} pluginHelper - The {@link PluginHelper} whose plugins are called @param {string} methodName - The name of the plugin method to call @param {object} args - The arguments to pass to the method @returns {{ result: *, plugin: ?object }} If the method was handled by a plugin (i.e. the plugin didn't call next()), then the returned object will contain a reference to the plugin, and the result that was returned by the plugin.
[ "Calls", "a", "synchronous", "plugin", "method", "with", "the", "given", "arguments", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginHelper/callSyncPlugin.js#L20-L26
train
glennjones/elsewhere-profiles
lib/plugins.js
load
function load(dirPath) { findFiles(dirPath, function(filePath){ collection.push( require(filePath) ); }) function findFiles(dirPath, callback){ fs.readdir(dirPath, function(err, files) { files.forEach(function(file){ fs.stat(dirPath + '/' + file, function(err, stats) { if(stats.isFile()) { callback(dirPath + '/' + file); } if(stats.isDirectory()) { getDirectoryFiles(dirPath + '/' + file, callback); } }); }); }); } }
javascript
function load(dirPath) { findFiles(dirPath, function(filePath){ collection.push( require(filePath) ); }) function findFiles(dirPath, callback){ fs.readdir(dirPath, function(err, files) { files.forEach(function(file){ fs.stat(dirPath + '/' + file, function(err, stats) { if(stats.isFile()) { callback(dirPath + '/' + file); } if(stats.isDirectory()) { getDirectoryFiles(dirPath + '/' + file, callback); } }); }); }); } }
[ "function", "load", "(", "dirPath", ")", "{", "findFiles", "(", "dirPath", ",", "function", "(", "filePath", ")", "{", "collection", ".", "push", "(", "require", "(", "filePath", ")", ")", ";", "}", ")", "function", "findFiles", "(", "dirPath", ",", "callback", ")", "{", "fs", ".", "readdir", "(", "dirPath", ",", "function", "(", "err", ",", "files", ")", "{", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "fs", ".", "stat", "(", "dirPath", "+", "'/'", "+", "file", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "stats", ".", "isFile", "(", ")", ")", "{", "callback", "(", "dirPath", "+", "'/'", "+", "file", ")", ";", "}", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "getDirectoryFiles", "(", "dirPath", "+", "'/'", "+", "file", ",", "callback", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}" ]
load any file that is found in the plugins directory
[ "load", "any", "file", "that", "is", "found", "in", "the", "plugins", "directory" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/plugins.js#L7-L27
train
glennjones/elsewhere-profiles
lib/plugins.js
add
function add(interface){ var i = arr.collection, found = false; while (i--) { if(interface.name === collection[i].name){ found = true; } } if(!found){ collection.push( interface ) }; }
javascript
function add(interface){ var i = arr.collection, found = false; while (i--) { if(interface.name === collection[i].name){ found = true; } } if(!found){ collection.push( interface ) }; }
[ "function", "add", "(", "interface", ")", "{", "var", "i", "=", "arr", ".", "collection", ",", "found", "=", "false", ";", "while", "(", "i", "--", ")", "{", "if", "(", "interface", ".", "name", "===", "collection", "[", "i", "]", ".", "name", ")", "{", "found", "=", "true", ";", "}", "}", "if", "(", "!", "found", ")", "{", "collection", ".", "push", "(", "interface", ")", "}", ";", "}" ]
add an plugin directly
[ "add", "an", "plugin", "directly" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/plugins.js#L30-L39
train
matteodelabre/midijs
lib/file/parser/track.js
parseTrack
function parseTrack(cursor) { var chunk, events = [], result, runningStatus = null; chunk = parseChunk('MTrk', cursor); while (!chunk.eof()) { result = parseEvent(chunk, runningStatus); runningStatus = result.runningStatus; events.push(result.event); } return new Track(events); }
javascript
function parseTrack(cursor) { var chunk, events = [], result, runningStatus = null; chunk = parseChunk('MTrk', cursor); while (!chunk.eof()) { result = parseEvent(chunk, runningStatus); runningStatus = result.runningStatus; events.push(result.event); } return new Track(events); }
[ "function", "parseTrack", "(", "cursor", ")", "{", "var", "chunk", ",", "events", "=", "[", "]", ",", "result", ",", "runningStatus", "=", "null", ";", "chunk", "=", "parseChunk", "(", "'MTrk'", ",", "cursor", ")", ";", "while", "(", "!", "chunk", ".", "eof", "(", ")", ")", "{", "result", "=", "parseEvent", "(", "chunk", ",", "runningStatus", ")", ";", "runningStatus", "=", "result", ".", "runningStatus", ";", "events", ".", "push", "(", "result", ".", "event", ")", ";", "}", "return", "new", "Track", "(", "events", ")", ";", "}" ]
Parse a MIDI track chunk @param {module:buffercursor} cursor Buffer to parse @return {module:midijs/lib/file/track~Track} Parsed track
[ "Parse", "a", "MIDI", "track", "chunk" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/track.js#L13-L27
train
uladkasach/clientside-require
src/utilities/content_loading/commonjs.js
function(request, options){ if(typeof options == "undefined") options = {}; // define options if not yet defined options.relative_path_root = relative_path_root; // overwrite user defined rel path root - TODO - make this a private property return require_function(request, options); }
javascript
function(request, options){ if(typeof options == "undefined") options = {}; // define options if not yet defined options.relative_path_root = relative_path_root; // overwrite user defined rel path root - TODO - make this a private property return require_function(request, options); }
[ "function", "(", "request", ",", "options", ")", "{", "if", "(", "typeof", "options", "==", "\"undefined\"", ")", "options", "=", "{", "}", ";", "options", ".", "relative_path_root", "=", "relative_path_root", ";", "return", "require_function", "(", "request", ",", "options", ")", ";", "}" ]
build the require function to inject
[ "build", "the", "require", "function", "to", "inject" ]
7f20105fb3935fe7ae86a687632c632f4a5dc88b
https://github.com/uladkasach/clientside-require/blob/7f20105fb3935fe7ae86a687632c632f4a5dc88b/src/utilities/content_loading/commonjs.js#L126-L130
train
JamesMessinger/json-schema-lib
lib/plugins/ArrayDecoderPlugin.js
stripBOM
function stripBOM (str) { var bom = str.charCodeAt(0); // Check for the UTF-16 byte order mark (0xFEFF or 0xFFFE) if (bom === 0xFEFF || bom === 0xFFFE) { return str.slice(1); } return str; }
javascript
function stripBOM (str) { var bom = str.charCodeAt(0); // Check for the UTF-16 byte order mark (0xFEFF or 0xFFFE) if (bom === 0xFEFF || bom === 0xFFFE) { return str.slice(1); } return str; }
[ "function", "stripBOM", "(", "str", ")", "{", "var", "bom", "=", "str", ".", "charCodeAt", "(", "0", ")", ";", "if", "(", "bom", "===", "0xFEFF", "||", "bom", "===", "0xFFFE", ")", "{", "return", "str", ".", "slice", "(", "1", ")", ";", "}", "return", "str", ";", "}" ]
Removes the UTF-16 byte order mark, if any, from a string. @param {string} str @returns {string}
[ "Removes", "the", "UTF", "-", "16", "byte", "order", "mark", "if", "any", "from", "a", "string", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/ArrayDecoderPlugin.js#L57-L66
train
JamesMessinger/json-schema-lib
lib/plugins/JsonPlugin.js
parseFile
function parseFile (args) { var file = args.file; var next = args.next; try { // Optimistically try to parse the file as JSON. return JSON.parse(file.data); } catch (error) { if (isJsonFile(file)) { // This is a JSON file, but its contents are invalid throw error; } else { // This probably isn't a JSON file, so call the next parser plugin next(); } } }
javascript
function parseFile (args) { var file = args.file; var next = args.next; try { // Optimistically try to parse the file as JSON. return JSON.parse(file.data); } catch (error) { if (isJsonFile(file)) { // This is a JSON file, but its contents are invalid throw error; } else { // This probably isn't a JSON file, so call the next parser plugin next(); } } }
[ "function", "parseFile", "(", "args", ")", "{", "var", "file", "=", "args", ".", "file", ";", "var", "next", "=", "args", ".", "next", ";", "try", "{", "return", "JSON", ".", "parse", "(", "file", ".", "data", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "isJsonFile", "(", "file", ")", ")", "{", "throw", "error", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", "}" ]
Parses the given file's data, in place. @param {File} args.file - The {@link File} to parse. @param {function} args.next - Calls the next plugin, if the file data cannot be parsed @returns {*}
[ "Parses", "the", "given", "file", "s", "data", "in", "place", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/JsonPlugin.js#L30-L48
train
JamesMessinger/json-schema-lib
lib/plugins/JsonPlugin.js
isJsonFile
function isJsonFile (file) { return file.data && // The file has data (typeof file.data === 'string') && // and it's a string ( mimeTypePattern.test(file.mimeType) || // and it has a JSON MIME type extensionPattern.test(file.url) // or at least a .json file extension ); }
javascript
function isJsonFile (file) { return file.data && // The file has data (typeof file.data === 'string') && // and it's a string ( mimeTypePattern.test(file.mimeType) || // and it has a JSON MIME type extensionPattern.test(file.url) // or at least a .json file extension ); }
[ "function", "isJsonFile", "(", "file", ")", "{", "return", "file", ".", "data", "&&", "(", "typeof", "file", ".", "data", "===", "'string'", ")", "&&", "(", "mimeTypePattern", ".", "test", "(", "file", ".", "mimeType", ")", "||", "extensionPattern", ".", "test", "(", "file", ".", "url", ")", ")", ";", "}" ]
Determines whether the file data is JSON @param {File} file @returns {boolean}
[ "Determines", "whether", "the", "file", "data", "is", "JSON" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/JsonPlugin.js#L57-L64
train
claudio-silva/grunt-angular-builder
tasks/middleware/exportRequiredTemplates.js
ExportRequiredTemplatesMiddleware
function ExportRequiredTemplatesMiddleware (context) { var options = context.options.requiredTemplates; var path = require ('path'); /** * Paths of the required templates. * @type {string[]} */ var paths = []; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { scan (module.head, module.headPath); module.bodies.forEach (function (path, i) { scan (path, module.bodyPaths[i]); }); }; this.build = function (targetScript) { /* jshint unused: vars */ // Export file paths. context.grunt.config (options.exportToConfigProperty, paths); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Extracts file paths from embedded comment references to templates and appends them to `paths`. * @param {string} sourceCode * @param {string} filePath */ function scan (sourceCode, filePath) { /* jshint -W083 */ var match; while ((match = MATCH_DIRECTIVE.exec (sourceCode))) { match[1].split (',').forEach (function (s) { var url = s.match (/(["'])(.*?)\1/)[2]; paths.push (path.normalize (path.dirname (filePath) + '/' + url)); }); } } }
javascript
function ExportRequiredTemplatesMiddleware (context) { var options = context.options.requiredTemplates; var path = require ('path'); /** * Paths of the required templates. * @type {string[]} */ var paths = []; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { scan (module.head, module.headPath); module.bodies.forEach (function (path, i) { scan (path, module.bodyPaths[i]); }); }; this.build = function (targetScript) { /* jshint unused: vars */ // Export file paths. context.grunt.config (options.exportToConfigProperty, paths); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Extracts file paths from embedded comment references to templates and appends them to `paths`. * @param {string} sourceCode * @param {string} filePath */ function scan (sourceCode, filePath) { /* jshint -W083 */ var match; while ((match = MATCH_DIRECTIVE.exec (sourceCode))) { match[1].split (',').forEach (function (s) { var url = s.match (/(["'])(.*?)\1/)[2]; paths.push (path.normalize (path.dirname (filePath) + '/' + url)); }); } } }
[ "function", "ExportRequiredTemplatesMiddleware", "(", "context", ")", "{", "var", "options", "=", "context", ".", "options", ".", "requiredTemplates", ";", "var", "path", "=", "require", "(", "'path'", ")", ";", "var", "paths", "=", "[", "]", ";", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "scan", "(", "module", ".", "head", ",", "module", ".", "headPath", ")", ";", "module", ".", "bodies", ".", "forEach", "(", "function", "(", "path", ",", "i", ")", "{", "scan", "(", "path", ",", "module", ".", "bodyPaths", "[", "i", "]", ")", ";", "}", ")", ";", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "context", ".", "grunt", ".", "config", "(", "options", ".", "exportToConfigProperty", ",", "paths", ")", ";", "}", ";", "function", "scan", "(", "sourceCode", ",", "filePath", ")", "{", "var", "match", ";", "while", "(", "(", "match", "=", "MATCH_DIRECTIVE", ".", "exec", "(", "sourceCode", ")", ")", ")", "{", "match", "[", "1", "]", ".", "split", "(", "','", ")", ".", "forEach", "(", "function", "(", "s", ")", "{", "var", "url", "=", "s", ".", "match", "(", "/", "([\"'])(.*?)\\1", "/", ")", "[", "2", "]", ";", "paths", ".", "push", "(", "path", ".", "normalize", "(", "path", ".", "dirname", "(", "filePath", ")", "+", "'/'", "+", "url", ")", ")", ";", "}", ")", ";", "}", "}", "}" ]
Exports to Grunt's global configuration the paths of all templates required by the application, in the order defined by the modules' dependency graph. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Exports", "to", "Grunt", "s", "global", "configuration", "the", "paths", "of", "all", "templates", "required", "by", "the", "application", "in", "the", "order", "defined", "by", "the", "modules", "dependency", "graph", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/exportRequiredTemplates.js#L59-L119
train
JamesMessinger/json-schema-lib
lib/api/FileArray.js
findFile
function findFile (schema, url) { if (schema.files.length === 0) { return null; } if (url instanceof File) { // Short-circuit behavior for File obejcts return findByURL(schema.files, url.url); } // Try to find an exact URL match var file = findByURL(schema.files, url); if (!file) { // Resolve the URL and see if we can find a match var absoluteURL = schema.plugins.resolveURL({ from: schema.rootURL, to: url }); file = findByURL(schema.files, absoluteURL); } return file; }
javascript
function findFile (schema, url) { if (schema.files.length === 0) { return null; } if (url instanceof File) { // Short-circuit behavior for File obejcts return findByURL(schema.files, url.url); } // Try to find an exact URL match var file = findByURL(schema.files, url); if (!file) { // Resolve the URL and see if we can find a match var absoluteURL = schema.plugins.resolveURL({ from: schema.rootURL, to: url }); file = findByURL(schema.files, absoluteURL); } return file; }
[ "function", "findFile", "(", "schema", ",", "url", ")", "{", "if", "(", "schema", ".", "files", ".", "length", "===", "0", ")", "{", "return", "null", ";", "}", "if", "(", "url", "instanceof", "File", ")", "{", "return", "findByURL", "(", "schema", ".", "files", ",", "url", ".", "url", ")", ";", "}", "var", "file", "=", "findByURL", "(", "schema", ".", "files", ",", "url", ")", ";", "if", "(", "!", "file", ")", "{", "var", "absoluteURL", "=", "schema", ".", "plugins", ".", "resolveURL", "(", "{", "from", ":", "schema", ".", "rootURL", ",", "to", ":", "url", "}", ")", ";", "file", "=", "findByURL", "(", "schema", ".", "files", ",", "absoluteURL", ")", ";", "}", "return", "file", ";", "}" ]
Finds the given file in the schema @param {Schema} schema @param {string|File} url An absolute URL, or a relative URL (relative to the schema's root file), or a {@link File} object @returns {?File}
[ "Finds", "the", "given", "file", "in", "the", "schema" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/FileArray.js#L82-L102
train
JamesMessinger/json-schema-lib
lib/api/FileArray.js
findByURL
function findByURL (files, url) { for (var i = 0; i < files.length; i++) { var file = files[i]; if (file.url === url) { return file; } } }
javascript
function findByURL (files, url) { for (var i = 0; i < files.length; i++) { var file = files[i]; if (file.url === url) { return file; } } }
[ "function", "findByURL", "(", "files", ",", "url", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "var", "file", "=", "files", "[", "i", "]", ";", "if", "(", "file", ".", "url", "===", "url", ")", "{", "return", "file", ";", "}", "}", "}" ]
Finds a file by its exact URL @param {FileArray} files @param {string} url @returns {?File}
[ "Finds", "a", "file", "by", "its", "exact", "URL" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/FileArray.js#L111-L118
train
genie-js/genie-drs
src/DRS.js
function (num) { for (var ext = '', i = 0; i < 4; i++) { ext = String.fromCharCode(num & 0xFF) + ext num >>= 8 } return ext }
javascript
function (num) { for (var ext = '', i = 0; i < 4; i++) { ext = String.fromCharCode(num & 0xFF) + ext num >>= 8 } return ext }
[ "function", "(", "num", ")", "{", "for", "(", "var", "ext", "=", "''", ",", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "ext", "=", "String", ".", "fromCharCode", "(", "num", "&", "0xFF", ")", "+", "ext", "num", ">>=", "8", "}", "return", "ext", "}" ]
Parse a numeric table type to a string.
[ "Parse", "a", "numeric", "table", "type", "to", "a", "string", "." ]
45535b6836c62d269cc6f30889fe6f43113f8dcf
https://github.com/genie-js/genie-drs/blob/45535b6836c62d269cc6f30889fe6f43113f8dcf/src/DRS.js#L33-L39
train
genie-js/genie-drs
src/DRS.js
function (str) { while (str.length < 4) str += ' ' for (var num = 0, i = 0; i < 4; i++) { num = (num << 8) + str.charCodeAt(i) } return num }
javascript
function (str) { while (str.length < 4) str += ' ' for (var num = 0, i = 0; i < 4; i++) { num = (num << 8) + str.charCodeAt(i) } return num }
[ "function", "(", "str", ")", "{", "while", "(", "str", ".", "length", "<", "4", ")", "str", "+=", "' '", "for", "(", "var", "num", "=", "0", ",", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "num", "=", "(", "num", "<<", "8", ")", "+", "str", ".", "charCodeAt", "(", "i", ")", "}", "return", "num", "}" ]
Serialize a table type string to a 32-bit integer.
[ "Serialize", "a", "table", "type", "string", "to", "a", "32", "-", "bit", "integer", "." ]
45535b6836c62d269cc6f30889fe6f43113f8dcf
https://github.com/genie-js/genie-drs/blob/45535b6836c62d269cc6f30889fe6f43113f8dcf/src/DRS.js#L42-L48
train
genie-js/genie-drs
src/DRS.js
DRS
function DRS (file) { if (!(this instanceof DRS)) return new DRS(file) this.tables = [] this.isSWGB = null if (typeof file === 'undefined') { file = {} } if (typeof file === 'string') { if (typeof FsSource !== 'function') { throw new Error('Cannot instantiate with a string filename in the browser') } this.source = new FsSource(file) } else if (typeof Blob !== 'undefined' && file instanceof Blob) { // eslint-disable-line no-undef this.source = new BlobSource(file) } else { if (typeof file !== 'object') { throw new TypeError('Expected a file path string or an options object, got ' + typeof file) } this.isSWGB = file.hasOwnProperty('isSWGB') ? file.isSWGB : false this.copyright = file.hasOwnProperty('copyright') ? file.copyright : (this.isSWGB ? COPYRIGHT_SWGB : COPYRIGHT_AOE) this.fileVersion = file.hasOwnProperty('fileVersion') ? file.fileVersion : '1.00' this.fileType = file.hasOwnProperty('fileType') ? file.fileType : 'tribe\0\0\0\0\0\0\0' } }
javascript
function DRS (file) { if (!(this instanceof DRS)) return new DRS(file) this.tables = [] this.isSWGB = null if (typeof file === 'undefined') { file = {} } if (typeof file === 'string') { if (typeof FsSource !== 'function') { throw new Error('Cannot instantiate with a string filename in the browser') } this.source = new FsSource(file) } else if (typeof Blob !== 'undefined' && file instanceof Blob) { // eslint-disable-line no-undef this.source = new BlobSource(file) } else { if (typeof file !== 'object') { throw new TypeError('Expected a file path string or an options object, got ' + typeof file) } this.isSWGB = file.hasOwnProperty('isSWGB') ? file.isSWGB : false this.copyright = file.hasOwnProperty('copyright') ? file.copyright : (this.isSWGB ? COPYRIGHT_SWGB : COPYRIGHT_AOE) this.fileVersion = file.hasOwnProperty('fileVersion') ? file.fileVersion : '1.00' this.fileType = file.hasOwnProperty('fileType') ? file.fileType : 'tribe\0\0\0\0\0\0\0' } }
[ "function", "DRS", "(", "file", ")", "{", "if", "(", "!", "(", "this", "instanceof", "DRS", ")", ")", "return", "new", "DRS", "(", "file", ")", "this", ".", "tables", "=", "[", "]", "this", ".", "isSWGB", "=", "null", "if", "(", "typeof", "file", "===", "'undefined'", ")", "{", "file", "=", "{", "}", "}", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "if", "(", "typeof", "FsSource", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Cannot instantiate with a string filename in the browser'", ")", "}", "this", ".", "source", "=", "new", "FsSource", "(", "file", ")", "}", "else", "if", "(", "typeof", "Blob", "!==", "'undefined'", "&&", "file", "instanceof", "Blob", ")", "{", "this", ".", "source", "=", "new", "BlobSource", "(", "file", ")", "}", "else", "{", "if", "(", "typeof", "file", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'Expected a file path string or an options object, got '", "+", "typeof", "file", ")", "}", "this", ".", "isSWGB", "=", "file", ".", "hasOwnProperty", "(", "'isSWGB'", ")", "?", "file", ".", "isSWGB", ":", "false", "this", ".", "copyright", "=", "file", ".", "hasOwnProperty", "(", "'copyright'", ")", "?", "file", ".", "copyright", ":", "(", "this", ".", "isSWGB", "?", "COPYRIGHT_SWGB", ":", "COPYRIGHT_AOE", ")", "this", ".", "fileVersion", "=", "file", ".", "hasOwnProperty", "(", "'fileVersion'", ")", "?", "file", ".", "fileVersion", ":", "'1.00'", "this", ".", "fileType", "=", "file", ".", "hasOwnProperty", "(", "'fileType'", ")", "?", "file", ".", "fileType", ":", "'tribe\\0\\0\\0\\0\\0\\0\\0'", "}", "}" ]
Represents a DRS file. @constructor @param {string} file Path to a .DRS file.
[ "Represents", "a", "DRS", "file", "." ]
45535b6836c62d269cc6f30889fe6f43113f8dcf
https://github.com/genie-js/genie-drs/blob/45535b6836c62d269cc6f30889fe6f43113f8dcf/src/DRS.js#L71-L98
train
claudio-silva/grunt-angular-builder
tasks/middleware/exportSourcePaths.js
ExportSourceCodePathsMiddleware
function ExportSourceCodePathsMiddleware (context) { var options = context.options.sourcePaths; /** * Paths of all the required files (excluding standalone scripts) in the correct loading order. * @type {string[]} */ var tracedPaths = []; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { tracedPaths.push (module.headPath); arrayAppend (tracedPaths, module.bodyPaths); }; this.build = function (targetScript) { /* jshint unused: vars */ var scripts = []; // Include paths of forced-include scripts. if (context.standaloneScripts.length) arrayAppend (scripts, context.standaloneScripts.map (function (e) { return e.path; })); // Include all module files. arrayAppend (scripts, tracedPaths); // Export. context.grunt.config (options.exportToConfigProperty, scripts); }; }
javascript
function ExportSourceCodePathsMiddleware (context) { var options = context.options.sourcePaths; /** * Paths of all the required files (excluding standalone scripts) in the correct loading order. * @type {string[]} */ var tracedPaths = []; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { tracedPaths.push (module.headPath); arrayAppend (tracedPaths, module.bodyPaths); }; this.build = function (targetScript) { /* jshint unused: vars */ var scripts = []; // Include paths of forced-include scripts. if (context.standaloneScripts.length) arrayAppend (scripts, context.standaloneScripts.map (function (e) { return e.path; })); // Include all module files. arrayAppend (scripts, tracedPaths); // Export. context.grunt.config (options.exportToConfigProperty, scripts); }; }
[ "function", "ExportSourceCodePathsMiddleware", "(", "context", ")", "{", "var", "options", "=", "context", ".", "options", ".", "sourcePaths", ";", "var", "tracedPaths", "=", "[", "]", ";", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "tracedPaths", ".", "push", "(", "module", ".", "headPath", ")", ";", "arrayAppend", "(", "tracedPaths", ",", "module", ".", "bodyPaths", ")", ";", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "var", "scripts", "=", "[", "]", ";", "if", "(", "context", ".", "standaloneScripts", ".", "length", ")", "arrayAppend", "(", "scripts", ",", "context", ".", "standaloneScripts", ".", "map", "(", "function", "(", "e", ")", "{", "return", "e", ".", "path", ";", "}", ")", ")", ";", "arrayAppend", "(", "scripts", ",", "tracedPaths", ")", ";", "context", ".", "grunt", ".", "config", "(", "options", ".", "exportToConfigProperty", ",", "scripts", ")", ";", "}", ";", "}" ]
Exports to Grunt's global configuration the paths of all script files that are required by the application, in the order defined by the modules' dependency graph. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Exports", "to", "Grunt", "s", "global", "configuration", "the", "paths", "of", "all", "script", "files", "that", "are", "required", "by", "the", "application", "in", "the", "order", "defined", "by", "the", "modules", "dependency", "graph", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/exportSourcePaths.js#L61-L108
train
matteodelabre/midijs
lib/connect/driver.js
Driver
function Driver(native) { var outputs = [], inputs = [], length, i; EventEmitter.call(this); this.native = native; length = native.outputs.size; for (i = 0; i < length; i += 1) { outputs[i] = new Output(native.outputs.get(i)); } length = native.inputs.size; for (i = 0; i < length; i += 1) { inputs[i] = new Input(native.inputs.get(i)); } this.outputs = outputs; this.output = null; this.inputs = inputs; this.input = null; native.onconnect = function (event) { var port = event.port; if (port.type === 'input') { port = new Input(port); this.inputs.push(port); } else { port = new Output(port); this.outputs.push(port); } this.emit('connect', port); }.bind(this); native.ondisconnect = function (event) { var port = event.port; if (port.type === 'input') { port = new Input(port); this.inputs = this.inputs.filter(function (input) { return (input.id !== port.id); }); } else { port = new Output(port); this.outputs = this.outputs.filter(function (output) { return (output.id !== port.id); }); } this.emit('disconnect', port); }.bind(this); }
javascript
function Driver(native) { var outputs = [], inputs = [], length, i; EventEmitter.call(this); this.native = native; length = native.outputs.size; for (i = 0; i < length; i += 1) { outputs[i] = new Output(native.outputs.get(i)); } length = native.inputs.size; for (i = 0; i < length; i += 1) { inputs[i] = new Input(native.inputs.get(i)); } this.outputs = outputs; this.output = null; this.inputs = inputs; this.input = null; native.onconnect = function (event) { var port = event.port; if (port.type === 'input') { port = new Input(port); this.inputs.push(port); } else { port = new Output(port); this.outputs.push(port); } this.emit('connect', port); }.bind(this); native.ondisconnect = function (event) { var port = event.port; if (port.type === 'input') { port = new Input(port); this.inputs = this.inputs.filter(function (input) { return (input.id !== port.id); }); } else { port = new Output(port); this.outputs = this.outputs.filter(function (output) { return (output.id !== port.id); }); } this.emit('disconnect', port); }.bind(this); }
[ "function", "Driver", "(", "native", ")", "{", "var", "outputs", "=", "[", "]", ",", "inputs", "=", "[", "]", ",", "length", ",", "i", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "native", "=", "native", ";", "length", "=", "native", ".", "outputs", ".", "size", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "outputs", "[", "i", "]", "=", "new", "Output", "(", "native", ".", "outputs", ".", "get", "(", "i", ")", ")", ";", "}", "length", "=", "native", ".", "inputs", ".", "size", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "inputs", "[", "i", "]", "=", "new", "Input", "(", "native", ".", "inputs", ".", "get", "(", "i", ")", ")", ";", "}", "this", ".", "outputs", "=", "outputs", ";", "this", ".", "output", "=", "null", ";", "this", ".", "inputs", "=", "inputs", ";", "this", ".", "input", "=", "null", ";", "native", ".", "onconnect", "=", "function", "(", "event", ")", "{", "var", "port", "=", "event", ".", "port", ";", "if", "(", "port", ".", "type", "===", "'input'", ")", "{", "port", "=", "new", "Input", "(", "port", ")", ";", "this", ".", "inputs", ".", "push", "(", "port", ")", ";", "}", "else", "{", "port", "=", "new", "Output", "(", "port", ")", ";", "this", ".", "outputs", ".", "push", "(", "port", ")", ";", "}", "this", ".", "emit", "(", "'connect'", ",", "port", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "native", ".", "ondisconnect", "=", "function", "(", "event", ")", "{", "var", "port", "=", "event", ".", "port", ";", "if", "(", "port", ".", "type", "===", "'input'", ")", "{", "port", "=", "new", "Input", "(", "port", ")", ";", "this", ".", "inputs", "=", "this", ".", "inputs", ".", "filter", "(", "function", "(", "input", ")", "{", "return", "(", "input", ".", "id", "!==", "port", ".", "id", ")", ";", "}", ")", ";", "}", "else", "{", "port", "=", "new", "Output", "(", "port", ")", ";", "this", ".", "outputs", "=", "this", ".", "outputs", ".", "filter", "(", "function", "(", "output", ")", "{", "return", "(", "output", ".", "id", "!==", "port", ".", "id", ")", ";", "}", ")", ";", "}", "this", ".", "emit", "(", "'disconnect'", ",", "port", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
Construct a new Driver @class Driver @extends events.EventEmitter @classdesc Enable you to access all the plugged-in MIDI devices and to control them @param {MIDIAccess} native Native MIDI access
[ "Construct", "a", "new", "Driver" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/connect/driver.js#L19-L73
train
claudio-silva/grunt-angular-builder
tasks/lib/types.js
Context
function Context (grunt, task, defaultOptions) { this.grunt = grunt; this.options = extend ({}, defaultOptions, task.options ()); switch (this.options.buildMode) { case 'release': this.options.debugBuild.enabled = false; this.options.releaseBuild.enabled = true; break; case 'debug': this.options.debugBuild.enabled = true; this.options.releaseBuild.enabled = false; } if (task.flags.debug !== undefined || grunt.option ('build') === 'debug') { this.options.debugBuild.enabled = true; this.options.releaseBuild.enabled = false; } this.verbose = grunt.option ('verbose'); // Clone the external modules and use it as a starting point. this.modules = extend ({}, this._setupExternalModules ()); // Reset tracer. this.loaded = {}; this.outputtedFiles = {}; this.filesRefCount = {}; // Reset the scripts list to a clone of the `require` option or to an empty list. this.standaloneScripts = (this.options.require || []).slice (); this.shared = {}; this._events = {}; }
javascript
function Context (grunt, task, defaultOptions) { this.grunt = grunt; this.options = extend ({}, defaultOptions, task.options ()); switch (this.options.buildMode) { case 'release': this.options.debugBuild.enabled = false; this.options.releaseBuild.enabled = true; break; case 'debug': this.options.debugBuild.enabled = true; this.options.releaseBuild.enabled = false; } if (task.flags.debug !== undefined || grunt.option ('build') === 'debug') { this.options.debugBuild.enabled = true; this.options.releaseBuild.enabled = false; } this.verbose = grunt.option ('verbose'); // Clone the external modules and use it as a starting point. this.modules = extend ({}, this._setupExternalModules ()); // Reset tracer. this.loaded = {}; this.outputtedFiles = {}; this.filesRefCount = {}; // Reset the scripts list to a clone of the `require` option or to an empty list. this.standaloneScripts = (this.options.require || []).slice (); this.shared = {}; this._events = {}; }
[ "function", "Context", "(", "grunt", ",", "task", ",", "defaultOptions", ")", "{", "this", ".", "grunt", "=", "grunt", ";", "this", ".", "options", "=", "extend", "(", "{", "}", ",", "defaultOptions", ",", "task", ".", "options", "(", ")", ")", ";", "switch", "(", "this", ".", "options", ".", "buildMode", ")", "{", "case", "'release'", ":", "this", ".", "options", ".", "debugBuild", ".", "enabled", "=", "false", ";", "this", ".", "options", ".", "releaseBuild", ".", "enabled", "=", "true", ";", "break", ";", "case", "'debug'", ":", "this", ".", "options", ".", "debugBuild", ".", "enabled", "=", "true", ";", "this", ".", "options", ".", "releaseBuild", ".", "enabled", "=", "false", ";", "}", "if", "(", "task", ".", "flags", ".", "debug", "!==", "undefined", "||", "grunt", ".", "option", "(", "'build'", ")", "===", "'debug'", ")", "{", "this", ".", "options", ".", "debugBuild", ".", "enabled", "=", "true", ";", "this", ".", "options", ".", "releaseBuild", ".", "enabled", "=", "false", ";", "}", "this", ".", "verbose", "=", "grunt", ".", "option", "(", "'verbose'", ")", ";", "this", ".", "modules", "=", "extend", "(", "{", "}", ",", "this", ".", "_setupExternalModules", "(", ")", ")", ";", "this", ".", "loaded", "=", "{", "}", ";", "this", ".", "outputtedFiles", "=", "{", "}", ";", "this", ".", "filesRefCount", "=", "{", "}", ";", "this", ".", "standaloneScripts", "=", "(", "this", ".", "options", ".", "require", "||", "[", "]", ")", ".", "slice", "(", ")", ";", "this", ".", "shared", "=", "{", "}", ";", "this", ".", "_events", "=", "{", "}", ";", "}" ]
The execution context for the middleware stack. Contains shared information available throughout the middleware stack. @constructor @param grunt The Grunt API. @param task The currently executing Grunt task. @param {TaskOptions} defaultOptions The default values for all of the Angular Builder's options, including all middleware options.
[ "The", "execution", "context", "for", "the", "middleware", "stack", ".", "Contains", "shared", "information", "available", "throughout", "the", "middleware", "stack", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/lib/types.js#L230-L258
train
claudio-silva/grunt-angular-builder
tasks/lib/types.js
function (eventName, handler) { if (!this._events[eventName]) this._events[eventName] = []; this._events[eventName].push (handler); }
javascript
function (eventName, handler) { if (!this._events[eventName]) this._events[eventName] = []; this._events[eventName].push (handler); }
[ "function", "(", "eventName", ",", "handler", ")", "{", "if", "(", "!", "this", ".", "_events", "[", "eventName", "]", ")", "this", ".", "_events", "[", "eventName", "]", "=", "[", "]", ";", "this", ".", "_events", "[", "eventName", "]", ".", "push", "(", "handler", ")", ";", "}" ]
Registers an event handler. @param {ContextEvent} eventName @param {function()} handler
[ "Registers", "an", "event", "handler", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/lib/types.js#L328-L333
train
claudio-silva/grunt-angular-builder
tasks/lib/types.js
function (eventName, args) { var e = this._events[eventName]; if (e) { args = args || []; e.forEach (function (handler) { handler.apply (this, args); }); } }
javascript
function (eventName, args) { var e = this._events[eventName]; if (e) { args = args || []; e.forEach (function (handler) { handler.apply (this, args); }); } }
[ "function", "(", "eventName", ",", "args", ")", "{", "var", "e", "=", "this", ".", "_events", "[", "eventName", "]", ";", "if", "(", "e", ")", "{", "args", "=", "args", "||", "[", "]", ";", "e", ".", "forEach", "(", "function", "(", "handler", ")", "{", "handler", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ")", ";", "}", "}" ]
Calls all registered event handlers for the specified event. @param {ContextEvent} eventName @param {Array?} args
[ "Calls", "all", "registered", "event", "handlers", "for", "the", "specified", "event", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/lib/types.js#L339-L349
train
claudio-silva/grunt-angular-builder
tasks/lib/types.js
function () { /** @type {Object.<string, ModuleDef>} */ var modules = {}; ((typeof this.options.externalModules === 'string' ? [this.options.externalModules] : this.options.externalModules ) || []). concat (this.options.builtinModules). forEach (function (moduleName) { // Ignore redundant names. if (!modules[moduleName]) { /** @type {ModuleDef} */ var module = modules[moduleName] = new ModuleDef (moduleName); module.external = true; } }); return modules; }
javascript
function () { /** @type {Object.<string, ModuleDef>} */ var modules = {}; ((typeof this.options.externalModules === 'string' ? [this.options.externalModules] : this.options.externalModules ) || []). concat (this.options.builtinModules). forEach (function (moduleName) { // Ignore redundant names. if (!modules[moduleName]) { /** @type {ModuleDef} */ var module = modules[moduleName] = new ModuleDef (moduleName); module.external = true; } }); return modules; }
[ "function", "(", ")", "{", "var", "modules", "=", "{", "}", ";", "(", "(", "typeof", "this", ".", "options", ".", "externalModules", "===", "'string'", "?", "[", "this", ".", "options", ".", "externalModules", "]", ":", "this", ".", "options", ".", "externalModules", ")", "||", "[", "]", ")", ".", "concat", "(", "this", ".", "options", ".", "builtinModules", ")", ".", "forEach", "(", "function", "(", "moduleName", ")", "{", "if", "(", "!", "modules", "[", "moduleName", "]", ")", "{", "var", "module", "=", "modules", "[", "moduleName", "]", "=", "new", "ModuleDef", "(", "moduleName", ")", ";", "module", ".", "external", "=", "true", ";", "}", "}", ")", ";", "return", "modules", ";", "}" ]
Registers the configured external modules so that they can be ignored during the build output generation. @returns {Object.<string, ModuleDef>} @private
[ "Registers", "the", "configured", "external", "modules", "so", "that", "they", "can", "be", "ignored", "during", "the", "build", "output", "generation", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/lib/types.js#L355-L373
train