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
amsb/react-evoke
examples/nutshell/src/index.js
toggleColor
async function toggleColor(store) { await store.update(state => { if (state.color === "blue") { state.color = "green" } else { state.color = "blue" } }) }
javascript
async function toggleColor(store) { await store.update(state => { if (state.color === "blue") { state.color = "green" } else { state.color = "blue" } }) }
[ "async", "function", "toggleColor", "(", "store", ")", "{", "await", "store", ".", "update", "(", "state", "=>", "{", "if", "(", "state", ".", "color", "===", "\"blue\"", ")", "{", "state", ".", "color", "=", "\"green\"", "}", "else", "{", "state", ".", "color", "=", "\"blue\"", "}", "}", ")", "}" ]
define action to toggle color
[ "define", "action", "to", "toggle", "color" ]
8c87b038b5c9ad214bb646b052b9b6a5bd31970f
https://github.com/amsb/react-evoke/blob/8c87b038b5c9ad214bb646b052b9b6a5bd31970f/examples/nutshell/src/index.js#L55-L63
train
amsb/react-evoke
examples/nutshell/src/index.js
ErrorMessage
function ErrorMessage({ state, error, clearError }) { return ( <> <h1 style={{ color: "red" }}>{error.message}</h1> <button onClick={() => clearError()}>Try Again</button> <pre>{JSON.stringify(state, null, 2)}</pre> </> ) }
javascript
function ErrorMessage({ state, error, clearError }) { return ( <> <h1 style={{ color: "red" }}>{error.message}</h1> <button onClick={() => clearError()}>Try Again</button> <pre>{JSON.stringify(state, null, 2)}</pre> </> ) }
[ "function", "ErrorMessage", "(", "{", "state", ",", "error", ",", "clearError", "}", ")", "{", "return", "(", "<", ">", " ", "<", "h1", "style", "=", "{", "{", "color", ":", "\"red\"", "}", "}", ">", "{", "error", ".", "message", "}", "<", "/", "h1", ">", " ", "<", "button", "onClick", "=", "{", "(", ")", "=>", "clearError", "(", ")", "}", ">", "Try Again", "<", "/", "button", ">", " ", "<", "pre", ">", "{", "JSON", ".", "stringify", "(", "state", ",", "null", ",", "2", ")", "}", "<", "/", "pre", ">", " ", "<", "/", ">", ")", "}" ]
a component for displaying an error message
[ "a", "component", "for", "displaying", "an", "error", "message" ]
8c87b038b5c9ad214bb646b052b9b6a5bd31970f
https://github.com/amsb/react-evoke/blob/8c87b038b5c9ad214bb646b052b9b6a5bd31970f/examples/nutshell/src/index.js#L88-L96
train
amsb/react-evoke
examples/nutshell/src/index.js
CurrentQuote
function CurrentQuote() { const [quoteId] = useStore("quoteId") const [quoteLength] = useStore("quoteLengths", quoteId) return ( <> <p>The following quote is {quoteLength} characters long:</p> <QuoteView quoteId={quoteId} /> </> ) }
javascript
function CurrentQuote() { const [quoteId] = useStore("quoteId") const [quoteLength] = useStore("quoteLengths", quoteId) return ( <> <p>The following quote is {quoteLength} characters long:</p> <QuoteView quoteId={quoteId} /> </> ) }
[ "function", "CurrentQuote", "(", ")", "{", "const", "[", "quoteId", "]", "=", "useStore", "(", "\"quoteId\"", ")", "const", "[", "quoteLength", "]", "=", "useStore", "(", "\"quoteLengths\"", ",", "quoteId", ")", "return", "(", "<", ">", " ", "<", "p", ">", "The following quote is ", "{", "quoteLength", "}", " characters long:", "<", "/", "p", ">", " ", "<", "QuoteView", "quoteId", "=", "{", "quoteId", "}", "/", ">", " ", "<", "/", ">", ")", "}" ]
read current quoteId from Store and render
[ "read", "current", "quoteId", "from", "Store", "and", "render" ]
8c87b038b5c9ad214bb646b052b9b6a5bd31970f
https://github.com/amsb/react-evoke/blob/8c87b038b5c9ad214bb646b052b9b6a5bd31970f/examples/nutshell/src/index.js#L99-L109
train
bebeanan/monkey-ui
lib/upload/index.js
fileToObject
function fileToObject(file) { return { lastModified: file.lastModified, lastModifiedDate: file.lastModifiedDate, name: file.filename || file.name, size: file.size, type: file.type, uid: file.uid, response: file.response, error: file.error, percent: 0, originFileObj: file }; }
javascript
function fileToObject(file) { return { lastModified: file.lastModified, lastModifiedDate: file.lastModifiedDate, name: file.filename || file.name, size: file.size, type: file.type, uid: file.uid, response: file.response, error: file.error, percent: 0, originFileObj: file }; }
[ "function", "fileToObject", "(", "file", ")", "{", "return", "{", "lastModified", ":", "file", ".", "lastModified", ",", "lastModifiedDate", ":", "file", ".", "lastModifiedDate", ",", "name", ":", "file", ".", "filename", "||", "file", ".", "name", ",", "size", ":", "file", ".", "size", ",", "type", ":", "file", ".", "type", ",", "uid", ":", "file", ".", "uid", ",", "response", ":", "file", ".", "response", ",", "error", ":", "file", ".", "error", ",", "percent", ":", "0", ",", "originFileObj", ":", "file", "}", ";", "}" ]
Fix IE file.status problem via coping a new Object
[ "Fix", "IE", "file", ".", "status", "problem", "via", "coping", "a", "new", "Object" ]
bc3e192c8b5e1f17a8d6b670f136d0b2f8a446f8
https://github.com/bebeanan/monkey-ui/blob/bc3e192c8b5e1f17a8d6b670f136d0b2f8a446f8/lib/upload/index.js#L51-L64
train
reboundjs/rebound
packages/rebound-router/lib/rebound-router.js
function(route) { // Save the previous route value this._previousRoute = this._currentRoute; // Fetch Resources document.body.classList.add("loading"); return this._fetchResource(route, this.config.container).then(function(res){ document.body.classList.remove('loading'); return res; }); }
javascript
function(route) { // Save the previous route value this._previousRoute = this._currentRoute; // Fetch Resources document.body.classList.add("loading"); return this._fetchResource(route, this.config.container).then(function(res){ document.body.classList.remove('loading'); return res; }); }
[ "function", "(", "route", ")", "{", "this", ".", "_previousRoute", "=", "this", ".", "_currentRoute", ";", "document", ".", "body", ".", "classList", ".", "add", "(", "\"loading\"", ")", ";", "return", "this", ".", "_fetchResource", "(", "route", ",", "this", ".", "config", ".", "container", ")", ".", "then", "(", "function", "(", "res", ")", "{", "document", ".", "body", ".", "classList", ".", "remove", "(", "'loading'", ")", ";", "return", "res", ";", "}", ")", ";", "}" ]
Called when no matching routes are found. Extracts root route and fetches it's resources
[ "Called", "when", "no", "matching", "routes", "are", "found", ".", "Extracts", "root", "route", "and", "fetches", "it", "s", "resources" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-router/lib/rebound-router.js#L76-L87
train
reboundjs/rebound
packages/rebound-router/lib/rebound-router.js
function(fragment, options={}) { // Default trigger to true unless otherwise specified (options.trigger === undefined) && (options.trigger = true); // Stringify any data passed in the options hash var query = options.data ? (~fragment.indexOf('?') ? '&' : '?') + $.url.query.stringify(options.data) : ''; // Un-Mark any `active` links in the page container var $container = $(this.config.containers).unMarkLinks(); // Navigate to the specified path. Return value is the value from the router // callback specified on the component var resp = Backbone.history.navigate(fragment + query, options); // Always return a promise. If the response of `Backbone.histroy.navigate` // was a promise, wait for it to resolve before resolving. Once resolved, // mark relevent links on the page as `active`. return new Promise(function(resolve, reject) { if(resp && resp.constructor === Promise) resp.then(resolve, resolve); resolve(resp); }).then(function(resp){ $container.markLinks(); return resp; }); }
javascript
function(fragment, options={}) { // Default trigger to true unless otherwise specified (options.trigger === undefined) && (options.trigger = true); // Stringify any data passed in the options hash var query = options.data ? (~fragment.indexOf('?') ? '&' : '?') + $.url.query.stringify(options.data) : ''; // Un-Mark any `active` links in the page container var $container = $(this.config.containers).unMarkLinks(); // Navigate to the specified path. Return value is the value from the router // callback specified on the component var resp = Backbone.history.navigate(fragment + query, options); // Always return a promise. If the response of `Backbone.histroy.navigate` // was a promise, wait for it to resolve before resolving. Once resolved, // mark relevent links on the page as `active`. return new Promise(function(resolve, reject) { if(resp && resp.constructor === Promise) resp.then(resolve, resolve); resolve(resp); }).then(function(resp){ $container.markLinks(); return resp; }); }
[ "function", "(", "fragment", ",", "options", "=", "{", "}", ")", "{", "(", "options", ".", "trigger", "===", "undefined", ")", "&&", "(", "options", ".", "trigger", "=", "true", ")", ";", "var", "query", "=", "options", ".", "data", "?", "(", "~", "fragment", ".", "indexOf", "(", "'?'", ")", "?", "'&'", ":", "'?'", ")", "+", "$", ".", "url", ".", "query", ".", "stringify", "(", "options", ".", "data", ")", ":", "''", ";", "var", "$container", "=", "$", "(", "this", ".", "config", ".", "containers", ")", ".", "unMarkLinks", "(", ")", ";", "var", "resp", "=", "Backbone", ".", "history", ".", "navigate", "(", "fragment", "+", "query", ",", "options", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "resp", "&&", "resp", ".", "constructor", "===", "Promise", ")", "resp", ".", "then", "(", "resolve", ",", "resolve", ")", ";", "resolve", "(", "resp", ")", ";", "}", ")", ".", "then", "(", "function", "(", "resp", ")", "{", "$container", ".", "markLinks", "(", ")", ";", "return", "resp", ";", "}", ")", ";", "}" ]
Modify navigate to default to `trigger=true` and to return the value of `Backbone.history.navigate` inside of a promise.
[ "Modify", "navigate", "to", "default", "to", "trigger", "=", "true", "and", "to", "return", "the", "value", "of", "Backbone", ".", "history", ".", "navigate", "inside", "of", "a", "promise", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-router/lib/rebound-router.js#L91-L116
train
reboundjs/rebound
packages/rebound-router/lib/rebound-router.js
function(route, name, callback) { if (_.isFunction(name)) { callback = name; name = ''; } if (!_.isRegExp(route)){ route = this._routeToRegExp(route); } if (!callback){ callback = this[name]; } Backbone.history.route(route, (fragment) => { // If this route was defined as a regular expression, we don't capture // query params. Only parse the actual path. fragment = fragment.split('?')[0]; // Extract the arguments we care about from the fragment var args = this._extractParameters(route, fragment); // Get the query params string var search = (Backbone.history.getSearch() || '').slice(1); // If this route was created from a string (not a regexp), remove the auto-captured // search params. if(route._isString){ args.pop(); } // If the route is not user prodided, if the history object has search params // then our args have the params as its last agrument as of Backbone 1.2.0 // If the route is a user provided regex, add in parsed search params from // the history object before passing to the callback. args.push((search) ? $.url.query.parse(search) : {}); var resp = this.execute(callback, args, name); if ( resp !== false) { this.trigger.apply(this, ['route:' + name].concat(args)); this.trigger('route', name, args); Backbone.history.trigger('route', this, name, args); } return resp; }); return this; }
javascript
function(route, name, callback) { if (_.isFunction(name)) { callback = name; name = ''; } if (!_.isRegExp(route)){ route = this._routeToRegExp(route); } if (!callback){ callback = this[name]; } Backbone.history.route(route, (fragment) => { // If this route was defined as a regular expression, we don't capture // query params. Only parse the actual path. fragment = fragment.split('?')[0]; // Extract the arguments we care about from the fragment var args = this._extractParameters(route, fragment); // Get the query params string var search = (Backbone.history.getSearch() || '').slice(1); // If this route was created from a string (not a regexp), remove the auto-captured // search params. if(route._isString){ args.pop(); } // If the route is not user prodided, if the history object has search params // then our args have the params as its last agrument as of Backbone 1.2.0 // If the route is a user provided regex, add in parsed search params from // the history object before passing to the callback. args.push((search) ? $.url.query.parse(search) : {}); var resp = this.execute(callback, args, name); if ( resp !== false) { this.trigger.apply(this, ['route:' + name].concat(args)); this.trigger('route', name, args); Backbone.history.trigger('route', this, name, args); } return resp; }); return this; }
[ "function", "(", "route", ",", "name", ",", "callback", ")", "{", "if", "(", "_", ".", "isFunction", "(", "name", ")", ")", "{", "callback", "=", "name", ";", "name", "=", "''", ";", "}", "if", "(", "!", "_", ".", "isRegExp", "(", "route", ")", ")", "{", "route", "=", "this", ".", "_routeToRegExp", "(", "route", ")", ";", "}", "if", "(", "!", "callback", ")", "{", "callback", "=", "this", "[", "name", "]", ";", "}", "Backbone", ".", "history", ".", "route", "(", "route", ",", "(", "fragment", ")", "=>", "{", "fragment", "=", "fragment", ".", "split", "(", "'?'", ")", "[", "0", "]", ";", "var", "args", "=", "this", ".", "_extractParameters", "(", "route", ",", "fragment", ")", ";", "var", "search", "=", "(", "Backbone", ".", "history", ".", "getSearch", "(", ")", "||", "''", ")", ".", "slice", "(", "1", ")", ";", "if", "(", "route", ".", "_isString", ")", "{", "args", ".", "pop", "(", ")", ";", "}", "args", ".", "push", "(", "(", "search", ")", "?", "$", ".", "url", ".", "query", ".", "parse", "(", "search", ")", ":", "{", "}", ")", ";", "var", "resp", "=", "this", ".", "execute", "(", "callback", ",", "args", ",", "name", ")", ";", "if", "(", "resp", "!==", "false", ")", "{", "this", ".", "trigger", ".", "apply", "(", "this", ",", "[", "'route:'", "+", "name", "]", ".", "concat", "(", "args", ")", ")", ";", "this", ".", "trigger", "(", "'route'", ",", "name", ",", "args", ")", ";", "Backbone", ".", "history", ".", "trigger", "(", "'route'", ",", "this", ",", "name", ",", "args", ")", ";", "}", "return", "resp", ";", "}", ")", ";", "return", "this", ";", "}" ]
Override route so if callback returns false, the route event is not triggered Every route also looks for query params, parses with QS, and passes the extra variable as a POJO to callbacks
[ "Override", "route", "so", "if", "callback", "returns", "false", "the", "route", "event", "is", "not", "triggered", "Every", "route", "also", "looks", "for", "query", "params", "parses", "with", "QS", "and", "passes", "the", "extra", "variable", "as", "a", "POJO", "to", "callbacks" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-router/lib/rebound-router.js#L144-L186
train
reboundjs/rebound
packages/rebound-router/lib/rebound-router.js
function(options={}, callback=function(){}) { // Let all of our components always have referance to our router Component.prototype.router = this; // Save our config referance this.config = options; this.config.handlers = []; this.config.containers = []; // Normalize our url configs this.config.root = normalizeUrl(this.config.root); this.config.assetRoot = this.config.assetRoot ? normalizeUrl(this.config.assetRoot) : this.config.root; this.config.jsPath = normalizeUrl(this.config.assetRoot, this.config.jsPath); this.config.cssPath = normalizeUrl(this.config.assetRoot, this.config.cssPath); // Get a unique instance id for this router this.uid = $.uniqueId('router'); // Allow user to override error route this.config.errorRoute && (ERROR_ROUTE_NAME = this.config.errorRoute); // Convert our routeMappings to regexps and push to our handlers _.each(this.config.routeMapping, function(value, route){ var regex = this._routeToRegExp(route); this.config.handlers.unshift({ route: route, regex: regex, app: value }); }, this); // Use the user provided container, or default to the closest `<main>` tag this.config.container = $((this.config.container || 'main'))[0]; this.config.containers.push(this.config.container); SERVICES.page = new ServiceLoader('page'); // Install our global components _.each(this.config.services, function(selector, route){ var container = $(selector)[0] || document.createElement('span'); this.config.containers.push(container); SERVICES[route] = new ServiceLoader(route); this._fetchResource(route, container).catch(function(){}); }, this); // Watch click events on links in all out containers this._watchLinks(this.config.containers); // Start the history and call the provided callback Backbone.history.start({ pushState: (this.config.pushState === undefined) ? true : this.config.pushState, root: (this.config.root || '') }).then(callback); return this; }
javascript
function(options={}, callback=function(){}) { // Let all of our components always have referance to our router Component.prototype.router = this; // Save our config referance this.config = options; this.config.handlers = []; this.config.containers = []; // Normalize our url configs this.config.root = normalizeUrl(this.config.root); this.config.assetRoot = this.config.assetRoot ? normalizeUrl(this.config.assetRoot) : this.config.root; this.config.jsPath = normalizeUrl(this.config.assetRoot, this.config.jsPath); this.config.cssPath = normalizeUrl(this.config.assetRoot, this.config.cssPath); // Get a unique instance id for this router this.uid = $.uniqueId('router'); // Allow user to override error route this.config.errorRoute && (ERROR_ROUTE_NAME = this.config.errorRoute); // Convert our routeMappings to regexps and push to our handlers _.each(this.config.routeMapping, function(value, route){ var regex = this._routeToRegExp(route); this.config.handlers.unshift({ route: route, regex: regex, app: value }); }, this); // Use the user provided container, or default to the closest `<main>` tag this.config.container = $((this.config.container || 'main'))[0]; this.config.containers.push(this.config.container); SERVICES.page = new ServiceLoader('page'); // Install our global components _.each(this.config.services, function(selector, route){ var container = $(selector)[0] || document.createElement('span'); this.config.containers.push(container); SERVICES[route] = new ServiceLoader(route); this._fetchResource(route, container).catch(function(){}); }, this); // Watch click events on links in all out containers this._watchLinks(this.config.containers); // Start the history and call the provided callback Backbone.history.start({ pushState: (this.config.pushState === undefined) ? true : this.config.pushState, root: (this.config.root || '') }).then(callback); return this; }
[ "function", "(", "options", "=", "{", "}", ",", "callback", "=", "function", "(", ")", "{", "}", ")", "{", "Component", ".", "prototype", ".", "router", "=", "this", ";", "this", ".", "config", "=", "options", ";", "this", ".", "config", ".", "handlers", "=", "[", "]", ";", "this", ".", "config", ".", "containers", "=", "[", "]", ";", "this", ".", "config", ".", "root", "=", "normalizeUrl", "(", "this", ".", "config", ".", "root", ")", ";", "this", ".", "config", ".", "assetRoot", "=", "this", ".", "config", ".", "assetRoot", "?", "normalizeUrl", "(", "this", ".", "config", ".", "assetRoot", ")", ":", "this", ".", "config", ".", "root", ";", "this", ".", "config", ".", "jsPath", "=", "normalizeUrl", "(", "this", ".", "config", ".", "assetRoot", ",", "this", ".", "config", ".", "jsPath", ")", ";", "this", ".", "config", ".", "cssPath", "=", "normalizeUrl", "(", "this", ".", "config", ".", "assetRoot", ",", "this", ".", "config", ".", "cssPath", ")", ";", "this", ".", "uid", "=", "$", ".", "uniqueId", "(", "'router'", ")", ";", "this", ".", "config", ".", "errorRoute", "&&", "(", "ERROR_ROUTE_NAME", "=", "this", ".", "config", ".", "errorRoute", ")", ";", "_", ".", "each", "(", "this", ".", "config", ".", "routeMapping", ",", "function", "(", "value", ",", "route", ")", "{", "var", "regex", "=", "this", ".", "_routeToRegExp", "(", "route", ")", ";", "this", ".", "config", ".", "handlers", ".", "unshift", "(", "{", "route", ":", "route", ",", "regex", ":", "regex", ",", "app", ":", "value", "}", ")", ";", "}", ",", "this", ")", ";", "this", ".", "config", ".", "container", "=", "$", "(", "(", "this", ".", "config", ".", "container", "||", "'main'", ")", ")", "[", "0", "]", ";", "this", ".", "config", ".", "containers", ".", "push", "(", "this", ".", "config", ".", "container", ")", ";", "SERVICES", ".", "page", "=", "new", "ServiceLoader", "(", "'page'", ")", ";", "_", ".", "each", "(", "this", ".", "config", ".", "services", ",", "function", "(", "selector", ",", "route", ")", "{", "var", "container", "=", "$", "(", "selector", ")", "[", "0", "]", "||", "document", ".", "createElement", "(", "'span'", ")", ";", "this", ".", "config", ".", "containers", ".", "push", "(", "container", ")", ";", "SERVICES", "[", "route", "]", "=", "new", "ServiceLoader", "(", "route", ")", ";", "this", ".", "_fetchResource", "(", "route", ",", "container", ")", ".", "catch", "(", "function", "(", ")", "{", "}", ")", ";", "}", ",", "this", ")", ";", "this", ".", "_watchLinks", "(", "this", ".", "config", ".", "containers", ")", ";", "Backbone", ".", "history", ".", "start", "(", "{", "pushState", ":", "(", "this", ".", "config", ".", "pushState", "===", "undefined", ")", "?", "true", ":", "this", ".", "config", ".", "pushState", ",", "root", ":", "(", "this", ".", "config", ".", "root", "||", "''", ")", "}", ")", ".", "then", "(", "callback", ")", ";", "return", "this", ";", "}" ]
On startup, save our config object and start the router
[ "On", "startup", "save", "our", "config", "object", "and", "start", "the", "router" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-router/lib/rebound-router.js#L189-L240
train
reboundjs/rebound
packages/rebound-router/lib/rebound-router.js
function(container){ // Navigate to route for any link with a relative href $(container).on('click', 'a', (e) => { var path = e.target.getAttribute('href'); // If the path is a remote URL, allow the browser to navigate normally. // Otherwise, prevent default so we can handle the route event. if(IS_REMOTE_URL.test(path) || path === '#'){ return void 0; } e.preventDefault(); // If this is not our current route, navigate to the new route if(path !== '/'+Backbone.history.fragment){ this.navigate(path, {trigger: true}); } }); }
javascript
function(container){ // Navigate to route for any link with a relative href $(container).on('click', 'a', (e) => { var path = e.target.getAttribute('href'); // If the path is a remote URL, allow the browser to navigate normally. // Otherwise, prevent default so we can handle the route event. if(IS_REMOTE_URL.test(path) || path === '#'){ return void 0; } e.preventDefault(); // If this is not our current route, navigate to the new route if(path !== '/'+Backbone.history.fragment){ this.navigate(path, {trigger: true}); } }); }
[ "function", "(", "container", ")", "{", "$", "(", "container", ")", ".", "on", "(", "'click'", ",", "'a'", ",", "(", "e", ")", "=>", "{", "var", "path", "=", "e", ".", "target", ".", "getAttribute", "(", "'href'", ")", ";", "if", "(", "IS_REMOTE_URL", ".", "test", "(", "path", ")", "||", "path", "===", "'#'", ")", "{", "return", "void", "0", ";", "}", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "path", "!==", "'/'", "+", "Backbone", ".", "history", ".", "fragment", ")", "{", "this", ".", "navigate", "(", "path", ",", "{", "trigger", ":", "true", "}", ")", ";", "}", "}", ")", ";", "}" ]
Given a dom element, watch for all click events on anchor tags. If the clicked anchor has a relative url, attempt to route to that path. Give all links on the page that match this path the class `active`.
[ "Given", "a", "dom", "element", "watch", "for", "all", "click", "events", "on", "anchor", "tags", ".", "If", "the", "clicked", "anchor", "has", "a", "relative", "url", "attempt", "to", "route", "to", "that", "path", ".", "Give", "all", "links", "on", "the", "page", "that", "match", "this", "path", "the", "class", "active", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-router/lib/rebound-router.js#L252-L267
train
reboundjs/rebound
packages/rebound-router/lib/rebound-router.js
function(){ var routes = this.current ? (this.current.data.routes || {}) : {}; routes[this._previousRoute] = ''; // Unset Previous Application's Routes. For each route in the page app, remove // the handler from our route object and delete our referance to the route's callback _.each(routes, (value, key) => { var regExp = this._routeToRegExp(key).toString(); Backbone.history.handlers = _.filter(Backbone.history.handlers, function(obj){ return obj.route.toString() !== regExp; }); }); if(!this.current){ return void 0; } var oldPageName = this.current.__pageId; // Un-hook Event Bindings, Delete Objects this.current.data.deinitialize(); // Now we no longer have a page installed. this.current = undefined; // Disable old css if it exists setTimeout(() => { if(this.status === ERROR){ return void 0; } document.getElementById(oldPageName + '-css').setAttribute('disabled', true); }, 500); }
javascript
function(){ var routes = this.current ? (this.current.data.routes || {}) : {}; routes[this._previousRoute] = ''; // Unset Previous Application's Routes. For each route in the page app, remove // the handler from our route object and delete our referance to the route's callback _.each(routes, (value, key) => { var regExp = this._routeToRegExp(key).toString(); Backbone.history.handlers = _.filter(Backbone.history.handlers, function(obj){ return obj.route.toString() !== regExp; }); }); if(!this.current){ return void 0; } var oldPageName = this.current.__pageId; // Un-hook Event Bindings, Delete Objects this.current.data.deinitialize(); // Now we no longer have a page installed. this.current = undefined; // Disable old css if it exists setTimeout(() => { if(this.status === ERROR){ return void 0; } document.getElementById(oldPageName + '-css').setAttribute('disabled', true); }, 500); }
[ "function", "(", ")", "{", "var", "routes", "=", "this", ".", "current", "?", "(", "this", ".", "current", ".", "data", ".", "routes", "||", "{", "}", ")", ":", "{", "}", ";", "routes", "[", "this", ".", "_previousRoute", "]", "=", "''", ";", "_", ".", "each", "(", "routes", ",", "(", "value", ",", "key", ")", "=>", "{", "var", "regExp", "=", "this", ".", "_routeToRegExp", "(", "key", ")", ".", "toString", "(", ")", ";", "Backbone", ".", "history", ".", "handlers", "=", "_", ".", "filter", "(", "Backbone", ".", "history", ".", "handlers", ",", "function", "(", "obj", ")", "{", "return", "obj", ".", "route", ".", "toString", "(", ")", "!==", "regExp", ";", "}", ")", ";", "}", ")", ";", "if", "(", "!", "this", ".", "current", ")", "{", "return", "void", "0", ";", "}", "var", "oldPageName", "=", "this", ".", "current", ".", "__pageId", ";", "this", ".", "current", ".", "data", ".", "deinitialize", "(", ")", ";", "this", ".", "current", "=", "undefined", ";", "setTimeout", "(", "(", ")", "=>", "{", "if", "(", "this", ".", "status", "===", "ERROR", ")", "{", "return", "void", "0", ";", "}", "document", ".", "getElementById", "(", "oldPageName", "+", "'-css'", ")", ".", "setAttribute", "(", "'disabled'", ",", "true", ")", ";", "}", ",", "500", ")", ";", "}" ]
De-initializes the previous app before rendering a new app This way we can ensure that every new page starts with a clean slate This is crucial for scalability of a single page app.
[ "De", "-", "initializes", "the", "previous", "app", "before", "rendering", "a", "new", "app", "This", "way", "we", "can", "ensure", "that", "every", "new", "page", "starts", "with", "a", "clean", "slate", "This", "is", "crucial", "for", "scalability", "of", "a", "single", "page", "app", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-router/lib/rebound-router.js#L272-L302
train
reboundjs/rebound
packages/rebound-router/lib/rebound-router.js
function(PageApp, appName, container) { var oldPageName, pageInstance, routes = []; var isService = (container !== this.config.container); var name = (isService) ? appName : 'page'; // If no container exists, throw an error if(!container) throw 'No container found on the page! Please specify a container that exists in your Rebound config.'; // Add page level loading class container.classList.remove('error', 'loading'); // Uninstall any old resource we have loaded if(!isService && this.current){ this._uninstallResource(); } // Load New PageApp, give it it's name so we know what css to remove when it deinitializes pageInstance = ComponentFactory(PageApp).el; if(SERVICES[name].isLazyComponent){ SERVICES[name].hydrate(pageInstance.data); } else{ SERVICES[name] = pageInstance.data; } pageInstance.__pageId = this.uid + '-' + appName; // Add to our page $(container).empty(); container.appendChild(pageInstance); // Make sure we're back at the top of the page document.body.scrollTop = 0; // Add a default route handler for the route that got us here so if the component // does not define a route that handles it, we don't get a redirect loop if(!isService){ this.route(this._currentRoute, 'default', function(){ return void 0; }); } // Augment ApplicationRouter with new routes from PageApp added in reverse order to preserve order higherarchy _.each(pageInstance.data.routes, (value, key) => { // Add the new callback referance on to our router and add the route handler this.route(key, value, function () { return pageInstance.data[value].apply(pageInstance.data, arguments); }); }); // If this is the main page component, set it as current if(!isService){ this.current = pageInstance; } // Always return a promise return new Promise(function(resolve, reject){ // Re-trigger route so the newly added route may execute if there's a route match. // If no routes are matched, app will hit wildCard route which will then trigger 404 if(!isService){ let res = Backbone.history.loadUrl(Backbone.history.fragment); if(res && typeof res.then === 'function') return res.then(resolve); return resolve(res); } // Return our newly installed app return resolve(pageInstance); }); }
javascript
function(PageApp, appName, container) { var oldPageName, pageInstance, routes = []; var isService = (container !== this.config.container); var name = (isService) ? appName : 'page'; // If no container exists, throw an error if(!container) throw 'No container found on the page! Please specify a container that exists in your Rebound config.'; // Add page level loading class container.classList.remove('error', 'loading'); // Uninstall any old resource we have loaded if(!isService && this.current){ this._uninstallResource(); } // Load New PageApp, give it it's name so we know what css to remove when it deinitializes pageInstance = ComponentFactory(PageApp).el; if(SERVICES[name].isLazyComponent){ SERVICES[name].hydrate(pageInstance.data); } else{ SERVICES[name] = pageInstance.data; } pageInstance.__pageId = this.uid + '-' + appName; // Add to our page $(container).empty(); container.appendChild(pageInstance); // Make sure we're back at the top of the page document.body.scrollTop = 0; // Add a default route handler for the route that got us here so if the component // does not define a route that handles it, we don't get a redirect loop if(!isService){ this.route(this._currentRoute, 'default', function(){ return void 0; }); } // Augment ApplicationRouter with new routes from PageApp added in reverse order to preserve order higherarchy _.each(pageInstance.data.routes, (value, key) => { // Add the new callback referance on to our router and add the route handler this.route(key, value, function () { return pageInstance.data[value].apply(pageInstance.data, arguments); }); }); // If this is the main page component, set it as current if(!isService){ this.current = pageInstance; } // Always return a promise return new Promise(function(resolve, reject){ // Re-trigger route so the newly added route may execute if there's a route match. // If no routes are matched, app will hit wildCard route which will then trigger 404 if(!isService){ let res = Backbone.history.loadUrl(Backbone.history.fragment); if(res && typeof res.then === 'function') return res.then(resolve); return resolve(res); } // Return our newly installed app return resolve(pageInstance); }); }
[ "function", "(", "PageApp", ",", "appName", ",", "container", ")", "{", "var", "oldPageName", ",", "pageInstance", ",", "routes", "=", "[", "]", ";", "var", "isService", "=", "(", "container", "!==", "this", ".", "config", ".", "container", ")", ";", "var", "name", "=", "(", "isService", ")", "?", "appName", ":", "'page'", ";", "if", "(", "!", "container", ")", "throw", "'No container found on the page! Please specify a container that exists in your Rebound config.'", ";", "container", ".", "classList", ".", "remove", "(", "'error'", ",", "'loading'", ")", ";", "if", "(", "!", "isService", "&&", "this", ".", "current", ")", "{", "this", ".", "_uninstallResource", "(", ")", ";", "}", "pageInstance", "=", "ComponentFactory", "(", "PageApp", ")", ".", "el", ";", "if", "(", "SERVICES", "[", "name", "]", ".", "isLazyComponent", ")", "{", "SERVICES", "[", "name", "]", ".", "hydrate", "(", "pageInstance", ".", "data", ")", ";", "}", "else", "{", "SERVICES", "[", "name", "]", "=", "pageInstance", ".", "data", ";", "}", "pageInstance", ".", "__pageId", "=", "this", ".", "uid", "+", "'-'", "+", "appName", ";", "$", "(", "container", ")", ".", "empty", "(", ")", ";", "container", ".", "appendChild", "(", "pageInstance", ")", ";", "document", ".", "body", ".", "scrollTop", "=", "0", ";", "if", "(", "!", "isService", ")", "{", "this", ".", "route", "(", "this", ".", "_currentRoute", ",", "'default'", ",", "function", "(", ")", "{", "return", "void", "0", ";", "}", ")", ";", "}", "_", ".", "each", "(", "pageInstance", ".", "data", ".", "routes", ",", "(", "value", ",", "key", ")", "=>", "{", "this", ".", "route", "(", "key", ",", "value", ",", "function", "(", ")", "{", "return", "pageInstance", ".", "data", "[", "value", "]", ".", "apply", "(", "pageInstance", ".", "data", ",", "arguments", ")", ";", "}", ")", ";", "}", ")", ";", "if", "(", "!", "isService", ")", "{", "this", ".", "current", "=", "pageInstance", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "isService", ")", "{", "let", "res", "=", "Backbone", ".", "history", ".", "loadUrl", "(", "Backbone", ".", "history", ".", "fragment", ")", ";", "if", "(", "res", "&&", "typeof", "res", ".", "then", "===", "'function'", ")", "return", "res", ".", "then", "(", "resolve", ")", ";", "return", "resolve", "(", "res", ")", ";", "}", "return", "resolve", "(", "pageInstance", ")", ";", "}", ")", ";", "}" ]
Give our new page component, load routes and render a new instance of the page component in the top level outlet.
[ "Give", "our", "new", "page", "component", "load", "routes", "and", "render", "a", "new", "instance", "of", "the", "page", "component", "in", "the", "top", "level", "outlet", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-router/lib/rebound-router.js#L306-L359
train
reboundjs/rebound
packages/rebound-router/lib/rebound-router.js
function(route, container) { var appName, routeName, isService = (container !== this.config.container), isError = (route === ERROR_ROUTE_NAME); // Normalize Route route || (route = ''); // Get the app name from this route appName = routeName = (route.split('/')[0] || 'index'); // If this isn't the error route, Find Any Custom Route Mappings if(!isService && !isError){ this._currentRoute = route.split('/')[0]; _.any(this.config.handlers, (handler) => { if (handler.regex.test(route)){ appName = handler.app; this._currentRoute = handler.route; return true; } }); } // Wrap these async resource fetches in a promise and return it. // This promise resolves when both css and js resources are loaded // It rejects if either of the css or js resources fails to load. return new Promise((resolve, reject) => { var throwError = (err) => { // If we are already in an error state, this means we were unable to load // a custom error page. Uninstall anything we have and insert our default 404 page. if(this.status === ERROR){ if(isService) return resolve(err); this._uninstallResource(); container.innerHTML = DEFAULT_404_PAGE; return resolve(err); } // Set our status to error and attempt to load a custom error page. console.error('Could not ' + ((isService) ? 'load the ' + appName + ' service:' : 'find the ' + (appName || 'index') + ' app.'), 'at', ('/' + route)); this.status = ERROR; this._currentRoute = route; resolve(this._fetchResource(ERROR_ROUTE_NAME, container)); }; // If the values we got from installing our resources are unexpected, 404 // Otherwise, set status, activate the css, and install the page component var install = (response) => { var cssElement = response[0], jsElement = response[1]; if(!(cssElement instanceof Element) || !(jsElement instanceof Element) ) return throwError(); (!isService && !isError) && (this.status = SUCCESS); cssElement && cssElement.removeAttribute('disabled'); this._installResource(jsElement.getAttribute('data-name'), appName, container).then(resolve, resolve); }; // If loading a page, set status to loading (!isService && !isError) && (this.status = LOADING); // If Page Is Already Loaded Then The Route Does Not Exist. 404 and Exit. if (this.current && this.current.__pageId === (this.uid + '-' + appName)){ return throwError(); } // Fetch our css and js in paralell, install or throw when both complete Promise.all([this._fetchCSS(routeName, appName), this._fetchJavascript(routeName, appName)]) .then(install, throwError); }); }
javascript
function(route, container) { var appName, routeName, isService = (container !== this.config.container), isError = (route === ERROR_ROUTE_NAME); // Normalize Route route || (route = ''); // Get the app name from this route appName = routeName = (route.split('/')[0] || 'index'); // If this isn't the error route, Find Any Custom Route Mappings if(!isService && !isError){ this._currentRoute = route.split('/')[0]; _.any(this.config.handlers, (handler) => { if (handler.regex.test(route)){ appName = handler.app; this._currentRoute = handler.route; return true; } }); } // Wrap these async resource fetches in a promise and return it. // This promise resolves when both css and js resources are loaded // It rejects if either of the css or js resources fails to load. return new Promise((resolve, reject) => { var throwError = (err) => { // If we are already in an error state, this means we were unable to load // a custom error page. Uninstall anything we have and insert our default 404 page. if(this.status === ERROR){ if(isService) return resolve(err); this._uninstallResource(); container.innerHTML = DEFAULT_404_PAGE; return resolve(err); } // Set our status to error and attempt to load a custom error page. console.error('Could not ' + ((isService) ? 'load the ' + appName + ' service:' : 'find the ' + (appName || 'index') + ' app.'), 'at', ('/' + route)); this.status = ERROR; this._currentRoute = route; resolve(this._fetchResource(ERROR_ROUTE_NAME, container)); }; // If the values we got from installing our resources are unexpected, 404 // Otherwise, set status, activate the css, and install the page component var install = (response) => { var cssElement = response[0], jsElement = response[1]; if(!(cssElement instanceof Element) || !(jsElement instanceof Element) ) return throwError(); (!isService && !isError) && (this.status = SUCCESS); cssElement && cssElement.removeAttribute('disabled'); this._installResource(jsElement.getAttribute('data-name'), appName, container).then(resolve, resolve); }; // If loading a page, set status to loading (!isService && !isError) && (this.status = LOADING); // If Page Is Already Loaded Then The Route Does Not Exist. 404 and Exit. if (this.current && this.current.__pageId === (this.uid + '-' + appName)){ return throwError(); } // Fetch our css and js in paralell, install or throw when both complete Promise.all([this._fetchCSS(routeName, appName), this._fetchJavascript(routeName, appName)]) .then(install, throwError); }); }
[ "function", "(", "route", ",", "container", ")", "{", "var", "appName", ",", "routeName", ",", "isService", "=", "(", "container", "!==", "this", ".", "config", ".", "container", ")", ",", "isError", "=", "(", "route", "===", "ERROR_ROUTE_NAME", ")", ";", "route", "||", "(", "route", "=", "''", ")", ";", "appName", "=", "routeName", "=", "(", "route", ".", "split", "(", "'/'", ")", "[", "0", "]", "||", "'index'", ")", ";", "if", "(", "!", "isService", "&&", "!", "isError", ")", "{", "this", ".", "_currentRoute", "=", "route", ".", "split", "(", "'/'", ")", "[", "0", "]", ";", "_", ".", "any", "(", "this", ".", "config", ".", "handlers", ",", "(", "handler", ")", "=>", "{", "if", "(", "handler", ".", "regex", ".", "test", "(", "route", ")", ")", "{", "appName", "=", "handler", ".", "app", ";", "this", ".", "_currentRoute", "=", "handler", ".", "route", ";", "return", "true", ";", "}", "}", ")", ";", "}", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "throwError", "=", "(", "err", ")", "=>", "{", "if", "(", "this", ".", "status", "===", "ERROR", ")", "{", "if", "(", "isService", ")", "return", "resolve", "(", "err", ")", ";", "this", ".", "_uninstallResource", "(", ")", ";", "container", ".", "innerHTML", "=", "DEFAULT_404_PAGE", ";", "return", "resolve", "(", "err", ")", ";", "}", "console", ".", "error", "(", "'Could not '", "+", "(", "(", "isService", ")", "?", "'load the '", "+", "appName", "+", "' service:'", ":", "'find the '", "+", "(", "appName", "||", "'index'", ")", "+", "' app.'", ")", ",", "'at'", ",", "(", "'/'", "+", "route", ")", ")", ";", "this", ".", "status", "=", "ERROR", ";", "this", ".", "_currentRoute", "=", "route", ";", "resolve", "(", "this", ".", "_fetchResource", "(", "ERROR_ROUTE_NAME", ",", "container", ")", ")", ";", "}", ";", "var", "install", "=", "(", "response", ")", "=>", "{", "var", "cssElement", "=", "response", "[", "0", "]", ",", "jsElement", "=", "response", "[", "1", "]", ";", "if", "(", "!", "(", "cssElement", "instanceof", "Element", ")", "||", "!", "(", "jsElement", "instanceof", "Element", ")", ")", "return", "throwError", "(", ")", ";", "(", "!", "isService", "&&", "!", "isError", ")", "&&", "(", "this", ".", "status", "=", "SUCCESS", ")", ";", "cssElement", "&&", "cssElement", ".", "removeAttribute", "(", "'disabled'", ")", ";", "this", ".", "_installResource", "(", "jsElement", ".", "getAttribute", "(", "'data-name'", ")", ",", "appName", ",", "container", ")", ".", "then", "(", "resolve", ",", "resolve", ")", ";", "}", ";", "(", "!", "isService", "&&", "!", "isError", ")", "&&", "(", "this", ".", "status", "=", "LOADING", ")", ";", "if", "(", "this", ".", "current", "&&", "this", ".", "current", ".", "__pageId", "===", "(", "this", ".", "uid", "+", "'-'", "+", "appName", ")", ")", "{", "return", "throwError", "(", ")", ";", "}", "Promise", ".", "all", "(", "[", "this", ".", "_fetchCSS", "(", "routeName", ",", "appName", ")", ",", "this", ".", "_fetchJavascript", "(", "routeName", ",", "appName", ")", "]", ")", ".", "then", "(", "install", ",", "throwError", ")", ";", "}", ")", ";", "}" ]
Fetches HTML and CSS
[ "Fetches", "HTML", "and", "CSS" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-router/lib/rebound-router.js#L379-L446
train
hammy2899/o
src/clone.js
clone
function clone(object) { // check if the object is an object and isn't empty if (is(object) && !empty(object)) { // create a new object for the result const result = {}; // for each key in the specified object add it // to the new result with the value from the // original object Object.keys(object).forEach((key) => { result[key] = object[key]; }); // return the result object return result; } // if the object isn't an object or is empty return // an empty object this will keep the return immutable return {}; }
javascript
function clone(object) { // check if the object is an object and isn't empty if (is(object) && !empty(object)) { // create a new object for the result const result = {}; // for each key in the specified object add it // to the new result with the value from the // original object Object.keys(object).forEach((key) => { result[key] = object[key]; }); // return the result object return result; } // if the object isn't an object or is empty return // an empty object this will keep the return immutable return {}; }
[ "function", "clone", "(", "object", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", ")", "{", "const", "result", "=", "{", "}", ";", "Object", ".", "keys", "(", "object", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "result", "[", "key", "]", "=", "object", "[", "key", "]", ";", "}", ")", ";", "return", "result", ";", "}", "return", "{", "}", ";", "}" ]
Clone the specified object @example const a = { a: 1 }; const b = clone(a); // => { a: 1 } b.a = 2; console.log(a); // => { a: 1 } console.log(b); // => { a: 2 } @since 1.0.0 @version 1.0.0 @param {object} object The object to clone @returns {object} The cloned object
[ "Clone", "the", "specified", "object" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/clone.js#L22-L42
train
kevinoid/stream-compare
index.js
endListener
function endListener(state) { // Note: If incremental is conclusive for 'end' event, this will be called // with isDone === true, since removeListener doesn't affect listeners for // an event which is already in-progress. if (state.ended || isDone) { return; } state.ended = true; ended += 1; debug(`${streamName(this)} has ended.`); if (options.incremental) { if (doCompare(options.incremental, CompareType.incremental)) { return; } } if (ended === 2) { const postEndCompare = function() { doCompare(options.compare, CompareType.last); }; if (options.delay) { debug(`All streams have ended. Delaying for ${options.delay }ms before final compare.`); postEndTimeout = setTimeout(postEndCompare, options.delay); } else { // Let pending I/O and callbacks complete to catch some errant events debug('All streams have ended. Delaying before final compare.'); postEndImmediate = setImmediate(postEndCompare); } } }
javascript
function endListener(state) { // Note: If incremental is conclusive for 'end' event, this will be called // with isDone === true, since removeListener doesn't affect listeners for // an event which is already in-progress. if (state.ended || isDone) { return; } state.ended = true; ended += 1; debug(`${streamName(this)} has ended.`); if (options.incremental) { if (doCompare(options.incremental, CompareType.incremental)) { return; } } if (ended === 2) { const postEndCompare = function() { doCompare(options.compare, CompareType.last); }; if (options.delay) { debug(`All streams have ended. Delaying for ${options.delay }ms before final compare.`); postEndTimeout = setTimeout(postEndCompare, options.delay); } else { // Let pending I/O and callbacks complete to catch some errant events debug('All streams have ended. Delaying before final compare.'); postEndImmediate = setImmediate(postEndCompare); } } }
[ "function", "endListener", "(", "state", ")", "{", "if", "(", "state", ".", "ended", "||", "isDone", ")", "{", "return", ";", "}", "state", ".", "ended", "=", "true", ";", "ended", "+=", "1", ";", "debug", "(", "`", "${", "streamName", "(", "this", ")", "}", "`", ")", ";", "if", "(", "options", ".", "incremental", ")", "{", "if", "(", "doCompare", "(", "options", ".", "incremental", ",", "CompareType", ".", "incremental", ")", ")", "{", "return", ";", "}", "}", "if", "(", "ended", "===", "2", ")", "{", "const", "postEndCompare", "=", "function", "(", ")", "{", "doCompare", "(", "options", ".", "compare", ",", "CompareType", ".", "last", ")", ";", "}", ";", "if", "(", "options", ".", "delay", ")", "{", "debug", "(", "`", "${", "options", ".", "delay", "}", "`", ")", ";", "postEndTimeout", "=", "setTimeout", "(", "postEndCompare", ",", "options", ".", "delay", ")", ";", "}", "else", "{", "debug", "(", "'All streams have ended. Delaying before final compare.'", ")", ";", "postEndImmediate", "=", "setImmediate", "(", "postEndCompare", ")", ";", "}", "}", "}" ]
Handles stream end events. @this {!Readable} @private
[ "Handles", "stream", "end", "events", "." ]
37cea4249b827151533024e79eca707f2a37c7c5
https://github.com/kevinoid/stream-compare/blob/37cea4249b827151533024e79eca707f2a37c7c5/index.js#L374-L407
train
kevinoid/stream-compare
index.js
addData
function addData(data) { if (options.objectMode) { if (!this.data) { this.data = [data]; } else { this.data.push(data); } this.totalDataLen += 1; } else if (typeof data !== 'string' && !(data instanceof Buffer)) { throw new TypeError(`expected string or Buffer, got ${ Object.prototype.toString.call(data)}. Need objectMode?`); } else if (this.data === null || this.data === undefined) { this.data = data; this.totalDataLen += data.length; } else if (typeof this.data === 'string' && typeof data === 'string') { // perf: Avoid unnecessary string concatenation if (this.data.length === 0) { this.data = data; } else if (data.length > 0) { this.data += data; } this.totalDataLen += data.length; } else if (this.data instanceof Buffer && data instanceof Buffer) { // perf: Avoid unnecessary Buffer concatenation if (this.data.length === 0) { this.data = data; } else if (data.length > 0) { // FIXME: Potential performance issue if data or this.data are large. // Should append to a Buffer we control and store a slice in .data this.data = Buffer.concat( [this.data, data], this.data.length + data.length ); } this.totalDataLen += data.length; } else { throw new TypeError(`read returned ${ Object.prototype.toString.call(data)}, previously ${ Object.prototype.toString.call(this.data) }. Need objectMode?`); } }
javascript
function addData(data) { if (options.objectMode) { if (!this.data) { this.data = [data]; } else { this.data.push(data); } this.totalDataLen += 1; } else if (typeof data !== 'string' && !(data instanceof Buffer)) { throw new TypeError(`expected string or Buffer, got ${ Object.prototype.toString.call(data)}. Need objectMode?`); } else if (this.data === null || this.data === undefined) { this.data = data; this.totalDataLen += data.length; } else if (typeof this.data === 'string' && typeof data === 'string') { // perf: Avoid unnecessary string concatenation if (this.data.length === 0) { this.data = data; } else if (data.length > 0) { this.data += data; } this.totalDataLen += data.length; } else if (this.data instanceof Buffer && data instanceof Buffer) { // perf: Avoid unnecessary Buffer concatenation if (this.data.length === 0) { this.data = data; } else if (data.length > 0) { // FIXME: Potential performance issue if data or this.data are large. // Should append to a Buffer we control and store a slice in .data this.data = Buffer.concat( [this.data, data], this.data.length + data.length ); } this.totalDataLen += data.length; } else { throw new TypeError(`read returned ${ Object.prototype.toString.call(data)}, previously ${ Object.prototype.toString.call(this.data) }. Need objectMode?`); } }
[ "function", "addData", "(", "data", ")", "{", "if", "(", "options", ".", "objectMode", ")", "{", "if", "(", "!", "this", ".", "data", ")", "{", "this", ".", "data", "=", "[", "data", "]", ";", "}", "else", "{", "this", ".", "data", ".", "push", "(", "data", ")", ";", "}", "this", ".", "totalDataLen", "+=", "1", ";", "}", "else", "if", "(", "typeof", "data", "!==", "'string'", "&&", "!", "(", "data", "instanceof", "Buffer", ")", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "data", ")", "}", "`", ")", ";", "}", "else", "if", "(", "this", ".", "data", "===", "null", "||", "this", ".", "data", "===", "undefined", ")", "{", "this", ".", "data", "=", "data", ";", "this", ".", "totalDataLen", "+=", "data", ".", "length", ";", "}", "else", "if", "(", "typeof", "this", ".", "data", "===", "'string'", "&&", "typeof", "data", "===", "'string'", ")", "{", "if", "(", "this", ".", "data", ".", "length", "===", "0", ")", "{", "this", ".", "data", "=", "data", ";", "}", "else", "if", "(", "data", ".", "length", ">", "0", ")", "{", "this", ".", "data", "+=", "data", ";", "}", "this", ".", "totalDataLen", "+=", "data", ".", "length", ";", "}", "else", "if", "(", "this", ".", "data", "instanceof", "Buffer", "&&", "data", "instanceof", "Buffer", ")", "{", "if", "(", "this", ".", "data", ".", "length", "===", "0", ")", "{", "this", ".", "data", "=", "data", ";", "}", "else", "if", "(", "data", ".", "length", ">", "0", ")", "{", "this", ".", "data", "=", "Buffer", ".", "concat", "(", "[", "this", ".", "data", ",", "data", "]", ",", "this", ".", "data", ".", "length", "+", "data", ".", "length", ")", ";", "}", "this", ".", "totalDataLen", "+=", "data", ".", "length", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "`", "${", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "data", ")", "}", "${", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "this", ".", "data", ")", "}", "`", ")", ";", "}", "}" ]
Adds data to a stream state. This function should be a method of StreamState, but that would violate our guarantees. We call it as if it were to convey this behavior and to avoid ESLint no-param-reassign. @this {!StreamState} @param {*} data Data read from the stream for this StreamState. @private
[ "Adds", "data", "to", "a", "stream", "state", "." ]
37cea4249b827151533024e79eca707f2a37c7c5
https://github.com/kevinoid/stream-compare/blob/37cea4249b827151533024e79eca707f2a37c7c5/index.js#L437-L478
train
kevinoid/stream-compare
index.js
handleData
function handleData(state, data) { debug('Read data from ', streamName(this)); try { addData.call(state, data); } catch (err) { debug(`Error adding data from ${streamName(this)}`, err); reject(err); done(); return; } if (options.incremental) { doCompare(options.incremental, CompareType.incremental); } }
javascript
function handleData(state, data) { debug('Read data from ', streamName(this)); try { addData.call(state, data); } catch (err) { debug(`Error adding data from ${streamName(this)}`, err); reject(err); done(); return; } if (options.incremental) { doCompare(options.incremental, CompareType.incremental); } }
[ "function", "handleData", "(", "state", ",", "data", ")", "{", "debug", "(", "'Read data from '", ",", "streamName", "(", "this", ")", ")", ";", "try", "{", "addData", ".", "call", "(", "state", ",", "data", ")", ";", "}", "catch", "(", "err", ")", "{", "debug", "(", "`", "${", "streamName", "(", "this", ")", "}", "`", ",", "err", ")", ";", "reject", "(", "err", ")", ";", "done", "(", ")", ";", "return", ";", "}", "if", "(", "options", ".", "incremental", ")", "{", "doCompare", "(", "options", ".", "incremental", ",", "CompareType", ".", "incremental", ")", ";", "}", "}" ]
Handles data read from the stream for a given state. @private
[ "Handles", "data", "read", "from", "the", "stream", "for", "a", "given", "state", "." ]
37cea4249b827151533024e79eca707f2a37c7c5
https://github.com/kevinoid/stream-compare/blob/37cea4249b827151533024e79eca707f2a37c7c5/index.js#L483-L498
train
kevinoid/stream-compare
index.js
readNext
function readNext() { let stream, state; while (!isDone) { if (!state1.ended && (state2.ended || state1.totalDataLen <= state2.totalDataLen)) { stream = stream1; state = state1; } else if (!state2.ended) { stream = stream2; state = state2; } else { debug('All streams have ended. No further reads.'); return; } const data = stream.read(); if (data === null) { debug(`Waiting for ${streamName(stream)} to be readable...`); stream.once('readable', readNext); return; } handleData.call(stream, state, data); } }
javascript
function readNext() { let stream, state; while (!isDone) { if (!state1.ended && (state2.ended || state1.totalDataLen <= state2.totalDataLen)) { stream = stream1; state = state1; } else if (!state2.ended) { stream = stream2; state = state2; } else { debug('All streams have ended. No further reads.'); return; } const data = stream.read(); if (data === null) { debug(`Waiting for ${streamName(stream)} to be readable...`); stream.once('readable', readNext); return; } handleData.call(stream, state, data); } }
[ "function", "readNext", "(", ")", "{", "let", "stream", ",", "state", ";", "while", "(", "!", "isDone", ")", "{", "if", "(", "!", "state1", ".", "ended", "&&", "(", "state2", ".", "ended", "||", "state1", ".", "totalDataLen", "<=", "state2", ".", "totalDataLen", ")", ")", "{", "stream", "=", "stream1", ";", "state", "=", "state1", ";", "}", "else", "if", "(", "!", "state2", ".", "ended", ")", "{", "stream", "=", "stream2", ";", "state", "=", "state2", ";", "}", "else", "{", "debug", "(", "'All streams have ended. No further reads.'", ")", ";", "return", ";", "}", "const", "data", "=", "stream", ".", "read", "(", ")", ";", "if", "(", "data", "===", "null", ")", "{", "debug", "(", "`", "${", "streamName", "(", "stream", ")", "}", "`", ")", ";", "stream", ".", "once", "(", "'readable'", ",", "readNext", ")", ";", "return", ";", "}", "handleData", ".", "call", "(", "stream", ",", "state", ",", "data", ")", ";", "}", "}" ]
Reads from the non-ended stream which has the smallest totalDataLen. @private
[ "Reads", "from", "the", "non", "-", "ended", "stream", "which", "has", "the", "smallest", "totalDataLen", "." ]
37cea4249b827151533024e79eca707f2a37c7c5
https://github.com/kevinoid/stream-compare/blob/37cea4249b827151533024e79eca707f2a37c7c5/index.js#L503-L528
train
pVelocity/pvserver
pvserver.js
function(operation, parameters) { var req; req = getXmlReqHeader.call(this); req.push('<Operation><Name>', operation, '</Name>', '<Params>'); if (parameters) { // don't send raw '&', but don't change '&amp;', '&lt;', etc. req.push( parameters.replace(/&/g, "&amp;") .replace(/&amp;(amp|lt|gt|quot);/g, "&$1;") ); } req.push('</Params></Operation></PVRequest>'); return req.join(''); }
javascript
function(operation, parameters) { var req; req = getXmlReqHeader.call(this); req.push('<Operation><Name>', operation, '</Name>', '<Params>'); if (parameters) { // don't send raw '&', but don't change '&amp;', '&lt;', etc. req.push( parameters.replace(/&/g, "&amp;") .replace(/&amp;(amp|lt|gt|quot);/g, "&$1;") ); } req.push('</Params></Operation></PVRequest>'); return req.join(''); }
[ "function", "(", "operation", ",", "parameters", ")", "{", "var", "req", ";", "req", "=", "getXmlReqHeader", ".", "call", "(", "this", ")", ";", "req", ".", "push", "(", "'<Operation><Name>'", ",", "operation", ",", "'</Name>'", ",", "'<Params>'", ")", ";", "if", "(", "parameters", ")", "{", "req", ".", "push", "(", "parameters", ".", "replace", "(", "/", "&", "/", "g", ",", "\"&amp;\"", ")", ".", "replace", "(", "/", "&amp;(amp|lt|gt|quot);", "/", "g", ",", "\"&$1;\"", ")", ")", ";", "}", "req", ".", "push", "(", "'</Params></Operation></PVRequest>'", ")", ";", "return", "req", ".", "join", "(", "''", ")", ";", "}" ]
Create an XML request string for the RPM API, note that the parameters are in XML.
[ "Create", "an", "XML", "request", "string", "for", "the", "RPM", "API", "note", "that", "the", "parameters", "are", "in", "XML", "." ]
d81d31df5b49458b304676437b79915a1638863f
https://github.com/pVelocity/pvserver/blob/d81d31df5b49458b304676437b79915a1638863f/pvserver.js#L108-L123
train
blond/ho-iter
lib/evenly.js
evenly
function evenly(iterables) { const iterators = iterables.map(iterable => createIterator(iterable, { strict: false })); const empties = new Set(); const count = iterators.length; let index = -1; /** * Returns next iterator. * * Returns the first iterator after the last one. * * @returns {Iterator} */ function step() { // Back to the first iterator. if (index === count - 1) { index = -1; } // Go to the next iterator. index++; // Ignore empty iterators. while(empties.has(index)) { if (index === count - 1) { index = -1; } index++; } return iterators[index]; } /** * Returns next value. * * @returns {{done: boolean, value: *}} */ function next() { // Exit if all iterators are traversed. if (empties.size === count) { return done; } // Go to the next iterator. const iter = step(); const res = iter.next(); // Mark iterator as empty and go to the next. if (res.done) { empties.add(index); return next(); } return res; } return { next, [Symbol.iterator]() { return this; } }; }
javascript
function evenly(iterables) { const iterators = iterables.map(iterable => createIterator(iterable, { strict: false })); const empties = new Set(); const count = iterators.length; let index = -1; /** * Returns next iterator. * * Returns the first iterator after the last one. * * @returns {Iterator} */ function step() { // Back to the first iterator. if (index === count - 1) { index = -1; } // Go to the next iterator. index++; // Ignore empty iterators. while(empties.has(index)) { if (index === count - 1) { index = -1; } index++; } return iterators[index]; } /** * Returns next value. * * @returns {{done: boolean, value: *}} */ function next() { // Exit if all iterators are traversed. if (empties.size === count) { return done; } // Go to the next iterator. const iter = step(); const res = iter.next(); // Mark iterator as empty and go to the next. if (res.done) { empties.add(index); return next(); } return res; } return { next, [Symbol.iterator]() { return this; } }; }
[ "function", "evenly", "(", "iterables", ")", "{", "const", "iterators", "=", "iterables", ".", "map", "(", "iterable", "=>", "createIterator", "(", "iterable", ",", "{", "strict", ":", "false", "}", ")", ")", ";", "const", "empties", "=", "new", "Set", "(", ")", ";", "const", "count", "=", "iterators", ".", "length", ";", "let", "index", "=", "-", "1", ";", "function", "step", "(", ")", "{", "if", "(", "index", "===", "count", "-", "1", ")", "{", "index", "=", "-", "1", ";", "}", "index", "++", ";", "while", "(", "empties", ".", "has", "(", "index", ")", ")", "{", "if", "(", "index", "===", "count", "-", "1", ")", "{", "index", "=", "-", "1", ";", "}", "index", "++", ";", "}", "return", "iterators", "[", "index", "]", ";", "}", "function", "next", "(", ")", "{", "if", "(", "empties", ".", "size", "===", "count", ")", "{", "return", "done", ";", "}", "const", "iter", "=", "step", "(", ")", ";", "const", "res", "=", "iter", ".", "next", "(", ")", ";", "if", "(", "res", ".", "done", ")", "{", "empties", ".", "add", "(", "index", ")", ";", "return", "next", "(", ")", ";", "}", "return", "res", ";", "}", "return", "{", "next", ",", "[", "Symbol", ".", "iterator", "]", "(", ")", "{", "return", "this", ";", "}", "}", ";", "}" ]
Returns an Iterator, that traverses iterators evenly. This is reminiscent of the traversing of several arrays @example const evenly = require('ho-iter').evenly; const arr1 = [1, 2]; const arr2 = [3, 4]; const set1 = new Set([1, 2]); const set2 = new Set([3, 4]); for (let i = 0; i < arr1.length; i++) { console.log(arr1[i]); console.log(arr2[i]); } // 1 3 2 4 for (let item of evenly(set1, set2)) { console.log(item); } // 1 3 2 4 @param {Iterable[]} iterables - iterable objects or iterators. @returns {Iterator}
[ "Returns", "an", "Iterator", "that", "traverses", "iterators", "evenly", "." ]
b68a4b8585a4b34aed3e9e3a138391c02999d687
https://github.com/blond/ho-iter/blob/b68a4b8585a4b34aed3e9e3a138391c02999d687/lib/evenly.js#L38-L100
train
blond/ho-iter
lib/evenly.js
step
function step() { // Back to the first iterator. if (index === count - 1) { index = -1; } // Go to the next iterator. index++; // Ignore empty iterators. while(empties.has(index)) { if (index === count - 1) { index = -1; } index++; } return iterators[index]; }
javascript
function step() { // Back to the first iterator. if (index === count - 1) { index = -1; } // Go to the next iterator. index++; // Ignore empty iterators. while(empties.has(index)) { if (index === count - 1) { index = -1; } index++; } return iterators[index]; }
[ "function", "step", "(", ")", "{", "if", "(", "index", "===", "count", "-", "1", ")", "{", "index", "=", "-", "1", ";", "}", "index", "++", ";", "while", "(", "empties", ".", "has", "(", "index", ")", ")", "{", "if", "(", "index", "===", "count", "-", "1", ")", "{", "index", "=", "-", "1", ";", "}", "index", "++", ";", "}", "return", "iterators", "[", "index", "]", ";", "}" ]
Returns next iterator. Returns the first iterator after the last one. @returns {Iterator}
[ "Returns", "next", "iterator", "." ]
b68a4b8585a4b34aed3e9e3a138391c02999d687
https://github.com/blond/ho-iter/blob/b68a4b8585a4b34aed3e9e3a138391c02999d687/lib/evenly.js#L52-L71
train
blond/ho-iter
lib/evenly.js
next
function next() { // Exit if all iterators are traversed. if (empties.size === count) { return done; } // Go to the next iterator. const iter = step(); const res = iter.next(); // Mark iterator as empty and go to the next. if (res.done) { empties.add(index); return next(); } return res; }
javascript
function next() { // Exit if all iterators are traversed. if (empties.size === count) { return done; } // Go to the next iterator. const iter = step(); const res = iter.next(); // Mark iterator as empty and go to the next. if (res.done) { empties.add(index); return next(); } return res; }
[ "function", "next", "(", ")", "{", "if", "(", "empties", ".", "size", "===", "count", ")", "{", "return", "done", ";", "}", "const", "iter", "=", "step", "(", ")", ";", "const", "res", "=", "iter", ".", "next", "(", ")", ";", "if", "(", "res", ".", "done", ")", "{", "empties", ".", "add", "(", "index", ")", ";", "return", "next", "(", ")", ";", "}", "return", "res", ";", "}" ]
Returns next value. @returns {{done: boolean, value: *}}
[ "Returns", "next", "value", "." ]
b68a4b8585a4b34aed3e9e3a138391c02999d687
https://github.com/blond/ho-iter/blob/b68a4b8585a4b34aed3e9e3a138391c02999d687/lib/evenly.js#L78-L97
train
blond/ho-iter
lib/series.js
series
function series(iterables) { if (iterables.length === 0) { return createIterator(); } let iter = createIterator(iterables.shift(), { strict: false }); return { [Symbol.iterator]() { return this; }, next() { let next = iter.next(); // If iterator is ended go to the next. // If next iterator is empty (is ended) go to the next, // until you get not empty iterator, or all iterators are ended. while (next.done) { // If iterators are ended, then exit. if (iterables.length === 0) { return done; } iter = createIterator(iterables.shift(), { strict: false }); next = iter.next(); } return next; } }; }
javascript
function series(iterables) { if (iterables.length === 0) { return createIterator(); } let iter = createIterator(iterables.shift(), { strict: false }); return { [Symbol.iterator]() { return this; }, next() { let next = iter.next(); // If iterator is ended go to the next. // If next iterator is empty (is ended) go to the next, // until you get not empty iterator, or all iterators are ended. while (next.done) { // If iterators are ended, then exit. if (iterables.length === 0) { return done; } iter = createIterator(iterables.shift(), { strict: false }); next = iter.next(); } return next; } }; }
[ "function", "series", "(", "iterables", ")", "{", "if", "(", "iterables", ".", "length", "===", "0", ")", "{", "return", "createIterator", "(", ")", ";", "}", "let", "iter", "=", "createIterator", "(", "iterables", ".", "shift", "(", ")", ",", "{", "strict", ":", "false", "}", ")", ";", "return", "{", "[", "Symbol", ".", "iterator", "]", "(", ")", "{", "return", "this", ";", "}", ",", "next", "(", ")", "{", "let", "next", "=", "iter", ".", "next", "(", ")", ";", "while", "(", "next", ".", "done", ")", "{", "if", "(", "iterables", ".", "length", "===", "0", ")", "{", "return", "done", ";", "}", "iter", "=", "createIterator", "(", "iterables", ".", "shift", "(", ")", ",", "{", "strict", ":", "false", "}", ")", ";", "next", "=", "iter", ".", "next", "(", ")", ";", "}", "return", "next", ";", "}", "}", ";", "}" ]
Returns an Iterator, that traverses iterators in series. This is reminiscent of the concatenation of arrays. @example ```js const series = require('ho-iter').series; const arr1 = [1, 2]; const arr2 = [3, 4]; const set1 = new Set([1, 2]); const set2 = new Set([3, 4]); [].concat(arr1, arr2); // [1, 2, 3, 4] for (let item of series(set1, set2)) { console.log(item); } // 1 2 3 4 ``` @param {Iterable[]} iterables - iterable objects or iterators. @returns {Iterator}
[ "Returns", "an", "Iterator", "that", "traverses", "iterators", "in", "series", "." ]
b68a4b8585a4b34aed3e9e3a138391c02999d687
https://github.com/blond/ho-iter/blob/b68a4b8585a4b34aed3e9e3a138391c02999d687/lib/series.js#L35-L64
train
Kronos-Integration/kronos-interceptor-http-request
src/transport-multipart-interceptor.js
transformMessageToRequestMessage
function transformMessageToRequestMessage(message) { const newMessage = { info: message.info, hops: message.hops }; let payload; if (message.payload === 'string') { payload = message.payload; } else if (message.payload instanceof stream.Stream) { payload = message.payload; } else { // expect that it is JSON payload = JSON.stringify(message.payload); } // make the message a form const formData = new FormData(); if (message.info) { formData.append('info', JSON.stringify(message.info)); } if (message.hops) { formData.append('hops', JSON.stringify(message.hops)); } if (payload) { formData.append('payload', payload); } newMessage.payload = formData; return newMessage; }
javascript
function transformMessageToRequestMessage(message) { const newMessage = { info: message.info, hops: message.hops }; let payload; if (message.payload === 'string') { payload = message.payload; } else if (message.payload instanceof stream.Stream) { payload = message.payload; } else { // expect that it is JSON payload = JSON.stringify(message.payload); } // make the message a form const formData = new FormData(); if (message.info) { formData.append('info', JSON.stringify(message.info)); } if (message.hops) { formData.append('hops', JSON.stringify(message.hops)); } if (payload) { formData.append('payload', payload); } newMessage.payload = formData; return newMessage; }
[ "function", "transformMessageToRequestMessage", "(", "message", ")", "{", "const", "newMessage", "=", "{", "info", ":", "message", ".", "info", ",", "hops", ":", "message", ".", "hops", "}", ";", "let", "payload", ";", "if", "(", "message", ".", "payload", "===", "'string'", ")", "{", "payload", "=", "message", ".", "payload", ";", "}", "else", "if", "(", "message", ".", "payload", "instanceof", "stream", ".", "Stream", ")", "{", "payload", "=", "message", ".", "payload", ";", "}", "else", "{", "payload", "=", "JSON", ".", "stringify", "(", "message", ".", "payload", ")", ";", "}", "const", "formData", "=", "new", "FormData", "(", ")", ";", "if", "(", "message", ".", "info", ")", "{", "formData", ".", "append", "(", "'info'", ",", "JSON", ".", "stringify", "(", "message", ".", "info", ")", ")", ";", "}", "if", "(", "message", ".", "hops", ")", "{", "formData", ".", "append", "(", "'hops'", ",", "JSON", ".", "stringify", "(", "message", ".", "hops", ")", ")", ";", "}", "if", "(", "payload", ")", "{", "formData", ".", "append", "(", "'payload'", ",", "payload", ")", ";", "}", "newMessage", ".", "payload", "=", "formData", ";", "return", "newMessage", ";", "}" ]
Copies the fields 'info' and 'hops' into the new message. Then create a formdata object containing 'info', 'hops' and 'payload'. Stores the formdata object as the payload of the 'newMessage' object. @param message The message to transform @return newMessage The transformed message
[ "Copies", "the", "fields", "info", "and", "hops", "into", "the", "new", "message", ".", "Then", "create", "a", "formdata", "object", "containing", "info", "hops", "and", "payload", ".", "Stores", "the", "formdata", "object", "as", "the", "payload", "of", "the", "newMessage", "object", "." ]
ed8530ac28ca1bfbef9833fb00915b535bcbe966
https://github.com/Kronos-Integration/kronos-interceptor-http-request/blob/ed8530ac28ca1bfbef9833fb00915b535bcbe966/src/transport-multipart-interceptor.js#L14-L45
train
Kronos-Integration/kronos-interceptor-http-request
src/transport-multipart-interceptor.js
unpackToMessage
function unpackToMessage(request, forwardFunction) { const busboy = new Busboy({ headers: request.headers }); return new Promise((resolve, reject) => { // the message which will be forwarded const newMessage = {}; let resultPromise; busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { if (fieldname === 'payload') { // This is a stream payload newMessage.payload = file; if (forwardFunction) { resolve(forwardFunction(newMessage)); } else { resolve(newMessage); } } }); busboy.on('field', function( fieldname, val, fieldnameTruncated, valTruncated ) { if ( fieldname === 'info' || fieldname === 'hops' || fieldname === 'payload' ) { newMessage[fieldname] = JSON.parse(val); } }); request.pipe(busboy); }); }
javascript
function unpackToMessage(request, forwardFunction) { const busboy = new Busboy({ headers: request.headers }); return new Promise((resolve, reject) => { // the message which will be forwarded const newMessage = {}; let resultPromise; busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { if (fieldname === 'payload') { // This is a stream payload newMessage.payload = file; if (forwardFunction) { resolve(forwardFunction(newMessage)); } else { resolve(newMessage); } } }); busboy.on('field', function( fieldname, val, fieldnameTruncated, valTruncated ) { if ( fieldname === 'info' || fieldname === 'hops' || fieldname === 'payload' ) { newMessage[fieldname] = JSON.parse(val); } }); request.pipe(busboy); }); }
[ "function", "unpackToMessage", "(", "request", ",", "forwardFunction", ")", "{", "const", "busboy", "=", "new", "Busboy", "(", "{", "headers", ":", "request", ".", "headers", "}", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "newMessage", "=", "{", "}", ";", "let", "resultPromise", ";", "busboy", ".", "on", "(", "'file'", ",", "function", "(", "fieldname", ",", "file", ",", "filename", ",", "encoding", ",", "mimetype", ")", "{", "if", "(", "fieldname", "===", "'payload'", ")", "{", "newMessage", ".", "payload", "=", "file", ";", "if", "(", "forwardFunction", ")", "{", "resolve", "(", "forwardFunction", "(", "newMessage", ")", ")", ";", "}", "else", "{", "resolve", "(", "newMessage", ")", ";", "}", "}", "}", ")", ";", "busboy", ".", "on", "(", "'field'", ",", "function", "(", "fieldname", ",", "val", ",", "fieldnameTruncated", ",", "valTruncated", ")", "{", "if", "(", "fieldname", "===", "'info'", "||", "fieldname", "===", "'hops'", "||", "fieldname", "===", "'payload'", ")", "{", "newMessage", "[", "fieldname", "]", "=", "JSON", ".", "parse", "(", "val", ")", ";", "}", "}", ")", ";", "request", ".", "pipe", "(", "busboy", ")", ";", "}", ")", ";", "}" ]
Unpacks a message from a multipart http request @param request The incomming http request @param forwardFunction The function to call with the new generated message. The function must return a Promise. If no 'forwardFunction' is given It will return the message in the promise @return Promise A promise with the result of the forwardFunction
[ "Unpacks", "a", "message", "from", "a", "multipart", "http", "request" ]
ed8530ac28ca1bfbef9833fb00915b535bcbe966
https://github.com/Kronos-Integration/kronos-interceptor-http-request/blob/ed8530ac28ca1bfbef9833fb00915b535bcbe966/src/transport-multipart-interceptor.js#L87-L127
train
reboundjs/rebound
packages/rebound-htmlbars/lib/render.js
function(arr){ var i, len = arr.length; this.added || (this.added = {}); arr.forEach((item) => { if(this.added[item.cid]){ return; } this.added[item.cid] = 1; if(item.isLazyValue){ item.makeDirty(); } this.push(item); }); }
javascript
function(arr){ var i, len = arr.length; this.added || (this.added = {}); arr.forEach((item) => { if(this.added[item.cid]){ return; } this.added[item.cid] = 1; if(item.isLazyValue){ item.makeDirty(); } this.push(item); }); }
[ "function", "(", "arr", ")", "{", "var", "i", ",", "len", "=", "arr", ".", "length", ";", "this", ".", "added", "||", "(", "this", ".", "added", "=", "{", "}", ")", ";", "arr", ".", "forEach", "(", "(", "item", ")", "=>", "{", "if", "(", "this", ".", "added", "[", "item", ".", "cid", "]", ")", "{", "return", ";", "}", "this", ".", "added", "[", "item", ".", "cid", "]", "=", "1", ";", "if", "(", "item", ".", "isLazyValue", ")", "{", "item", ".", "makeDirty", "(", ")", ";", "}", "this", ".", "push", "(", "item", ")", ";", "}", ")", ";", "}" ]
A convenience method to push only unique eleents in an array of objects to the TO_RENDER queue. If the element is a Lazy Value, it marks it as dirty in the process
[ "A", "convenience", "method", "to", "push", "only", "unique", "eleents", "in", "an", "array", "of", "objects", "to", "the", "TO_RENDER", "queue", ".", "If", "the", "element", "is", "a", "Lazy", "Value", "it", "marks", "it", "as", "dirty", "in", "the", "process" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-htmlbars/lib/render.js#L12-L21
train
reboundjs/rebound
packages/rebound-htmlbars/lib/render.js
onReset
function onReset(data, options){ trigger.call(this, 'reset', data, data.isModel ? data.changedAttributes() : { '@each': data }, options); }
javascript
function onReset(data, options){ trigger.call(this, 'reset', data, data.isModel ? data.changedAttributes() : { '@each': data }, options); }
[ "function", "onReset", "(", "data", ",", "options", ")", "{", "trigger", ".", "call", "(", "this", ",", "'reset'", ",", "data", ",", "data", ".", "isModel", "?", "data", ".", "changedAttributes", "(", ")", ":", "{", "'@each'", ":", "data", "}", ",", "options", ")", ";", "}" ]
Listens for `reset` events and calls `trigger` with the correct values
[ "Listens", "for", "reset", "events", "and", "calls", "trigger", "with", "the", "correct", "values" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-htmlbars/lib/render.js#L83-L85
train
reboundjs/rebound
packages/rebound-data/lib/model.js
function(attributes, options={}){ var self = this; if(attributes === null || attributes === undefined){ attributes = {}; } attributes.isModel && (attributes = attributes.attributes); this.helpers = {}; this.defaults = this.defaults || {}; this.setParent( options.parent || this ); this.setRoot( options.root || this ); this.__path = options.path || this.__path; // Convert getters and setters to computed properties $.extractComputedProps(attributes); Backbone.Model.call( this, attributes, options ); }
javascript
function(attributes, options={}){ var self = this; if(attributes === null || attributes === undefined){ attributes = {}; } attributes.isModel && (attributes = attributes.attributes); this.helpers = {}; this.defaults = this.defaults || {}; this.setParent( options.parent || this ); this.setRoot( options.root || this ); this.__path = options.path || this.__path; // Convert getters and setters to computed properties $.extractComputedProps(attributes); Backbone.Model.call( this, attributes, options ); }
[ "function", "(", "attributes", ",", "options", "=", "{", "}", ")", "{", "var", "self", "=", "this", ";", "if", "(", "attributes", "===", "null", "||", "attributes", "===", "undefined", ")", "{", "attributes", "=", "{", "}", ";", "}", "attributes", ".", "isModel", "&&", "(", "attributes", "=", "attributes", ".", "attributes", ")", ";", "this", ".", "helpers", "=", "{", "}", ";", "this", ".", "defaults", "=", "this", ".", "defaults", "||", "{", "}", ";", "this", ".", "setParent", "(", "options", ".", "parent", "||", "this", ")", ";", "this", ".", "setRoot", "(", "options", ".", "root", "||", "this", ")", ";", "this", ".", "__path", "=", "options", ".", "path", "||", "this", ".", "__path", ";", "$", ".", "extractComputedProps", "(", "attributes", ")", ";", "Backbone", ".", "Model", ".", "call", "(", "this", ",", "attributes", ",", "options", ")", ";", "}" ]
Create a new Model with the specified attributes. The Model's lineage is set up here to keep track of it's place in the data tree.
[ "Create", "a", "new", "Model", "with", "the", "specified", "attributes", ".", "The", "Model", "s", "lineage", "is", "set", "up", "here", "to", "keep", "track", "of", "it", "s", "place", "in", "the", "data", "tree", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/model.js#L36-L51
train
reboundjs/rebound
packages/rebound-data/lib/model.js
function(attr, options) { options = options ? _.clone(options) : {}; var val = this.get(attr); if(!_.isBoolean(val)) console.error('Tried to toggle non-boolean value ' + attr +'!', this); return this.set(attr, !val, options); }
javascript
function(attr, options) { options = options ? _.clone(options) : {}; var val = this.get(attr); if(!_.isBoolean(val)) console.error('Tried to toggle non-boolean value ' + attr +'!', this); return this.set(attr, !val, options); }
[ "function", "(", "attr", ",", "options", ")", "{", "options", "=", "options", "?", "_", ".", "clone", "(", "options", ")", ":", "{", "}", ";", "var", "val", "=", "this", ".", "get", "(", "attr", ")", ";", "if", "(", "!", "_", ".", "isBoolean", "(", "val", ")", ")", "console", ".", "error", "(", "'Tried to toggle non-boolean value '", "+", "attr", "+", "'!'", ",", "this", ")", ";", "return", "this", ".", "set", "(", "attr", ",", "!", "val", ",", "options", ")", ";", "}" ]
New convenience function to toggle boolean values in the Model.
[ "New", "convenience", "function", "to", "toggle", "boolean", "values", "in", "the", "Model", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/model.js#L54-L59
train
reboundjs/rebound
packages/rebound-data/lib/model.js
function(obj, options){ var changed = {}, key, value; options || (options = {}); options.reset = true; obj = (obj && obj.isModel && obj.attributes) || obj || {}; options.previousAttributes = _.clone(this.attributes); // Any unset previously existing values will be set back to default _.each(this.defaults, function(val, key){ if(!obj.hasOwnProperty(key)){ obj[key] = val; } }, this); // Iterate over the Model's attributes: // - If the property is the `idAttribute`, skip. // - If the properties are already the same, skip // - If the property is currently undefined and being changed, assign // - If the property is a `Model`, `Collection`, or `ComputedProperty`, reset it. // - If the passed object has the property, set it to the new value. // - If the Model has a default value for this property, set it back to default. // - Otherwise, unset the attribute. for(key in this.attributes){ value = this.attributes[key]; if(value === obj[key]){ continue; } else if(_.isUndefined(value) && !_.isUndefined(obj[key])){ changed[key] = obj[key]; } else if (value.isComponent){ continue; } else if (value.isCollection || value.isModel || value.isComputedProperty){ value.reset((obj[key] || []), {silent: true}); if(value.isCollection) changed[key] = value.previousModels; else if(value.isModel && value.isComputedProperty) changed[key] = value.cache.model.changedAttributes(); else if(value.isModel) changed[key] = value.changedAttributes(); } else if (obj.hasOwnProperty(key)){ changed[key] = obj[key]; } else{ changed[key] = undefined; this.unset(key, {silent: true}); } } // Any new values will be set to on the model _.each(obj, function(val, key){ if(_.isUndefined(changed[key])){ changed[key] = val; } }); // Reset our model obj = this.set(obj, _.extend({}, options, {silent: true, reset: false})); // Trigger custom reset event this.changed = changed; if (!options.silent){ this.trigger('reset', this, options); } // Return new values return obj; }
javascript
function(obj, options){ var changed = {}, key, value; options || (options = {}); options.reset = true; obj = (obj && obj.isModel && obj.attributes) || obj || {}; options.previousAttributes = _.clone(this.attributes); // Any unset previously existing values will be set back to default _.each(this.defaults, function(val, key){ if(!obj.hasOwnProperty(key)){ obj[key] = val; } }, this); // Iterate over the Model's attributes: // - If the property is the `idAttribute`, skip. // - If the properties are already the same, skip // - If the property is currently undefined and being changed, assign // - If the property is a `Model`, `Collection`, or `ComputedProperty`, reset it. // - If the passed object has the property, set it to the new value. // - If the Model has a default value for this property, set it back to default. // - Otherwise, unset the attribute. for(key in this.attributes){ value = this.attributes[key]; if(value === obj[key]){ continue; } else if(_.isUndefined(value) && !_.isUndefined(obj[key])){ changed[key] = obj[key]; } else if (value.isComponent){ continue; } else if (value.isCollection || value.isModel || value.isComputedProperty){ value.reset((obj[key] || []), {silent: true}); if(value.isCollection) changed[key] = value.previousModels; else if(value.isModel && value.isComputedProperty) changed[key] = value.cache.model.changedAttributes(); else if(value.isModel) changed[key] = value.changedAttributes(); } else if (obj.hasOwnProperty(key)){ changed[key] = obj[key]; } else{ changed[key] = undefined; this.unset(key, {silent: true}); } } // Any new values will be set to on the model _.each(obj, function(val, key){ if(_.isUndefined(changed[key])){ changed[key] = val; } }); // Reset our model obj = this.set(obj, _.extend({}, options, {silent: true, reset: false})); // Trigger custom reset event this.changed = changed; if (!options.silent){ this.trigger('reset', this, options); } // Return new values return obj; }
[ "function", "(", "obj", ",", "options", ")", "{", "var", "changed", "=", "{", "}", ",", "key", ",", "value", ";", "options", "||", "(", "options", "=", "{", "}", ")", ";", "options", ".", "reset", "=", "true", ";", "obj", "=", "(", "obj", "&&", "obj", ".", "isModel", "&&", "obj", ".", "attributes", ")", "||", "obj", "||", "{", "}", ";", "options", ".", "previousAttributes", "=", "_", ".", "clone", "(", "this", ".", "attributes", ")", ";", "_", ".", "each", "(", "this", ".", "defaults", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "!", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "obj", "[", "key", "]", "=", "val", ";", "}", "}", ",", "this", ")", ";", "for", "(", "key", "in", "this", ".", "attributes", ")", "{", "value", "=", "this", ".", "attributes", "[", "key", "]", ";", "if", "(", "value", "===", "obj", "[", "key", "]", ")", "{", "continue", ";", "}", "else", "if", "(", "_", ".", "isUndefined", "(", "value", ")", "&&", "!", "_", ".", "isUndefined", "(", "obj", "[", "key", "]", ")", ")", "{", "changed", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "else", "if", "(", "value", ".", "isComponent", ")", "{", "continue", ";", "}", "else", "if", "(", "value", ".", "isCollection", "||", "value", ".", "isModel", "||", "value", ".", "isComputedProperty", ")", "{", "value", ".", "reset", "(", "(", "obj", "[", "key", "]", "||", "[", "]", ")", ",", "{", "silent", ":", "true", "}", ")", ";", "if", "(", "value", ".", "isCollection", ")", "changed", "[", "key", "]", "=", "value", ".", "previousModels", ";", "else", "if", "(", "value", ".", "isModel", "&&", "value", ".", "isComputedProperty", ")", "changed", "[", "key", "]", "=", "value", ".", "cache", ".", "model", ".", "changedAttributes", "(", ")", ";", "else", "if", "(", "value", ".", "isModel", ")", "changed", "[", "key", "]", "=", "value", ".", "changedAttributes", "(", ")", ";", "}", "else", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "changed", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "else", "{", "changed", "[", "key", "]", "=", "undefined", ";", "this", ".", "unset", "(", "key", ",", "{", "silent", ":", "true", "}", ")", ";", "}", "}", "_", ".", "each", "(", "obj", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "changed", "[", "key", "]", ")", ")", "{", "changed", "[", "key", "]", "=", "val", ";", "}", "}", ")", ";", "obj", "=", "this", ".", "set", "(", "obj", ",", "_", ".", "extend", "(", "{", "}", ",", "options", ",", "{", "silent", ":", "true", ",", "reset", ":", "false", "}", ")", ")", ";", "this", ".", "changed", "=", "changed", ";", "if", "(", "!", "options", ".", "silent", ")", "{", "this", ".", "trigger", "(", "'reset'", ",", "this", ",", "options", ")", ";", "}", "return", "obj", ";", "}" ]
Model Reset does a deep reset on the data tree starting at this Model. A `previousAttributes` property is set on the `options` property with the Model's old values.
[ "Model", "Reset", "does", "a", "deep", "reset", "on", "the", "data", "tree", "starting", "at", "this", "Model", ".", "A", "previousAttributes", "property", "is", "set", "on", "the", "options", "property", "with", "the", "Model", "s", "old", "values", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/model.js#L91-L143
train
reboundjs/rebound
packages/rebound-data/lib/model.js
function() { if (this._isSerializing){ return this.id || this.cid; } this._isSerializing = true; var json = _.clone(this.attributes); _.each(json, function(value, name) { if( _.isNull(value) || _.isUndefined(value) ){ return void 0; } _.isFunction(value.toJSON) && (json[name] = value.toJSON()); }); this._isSerializing = false; return json; }
javascript
function() { if (this._isSerializing){ return this.id || this.cid; } this._isSerializing = true; var json = _.clone(this.attributes); _.each(json, function(value, name) { if( _.isNull(value) || _.isUndefined(value) ){ return void 0; } _.isFunction(value.toJSON) && (json[name] = value.toJSON()); }); this._isSerializing = false; return json; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "_isSerializing", ")", "{", "return", "this", ".", "id", "||", "this", ".", "cid", ";", "}", "this", ".", "_isSerializing", "=", "true", ";", "var", "json", "=", "_", ".", "clone", "(", "this", ".", "attributes", ")", ";", "_", ".", "each", "(", "json", ",", "function", "(", "value", ",", "name", ")", "{", "if", "(", "_", ".", "isNull", "(", "value", ")", "||", "_", ".", "isUndefined", "(", "value", ")", ")", "{", "return", "void", "0", ";", "}", "_", ".", "isFunction", "(", "value", ".", "toJSON", ")", "&&", "(", "json", "[", "name", "]", "=", "value", ".", "toJSON", "(", ")", ")", ";", "}", ")", ";", "this", ".", "_isSerializing", "=", "false", ";", "return", "json", ";", "}" ]
Recursive `toJSON` function traverses the data tree returning a JSON object. If there are any cyclic dependancies the object's `cid` is used instead of looping infinitely.
[ "Recursive", "toJSON", "function", "traverses", "the", "data", "tree", "returning", "a", "JSON", "object", ".", "If", "there", "are", "any", "cyclic", "dependancies", "the", "object", "s", "cid", "is", "used", "instead", "of", "looping", "infinitely", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/model.js#L283-L293
train
litixsoft/generator-baboon
app/templates/_Gruntfile.js
getCoverageReport
function getCoverageReport (folder) { var reports = grunt.file.expand(folder + '*/index.html'); if (reports && reports.length > 0) { return reports[0]; } return ''; }
javascript
function getCoverageReport (folder) { var reports = grunt.file.expand(folder + '*/index.html'); if (reports && reports.length > 0) { return reports[0]; } return ''; }
[ "function", "getCoverageReport", "(", "folder", ")", "{", "var", "reports", "=", "grunt", ".", "file", ".", "expand", "(", "folder", "+", "'*/index.html'", ")", ";", "if", "(", "reports", "&&", "reports", ".", "length", ">", "0", ")", "{", "return", "reports", "[", "0", "]", ";", "}", "return", "''", ";", "}" ]
Gets the index.html file from the code coverage folder. @param {!string} folder The path to the code coverage folder.
[ "Gets", "the", "index", ".", "html", "file", "from", "the", "code", "coverage", "folder", "." ]
37282a92f3c1d2945c01b5c4a45f9b11528e99a1
https://github.com/litixsoft/generator-baboon/blob/37282a92f3c1d2945c01b5c4a45f9b11528e99a1/app/templates/_Gruntfile.js#L13-L21
train
MRN-Code/bookshelf-shield
lib/main.js
getAuthConfigs
function getAuthConfigs(modelName) { return _.filter(internals.authConfig, function hasSameModelName(c) { return c.defaults.modelName === modelName; }); }
javascript
function getAuthConfigs(modelName) { return _.filter(internals.authConfig, function hasSameModelName(c) { return c.defaults.modelName === modelName; }); }
[ "function", "getAuthConfigs", "(", "modelName", ")", "{", "return", "_", ".", "filter", "(", "internals", ".", "authConfig", ",", "function", "hasSameModelName", "(", "c", ")", "{", "return", "c", ".", "defaults", ".", "modelName", "===", "modelName", ";", "}", ")", ";", "}" ]
Shortcut to get auth configs that apply to a given model @param {string} modelName is the name of the model @return {array} an array of matching configs
[ "Shortcut", "to", "get", "auth", "configs", "that", "apply", "to", "a", "given", "model" ]
4f13ed22e3f951b3e7733823841c7bf9ef88df0b
https://github.com/MRN-Code/bookshelf-shield/blob/4f13ed22e3f951b3e7733823841c7bf9ef88df0b/lib/main.js#L17-L21
train
MRN-Code/bookshelf-shield
lib/main.js
setModel
function setModel(Model, modelName) { let authConfigs; if (!internals.acl) { throw new Error('Attempt to shield model before setting acl'); } if (!internals.authConfig.length) { throw new Error('Attempt to shield model before seting configs'); } // raise shield around Model new Shield(Model, internals.acl); authConfigs = getAuthConfigs(modelName); _.each(authConfigs, _.bind(Model.shield.addRules, Model.shield)); internals.models[modelName] = Model; }
javascript
function setModel(Model, modelName) { let authConfigs; if (!internals.acl) { throw new Error('Attempt to shield model before setting acl'); } if (!internals.authConfig.length) { throw new Error('Attempt to shield model before seting configs'); } // raise shield around Model new Shield(Model, internals.acl); authConfigs = getAuthConfigs(modelName); _.each(authConfigs, _.bind(Model.shield.addRules, Model.shield)); internals.models[modelName] = Model; }
[ "function", "setModel", "(", "Model", ",", "modelName", ")", "{", "let", "authConfigs", ";", "if", "(", "!", "internals", ".", "acl", ")", "{", "throw", "new", "Error", "(", "'Attempt to shield model before setting acl'", ")", ";", "}", "if", "(", "!", "internals", ".", "authConfig", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Attempt to shield model before seting configs'", ")", ";", "}", "new", "Shield", "(", "Model", ",", "internals", ".", "acl", ")", ";", "authConfigs", "=", "getAuthConfigs", "(", "modelName", ")", ";", "_", ".", "each", "(", "authConfigs", ",", "_", ".", "bind", "(", "Model", ".", "shield", ".", "addRules", ",", "Model", ".", "shield", ")", ")", ";", "internals", ".", "models", "[", "modelName", "]", "=", "Model", ";", "}" ]
Set an individual model on the internal scope after wrapping it with a shield @param {bookshelfModel} Model is a bookshelf Model constructor @return null;
[ "Set", "an", "individual", "model", "on", "the", "internal", "scope", "after", "wrapping", "it", "with", "a", "shield" ]
4f13ed22e3f951b3e7733823841c7bf9ef88df0b
https://github.com/MRN-Code/bookshelf-shield/blob/4f13ed22e3f951b3e7733823841c7bf9ef88df0b/lib/main.js#L28-L43
train
MRN-Code/bookshelf-shield
lib/main.js
validate
function validate(options) { const schema = joi.object().keys({ config: joi.array().min(_.keys(options.models).length).required(), acl: joi.object().required(), models: joi.object().required() }); joi.assert(options, schema, 'Invalid Shield Options:'); return true; }
javascript
function validate(options) { const schema = joi.object().keys({ config: joi.array().min(_.keys(options.models).length).required(), acl: joi.object().required(), models: joi.object().required() }); joi.assert(options, schema, 'Invalid Shield Options:'); return true; }
[ "function", "validate", "(", "options", ")", "{", "const", "schema", "=", "joi", ".", "object", "(", ")", ".", "keys", "(", "{", "config", ":", "joi", ".", "array", "(", ")", ".", "min", "(", "_", ".", "keys", "(", "options", ".", "models", ")", ".", "length", ")", ".", "required", "(", ")", ",", "acl", ":", "joi", ".", "object", "(", ")", ".", "required", "(", ")", ",", "models", ":", "joi", ".", "object", "(", ")", ".", "required", "(", ")", "}", ")", ";", "joi", ".", "assert", "(", "options", ",", "schema", ",", "'Invalid Shield Options:'", ")", ";", "return", "true", ";", "}" ]
Validate that the all inputs are properly specified
[ "Validate", "that", "the", "all", "inputs", "are", "properly", "specified" ]
4f13ed22e3f951b3e7733823841c7bf9ef88df0b
https://github.com/MRN-Code/bookshelf-shield/blob/4f13ed22e3f951b3e7733823841c7bf9ef88df0b/lib/main.js#L75-L83
train
MRN-Code/bookshelf-shield
lib/main.js
init
function init(options) { validate(options); setAuthConfig(options.config); setAcl(options.acl); setModels(options.models); }
javascript
function init(options) { validate(options); setAuthConfig(options.config); setAcl(options.acl); setModels(options.models); }
[ "function", "init", "(", "options", ")", "{", "validate", "(", "options", ")", ";", "setAuthConfig", "(", "options", ".", "config", ")", ";", "setAcl", "(", "options", ".", "acl", ")", ";", "setModels", "(", "options", ".", "models", ")", ";", "}" ]
Main initialization method @param {object} options is an object with keys for: config: the authConfig detailing rules for each model models: an object containing modelName: Model key pairs acl: the Action Control List object containing methods for each context @return {null} the shield internals are private
[ "Main", "initialization", "method" ]
4f13ed22e3f951b3e7733823841c7bf9ef88df0b
https://github.com/MRN-Code/bookshelf-shield/blob/4f13ed22e3f951b3e7733823841c7bf9ef88df0b/lib/main.js#L93-L98
train
audio-lab/lab
plugin/radio.js
Radio
function Radio (url) { var self = this; Block.apply(self, arguments); self.audio = document.createElement('audio'); self.audio.autoplay = true; self.audio.src = self.url; self.node = self.app.context.createMediaElementSource(self.audio); self.audio.play(); //show code in textarea self.input = q('input', self.content); self.input.value = self.url; //update url on(self.input, 'change', function () { self.audio.src = self.input.value; }); //go ready state self.state = 'ready'; }
javascript
function Radio (url) { var self = this; Block.apply(self, arguments); self.audio = document.createElement('audio'); self.audio.autoplay = true; self.audio.src = self.url; self.node = self.app.context.createMediaElementSource(self.audio); self.audio.play(); //show code in textarea self.input = q('input', self.content); self.input.value = self.url; //update url on(self.input, 'change', function () { self.audio.src = self.input.value; }); //go ready state self.state = 'ready'; }
[ "function", "Radio", "(", "url", ")", "{", "var", "self", "=", "this", ";", "Block", ".", "apply", "(", "self", ",", "arguments", ")", ";", "self", ".", "audio", "=", "document", ".", "createElement", "(", "'audio'", ")", ";", "self", ".", "audio", ".", "autoplay", "=", "true", ";", "self", ".", "audio", ".", "src", "=", "self", ".", "url", ";", "self", ".", "node", "=", "self", ".", "app", ".", "context", ".", "createMediaElementSource", "(", "self", ".", "audio", ")", ";", "self", ".", "audio", ".", "play", "(", ")", ";", "self", ".", "input", "=", "q", "(", "'input'", ",", "self", ".", "content", ")", ";", "self", ".", "input", ".", "value", "=", "self", ".", "url", ";", "on", "(", "self", ".", "input", ",", "'change'", ",", "function", "(", ")", "{", "self", ".", "audio", ".", "src", "=", "self", ".", "input", ".", "value", ";", "}", ")", ";", "self", ".", "state", "=", "'ready'", ";", "}" ]
Create internet radio source based of url passed @constructor
[ "Create", "internet", "radio", "source", "based", "of", "url", "passed" ]
ec5b40d48e36be179dffbfd23ba666c1bc2e9416
https://github.com/audio-lab/lab/blob/ec5b40d48e36be179dffbfd23ba666c1bc2e9416/plugin/radio.js#L17-L40
train
hammy2899/o
src/keys.js
keys
function keys(object, follow = false) { // check if the object is an object and it's not empty if (is(object) && !empty(object)) { // create an empty array for the result let result = []; // if follow is enabled if (follow) { // create a new function which gets the keys and // adds them with dot notation to the results array const followKeys = (obj, currentPath) => { // get all the keys for the inner object Object.keys(obj).forEach((key) => { // parse the dot notation path const followPath = `${currentPath}.${key}`; // if the result is an object run the function again // for that object if (is(obj[key]) && !empty(obj[key])) { // the value is an object so run the function again // for that object but with the new path followKeys(obj[key], followPath); } // add the new parsed path to the result object result.push(followPath); }); }; // for each key in the specified object Object.keys(object).forEach((key) => { // add the key to the results array result.push(key); // if the value of the key is an object add all them keys // to the results array if (is(object[key]) && !empty(object[key])) { // the value is an object so add all them keys also // to the results array followKeys(object[key], key); } }); } else { // if follow isn't enabled just add all the base object keys // to the results array result = Object.keys(object); } // return the results array return result; } // if the object isn't an object or its empty return an empty array return []; }
javascript
function keys(object, follow = false) { // check if the object is an object and it's not empty if (is(object) && !empty(object)) { // create an empty array for the result let result = []; // if follow is enabled if (follow) { // create a new function which gets the keys and // adds them with dot notation to the results array const followKeys = (obj, currentPath) => { // get all the keys for the inner object Object.keys(obj).forEach((key) => { // parse the dot notation path const followPath = `${currentPath}.${key}`; // if the result is an object run the function again // for that object if (is(obj[key]) && !empty(obj[key])) { // the value is an object so run the function again // for that object but with the new path followKeys(obj[key], followPath); } // add the new parsed path to the result object result.push(followPath); }); }; // for each key in the specified object Object.keys(object).forEach((key) => { // add the key to the results array result.push(key); // if the value of the key is an object add all them keys // to the results array if (is(object[key]) && !empty(object[key])) { // the value is an object so add all them keys also // to the results array followKeys(object[key], key); } }); } else { // if follow isn't enabled just add all the base object keys // to the results array result = Object.keys(object); } // return the results array return result; } // if the object isn't an object or its empty return an empty array return []; }
[ "function", "keys", "(", "object", ",", "follow", "=", "false", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", ")", "{", "let", "result", "=", "[", "]", ";", "if", "(", "follow", ")", "{", "const", "followKeys", "=", "(", "obj", ",", "currentPath", ")", "=>", "{", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "const", "followPath", "=", "`", "${", "currentPath", "}", "${", "key", "}", "`", ";", "if", "(", "is", "(", "obj", "[", "key", "]", ")", "&&", "!", "empty", "(", "obj", "[", "key", "]", ")", ")", "{", "followKeys", "(", "obj", "[", "key", "]", ",", "followPath", ")", ";", "}", "result", ".", "push", "(", "followPath", ")", ";", "}", ")", ";", "}", ";", "Object", ".", "keys", "(", "object", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "result", ".", "push", "(", "key", ")", ";", "if", "(", "is", "(", "object", "[", "key", "]", ")", "&&", "!", "empty", "(", "object", "[", "key", "]", ")", ")", "{", "followKeys", "(", "object", "[", "key", "]", ",", "key", ")", ";", "}", "}", ")", ";", "}", "else", "{", "result", "=", "Object", ".", "keys", "(", "object", ")", ";", "}", "return", "result", ";", "}", "return", "[", "]", ";", "}" ]
Get the keys of the specified object @example const a = { a: 1, b: 2, c: 3 }; keys(a); // => ['a', 'b', 'c'] @since 1.0.0 @version 1.0.0 @param {object} object The object to get the keys from @param {boolean} follow Whether to follow objects @returns {string[]} An array of object keys
[ "Get", "the", "keys", "of", "the", "specified", "object" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/keys.js#L20-L71
train
bootprint/customize-engine-handlebars
lib/partial-details.js
hierarchy
function hierarchy (config) { const templates = _.mapValues(config.templates, augmentSingleFile) const partials = _.mapValues(config.partials, augmentSingleFile) return { children: Object.keys(templates).map((name) => { let template = templates[name] return { name: name, type: 'template', path: template.path, comments: template.comments, children: template.callsPartial .map((callee) => callee.name) // Remove redundant names (only take the first one) .filter((name, index, array) => array.indexOf(name) === index) .map((name) => partialForCallTree(name, partials, {})) } }) } }
javascript
function hierarchy (config) { const templates = _.mapValues(config.templates, augmentSingleFile) const partials = _.mapValues(config.partials, augmentSingleFile) return { children: Object.keys(templates).map((name) => { let template = templates[name] return { name: name, type: 'template', path: template.path, comments: template.comments, children: template.callsPartial .map((callee) => callee.name) // Remove redundant names (only take the first one) .filter((name, index, array) => array.indexOf(name) === index) .map((name) => partialForCallTree(name, partials, {})) } }) } }
[ "function", "hierarchy", "(", "config", ")", "{", "const", "templates", "=", "_", ".", "mapValues", "(", "config", ".", "templates", ",", "augmentSingleFile", ")", "const", "partials", "=", "_", ".", "mapValues", "(", "config", ".", "partials", ",", "augmentSingleFile", ")", "return", "{", "children", ":", "Object", ".", "keys", "(", "templates", ")", ".", "map", "(", "(", "name", ")", "=>", "{", "let", "template", "=", "templates", "[", "name", "]", "return", "{", "name", ":", "name", ",", "type", ":", "'template'", ",", "path", ":", "template", ".", "path", ",", "comments", ":", "template", ".", "comments", ",", "children", ":", "template", ".", "callsPartial", ".", "map", "(", "(", "callee", ")", "=>", "callee", ".", "name", ")", ".", "filter", "(", "(", "name", ",", "index", ",", "array", ")", "=>", "array", ".", "indexOf", "(", "name", ")", "===", "index", ")", ".", "map", "(", "(", "name", ")", "=>", "partialForCallTree", "(", "name", ",", "partials", ",", "{", "}", ")", ")", "}", "}", ")", "}", "}" ]
Compute a hierarchy tree of templates and partials calling other partials. The return value can be used as input for the 'renderTree'-helper and has the form ``` [{ "name": "template1", "type": "template", "path": "src/tmpl/template1.hbs "comments": ["a comment for template1"], "children": [ "name": "partial1", "path": "src/prt/partial1.hbs "type": "partial", "comments": ["a comment for partial 1"], "children": [] ] }] ``` @param {{templates: object, partials: object}} config @return {object}
[ "Compute", "a", "hierarchy", "tree", "of", "templates", "and", "partials", "calling", "other", "partials", ".", "The", "return", "value", "can", "be", "used", "as", "input", "for", "the", "renderTree", "-", "helper", "and", "has", "the", "form" ]
74ef0b625da20b51a6d5cb6e1ec1d128890add78
https://github.com/bootprint/customize-engine-handlebars/blob/74ef0b625da20b51a6d5cb6e1ec1d128890add78/lib/partial-details.js#L41-L60
train
bootprint/customize-engine-handlebars
lib/partial-details.js
partialForCallTree
function partialForCallTree (name, partials, visitedNodes) { const cycleFound = visitedNodes[name] try { visitedNodes[name] = true const partial = partials[name] if (!partial) { throw new Error(`Missing partial "${name}"`) } let children if (!cycleFound) { children = partial.callsPartial .map((callee) => callee.name) // Remove redundant names (only take the first one) .filter((name, index, array) => array.indexOf(name) === index) .map((name) => partialForCallTree(name, partials, visitedNodes)) } return { name, type: 'partial', comments: partial.comments, path: partial.path, children, cycleFound } } finally { if (!cycleFound) { delete visitedNodes[name] } } }
javascript
function partialForCallTree (name, partials, visitedNodes) { const cycleFound = visitedNodes[name] try { visitedNodes[name] = true const partial = partials[name] if (!partial) { throw new Error(`Missing partial "${name}"`) } let children if (!cycleFound) { children = partial.callsPartial .map((callee) => callee.name) // Remove redundant names (only take the first one) .filter((name, index, array) => array.indexOf(name) === index) .map((name) => partialForCallTree(name, partials, visitedNodes)) } return { name, type: 'partial', comments: partial.comments, path: partial.path, children, cycleFound } } finally { if (!cycleFound) { delete visitedNodes[name] } } }
[ "function", "partialForCallTree", "(", "name", ",", "partials", ",", "visitedNodes", ")", "{", "const", "cycleFound", "=", "visitedNodes", "[", "name", "]", "try", "{", "visitedNodes", "[", "name", "]", "=", "true", "const", "partial", "=", "partials", "[", "name", "]", "if", "(", "!", "partial", ")", "{", "throw", "new", "Error", "(", "`", "${", "name", "}", "`", ")", "}", "let", "children", "if", "(", "!", "cycleFound", ")", "{", "children", "=", "partial", ".", "callsPartial", ".", "map", "(", "(", "callee", ")", "=>", "callee", ".", "name", ")", ".", "filter", "(", "(", "name", ",", "index", ",", "array", ")", "=>", "array", ".", "indexOf", "(", "name", ")", "===", "index", ")", ".", "map", "(", "(", "name", ")", "=>", "partialForCallTree", "(", "name", ",", "partials", ",", "visitedNodes", ")", ")", "}", "return", "{", "name", ",", "type", ":", "'partial'", ",", "comments", ":", "partial", ".", "comments", ",", "path", ":", "partial", ".", "path", ",", "children", ",", "cycleFound", "}", "}", "finally", "{", "if", "(", "!", "cycleFound", ")", "{", "delete", "visitedNodes", "[", "name", "]", "}", "}", "}" ]
Inner function that returns a partial and its callees as tree @param {string} name the name of the partial @param {object} partials an object of all partials (by name). This is assumed to be an augmentedPartial with comment and callee @param {object<boolean>=} visitedNodes names of the visited nodes for breaking cycles (values are alwasy "true") @returns {{name: *, type: string, comment}}
[ "Inner", "function", "that", "returns", "a", "partial", "and", "its", "callees", "as", "tree" ]
74ef0b625da20b51a6d5cb6e1ec1d128890add78
https://github.com/bootprint/customize-engine-handlebars/blob/74ef0b625da20b51a6d5cb6e1ec1d128890add78/lib/partial-details.js#L70-L99
train
hammy2899/o
src/keyOf.js
keyOf
function keyOf(object, value, follow = false) { // if the object is an object and is not empty if (is(object) && !empty(object)) { // create a found boolean so we can skip // over keys once we have found the correct // key let found = false; // create an result variable as false let result = ''; // for each key/value in the object // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, objValue) => { // if the result isn't already found if (!found) { // check if the object value is equal to // the specified value if (objValue === value) { // set found to true since the key was found found = true; // if the values are the same set the result // to the key result = key; } } }, follow); // return the result if it was found else return // undefined return found ? result : undefined; } // if the object isn't an object or is empty return // false because the object can't be checked return undefined; }
javascript
function keyOf(object, value, follow = false) { // if the object is an object and is not empty if (is(object) && !empty(object)) { // create a found boolean so we can skip // over keys once we have found the correct // key let found = false; // create an result variable as false let result = ''; // for each key/value in the object // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, objValue) => { // if the result isn't already found if (!found) { // check if the object value is equal to // the specified value if (objValue === value) { // set found to true since the key was found found = true; // if the values are the same set the result // to the key result = key; } } }, follow); // return the result if it was found else return // undefined return found ? result : undefined; } // if the object isn't an object or is empty return // false because the object can't be checked return undefined; }
[ "function", "keyOf", "(", "object", ",", "value", ",", "follow", "=", "false", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", ")", "{", "let", "found", "=", "false", ";", "let", "result", "=", "''", ";", "each", "(", "object", ",", "(", "key", ",", "objValue", ")", "=>", "{", "if", "(", "!", "found", ")", "{", "if", "(", "objValue", "===", "value", ")", "{", "found", "=", "true", ";", "result", "=", "key", ";", "}", "}", "}", ",", "follow", ")", ";", "return", "found", "?", "result", ":", "undefined", ";", "}", "return", "undefined", ";", "}" ]
Get the key of the specified value in dot notation @example const a = { a: 1, b: 2, c: 3 }; keyOf(a, 2); // => 'b' @since 1.0.0 @version 1.0.0 @param {object} object The object to search @param {*} value The value to look for @param {boolean} [follow=false] Whether to follow objects @returns {string} The key when found else undefined
[ "Get", "the", "key", "of", "the", "specified", "value", "in", "dot", "notation" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/keyOf.js#L22-L62
train
hammy2899/o
src/every.js
every
function every(object, iterator, follow = false) { // if the object is an object and is not empty if (is(object) && !empty(object) && typeof iterator === 'function') { // set the result to true so we can change it // to false if the iterator fails let result = true; // for each over the object keys and values // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, value) => { // run the iterator function on the key and // value and if it evaluates to false set // the result to false if (iterator(key, value) === false) { // set the result to false result = false; } }, follow); // return the result return result; } // if the object isn't an object or is empty return false // because the iterator can't be ran to make a check return false; }
javascript
function every(object, iterator, follow = false) { // if the object is an object and is not empty if (is(object) && !empty(object) && typeof iterator === 'function') { // set the result to true so we can change it // to false if the iterator fails let result = true; // for each over the object keys and values // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, value) => { // run the iterator function on the key and // value and if it evaluates to false set // the result to false if (iterator(key, value) === false) { // set the result to false result = false; } }, follow); // return the result return result; } // if the object isn't an object or is empty return false // because the iterator can't be ran to make a check return false; }
[ "function", "every", "(", "object", ",", "iterator", ",", "follow", "=", "false", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", "&&", "typeof", "iterator", "===", "'function'", ")", "{", "let", "result", "=", "true", ";", "each", "(", "object", ",", "(", "key", ",", "value", ")", "=>", "{", "if", "(", "iterator", "(", "key", ",", "value", ")", "===", "false", ")", "{", "result", "=", "false", ";", "}", "}", ",", "follow", ")", ";", "return", "result", ";", "}", "return", "false", ";", "}" ]
Check every element in an object evaluate to the iterator @example const a = { a: 1, b: 2 }; const b = { a: 1, b: 'test' } every(a, (key, value) => typeof value === 'number'); // => true every(b, (key, value) => typeof value === 'number'); // => false @since 1.0.0 @version 1.0.0 @param {object} object The object to check @param {function(key: string, value: *)} iterator The function to evaluate @param {boolean} follow Whether to follow objects @returns {boolean} Whether all objects evaluate to the iterator
[ "Check", "every", "element", "in", "an", "object", "evaluate", "to", "the", "iterator" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/every.js#L24-L52
train
MaximeMaillet/express-imp-router
src/route.js
parseStaticRoutes
function parseStaticRoutes(config) { Object.keys(config).map((key) => { StaticRoutes.push({ method: 'get', route: key, controller: config[key].target, action: '*', options: config[key].options, generated: true, debug: { controller: config[key].target, action: '*' } }); }); }
javascript
function parseStaticRoutes(config) { Object.keys(config).map((key) => { StaticRoutes.push({ method: 'get', route: key, controller: config[key].target, action: '*', options: config[key].options, generated: true, debug: { controller: config[key].target, action: '*' } }); }); }
[ "function", "parseStaticRoutes", "(", "config", ")", "{", "Object", ".", "keys", "(", "config", ")", ".", "map", "(", "(", "key", ")", "=>", "{", "StaticRoutes", ".", "push", "(", "{", "method", ":", "'get'", ",", "route", ":", "key", ",", "controller", ":", "config", "[", "key", "]", ".", "target", ",", "action", ":", "'*'", ",", "options", ":", "config", "[", "key", "]", ".", "options", ",", "generated", ":", "true", ",", "debug", ":", "{", "controller", ":", "config", "[", "key", "]", ".", "target", ",", "action", ":", "'*'", "}", "}", ")", ";", "}", ")", ";", "}" ]
Generate static routes @param config
[ "Generate", "static", "routes" ]
4bcb687133a6e78d8c823c70413d9f866c506af2
https://github.com/MaximeMaillet/express-imp-router/blob/4bcb687133a6e78d8c823c70413d9f866c506af2/src/route.js#L289-L304
train
MaximeMaillet/express-imp-router
src/route.js
extractErrorHandler
function extractErrorHandler(target, name) { if(name.indexOf('#') !== -1) { const [controller, action] = name.split('#'); ErrorsHandler.push({ target: target, controller, action, }); } else { ErrorsHandler.push({ target: target, controller: name, }); } }
javascript
function extractErrorHandler(target, name) { if(name.indexOf('#') !== -1) { const [controller, action] = name.split('#'); ErrorsHandler.push({ target: target, controller, action, }); } else { ErrorsHandler.push({ target: target, controller: name, }); } }
[ "function", "extractErrorHandler", "(", "target", ",", "name", ")", "{", "if", "(", "name", ".", "indexOf", "(", "'#'", ")", "!==", "-", "1", ")", "{", "const", "[", "controller", ",", "action", "]", "=", "name", ".", "split", "(", "'#'", ")", ";", "ErrorsHandler", ".", "push", "(", "{", "target", ":", "target", ",", "controller", ",", "action", ",", "}", ")", ";", "}", "else", "{", "ErrorsHandler", ".", "push", "(", "{", "target", ":", "target", ",", "controller", ":", "name", ",", "}", ")", ";", "}", "}" ]
Extract error handler @param target @param name
[ "Extract", "error", "handler" ]
4bcb687133a6e78d8c823c70413d9f866c506af2
https://github.com/MaximeMaillet/express-imp-router/blob/4bcb687133a6e78d8c823c70413d9f866c506af2/src/route.js#L480-L494
train
MaximeMaillet/express-imp-router
src/route.js
generate
function generate() { for(const i in Routes) { if(!Routes[i].generated) { Routes[i] = generateController(path.controllers, Routes[i]); } } for(const i in MiddleWares) { MiddleWares[i] = generateController(path.middlewares, MiddleWares[i]); } for(const i in GlobalMiddleWares) { GlobalMiddleWares[i] = generateController(path.middlewares, GlobalMiddleWares[i]); } for(const i in ErrorsHandler) { ErrorsHandler[i] = generateController(path.errorHandler, ErrorsHandler[i]); } for(const i in Services) { Services[i] = generateService(path.services, Services[i]); } }
javascript
function generate() { for(const i in Routes) { if(!Routes[i].generated) { Routes[i] = generateController(path.controllers, Routes[i]); } } for(const i in MiddleWares) { MiddleWares[i] = generateController(path.middlewares, MiddleWares[i]); } for(const i in GlobalMiddleWares) { GlobalMiddleWares[i] = generateController(path.middlewares, GlobalMiddleWares[i]); } for(const i in ErrorsHandler) { ErrorsHandler[i] = generateController(path.errorHandler, ErrorsHandler[i]); } for(const i in Services) { Services[i] = generateService(path.services, Services[i]); } }
[ "function", "generate", "(", ")", "{", "for", "(", "const", "i", "in", "Routes", ")", "{", "if", "(", "!", "Routes", "[", "i", "]", ".", "generated", ")", "{", "Routes", "[", "i", "]", "=", "generateController", "(", "path", ".", "controllers", ",", "Routes", "[", "i", "]", ")", ";", "}", "}", "for", "(", "const", "i", "in", "MiddleWares", ")", "{", "MiddleWares", "[", "i", "]", "=", "generateController", "(", "path", ".", "middlewares", ",", "MiddleWares", "[", "i", "]", ")", ";", "}", "for", "(", "const", "i", "in", "GlobalMiddleWares", ")", "{", "GlobalMiddleWares", "[", "i", "]", "=", "generateController", "(", "path", ".", "middlewares", ",", "GlobalMiddleWares", "[", "i", "]", ")", ";", "}", "for", "(", "const", "i", "in", "ErrorsHandler", ")", "{", "ErrorsHandler", "[", "i", "]", "=", "generateController", "(", "path", ".", "errorHandler", ",", "ErrorsHandler", "[", "i", "]", ")", ";", "}", "for", "(", "const", "i", "in", "Services", ")", "{", "Services", "[", "i", "]", "=", "generateService", "(", "path", ".", "services", ",", "Services", "[", "i", "]", ")", ";", "}", "}" ]
Generate controller of all routes & middlewares
[ "Generate", "controller", "of", "all", "routes", "&", "middlewares" ]
4bcb687133a6e78d8c823c70413d9f866c506af2
https://github.com/MaximeMaillet/express-imp-router/blob/4bcb687133a6e78d8c823c70413d9f866c506af2/src/route.js#L499-L521
train
GCheung55/Neuro
src/model/model.js
function(prop){ var props = {}, len, i = 0, item; prop = Array.from(prop); len = prop.length; while(len--){ props[prop[i++]] = void 0; } // void 0 is used because 'undefined' is a var that can be changed in some browsers this.set(props); return this; }
javascript
function(prop){ var props = {}, len, i = 0, item; prop = Array.from(prop); len = prop.length; while(len--){ props[prop[i++]] = void 0; } // void 0 is used because 'undefined' is a var that can be changed in some browsers this.set(props); return this; }
[ "function", "(", "prop", ")", "{", "var", "props", "=", "{", "}", ",", "len", ",", "i", "=", "0", ",", "item", ";", "prop", "=", "Array", ".", "from", "(", "prop", ")", ";", "len", "=", "prop", ".", "length", ";", "while", "(", "len", "--", ")", "{", "props", "[", "prop", "[", "i", "++", "]", "]", "=", "void", "0", ";", "}", "this", ".", "set", "(", "props", ")", ";", "return", "this", ";", "}" ]
Unset a data property. It can not be erased so it will be set to undefined @param {String|Array} prop Property name/names to be unset @return {Class} The Model instance
[ "Unset", "a", "data", "property", ".", "It", "can", "not", "be", "erased", "so", "it", "will", "be", "set", "to", "undefined" ]
9d21bb94fe60069ef51c4120215baa8f38865600
https://github.com/GCheung55/Neuro/blob/9d21bb94fe60069ef51c4120215baa8f38865600/src/model/model.js#L180-L195
train
pex-gl/pex-io
loadBinary.js
loadBinary
function loadBinary (file, callback) { if (isPlask) { loadBinaryPlask(file, callback) } else { loadBinaryBrowser(file, callback) } }
javascript
function loadBinary (file, callback) { if (isPlask) { loadBinaryPlask(file, callback) } else { loadBinaryBrowser(file, callback) } }
[ "function", "loadBinary", "(", "file", ",", "callback", ")", "{", "if", "(", "isPlask", ")", "{", "loadBinaryPlask", "(", "file", ",", "callback", ")", "}", "else", "{", "loadBinaryBrowser", "(", "file", ",", "callback", ")", "}", "}" ]
Loads binary data @param {String} file - url addess (Browser) or file path (Plask) @param {Function} callback - function(err, data) { } @param {Error} callback.err - error if any or null @param {ArrayBuffer} callback.data - loaded binary data
[ "Loads", "binary", "data" ]
58e730e2c0a20e3574627ecbc5b0d03f20019972
https://github.com/pex-gl/pex-io/blob/58e730e2c0a20e3574627ecbc5b0d03f20019972/loadBinary.js#L52-L58
train
hammy2899/o
src/map.js
map
function map(object, iterator, follow = false) { // if the object is an object and is not empty if (is(object) && !empty(object) && typeof iterator === 'function') { // create an empty object for the result let result = {}; // for each key/value in the object // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, value) => { // set the result to the object with the key/value computed // from the specified iterator result = set(result, key, iterator(key, value)); }, follow); // return the result return result; } // if the object isn't an object or is empty return an // empty object because the iterator can't be ran to // compute the values return {}; }
javascript
function map(object, iterator, follow = false) { // if the object is an object and is not empty if (is(object) && !empty(object) && typeof iterator === 'function') { // create an empty object for the result let result = {}; // for each key/value in the object // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, value) => { // set the result to the object with the key/value computed // from the specified iterator result = set(result, key, iterator(key, value)); }, follow); // return the result return result; } // if the object isn't an object or is empty return an // empty object because the iterator can't be ran to // compute the values return {}; }
[ "function", "map", "(", "object", ",", "iterator", ",", "follow", "=", "false", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", "&&", "typeof", "iterator", "===", "'function'", ")", "{", "let", "result", "=", "{", "}", ";", "each", "(", "object", ",", "(", "key", ",", "value", ")", "=>", "{", "result", "=", "set", "(", "result", ",", "key", ",", "iterator", "(", "key", ",", "value", ")", ")", ";", "}", ",", "follow", ")", ";", "return", "result", ";", "}", "return", "{", "}", ";", "}" ]
Loop over an object and return a new object with the values computed from the specified iterator @example const a = { a: 1, b: 2, c: 3 }; map(a, (key, value) => value * 2); // => { a: 2, b: 4, c: 6 } @since 1.0.0 @version 1.0.0 @param {object} object The object to map @param {function(key: string, value: *)} iterator The function used to compute the value @param {boolean} [follow=false] Whether or not to follow objects @returns {object} The result object with the computed values
[ "Loop", "over", "an", "object", "and", "return", "a", "new", "object", "with", "the", "values", "computed", "from", "the", "specified", "iterator" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/map.js#L24-L48
train
akoenig/github-trending
lib/index.js
trending
function trending () { var language; var timespan; var callback; if (arguments.length === 3) { language = arguments[0]; timespan = arguments[1]; callback = arguments[2]; } else if (arguments.length === 2) { language = arguments[0]; callback = arguments[1]; } else { callback = arguments[0]; } language = (language || 'all').toLowerCase(); timespan = timespan || 'daily'; function onResponse (err, html) { var repositories; if (err) { return callback(new VError(err, 'failed to fetch trending repositories (language: %s).', language)); } repositories = scraper.repositories(html); callback(null, repositories); } mandatory(callback) .is('function', 'Please define a proper callback function.'); request(endpoint, { l: language, since: timespan }, onResponse); }
javascript
function trending () { var language; var timespan; var callback; if (arguments.length === 3) { language = arguments[0]; timespan = arguments[1]; callback = arguments[2]; } else if (arguments.length === 2) { language = arguments[0]; callback = arguments[1]; } else { callback = arguments[0]; } language = (language || 'all').toLowerCase(); timespan = timespan || 'daily'; function onResponse (err, html) { var repositories; if (err) { return callback(new VError(err, 'failed to fetch trending repositories (language: %s).', language)); } repositories = scraper.repositories(html); callback(null, repositories); } mandatory(callback) .is('function', 'Please define a proper callback function.'); request(endpoint, { l: language, since: timespan }, onResponse); }
[ "function", "trending", "(", ")", "{", "var", "language", ";", "var", "timespan", ";", "var", "callback", ";", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "language", "=", "arguments", "[", "0", "]", ";", "timespan", "=", "arguments", "[", "1", "]", ";", "callback", "=", "arguments", "[", "2", "]", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "language", "=", "arguments", "[", "0", "]", ";", "callback", "=", "arguments", "[", "1", "]", ";", "}", "else", "{", "callback", "=", "arguments", "[", "0", "]", ";", "}", "language", "=", "(", "language", "||", "'all'", ")", ".", "toLowerCase", "(", ")", ";", "timespan", "=", "timespan", "||", "'daily'", ";", "function", "onResponse", "(", "err", ",", "html", ")", "{", "var", "repositories", ";", "if", "(", "err", ")", "{", "return", "callback", "(", "new", "VError", "(", "err", ",", "'failed to fetch trending repositories (language: %s).'", ",", "language", ")", ")", ";", "}", "repositories", "=", "scraper", ".", "repositories", "(", "html", ")", ";", "callback", "(", "null", ",", "repositories", ")", ";", "}", "mandatory", "(", "callback", ")", ".", "is", "(", "'function'", ",", "'Please define a proper callback function.'", ")", ";", "request", "(", "endpoint", ",", "{", "l", ":", "language", ",", "since", ":", "timespan", "}", ",", "onResponse", ")", ";", "}" ]
Grabs the trending repositories of a particular language. @param {string} language The language for which the trending repos should be fetched. @param {function} callback Will be invoked when the trending repository data has been fetched. Invoked as `callback(err, repositories)`.
[ "Grabs", "the", "trending", "repositories", "of", "a", "particular", "language", "." ]
cbac1ac468660bbaa88c5d7a7607377041c551c1
https://github.com/akoenig/github-trending/blob/cbac1ac468660bbaa88c5d7a7607377041c551c1/lib/index.js#L35-L73
train
hammy2899/o
src/find.js
find
function find(object, iterator, follow) { // if the object is an object and is not empty if (is(object) && !empty(object) && typeof iterator === 'function') { // create an result variable as undefined let found = false; let result = ''; // for each key/value in the object // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, value) => { // if the value hasn't already been found if (!found) { // check if the iterator is false if it // is false then delete that key from the object if (iterator(key, value) === true) { found = true; result = key; } } }, follow); // return the result unless the value wasn't found // then return undefined return found ? result : undefined; } // if the object isn't an object or is empty return // undefined because the iterator can't be ran to // make a check return undefined; }
javascript
function find(object, iterator, follow) { // if the object is an object and is not empty if (is(object) && !empty(object) && typeof iterator === 'function') { // create an result variable as undefined let found = false; let result = ''; // for each key/value in the object // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, value) => { // if the value hasn't already been found if (!found) { // check if the iterator is false if it // is false then delete that key from the object if (iterator(key, value) === true) { found = true; result = key; } } }, follow); // return the result unless the value wasn't found // then return undefined return found ? result : undefined; } // if the object isn't an object or is empty return // undefined because the iterator can't be ran to // make a check return undefined; }
[ "function", "find", "(", "object", ",", "iterator", ",", "follow", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", "&&", "typeof", "iterator", "===", "'function'", ")", "{", "let", "found", "=", "false", ";", "let", "result", "=", "''", ";", "each", "(", "object", ",", "(", "key", ",", "value", ")", "=>", "{", "if", "(", "!", "found", ")", "{", "if", "(", "iterator", "(", "key", ",", "value", ")", "===", "true", ")", "{", "found", "=", "true", ";", "result", "=", "key", ";", "}", "}", "}", ",", "follow", ")", ";", "return", "found", "?", "result", ":", "undefined", ";", "}", "return", "undefined", ";", "}" ]
Find the key matching the iterator evaluation @example const a = { a: 1, b: 2, c: 3 }; find(a, (key, value) => value === 3); // => 'c' @since 1.0.0 @version 1.0.0 @param {object} object The object to search @param {function(key: string, value: *)} iterator The function to evaluate @param {boolean} [follow=false] Whether to follow objects @returns {string} The key which evaluates to the iterator
[ "Find", "the", "key", "matching", "the", "iterator", "evaluation" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/find.js#L22-L56
train
pex-gl/pex-io
loadImage.js
loadImage
function loadImage (file, callback, crossOrigin) { if (isPlask) { loadImagePlask(file, callback) } else { loadImageBrowser(file, callback, crossOrigin) } }
javascript
function loadImage (file, callback, crossOrigin) { if (isPlask) { loadImagePlask(file, callback) } else { loadImageBrowser(file, callback, crossOrigin) } }
[ "function", "loadImage", "(", "file", ",", "callback", ",", "crossOrigin", ")", "{", "if", "(", "isPlask", ")", "{", "loadImagePlask", "(", "file", ",", "callback", ")", "}", "else", "{", "loadImageBrowser", "(", "file", ",", "callback", ",", "crossOrigin", ")", "}", "}" ]
Loads a HTML Image from an url in the borwser, SkCanvas from a file in Plask @param {String} file - url addess (Browser) or file path (Plask) @param {Function} callback - function(err, image) { } @param {Error} callback.err - error if any or null @param {Image|SkCanvas} callback.image - loaded image
[ "Loads", "a", "HTML", "Image", "from", "an", "url", "in", "the", "borwser", "SkCanvas", "from", "a", "file", "in", "Plask" ]
58e730e2c0a20e3574627ecbc5b0d03f20019972
https://github.com/pex-gl/pex-io/blob/58e730e2c0a20e3574627ecbc5b0d03f20019972/loadImage.js#L58-L64
train
hammy2899/o
src/slice.js
slice
function slice(object, start, end = Object.keys(object).length) { // if the object is an object and is not empty if (is(object) && !empty(object)) { // get the keys from the object const objKeys = keys(object); // create an empty object for the result const result = {}; // slice the object keys to the specified start and end // and for each key returned objKeys.slice(start, end).forEach((key) => { // set the result object key to the value result[key] = object[key]; }); // return the result return result; } // if the object isn't an object or is empty return an // empty object because slicing won't return anything anyway return {}; }
javascript
function slice(object, start, end = Object.keys(object).length) { // if the object is an object and is not empty if (is(object) && !empty(object)) { // get the keys from the object const objKeys = keys(object); // create an empty object for the result const result = {}; // slice the object keys to the specified start and end // and for each key returned objKeys.slice(start, end).forEach((key) => { // set the result object key to the value result[key] = object[key]; }); // return the result return result; } // if the object isn't an object or is empty return an // empty object because slicing won't return anything anyway return {}; }
[ "function", "slice", "(", "object", ",", "start", ",", "end", "=", "Object", ".", "keys", "(", "object", ")", ".", "length", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", ")", "{", "const", "objKeys", "=", "keys", "(", "object", ")", ";", "const", "result", "=", "{", "}", ";", "objKeys", ".", "slice", "(", "start", ",", "end", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "result", "[", "key", "]", "=", "object", "[", "key", "]", ";", "}", ")", ";", "return", "result", ";", "}", "return", "{", "}", ";", "}" ]
Get a portion of the specified object @example const a = { a: 1, b: 2, c: 3 }; slice(a, 0, 1); // => { a: 1 } @since 1.0.0 @version 1.0.0 @param {object} object The object to slice @param {number} start The start index @param {number} [end] The end index (defaults to object keys length) @returns {object} The sliced object
[ "Get", "a", "portion", "of", "the", "specified", "object" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/slice.js#L22-L45
train
hammy2899/o
src/get.js
get
function get(object, path, defaultValue = undefined) { // check if the object is an object and is not empty // and it has the path specified if (is(object) && !empty(object) && has(object, path)) { // set the currentValue to the object so its easier to // iterate over the objects let currentValue = object; // for each path parts from the parsed path getPathParts(path).forEach((key) => { currentValue = currentValue[key]; }); // if it isn't undefined return the value return currentValue; } // if the object isn't an object or it is empty or // it doesn't have the specified path return the // default value return defaultValue; }
javascript
function get(object, path, defaultValue = undefined) { // check if the object is an object and is not empty // and it has the path specified if (is(object) && !empty(object) && has(object, path)) { // set the currentValue to the object so its easier to // iterate over the objects let currentValue = object; // for each path parts from the parsed path getPathParts(path).forEach((key) => { currentValue = currentValue[key]; }); // if it isn't undefined return the value return currentValue; } // if the object isn't an object or it is empty or // it doesn't have the specified path return the // default value return defaultValue; }
[ "function", "get", "(", "object", ",", "path", ",", "defaultValue", "=", "undefined", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", "&&", "has", "(", "object", ",", "path", ")", ")", "{", "let", "currentValue", "=", "object", ";", "getPathParts", "(", "path", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "currentValue", "=", "currentValue", "[", "key", "]", ";", "}", ")", ";", "return", "currentValue", ";", "}", "return", "defaultValue", ";", "}" ]
Get the value from the specified path @example const a = { a: 1, b: 2, c: 3 }; get(a, 'b'); // => 2 @since 1.0.0 @version 1.0.0 @param {object} object The object the get from @param {string} path The path to get @param {*} [defaultValue=undefined] The default value to return if the path doesn't exist @returns {*} The value from the path or the default value
[ "Get", "the", "value", "from", "the", "specified", "path" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/get.js#L23-L44
train
hammy2899/o
src/has.js
has
function has(object, ...paths) { // check if object is an object if (is(object) && !empty(object)) { // set the result to true by default let hasPaths = true; // for each path specified paths.forEach((path) => { // get the parsed path parts const parts = getPathParts(path); // set the current value so its easier to iterate over let currentValue = object; // for each part in the path parts.forEach((key) => { if (is(currentValue) && !empty(currentValue)) { currentValue = currentValue[key]; } else { currentValue = undefined; } }); // check if the currentValue is undefined meaning that the path // doesn't exist if (currentValue === undefined) { // if the currentValue is undefined set hasPaths to false // this will lead to the function returning false because // the object specified doesn't have all the paths specified hasPaths = false; } }); // return whether or not all the paths exist in the specified object return hasPaths; } // return false because the object specified isn't an object return false; }
javascript
function has(object, ...paths) { // check if object is an object if (is(object) && !empty(object)) { // set the result to true by default let hasPaths = true; // for each path specified paths.forEach((path) => { // get the parsed path parts const parts = getPathParts(path); // set the current value so its easier to iterate over let currentValue = object; // for each part in the path parts.forEach((key) => { if (is(currentValue) && !empty(currentValue)) { currentValue = currentValue[key]; } else { currentValue = undefined; } }); // check if the currentValue is undefined meaning that the path // doesn't exist if (currentValue === undefined) { // if the currentValue is undefined set hasPaths to false // this will lead to the function returning false because // the object specified doesn't have all the paths specified hasPaths = false; } }); // return whether or not all the paths exist in the specified object return hasPaths; } // return false because the object specified isn't an object return false; }
[ "function", "has", "(", "object", ",", "...", "paths", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", ")", "{", "let", "hasPaths", "=", "true", ";", "paths", ".", "forEach", "(", "(", "path", ")", "=>", "{", "const", "parts", "=", "getPathParts", "(", "path", ")", ";", "let", "currentValue", "=", "object", ";", "parts", ".", "forEach", "(", "(", "key", ")", "=>", "{", "if", "(", "is", "(", "currentValue", ")", "&&", "!", "empty", "(", "currentValue", ")", ")", "{", "currentValue", "=", "currentValue", "[", "key", "]", ";", "}", "else", "{", "currentValue", "=", "undefined", ";", "}", "}", ")", ";", "if", "(", "currentValue", "===", "undefined", ")", "{", "hasPaths", "=", "false", ";", "}", "}", ")", ";", "return", "hasPaths", ";", "}", "return", "false", ";", "}" ]
Check if an object has the specified paths @example const a = { a: 1, b: 2, c: 3 }; has(a, 'a'); // => true has(a, 'd'); // => false @since 1.0.0 @version 1.0.0 @param {object} object The object to check @param {...string} paths The paths to check for @returns {boolean} Whether the object contains the specified path
[ "Check", "if", "an", "object", "has", "the", "specified", "paths" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/has.js#L22-L61
train
xriss/plated
js/plated_files.js
function(stat) { if(stat) { if(stat.isDirectory) { return stat.isDirectory() } if(stat.type) { if(stat.type=="dir") { return true } } } return false }
javascript
function(stat) { if(stat) { if(stat.isDirectory) { return stat.isDirectory() } if(stat.type) { if(stat.type=="dir") { return true } } } return false }
[ "function", "(", "stat", ")", "{", "if", "(", "stat", ")", "{", "if", "(", "stat", ".", "isDirectory", ")", "{", "return", "stat", ".", "isDirectory", "(", ")", "}", "if", "(", "stat", ".", "type", ")", "{", "if", "(", "stat", ".", "type", "==", "\"dir\"", ")", "{", "return", "true", "}", "}", "}", "return", "false", "}" ]
hax for partial file system implimentations
[ "hax", "for", "partial", "file", "system", "implimentations" ]
3490ed4ed8b6ff40bfac5ebef75ad5ef5f2f1af2
https://github.com/xriss/plated/blob/3490ed4ed8b6ff40bfac5ebef75ad5ef5f2f1af2/js/plated_files.js#L31-L48
train
FBDY/bb-blocks
blocks_vertical/looks.js
function() { this.jsonInit({ "message0": Blockly.Msg.LOOKS_CHANGESIZEBY, "args0": [ { "type": "field_dropdown", "name": "TYPE", "options": [ [Blockly.Msg.LOOKS_SETSIZETO_SIZE, 'size'], [Blockly.Msg.LOOKS_SETSIZETO_STRETCH_X, 'stretch x'], [Blockly.Msg.LOOKS_SETSIZETO_STRETCH_Y, 'stretch y'] ] }, { "type": "input_value", "name": "CHANGE" } ], "category": Blockly.Categories.looks, "extensions": ["colours_looks", "shape_statement"] }); }
javascript
function() { this.jsonInit({ "message0": Blockly.Msg.LOOKS_CHANGESIZEBY, "args0": [ { "type": "field_dropdown", "name": "TYPE", "options": [ [Blockly.Msg.LOOKS_SETSIZETO_SIZE, 'size'], [Blockly.Msg.LOOKS_SETSIZETO_STRETCH_X, 'stretch x'], [Blockly.Msg.LOOKS_SETSIZETO_STRETCH_Y, 'stretch y'] ] }, { "type": "input_value", "name": "CHANGE" } ], "category": Blockly.Categories.looks, "extensions": ["colours_looks", "shape_statement"] }); }
[ "function", "(", ")", "{", "this", ".", "jsonInit", "(", "{", "\"message0\"", ":", "Blockly", ".", "Msg", ".", "LOOKS_CHANGESIZEBY", ",", "\"args0\"", ":", "[", "{", "\"type\"", ":", "\"field_dropdown\"", ",", "\"name\"", ":", "\"TYPE\"", ",", "\"options\"", ":", "[", "[", "Blockly", ".", "Msg", ".", "LOOKS_SETSIZETO_SIZE", ",", "'size'", "]", ",", "[", "Blockly", ".", "Msg", ".", "LOOKS_SETSIZETO_STRETCH_X", ",", "'stretch x'", "]", ",", "[", "Blockly", ".", "Msg", ".", "LOOKS_SETSIZETO_STRETCH_Y", ",", "'stretch y'", "]", "]", "}", ",", "{", "\"type\"", ":", "\"input_value\"", ",", "\"name\"", ":", "\"CHANGE\"", "}", "]", ",", "\"category\"", ":", "Blockly", ".", "Categories", ".", "looks", ",", "\"extensions\"", ":", "[", "\"colours_looks\"", ",", "\"shape_statement\"", "]", "}", ")", ";", "}" ]
Block to change size @this Blockly.Block
[ "Block", "to", "change", "size" ]
748cb75966a730f13134bba4e76690793b042675
https://github.com/FBDY/bb-blocks/blob/748cb75966a730f13134bba4e76690793b042675/blocks_vertical/looks.js#L248-L269
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
startsWith
function startsWith(str, test){ if(str === test){ return true; } return str.substring(0, test.length+1) === test+'.'; }
javascript
function startsWith(str, test){ if(str === test){ return true; } return str.substring(0, test.length+1) === test+'.'; }
[ "function", "startsWith", "(", "str", ",", "test", ")", "{", "if", "(", "str", "===", "test", ")", "{", "return", "true", ";", "}", "return", "str", ".", "substring", "(", "0", ",", "test", ".", "length", "+", "1", ")", "===", "test", "+", "'.'", ";", "}" ]
Returns true if str starts with test
[ "Returns", "true", "if", "str", "starts", "with", "test" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L14-L17
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
push
function push(arr){ var i, len = arr.length; this.added || (this.added = {}); for(i=0;i<len;i++){ arr[i].markDirty(); if(this.added[arr[i].cid]) continue; this.added[arr[i].cid] = 1; this.push(arr[i]); } }
javascript
function push(arr){ var i, len = arr.length; this.added || (this.added = {}); for(i=0;i<len;i++){ arr[i].markDirty(); if(this.added[arr[i].cid]) continue; this.added[arr[i].cid] = 1; this.push(arr[i]); } }
[ "function", "push", "(", "arr", ")", "{", "var", "i", ",", "len", "=", "arr", ".", "length", ";", "this", ".", "added", "||", "(", "this", ".", "added", "=", "{", "}", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "arr", "[", "i", "]", ".", "markDirty", "(", ")", ";", "if", "(", "this", ".", "added", "[", "arr", "[", "i", "]", ".", "cid", "]", ")", "continue", ";", "this", ".", "added", "[", "arr", "[", "i", "]", ".", "cid", "]", "=", "1", ";", "this", ".", "push", "(", "arr", "[", "i", "]", ")", ";", "}", "}" ]
Push all elements in `arr` to the end of an array. Mark all Computed Properties as dirty on their way in.
[ "Push", "all", "elements", "in", "arr", "to", "the", "end", "of", "an", "array", ".", "Mark", "all", "Computed", "Properties", "as", "dirty", "on", "their", "way", "in", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L21-L30
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
recomputeCallback
function recomputeCallback(){ var len = TO_CALL.length; CALL_TIMEOUT = null; while(len--){ (TO_CALL.shift() || NOOP).call(); } TO_CALL.added = {}; }
javascript
function recomputeCallback(){ var len = TO_CALL.length; CALL_TIMEOUT = null; while(len--){ (TO_CALL.shift() || NOOP).call(); } TO_CALL.added = {}; }
[ "function", "recomputeCallback", "(", ")", "{", "var", "len", "=", "TO_CALL", ".", "length", ";", "CALL_TIMEOUT", "=", "null", ";", "while", "(", "len", "--", ")", "{", "(", "TO_CALL", ".", "shift", "(", ")", "||", "NOOP", ")", ".", "call", "(", ")", ";", "}", "TO_CALL", ".", "added", "=", "{", "}", ";", "}" ]
Called after callstack is exausted to call all of this computed property's dependants that need to be recomputed
[ "Called", "after", "callstack", "is", "exausted", "to", "call", "all", "of", "this", "computed", "property", "s", "dependants", "that", "need", "to", "be", "recomputed" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L34-L42
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
function(){ var root = this.__root__; var context = this.__parent__; root.__computedDeps || (root.__computedDeps = {}); _.each(this.deps, function(path){ // For each dependancy, mark ourselves as dirty if they become dirty var dep = root.get(path, {raw: true, isPath: true}); if(dep && dep.isComputedProperty){ dep.on('dirty', this.markDirty); } // Find actual context and path from relative paths var split = $.splitPath(path); while(split[0] === '@parent'){ context = context.__parent__; split.shift(); } path = context.__path().replace(/\.?\[.*\]/ig, '.@each'); path = path + (path && '.') + split.join('.'); // Add ourselves as dependants root.__computedDeps[path] || (root.__computedDeps[path] = []); root.__computedDeps[path].push(this); }, this); // Ensure we only have one listener per Model at a time. context.off('all', this.onRecompute).on('all', this.onRecompute); }
javascript
function(){ var root = this.__root__; var context = this.__parent__; root.__computedDeps || (root.__computedDeps = {}); _.each(this.deps, function(path){ // For each dependancy, mark ourselves as dirty if they become dirty var dep = root.get(path, {raw: true, isPath: true}); if(dep && dep.isComputedProperty){ dep.on('dirty', this.markDirty); } // Find actual context and path from relative paths var split = $.splitPath(path); while(split[0] === '@parent'){ context = context.__parent__; split.shift(); } path = context.__path().replace(/\.?\[.*\]/ig, '.@each'); path = path + (path && '.') + split.join('.'); // Add ourselves as dependants root.__computedDeps[path] || (root.__computedDeps[path] = []); root.__computedDeps[path].push(this); }, this); // Ensure we only have one listener per Model at a time. context.off('all', this.onRecompute).on('all', this.onRecompute); }
[ "function", "(", ")", "{", "var", "root", "=", "this", ".", "__root__", ";", "var", "context", "=", "this", ".", "__parent__", ";", "root", ".", "__computedDeps", "||", "(", "root", ".", "__computedDeps", "=", "{", "}", ")", ";", "_", ".", "each", "(", "this", ".", "deps", ",", "function", "(", "path", ")", "{", "var", "dep", "=", "root", ".", "get", "(", "path", ",", "{", "raw", ":", "true", ",", "isPath", ":", "true", "}", ")", ";", "if", "(", "dep", "&&", "dep", ".", "isComputedProperty", ")", "{", "dep", ".", "on", "(", "'dirty'", ",", "this", ".", "markDirty", ")", ";", "}", "var", "split", "=", "$", ".", "splitPath", "(", "path", ")", ";", "while", "(", "split", "[", "0", "]", "===", "'@parent'", ")", "{", "context", "=", "context", ".", "__parent__", ";", "split", ".", "shift", "(", ")", ";", "}", "path", "=", "context", ".", "__path", "(", ")", ".", "replace", "(", "/", "\\.?\\[.*\\]", "/", "ig", ",", "'.@each'", ")", ";", "path", "=", "path", "+", "(", "path", "&&", "'.'", ")", "+", "split", ".", "join", "(", "'.'", ")", ";", "root", ".", "__computedDeps", "[", "path", "]", "||", "(", "root", ".", "__computedDeps", "[", "path", "]", "=", "[", "]", ")", ";", "root", ".", "__computedDeps", "[", "path", "]", ".", "push", "(", "this", ")", ";", "}", ",", "this", ")", ";", "context", ".", "off", "(", "'all'", ",", "this", ".", "onRecompute", ")", ".", "on", "(", "'all'", ",", "this", ".", "onRecompute", ")", ";", "}" ]
Adds a litener to the root object and tells it what properties this Computed Property depend on. The listener will re-compute this Computed Property when any are changed.
[ "Adds", "a", "litener", "to", "the", "root", "object", "and", "tells", "it", "what", "properties", "this", "Computed", "Property", "depend", "on", ".", "The", "listener", "will", "re", "-", "compute", "this", "Computed", "Property", "when", "any", "are", "changed", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L193-L220
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
function(object){ var target = this.value(); if(!object || !target || !target.isData || !object.isData){ return void 0; } target._cid || (target._cid = target.cid); object._cid || (object._cid = object.cid); target.cid = object.cid; this.tracking = object; }
javascript
function(object){ var target = this.value(); if(!object || !target || !target.isData || !object.isData){ return void 0; } target._cid || (target._cid = target.cid); object._cid || (object._cid = object.cid); target.cid = object.cid; this.tracking = object; }
[ "function", "(", "object", ")", "{", "var", "target", "=", "this", ".", "value", "(", ")", ";", "if", "(", "!", "object", "||", "!", "target", "||", "!", "target", ".", "isData", "||", "!", "object", ".", "isData", ")", "{", "return", "void", "0", ";", "}", "target", ".", "_cid", "||", "(", "target", ".", "_cid", "=", "target", ".", "cid", ")", ";", "object", ".", "_cid", "||", "(", "object", ".", "_cid", "=", "object", ".", "cid", ")", ";", "target", ".", "cid", "=", "object", ".", "cid", ";", "this", ".", "tracking", "=", "object", ";", "}" ]
When we receive a new model to set in our cache, unbind the tracker from the previous cache object, sync the objects' cids so helpers think they are the same object, save a referance to the object we are tracking, and re-bind our onModify hook.
[ "When", "we", "receive", "a", "new", "model", "to", "set", "in", "our", "cache", "unbind", "the", "tracker", "from", "the", "previous", "cache", "object", "sync", "the", "objects", "cids", "so", "helpers", "think", "they", "are", "the", "same", "object", "save", "a", "referance", "to", "the", "object", "we", "are", "tracking", "and", "re", "-", "bind", "our", "onModify", "hook", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L333-L340
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
function(key, options={}){ if(this.returnType === 'value'){ return console.error('Called get on the `'+ this.name +'` computed property which returns a primitive value.'); } return this.value().get(key, options); }
javascript
function(key, options={}){ if(this.returnType === 'value'){ return console.error('Called get on the `'+ this.name +'` computed property which returns a primitive value.'); } return this.value().get(key, options); }
[ "function", "(", "key", ",", "options", "=", "{", "}", ")", "{", "if", "(", "this", ".", "returnType", "===", "'value'", ")", "{", "return", "console", ".", "error", "(", "'Called get on the `'", "+", "this", ".", "name", "+", "'` computed property which returns a primitive value.'", ")", ";", "}", "return", "this", ".", "value", "(", ")", ".", "get", "(", "key", ",", "options", ")", ";", "}" ]
Get from the Computed Property's cache
[ "Get", "from", "the", "Computed", "Property", "s", "cache" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L343-L346
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
function(key, val, options={}){ if(this.returnType === null){ return void 0; } var attrs = key; var value = this.value(); // Noralize the data passed in if(this.returnType === 'model'){ if (typeof key === 'object') { attrs = (key.isModel) ? key.attributes : key; options = val || {}; } else { (attrs = {})[key] = val; } } if(this.returnType !== 'model'){ options = val || {}; } attrs = (attrs && attrs.isComputedProperty) ? attrs.value() : attrs; // If a new value, set it and trigger events this.setter && this.setter.call(this.__root__, attrs); if(this.returnType === 'value' && this.cache.value !== attrs) { this.cache.value = attrs; if(!options.quiet){ // If set was called not through computedProperty.call(), this is a fresh new event burst. if(!this.isDirty && !this.isChanging) this.__parent__.changed = {}; this.__parent__.changed[this.name] = attrs; this.trigger('change', this.__parent__); this.trigger('change:'+this.name, this.__parent__, attrs); delete this.__parent__.changed[this.name]; } } else if(this.returnType !== 'value' && options.reset){ key = value.reset(attrs, options); } else if(this.returnType !== 'value'){ key = value.set(attrs, options); } this.isDirty = this.isChanging = false; // Call all reamining computed properties waiting for this value to resolve. _.each(this.waiting, function(prop){ prop && prop.call(); }); return key; }
javascript
function(key, val, options={}){ if(this.returnType === null){ return void 0; } var attrs = key; var value = this.value(); // Noralize the data passed in if(this.returnType === 'model'){ if (typeof key === 'object') { attrs = (key.isModel) ? key.attributes : key; options = val || {}; } else { (attrs = {})[key] = val; } } if(this.returnType !== 'model'){ options = val || {}; } attrs = (attrs && attrs.isComputedProperty) ? attrs.value() : attrs; // If a new value, set it and trigger events this.setter && this.setter.call(this.__root__, attrs); if(this.returnType === 'value' && this.cache.value !== attrs) { this.cache.value = attrs; if(!options.quiet){ // If set was called not through computedProperty.call(), this is a fresh new event burst. if(!this.isDirty && !this.isChanging) this.__parent__.changed = {}; this.__parent__.changed[this.name] = attrs; this.trigger('change', this.__parent__); this.trigger('change:'+this.name, this.__parent__, attrs); delete this.__parent__.changed[this.name]; } } else if(this.returnType !== 'value' && options.reset){ key = value.reset(attrs, options); } else if(this.returnType !== 'value'){ key = value.set(attrs, options); } this.isDirty = this.isChanging = false; // Call all reamining computed properties waiting for this value to resolve. _.each(this.waiting, function(prop){ prop && prop.call(); }); return key; }
[ "function", "(", "key", ",", "val", ",", "options", "=", "{", "}", ")", "{", "if", "(", "this", ".", "returnType", "===", "null", ")", "{", "return", "void", "0", ";", "}", "var", "attrs", "=", "key", ";", "var", "value", "=", "this", ".", "value", "(", ")", ";", "if", "(", "this", ".", "returnType", "===", "'model'", ")", "{", "if", "(", "typeof", "key", "===", "'object'", ")", "{", "attrs", "=", "(", "key", ".", "isModel", ")", "?", "key", ".", "attributes", ":", "key", ";", "options", "=", "val", "||", "{", "}", ";", "}", "else", "{", "(", "attrs", "=", "{", "}", ")", "[", "key", "]", "=", "val", ";", "}", "}", "if", "(", "this", ".", "returnType", "!==", "'model'", ")", "{", "options", "=", "val", "||", "{", "}", ";", "}", "attrs", "=", "(", "attrs", "&&", "attrs", ".", "isComputedProperty", ")", "?", "attrs", ".", "value", "(", ")", ":", "attrs", ";", "this", ".", "setter", "&&", "this", ".", "setter", ".", "call", "(", "this", ".", "__root__", ",", "attrs", ")", ";", "if", "(", "this", ".", "returnType", "===", "'value'", "&&", "this", ".", "cache", ".", "value", "!==", "attrs", ")", "{", "this", ".", "cache", ".", "value", "=", "attrs", ";", "if", "(", "!", "options", ".", "quiet", ")", "{", "if", "(", "!", "this", ".", "isDirty", "&&", "!", "this", ".", "isChanging", ")", "this", ".", "__parent__", ".", "changed", "=", "{", "}", ";", "this", ".", "__parent__", ".", "changed", "[", "this", ".", "name", "]", "=", "attrs", ";", "this", ".", "trigger", "(", "'change'", ",", "this", ".", "__parent__", ")", ";", "this", ".", "trigger", "(", "'change:'", "+", "this", ".", "name", ",", "this", ".", "__parent__", ",", "attrs", ")", ";", "delete", "this", ".", "__parent__", ".", "changed", "[", "this", ".", "name", "]", ";", "}", "}", "else", "if", "(", "this", ".", "returnType", "!==", "'value'", "&&", "options", ".", "reset", ")", "{", "key", "=", "value", ".", "reset", "(", "attrs", ",", "options", ")", ";", "}", "else", "if", "(", "this", ".", "returnType", "!==", "'value'", ")", "{", "key", "=", "value", ".", "set", "(", "attrs", ",", "options", ")", ";", "}", "this", ".", "isDirty", "=", "this", ".", "isChanging", "=", "false", ";", "_", ".", "each", "(", "this", ".", "waiting", ",", "function", "(", "prop", ")", "{", "prop", "&&", "prop", ".", "call", "(", ")", ";", "}", ")", ";", "return", "key", ";", "}" ]
Set the Computed Property's cache to a new value and trigger appropreate events. Changes will propagate back to the original object if a Rebound Data Object and re-compute. If Computed Property returns a value, all downstream dependancies will re-compute.
[ "Set", "the", "Computed", "Property", "s", "cache", "to", "a", "new", "value", "and", "trigger", "appropreate", "events", ".", "Changes", "will", "propagate", "back", "to", "the", "original", "object", "if", "a", "Rebound", "Data", "Object", "and", "re", "-", "compute", ".", "If", "Computed", "Property", "returns", "a", "value", "all", "downstream", "dependancies", "will", "re", "-", "compute", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L351-L391
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
function(obj, options={}){ if(_.isNull(this.returnType)){ return void 0; } options.reset = true; return this.set(obj, options); }
javascript
function(obj, options={}){ if(_.isNull(this.returnType)){ return void 0; } options.reset = true; return this.set(obj, options); }
[ "function", "(", "obj", ",", "options", "=", "{", "}", ")", "{", "if", "(", "_", ".", "isNull", "(", "this", ".", "returnType", ")", ")", "{", "return", "void", "0", ";", "}", "options", ".", "reset", "=", "true", ";", "return", "this", ".", "set", "(", "obj", ",", "options", ")", ";", "}" ]
Reset the current value in the cache, unless if first run.
[ "Reset", "the", "current", "value", "in", "the", "cache", "unless", "if", "first", "run", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L400-L404
train
reboundjs/rebound
packages/rebound-data/lib/computed-property.js
function() { if (this._isSerializing){ return this.cid; } var val = this.value(); this._isSerializing = true; var json = (val && _.isFunction(val.toJSON)) ? val.toJSON() : val; this._isSerializing = false; return json; }
javascript
function() { if (this._isSerializing){ return this.cid; } var val = this.value(); this._isSerializing = true; var json = (val && _.isFunction(val.toJSON)) ? val.toJSON() : val; this._isSerializing = false; return json; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "_isSerializing", ")", "{", "return", "this", ".", "cid", ";", "}", "var", "val", "=", "this", ".", "value", "(", ")", ";", "this", ".", "_isSerializing", "=", "true", ";", "var", "json", "=", "(", "val", "&&", "_", ".", "isFunction", "(", "val", ".", "toJSON", ")", ")", "?", "val", ".", "toJSON", "(", ")", ":", "val", ";", "this", ".", "_isSerializing", "=", "false", ";", "return", "json", ";", "}" ]
Cyclic dependancy safe toJSON method.
[ "Cyclic", "dependancy", "safe", "toJSON", "method", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-data/lib/computed-property.js#L407-L414
train
EnnoLohmann/ElectronSpellcheckerStaticDictionary
src/spell-check-handler.js
fromEventCapture
function fromEventCapture(element, name) { return Observable.create((subj) => { const handler = function (...args) { if (args.length > 1) { subj.next(args); } else { subj.next(args[0] || true); } }; element.addEventListener(name, handler, true); return new Subscription(() => element.removeEventListener(name, handler, true)); }); }
javascript
function fromEventCapture(element, name) { return Observable.create((subj) => { const handler = function (...args) { if (args.length > 1) { subj.next(args); } else { subj.next(args[0] || true); } }; element.addEventListener(name, handler, true); return new Subscription(() => element.removeEventListener(name, handler, true)); }); }
[ "function", "fromEventCapture", "(", "element", ",", "name", ")", "{", "return", "Observable", ".", "create", "(", "(", "subj", ")", "=>", "{", "const", "handler", "=", "function", "(", "...", "args", ")", "{", "if", "(", "args", ".", "length", ">", "1", ")", "{", "subj", ".", "next", "(", "args", ")", ";", "}", "else", "{", "subj", ".", "next", "(", "args", "[", "0", "]", "||", "true", ")", ";", "}", "}", ";", "element", ".", "addEventListener", "(", "name", ",", "handler", ",", "true", ")", ";", "return", "new", "Subscription", "(", "(", ")", "=>", "element", ".", "removeEventListener", "(", "name", ",", "handler", ",", "true", ")", ")", ";", "}", ")", ";", "}" ]
This method mimics Observable.fromEvent, but with capture semantics.
[ "This", "method", "mimics", "Observable", ".", "fromEvent", "but", "with", "capture", "semantics", "." ]
6f2baf8cbb162771f691ff7c76b359d07b596870
https://github.com/EnnoLohmann/ElectronSpellcheckerStaticDictionary/blob/6f2baf8cbb162771f691ff7c76b359d07b596870/src/spell-check-handler.js#L57-L70
train
GCheung55/Neuro
mixins/snitch.js
function(obj){ var validators = Object.clone(this._validators), // Store the global validator global = validators[asterisk], keys; // If global validator exists, test the object against it if (global) { // remove '*' validator from validators obj otherwise comparing keys will not pass delete validators[asterisk]; // retrieve keys of obj for comparison; keys = Object.keys(obj); // return global(obj) && Object.every(validators, function(val, prop){ return prop in obj;}); return global(obj) && Object.keys(validators).every( keys.contains.bind(keys) ); } else { // result and Snitch.proof must return true in order to pass proofing return Snitch.proof(obj, validators); } }
javascript
function(obj){ var validators = Object.clone(this._validators), // Store the global validator global = validators[asterisk], keys; // If global validator exists, test the object against it if (global) { // remove '*' validator from validators obj otherwise comparing keys will not pass delete validators[asterisk]; // retrieve keys of obj for comparison; keys = Object.keys(obj); // return global(obj) && Object.every(validators, function(val, prop){ return prop in obj;}); return global(obj) && Object.keys(validators).every( keys.contains.bind(keys) ); } else { // result and Snitch.proof must return true in order to pass proofing return Snitch.proof(obj, validators); } }
[ "function", "(", "obj", ")", "{", "var", "validators", "=", "Object", ".", "clone", "(", "this", ".", "_validators", ")", ",", "global", "=", "validators", "[", "asterisk", "]", ",", "keys", ";", "if", "(", "global", ")", "{", "delete", "validators", "[", "asterisk", "]", ";", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "return", "global", "(", "obj", ")", "&&", "Object", ".", "keys", "(", "validators", ")", ".", "every", "(", "keys", ".", "contains", ".", "bind", "(", "keys", ")", ")", ";", "}", "else", "{", "return", "Snitch", ".", "proof", "(", "obj", ",", "validators", ")", ";", "}", "}" ]
Proof the object that it has every item that this._validators has and that every validator passes. @param {Object} obj Object to validate @return {Boolean} The answer to whether the object passes or not
[ "Proof", "the", "object", "that", "it", "has", "every", "item", "that", "this", ".", "_validators", "has", "and", "that", "every", "validator", "passes", "." ]
9d21bb94fe60069ef51c4120215baa8f38865600
https://github.com/GCheung55/Neuro/blob/9d21bb94fe60069ef51c4120215baa8f38865600/mixins/snitch.js#L93-L111
train
Kronos-Integration/kronos-koa
src/kronos-koa.js
respond
function respond(ctx) { // allow bypassing koa if (false === ctx.respond) return; const res = ctx.res; if (!ctx.writable) return; let body = ctx.body; const code = ctx.status; // ignore body if (statuses.empty[code]) { // strip headers ctx.body = null; return res.end(); } if ("HEAD" == ctx.method) { if (!res.headersSent && isJSON(body)) { ctx.length = Buffer.byteLength(JSON.stringify(body)); } return res.end(); } // status body if (null == body) { body = ctx.message || String(code); if (!res.headersSent) { ctx.type = "text"; ctx.length = Buffer.byteLength(body); } return res.end(body); } // responses if (Buffer.isBuffer(body)) return res.end(body); if ("string" == typeof body) return res.end(body); if (body instanceof Stream) return body.pipe(res); // body: json body = JSON.stringify(body); if (!res.headersSent) { ctx.length = Buffer.byteLength(body); } res.end(body); }
javascript
function respond(ctx) { // allow bypassing koa if (false === ctx.respond) return; const res = ctx.res; if (!ctx.writable) return; let body = ctx.body; const code = ctx.status; // ignore body if (statuses.empty[code]) { // strip headers ctx.body = null; return res.end(); } if ("HEAD" == ctx.method) { if (!res.headersSent && isJSON(body)) { ctx.length = Buffer.byteLength(JSON.stringify(body)); } return res.end(); } // status body if (null == body) { body = ctx.message || String(code); if (!res.headersSent) { ctx.type = "text"; ctx.length = Buffer.byteLength(body); } return res.end(body); } // responses if (Buffer.isBuffer(body)) return res.end(body); if ("string" == typeof body) return res.end(body); if (body instanceof Stream) return body.pipe(res); // body: json body = JSON.stringify(body); if (!res.headersSent) { ctx.length = Buffer.byteLength(body); } res.end(body); }
[ "function", "respond", "(", "ctx", ")", "{", "if", "(", "false", "===", "ctx", ".", "respond", ")", "return", ";", "const", "res", "=", "ctx", ".", "res", ";", "if", "(", "!", "ctx", ".", "writable", ")", "return", ";", "let", "body", "=", "ctx", ".", "body", ";", "const", "code", "=", "ctx", ".", "status", ";", "if", "(", "statuses", ".", "empty", "[", "code", "]", ")", "{", "ctx", ".", "body", "=", "null", ";", "return", "res", ".", "end", "(", ")", ";", "}", "if", "(", "\"HEAD\"", "==", "ctx", ".", "method", ")", "{", "if", "(", "!", "res", ".", "headersSent", "&&", "isJSON", "(", "body", ")", ")", "{", "ctx", ".", "length", "=", "Buffer", ".", "byteLength", "(", "JSON", ".", "stringify", "(", "body", ")", ")", ";", "}", "return", "res", ".", "end", "(", ")", ";", "}", "if", "(", "null", "==", "body", ")", "{", "body", "=", "ctx", ".", "message", "||", "String", "(", "code", ")", ";", "if", "(", "!", "res", ".", "headersSent", ")", "{", "ctx", ".", "type", "=", "\"text\"", ";", "ctx", ".", "length", "=", "Buffer", ".", "byteLength", "(", "body", ")", ";", "}", "return", "res", ".", "end", "(", "body", ")", ";", "}", "if", "(", "Buffer", ".", "isBuffer", "(", "body", ")", ")", "return", "res", ".", "end", "(", "body", ")", ";", "if", "(", "\"string\"", "==", "typeof", "body", ")", "return", "res", ".", "end", "(", "body", ")", ";", "if", "(", "body", "instanceof", "Stream", ")", "return", "body", ".", "pipe", "(", "res", ")", ";", "body", "=", "JSON", ".", "stringify", "(", "body", ")", ";", "if", "(", "!", "res", ".", "headersSent", ")", "{", "ctx", ".", "length", "=", "Buffer", ".", "byteLength", "(", "body", ")", ";", "}", "res", ".", "end", "(", "body", ")", ";", "}" ]
Response helper. copied from the original
[ "Response", "helper", ".", "copied", "from", "the", "original" ]
214a7c63dd376bbbf26b3339702d84fb3521fd66
https://github.com/Kronos-Integration/kronos-koa/blob/214a7c63dd376bbbf26b3339702d84fb3521fd66/src/kronos-koa.js#L70-L115
train
shapesecurity/shift-spidermonkey-converter-js
src/cook-template-string.js
getHexValue
function getHexValue(rune) { if ("0" <= rune && rune <= "9") { return rune.charCodeAt(0) - 48; } if ("a" <= rune && rune <= "f") { return rune.charCodeAt(0) - 87; } if ("A" <= rune && rune <= "F") { return rune.charCodeAt(0) - 55; } return -1; }
javascript
function getHexValue(rune) { if ("0" <= rune && rune <= "9") { return rune.charCodeAt(0) - 48; } if ("a" <= rune && rune <= "f") { return rune.charCodeAt(0) - 87; } if ("A" <= rune && rune <= "F") { return rune.charCodeAt(0) - 55; } return -1; }
[ "function", "getHexValue", "(", "rune", ")", "{", "if", "(", "\"0\"", "<=", "rune", "&&", "rune", "<=", "\"9\"", ")", "{", "return", "rune", ".", "charCodeAt", "(", "0", ")", "-", "48", ";", "}", "if", "(", "\"a\"", "<=", "rune", "&&", "rune", "<=", "\"f\"", ")", "{", "return", "rune", ".", "charCodeAt", "(", "0", ")", "-", "87", ";", "}", "if", "(", "\"A\"", "<=", "rune", "&&", "rune", "<=", "\"F\"", ")", "{", "return", "rune", ".", "charCodeAt", "(", "0", ")", "-", "55", ";", "}", "return", "-", "1", ";", "}" ]
Exports a single function which "cooks" template strings, i.e. interprets any escape sequences and converts \r\n into \n. Adapted from shift-parser's scanStringEscape
[ "Exports", "a", "single", "function", "which", "cooks", "template", "strings", "i", ".", "e", ".", "interprets", "any", "escape", "sequences", "and", "converts", "\\", "r", "\\", "n", "into", "\\", "n", ".", "Adapted", "from", "shift", "-", "parser", "s", "scanStringEscape" ]
f958dfef3d86acc1961457b952f9e123508e2213
https://github.com/shapesecurity/shift-spidermonkey-converter-js/blob/f958dfef3d86acc1961457b952f9e123508e2213/src/cook-template-string.js#L22-L33
train
hammy2899/o
src/flip.js
flip
function flip(object, follow = false, useToString = false) { // if the object is an object and is not empty if (is(object) && !empty(object)) { // create an empty object for the result const result = {}; // for each key/value in the object each(object, (key, value) => { // if the value is a string it can be used as // the new key if (typeof value === 'string') { // set the new key/value to the result result[value] = key; } else if (typeof value !== 'string' && useToString) { // if the value isn't a string but useToString is true // toString the value result[String(value).toString()] = key; } }, follow); // return the result object return result; } // if the object isn't an object or is empty return // an empty object return {}; }
javascript
function flip(object, follow = false, useToString = false) { // if the object is an object and is not empty if (is(object) && !empty(object)) { // create an empty object for the result const result = {}; // for each key/value in the object each(object, (key, value) => { // if the value is a string it can be used as // the new key if (typeof value === 'string') { // set the new key/value to the result result[value] = key; } else if (typeof value !== 'string' && useToString) { // if the value isn't a string but useToString is true // toString the value result[String(value).toString()] = key; } }, follow); // return the result object return result; } // if the object isn't an object or is empty return // an empty object return {}; }
[ "function", "flip", "(", "object", ",", "follow", "=", "false", ",", "useToString", "=", "false", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", ")", "{", "const", "result", "=", "{", "}", ";", "each", "(", "object", ",", "(", "key", ",", "value", ")", "=>", "{", "if", "(", "typeof", "value", "===", "'string'", ")", "{", "result", "[", "value", "]", "=", "key", ";", "}", "else", "if", "(", "typeof", "value", "!==", "'string'", "&&", "useToString", ")", "{", "result", "[", "String", "(", "value", ")", ".", "toString", "(", ")", "]", "=", "key", ";", "}", "}", ",", "follow", ")", ";", "return", "result", ";", "}", "return", "{", "}", ";", "}" ]
Flip an objects keys for values and values for keys @example const a = { a: 1, b: 2, c: 3 }; flip(a); // => { 1: 'a', 2: 'b', 3: 'c' } @since 1.0.0 @version 1.0.0 @param {object} object The object to flip @param {boolean} [follow=false] Whether to follow objects @param {boolean} [useToString=false] Whether to use toString on incompatible values @returns {object} The flipped object
[ "Flip", "an", "objects", "keys", "for", "values", "and", "values", "for", "keys" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/flip.js#L22-L49
train
Woorank/node-url-tools
lib/Tld.js
traverse
function traverse(segments, tree, trail, iteration) { if (iteration === undefined) { iteration = 0; } iteration += 1; var last = segments.pop(); if (last) { if (tree[last] !== undefined) { trail.unshift(last); return traverse(segments, tree[last], trail); } if (tree["*"] !== undefined) { if (tree["!" + last] !== undefined) { return last; } trail.unshift(last); return traverse(segments, tree["*"], trail); } if (tree[true]) { return last; } if (iteration === 1) { // In first iteration everything is allowed (eg. foo.bar.example) trail.unshift(last); last = segments.pop(); if (last) { return last; } } } return null; }
javascript
function traverse(segments, tree, trail, iteration) { if (iteration === undefined) { iteration = 0; } iteration += 1; var last = segments.pop(); if (last) { if (tree[last] !== undefined) { trail.unshift(last); return traverse(segments, tree[last], trail); } if (tree["*"] !== undefined) { if (tree["!" + last] !== undefined) { return last; } trail.unshift(last); return traverse(segments, tree["*"], trail); } if (tree[true]) { return last; } if (iteration === 1) { // In first iteration everything is allowed (eg. foo.bar.example) trail.unshift(last); last = segments.pop(); if (last) { return last; } } } return null; }
[ "function", "traverse", "(", "segments", ",", "tree", ",", "trail", ",", "iteration", ")", "{", "if", "(", "iteration", "===", "undefined", ")", "{", "iteration", "=", "0", ";", "}", "iteration", "+=", "1", ";", "var", "last", "=", "segments", ".", "pop", "(", ")", ";", "if", "(", "last", ")", "{", "if", "(", "tree", "[", "last", "]", "!==", "undefined", ")", "{", "trail", ".", "unshift", "(", "last", ")", ";", "return", "traverse", "(", "segments", ",", "tree", "[", "last", "]", ",", "trail", ")", ";", "}", "if", "(", "tree", "[", "\"*\"", "]", "!==", "undefined", ")", "{", "if", "(", "tree", "[", "\"!\"", "+", "last", "]", "!==", "undefined", ")", "{", "return", "last", ";", "}", "trail", ".", "unshift", "(", "last", ")", ";", "return", "traverse", "(", "segments", ",", "tree", "[", "\"*\"", "]", ",", "trail", ")", ";", "}", "if", "(", "tree", "[", "true", "]", ")", "{", "return", "last", ";", "}", "if", "(", "iteration", "===", "1", ")", "{", "trail", ".", "unshift", "(", "last", ")", ";", "last", "=", "segments", ".", "pop", "(", ")", ";", "if", "(", "last", ")", "{", "return", "last", ";", "}", "}", "}", "return", "null", ";", "}" ]
Traverse the url segments and map to the tree leafs if it exists. @param {Array} segments URL segments. @param {Object} tree Represents the TLD rules in a tree format. @param {Array} trail Trail of traversed leafs. @param {Int} iteration Keep count of the recursive iterations. @return {String} The extracted domain based on the rules tree.
[ "Traverse", "the", "url", "segments", "and", "map", "to", "the", "tree", "leafs", "if", "it", "exists", "." ]
d55b3a405a32a2d9d06dc47684d63fd91dbf5d6f
https://github.com/Woorank/node-url-tools/blob/d55b3a405a32a2d9d06dc47684d63fd91dbf5d6f/lib/Tld.js#L21-L58
train
blond/ho-iter
lib/reverse.js
reverse
function reverse(iterable) { assert( arguments.length < 2, 'The `resolve()` method not support more than one argument. Use `series() or `evenly()` to combine iterators.' ); if (arguments.length === 0) { return createIterator(); } const iter = createIterator(iterable); const arr = Array.from(iter); let index = arr.length - 1; return { [Symbol.iterator]() { return this; }, next() { if (index === -1) { return done; } return { value: arr[index--], done: false } } } }
javascript
function reverse(iterable) { assert( arguments.length < 2, 'The `resolve()` method not support more than one argument. Use `series() or `evenly()` to combine iterators.' ); if (arguments.length === 0) { return createIterator(); } const iter = createIterator(iterable); const arr = Array.from(iter); let index = arr.length - 1; return { [Symbol.iterator]() { return this; }, next() { if (index === -1) { return done; } return { value: arr[index--], done: false } } } }
[ "function", "reverse", "(", "iterable", ")", "{", "assert", "(", "arguments", ".", "length", "<", "2", ",", "'The `resolve()` method not support more than one argument. Use `series() or `evenly()` to combine iterators.'", ")", ";", "if", "(", "arguments", ".", "length", "===", "0", ")", "{", "return", "createIterator", "(", ")", ";", "}", "const", "iter", "=", "createIterator", "(", "iterable", ")", ";", "const", "arr", "=", "Array", ".", "from", "(", "iter", ")", ";", "let", "index", "=", "arr", ".", "length", "-", "1", ";", "return", "{", "[", "Symbol", ".", "iterator", "]", "(", ")", "{", "return", "this", ";", "}", ",", "next", "(", ")", "{", "if", "(", "index", "===", "-", "1", ")", "{", "return", "done", ";", "}", "return", "{", "value", ":", "arr", "[", "index", "--", "]", ",", "done", ":", "false", "}", "}", "}", "}" ]
Returns an reversed Iterator. **Important:** incompatible with infinite iterator. Don't use infinite iterator, otherwise reverse method will fall into endless loop loop. This is reminiscent of the reversing of an array. @example const reverse = require('ho-iter').reverse; const arr = [1, 2, 3, 4]; const set = new Set([1, 2, 3, 4]); for (let i = arr.length - 1 ; i >= 0; i--) { console.log(arr[i]); } // ➜ 4 3 2 1 for (let item of reverse(set)) { console.log(item); } // ➜ 4 3 2 1 @param {Iterable} iterable iterable object to reversing. @returns {Iterator}
[ "Returns", "an", "reversed", "Iterator", "." ]
b68a4b8585a4b34aed3e9e3a138391c02999d687
https://github.com/blond/ho-iter/blob/b68a4b8585a4b34aed3e9e3a138391c02999d687/lib/reverse.js#L37-L65
train
bootprint/customize-engine-handlebars
lib/utils.js
forEachValue
function forEachValue (obj, iteratee) { Object.keys(obj).forEach((key) => iteratee(obj[key], key, obj)) }
javascript
function forEachValue (obj, iteratee) { Object.keys(obj).forEach((key) => iteratee(obj[key], key, obj)) }
[ "function", "forEachValue", "(", "obj", ",", "iteratee", ")", "{", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "(", "key", ")", "=>", "iteratee", "(", "obj", "[", "key", "]", ",", "key", ",", "obj", ")", ")", "}" ]
Call the iteratee for all values of the object
[ "Call", "the", "iteratee", "for", "all", "values", "of", "the", "object" ]
74ef0b625da20b51a6d5cb6e1ec1d128890add78
https://github.com/bootprint/customize-engine-handlebars/blob/74ef0b625da20b51a6d5cb6e1ec1d128890add78/lib/utils.js#L43-L45
train
reboundjs/rebound
packages/rebound-htmlbars/lib/lazy-value.js
function(){ if(this.cache === NIL){ return void 0; } this.cache = NIL; for (var i = 0, l = this.subscribers.length; i < l; i++) { this.subscribers[i].isLazyValue && this.subscribers[i].makeDirty(); } }
javascript
function(){ if(this.cache === NIL){ return void 0; } this.cache = NIL; for (var i = 0, l = this.subscribers.length; i < l; i++) { this.subscribers[i].isLazyValue && this.subscribers[i].makeDirty(); } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "cache", "===", "NIL", ")", "{", "return", "void", "0", ";", "}", "this", ".", "cache", "=", "NIL", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "this", ".", "subscribers", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "this", ".", "subscribers", "[", "i", "]", ".", "isLazyValue", "&&", "this", ".", "subscribers", "[", "i", "]", ".", "makeDirty", "(", ")", ";", "}", "}" ]
Mark this LazyValue, and all who depend on it, as dirty by setting its cache to NIL. This will force a full re-compute of its value when next requests rather than just returning the cache object.
[ "Mark", "this", "LazyValue", "and", "all", "who", "depend", "on", "it", "as", "dirty", "by", "setting", "its", "cache", "to", "NIL", ".", "This", "will", "force", "a", "full", "re", "-", "compute", "of", "its", "value", "when", "next", "requests", "rather", "than", "just", "returning", "the", "cache", "object", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-htmlbars/lib/lazy-value.js#L90-L96
train
reboundjs/rebound
packages/rebound-htmlbars/lib/lazy-value.js
function() { this.makeDirty(); for (var i = 0, l = this.subscribers.length; i < l; i++) { if(!this.subscribers[i]){ continue; } else if(this.subscribers[i].isLazyValue){ this.subscribers[i].destroyed ? (this.subscribers[i] = void 0) : this.subscribers[i].notify(); } else{ this.subscribers[i](this); } } }
javascript
function() { this.makeDirty(); for (var i = 0, l = this.subscribers.length; i < l; i++) { if(!this.subscribers[i]){ continue; } else if(this.subscribers[i].isLazyValue){ this.subscribers[i].destroyed ? (this.subscribers[i] = void 0) : this.subscribers[i].notify(); } else{ this.subscribers[i](this); } } }
[ "function", "(", ")", "{", "this", ".", "makeDirty", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "this", ".", "subscribers", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "!", "this", ".", "subscribers", "[", "i", "]", ")", "{", "continue", ";", "}", "else", "if", "(", "this", ".", "subscribers", "[", "i", "]", ".", "isLazyValue", ")", "{", "this", ".", "subscribers", "[", "i", "]", ".", "destroyed", "?", "(", "this", ".", "subscribers", "[", "i", "]", "=", "void", "0", ")", ":", "this", ".", "subscribers", "[", "i", "]", ".", "notify", "(", ")", ";", "}", "else", "{", "this", ".", "subscribers", "[", "i", "]", "(", "this", ")", ";", "}", "}", "}" ]
Ensure that this node and all of its dependants are dirty, then call each of its dependants. If a dependant is a LazyValue, and marked as destroyed, remove it fromt the array
[ "Ensure", "that", "this", "node", "and", "all", "of", "its", "dependants", "are", "dirty", "then", "call", "each", "of", "its", "dependants", ".", "If", "a", "dependant", "is", "a", "LazyValue", "and", "marked", "as", "destroyed", "remove", "it", "fromt", "the", "array" ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-htmlbars/lib/lazy-value.js#L101-L112
train
hammy2899/o
src/set.js
set
function set(object, path, value) { // check if the object is an object if (is(object)) { // clone the object let cloned = clone(object); // set a new value for the cloned object so we // can manipulate it const result = cloned; // get the path parts const pathParts = getPathParts(path); // loop over all the path parts for (let index = 0; index < pathParts.length; index += 1) { // get the current key const key = pathParts[index]; // check if the value is an object if (!is(cloned[key])) { // if it isn't an object set it to an empty object cloned[key] = {}; } // check if the current path is the last key if (index === pathParts.length - 1) { // if it is the last key set it as the value cloned[key] = value; } // set the modified values to the object cloned = cloned[key]; } // returned the result return result; } // if the object isn't an object return an empty // object this will keep the return immutable return {}; }
javascript
function set(object, path, value) { // check if the object is an object if (is(object)) { // clone the object let cloned = clone(object); // set a new value for the cloned object so we // can manipulate it const result = cloned; // get the path parts const pathParts = getPathParts(path); // loop over all the path parts for (let index = 0; index < pathParts.length; index += 1) { // get the current key const key = pathParts[index]; // check if the value is an object if (!is(cloned[key])) { // if it isn't an object set it to an empty object cloned[key] = {}; } // check if the current path is the last key if (index === pathParts.length - 1) { // if it is the last key set it as the value cloned[key] = value; } // set the modified values to the object cloned = cloned[key]; } // returned the result return result; } // if the object isn't an object return an empty // object this will keep the return immutable return {}; }
[ "function", "set", "(", "object", ",", "path", ",", "value", ")", "{", "if", "(", "is", "(", "object", ")", ")", "{", "let", "cloned", "=", "clone", "(", "object", ")", ";", "const", "result", "=", "cloned", ";", "const", "pathParts", "=", "getPathParts", "(", "path", ")", ";", "for", "(", "let", "index", "=", "0", ";", "index", "<", "pathParts", ".", "length", ";", "index", "+=", "1", ")", "{", "const", "key", "=", "pathParts", "[", "index", "]", ";", "if", "(", "!", "is", "(", "cloned", "[", "key", "]", ")", ")", "{", "cloned", "[", "key", "]", "=", "{", "}", ";", "}", "if", "(", "index", "===", "pathParts", ".", "length", "-", "1", ")", "{", "cloned", "[", "key", "]", "=", "value", ";", "}", "cloned", "=", "cloned", "[", "key", "]", ";", "}", "return", "result", ";", "}", "return", "{", "}", ";", "}" ]
Set the specified path with the specified value @example const a = { a: 1, b: 2 }; set(a, 'c', 3); // => { a: 1, b: 2, c: 3 } @since 1.0.0 @version 1.0.0 @param {object} object The object to set the value on @param {string} path The path to set the value as @param {*} value The value to set @return {object} The object with the new set value
[ "Set", "the", "specified", "path", "with", "the", "specified", "value" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/set.js#L22-L63
train
audio-lab/lab
plugin/microphone.js
Microphone
function Microphone (options) { var self = this; Block.apply(self, arguments); //get access to the microphone getUserMedia({video: false, audio: true}, function (err, stream) { if (err) { console.log('failed to get microphone'); self.state = 'error'; } else { self.node = self.app.context.createMediaStreamSource(stream); self.restart(); self.state = 'ready'; } }); return self; }
javascript
function Microphone (options) { var self = this; Block.apply(self, arguments); //get access to the microphone getUserMedia({video: false, audio: true}, function (err, stream) { if (err) { console.log('failed to get microphone'); self.state = 'error'; } else { self.node = self.app.context.createMediaStreamSource(stream); self.restart(); self.state = 'ready'; } }); return self; }
[ "function", "Microphone", "(", "options", ")", "{", "var", "self", "=", "this", ";", "Block", ".", "apply", "(", "self", ",", "arguments", ")", ";", "getUserMedia", "(", "{", "video", ":", "false", ",", "audio", ":", "true", "}", ",", "function", "(", "err", ",", "stream", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "'failed to get microphone'", ")", ";", "self", ".", "state", "=", "'error'", ";", "}", "else", "{", "self", ".", "node", "=", "self", ".", "app", ".", "context", ".", "createMediaStreamSource", "(", "stream", ")", ";", "self", ".", "restart", "(", ")", ";", "self", ".", "state", "=", "'ready'", ";", "}", "}", ")", ";", "return", "self", ";", "}" ]
Create microphone based on usermedia @constructor
[ "Create", "microphone", "based", "on", "usermedia" ]
ec5b40d48e36be179dffbfd23ba666c1bc2e9416
https://github.com/audio-lab/lab/blob/ec5b40d48e36be179dffbfd23ba666c1bc2e9416/plugin/microphone.js#L18-L36
train
bootprint/customize-engine-handlebars
index.js
moduleIfString
function moduleIfString (pathOrObject, type) { // If this is a string, treat if as module to be required try { if (_.isString(pathOrObject)) { // Attempt to find module without resolving the contents // If there is an error, the module does not exist (which // is ignored at the moment) // If there is no error, the module should be loaded and error while loading // the module should be reported require.resolve(path.resolve(pathOrObject)) } } catch (e) { debug('Ignoring missing ' + type + ' module: ' + pathOrObject) pathOrObject = undefined } // Require module if needed if (_.isString(pathOrObject)) { var absPath = path.resolve(pathOrObject) delete require.cache[absPath] pathOrObject = require(absPath) } return pathOrObject }
javascript
function moduleIfString (pathOrObject, type) { // If this is a string, treat if as module to be required try { if (_.isString(pathOrObject)) { // Attempt to find module without resolving the contents // If there is an error, the module does not exist (which // is ignored at the moment) // If there is no error, the module should be loaded and error while loading // the module should be reported require.resolve(path.resolve(pathOrObject)) } } catch (e) { debug('Ignoring missing ' + type + ' module: ' + pathOrObject) pathOrObject = undefined } // Require module if needed if (_.isString(pathOrObject)) { var absPath = path.resolve(pathOrObject) delete require.cache[absPath] pathOrObject = require(absPath) } return pathOrObject }
[ "function", "moduleIfString", "(", "pathOrObject", ",", "type", ")", "{", "try", "{", "if", "(", "_", ".", "isString", "(", "pathOrObject", ")", ")", "{", "require", ".", "resolve", "(", "path", ".", "resolve", "(", "pathOrObject", ")", ")", "}", "}", "catch", "(", "e", ")", "{", "debug", "(", "'Ignoring missing '", "+", "type", "+", "' module: '", "+", "pathOrObject", ")", "pathOrObject", "=", "undefined", "}", "if", "(", "_", ".", "isString", "(", "pathOrObject", ")", ")", "{", "var", "absPath", "=", "path", ".", "resolve", "(", "pathOrObject", ")", "delete", "require", ".", "cache", "[", "absPath", "]", "pathOrObject", "=", "require", "(", "absPath", ")", "}", "return", "pathOrObject", "}" ]
Internal function that returns `require`s a module if the parameter is a string. If parameter is a string (path) and a file with that path exists, load it as module If the parameter is not a string, just return it. If the parameter is a string, but the file does not exist, return `undefined` @param {string|*} pathOrObject path to the file or configuration @param {string} type additional information that can displayed in case the module is not found. @returns {*} @access private
[ "Internal", "function", "that", "returns", "require", "s", "a", "module", "if", "the", "parameter", "is", "a", "string", "." ]
74ef0b625da20b51a6d5cb6e1ec1d128890add78
https://github.com/bootprint/customize-engine-handlebars/blob/74ef0b625da20b51a6d5cb6e1ec1d128890add78/index.js#L214-L237
train
ArchimediaZerogroup/alchemy-custom-model
vendor/assets/elfinder_OLD/main.default.js
function(fm, extraObj) { // `init` event callback function fm.bind('init', function() { // Optional for Japanese decoder "encoding-japanese" if (fm.lang === 'ja') { require( [ 'encoding-japanese' ], function(Encoding) { if (Encoding && Encoding.convert) { fm.registRawStringDecoder(function(s) { return Encoding.convert(s, {to:'UNICODE',type:'string'}); }); } } ); } }); }
javascript
function(fm, extraObj) { // `init` event callback function fm.bind('init', function() { // Optional for Japanese decoder "encoding-japanese" if (fm.lang === 'ja') { require( [ 'encoding-japanese' ], function(Encoding) { if (Encoding && Encoding.convert) { fm.registRawStringDecoder(function(s) { return Encoding.convert(s, {to:'UNICODE',type:'string'}); }); } } ); } }); }
[ "function", "(", "fm", ",", "extraObj", ")", "{", "fm", ".", "bind", "(", "'init'", ",", "function", "(", ")", "{", "if", "(", "fm", ".", "lang", "===", "'ja'", ")", "{", "require", "(", "[", "'encoding-japanese'", "]", ",", "function", "(", "Encoding", ")", "{", "if", "(", "Encoding", "&&", "Encoding", ".", "convert", ")", "{", "fm", ".", "registRawStringDecoder", "(", "function", "(", "s", ")", "{", "return", "Encoding", ".", "convert", "(", "s", ",", "{", "to", ":", "'UNICODE'", ",", "type", ":", "'string'", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
2nd Arg - before boot up function
[ "2nd", "Arg", "-", "before", "boot", "up", "function" ]
1654c68c48dd0f760d46eac720f59fed75a32357
https://github.com/ArchimediaZerogroup/alchemy-custom-model/blob/1654c68c48dd0f760d46eac720f59fed75a32357/vendor/assets/elfinder_OLD/main.default.js#L61-L78
train
nodeGame/nodegame-monitor
public/js/GameControls.js
createCmdButton
function createCmdButton(cmd, label, forceCheckbox, className) { var button; button = document.createElement('button'); button.className = className || 'btn'; button.innerHTML = label; button.onclick = function() { var cl; var clients, doLogic; cl = node.game.clientList; // Get selected clients. clients = cl.getSelectedClients(); if (!clients || clients.length === 0) return; // If the room's logic client is selected, handle it specially. if (node.game.roomLogicId) { doLogic = J.removeElement(cl.roomLogicId, clients); } node.socket.send(node.msg.create({ target: 'SERVERCOMMAND', text: 'ROOMCOMMAND', data: { type: cmd, roomId: cl.roomId, doLogic: !!doLogic, clients: clients, force: forceCheckbox.checked } })); }; return button; }
javascript
function createCmdButton(cmd, label, forceCheckbox, className) { var button; button = document.createElement('button'); button.className = className || 'btn'; button.innerHTML = label; button.onclick = function() { var cl; var clients, doLogic; cl = node.game.clientList; // Get selected clients. clients = cl.getSelectedClients(); if (!clients || clients.length === 0) return; // If the room's logic client is selected, handle it specially. if (node.game.roomLogicId) { doLogic = J.removeElement(cl.roomLogicId, clients); } node.socket.send(node.msg.create({ target: 'SERVERCOMMAND', text: 'ROOMCOMMAND', data: { type: cmd, roomId: cl.roomId, doLogic: !!doLogic, clients: clients, force: forceCheckbox.checked } })); }; return button; }
[ "function", "createCmdButton", "(", "cmd", ",", "label", ",", "forceCheckbox", ",", "className", ")", "{", "var", "button", ";", "button", "=", "document", ".", "createElement", "(", "'button'", ")", ";", "button", ".", "className", "=", "className", "||", "'btn'", ";", "button", ".", "innerHTML", "=", "label", ";", "button", ".", "onclick", "=", "function", "(", ")", "{", "var", "cl", ";", "var", "clients", ",", "doLogic", ";", "cl", "=", "node", ".", "game", ".", "clientList", ";", "clients", "=", "cl", ".", "getSelectedClients", "(", ")", ";", "if", "(", "!", "clients", "||", "clients", ".", "length", "===", "0", ")", "return", ";", "if", "(", "node", ".", "game", ".", "roomLogicId", ")", "{", "doLogic", "=", "J", ".", "removeElement", "(", "cl", ".", "roomLogicId", ",", "clients", ")", ";", "}", "node", ".", "socket", ".", "send", "(", "node", ".", "msg", ".", "create", "(", "{", "target", ":", "'SERVERCOMMAND'", ",", "text", ":", "'ROOMCOMMAND'", ",", "data", ":", "{", "type", ":", "cmd", ",", "roomId", ":", "cl", ".", "roomId", ",", "doLogic", ":", "!", "!", "doLogic", ",", "clients", ":", "clients", ",", "force", ":", "forceCheckbox", ".", "checked", "}", "}", ")", ")", ";", "}", ";", "return", "button", ";", "}" ]
Helper functions. Make a button that sends a given ROOMCOMMAND.
[ "Helper", "functions", ".", "Make", "a", "button", "that", "sends", "a", "given", "ROOMCOMMAND", "." ]
da36cf93628d72a1e9837d9ad12a3b0fa23e04ef
https://github.com/nodeGame/nodegame-monitor/blob/da36cf93628d72a1e9837d9ad12a3b0fa23e04ef/public/js/GameControls.js#L136-L167
train
reboundjs/rebound
packages/rebound-utils/lib/events.js
function() { var e = this.originalEvent; this.defaultPrevented = true; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ){ e.preventDefault(); } }
javascript
function() { var e = this.originalEvent; this.defaultPrevented = true; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ){ e.preventDefault(); } }
[ "function", "(", ")", "{", "var", "e", "=", "this", ".", "originalEvent", ";", "this", ".", "defaultPrevented", "=", "true", ";", "this", ".", "isDefaultPrevented", "=", "returnTrue", ";", "if", "(", "e", "&&", "e", ".", "preventDefault", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "}", "}" ]
Call preventDefault on original event object.
[ "Call", "preventDefault", "on", "original", "event", "object", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-utils/lib/events.js#L61-L66
train
reboundjs/rebound
packages/rebound-utils/lib/events.js
getCallbacks
function getCallbacks(target, delegate, eventType){ var callbacks = []; if(target.delegateGroup && EVENT_CACHE[target.delegateGroup][eventType]){ _.each(EVENT_CACHE[target.delegateGroup][eventType], function(callbacksList, delegateId){ if(_.isArray(callbacksList) && (delegateId === delegate.delegateId || ( delegate.matchesSelector && delegate.matchesSelector(delegateId) )) ){ callbacks = callbacks.concat(callbacksList); } }); } return callbacks; }
javascript
function getCallbacks(target, delegate, eventType){ var callbacks = []; if(target.delegateGroup && EVENT_CACHE[target.delegateGroup][eventType]){ _.each(EVENT_CACHE[target.delegateGroup][eventType], function(callbacksList, delegateId){ if(_.isArray(callbacksList) && (delegateId === delegate.delegateId || ( delegate.matchesSelector && delegate.matchesSelector(delegateId) )) ){ callbacks = callbacks.concat(callbacksList); } }); } return callbacks; }
[ "function", "getCallbacks", "(", "target", ",", "delegate", ",", "eventType", ")", "{", "var", "callbacks", "=", "[", "]", ";", "if", "(", "target", ".", "delegateGroup", "&&", "EVENT_CACHE", "[", "target", ".", "delegateGroup", "]", "[", "eventType", "]", ")", "{", "_", ".", "each", "(", "EVENT_CACHE", "[", "target", ".", "delegateGroup", "]", "[", "eventType", "]", ",", "function", "(", "callbacksList", ",", "delegateId", ")", "{", "if", "(", "_", ".", "isArray", "(", "callbacksList", ")", "&&", "(", "delegateId", "===", "delegate", ".", "delegateId", "||", "(", "delegate", ".", "matchesSelector", "&&", "delegate", ".", "matchesSelector", "(", "delegateId", ")", ")", ")", ")", "{", "callbacks", "=", "callbacks", ".", "concat", "(", "callbacksList", ")", ";", "}", "}", ")", ";", "}", "return", "callbacks", ";", "}" ]
Given a delegate element, an event type, and a test element, test every delegate ID. If it is the same as our test element's delegate ID, or if the test element matches the delegate ID when it is used as a CSS selector, add the callback to the list of callbacks to call.
[ "Given", "a", "delegate", "element", "an", "event", "type", "and", "a", "test", "element", "test", "every", "delegate", "ID", ".", "If", "it", "is", "the", "same", "as", "our", "test", "element", "s", "delegate", "ID", "or", "if", "the", "test", "element", "matches", "the", "delegate", "ID", "when", "it", "is", "used", "as", "a", "CSS", "selector", "add", "the", "callback", "to", "the", "list", "of", "callbacks", "to", "call", "." ]
a934c9ae7d2c23c1e9b259dd1648e22bf781f233
https://github.com/reboundjs/rebound/blob/a934c9ae7d2c23c1e9b259dd1648e22bf781f233/packages/rebound-utils/lib/events.js#L89-L99
train
MRN-Code/bookshelf-shield
lib/wrapRelations.js
enumerateFunctions
function enumerateFunctions(relations) { const blacklist = [ 'use', 'tearDown', 'define' ]; return _.reduce(relations, function(functions, prop, key) { if (blacklist.indexOf(key) === -1 && _.isFunction(prop)) { functions.push(key); } return functions; }, []); }
javascript
function enumerateFunctions(relations) { const blacklist = [ 'use', 'tearDown', 'define' ]; return _.reduce(relations, function(functions, prop, key) { if (blacklist.indexOf(key) === -1 && _.isFunction(prop)) { functions.push(key); } return functions; }, []); }
[ "function", "enumerateFunctions", "(", "relations", ")", "{", "const", "blacklist", "=", "[", "'use'", ",", "'tearDown'", ",", "'define'", "]", ";", "return", "_", ".", "reduce", "(", "relations", ",", "function", "(", "functions", ",", "prop", ",", "key", ")", "{", "if", "(", "blacklist", ".", "indexOf", "(", "key", ")", "===", "-", "1", "&&", "_", ".", "isFunction", "(", "prop", ")", ")", "{", "functions", ".", "push", "(", "key", ")", ";", "}", "return", "functions", ";", "}", ",", "[", "]", ")", ";", "}" ]
loop through enumerable properties of obj and store the keys of properties which are functions and are not in the blacklist @param {object} relations @return {array} an array of keys
[ "loop", "through", "enumerable", "properties", "of", "obj", "and", "store", "the", "keys", "of", "properties", "which", "are", "functions", "and", "are", "not", "in", "the", "blacklist" ]
4f13ed22e3f951b3e7733823841c7bf9ef88df0b
https://github.com/MRN-Code/bookshelf-shield/blob/4f13ed22e3f951b3e7733823841c7bf9ef88df0b/lib/wrapRelations.js#L13-L26
train
hammy2899/o
src/each.js
each
function each(object, iterator, follow = false) { // check if the object is an object and isn't empty // if it is it would be pointless running the forEach if (is(object) && !empty(object) && typeof iterator === 'function') { // if follow is true flatten the object keys so // its easy to get the path and values if follow // is false it will just be the base object // therefore it will only use the base keys const flattenedObject = follow ? deflate(object) : object; // loop over the keys of the object Object.keys(flattenedObject).forEach((key) => { // get the value of the current key const value = flattenedObject[key]; // run the iterator with the key and value iterator(key, value); }); // return true because the iterator was ran return true; } // return false because the iterator couldn't of been ran return false; }
javascript
function each(object, iterator, follow = false) { // check if the object is an object and isn't empty // if it is it would be pointless running the forEach if (is(object) && !empty(object) && typeof iterator === 'function') { // if follow is true flatten the object keys so // its easy to get the path and values if follow // is false it will just be the base object // therefore it will only use the base keys const flattenedObject = follow ? deflate(object) : object; // loop over the keys of the object Object.keys(flattenedObject).forEach((key) => { // get the value of the current key const value = flattenedObject[key]; // run the iterator with the key and value iterator(key, value); }); // return true because the iterator was ran return true; } // return false because the iterator couldn't of been ran return false; }
[ "function", "each", "(", "object", ",", "iterator", ",", "follow", "=", "false", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", "&&", "typeof", "iterator", "===", "'function'", ")", "{", "const", "flattenedObject", "=", "follow", "?", "deflate", "(", "object", ")", ":", "object", ";", "Object", ".", "keys", "(", "flattenedObject", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "const", "value", "=", "flattenedObject", "[", "key", "]", ";", "iterator", "(", "key", ",", "value", ")", ";", "}", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Foreach over the object @example const a = { a: 1, b: 2 }; each(a, (key, value) => { console.log(`${key}:`, value) }); // => a: 1 // => b: 2 @since 1.0.0 @version 1.0.0 @param {object} object The object to iterate over @param {function(key: string, value: *)} iterator The iterator function @param {boolean} [follow=false] Whether to follow objects
[ "Foreach", "over", "the", "object" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/each.js#L22-L49
train
hammy2899/o
src/includes.js
includes
function includes(object, value, follow = false) { // if the object is an object and is not empty if (is(object) && !empty(object)) { // create an result variable as false let result = false; // for each key/value in the object // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, objValue) => { // if the result isn't already true if (!result) { // check if the object value is equal to // the specified value if (objValue === value) { // if they are the same set the result // to true result = true; } } }, follow); // return the result return result; } // if the object isn't an object or is empty return // false because the object can't be checked return false; }
javascript
function includes(object, value, follow = false) { // if the object is an object and is not empty if (is(object) && !empty(object)) { // create an result variable as false let result = false; // for each key/value in the object // follow is passed into each therefore the // each function works out whether to follow // the objects each(object, (key, objValue) => { // if the result isn't already true if (!result) { // check if the object value is equal to // the specified value if (objValue === value) { // if they are the same set the result // to true result = true; } } }, follow); // return the result return result; } // if the object isn't an object or is empty return // false because the object can't be checked return false; }
[ "function", "includes", "(", "object", ",", "value", ",", "follow", "=", "false", ")", "{", "if", "(", "is", "(", "object", ")", "&&", "!", "empty", "(", "object", ")", ")", "{", "let", "result", "=", "false", ";", "each", "(", "object", ",", "(", "key", ",", "objValue", ")", "=>", "{", "if", "(", "!", "result", ")", "{", "if", "(", "objValue", "===", "value", ")", "{", "result", "=", "true", ";", "}", "}", "}", ",", "follow", ")", ";", "return", "result", ";", "}", "return", "false", ";", "}" ]
Check if the object includes the specified object @example const a = { a: 1, b: 2, c: 3 }; includes(a, 1); // => true includes(a, 5); // => false @since 1.0.0 @version 1.0.0 @param {object} object The object to check @param {*} value The value to check for @param {boolean} follow Whether to follow objects @returns {boolean} Whether the object contains the specified value
[ "Check", "if", "the", "object", "includes", "the", "specified", "object" ]
666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54
https://github.com/hammy2899/o/blob/666c9faa36586c0bcdecc0f2a7e1f069a7a3ce54/src/includes.js#L23-L53
train
anodejs/node-rebus
lib/rebus.js
_publish
function _publish(obj, callback) { // Write the object to the separate file. var shortname = prop + '.json'; var data = JSON.stringify(obj); var hash = _checkNewHash(shortname, data); if (!hash) { // No need to publish if the data is the same. return callback(); } published[shortname] = true; // Update new object and call notifications. _updateObject(shortname, obj, hash); var fullname = path.join(folder, shortname); fs.writeFile(fullname, data, function (err) { if (err) { console.error('Failed to write file %s err:', fullname, err); } return callback(err); }); }
javascript
function _publish(obj, callback) { // Write the object to the separate file. var shortname = prop + '.json'; var data = JSON.stringify(obj); var hash = _checkNewHash(shortname, data); if (!hash) { // No need to publish if the data is the same. return callback(); } published[shortname] = true; // Update new object and call notifications. _updateObject(shortname, obj, hash); var fullname = path.join(folder, shortname); fs.writeFile(fullname, data, function (err) { if (err) { console.error('Failed to write file %s err:', fullname, err); } return callback(err); }); }
[ "function", "_publish", "(", "obj", ",", "callback", ")", "{", "var", "shortname", "=", "prop", "+", "'.json'", ";", "var", "data", "=", "JSON", ".", "stringify", "(", "obj", ")", ";", "var", "hash", "=", "_checkNewHash", "(", "shortname", ",", "data", ")", ";", "if", "(", "!", "hash", ")", "{", "return", "callback", "(", ")", ";", "}", "published", "[", "shortname", "]", "=", "true", ";", "_updateObject", "(", "shortname", ",", "obj", ",", "hash", ")", ";", "var", "fullname", "=", "path", ".", "join", "(", "folder", ",", "shortname", ")", ";", "fs", ".", "writeFile", "(", "fullname", ",", "data", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "'Failed to write file %s err:'", ",", "fullname", ",", "err", ")", ";", "}", "return", "callback", "(", "err", ")", ";", "}", ")", ";", "}" ]
Worker for publishing queue.
[ "Worker", "for", "publishing", "queue", "." ]
fdf415d91dc72991263d6f70f678507cfafdece5
https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L158-L177
train
anodejs/node-rebus
lib/rebus.js
close
function close() { if (watcher && !closed) { if (options.persistent) { // Close handle only if watcher was created persistent. watcher.close(); } else { // Stop handling change events. watcher.removeAllListeners(); // Leave watcher on error events that may come from unclosed handle. watcher.on('error', function (err) { }); } closed = true; } }
javascript
function close() { if (watcher && !closed) { if (options.persistent) { // Close handle only if watcher was created persistent. watcher.close(); } else { // Stop handling change events. watcher.removeAllListeners(); // Leave watcher on error events that may come from unclosed handle. watcher.on('error', function (err) { }); } closed = true; } }
[ "function", "close", "(", ")", "{", "if", "(", "watcher", "&&", "!", "closed", ")", "{", "if", "(", "options", ".", "persistent", ")", "{", "watcher", ".", "close", "(", ")", ";", "}", "else", "{", "watcher", ".", "removeAllListeners", "(", ")", ";", "watcher", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "}", ")", ";", "}", "closed", "=", "true", ";", "}", "}" ]
Cleanup rebus instance.
[ "Cleanup", "rebus", "instance", "." ]
fdf415d91dc72991263d6f70f678507cfafdece5
https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L203-L217
train
anodejs/node-rebus
lib/rebus.js
_updateSingleton
function _updateSingleton() { if (!options.singletons) { return; } if (process.rebusinstances[folder]) { // Somebody added instance already. return; } // Save this instance to return the same for the same folder. process.rebusinstances[folder] = instance; }
javascript
function _updateSingleton() { if (!options.singletons) { return; } if (process.rebusinstances[folder]) { // Somebody added instance already. return; } // Save this instance to return the same for the same folder. process.rebusinstances[folder] = instance; }
[ "function", "_updateSingleton", "(", ")", "{", "if", "(", "!", "options", ".", "singletons", ")", "{", "return", ";", "}", "if", "(", "process", ".", "rebusinstances", "[", "folder", "]", ")", "{", "return", ";", "}", "process", ".", "rebusinstances", "[", "folder", "]", "=", "instance", ";", "}" ]
Store the instance of rebus per process to be reused if requried again.
[ "Store", "the", "instance", "of", "rebus", "per", "process", "to", "be", "reused", "if", "requried", "again", "." ]
fdf415d91dc72991263d6f70f678507cfafdece5
https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L245-L255
train
anodejs/node-rebus
lib/rebus.js
_startWatchdog
function _startWatchdog() { if (!watcher) { var watcherOptions = { persistent: !!options.persistent }; watcher = fs.watch(folder, watcherOptions, function (event, filename) { if (event === 'change' && filename.charAt(0) != '.') { // On every change load the changed file. This will trigger notifications for interested // subscribers. _loadFile(filename); } }); } }
javascript
function _startWatchdog() { if (!watcher) { var watcherOptions = { persistent: !!options.persistent }; watcher = fs.watch(folder, watcherOptions, function (event, filename) { if (event === 'change' && filename.charAt(0) != '.') { // On every change load the changed file. This will trigger notifications for interested // subscribers. _loadFile(filename); } }); } }
[ "function", "_startWatchdog", "(", ")", "{", "if", "(", "!", "watcher", ")", "{", "var", "watcherOptions", "=", "{", "persistent", ":", "!", "!", "options", ".", "persistent", "}", ";", "watcher", "=", "fs", ".", "watch", "(", "folder", ",", "watcherOptions", ",", "function", "(", "event", ",", "filename", ")", "{", "if", "(", "event", "===", "'change'", "&&", "filename", ".", "charAt", "(", "0", ")", "!=", "'.'", ")", "{", "_loadFile", "(", "filename", ")", ";", "}", "}", ")", ";", "}", "}" ]
Start watching directory changes.
[ "Start", "watching", "directory", "changes", "." ]
fdf415d91dc72991263d6f70f678507cfafdece5
https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L265-L276
train
anodejs/node-rebus
lib/rebus.js
_loadFile
function _loadFile(filename, callback) { callback = callback || function () { }; if (filename.charAt(0) == '.') { callback(); return; } var filepath = path.join(folder, filename); fs.readFile(filepath, function (err, data) { if (err) { console.error('Failed to read file ' + filepath + ' err:', err); callback(err); return; } try { _loadData(filename, data.toString()); } catch (e) { console.info('Object ' + filename + ' was not yet fully written, exception:', e); // There will be another notification of change when the last write to file is completed. // Meanwhile leave the previous value. if (loader) { // Store this error to wait until file will be successfully loaded for the 1st time. loader.errors[filename] = e; } // Don't return error to continue asynchronous loading of other files. Errors are assembled on loader. callback(); return; } console.log('Loaded ' + filename); if (loader) { if (loader.errors[filename]) { // File that previously failed to load, now is loaded. delete loader.errors[filename]; var countErrors = Object.keys(loader.errors).length; if (countErrors === 0) { // All errors are fixed. This is the time to complete loading. var initcb = loader.callback; loader = null; _updateSingleton(); initcb(); } } } callback(); }); }
javascript
function _loadFile(filename, callback) { callback = callback || function () { }; if (filename.charAt(0) == '.') { callback(); return; } var filepath = path.join(folder, filename); fs.readFile(filepath, function (err, data) { if (err) { console.error('Failed to read file ' + filepath + ' err:', err); callback(err); return; } try { _loadData(filename, data.toString()); } catch (e) { console.info('Object ' + filename + ' was not yet fully written, exception:', e); // There will be another notification of change when the last write to file is completed. // Meanwhile leave the previous value. if (loader) { // Store this error to wait until file will be successfully loaded for the 1st time. loader.errors[filename] = e; } // Don't return error to continue asynchronous loading of other files. Errors are assembled on loader. callback(); return; } console.log('Loaded ' + filename); if (loader) { if (loader.errors[filename]) { // File that previously failed to load, now is loaded. delete loader.errors[filename]; var countErrors = Object.keys(loader.errors).length; if (countErrors === 0) { // All errors are fixed. This is the time to complete loading. var initcb = loader.callback; loader = null; _updateSingleton(); initcb(); } } } callback(); }); }
[ "function", "_loadFile", "(", "filename", ",", "callback", ")", "{", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "if", "(", "filename", ".", "charAt", "(", "0", ")", "==", "'.'", ")", "{", "callback", "(", ")", ";", "return", ";", "}", "var", "filepath", "=", "path", ".", "join", "(", "folder", ",", "filename", ")", ";", "fs", ".", "readFile", "(", "filepath", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "'Failed to read file '", "+", "filepath", "+", "' err:'", ",", "err", ")", ";", "callback", "(", "err", ")", ";", "return", ";", "}", "try", "{", "_loadData", "(", "filename", ",", "data", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "info", "(", "'Object '", "+", "filename", "+", "' was not yet fully written, exception:'", ",", "e", ")", ";", "if", "(", "loader", ")", "{", "loader", ".", "errors", "[", "filename", "]", "=", "e", ";", "}", "callback", "(", ")", ";", "return", ";", "}", "console", ".", "log", "(", "'Loaded '", "+", "filename", ")", ";", "if", "(", "loader", ")", "{", "if", "(", "loader", ".", "errors", "[", "filename", "]", ")", "{", "delete", "loader", ".", "errors", "[", "filename", "]", ";", "var", "countErrors", "=", "Object", ".", "keys", "(", "loader", ".", "errors", ")", ".", "length", ";", "if", "(", "countErrors", "===", "0", ")", "{", "var", "initcb", "=", "loader", ".", "callback", ";", "loader", "=", "null", ";", "_updateSingleton", "(", ")", ";", "initcb", "(", ")", ";", "}", "}", "}", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Load object from a file. Update state and call notifications.
[ "Load", "object", "from", "a", "file", ".", "Update", "state", "and", "call", "notifications", "." ]
fdf415d91dc72991263d6f70f678507cfafdece5
https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L280-L327
train
anodejs/node-rebus
lib/rebus.js
_traverse
function _traverse(props, obj, notification) { var length = props.length; var refobj = shared; var refmeta = meta; var handler = {}; var fns = []; for (var i = 0; i < length; i++) { var prop = props[i]; if (!refmeta[prop]) { refmeta[prop] = {}; refmeta[prop][nfs] = {}; } var currentmeta = refmeta[prop]; if (!refobj[prop]) { refobj[prop] = {}; } var currentobj = refobj[prop]; if (i === (length - 1)) { // The end of the path. if (obj) { // Pin the object here. refobj[prop] = obj; // Since object changed, append all notifications in the subtree. _traverseSubtree(currentmeta, obj, fns); } if (notification) { // Pin notification at the end of the path. var id = freeId++; currentmeta[nfs][id] = notification; // Return value indicates where the notification was pinned. handler = { id: id, close: closeNotification }; handler[nfs] = currentmeta[nfs]; // Call the notification with initial value of the object. // Call notification in the next tick, so that return value from subsribtion // will be available. process.nextTick(function () { notification(currentobj); }); } } else if (obj) { // If change occured, call all notifications along the path. _pushNotifications(currentmeta, currentobj, fns); } // Go deep into the tree. refobj = currentobj; refmeta = currentmeta; } if (obj) { // Call all notifications. async.parallel(fns); } return handler; }
javascript
function _traverse(props, obj, notification) { var length = props.length; var refobj = shared; var refmeta = meta; var handler = {}; var fns = []; for (var i = 0; i < length; i++) { var prop = props[i]; if (!refmeta[prop]) { refmeta[prop] = {}; refmeta[prop][nfs] = {}; } var currentmeta = refmeta[prop]; if (!refobj[prop]) { refobj[prop] = {}; } var currentobj = refobj[prop]; if (i === (length - 1)) { // The end of the path. if (obj) { // Pin the object here. refobj[prop] = obj; // Since object changed, append all notifications in the subtree. _traverseSubtree(currentmeta, obj, fns); } if (notification) { // Pin notification at the end of the path. var id = freeId++; currentmeta[nfs][id] = notification; // Return value indicates where the notification was pinned. handler = { id: id, close: closeNotification }; handler[nfs] = currentmeta[nfs]; // Call the notification with initial value of the object. // Call notification in the next tick, so that return value from subsribtion // will be available. process.nextTick(function () { notification(currentobj); }); } } else if (obj) { // If change occured, call all notifications along the path. _pushNotifications(currentmeta, currentobj, fns); } // Go deep into the tree. refobj = currentobj; refmeta = currentmeta; } if (obj) { // Call all notifications. async.parallel(fns); } return handler; }
[ "function", "_traverse", "(", "props", ",", "obj", ",", "notification", ")", "{", "var", "length", "=", "props", ".", "length", ";", "var", "refobj", "=", "shared", ";", "var", "refmeta", "=", "meta", ";", "var", "handler", "=", "{", "}", ";", "var", "fns", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "var", "prop", "=", "props", "[", "i", "]", ";", "if", "(", "!", "refmeta", "[", "prop", "]", ")", "{", "refmeta", "[", "prop", "]", "=", "{", "}", ";", "refmeta", "[", "prop", "]", "[", "nfs", "]", "=", "{", "}", ";", "}", "var", "currentmeta", "=", "refmeta", "[", "prop", "]", ";", "if", "(", "!", "refobj", "[", "prop", "]", ")", "{", "refobj", "[", "prop", "]", "=", "{", "}", ";", "}", "var", "currentobj", "=", "refobj", "[", "prop", "]", ";", "if", "(", "i", "===", "(", "length", "-", "1", ")", ")", "{", "if", "(", "obj", ")", "{", "refobj", "[", "prop", "]", "=", "obj", ";", "_traverseSubtree", "(", "currentmeta", ",", "obj", ",", "fns", ")", ";", "}", "if", "(", "notification", ")", "{", "var", "id", "=", "freeId", "++", ";", "currentmeta", "[", "nfs", "]", "[", "id", "]", "=", "notification", ";", "handler", "=", "{", "id", ":", "id", ",", "close", ":", "closeNotification", "}", ";", "handler", "[", "nfs", "]", "=", "currentmeta", "[", "nfs", "]", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "notification", "(", "currentobj", ")", ";", "}", ")", ";", "}", "}", "else", "if", "(", "obj", ")", "{", "_pushNotifications", "(", "currentmeta", ",", "currentobj", ",", "fns", ")", ";", "}", "refobj", "=", "currentobj", ";", "refmeta", "=", "currentmeta", ";", "}", "if", "(", "obj", ")", "{", "async", ".", "parallel", "(", "fns", ")", ";", "}", "return", "handler", ";", "}" ]
Traverse the shared object according to property path. If object is specified, call all affected notifications. Those are the notifications along the property path and in the subtree at the end of the path. props - the path in the shared object. obj - if defined, pin the object at the end of the specified path. notification - if defined, pin the notification at the end of the specified path. Returns - if called with notification, returns the handler with information where the notification was pinned, so can be unpinned later.
[ "Traverse", "the", "shared", "object", "according", "to", "property", "path", ".", "If", "object", "is", "specified", "call", "all", "affected", "notifications", ".", "Those", "are", "the", "notifications", "along", "the", "property", "path", "and", "in", "the", "subtree", "at", "the", "end", "of", "the", "path", ".", "props", "-", "the", "path", "in", "the", "shared", "object", ".", "obj", "-", "if", "defined", "pin", "the", "object", "at", "the", "end", "of", "the", "specified", "path", ".", "notification", "-", "if", "defined", "pin", "the", "notification", "at", "the", "end", "of", "the", "specified", "path", ".", "Returns", "-", "if", "called", "with", "notification", "returns", "the", "handler", "with", "information", "where", "the", "notification", "was", "pinned", "so", "can", "be", "unpinned", "later", "." ]
fdf415d91dc72991263d6f70f678507cfafdece5
https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L370-L432
train
anodejs/node-rebus
lib/rebus.js
_traverseSubtree
function _traverseSubtree(meta, obj, fns) { _pushNotifications(meta, obj, fns); for (var key in meta) { if (key === nfs) { continue; } var subobj; if (obj) { subobj = obj[key]; } _traverseSubtree(meta[key], subobj, fns); } }
javascript
function _traverseSubtree(meta, obj, fns) { _pushNotifications(meta, obj, fns); for (var key in meta) { if (key === nfs) { continue; } var subobj; if (obj) { subobj = obj[key]; } _traverseSubtree(meta[key], subobj, fns); } }
[ "function", "_traverseSubtree", "(", "meta", ",", "obj", ",", "fns", ")", "{", "_pushNotifications", "(", "meta", ",", "obj", ",", "fns", ")", ";", "for", "(", "var", "key", "in", "meta", ")", "{", "if", "(", "key", "===", "nfs", ")", "{", "continue", ";", "}", "var", "subobj", ";", "if", "(", "obj", ")", "{", "subobj", "=", "obj", "[", "key", "]", ";", "}", "_traverseSubtree", "(", "meta", "[", "key", "]", ",", "subobj", ",", "fns", ")", ";", "}", "}" ]
Append notificaitons for entire subtree.
[ "Append", "notificaitons", "for", "entire", "subtree", "." ]
fdf415d91dc72991263d6f70f678507cfafdece5
https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L435-L447
train
anodejs/node-rebus
lib/rebus.js
_pushNotifications
function _pushNotifications(meta, obj, fns) { for (var id in meta[nfs]) { fns.push(function (i) { return function () { meta[nfs][i](obj); } } (id)); } }
javascript
function _pushNotifications(meta, obj, fns) { for (var id in meta[nfs]) { fns.push(function (i) { return function () { meta[nfs][i](obj); } } (id)); } }
[ "function", "_pushNotifications", "(", "meta", ",", "obj", ",", "fns", ")", "{", "for", "(", "var", "id", "in", "meta", "[", "nfs", "]", ")", "{", "fns", ".", "push", "(", "function", "(", "i", ")", "{", "return", "function", "(", ")", "{", "meta", "[", "nfs", "]", "[", "i", "]", "(", "obj", ")", ";", "}", "}", "(", "id", ")", ")", ";", "}", "}" ]
Append notification from the tree node.
[ "Append", "notification", "from", "the", "tree", "node", "." ]
fdf415d91dc72991263d6f70f678507cfafdece5
https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L450-L458
train
hash-bang/tree-tools
dist/ngTreeTools.js
children
function children(tree, query, options) { var compiledQuery = query ? _.matches(query) : null; var settings = _.defaults(options, { childNode: ['children'] }); settings.childNode = _.castArray(settings.childNode); var rootNode = query ? treeTools.find(tree, query) : tree; var seekStack = []; var seekDown = function seekDown(branch, level) { if (level > 0) seekStack.push(branch); settings.childNode.some(function (key) { if (branch[key] && _.isArray(branch[key])) { branch[key].forEach(function (branchChild) { seekDown(branchChild, level + 1); }); return true; } }); }; seekDown(rootNode, 0); return seekStack; }
javascript
function children(tree, query, options) { var compiledQuery = query ? _.matches(query) : null; var settings = _.defaults(options, { childNode: ['children'] }); settings.childNode = _.castArray(settings.childNode); var rootNode = query ? treeTools.find(tree, query) : tree; var seekStack = []; var seekDown = function seekDown(branch, level) { if (level > 0) seekStack.push(branch); settings.childNode.some(function (key) { if (branch[key] && _.isArray(branch[key])) { branch[key].forEach(function (branchChild) { seekDown(branchChild, level + 1); }); return true; } }); }; seekDown(rootNode, 0); return seekStack; }
[ "function", "children", "(", "tree", ",", "query", ",", "options", ")", "{", "var", "compiledQuery", "=", "query", "?", "_", ".", "matches", "(", "query", ")", ":", "null", ";", "var", "settings", "=", "_", ".", "defaults", "(", "options", ",", "{", "childNode", ":", "[", "'children'", "]", "}", ")", ";", "settings", ".", "childNode", "=", "_", ".", "castArray", "(", "settings", ".", "childNode", ")", ";", "var", "rootNode", "=", "query", "?", "treeTools", ".", "find", "(", "tree", ",", "query", ")", ":", "tree", ";", "var", "seekStack", "=", "[", "]", ";", "var", "seekDown", "=", "function", "seekDown", "(", "branch", ",", "level", ")", "{", "if", "(", "level", ">", "0", ")", "seekStack", ".", "push", "(", "branch", ")", ";", "settings", ".", "childNode", ".", "some", "(", "function", "(", "key", ")", "{", "if", "(", "branch", "[", "key", "]", "&&", "_", ".", "isArray", "(", "branch", "[", "key", "]", ")", ")", "{", "branch", "[", "key", "]", ".", "forEach", "(", "function", "(", "branchChild", ")", "{", "seekDown", "(", "branchChild", ",", "level", "+", "1", ")", ";", "}", ")", ";", "return", "true", ";", "}", "}", ")", ";", "}", ";", "seekDown", "(", "rootNode", ",", "0", ")", ";", "return", "seekStack", ";", "}" ]
Utility function to deep search a tree structure for a matching query and find all children after the given query If found this function will return an array of all child elements NOT including the query element @param {Object|array} tree The tree structure to search (assumed to be a collection) @param {Object|function|null} [query] A valid lodash query to run (anything valid via _.find()) or a callback function. If null the entire flattened tree is returned @param {Object} [options] Optional options object @param {array|string} [options.childNode="children"] Node or nodes to examine to discover the child elements @return {array} An array of all child elements under that item
[ "Utility", "function", "to", "deep", "search", "a", "tree", "structure", "for", "a", "matching", "query", "and", "find", "all", "children", "after", "the", "given", "query", "If", "found", "this", "function", "will", "return", "an", "array", "of", "all", "child", "elements", "NOT", "including", "the", "query", "element" ]
12544aebaaaa506cb34259f16da34e4b5364829d
https://github.com/hash-bang/tree-tools/blob/12544aebaaaa506cb34259f16da34e4b5364829d/dist/ngTreeTools.js#L158-L183
train
carbon-design-system/toolkit
packages/npm/src/getPackageInfoFrom.js
getPackageInfoFrom
function getPackageInfoFrom(string) { if (string[0] === '@') { const [scope, rawName] = string.split('/'); const { name, version } = getVersionFromString(rawName); return { name: `${scope}/${name}`, version, }; } return getVersionFromString(string); }
javascript
function getPackageInfoFrom(string) { if (string[0] === '@') { const [scope, rawName] = string.split('/'); const { name, version } = getVersionFromString(rawName); return { name: `${scope}/${name}`, version, }; } return getVersionFromString(string); }
[ "function", "getPackageInfoFrom", "(", "string", ")", "{", "if", "(", "string", "[", "0", "]", "===", "'@'", ")", "{", "const", "[", "scope", ",", "rawName", "]", "=", "string", ".", "split", "(", "'/'", ")", ";", "const", "{", "name", ",", "version", "}", "=", "getVersionFromString", "(", "rawName", ")", ";", "return", "{", "name", ":", "`", "${", "scope", "}", "${", "name", "}", "`", ",", "version", ",", "}", ";", "}", "return", "getVersionFromString", "(", "string", ")", ";", "}" ]
some-package some-package@next @foo/some-package @foo/some-package@next
[ "some", "-", "package", "some", "-", "package" ]
e3674566154a96e99fb93237faa2171a02f09275
https://github.com/carbon-design-system/toolkit/blob/e3674566154a96e99fb93237faa2171a02f09275/packages/npm/src/getPackageInfoFrom.js#L7-L18
train
pbeshai/react-computed-props
examples/many-circles/src/Circles.js
visProps
function visProps(props) { const { data, height, width, } = props; const padding = { top: 20, right: 20, bottom: 40, left: 50, }; const plotAreaWidth = width - padding.left - padding.right; const plotAreaHeight = height - padding.top - padding.bottom; const xDomain = d3.extent(data, d => d.x); const yDomain = d3.extent(data, d => d.y); const xDomainPadding = 0.05 * xDomain[1]; const yDomainPadding = 0.02 * yDomain[1]; const xScale = d3.scaleLinear() .domain([xDomain[0] - xDomainPadding, xDomain[1] + xDomainPadding]) .range([0, plotAreaWidth]); const yScale = d3.scaleLinear() .domain([yDomain[0] - yDomainPadding, yDomain[1] + yDomainPadding]) .range([plotAreaHeight, 0]); const color = ({ y }) => `rgb(150, 200, ${Math.floor(255 * (yScale(y) / plotAreaHeight))})`; const voronoiDiagram = d3.voronoi() .x(d => xScale(d.x)) .y(d => yScale(d.y)) .size([plotAreaWidth, plotAreaHeight])(data); return { color, padding, plotAreaWidth, plotAreaHeight, xScale, yScale, voronoiDiagram, }; }
javascript
function visProps(props) { const { data, height, width, } = props; const padding = { top: 20, right: 20, bottom: 40, left: 50, }; const plotAreaWidth = width - padding.left - padding.right; const plotAreaHeight = height - padding.top - padding.bottom; const xDomain = d3.extent(data, d => d.x); const yDomain = d3.extent(data, d => d.y); const xDomainPadding = 0.05 * xDomain[1]; const yDomainPadding = 0.02 * yDomain[1]; const xScale = d3.scaleLinear() .domain([xDomain[0] - xDomainPadding, xDomain[1] + xDomainPadding]) .range([0, plotAreaWidth]); const yScale = d3.scaleLinear() .domain([yDomain[0] - yDomainPadding, yDomain[1] + yDomainPadding]) .range([plotAreaHeight, 0]); const color = ({ y }) => `rgb(150, 200, ${Math.floor(255 * (yScale(y) / plotAreaHeight))})`; const voronoiDiagram = d3.voronoi() .x(d => xScale(d.x)) .y(d => yScale(d.y)) .size([plotAreaWidth, plotAreaHeight])(data); return { color, padding, plotAreaWidth, plotAreaHeight, xScale, yScale, voronoiDiagram, }; }
[ "function", "visProps", "(", "props", ")", "{", "const", "{", "data", ",", "height", ",", "width", ",", "}", "=", "props", ";", "const", "padding", "=", "{", "top", ":", "20", ",", "right", ":", "20", ",", "bottom", ":", "40", ",", "left", ":", "50", ",", "}", ";", "const", "plotAreaWidth", "=", "width", "-", "padding", ".", "left", "-", "padding", ".", "right", ";", "const", "plotAreaHeight", "=", "height", "-", "padding", ".", "top", "-", "padding", ".", "bottom", ";", "const", "xDomain", "=", "d3", ".", "extent", "(", "data", ",", "d", "=>", "d", ".", "x", ")", ";", "const", "yDomain", "=", "d3", ".", "extent", "(", "data", ",", "d", "=>", "d", ".", "y", ")", ";", "const", "xDomainPadding", "=", "0.05", "*", "xDomain", "[", "1", "]", ";", "const", "yDomainPadding", "=", "0.02", "*", "yDomain", "[", "1", "]", ";", "const", "xScale", "=", "d3", ".", "scaleLinear", "(", ")", ".", "domain", "(", "[", "xDomain", "[", "0", "]", "-", "xDomainPadding", ",", "xDomain", "[", "1", "]", "+", "xDomainPadding", "]", ")", ".", "range", "(", "[", "0", ",", "plotAreaWidth", "]", ")", ";", "const", "yScale", "=", "d3", ".", "scaleLinear", "(", ")", ".", "domain", "(", "[", "yDomain", "[", "0", "]", "-", "yDomainPadding", ",", "yDomain", "[", "1", "]", "+", "yDomainPadding", "]", ")", ".", "range", "(", "[", "plotAreaHeight", ",", "0", "]", ")", ";", "const", "color", "=", "(", "{", "y", "}", ")", "=>", "`", "${", "Math", ".", "floor", "(", "255", "*", "(", "yScale", "(", "y", ")", "/", "plotAreaHeight", ")", ")", "}", "`", ";", "const", "voronoiDiagram", "=", "d3", ".", "voronoi", "(", ")", ".", "x", "(", "d", "=>", "xScale", "(", "d", ".", "x", ")", ")", ".", "y", "(", "d", "=>", "yScale", "(", "d", ".", "y", ")", ")", ".", "size", "(", "[", "plotAreaWidth", ",", "plotAreaHeight", "]", ")", "(", "data", ")", ";", "return", "{", "color", ",", "padding", ",", "plotAreaWidth", ",", "plotAreaHeight", ",", "xScale", ",", "yScale", ",", "voronoiDiagram", ",", "}", ";", "}" ]
Figure out what is needed to render the chart based on the props of the component
[ "Figure", "out", "what", "is", "needed", "to", "render", "the", "chart", "based", "on", "the", "props", "of", "the", "component" ]
e5098cb209d4958ac1bd743fb4b451b1834ff910
https://github.com/pbeshai/react-computed-props/blob/e5098cb209d4958ac1bd743fb4b451b1834ff910/examples/many-circles/src/Circles.js#L8-L55
train
pbeshai/react-computed-props
src/shallowEquals.js
excludeIncludeKeys
function excludeIncludeKeys(objA, objB, excludeKeys, includeKeys) { let keysA = Object.keys(objA); let keysB = Object.keys(objB); if (excludeKeys) { keysA = keysA.filter(key => excludeKeys.indexOf(key) === -1); keysB = keysB.filter(key => excludeKeys.indexOf(key) === -1); } else if (includeKeys) { keysA = keysA.filter(key => includeKeys.indexOf(key) !== -1); keysB = keysB.filter(key => includeKeys.indexOf(key) !== -1); } return [keysA, keysB]; }
javascript
function excludeIncludeKeys(objA, objB, excludeKeys, includeKeys) { let keysA = Object.keys(objA); let keysB = Object.keys(objB); if (excludeKeys) { keysA = keysA.filter(key => excludeKeys.indexOf(key) === -1); keysB = keysB.filter(key => excludeKeys.indexOf(key) === -1); } else if (includeKeys) { keysA = keysA.filter(key => includeKeys.indexOf(key) !== -1); keysB = keysB.filter(key => includeKeys.indexOf(key) !== -1); } return [keysA, keysB]; }
[ "function", "excludeIncludeKeys", "(", "objA", ",", "objB", ",", "excludeKeys", ",", "includeKeys", ")", "{", "let", "keysA", "=", "Object", ".", "keys", "(", "objA", ")", ";", "let", "keysB", "=", "Object", ".", "keys", "(", "objB", ")", ";", "if", "(", "excludeKeys", ")", "{", "keysA", "=", "keysA", ".", "filter", "(", "key", "=>", "excludeKeys", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", ";", "keysB", "=", "keysB", ".", "filter", "(", "key", "=>", "excludeKeys", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", ";", "}", "else", "if", "(", "includeKeys", ")", "{", "keysA", "=", "keysA", ".", "filter", "(", "key", "=>", "includeKeys", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", ";", "keysB", "=", "keysB", ".", "filter", "(", "key", "=>", "includeKeys", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", ";", "}", "return", "[", "keysA", ",", "keysB", "]", ";", "}" ]
Helper function to include or exclude keys before comparing
[ "Helper", "function", "to", "include", "or", "exclude", "keys", "before", "comparing" ]
e5098cb209d4958ac1bd743fb4b451b1834ff910
https://github.com/pbeshai/react-computed-props/blob/e5098cb209d4958ac1bd743fb4b451b1834ff910/src/shallowEquals.js#L4-L17
train
carbon-design-system/toolkit
packages/cli-config/src/load.js
loadPlugin
function loadPlugin(descriptor, loader) { const config = Array.isArray(descriptor) ? descriptor : [descriptor]; const [name, options = {}] = config; const { error, module: plugin } = loader(name); if (error) { return { error, name, }; } if (typeof plugin !== 'function') { return { error: new Error( `Expected the plugin \`${name}\` to export a function, instead ` + `recieved: ${typeof plugin}` ), name, }; } return { name, options, plugin, }; }
javascript
function loadPlugin(descriptor, loader) { const config = Array.isArray(descriptor) ? descriptor : [descriptor]; const [name, options = {}] = config; const { error, module: plugin } = loader(name); if (error) { return { error, name, }; } if (typeof plugin !== 'function') { return { error: new Error( `Expected the plugin \`${name}\` to export a function, instead ` + `recieved: ${typeof plugin}` ), name, }; } return { name, options, plugin, }; }
[ "function", "loadPlugin", "(", "descriptor", ",", "loader", ")", "{", "const", "config", "=", "Array", ".", "isArray", "(", "descriptor", ")", "?", "descriptor", ":", "[", "descriptor", "]", ";", "const", "[", "name", ",", "options", "=", "{", "}", "]", "=", "config", ";", "const", "{", "error", ",", "module", ":", "plugin", "}", "=", "loader", "(", "name", ")", ";", "if", "(", "error", ")", "{", "return", "{", "error", ",", "name", ",", "}", ";", "}", "if", "(", "typeof", "plugin", "!==", "'function'", ")", "{", "return", "{", "error", ":", "new", "Error", "(", "`", "\\`", "${", "name", "}", "\\`", "`", "+", "`", "${", "typeof", "plugin", "}", "`", ")", ",", "name", ",", "}", ";", "}", "return", "{", "name", ",", "options", ",", "plugin", ",", "}", ";", "}" ]
Load the plugin descriptor with the given loader @param {Descriptor} descriptor @param {Loader} loader
[ "Load", "the", "plugin", "descriptor", "with", "the", "given", "loader" ]
e3674566154a96e99fb93237faa2171a02f09275
https://github.com/carbon-design-system/toolkit/blob/e3674566154a96e99fb93237faa2171a02f09275/packages/cli-config/src/load.js#L47-L74
train
carbon-design-system/toolkit
packages/cli-config/src/load.js
loadPreset
function loadPreset(descriptor, loader) { const config = Array.isArray(descriptor) ? descriptor : [descriptor]; const [name, options = {}] = config; const { error: loaderError, module: getPreset } = loader(name); if (loaderError) { return { error: loaderError, name, }; } if (typeof getPreset !== 'function') { return { error: new Error( `Expected the preset \`${name}\` to export a function, instead ` + `recieved: ${typeof getPreset}` ), name, }; } let preset; try { preset = getPreset(options); } catch (error) { return { error, name, options, }; } const { presets = [], plugins = [] } = preset; return { name, options, presets: presets.map(descriptor => loadPreset(descriptor, loader)), plugins: plugins.map(descriptor => loadPlugin(descriptor, loader)), }; }
javascript
function loadPreset(descriptor, loader) { const config = Array.isArray(descriptor) ? descriptor : [descriptor]; const [name, options = {}] = config; const { error: loaderError, module: getPreset } = loader(name); if (loaderError) { return { error: loaderError, name, }; } if (typeof getPreset !== 'function') { return { error: new Error( `Expected the preset \`${name}\` to export a function, instead ` + `recieved: ${typeof getPreset}` ), name, }; } let preset; try { preset = getPreset(options); } catch (error) { return { error, name, options, }; } const { presets = [], plugins = [] } = preset; return { name, options, presets: presets.map(descriptor => loadPreset(descriptor, loader)), plugins: plugins.map(descriptor => loadPlugin(descriptor, loader)), }; }
[ "function", "loadPreset", "(", "descriptor", ",", "loader", ")", "{", "const", "config", "=", "Array", ".", "isArray", "(", "descriptor", ")", "?", "descriptor", ":", "[", "descriptor", "]", ";", "const", "[", "name", ",", "options", "=", "{", "}", "]", "=", "config", ";", "const", "{", "error", ":", "loaderError", ",", "module", ":", "getPreset", "}", "=", "loader", "(", "name", ")", ";", "if", "(", "loaderError", ")", "{", "return", "{", "error", ":", "loaderError", ",", "name", ",", "}", ";", "}", "if", "(", "typeof", "getPreset", "!==", "'function'", ")", "{", "return", "{", "error", ":", "new", "Error", "(", "`", "\\`", "${", "name", "}", "\\`", "`", "+", "`", "${", "typeof", "getPreset", "}", "`", ")", ",", "name", ",", "}", ";", "}", "let", "preset", ";", "try", "{", "preset", "=", "getPreset", "(", "options", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "{", "error", ",", "name", ",", "options", ",", "}", ";", "}", "const", "{", "presets", "=", "[", "]", ",", "plugins", "=", "[", "]", "}", "=", "preset", ";", "return", "{", "name", ",", "options", ",", "presets", ":", "presets", ".", "map", "(", "descriptor", "=>", "loadPreset", "(", "descriptor", ",", "loader", ")", ")", ",", "plugins", ":", "plugins", ".", "map", "(", "descriptor", "=>", "loadPlugin", "(", "descriptor", ",", "loader", ")", ")", ",", "}", ";", "}" ]
Load the preset with the given loader @param {Descriptor} descriptor @param {Loader} loader
[ "Load", "the", "preset", "with", "the", "given", "loader" ]
e3674566154a96e99fb93237faa2171a02f09275
https://github.com/carbon-design-system/toolkit/blob/e3674566154a96e99fb93237faa2171a02f09275/packages/cli-config/src/load.js#L81-L122
train
carbon-design-system/toolkit
packages/cli-runtime/src/plugins/create/create.js
create
async function create(name, options, api, env) { // Grab the cwd and npmClient off of the environment. We can use these to // create the folder for the project and for determining what client to use // for npm-related commands const { CLI_ENV, cwd, npmClient } = env; // We support a couple of options for our `create` command, some only exist // during development (like link and linkCli). const { link, linkCli, plugins = [], presets = [], skip } = options; const root = path.join(cwd, name); logger.trace('Creating project:', name, 'at:', root); if (await fs.exists(root)) { throw new Error(`A folder already exists at \`${root}\``); } // Create the root directory for the new project await fs.ensureDir(root); const { writePackageJson, installDependencies, linkDependencies, } = await createClient(npmClient, root); const packageJson = { name, private: true, license: 'MIT', scripts: {}, dependencies: {}, devDependencies: {}, toolkit: {}, }; // Write the packageJson to the newly created `root` folder await writePackageJson(packageJson); const installer = linkCli ? linkDependencies : installDependencies; await installer(['@carbon/toolkit']); if (CLI_ENV === 'production') { clearConsole(); } if (skip) { displaySuccess(root, name, npmClient); return; } const toolkit = await which('toolkit', { cwd: root }); if (presets.length > 0) { const args = ['add', ...presets, link && '--link'].filter(Boolean); await spawn(toolkit, args, { cwd: root, stdio: 'inherit', }); } if (plugins.length > 0) { const args = ['add', ...plugins, link && '--link'].filter(Boolean); await spawn(toolkit, args, { cwd: root, stdio: 'inherit', }); } displaySuccess(root, name, npmClient); }
javascript
async function create(name, options, api, env) { // Grab the cwd and npmClient off of the environment. We can use these to // create the folder for the project and for determining what client to use // for npm-related commands const { CLI_ENV, cwd, npmClient } = env; // We support a couple of options for our `create` command, some only exist // during development (like link and linkCli). const { link, linkCli, plugins = [], presets = [], skip } = options; const root = path.join(cwd, name); logger.trace('Creating project:', name, 'at:', root); if (await fs.exists(root)) { throw new Error(`A folder already exists at \`${root}\``); } // Create the root directory for the new project await fs.ensureDir(root); const { writePackageJson, installDependencies, linkDependencies, } = await createClient(npmClient, root); const packageJson = { name, private: true, license: 'MIT', scripts: {}, dependencies: {}, devDependencies: {}, toolkit: {}, }; // Write the packageJson to the newly created `root` folder await writePackageJson(packageJson); const installer = linkCli ? linkDependencies : installDependencies; await installer(['@carbon/toolkit']); if (CLI_ENV === 'production') { clearConsole(); } if (skip) { displaySuccess(root, name, npmClient); return; } const toolkit = await which('toolkit', { cwd: root }); if (presets.length > 0) { const args = ['add', ...presets, link && '--link'].filter(Boolean); await spawn(toolkit, args, { cwd: root, stdio: 'inherit', }); } if (plugins.length > 0) { const args = ['add', ...plugins, link && '--link'].filter(Boolean); await spawn(toolkit, args, { cwd: root, stdio: 'inherit', }); } displaySuccess(root, name, npmClient); }
[ "async", "function", "create", "(", "name", ",", "options", ",", "api", ",", "env", ")", "{", "const", "{", "CLI_ENV", ",", "cwd", ",", "npmClient", "}", "=", "env", ";", "const", "{", "link", ",", "linkCli", ",", "plugins", "=", "[", "]", ",", "presets", "=", "[", "]", ",", "skip", "}", "=", "options", ";", "const", "root", "=", "path", ".", "join", "(", "cwd", ",", "name", ")", ";", "logger", ".", "trace", "(", "'Creating project:'", ",", "name", ",", "'at:'", ",", "root", ")", ";", "if", "(", "await", "fs", ".", "exists", "(", "root", ")", ")", "{", "throw", "new", "Error", "(", "`", "\\`", "${", "root", "}", "\\`", "`", ")", ";", "}", "await", "fs", ".", "ensureDir", "(", "root", ")", ";", "const", "{", "writePackageJson", ",", "installDependencies", ",", "linkDependencies", ",", "}", "=", "await", "createClient", "(", "npmClient", ",", "root", ")", ";", "const", "packageJson", "=", "{", "name", ",", "private", ":", "true", ",", "license", ":", "'MIT'", ",", "scripts", ":", "{", "}", ",", "dependencies", ":", "{", "}", ",", "devDependencies", ":", "{", "}", ",", "toolkit", ":", "{", "}", ",", "}", ";", "await", "writePackageJson", "(", "packageJson", ")", ";", "const", "installer", "=", "linkCli", "?", "linkDependencies", ":", "installDependencies", ";", "await", "installer", "(", "[", "'@carbon/toolkit'", "]", ")", ";", "if", "(", "CLI_ENV", "===", "'production'", ")", "{", "clearConsole", "(", ")", ";", "}", "if", "(", "skip", ")", "{", "displaySuccess", "(", "root", ",", "name", ",", "npmClient", ")", ";", "return", ";", "}", "const", "toolkit", "=", "await", "which", "(", "'toolkit'", ",", "{", "cwd", ":", "root", "}", ")", ";", "if", "(", "presets", ".", "length", ">", "0", ")", "{", "const", "args", "=", "[", "'add'", ",", "...", "presets", ",", "link", "&&", "'--link'", "]", ".", "filter", "(", "Boolean", ")", ";", "await", "spawn", "(", "toolkit", ",", "args", ",", "{", "cwd", ":", "root", ",", "stdio", ":", "'inherit'", ",", "}", ")", ";", "}", "if", "(", "plugins", ".", "length", ">", "0", ")", "{", "const", "args", "=", "[", "'add'", ",", "...", "plugins", ",", "link", "&&", "'--link'", "]", ".", "filter", "(", "Boolean", ")", ";", "await", "spawn", "(", "toolkit", ",", "args", ",", "{", "cwd", ":", "root", ",", "stdio", ":", "'inherit'", ",", "}", ")", ";", "}", "displaySuccess", "(", "root", ",", "name", ",", "npmClient", ")", ";", "}" ]
Create a toolkit project with the given name and options.
[ "Create", "a", "toolkit", "project", "with", "the", "given", "name", "and", "options", "." ]
e3674566154a96e99fb93237faa2171a02f09275
https://github.com/carbon-design-system/toolkit/blob/e3674566154a96e99fb93237faa2171a02f09275/packages/cli-runtime/src/plugins/create/create.js#L20-L88
train
whxaxes/mus
lib/compile/parser.js
collect
function collect(str, type) { if (!type) { if (otherRE.test(str)) { // base type, null|undefined etc. type = 'base'; } else if (objectRE.test(str)) { // simple property type = 'prop'; } } fragments.push(last = lastEl = { expr: str, type, }); }
javascript
function collect(str, type) { if (!type) { if (otherRE.test(str)) { // base type, null|undefined etc. type = 'base'; } else if (objectRE.test(str)) { // simple property type = 'prop'; } } fragments.push(last = lastEl = { expr: str, type, }); }
[ "function", "collect", "(", "str", ",", "type", ")", "{", "if", "(", "!", "type", ")", "{", "if", "(", "otherRE", ".", "test", "(", "str", ")", ")", "{", "type", "=", "'base'", ";", "}", "else", "if", "(", "objectRE", ".", "test", "(", "str", ")", ")", "{", "type", "=", "'prop'", ";", "}", "}", "fragments", ".", "push", "(", "last", "=", "lastEl", "=", "{", "expr", ":", "str", ",", "type", ",", "}", ")", ";", "}" ]
collect property | base type | string
[ "collect", "property", "|", "base", "type", "|", "string" ]
221d48b258cb896bcadac0832d4d9167ad6b4d7a
https://github.com/whxaxes/mus/blob/221d48b258cb896bcadac0832d4d9167ad6b4d7a/lib/compile/parser.js#L331-L346
train