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
reelyactive/hlc-server
web/apps/hello-infrastructure/js/hello-infrastructure.js
sortReceiversAndHighlight
function sortReceiversAndHighlight(receiverSignature) { let trs = Array.from(tbody.getElementsByTagName('tr')); let sortedFragment = document.createDocumentFragment(); trs.sort(sortFunction); trs.forEach(function(tr) { if(tr.id === receiverSignature) { tr.setAttribute('class', 'monospace animated-highlight-reelyactive'); } else { tr.setAttribute('class', 'monospace'); } sortedFragment.appendChild(tr); }); tbody.appendChild(sortedFragment); }
javascript
function sortReceiversAndHighlight(receiverSignature) { let trs = Array.from(tbody.getElementsByTagName('tr')); let sortedFragment = document.createDocumentFragment(); trs.sort(sortFunction); trs.forEach(function(tr) { if(tr.id === receiverSignature) { tr.setAttribute('class', 'monospace animated-highlight-reelyactive'); } else { tr.setAttribute('class', 'monospace'); } sortedFragment.appendChild(tr); }); tbody.appendChild(sortedFragment); }
[ "function", "sortReceiversAndHighlight", "(", "receiverSignature", ")", "{", "let", "trs", "=", "Array", ".", "from", "(", "tbody", ".", "getElementsByTagName", "(", "'tr'", ")", ")", ";", "let", "sortedFragment", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "trs", ".", "sort", "(", "sortFunction", ")", ";", "trs", ".", "forEach", "(", "function", "(", "tr", ")", "{", "if", "(", "tr", ".", "id", "===", "receiverSignature", ")", "{", "tr", ".", "setAttribute", "(", "'class'", ",", "'monospace animated-highlight-reelyactive'", ")", ";", "}", "else", "{", "tr", ".", "setAttribute", "(", "'class'", ",", "'monospace'", ")", ";", "}", "sortedFragment", ".", "appendChild", "(", "tr", ")", ";", "}", ")", ";", "tbody", ".", "appendChild", "(", "sortedFragment", ")", ";", "}" ]
Sort the receivers in the table, highlighting the given receiver
[ "Sort", "the", "receivers", "in", "the", "table", "highlighting", "the", "given", "receiver" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-infrastructure/js/hello-infrastructure.js#L128-L145
train
clux/modul8
examples/npm/output.js
function(ev, callback, context) { var calls = this._callbacks || (this._callbacks = {}); var list = calls[ev] || (calls[ev] = []); list.push([callback, context]); return this; }
javascript
function(ev, callback, context) { var calls = this._callbacks || (this._callbacks = {}); var list = calls[ev] || (calls[ev] = []); list.push([callback, context]); return this; }
[ "function", "(", "ev", ",", "callback", ",", "context", ")", "{", "var", "calls", "=", "this", ".", "_callbacks", "||", "(", "this", ".", "_callbacks", "=", "{", "}", ")", ";", "var", "list", "=", "calls", "[", "ev", "]", "||", "(", "calls", "[", "ev", "]", "=", "[", "]", ")", ";", "list", ".", "push", "(", "[", "callback", ",", "context", "]", ")", ";", "return", "this", ";", "}" ]
Bind an event, specified by a string name, `ev`, to a `callback` function. Passing `"all"` will bind the callback to all events fired.
[ "Bind", "an", "event", "specified", "by", "a", "string", "name", "ev", "to", "a", "callback", "function", ".", "Passing", "all", "will", "bind", "the", "callback", "to", "all", "events", "fired", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L1601-L1606
train
clux/modul8
examples/npm/output.js
function(ev, callback) { var calls; if (!ev) { this._callbacks = {}; } else if (calls = this._callbacks) { if (!callback) { calls[ev] = []; } else { var list = calls[ev]; if (!list) return this; for (var i = 0, l = list.length; i < l; i++) { if (list[i] && callback === list[i][0]) { list[i] = null; break; } } } } return this; }
javascript
function(ev, callback) { var calls; if (!ev) { this._callbacks = {}; } else if (calls = this._callbacks) { if (!callback) { calls[ev] = []; } else { var list = calls[ev]; if (!list) return this; for (var i = 0, l = list.length; i < l; i++) { if (list[i] && callback === list[i][0]) { list[i] = null; break; } } } } return this; }
[ "function", "(", "ev", ",", "callback", ")", "{", "var", "calls", ";", "if", "(", "!", "ev", ")", "{", "this", ".", "_callbacks", "=", "{", "}", ";", "}", "else", "if", "(", "calls", "=", "this", ".", "_callbacks", ")", "{", "if", "(", "!", "callback", ")", "{", "calls", "[", "ev", "]", "=", "[", "]", ";", "}", "else", "{", "var", "list", "=", "calls", "[", "ev", "]", ";", "if", "(", "!", "list", ")", "return", "this", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "list", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "list", "[", "i", "]", "&&", "callback", "===", "list", "[", "i", "]", "[", "0", "]", ")", "{", "list", "[", "i", "]", "=", "null", ";", "break", ";", "}", "}", "}", "}", "return", "this", ";", "}" ]
Remove one or many callbacks. If `callback` is null, removes all callbacks for the event. If `ev` is null, removes all bound callbacks for all events.
[ "Remove", "one", "or", "many", "callbacks", ".", "If", "callback", "is", "null", "removes", "all", "callbacks", "for", "the", "event", ".", "If", "ev", "is", "null", "removes", "all", "bound", "callbacks", "for", "all", "events", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L1611-L1630
train
clux/modul8
examples/npm/output.js
function(eventName) { var list, calls, ev, callback, args; var both = 2; if (!(calls = this._callbacks)) return this; while (both--) { ev = both ? eventName : 'all'; if (list = calls[ev]) { for (var i = 0, l = list.length; i < l; i++) { if (!(callback = list[i])) { list.splice(i, 1); i--; l--; } else { args = both ? Array.prototype.slice.call(arguments, 1) : arguments; callback[0].apply(callback[1] || this, args); } } } } return this; }
javascript
function(eventName) { var list, calls, ev, callback, args; var both = 2; if (!(calls = this._callbacks)) return this; while (both--) { ev = both ? eventName : 'all'; if (list = calls[ev]) { for (var i = 0, l = list.length; i < l; i++) { if (!(callback = list[i])) { list.splice(i, 1); i--; l--; } else { args = both ? Array.prototype.slice.call(arguments, 1) : arguments; callback[0].apply(callback[1] || this, args); } } } } return this; }
[ "function", "(", "eventName", ")", "{", "var", "list", ",", "calls", ",", "ev", ",", "callback", ",", "args", ";", "var", "both", "=", "2", ";", "if", "(", "!", "(", "calls", "=", "this", ".", "_callbacks", ")", ")", "return", "this", ";", "while", "(", "both", "--", ")", "{", "ev", "=", "both", "?", "eventName", ":", "'all'", ";", "if", "(", "list", "=", "calls", "[", "ev", "]", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "list", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "!", "(", "callback", "=", "list", "[", "i", "]", ")", ")", "{", "list", ".", "splice", "(", "i", ",", "1", ")", ";", "i", "--", ";", "l", "--", ";", "}", "else", "{", "args", "=", "both", "?", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ":", "arguments", ";", "callback", "[", "0", "]", ".", "apply", "(", "callback", "[", "1", "]", "||", "this", ",", "args", ")", ";", "}", "}", "}", "}", "return", "this", ";", "}" ]
Trigger an event, firing all bound callbacks. Callbacks are passed the same arguments as `trigger` is, apart from the event name. Listening for `"all"` passes the true event name as the first argument.
[ "Trigger", "an", "event", "firing", "all", "bound", "callbacks", ".", "Callbacks", "are", "passed", "the", "same", "arguments", "as", "trigger", "is", "apart", "from", "the", "event", "name", ".", "Listening", "for", "all", "passes", "the", "true", "event", "name", "as", "the", "first", "argument", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L1635-L1653
train
clux/modul8
examples/npm/output.js
function(options) { options || (options = {}); if (this.isNew()) return this.trigger('destroy', this, this.collection, options); var model = this; var success = options.success; options.success = function(resp) { model.trigger('destroy', model, model.collection, options); if (success) success(model, resp); }; options.error = wrapError(options.error, model, options); return (this.sync || Backbone.sync).call(this, 'delete', this, options); }
javascript
function(options) { options || (options = {}); if (this.isNew()) return this.trigger('destroy', this, this.collection, options); var model = this; var success = options.success; options.success = function(resp) { model.trigger('destroy', model, model.collection, options); if (success) success(model, resp); }; options.error = wrapError(options.error, model, options); return (this.sync || Backbone.sync).call(this, 'delete', this, options); }
[ "function", "(", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "if", "(", "this", ".", "isNew", "(", ")", ")", "return", "this", ".", "trigger", "(", "'destroy'", ",", "this", ",", "this", ".", "collection", ",", "options", ")", ";", "var", "model", "=", "this", ";", "var", "success", "=", "options", ".", "success", ";", "options", ".", "success", "=", "function", "(", "resp", ")", "{", "model", ".", "trigger", "(", "'destroy'", ",", "model", ",", "model", ".", "collection", ",", "options", ")", ";", "if", "(", "success", ")", "success", "(", "model", ",", "resp", ")", ";", "}", ";", "options", ".", "error", "=", "wrapError", "(", "options", ".", "error", ",", "model", ",", "options", ")", ";", "return", "(", "this", ".", "sync", "||", "Backbone", ".", "sync", ")", ".", "call", "(", "this", ",", "'delete'", ",", "this", ",", "options", ")", ";", "}" ]
Destroy this model on the server if it was already persisted. Upon success, the model is removed from its collection, if it has one.
[ "Destroy", "this", "model", "on", "the", "server", "if", "it", "was", "already", "persisted", ".", "Upon", "success", "the", "model", "is", "removed", "from", "its", "collection", "if", "it", "has", "one", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L1840-L1851
train
clux/modul8
examples/npm/output.js
function(models, options) { if (_.isArray(models)) { for (var i = 0, l = models.length; i < l; i++) { this._remove(models[i], options); } } else { this._remove(models, options); } return this; }
javascript
function(models, options) { if (_.isArray(models)) { for (var i = 0, l = models.length; i < l; i++) { this._remove(models[i], options); } } else { this._remove(models, options); } return this; }
[ "function", "(", "models", ",", "options", ")", "{", "if", "(", "_", ".", "isArray", "(", "models", ")", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "models", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "this", ".", "_remove", "(", "models", "[", "i", "]", ",", "options", ")", ";", "}", "}", "else", "{", "this", ".", "_remove", "(", "models", ",", "options", ")", ";", "}", "return", "this", ";", "}" ]
Remove a model, or a list of models from the set. Pass silent to avoid firing the `removed` event for every model removed.
[ "Remove", "a", "model", "or", "a", "list", "of", "models", "from", "the", "set", ".", "Pass", "silent", "to", "avoid", "firing", "the", "removed", "event", "for", "every", "model", "removed", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L1988-L1997
train
clux/modul8
examples/npm/output.js
function(models, options) { models || (models = []); options || (options = {}); this.each(this._removeReference); this._reset(); this.add(models, {silent: true}); if (!options.silent) this.trigger('reset', this, options); return this; }
javascript
function(models, options) { models || (models = []); options || (options = {}); this.each(this._removeReference); this._reset(); this.add(models, {silent: true}); if (!options.silent) this.trigger('reset', this, options); return this; }
[ "function", "(", "models", ",", "options", ")", "{", "models", "||", "(", "models", "=", "[", "]", ")", ";", "options", "||", "(", "options", "=", "{", "}", ")", ";", "this", ".", "each", "(", "this", ".", "_removeReference", ")", ";", "this", ".", "_reset", "(", ")", ";", "this", ".", "add", "(", "models", ",", "{", "silent", ":", "true", "}", ")", ";", "if", "(", "!", "options", ".", "silent", ")", "this", ".", "trigger", "(", "'reset'", ",", "this", ",", "options", ")", ";", "return", "this", ";", "}" ]
When you have more items than you want to add or remove individually, you can reset the entire set with a new list of models, without firing any `added` or `removed` events. Fires `reset` when finished.
[ "When", "you", "have", "more", "items", "than", "you", "want", "to", "add", "or", "remove", "individually", "you", "can", "reset", "the", "entire", "set", "with", "a", "new", "list", "of", "models", "without", "firing", "any", "added", "or", "removed", "events", ".", "Fires", "reset", "when", "finished", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L2033-L2041
train
clux/modul8
examples/npm/output.js
function(model, options) { var coll = this; options || (options = {}); model = this._prepareModel(model, options); if (!model) return false; var success = options.success; options.success = function(nextModel, resp, xhr) { coll.add(nextModel, options); if (success) success(nextModel, resp, xhr); }; model.save(null, options); return model; }
javascript
function(model, options) { var coll = this; options || (options = {}); model = this._prepareModel(model, options); if (!model) return false; var success = options.success; options.success = function(nextModel, resp, xhr) { coll.add(nextModel, options); if (success) success(nextModel, resp, xhr); }; model.save(null, options); return model; }
[ "function", "(", "model", ",", "options", ")", "{", "var", "coll", "=", "this", ";", "options", "||", "(", "options", "=", "{", "}", ")", ";", "model", "=", "this", ".", "_prepareModel", "(", "model", ",", "options", ")", ";", "if", "(", "!", "model", ")", "return", "false", ";", "var", "success", "=", "options", ".", "success", ";", "options", ".", "success", "=", "function", "(", "nextModel", ",", "resp", ",", "xhr", ")", "{", "coll", ".", "add", "(", "nextModel", ",", "options", ")", ";", "if", "(", "success", ")", "success", "(", "nextModel", ",", "resp", ",", "xhr", ")", ";", "}", ";", "model", ".", "save", "(", "null", ",", "options", ")", ";", "return", "model", ";", "}" ]
Create a new instance of a model in this collection. After the model has been created on the server, it will be added to the collection. Returns the model, or 'false' if validation on a new model fails.
[ "Create", "a", "new", "instance", "of", "a", "model", "in", "this", "collection", ".", "After", "the", "model", "has", "been", "created", "on", "the", "server", "it", "will", "be", "added", "to", "the", "collection", ".", "Returns", "the", "model", "or", "false", "if", "validation", "on", "a", "new", "model", "fails", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L2061-L2073
train
clux/modul8
examples/npm/output.js
function(model, options) { if (!(model instanceof Backbone.Model)) { var attrs = model; model = new this.model(attrs, {collection: this}); if (model.validate && !model._performValidation(attrs, options)) model = false; } else if (!model.collection) { model.collection = this; } return model; }
javascript
function(model, options) { if (!(model instanceof Backbone.Model)) { var attrs = model; model = new this.model(attrs, {collection: this}); if (model.validate && !model._performValidation(attrs, options)) model = false; } else if (!model.collection) { model.collection = this; } return model; }
[ "function", "(", "model", ",", "options", ")", "{", "if", "(", "!", "(", "model", "instanceof", "Backbone", ".", "Model", ")", ")", "{", "var", "attrs", "=", "model", ";", "model", "=", "new", "this", ".", "model", "(", "attrs", ",", "{", "collection", ":", "this", "}", ")", ";", "if", "(", "model", ".", "validate", "&&", "!", "model", ".", "_performValidation", "(", "attrs", ",", "options", ")", ")", "model", "=", "false", ";", "}", "else", "if", "(", "!", "model", ".", "collection", ")", "{", "model", ".", "collection", "=", "this", ";", "}", "return", "model", ";", "}" ]
Prepare a model to be added to this collection
[ "Prepare", "a", "model", "to", "be", "added", "to", "this", "collection" ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L2097-L2106
train
clux/modul8
examples/npm/output.js
function(model, options) { options || (options = {}); model = this.getByCid(model) || this.get(model); if (!model) return null; delete this._byId[model.id]; delete this._byCid[model.cid]; this.models.splice(this.indexOf(model), 1); this.length--; if (!options.silent) model.trigger('remove', model, this, options); this._removeReference(model); return model; }
javascript
function(model, options) { options || (options = {}); model = this.getByCid(model) || this.get(model); if (!model) return null; delete this._byId[model.id]; delete this._byCid[model.cid]; this.models.splice(this.indexOf(model), 1); this.length--; if (!options.silent) model.trigger('remove', model, this, options); this._removeReference(model); return model; }
[ "function", "(", "model", ",", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "model", "=", "this", ".", "getByCid", "(", "model", ")", "||", "this", ".", "get", "(", "model", ")", ";", "if", "(", "!", "model", ")", "return", "null", ";", "delete", "this", ".", "_byId", "[", "model", ".", "id", "]", ";", "delete", "this", ".", "_byCid", "[", "model", ".", "cid", "]", ";", "this", ".", "models", ".", "splice", "(", "this", ".", "indexOf", "(", "model", ")", ",", "1", ")", ";", "this", ".", "length", "--", ";", "if", "(", "!", "options", ".", "silent", ")", "model", ".", "trigger", "(", "'remove'", ",", "model", ",", "this", ",", "options", ")", ";", "this", ".", "_removeReference", "(", "model", ")", ";", "return", "model", ";", "}" ]
Internal implementation of removing a single model from the set, updating hash indexes for `id` and `cid` lookups.
[ "Internal", "implementation", "of", "removing", "a", "single", "model", "from", "the", "set", "updating", "hash", "indexes", "for", "id", "and", "cid", "lookups", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L2131-L2142
train
clux/modul8
examples/npm/output.js
function(fragment, triggerRoute) { var frag = (fragment || '').replace(hashStrip, ''); if (this.fragment == frag || this.fragment == decodeURIComponent(frag)) return; if (this._hasPushState) { var loc = window.location; if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag; this.fragment = frag; window.history.pushState({}, document.title, loc.protocol + '//' + loc.host + frag); } else { window.location.hash = this.fragment = frag; if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) { this.iframe.document.open().close(); this.iframe.location.hash = frag; } } if (triggerRoute) this.loadUrl(fragment); }
javascript
function(fragment, triggerRoute) { var frag = (fragment || '').replace(hashStrip, ''); if (this.fragment == frag || this.fragment == decodeURIComponent(frag)) return; if (this._hasPushState) { var loc = window.location; if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag; this.fragment = frag; window.history.pushState({}, document.title, loc.protocol + '//' + loc.host + frag); } else { window.location.hash = this.fragment = frag; if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) { this.iframe.document.open().close(); this.iframe.location.hash = frag; } } if (triggerRoute) this.loadUrl(fragment); }
[ "function", "(", "fragment", ",", "triggerRoute", ")", "{", "var", "frag", "=", "(", "fragment", "||", "''", ")", ".", "replace", "(", "hashStrip", ",", "''", ")", ";", "if", "(", "this", ".", "fragment", "==", "frag", "||", "this", ".", "fragment", "==", "decodeURIComponent", "(", "frag", ")", ")", "return", ";", "if", "(", "this", ".", "_hasPushState", ")", "{", "var", "loc", "=", "window", ".", "location", ";", "if", "(", "frag", ".", "indexOf", "(", "this", ".", "options", ".", "root", ")", "!=", "0", ")", "frag", "=", "this", ".", "options", ".", "root", "+", "frag", ";", "this", ".", "fragment", "=", "frag", ";", "window", ".", "history", ".", "pushState", "(", "{", "}", ",", "document", ".", "title", ",", "loc", ".", "protocol", "+", "'//'", "+", "loc", ".", "host", "+", "frag", ")", ";", "}", "else", "{", "window", ".", "location", ".", "hash", "=", "this", ".", "fragment", "=", "frag", ";", "if", "(", "this", ".", "iframe", "&&", "(", "frag", "!=", "this", ".", "getFragment", "(", "this", ".", "iframe", ".", "location", ".", "hash", ")", ")", ")", "{", "this", ".", "iframe", ".", "document", ".", "open", "(", ")", ".", "close", "(", ")", ";", "this", ".", "iframe", ".", "location", ".", "hash", "=", "frag", ";", "}", "}", "if", "(", "triggerRoute", ")", "this", ".", "loadUrl", "(", "fragment", ")", ";", "}" ]
Save a fragment into the hash history. You are responsible for properly URL-encoding the fragment in advance. This does not trigger a `hashchange` event.
[ "Save", "a", "fragment", "into", "the", "hash", "history", ".", "You", "are", "responsible", "for", "properly", "URL", "-", "encoding", "the", "fragment", "in", "advance", ".", "This", "does", "not", "trigger", "a", "hashchange", "event", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L2384-L2400
train
clux/modul8
examples/npm/output.js
function(object) { if (!(object && object.url)) return null; return _.isFunction(object.url) ? object.url() : object.url; }
javascript
function(object) { if (!(object && object.url)) return null; return _.isFunction(object.url) ? object.url() : object.url; }
[ "function", "(", "object", ")", "{", "if", "(", "!", "(", "object", "&&", "object", ".", "url", ")", ")", "return", "null", ";", "return", "_", ".", "isFunction", "(", "object", ".", "url", ")", "?", "object", ".", "url", "(", ")", ":", "object", ".", "url", ";", "}" ]
Helper function to get a URL from a Model or Collection as a property or as a function.
[ "Helper", "function", "to", "get", "a", "URL", "from", "a", "Model", "or", "Collection", "as", "a", "property", "or", "as", "a", "function", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L2662-L2665
train
clux/modul8
examples/npm/output.js
function(string) { return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;'); }
javascript
function(string) { return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;'); }
[ "function", "(", "string", ")", "{", "return", "string", ".", "replace", "(", "/", "&(?!\\w+;|#\\d+;|#x[\\da-f]+;)", "/", "gi", ",", "'&amp;'", ")", ".", "replace", "(", "/", "<", "/", "g", ",", "'&lt;'", ")", ".", "replace", "(", "/", ">", "/", "g", ",", "'&gt;'", ")", ".", "replace", "(", "/", "\"", "/", "g", ",", "'&quot;'", ")", ".", "replace", "(", "/", "'", "/", "g", ",", "'&#x27;'", ")", ".", "replace", "(", "/", "\\/", "/", "g", ",", "'&#x2F;'", ")", ";", "}" ]
Helper function to escape a string for HTML rendering.
[ "Helper", "function", "to", "escape", "a", "string", "for", "HTML", "rendering", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L2684-L2686
train
clux/modul8
examples/npm/output.js
eq
function eq(a, b, stack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a._chain) a = a._wrapped; if (b._chain) b = b._wrapped; // Invoke a custom `isEqual` method if one is provided. if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b); if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a); // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = stack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (stack[length] == a) return true; } // Add the first object to the stack of traversed objects. stack.push(a); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { // Ensure commutative equality for sparse arrays. if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; } } } else { // Objects with different constructors are not equivalent. if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false; // Deep compare objects. for (var key in a) { if (hasOwnProperty.call(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (hasOwnProperty.call(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. stack.pop(); return result; }
javascript
function eq(a, b, stack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a._chain) a = a._wrapped; if (b._chain) b = b._wrapped; // Invoke a custom `isEqual` method if one is provided. if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b); if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a); // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = stack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (stack[length] == a) return true; } // Add the first object to the stack of traversed objects. stack.push(a); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { // Ensure commutative equality for sparse arrays. if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; } } } else { // Objects with different constructors are not equivalent. if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false; // Deep compare objects. for (var key in a) { if (hasOwnProperty.call(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (hasOwnProperty.call(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. stack.pop(); return result; }
[ "function", "eq", "(", "a", ",", "b", ",", "stack", ")", "{", "if", "(", "a", "===", "b", ")", "return", "a", "!==", "0", "||", "1", "/", "a", "==", "1", "/", "b", ";", "if", "(", "a", "==", "null", "||", "b", "==", "null", ")", "return", "a", "===", "b", ";", "if", "(", "a", ".", "_chain", ")", "a", "=", "a", ".", "_wrapped", ";", "if", "(", "b", ".", "_chain", ")", "b", "=", "b", ".", "_wrapped", ";", "if", "(", "a", ".", "isEqual", "&&", "_", ".", "isFunction", "(", "a", ".", "isEqual", ")", ")", "return", "a", ".", "isEqual", "(", "b", ")", ";", "if", "(", "b", ".", "isEqual", "&&", "_", ".", "isFunction", "(", "b", ".", "isEqual", ")", ")", "return", "b", ".", "isEqual", "(", "a", ")", ";", "var", "className", "=", "toString", ".", "call", "(", "a", ")", ";", "if", "(", "className", "!=", "toString", ".", "call", "(", "b", ")", ")", "return", "false", ";", "switch", "(", "className", ")", "{", "case", "'[object String]'", ":", "return", "a", "==", "String", "(", "b", ")", ";", "case", "'[object Number]'", ":", "return", "a", "!=", "+", "a", "?", "b", "!=", "+", "b", ":", "(", "a", "==", "0", "?", "1", "/", "a", "==", "1", "/", "b", ":", "a", "==", "+", "b", ")", ";", "case", "'[object Date]'", ":", "case", "'[object Boolean]'", ":", "return", "+", "a", "==", "+", "b", ";", "case", "'[object RegExp]'", ":", "return", "a", ".", "source", "==", "b", ".", "source", "&&", "a", ".", "global", "==", "b", ".", "global", "&&", "a", ".", "multiline", "==", "b", ".", "multiline", "&&", "a", ".", "ignoreCase", "==", "b", ".", "ignoreCase", ";", "}", "if", "(", "typeof", "a", "!=", "'object'", "||", "typeof", "b", "!=", "'object'", ")", "return", "false", ";", "var", "length", "=", "stack", ".", "length", ";", "while", "(", "length", "--", ")", "{", "if", "(", "stack", "[", "length", "]", "==", "a", ")", "return", "true", ";", "}", "stack", ".", "push", "(", "a", ")", ";", "var", "size", "=", "0", ",", "result", "=", "true", ";", "if", "(", "className", "==", "'[object Array]'", ")", "{", "size", "=", "a", ".", "length", ";", "result", "=", "size", "==", "b", ".", "length", ";", "if", "(", "result", ")", "{", "while", "(", "size", "--", ")", "{", "if", "(", "!", "(", "result", "=", "size", "in", "a", "==", "size", "in", "b", "&&", "eq", "(", "a", "[", "size", "]", ",", "b", "[", "size", "]", ",", "stack", ")", ")", ")", "break", ";", "}", "}", "}", "else", "{", "if", "(", "'constructor'", "in", "a", "!=", "'constructor'", "in", "b", "||", "a", ".", "constructor", "!=", "b", ".", "constructor", ")", "return", "false", ";", "for", "(", "var", "key", "in", "a", ")", "{", "if", "(", "hasOwnProperty", ".", "call", "(", "a", ",", "key", ")", ")", "{", "size", "++", ";", "if", "(", "!", "(", "result", "=", "hasOwnProperty", ".", "call", "(", "b", ",", "key", ")", "&&", "eq", "(", "a", "[", "key", "]", ",", "b", "[", "key", "]", ",", "stack", ")", ")", ")", "break", ";", "}", "}", "if", "(", "result", ")", "{", "for", "(", "key", "in", "b", ")", "{", "if", "(", "hasOwnProperty", ".", "call", "(", "b", ",", "key", ")", "&&", "!", "(", "size", "--", ")", ")", "break", ";", "}", "result", "=", "!", "size", ";", "}", "}", "stack", ".", "pop", "(", ")", ";", "return", "result", ";", "}" ]
Internal recursive comparison function.
[ "Internal", "recursive", "comparison", "function", "." ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/examples/npm/output.js#L3365-L3450
train
reelyactive/hlc-server
web/apps/hello-tracking/js/hello-tracking.js
updateNode
function updateNode(node, content, append) { append = append || false; while(!append && node.firstChild) { node.removeChild(node.firstChild); } if(content instanceof Element) { node.appendChild(content); } else if(content instanceof Array) { content.forEach(function(element) { node.appendChild(element); }); } else { node.textContent = content; } }
javascript
function updateNode(node, content, append) { append = append || false; while(!append && node.firstChild) { node.removeChild(node.firstChild); } if(content instanceof Element) { node.appendChild(content); } else if(content instanceof Array) { content.forEach(function(element) { node.appendChild(element); }); } else { node.textContent = content; } }
[ "function", "updateNode", "(", "node", ",", "content", ",", "append", ")", "{", "append", "=", "append", "||", "false", ";", "while", "(", "!", "append", "&&", "node", ".", "firstChild", ")", "{", "node", ".", "removeChild", "(", "node", ".", "firstChild", ")", ";", "}", "if", "(", "content", "instanceof", "Element", ")", "{", "node", ".", "appendChild", "(", "content", ")", ";", "}", "else", "if", "(", "content", "instanceof", "Array", ")", "{", "content", ".", "forEach", "(", "function", "(", "element", ")", "{", "node", ".", "appendChild", "(", "element", ")", ";", "}", ")", ";", "}", "else", "{", "node", ".", "textContent", "=", "content", ";", "}", "}" ]
Update the given node with the given content
[ "Update", "the", "given", "node", "with", "the", "given", "content" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-tracking/js/hello-tracking.js#L118-L136
train
reelyactive/hlc-server
web/apps/hello-tracking/js/hello-tracking.js
prepareEvents
function prepareEvents(raddec) { let elements = []; raddec.events.forEach(function(event) { let i = document.createElement('i'); let space = document.createTextNode(' '); i.setAttribute('class', EVENT_ICONS[event]); elements.push(i); elements.push(space); }); return elements; }
javascript
function prepareEvents(raddec) { let elements = []; raddec.events.forEach(function(event) { let i = document.createElement('i'); let space = document.createTextNode(' '); i.setAttribute('class', EVENT_ICONS[event]); elements.push(i); elements.push(space); }); return elements; }
[ "function", "prepareEvents", "(", "raddec", ")", "{", "let", "elements", "=", "[", "]", ";", "raddec", ".", "events", ".", "forEach", "(", "function", "(", "event", ")", "{", "let", "i", "=", "document", ".", "createElement", "(", "'i'", ")", ";", "let", "space", "=", "document", ".", "createTextNode", "(", "' '", ")", ";", "i", ".", "setAttribute", "(", "'class'", ",", "EVENT_ICONS", "[", "event", "]", ")", ";", "elements", ".", "push", "(", "i", ")", ";", "elements", ".", "push", "(", "space", ")", ";", "}", ")", ";", "return", "elements", ";", "}" ]
Prepare the event icons
[ "Prepare", "the", "event", "icons" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-tracking/js/hello-tracking.js#L139-L151
train
reelyactive/hlc-server
web/apps/hello-tracking/js/hello-tracking.js
prepareRecDecPac
function prepareRecDecPac(raddec) { let maxNumberOfDecodings = 0; raddec.rssiSignature.forEach(function(signature) { if(signature.numberOfDecodings > maxNumberOfDecodings) { maxNumberOfDecodings = signature.numberOfDecodings; } }); return raddec.rssiSignature.length + RDPS + maxNumberOfDecodings + RDPS + raddec.packets.length; }
javascript
function prepareRecDecPac(raddec) { let maxNumberOfDecodings = 0; raddec.rssiSignature.forEach(function(signature) { if(signature.numberOfDecodings > maxNumberOfDecodings) { maxNumberOfDecodings = signature.numberOfDecodings; } }); return raddec.rssiSignature.length + RDPS + maxNumberOfDecodings + RDPS + raddec.packets.length; }
[ "function", "prepareRecDecPac", "(", "raddec", ")", "{", "let", "maxNumberOfDecodings", "=", "0", ";", "raddec", ".", "rssiSignature", ".", "forEach", "(", "function", "(", "signature", ")", "{", "if", "(", "signature", ".", "numberOfDecodings", ">", "maxNumberOfDecodings", ")", "{", "maxNumberOfDecodings", "=", "signature", ".", "numberOfDecodings", ";", "}", "}", ")", ";", "return", "raddec", ".", "rssiSignature", ".", "length", "+", "RDPS", "+", "maxNumberOfDecodings", "+", "RDPS", "+", "raddec", ".", "packets", ".", "length", ";", "}" ]
Prepare the receivers-decodings-packets string
[ "Prepare", "the", "receivers", "-", "decodings", "-", "packets", "string" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-tracking/js/hello-tracking.js#L154-L165
train
reelyactive/hlc-server
web/apps/hello-tracking/js/hello-tracking.js
sortRaddecsAndHighlight
function sortRaddecsAndHighlight(transmitterId) { let trs = Array.from(tbody.getElementsByTagName('tr')); let sortedFragment = document.createDocumentFragment(); trs.sort(sortFunction); trs.forEach(function(tr) { if(tr.id === transmitterId) { tr.setAttribute('class', 'monospace animated-highlight-reelyactive'); } else { tr.setAttribute('class', 'monospace'); } sortedFragment.appendChild(tr); }); tbody.appendChild(sortedFragment); }
javascript
function sortRaddecsAndHighlight(transmitterId) { let trs = Array.from(tbody.getElementsByTagName('tr')); let sortedFragment = document.createDocumentFragment(); trs.sort(sortFunction); trs.forEach(function(tr) { if(tr.id === transmitterId) { tr.setAttribute('class', 'monospace animated-highlight-reelyactive'); } else { tr.setAttribute('class', 'monospace'); } sortedFragment.appendChild(tr); }); tbody.appendChild(sortedFragment); }
[ "function", "sortRaddecsAndHighlight", "(", "transmitterId", ")", "{", "let", "trs", "=", "Array", ".", "from", "(", "tbody", ".", "getElementsByTagName", "(", "'tr'", ")", ")", ";", "let", "sortedFragment", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "trs", ".", "sort", "(", "sortFunction", ")", ";", "trs", ".", "forEach", "(", "function", "(", "tr", ")", "{", "if", "(", "tr", ".", "id", "===", "transmitterId", ")", "{", "tr", ".", "setAttribute", "(", "'class'", ",", "'monospace animated-highlight-reelyactive'", ")", ";", "}", "else", "{", "tr", ".", "setAttribute", "(", "'class'", ",", "'monospace'", ")", ";", "}", "sortedFragment", ".", "appendChild", "(", "tr", ")", ";", "}", ")", ";", "tbody", ".", "appendChild", "(", "sortedFragment", ")", ";", "}" ]
Sort the raddecs in the table, highlighting the given transmitterId
[ "Sort", "the", "raddecs", "in", "the", "table", "highlighting", "the", "given", "transmitterId" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-tracking/js/hello-tracking.js#L193-L210
train
runspired/ember-mobiletouch
addon/utils/prevent-ghost-clicks.js
makeGhostBuster
function makeGhostBuster() { var coordinates = []; var threshold = 25; var timeout = 2500; // no touch support if(!mobileDetection.is()) { return { add : function(){}, remove : function(){} }; } /** * prevent clicks if they're in a registered XY region * @param {MouseEvent} event */ function preventGhostClick(event) { var ev = event.originalEvent || event; //don't prevent fastclicks if (ev.fastclick) { return true; } for (var i = 0; i < coordinates.length; i++) { var x = coordinates[i][0]; var y = coordinates[i][1]; // within the range, so prevent the click if (Math.abs(ev.clientX - x) < threshold && Math.abs(ev.clientY - y) < threshold) { event.stopPropagation(); event.stopImmediatePropagation(); event.preventDefault(); return false; } } } /** * reset the coordinates array */ function resetCoordinates() { coordinates = []; } /** * remove the first coordinates set from the array */ function popCoordinates() { coordinates.splice(0, 1); } /** * if it is an final touchend, we want to register it's place * @param {TouchEvent} event */ function registerCoordinates(event) { var ev = event.originalEvent || event; // It seems that touchend is the cause for derived events like 'change' for // checkboxes. Since we're creating fastclicks, which will also cause 'change' // events to fire, we need to prevent default on touchend events, which has // the effect of not causing these derived events to be created. I am not // sure if this has any other negative consequences. ev.preventDefault(); // touchend is triggered on every releasing finger // changed touches always contain the removed touches on a touchend // the touches object might contain these also at some browsers (firefox os) // so touches - changedTouches will be 0 or lower, like -1, on the final touchend if(ev.touches.length - ev.changedTouches.length <= 0) { var touch = ev.changedTouches[0]; coordinates.push([touch.clientX, touch.clientY]); setTimeout(popCoordinates, timeout); } } /** * prevent click events for the given element * @param {EventTarget} $element jQuery object */ return { add : Ember.run.bind(this, function ($element) { $element.on("touchstart.ghost-click-buster", resetCoordinates); $element.on("touchend.ghost-click-buster", registerCoordinates); // register the click buster on with the selector, '*', which will // cause it to fire on the first element that gets clicked on so that // if this is a ghost click it will get killed immediately. $element.on("click.ghost-click-buster", '*', preventGhostClick); }), remove : Ember.run.bind(this, function ($element) { $element.off('.ghost-click-buster'); }) }; }
javascript
function makeGhostBuster() { var coordinates = []; var threshold = 25; var timeout = 2500; // no touch support if(!mobileDetection.is()) { return { add : function(){}, remove : function(){} }; } /** * prevent clicks if they're in a registered XY region * @param {MouseEvent} event */ function preventGhostClick(event) { var ev = event.originalEvent || event; //don't prevent fastclicks if (ev.fastclick) { return true; } for (var i = 0; i < coordinates.length; i++) { var x = coordinates[i][0]; var y = coordinates[i][1]; // within the range, so prevent the click if (Math.abs(ev.clientX - x) < threshold && Math.abs(ev.clientY - y) < threshold) { event.stopPropagation(); event.stopImmediatePropagation(); event.preventDefault(); return false; } } } /** * reset the coordinates array */ function resetCoordinates() { coordinates = []; } /** * remove the first coordinates set from the array */ function popCoordinates() { coordinates.splice(0, 1); } /** * if it is an final touchend, we want to register it's place * @param {TouchEvent} event */ function registerCoordinates(event) { var ev = event.originalEvent || event; // It seems that touchend is the cause for derived events like 'change' for // checkboxes. Since we're creating fastclicks, which will also cause 'change' // events to fire, we need to prevent default on touchend events, which has // the effect of not causing these derived events to be created. I am not // sure if this has any other negative consequences. ev.preventDefault(); // touchend is triggered on every releasing finger // changed touches always contain the removed touches on a touchend // the touches object might contain these also at some browsers (firefox os) // so touches - changedTouches will be 0 or lower, like -1, on the final touchend if(ev.touches.length - ev.changedTouches.length <= 0) { var touch = ev.changedTouches[0]; coordinates.push([touch.clientX, touch.clientY]); setTimeout(popCoordinates, timeout); } } /** * prevent click events for the given element * @param {EventTarget} $element jQuery object */ return { add : Ember.run.bind(this, function ($element) { $element.on("touchstart.ghost-click-buster", resetCoordinates); $element.on("touchend.ghost-click-buster", registerCoordinates); // register the click buster on with the selector, '*', which will // cause it to fire on the first element that gets clicked on so that // if this is a ghost click it will get killed immediately. $element.on("click.ghost-click-buster", '*', preventGhostClick); }), remove : Ember.run.bind(this, function ($element) { $element.off('.ghost-click-buster'); }) }; }
[ "function", "makeGhostBuster", "(", ")", "{", "var", "coordinates", "=", "[", "]", ";", "var", "threshold", "=", "25", ";", "var", "timeout", "=", "2500", ";", "if", "(", "!", "mobileDetection", ".", "is", "(", ")", ")", "{", "return", "{", "add", ":", "function", "(", ")", "{", "}", ",", "remove", ":", "function", "(", ")", "{", "}", "}", ";", "}", "function", "preventGhostClick", "(", "event", ")", "{", "var", "ev", "=", "event", ".", "originalEvent", "||", "event", ";", "if", "(", "ev", ".", "fastclick", ")", "{", "return", "true", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "coordinates", ".", "length", ";", "i", "++", ")", "{", "var", "x", "=", "coordinates", "[", "i", "]", "[", "0", "]", ";", "var", "y", "=", "coordinates", "[", "i", "]", "[", "1", "]", ";", "if", "(", "Math", ".", "abs", "(", "ev", ".", "clientX", "-", "x", ")", "<", "threshold", "&&", "Math", ".", "abs", "(", "ev", ".", "clientY", "-", "y", ")", "<", "threshold", ")", "{", "event", ".", "stopPropagation", "(", ")", ";", "event", ".", "stopImmediatePropagation", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "return", "false", ";", "}", "}", "}", "function", "resetCoordinates", "(", ")", "{", "coordinates", "=", "[", "]", ";", "}", "function", "popCoordinates", "(", ")", "{", "coordinates", ".", "splice", "(", "0", ",", "1", ")", ";", "}", "function", "registerCoordinates", "(", "event", ")", "{", "var", "ev", "=", "event", ".", "originalEvent", "||", "event", ";", "ev", ".", "preventDefault", "(", ")", ";", "if", "(", "ev", ".", "touches", ".", "length", "-", "ev", ".", "changedTouches", ".", "length", "<=", "0", ")", "{", "var", "touch", "=", "ev", ".", "changedTouches", "[", "0", "]", ";", "coordinates", ".", "push", "(", "[", "touch", ".", "clientX", ",", "touch", ".", "clientY", "]", ")", ";", "setTimeout", "(", "popCoordinates", ",", "timeout", ")", ";", "}", "}", "return", "{", "add", ":", "Ember", ".", "run", ".", "bind", "(", "this", ",", "function", "(", "$element", ")", "{", "$element", ".", "on", "(", "\"touchstart.ghost-click-buster\"", ",", "resetCoordinates", ")", ";", "$element", ".", "on", "(", "\"touchend.ghost-click-buster\"", ",", "registerCoordinates", ")", ";", "$element", ".", "on", "(", "\"click.ghost-click-buster\"", ",", "'*'", ",", "preventGhostClick", ")", ";", "}", ")", ",", "remove", ":", "Ember", ".", "run", ".", "bind", "(", "this", ",", "function", "(", "$element", ")", "{", "$element", ".", "off", "(", "'.ghost-click-buster'", ")", ";", "}", ")", "}", ";", "}" ]
Prevent click events after a touchend. Inspired/copy-paste from this article of Google by Ryan Fioravanti https://developers.google.com/mobile/articles/fast_buttons#ghost USAGE: Prevent the click event for an certain element ```` PreventGhostClick($element); ````
[ "Prevent", "click", "events", "after", "a", "touchend", "." ]
65790013838776430bd55ee980bc9137711f8c36
https://github.com/runspired/ember-mobiletouch/blob/65790013838776430bd55ee980bc9137711f8c36/addon/utils/prevent-ghost-clicks.js#L17-L110
train
runspired/ember-mobiletouch
addon/utils/prevent-ghost-clicks.js
registerCoordinates
function registerCoordinates(event) { var ev = event.originalEvent || event; // It seems that touchend is the cause for derived events like 'change' for // checkboxes. Since we're creating fastclicks, which will also cause 'change' // events to fire, we need to prevent default on touchend events, which has // the effect of not causing these derived events to be created. I am not // sure if this has any other negative consequences. ev.preventDefault(); // touchend is triggered on every releasing finger // changed touches always contain the removed touches on a touchend // the touches object might contain these also at some browsers (firefox os) // so touches - changedTouches will be 0 or lower, like -1, on the final touchend if(ev.touches.length - ev.changedTouches.length <= 0) { var touch = ev.changedTouches[0]; coordinates.push([touch.clientX, touch.clientY]); setTimeout(popCoordinates, timeout); } }
javascript
function registerCoordinates(event) { var ev = event.originalEvent || event; // It seems that touchend is the cause for derived events like 'change' for // checkboxes. Since we're creating fastclicks, which will also cause 'change' // events to fire, we need to prevent default on touchend events, which has // the effect of not causing these derived events to be created. I am not // sure if this has any other negative consequences. ev.preventDefault(); // touchend is triggered on every releasing finger // changed touches always contain the removed touches on a touchend // the touches object might contain these also at some browsers (firefox os) // so touches - changedTouches will be 0 or lower, like -1, on the final touchend if(ev.touches.length - ev.changedTouches.length <= 0) { var touch = ev.changedTouches[0]; coordinates.push([touch.clientX, touch.clientY]); setTimeout(popCoordinates, timeout); } }
[ "function", "registerCoordinates", "(", "event", ")", "{", "var", "ev", "=", "event", ".", "originalEvent", "||", "event", ";", "ev", ".", "preventDefault", "(", ")", ";", "if", "(", "ev", ".", "touches", ".", "length", "-", "ev", ".", "changedTouches", ".", "length", "<=", "0", ")", "{", "var", "touch", "=", "ev", ".", "changedTouches", "[", "0", "]", ";", "coordinates", ".", "push", "(", "[", "touch", ".", "clientX", ",", "touch", ".", "clientY", "]", ")", ";", "setTimeout", "(", "popCoordinates", ",", "timeout", ")", ";", "}", "}" ]
if it is an final touchend, we want to register it's place @param {TouchEvent} event
[ "if", "it", "is", "an", "final", "touchend", "we", "want", "to", "register", "it", "s", "place" ]
65790013838776430bd55ee980bc9137711f8c36
https://github.com/runspired/ember-mobiletouch/blob/65790013838776430bd55ee980bc9137711f8c36/addon/utils/prevent-ghost-clicks.js#L70-L89
train
erha19/eslint-plugin-weex
eslint-internal-rules/require-meta-docs-url.js
getKeyName
function getKeyName (property) { if (!property.computed && property.key.type === 'Identifier') { return property.key.name } if (property.key.type === 'Literal') { return '' + property.key.value } if (property.key.type === 'TemplateLiteral' && property.key.quasis.length === 1) { return property.key.quasis[0].value.cooked } return null }
javascript
function getKeyName (property) { if (!property.computed && property.key.type === 'Identifier') { return property.key.name } if (property.key.type === 'Literal') { return '' + property.key.value } if (property.key.type === 'TemplateLiteral' && property.key.quasis.length === 1) { return property.key.quasis[0].value.cooked } return null }
[ "function", "getKeyName", "(", "property", ")", "{", "if", "(", "!", "property", ".", "computed", "&&", "property", ".", "key", ".", "type", "===", "'Identifier'", ")", "{", "return", "property", ".", "key", ".", "name", "}", "if", "(", "property", ".", "key", ".", "type", "===", "'Literal'", ")", "{", "return", "''", "+", "property", ".", "key", ".", "value", "}", "if", "(", "property", ".", "key", ".", "type", "===", "'TemplateLiteral'", "&&", "property", ".", "key", ".", "quasis", ".", "length", "===", "1", ")", "{", "return", "property", ".", "key", ".", "quasis", "[", "0", "]", ".", "value", ".", "cooked", "}", "return", "null", "}" ]
Gets the key name of a Property, if it can be determined statically. @param {ASTNode} node The `Property` node @returns {string|null} The key name, or `null` if the name cannot be determined statically.
[ "Gets", "the", "key", "name", "of", "a", "Property", "if", "it", "can", "be", "determined", "statically", "." ]
2f7db1812fe66a529c3dc68fd2d22e9e7962d51e
https://github.com/erha19/eslint-plugin-weex/blob/2f7db1812fe66a529c3dc68fd2d22e9e7962d51e/eslint-internal-rules/require-meta-docs-url.js#L37-L48
train
erha19/eslint-plugin-weex
eslint-internal-rules/require-meta-docs-url.js
getRuleInfo
function getRuleInfo (ast) { const INTERESTING_KEYS = new Set(['create', 'meta']) let exportsVarOverridden = false let exportsIsFunction = false const exportNodes = ast.body .filter(statement => statement.type === 'ExpressionStatement') .map(statement => statement.expression) .filter(expression => expression.type === 'AssignmentExpression') .filter(expression => expression.left.type === 'MemberExpression') .reduce((currentExports, node) => { if ( node.left.object.type === 'Identifier' && node.left.object.name === 'module' && node.left.property.type === 'Identifier' && node.left.property.name === 'exports' ) { exportsVarOverridden = true if (isNormalFunctionExpression(node.right)) { // Check `module.exports = function () {}` exportsIsFunction = true return { create: node.right, meta: null } } else if (node.right.type === 'ObjectExpression') { // Check `module.exports = { create: function () {}, meta: {} }` exportsIsFunction = false return node.right.properties.reduce((parsedProps, prop) => { const keyValue = getKeyName(prop) if (INTERESTING_KEYS.has(keyValue)) { parsedProps[keyValue] = prop.value } return parsedProps }, {}) } return {} } else if ( !exportsIsFunction && node.left.object.type === 'MemberExpression' && node.left.object.object.type === 'Identifier' && node.left.object.object.name === 'module' && node.left.object.property.type === 'Identifier' && node.left.object.property.name === 'exports' && node.left.property.type === 'Identifier' && INTERESTING_KEYS.has(node.left.property.name) ) { // Check `module.exports.create = () => {}` currentExports[node.left.property.name] = node.right } else if ( !exportsVarOverridden && node.left.object.type === 'Identifier' && node.left.object.name === 'exports' && node.left.property.type === 'Identifier' && INTERESTING_KEYS.has(node.left.property.name) ) { // Check `exports.create = () => {}` currentExports[node.left.property.name] = node.right } return currentExports }, {}) return Object.prototype.hasOwnProperty.call(exportNodes, 'create') && isNormalFunctionExpression(exportNodes.create) ? Object.assign({ isNewStyle: !exportsIsFunction, meta: null }, exportNodes) : null }
javascript
function getRuleInfo (ast) { const INTERESTING_KEYS = new Set(['create', 'meta']) let exportsVarOverridden = false let exportsIsFunction = false const exportNodes = ast.body .filter(statement => statement.type === 'ExpressionStatement') .map(statement => statement.expression) .filter(expression => expression.type === 'AssignmentExpression') .filter(expression => expression.left.type === 'MemberExpression') .reduce((currentExports, node) => { if ( node.left.object.type === 'Identifier' && node.left.object.name === 'module' && node.left.property.type === 'Identifier' && node.left.property.name === 'exports' ) { exportsVarOverridden = true if (isNormalFunctionExpression(node.right)) { // Check `module.exports = function () {}` exportsIsFunction = true return { create: node.right, meta: null } } else if (node.right.type === 'ObjectExpression') { // Check `module.exports = { create: function () {}, meta: {} }` exportsIsFunction = false return node.right.properties.reduce((parsedProps, prop) => { const keyValue = getKeyName(prop) if (INTERESTING_KEYS.has(keyValue)) { parsedProps[keyValue] = prop.value } return parsedProps }, {}) } return {} } else if ( !exportsIsFunction && node.left.object.type === 'MemberExpression' && node.left.object.object.type === 'Identifier' && node.left.object.object.name === 'module' && node.left.object.property.type === 'Identifier' && node.left.object.property.name === 'exports' && node.left.property.type === 'Identifier' && INTERESTING_KEYS.has(node.left.property.name) ) { // Check `module.exports.create = () => {}` currentExports[node.left.property.name] = node.right } else if ( !exportsVarOverridden && node.left.object.type === 'Identifier' && node.left.object.name === 'exports' && node.left.property.type === 'Identifier' && INTERESTING_KEYS.has(node.left.property.name) ) { // Check `exports.create = () => {}` currentExports[node.left.property.name] = node.right } return currentExports }, {}) return Object.prototype.hasOwnProperty.call(exportNodes, 'create') && isNormalFunctionExpression(exportNodes.create) ? Object.assign({ isNewStyle: !exportsIsFunction, meta: null }, exportNodes) : null }
[ "function", "getRuleInfo", "(", "ast", ")", "{", "const", "INTERESTING_KEYS", "=", "new", "Set", "(", "[", "'create'", ",", "'meta'", "]", ")", "let", "exportsVarOverridden", "=", "false", "let", "exportsIsFunction", "=", "false", "const", "exportNodes", "=", "ast", ".", "body", ".", "filter", "(", "statement", "=>", "statement", ".", "type", "===", "'ExpressionStatement'", ")", ".", "map", "(", "statement", "=>", "statement", ".", "expression", ")", ".", "filter", "(", "expression", "=>", "expression", ".", "type", "===", "'AssignmentExpression'", ")", ".", "filter", "(", "expression", "=>", "expression", ".", "left", ".", "type", "===", "'MemberExpression'", ")", ".", "reduce", "(", "(", "currentExports", ",", "node", ")", "=>", "{", "if", "(", "node", ".", "left", ".", "object", ".", "type", "===", "'Identifier'", "&&", "node", ".", "left", ".", "object", ".", "name", "===", "'module'", "&&", "node", ".", "left", ".", "property", ".", "type", "===", "'Identifier'", "&&", "node", ".", "left", ".", "property", ".", "name", "===", "'exports'", ")", "{", "exportsVarOverridden", "=", "true", "if", "(", "isNormalFunctionExpression", "(", "node", ".", "right", ")", ")", "{", "exportsIsFunction", "=", "true", "return", "{", "create", ":", "node", ".", "right", ",", "meta", ":", "null", "}", "}", "else", "if", "(", "node", ".", "right", ".", "type", "===", "'ObjectExpression'", ")", "{", "exportsIsFunction", "=", "false", "return", "node", ".", "right", ".", "properties", ".", "reduce", "(", "(", "parsedProps", ",", "prop", ")", "=>", "{", "const", "keyValue", "=", "getKeyName", "(", "prop", ")", "if", "(", "INTERESTING_KEYS", ".", "has", "(", "keyValue", ")", ")", "{", "parsedProps", "[", "keyValue", "]", "=", "prop", ".", "value", "}", "return", "parsedProps", "}", ",", "{", "}", ")", "}", "return", "{", "}", "}", "else", "if", "(", "!", "exportsIsFunction", "&&", "node", ".", "left", ".", "object", ".", "type", "===", "'MemberExpression'", "&&", "node", ".", "left", ".", "object", ".", "object", ".", "type", "===", "'Identifier'", "&&", "node", ".", "left", ".", "object", ".", "object", ".", "name", "===", "'module'", "&&", "node", ".", "left", ".", "object", ".", "property", ".", "type", "===", "'Identifier'", "&&", "node", ".", "left", ".", "object", ".", "property", ".", "name", "===", "'exports'", "&&", "node", ".", "left", ".", "property", ".", "type", "===", "'Identifier'", "&&", "INTERESTING_KEYS", ".", "has", "(", "node", ".", "left", ".", "property", ".", "name", ")", ")", "{", "currentExports", "[", "node", ".", "left", ".", "property", ".", "name", "]", "=", "node", ".", "right", "}", "else", "if", "(", "!", "exportsVarOverridden", "&&", "node", ".", "left", ".", "object", ".", "type", "===", "'Identifier'", "&&", "node", ".", "left", ".", "object", ".", "name", "===", "'exports'", "&&", "node", ".", "left", ".", "property", ".", "type", "===", "'Identifier'", "&&", "INTERESTING_KEYS", ".", "has", "(", "node", ".", "left", ".", "property", ".", "name", ")", ")", "{", "currentExports", "[", "node", ".", "left", ".", "property", ".", "name", "]", "=", "node", ".", "right", "}", "return", "currentExports", "}", ",", "{", "}", ")", "return", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "exportNodes", ",", "'create'", ")", "&&", "isNormalFunctionExpression", "(", "exportNodes", ".", "create", ")", "?", "Object", ".", "assign", "(", "{", "isNewStyle", ":", "!", "exportsIsFunction", ",", "meta", ":", "null", "}", ",", "exportNodes", ")", ":", "null", "}" ]
Performs static analysis on an AST to try to determine the final value of `module.exports`. @param {ASTNode} ast The `Program` AST node @returns {Object} An object with keys `meta`, `create`, and `isNewStyle`. `meta` and `create` correspond to the AST nodes for the final values of `module.exports.meta` and `module.exports.create`. `isNewStyle` will be `true` if `module.exports` is an object, and `false` if module.exports is just the `create` function. If no valid ESLint rule info can be extracted from the file, the return value will be `null`.
[ "Performs", "static", "analysis", "on", "an", "AST", "to", "try", "to", "determine", "the", "final", "value", "of", "module", ".", "exports", "." ]
2f7db1812fe66a529c3dc68fd2d22e9e7962d51e
https://github.com/erha19/eslint-plugin-weex/blob/2f7db1812fe66a529c3dc68fd2d22e9e7962d51e/eslint-internal-rules/require-meta-docs-url.js#L58-L118
train
jiahaog/Revenant
lib/helpers/helpers.js
cookieToHeader
function cookieToHeader(cookies) { const SEPARATOR = '; '; return cookies.reduce(function (previous, current) { return previous + current.name + '=' + current.value + SEPARATOR; }, ''); }
javascript
function cookieToHeader(cookies) { const SEPARATOR = '; '; return cookies.reduce(function (previous, current) { return previous + current.name + '=' + current.value + SEPARATOR; }, ''); }
[ "function", "cookieToHeader", "(", "cookies", ")", "{", "const", "SEPARATOR", "=", "'; '", ";", "return", "cookies", ".", "reduce", "(", "function", "(", "previous", ",", "current", ")", "{", "return", "previous", "+", "current", ".", "name", "+", "'='", "+", "current", ".", "value", "+", "SEPARATOR", ";", "}", ",", "''", ")", ";", "}" ]
Transforms an array of cookies objects into a request header @param cookies {array} @returns {string}
[ "Transforms", "an", "array", "of", "cookies", "objects", "into", "a", "request", "header" ]
562dd4e7a6bacb9c8b51c1344a5e336545177516
https://github.com/jiahaog/Revenant/blob/562dd4e7a6bacb9c8b51c1344a5e336545177516/lib/helpers/helpers.js#L32-L37
train
reelyactive/hlc-server
web/apps/hello-elasticsearch/js/hello-elasticsearch.js
updateQuery
function updateQuery() { let query = {}; switch(queryTemplates.value) { case '0': // All raddecs query = { "size": 10, "query": { "match_all": {} }, "_source": [ "transmitterId", "transmitterIdType", "receiverId", "receiverIdType", "rssi", "timestamp", "numberOfDecodings", "numberOfReceivers", "numberOfPackets" ] }; queryBox.value = JSON.stringify(query, null, 2); break; case '1': // Specific transmitterId query = { "size": 10, "query": { "term": { "transmitterId": "" } }, "_source": [ "receiverId", "receiverIdType", "rssi", "timestamp", "numberOfDecodings", "numberOfReceivers", "numberOfPackets", "packets" ] }; queryBox.value = JSON.stringify(query, null, 2); break; case '2': // Prefix transmitterId query = { "size": 10, "query": { "prefix": { "transmitterId": "" } }, "_source": [ "transmitterId", "transmitterIdType", "receiverId", "receiverIdType", "rssi", "timestamp", "numberOfDecodings", "numberOfReceivers", "numberOfPackets" ] }; queryBox.value = JSON.stringify(query, null, 2); break; case '3': // Aggregate receiverId query = { "size": 0, "aggs" : { "receivers" : { "terms" : { "field" : "receiverId.keyword", "order" : { "_count" : "desc" }, "size": 12 } } } }; queryBox.value = JSON.stringify(query, null, 2); break; case '4': // Aggregate rec/dec/pac query = { "size": 0, "aggs" : { "numberOfReceivers" : { "histogram" : { "field" : "numberOfReceivers", "interval" : 1 } }, "numberOfDecodings" : { "histogram" : { "field" : "numberOfDecodings", "interval" : 1, "min_doc_count" : 1 } }, "numberOfDistinctPackets" : { "histogram" : { "field" : "numberOfDistinctPackets", "interval" : 1 } } } }; queryBox.value = JSON.stringify(query, null, 2); break; case '5': // Auto-date histogram query = { "size": 0, "aggs" : { "periods" : { "auto_date_histogram" : { "field" : "timestamp", "buckets" : 12 } } } }; queryBox.value = JSON.stringify(query, null, 2); break; } queryBox.rows = countNumberOfLines(queryBox.value); parseQuery(); }
javascript
function updateQuery() { let query = {}; switch(queryTemplates.value) { case '0': // All raddecs query = { "size": 10, "query": { "match_all": {} }, "_source": [ "transmitterId", "transmitterIdType", "receiverId", "receiverIdType", "rssi", "timestamp", "numberOfDecodings", "numberOfReceivers", "numberOfPackets" ] }; queryBox.value = JSON.stringify(query, null, 2); break; case '1': // Specific transmitterId query = { "size": 10, "query": { "term": { "transmitterId": "" } }, "_source": [ "receiverId", "receiverIdType", "rssi", "timestamp", "numberOfDecodings", "numberOfReceivers", "numberOfPackets", "packets" ] }; queryBox.value = JSON.stringify(query, null, 2); break; case '2': // Prefix transmitterId query = { "size": 10, "query": { "prefix": { "transmitterId": "" } }, "_source": [ "transmitterId", "transmitterIdType", "receiverId", "receiverIdType", "rssi", "timestamp", "numberOfDecodings", "numberOfReceivers", "numberOfPackets" ] }; queryBox.value = JSON.stringify(query, null, 2); break; case '3': // Aggregate receiverId query = { "size": 0, "aggs" : { "receivers" : { "terms" : { "field" : "receiverId.keyword", "order" : { "_count" : "desc" }, "size": 12 } } } }; queryBox.value = JSON.stringify(query, null, 2); break; case '4': // Aggregate rec/dec/pac query = { "size": 0, "aggs" : { "numberOfReceivers" : { "histogram" : { "field" : "numberOfReceivers", "interval" : 1 } }, "numberOfDecodings" : { "histogram" : { "field" : "numberOfDecodings", "interval" : 1, "min_doc_count" : 1 } }, "numberOfDistinctPackets" : { "histogram" : { "field" : "numberOfDistinctPackets", "interval" : 1 } } } }; queryBox.value = JSON.stringify(query, null, 2); break; case '5': // Auto-date histogram query = { "size": 0, "aggs" : { "periods" : { "auto_date_histogram" : { "field" : "timestamp", "buckets" : 12 } } } }; queryBox.value = JSON.stringify(query, null, 2); break; } queryBox.rows = countNumberOfLines(queryBox.value); parseQuery(); }
[ "function", "updateQuery", "(", ")", "{", "let", "query", "=", "{", "}", ";", "switch", "(", "queryTemplates", ".", "value", ")", "{", "case", "'0'", ":", "query", "=", "{", "\"size\"", ":", "10", ",", "\"query\"", ":", "{", "\"match_all\"", ":", "{", "}", "}", ",", "\"_source\"", ":", "[", "\"transmitterId\"", ",", "\"transmitterIdType\"", ",", "\"receiverId\"", ",", "\"receiverIdType\"", ",", "\"rssi\"", ",", "\"timestamp\"", ",", "\"numberOfDecodings\"", ",", "\"numberOfReceivers\"", ",", "\"numberOfPackets\"", "]", "}", ";", "queryBox", ".", "value", "=", "JSON", ".", "stringify", "(", "query", ",", "null", ",", "2", ")", ";", "break", ";", "case", "'1'", ":", "query", "=", "{", "\"size\"", ":", "10", ",", "\"query\"", ":", "{", "\"term\"", ":", "{", "\"transmitterId\"", ":", "\"\"", "}", "}", ",", "\"_source\"", ":", "[", "\"receiverId\"", ",", "\"receiverIdType\"", ",", "\"rssi\"", ",", "\"timestamp\"", ",", "\"numberOfDecodings\"", ",", "\"numberOfReceivers\"", ",", "\"numberOfPackets\"", ",", "\"packets\"", "]", "}", ";", "queryBox", ".", "value", "=", "JSON", ".", "stringify", "(", "query", ",", "null", ",", "2", ")", ";", "break", ";", "case", "'2'", ":", "query", "=", "{", "\"size\"", ":", "10", ",", "\"query\"", ":", "{", "\"prefix\"", ":", "{", "\"transmitterId\"", ":", "\"\"", "}", "}", ",", "\"_source\"", ":", "[", "\"transmitterId\"", ",", "\"transmitterIdType\"", ",", "\"receiverId\"", ",", "\"receiverIdType\"", ",", "\"rssi\"", ",", "\"timestamp\"", ",", "\"numberOfDecodings\"", ",", "\"numberOfReceivers\"", ",", "\"numberOfPackets\"", "]", "}", ";", "queryBox", ".", "value", "=", "JSON", ".", "stringify", "(", "query", ",", "null", ",", "2", ")", ";", "break", ";", "case", "'3'", ":", "query", "=", "{", "\"size\"", ":", "0", ",", "\"aggs\"", ":", "{", "\"receivers\"", ":", "{", "\"terms\"", ":", "{", "\"field\"", ":", "\"receiverId.keyword\"", ",", "\"order\"", ":", "{", "\"_count\"", ":", "\"desc\"", "}", ",", "\"size\"", ":", "12", "}", "}", "}", "}", ";", "queryBox", ".", "value", "=", "JSON", ".", "stringify", "(", "query", ",", "null", ",", "2", ")", ";", "break", ";", "case", "'4'", ":", "query", "=", "{", "\"size\"", ":", "0", ",", "\"aggs\"", ":", "{", "\"numberOfReceivers\"", ":", "{", "\"histogram\"", ":", "{", "\"field\"", ":", "\"numberOfReceivers\"", ",", "\"interval\"", ":", "1", "}", "}", ",", "\"numberOfDecodings\"", ":", "{", "\"histogram\"", ":", "{", "\"field\"", ":", "\"numberOfDecodings\"", ",", "\"interval\"", ":", "1", ",", "\"min_doc_count\"", ":", "1", "}", "}", ",", "\"numberOfDistinctPackets\"", ":", "{", "\"histogram\"", ":", "{", "\"field\"", ":", "\"numberOfDistinctPackets\"", ",", "\"interval\"", ":", "1", "}", "}", "}", "}", ";", "queryBox", ".", "value", "=", "JSON", ".", "stringify", "(", "query", ",", "null", ",", "2", ")", ";", "break", ";", "case", "'5'", ":", "query", "=", "{", "\"size\"", ":", "0", ",", "\"aggs\"", ":", "{", "\"periods\"", ":", "{", "\"auto_date_histogram\"", ":", "{", "\"field\"", ":", "\"timestamp\"", ",", "\"buckets\"", ":", "12", "}", "}", "}", "}", ";", "queryBox", ".", "value", "=", "JSON", ".", "stringify", "(", "query", ",", "null", ",", "2", ")", ";", "break", ";", "}", "queryBox", ".", "rows", "=", "countNumberOfLines", "(", "queryBox", ".", "value", ")", ";", "parseQuery", "(", ")", ";", "}" ]
Update the query JSON based on the selected template
[ "Update", "the", "query", "JSON", "based", "on", "the", "selected", "template" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-elasticsearch/js/hello-elasticsearch.js#L44-L139
train
reelyactive/hlc-server
web/apps/hello-elasticsearch/js/hello-elasticsearch.js
parseQuery
function parseQuery() { let query = {}; try { query = JSON.parse(queryBox.value); } catch(error) { queryError.textContent = 'Query must be valid JSON'; hide(queryButton); hide(queryResults); show(queryError); return null; } hide(queryError); show(queryButton); return query; }
javascript
function parseQuery() { let query = {}; try { query = JSON.parse(queryBox.value); } catch(error) { queryError.textContent = 'Query must be valid JSON'; hide(queryButton); hide(queryResults); show(queryError); return null; } hide(queryError); show(queryButton); return query; }
[ "function", "parseQuery", "(", ")", "{", "let", "query", "=", "{", "}", ";", "try", "{", "query", "=", "JSON", ".", "parse", "(", "queryBox", ".", "value", ")", ";", "}", "catch", "(", "error", ")", "{", "queryError", ".", "textContent", "=", "'Query must be valid JSON'", ";", "hide", "(", "queryButton", ")", ";", "hide", "(", "queryResults", ")", ";", "show", "(", "queryError", ")", ";", "return", "null", ";", "}", "hide", "(", "queryError", ")", ";", "show", "(", "queryButton", ")", ";", "return", "query", ";", "}" ]
Parse the query as typed in the box and confirm it is valid JSON
[ "Parse", "the", "query", "as", "typed", "in", "the", "box", "and", "confirm", "it", "is", "valid", "JSON" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-elasticsearch/js/hello-elasticsearch.js#L142-L157
train
reelyactive/hlc-server
web/apps/hello-elasticsearch/js/hello-elasticsearch.js
handleQuery
function handleQuery() { let query = parseQuery(); let url = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + ELASTICSEARCH_INTERFACE_ROUTE; let httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if(httpRequest.readyState === XMLHttpRequest.DONE) { if(httpRequest.status === 200) { let response = JSON.parse(httpRequest.responseText); updateResults(response); updateHits(response); updateAggregations(response); show(queryResults); } else { queryError.textContent = 'Query returned status ' + httpRequest.status + '. Is Elasticsearch connected and running?'; hide(queryResults); hide(queryButton); show(queryError); } } }; httpRequest.open('POST', url); httpRequest.setRequestHeader('Content-Type', 'application/json'); httpRequest.setRequestHeader('Accept', 'application/json'); httpRequest.send(JSON.stringify(query)); }
javascript
function handleQuery() { let query = parseQuery(); let url = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + ELASTICSEARCH_INTERFACE_ROUTE; let httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if(httpRequest.readyState === XMLHttpRequest.DONE) { if(httpRequest.status === 200) { let response = JSON.parse(httpRequest.responseText); updateResults(response); updateHits(response); updateAggregations(response); show(queryResults); } else { queryError.textContent = 'Query returned status ' + httpRequest.status + '. Is Elasticsearch connected and running?'; hide(queryResults); hide(queryButton); show(queryError); } } }; httpRequest.open('POST', url); httpRequest.setRequestHeader('Content-Type', 'application/json'); httpRequest.setRequestHeader('Accept', 'application/json'); httpRequest.send(JSON.stringify(query)); }
[ "function", "handleQuery", "(", ")", "{", "let", "query", "=", "parseQuery", "(", ")", ";", "let", "url", "=", "window", ".", "location", ".", "protocol", "+", "'//'", "+", "window", ".", "location", ".", "hostname", "+", "':'", "+", "window", ".", "location", ".", "port", "+", "ELASTICSEARCH_INTERFACE_ROUTE", ";", "let", "httpRequest", "=", "new", "XMLHttpRequest", "(", ")", ";", "httpRequest", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "httpRequest", ".", "readyState", "===", "XMLHttpRequest", ".", "DONE", ")", "{", "if", "(", "httpRequest", ".", "status", "===", "200", ")", "{", "let", "response", "=", "JSON", ".", "parse", "(", "httpRequest", ".", "responseText", ")", ";", "updateResults", "(", "response", ")", ";", "updateHits", "(", "response", ")", ";", "updateAggregations", "(", "response", ")", ";", "show", "(", "queryResults", ")", ";", "}", "else", "{", "queryError", ".", "textContent", "=", "'Query returned status '", "+", "httpRequest", ".", "status", "+", "'. Is Elasticsearch connected and running?'", ";", "hide", "(", "queryResults", ")", ";", "hide", "(", "queryButton", ")", ";", "show", "(", "queryError", ")", ";", "}", "}", "}", ";", "httpRequest", ".", "open", "(", "'POST'", ",", "url", ")", ";", "httpRequest", ".", "setRequestHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "httpRequest", ".", "setRequestHeader", "(", "'Accept'", ",", "'application/json'", ")", ";", "httpRequest", ".", "send", "(", "JSON", ".", "stringify", "(", "query", ")", ")", ";", "}" ]
Handle the current Elasticsearch query
[ "Handle", "the", "current", "Elasticsearch", "query" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-elasticsearch/js/hello-elasticsearch.js#L160-L189
train
reelyactive/hlc-server
web/apps/hello-elasticsearch/js/hello-elasticsearch.js
updateResults
function updateResults(response) { responseHits.textContent = response.hits.total; responseTime.textContent = response.took; }
javascript
function updateResults(response) { responseHits.textContent = response.hits.total; responseTime.textContent = response.took; }
[ "function", "updateResults", "(", "response", ")", "{", "responseHits", ".", "textContent", "=", "response", ".", "hits", ".", "total", ";", "responseTime", ".", "textContent", "=", "response", ".", "took", ";", "}" ]
Update the results
[ "Update", "the", "results" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-elasticsearch/js/hello-elasticsearch.js#L192-L195
train
reelyactive/hlc-server
web/apps/hello-elasticsearch/js/hello-elasticsearch.js
updateHits
function updateHits(response) { if(!response.hits.hasOwnProperty('hits') || (response.hits.hits.length === 0)) { hide(hitsCard); } else { show(hitsCard); hitsBox.textContent = JSON.stringify(response.hits.hits, null, 2); } }
javascript
function updateHits(response) { if(!response.hits.hasOwnProperty('hits') || (response.hits.hits.length === 0)) { hide(hitsCard); } else { show(hitsCard); hitsBox.textContent = JSON.stringify(response.hits.hits, null, 2); } }
[ "function", "updateHits", "(", "response", ")", "{", "if", "(", "!", "response", ".", "hits", ".", "hasOwnProperty", "(", "'hits'", ")", "||", "(", "response", ".", "hits", ".", "hits", ".", "length", "===", "0", ")", ")", "{", "hide", "(", "hitsCard", ")", ";", "}", "else", "{", "show", "(", "hitsCard", ")", ";", "hitsBox", ".", "textContent", "=", "JSON", ".", "stringify", "(", "response", ".", "hits", ".", "hits", ",", "null", ",", "2", ")", ";", "}", "}" ]
Update the hits
[ "Update", "the", "hits" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-elasticsearch/js/hello-elasticsearch.js#L198-L207
train
reelyactive/hlc-server
web/apps/hello-elasticsearch/js/hello-elasticsearch.js
updateAggregations
function updateAggregations(response) { if(response.hasOwnProperty('aggregations')) { aggregationsBox.textContent = JSON.stringify(response.aggregations, null, 2); show(aggregationsCard); } else { hide(aggregationsCard); } }
javascript
function updateAggregations(response) { if(response.hasOwnProperty('aggregations')) { aggregationsBox.textContent = JSON.stringify(response.aggregations, null, 2); show(aggregationsCard); } else { hide(aggregationsCard); } }
[ "function", "updateAggregations", "(", "response", ")", "{", "if", "(", "response", ".", "hasOwnProperty", "(", "'aggregations'", ")", ")", "{", "aggregationsBox", ".", "textContent", "=", "JSON", ".", "stringify", "(", "response", ".", "aggregations", ",", "null", ",", "2", ")", ";", "show", "(", "aggregationsCard", ")", ";", "}", "else", "{", "hide", "(", "aggregationsCard", ")", ";", "}", "}" ]
Update the aggregations
[ "Update", "the", "aggregations" ]
6e20593440557264449d67ce0edf5c3f6aefb81e
https://github.com/reelyactive/hlc-server/blob/6e20593440557264449d67ce0edf5c3f6aefb81e/web/apps/hello-elasticsearch/js/hello-elasticsearch.js#L210-L219
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
implodeArray
function implodeArray(tokens) { var message = "", i, l; l = tokens.length; for (i = 0; i < l; i++) { message += (i > 0 ? globals.SEP : "") + tokens[i]; } return message; }
javascript
function implodeArray(tokens) { var message = "", i, l; l = tokens.length; for (i = 0; i < l; i++) { message += (i > 0 ? globals.SEP : "") + tokens[i]; } return message; }
[ "function", "implodeArray", "(", "tokens", ")", "{", "var", "message", "=", "\"\"", ",", "i", ",", "l", ";", "l", "=", "tokens", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "message", "+=", "(", "i", ">", "0", "?", "globals", ".", "SEP", ":", "\"\"", ")", "+", "tokens", "[", "i", "]", ";", "}", "return", "message", ";", "}" ]
Concatenates the array in a pipe-delimited string @param {Array} tokens to be concatenated @return {String} the pipe-delimited string @private
[ "Concatenates", "the", "array", "in", "a", "pipe", "-", "delimited", "string" ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L41-L48
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
implodeData
function implodeData(data) { var dataArray = [], field; for(field in data) { dataArray.push(types.STRING); dataArray.push(encodeString(field)); dataArray.push(types.STRING); dataArray.push(encodeString(data[field])); } return implodeArray(dataArray); }
javascript
function implodeData(data) { var dataArray = [], field; for(field in data) { dataArray.push(types.STRING); dataArray.push(encodeString(field)); dataArray.push(types.STRING); dataArray.push(encodeString(data[field])); } return implodeArray(dataArray); }
[ "function", "implodeData", "(", "data", ")", "{", "var", "dataArray", "=", "[", "]", ",", "field", ";", "for", "(", "field", "in", "data", ")", "{", "dataArray", ".", "push", "(", "types", ".", "STRING", ")", ";", "dataArray", ".", "push", "(", "encodeString", "(", "field", ")", ")", ";", "dataArray", ".", "push", "(", "types", ".", "STRING", ")", ";", "dataArray", ".", "push", "(", "encodeString", "(", "data", "[", "field", "]", ")", ")", ";", "}", "return", "implodeArray", "(", "dataArray", ")", ";", "}" ]
Concatenates the associative array in a pipe-delimited string in the following form FIELD_TYPE_STRING|key|FIELD_TYPE_STRING|value. Values are encoded as strings. @param {Array} data an associative array @return {String} the pipe-delimited string @private
[ "Concatenates", "the", "associative", "array", "in", "a", "pipe", "-", "delimited", "string", "in", "the", "following", "form", "FIELD_TYPE_STRING|key|FIELD_TYPE_STRING|value", ".", "Values", "are", "encoded", "as", "strings", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L59-L68
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
implodeDataArray
function implodeDataArray(data) { var dataArray = [], i, l; l = data.length; for(i = 0; i < l; i++) { dataArray.push(types.STRING); dataArray.push(encodeString(data[i])); } return implodeArray(dataArray); }
javascript
function implodeDataArray(data) { var dataArray = [], i, l; l = data.length; for(i = 0; i < l; i++) { dataArray.push(types.STRING); dataArray.push(encodeString(data[i])); } return implodeArray(dataArray); }
[ "function", "implodeDataArray", "(", "data", ")", "{", "var", "dataArray", "=", "[", "]", ",", "i", ",", "l", ";", "l", "=", "data", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "dataArray", ".", "push", "(", "types", ".", "STRING", ")", ";", "dataArray", ".", "push", "(", "encodeString", "(", "data", "[", "i", "]", ")", ")", ";", "}", "return", "implodeArray", "(", "dataArray", ")", ";", "}" ]
Concatenates the array values in a pipe-delimited string in the following form FIELD_TYPE_STRING|value. Values are encoded as strings. @param {Array} data fields to be encoded @return {String} the pipe-delimited string @private
[ "Concatenates", "the", "array", "values", "in", "a", "pipe", "-", "delimited", "string", "in", "the", "following", "form", "FIELD_TYPE_STRING|value", ".", "Values", "are", "encoded", "as", "strings", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L79-L87
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
encodeString
function encodeString(string) { //it actually accepts any kind of object as input if (string === null) { return values.NULL; } else if (string === "") { return values.EMPTY; } else {//0 false undefined NaN will pass from here return encodeURIComponent(string) .replace(/%20/g, "+"); } }
javascript
function encodeString(string) { //it actually accepts any kind of object as input if (string === null) { return values.NULL; } else if (string === "") { return values.EMPTY; } else {//0 false undefined NaN will pass from here return encodeURIComponent(string) .replace(/%20/g, "+"); } }
[ "function", "encodeString", "(", "string", ")", "{", "if", "(", "string", "===", "null", ")", "{", "return", "values", ".", "NULL", ";", "}", "else", "if", "(", "string", "===", "\"\"", ")", "{", "return", "values", ".", "EMPTY", ";", "}", "else", "{", "return", "encodeURIComponent", "(", "string", ")", ".", "replace", "(", "/", "%20", "/", "g", ",", "\"+\"", ")", ";", "}", "}" ]
Encodes a string according to the ARI protocol. @param {String} string input @return {String} output @private
[ "Encodes", "a", "string", "according", "to", "the", "ARI", "protocol", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L168-L178
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
decodeString
function decodeString (string) { if (string === values.EMPTY) { return ""; } else if (string === values.NULL) { return null; } else { return decodeURIComponent( string.replace(/\+/g,"%20")); } }
javascript
function decodeString (string) { if (string === values.EMPTY) { return ""; } else if (string === values.NULL) { return null; } else { return decodeURIComponent( string.replace(/\+/g,"%20")); } }
[ "function", "decodeString", "(", "string", ")", "{", "if", "(", "string", "===", "values", ".", "EMPTY", ")", "{", "return", "\"\"", ";", "}", "else", "if", "(", "string", "===", "values", ".", "NULL", ")", "{", "return", "null", ";", "}", "else", "{", "return", "decodeURIComponent", "(", "string", ".", "replace", "(", "/", "\\+", "/", "g", ",", "\"%20\"", ")", ")", ";", "}", "}" ]
Decodes a string according to the ARI protocol. @param {String} string input @return {String} output @private
[ "Decodes", "a", "string", "according", "to", "the", "ARI", "protocol", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L187-L196
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
encodeInteger
function encodeInteger(value) { if (value === null) { return values.NULL; } else if (!isNaN(value) && parseInt(value)==value) { return value + ""; } else { throw new Error('Invalid integer value "' + value + '"'); } }
javascript
function encodeInteger(value) { if (value === null) { return values.NULL; } else if (!isNaN(value) && parseInt(value)==value) { return value + ""; } else { throw new Error('Invalid integer value "' + value + '"'); } }
[ "function", "encodeInteger", "(", "value", ")", "{", "if", "(", "value", "===", "null", ")", "{", "return", "values", ".", "NULL", ";", "}", "else", "if", "(", "!", "isNaN", "(", "value", ")", "&&", "parseInt", "(", "value", ")", "==", "value", ")", "{", "return", "value", "+", "\"\"", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid integer value \"'", "+", "value", "+", "'\"'", ")", ";", "}", "}" ]
Encodes an integer according to the ARI protocol. @param {Number} value input @return {String} output @private
[ "Encodes", "an", "integer", "according", "to", "the", "ARI", "protocol", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L220-L228
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
encodeDouble
function encodeDouble(value) { if (value === null) { return values.NULL; } else if (!isNaN(value)) { return value + ""; } else { throw new Error('Invalid double value "' + value + '"'); } }
javascript
function encodeDouble(value) { if (value === null) { return values.NULL; } else if (!isNaN(value)) { return value + ""; } else { throw new Error('Invalid double value "' + value + '"'); } }
[ "function", "encodeDouble", "(", "value", ")", "{", "if", "(", "value", "===", "null", ")", "{", "return", "values", ".", "NULL", ";", "}", "else", "if", "(", "!", "isNaN", "(", "value", ")", ")", "{", "return", "value", "+", "\"\"", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid double value \"'", "+", "value", "+", "'\"'", ")", ";", "}", "}" ]
Encodes a float according to the ARI protocol. @param {Number} value input @return {String} output @private
[ "Encodes", "a", "float", "according", "to", "the", "ARI", "protocol", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L237-L245
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
encodeMetadataException
function encodeMetadataException(type) { if (type === "metadata") { return exceptions.METADATA; } else if (type === "access") { return exceptions.ACCESS; } else if (type === "credits") { return exceptions.CREDITS; } else if (type === "conflictingSession") { return exceptions.CONFLICTING_SESSION; } else if (type === "items") { return exceptions.ITEMS; } else if (type === "schema") { return exceptions.SCHEMA; } else if (type === "notification") { return exceptions.NOTIFICATION; } else { return exceptions.GENERIC; } }
javascript
function encodeMetadataException(type) { if (type === "metadata") { return exceptions.METADATA; } else if (type === "access") { return exceptions.ACCESS; } else if (type === "credits") { return exceptions.CREDITS; } else if (type === "conflictingSession") { return exceptions.CONFLICTING_SESSION; } else if (type === "items") { return exceptions.ITEMS; } else if (type === "schema") { return exceptions.SCHEMA; } else if (type === "notification") { return exceptions.NOTIFICATION; } else { return exceptions.GENERIC; } }
[ "function", "encodeMetadataException", "(", "type", ")", "{", "if", "(", "type", "===", "\"metadata\"", ")", "{", "return", "exceptions", ".", "METADATA", ";", "}", "else", "if", "(", "type", "===", "\"access\"", ")", "{", "return", "exceptions", ".", "ACCESS", ";", "}", "else", "if", "(", "type", "===", "\"credits\"", ")", "{", "return", "exceptions", ".", "CREDITS", ";", "}", "else", "if", "(", "type", "===", "\"conflictingSession\"", ")", "{", "return", "exceptions", ".", "CONFLICTING_SESSION", ";", "}", "else", "if", "(", "type", "===", "\"items\"", ")", "{", "return", "exceptions", ".", "ITEMS", ";", "}", "else", "if", "(", "type", "===", "\"schema\"", ")", "{", "return", "exceptions", ".", "SCHEMA", ";", "}", "else", "if", "(", "type", "===", "\"notification\"", ")", "{", "return", "exceptions", ".", "NOTIFICATION", ";", "}", "else", "{", "return", "exceptions", ".", "GENERIC", ";", "}", "}" ]
Encodes a metadata exception type. @param {Boolean} type input @return {String} output @private
[ "Encodes", "a", "metadata", "exception", "type", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L265-L283
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/protocol.js
parse
function parse(data, initExpected) { var lines, i, last; data = tail + data; data = data.replace(/\r*\n+/g, "\n"); lines = data.split("\n"); last = lines.length - 1; for (i = 0; i < last; i++) { messages.push(read(lines[i], initExpected)); } tail = lines[lines.length - 1]; }
javascript
function parse(data, initExpected) { var lines, i, last; data = tail + data; data = data.replace(/\r*\n+/g, "\n"); lines = data.split("\n"); last = lines.length - 1; for (i = 0; i < last; i++) { messages.push(read(lines[i], initExpected)); } tail = lines[lines.length - 1]; }
[ "function", "parse", "(", "data", ",", "initExpected", ")", "{", "var", "lines", ",", "i", ",", "last", ";", "data", "=", "tail", "+", "data", ";", "data", "=", "data", ".", "replace", "(", "/", "\\r*\\n+", "/", "g", ",", "\"\\n\"", ")", ";", "\\n", "lines", "=", "data", ".", "split", "(", "\"\\n\"", ")", ";", "\\n", "last", "=", "lines", ".", "length", "-", "1", ";", "}" ]
Parsa new data. @param {String} data New data from the stream
[ "Parsa", "new", "data", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/protocol.js#L310-L320
train
clux/modul8
lib/bundler.js
bundleApp
function bundleApp(codeList, ns, domload, compile, before, npmTree, o) { var l = [] , usedBuiltIns = npmTree._builtIns , len = 0; delete npmTree._builtIns; // 1. construct the global namespace object l.push("window." + ns + " = {data:{}, path:{}};"); // 2. attach path code to the namespace object so that require.js can efficiently resolve paths l.push('\n// include npm::path'); var pathCode = read(join(builtInDir, 'path.posix.js')); l.push('(function (exports) {\n ' + pathCode + '\n}(window.' + ns + '.path));'); // 3. pull in serialized data Object.keys(o.data).forEach(function (name) { return l.push(ns + ".data." + name + " = " + o.data[name] + ";"); }); // 4. attach require code var config = { namespace : ns , domains : Object.keys(o.domains) // TODO: remove npm from here , arbiters : o.arbiters , logging : o.logLevel , npmTree : npmTree , builtIns : builtIns , slash : '/' //TODO: figure out if different types can coexist, if so, determine in resolver, and on client }; l.push(anonWrap(read(join(dir, 'require.js')) .replace(/VERSION/, JSON.parse(read(join(dir, '..', 'package.json'))).version) .replace(/REQUIRECONFIG/, JSON.stringify(config)) )); // 5. include CommonJS compatible code in the order they have to be defined var defineWrap = function (exportName, domain, code) { return ns + ".define('" + exportName + "','" + domain + "',function (require, module, exports) {\n" + code + "\n});"; }; // 6. harvest function splits code into app and non-app code and defineWraps var harvest = function (onlyMain) { codeList.forEach(function (pair) { var dom = pair[0] , file = pair[1] , basename = file.split('.')[0]; if ((dom === 'app') !== onlyMain) { return; } var code = before(compile(join(o.domains[dom], file))); l.push(defineWrap(basename, dom, code)); }); }; // 7.a) include required builtIns l.push("\n// node builtins\n"); len = l.length; usedBuiltIns.forEach(function (b) { if (b === 'path') { // already included return; } l.push(defineWrap(b, 'npm', read(join(builtInDir, b + '.js')))); }); if (l.length === len) { l.pop(); } // 7.b) include modules not on the app domain l.push("\n// shared code\n"); len = l.length; harvest(false); if (l.length === len) { l.pop(); } // 7.c) include modules on the app domain, and wait for domloader if set l.push("\n// app code - safety wrapped\n\n"); domload(harvest(true)); // 8. use a closure to encapsulate the private internal data and APIs return anonWrap(l.join('\n')); }
javascript
function bundleApp(codeList, ns, domload, compile, before, npmTree, o) { var l = [] , usedBuiltIns = npmTree._builtIns , len = 0; delete npmTree._builtIns; // 1. construct the global namespace object l.push("window." + ns + " = {data:{}, path:{}};"); // 2. attach path code to the namespace object so that require.js can efficiently resolve paths l.push('\n// include npm::path'); var pathCode = read(join(builtInDir, 'path.posix.js')); l.push('(function (exports) {\n ' + pathCode + '\n}(window.' + ns + '.path));'); // 3. pull in serialized data Object.keys(o.data).forEach(function (name) { return l.push(ns + ".data." + name + " = " + o.data[name] + ";"); }); // 4. attach require code var config = { namespace : ns , domains : Object.keys(o.domains) // TODO: remove npm from here , arbiters : o.arbiters , logging : o.logLevel , npmTree : npmTree , builtIns : builtIns , slash : '/' //TODO: figure out if different types can coexist, if so, determine in resolver, and on client }; l.push(anonWrap(read(join(dir, 'require.js')) .replace(/VERSION/, JSON.parse(read(join(dir, '..', 'package.json'))).version) .replace(/REQUIRECONFIG/, JSON.stringify(config)) )); // 5. include CommonJS compatible code in the order they have to be defined var defineWrap = function (exportName, domain, code) { return ns + ".define('" + exportName + "','" + domain + "',function (require, module, exports) {\n" + code + "\n});"; }; // 6. harvest function splits code into app and non-app code and defineWraps var harvest = function (onlyMain) { codeList.forEach(function (pair) { var dom = pair[0] , file = pair[1] , basename = file.split('.')[0]; if ((dom === 'app') !== onlyMain) { return; } var code = before(compile(join(o.domains[dom], file))); l.push(defineWrap(basename, dom, code)); }); }; // 7.a) include required builtIns l.push("\n// node builtins\n"); len = l.length; usedBuiltIns.forEach(function (b) { if (b === 'path') { // already included return; } l.push(defineWrap(b, 'npm', read(join(builtInDir, b + '.js')))); }); if (l.length === len) { l.pop(); } // 7.b) include modules not on the app domain l.push("\n// shared code\n"); len = l.length; harvest(false); if (l.length === len) { l.pop(); } // 7.c) include modules on the app domain, and wait for domloader if set l.push("\n// app code - safety wrapped\n\n"); domload(harvest(true)); // 8. use a closure to encapsulate the private internal data and APIs return anonWrap(l.join('\n')); }
[ "function", "bundleApp", "(", "codeList", ",", "ns", ",", "domload", ",", "compile", ",", "before", ",", "npmTree", ",", "o", ")", "{", "var", "l", "=", "[", "]", ",", "usedBuiltIns", "=", "npmTree", ".", "_builtIns", ",", "len", "=", "0", ";", "delete", "npmTree", ".", "_builtIns", ";", "l", ".", "push", "(", "\"window.\"", "+", "ns", "+", "\" = {data:{}, path:{}};\"", ")", ";", "l", ".", "push", "(", "'\\n// include npm::path'", ")", ";", "\\n", "var", "pathCode", "=", "read", "(", "join", "(", "builtInDir", ",", "'path.posix.js'", ")", ")", ";", "l", ".", "push", "(", "'(function (exports) {\\n '", "+", "\\n", "+", "pathCode", "+", "'\\n}(window.'", "+", "\\n", ")", ";", "ns", "'.path));'", "Object", ".", "keys", "(", "o", ".", "data", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "return", "l", ".", "push", "(", "ns", "+", "\".data.\"", "+", "name", "+", "\" = \"", "+", "o", ".", "data", "[", "name", "]", "+", "\";\"", ")", ";", "}", ")", ";", "var", "config", "=", "{", "namespace", ":", "ns", ",", "domains", ":", "Object", ".", "keys", "(", "o", ".", "domains", ")", ",", "arbiters", ":", "o", ".", "arbiters", ",", "logging", ":", "o", ".", "logLevel", ",", "npmTree", ":", "npmTree", ",", "builtIns", ":", "builtIns", ",", "slash", ":", "'/'", "}", ";", "l", ".", "push", "(", "anonWrap", "(", "read", "(", "join", "(", "dir", ",", "'require.js'", ")", ")", ".", "replace", "(", "/", "VERSION", "/", ",", "JSON", ".", "parse", "(", "read", "(", "join", "(", "dir", ",", "'..'", ",", "'package.json'", ")", ")", ")", ".", "version", ")", ".", "replace", "(", "/", "REQUIRECONFIG", "/", ",", "JSON", ".", "stringify", "(", "config", ")", ")", ")", ")", ";", "var", "defineWrap", "=", "function", "(", "exportName", ",", "domain", ",", "code", ")", "{", "return", "ns", "+", "\".define('\"", "+", "exportName", "+", "\"','\"", "+", "domain", "+", "\"',function (require, module, exports) {\\n\"", "+", "\\n", "+", "code", ";", "}", ";", "\"\\n});\"", "\\n", "var", "harvest", "=", "function", "(", "onlyMain", ")", "{", "codeList", ".", "forEach", "(", "function", "(", "pair", ")", "{", "var", "dom", "=", "pair", "[", "0", "]", ",", "file", "=", "pair", "[", "1", "]", ",", "basename", "=", "file", ".", "split", "(", "'.'", ")", "[", "0", "]", ";", "if", "(", "(", "dom", "===", "'app'", ")", "!==", "onlyMain", ")", "{", "return", ";", "}", "var", "code", "=", "before", "(", "compile", "(", "join", "(", "o", ".", "domains", "[", "dom", "]", ",", "file", ")", ")", ")", ";", "l", ".", "push", "(", "defineWrap", "(", "basename", ",", "dom", ",", "code", ")", ")", ";", "}", ")", ";", "}", ";", "l", ".", "push", "(", "\"\\n// node builtins\\n\"", ")", ";", "\\n", "\\n", "len", "=", "l", ".", "length", ";", "usedBuiltIns", ".", "forEach", "(", "function", "(", "b", ")", "{", "if", "(", "b", "===", "'path'", ")", "{", "return", ";", "}", "l", ".", "push", "(", "defineWrap", "(", "b", ",", "'npm'", ",", "read", "(", "join", "(", "builtInDir", ",", "b", "+", "'.js'", ")", ")", ")", ")", ";", "}", ")", ";", "if", "(", "l", ".", "length", "===", "len", ")", "{", "l", ".", "pop", "(", ")", ";", "}", "}" ]
main application packager
[ "main", "application", "packager" ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/lib/bundler.js#L58-L139
train
clux/modul8
lib/bundler.js
function (onlyMain) { codeList.forEach(function (pair) { var dom = pair[0] , file = pair[1] , basename = file.split('.')[0]; if ((dom === 'app') !== onlyMain) { return; } var code = before(compile(join(o.domains[dom], file))); l.push(defineWrap(basename, dom, code)); }); }
javascript
function (onlyMain) { codeList.forEach(function (pair) { var dom = pair[0] , file = pair[1] , basename = file.split('.')[0]; if ((dom === 'app') !== onlyMain) { return; } var code = before(compile(join(o.domains[dom], file))); l.push(defineWrap(basename, dom, code)); }); }
[ "function", "(", "onlyMain", ")", "{", "codeList", ".", "forEach", "(", "function", "(", "pair", ")", "{", "var", "dom", "=", "pair", "[", "0", "]", ",", "file", "=", "pair", "[", "1", "]", ",", "basename", "=", "file", ".", "split", "(", "'.'", ")", "[", "0", "]", ";", "if", "(", "(", "dom", "===", "'app'", ")", "!==", "onlyMain", ")", "{", "return", ";", "}", "var", "code", "=", "before", "(", "compile", "(", "join", "(", "o", ".", "domains", "[", "dom", "]", ",", "file", ")", ")", ")", ";", "l", ".", "push", "(", "defineWrap", "(", "basename", ",", "dom", ",", "code", ")", ")", ";", "}", ")", ";", "}" ]
6. harvest function splits code into app and non-app code and defineWraps
[ "6", ".", "harvest", "function", "splits", "code", "into", "app", "and", "non", "-", "app", "code", "and", "defineWraps" ]
dd2809a5de14ec339660c584b0c0ec8309be2097
https://github.com/clux/modul8/blob/dd2809a5de14ec339660c584b0c0ec8309be2097/lib/bundler.js#L99-L110
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
subscribe
function subscribe(message) { reply(proto.writeSubscribe(message.id)); subscritions[message.itemName] = message.id; if (!isSnapshotAvailable(message.itemName)) { notify(proto.writeEndOfSnapshot(message.id, message.itemName)); } dequeueSubUnsubRequest(message.itemName); fireFirstSubUnsubEvent(message.itemName); }
javascript
function subscribe(message) { reply(proto.writeSubscribe(message.id)); subscritions[message.itemName] = message.id; if (!isSnapshotAvailable(message.itemName)) { notify(proto.writeEndOfSnapshot(message.id, message.itemName)); } dequeueSubUnsubRequest(message.itemName); fireFirstSubUnsubEvent(message.itemName); }
[ "function", "subscribe", "(", "message", ")", "{", "reply", "(", "proto", ".", "writeSubscribe", "(", "message", ".", "id", ")", ")", ";", "subscritions", "[", "message", ".", "itemName", "]", "=", "message", ".", "id", ";", "if", "(", "!", "isSnapshotAvailable", "(", "message", ".", "itemName", ")", ")", "{", "notify", "(", "proto", ".", "writeEndOfSnapshot", "(", "message", ".", "id", ",", "message", ".", "itemName", ")", ")", ";", "}", "dequeueSubUnsubRequest", "(", "message", ".", "itemName", ")", ";", "fireFirstSubUnsubEvent", "(", "message", ".", "itemName", ")", ";", "}" ]
Sends a subscribe reply @param {Object} message the decoded request message @private
[ "Sends", "a", "subscribe", "reply" ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L125-L133
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
subscribeError
function subscribeError(message, exceptionMessage, exceptionType) { reply(proto.writeSubscribeException( message.id, exceptionMessage, exceptionType)); dequeueSubUnsubRequest(message.itemName); fireFirstSubUnsubEvent(message.itemName); }
javascript
function subscribeError(message, exceptionMessage, exceptionType) { reply(proto.writeSubscribeException( message.id, exceptionMessage, exceptionType)); dequeueSubUnsubRequest(message.itemName); fireFirstSubUnsubEvent(message.itemName); }
[ "function", "subscribeError", "(", "message", ",", "exceptionMessage", ",", "exceptionType", ")", "{", "reply", "(", "proto", ".", "writeSubscribeException", "(", "message", ".", "id", ",", "exceptionMessage", ",", "exceptionType", ")", ")", ";", "dequeueSubUnsubRequest", "(", "message", ".", "itemName", ")", ";", "fireFirstSubUnsubEvent", "(", "message", ".", "itemName", ")", ";", "}" ]
Sends a subscribe error reply @param {Object} message the decoded request message @private
[ "Sends", "a", "subscribe", "error", "reply" ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L141-L146
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
unsubscribe
function unsubscribe(message) { reply(proto.writeUnsubscribe(message.id)); subscritions[message.itemName] = undefined; dequeueSubUnsubRequest(message.itemName); handleLateSubUnsubRequests(message.itemName); fireFirstSubUnsubEvent(message.itemName); }
javascript
function unsubscribe(message) { reply(proto.writeUnsubscribe(message.id)); subscritions[message.itemName] = undefined; dequeueSubUnsubRequest(message.itemName); handleLateSubUnsubRequests(message.itemName); fireFirstSubUnsubEvent(message.itemName); }
[ "function", "unsubscribe", "(", "message", ")", "{", "reply", "(", "proto", ".", "writeUnsubscribe", "(", "message", ".", "id", ")", ")", ";", "subscritions", "[", "message", ".", "itemName", "]", "=", "undefined", ";", "dequeueSubUnsubRequest", "(", "message", ".", "itemName", ")", ";", "handleLateSubUnsubRequests", "(", "message", ".", "itemName", ")", ";", "fireFirstSubUnsubEvent", "(", "message", ".", "itemName", ")", ";", "}" ]
Sends an unsubscribe reply @param {Object} message the decoded request message @private
[ "Sends", "an", "unsubscribe", "reply" ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L154-L160
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
unsubscribeError
function unsubscribeError(message, exceptionMessage, exceptionType) { reply(proto.writeUnsubscribeException( message.id, exceptionMessage, exceptionType)); dequeueSubUnsubRequest(message.itemName); fireFirstSubUnsubEvent(message.itemName); }
javascript
function unsubscribeError(message, exceptionMessage, exceptionType) { reply(proto.writeUnsubscribeException( message.id, exceptionMessage, exceptionType)); dequeueSubUnsubRequest(message.itemName); fireFirstSubUnsubEvent(message.itemName); }
[ "function", "unsubscribeError", "(", "message", ",", "exceptionMessage", ",", "exceptionType", ")", "{", "reply", "(", "proto", ".", "writeUnsubscribeException", "(", "message", ".", "id", ",", "exceptionMessage", ",", "exceptionType", ")", ")", ";", "dequeueSubUnsubRequest", "(", "message", ".", "itemName", ")", ";", "fireFirstSubUnsubEvent", "(", "message", ".", "itemName", ")", ";", "}" ]
Sends an unsubscribe error reply @param {Object} message the decoded request message @private
[ "Sends", "an", "unsubscribe", "error", "reply" ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L168-L173
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
fireFirstSubUnsubEvent
function fireFirstSubUnsubEvent(itemName) { if (subUnsubQueue[itemName].length > 0) { request = subUnsubQueue[itemName][0]; that.emit(request.message.verb, itemName, request.response); } }
javascript
function fireFirstSubUnsubEvent(itemName) { if (subUnsubQueue[itemName].length > 0) { request = subUnsubQueue[itemName][0]; that.emit(request.message.verb, itemName, request.response); } }
[ "function", "fireFirstSubUnsubEvent", "(", "itemName", ")", "{", "if", "(", "subUnsubQueue", "[", "itemName", "]", ".", "length", ">", "0", ")", "{", "request", "=", "subUnsubQueue", "[", "itemName", "]", "[", "0", "]", ";", "that", ".", "emit", "(", "request", ".", "message", ".", "verb", ",", "itemName", ",", "request", ".", "response", ")", ";", "}", "}" ]
Fire the first event in the queue @param {String} itemName the item name @private
[ "Fire", "the", "first", "event", "in", "the", "queue" ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L206-L211
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
function(message) { if (that.listeners(message.verb).length) { var successHandler = function(msg) { reply(proto.writeInit(msg.id)); }; var errorHandler = function(msg, exceptionMessage, exceptionType) { reply(proto.writeInitException(msg.id, exceptionMessage, exceptionType)); }; var response = new DataResponse(message, successHandler, errorHandler); that.emit("init", message, response); } else { reply(proto.writeInit(message.id)); } }
javascript
function(message) { if (that.listeners(message.verb).length) { var successHandler = function(msg) { reply(proto.writeInit(msg.id)); }; var errorHandler = function(msg, exceptionMessage, exceptionType) { reply(proto.writeInitException(msg.id, exceptionMessage, exceptionType)); }; var response = new DataResponse(message, successHandler, errorHandler); that.emit("init", message, response); } else { reply(proto.writeInit(message.id)); } }
[ "function", "(", "message", ")", "{", "if", "(", "that", ".", "listeners", "(", "message", ".", "verb", ")", ".", "length", ")", "{", "var", "successHandler", "=", "function", "(", "msg", ")", "{", "reply", "(", "proto", ".", "writeInit", "(", "msg", ".", "id", ")", ")", ";", "}", ";", "var", "errorHandler", "=", "function", "(", "msg", ",", "exceptionMessage", ",", "exceptionType", ")", "{", "reply", "(", "proto", ".", "writeInitException", "(", "msg", ".", "id", ",", "exceptionMessage", ",", "exceptionType", ")", ")", ";", "}", ";", "var", "response", "=", "new", "DataResponse", "(", "message", ",", "successHandler", ",", "errorHandler", ")", ";", "that", ".", "emit", "(", "\"init\"", ",", "message", ",", "response", ")", ";", "}", "else", "{", "reply", "(", "proto", ".", "writeInit", "(", "message", ".", "id", ")", ")", ";", "}", "}" ]
Handles an initialization request creating a DataResponse Object and emitting the subscribe event. If the handler is not defined, just writes an ack response. @param {Object} message the incoming request associative array @private
[ "Handles", "an", "initialization", "request", "creating", "a", "DataResponse", "Object", "and", "emitting", "the", "subscribe", "event", ".", "If", "the", "handler", "is", "not", "defined", "just", "writes", "an", "ack", "response", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L245-L258
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
function(message) { var response = new DataResponse(message, subscribe, subscribeError); if (queueSubUnsubRequest(message, response) === 1) { fireFirstSubUnsubEvent(message.itemName); } else { that.emit("subscribeInQueue", message.itemName); } }
javascript
function(message) { var response = new DataResponse(message, subscribe, subscribeError); if (queueSubUnsubRequest(message, response) === 1) { fireFirstSubUnsubEvent(message.itemName); } else { that.emit("subscribeInQueue", message.itemName); } }
[ "function", "(", "message", ")", "{", "var", "response", "=", "new", "DataResponse", "(", "message", ",", "subscribe", ",", "subscribeError", ")", ";", "if", "(", "queueSubUnsubRequest", "(", "message", ",", "response", ")", "===", "1", ")", "{", "fireFirstSubUnsubEvent", "(", "message", ".", "itemName", ")", ";", "}", "else", "{", "that", ".", "emit", "(", "\"subscribeInQueue\"", ",", "message", ".", "itemName", ")", ";", "}", "}" ]
Handles a subscribe request creating a DataResponse Object and emitting the subscribe event. @param {Object} message the incoming request associative array @private
[ "Handles", "a", "subscribe", "request", "creating", "a", "DataResponse", "Object", "and", "emitting", "the", "subscribe", "event", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L266-L273
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
function(message) { var response = new DataResponse(message, unsubscribe, unsubscribeError); if (queueSubUnsubRequest(message, response) === 1) { fireFirstSubUnsubEvent(message.itemName); } else { that.emit("unsubscribeInQueue", message.itemName); } }
javascript
function(message) { var response = new DataResponse(message, unsubscribe, unsubscribeError); if (queueSubUnsubRequest(message, response) === 1) { fireFirstSubUnsubEvent(message.itemName); } else { that.emit("unsubscribeInQueue", message.itemName); } }
[ "function", "(", "message", ")", "{", "var", "response", "=", "new", "DataResponse", "(", "message", ",", "unsubscribe", ",", "unsubscribeError", ")", ";", "if", "(", "queueSubUnsubRequest", "(", "message", ",", "response", ")", "===", "1", ")", "{", "fireFirstSubUnsubEvent", "(", "message", ".", "itemName", ")", ";", "}", "else", "{", "that", ".", "emit", "(", "\"unsubscribeInQueue\"", ",", "message", ".", "itemName", ")", ";", "}", "}" ]
Handles an unsubscribe request creating a DataResponse Object and emitting the unsubscribe event. @param {Object} message the incoming request associative array @private
[ "Handles", "an", "unsubscribe", "request", "creating", "a", "DataResponse", "Object", "and", "emitting", "the", "unsubscribe", "event", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L281-L288
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
update
function update(itemName, isSnapshot, data) { var message, id = getIdFromItemName(itemName); message = proto.writeUpdate(id, itemName, isSnapshot, data); notify(message); return that; }
javascript
function update(itemName, isSnapshot, data) { var message, id = getIdFromItemName(itemName); message = proto.writeUpdate(id, itemName, isSnapshot, data); notify(message); return that; }
[ "function", "update", "(", "itemName", ",", "isSnapshot", ",", "data", ")", "{", "var", "message", ",", "id", "=", "getIdFromItemName", "(", "itemName", ")", ";", "message", "=", "proto", ".", "writeUpdate", "(", "id", ",", "itemName", ",", "isSnapshot", ",", "data", ")", ";", "notify", "(", "message", ")", ";", "return", "that", ";", "}" ]
Sends an update for a particular item to the remote LS proxy. @param {String} itemName the item name @param {Boolean} isSnapshot is it a snapshot? @param {Object} data an associative array of strings that represents the data to be published
[ "Sends", "an", "update", "for", "a", "particular", "item", "to", "the", "remote", "LS", "proxy", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L299-L304
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
endOfSnapshot
function endOfSnapshot(itemName) { var message, id = getIdFromItemName(itemName); message = proto.writeEndOfSnapshot(id, itemName); notify(message); return that; }
javascript
function endOfSnapshot(itemName) { var message, id = getIdFromItemName(itemName); message = proto.writeEndOfSnapshot(id, itemName); notify(message); return that; }
[ "function", "endOfSnapshot", "(", "itemName", ")", "{", "var", "message", ",", "id", "=", "getIdFromItemName", "(", "itemName", ")", ";", "message", "=", "proto", ".", "writeEndOfSnapshot", "(", "id", ",", "itemName", ")", ";", "notify", "(", "message", ")", ";", "return", "that", ";", "}" ]
Sends an end of snapshot message for a particular item to the remote LS proxy. @param {String} itemName the item name
[ "Sends", "an", "end", "of", "snapshot", "message", "for", "a", "particular", "item", "to", "the", "remote", "LS", "proxy", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L311-L316
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
clearSnapshot
function clearSnapshot(itemName) { var message, id = getIdFromItemName(itemName); message = proto.writeClearSnapshot(id, itemName); notify(message); return that; }
javascript
function clearSnapshot(itemName) { var message, id = getIdFromItemName(itemName); message = proto.writeClearSnapshot(id, itemName); notify(message); return that; }
[ "function", "clearSnapshot", "(", "itemName", ")", "{", "var", "message", ",", "id", "=", "getIdFromItemName", "(", "itemName", ")", ";", "message", "=", "proto", ".", "writeClearSnapshot", "(", "id", ",", "itemName", ")", ";", "notify", "(", "message", ")", ";", "return", "that", ";", "}" ]
Sends a clear snapshot message for a particular item to the remote LS proxy. @param {String} itemName the item name
[ "Sends", "a", "clear", "snapshot", "message", "for", "a", "particular", "item", "to", "the", "remote", "LS", "proxy", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L323-L328
train
Lightstreamer/Lightstreamer-lib-node-adapter
lib/dataprovider.js
failure
function failure(exception) { var message; message = proto.writeFailure(exception); notify(message); return that; }
javascript
function failure(exception) { var message; message = proto.writeFailure(exception); notify(message); return that; }
[ "function", "failure", "(", "exception", ")", "{", "var", "message", ";", "message", "=", "proto", ".", "writeFailure", "(", "exception", ")", ";", "notify", "(", "message", ")", ";", "return", "that", ";", "}" ]
Sends a failure message to the remote LS proxy. @param {String} exception the exception message
[ "Sends", "a", "failure", "message", "to", "the", "remote", "LS", "proxy", "." ]
5fa5dbf983e169b7b0204eaa360c0d1c446d9b00
https://github.com/Lightstreamer/Lightstreamer-lib-node-adapter/blob/5fa5dbf983e169b7b0204eaa360c0d1c446d9b00/lib/dataprovider.js#L335-L340
train
MeldCE/json-crud
src/spec/unit/common.js
function (array1, array2) { if (array1.length !== array2.length) { return false; } // Clone the second array array2 = array2.concat(); let i; for (i = 0; i < array1.length; i++) { let index = array2.indexOf(array1[i]); if (index === -1) { return false; } array2.splice(index, 1); } if (array2.length === 0) { return true; } return false; }
javascript
function (array1, array2) { if (array1.length !== array2.length) { return false; } // Clone the second array array2 = array2.concat(); let i; for (i = 0; i < array1.length; i++) { let index = array2.indexOf(array1[i]); if (index === -1) { return false; } array2.splice(index, 1); } if (array2.length === 0) { return true; } return false; }
[ "function", "(", "array1", ",", "array2", ")", "{", "if", "(", "array1", ".", "length", "!==", "array2", ".", "length", ")", "{", "return", "false", ";", "}", "array2", "=", "array2", ".", "concat", "(", ")", ";", "let", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "array1", ".", "length", ";", "i", "++", ")", "{", "let", "index", "=", "array2", ".", "indexOf", "(", "array1", "[", "i", "]", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "return", "false", ";", "}", "array2", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "if", "(", "array2", ".", "length", "===", "0", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if two arrays have the same values in them, not worrying about order @param array1 First array to check @param array2 Second array to check @returns {boolean} True is the arrays contain the same values
[ "Checks", "if", "two", "arrays", "have", "the", "same", "values", "in", "them", "not", "worrying", "about", "order" ]
524d0f95dc72b73db4c4571fc03a4d2b30676057
https://github.com/MeldCE/json-crud/blob/524d0f95dc72b73db4c4571fc03a4d2b30676057/src/spec/unit/common.js#L13-L38
train
jiahaog/Revenant
lib/actions.js
changeDropdownIndex
function changeDropdownIndex(page, ph, selectorAndIndex, callback) { page.evaluate(function (selectorAndIndex) { try { var selector = selectorAndIndex[0]; var index = selectorAndIndex[1]; var element = document.querySelector(selector); element.selectedIndex = index; // event is needed because listeners to the change do not react to // programmatic changes var event = document.createEvent('Event'); event.initEvent('change', true, false); element.dispatchEvent(event); return null; } catch (error) { return error; } }, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error, page, ph); return; } callback(null, page, ph); }, selectorAndIndex); }
javascript
function changeDropdownIndex(page, ph, selectorAndIndex, callback) { page.evaluate(function (selectorAndIndex) { try { var selector = selectorAndIndex[0]; var index = selectorAndIndex[1]; var element = document.querySelector(selector); element.selectedIndex = index; // event is needed because listeners to the change do not react to // programmatic changes var event = document.createEvent('Event'); event.initEvent('change', true, false); element.dispatchEvent(event); return null; } catch (error) { return error; } }, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error, page, ph); return; } callback(null, page, ph); }, selectorAndIndex); }
[ "function", "changeDropdownIndex", "(", "page", ",", "ph", ",", "selectorAndIndex", ",", "callback", ")", "{", "page", ".", "evaluate", "(", "function", "(", "selectorAndIndex", ")", "{", "try", "{", "var", "selector", "=", "selectorAndIndex", "[", "0", "]", ";", "var", "index", "=", "selectorAndIndex", "[", "1", "]", ";", "var", "element", "=", "document", ".", "querySelector", "(", "selector", ")", ";", "element", ".", "selectedIndex", "=", "index", ";", "var", "event", "=", "document", ".", "createEvent", "(", "'Event'", ")", ";", "event", ".", "initEvent", "(", "'change'", ",", "true", ",", "false", ")", ";", "element", ".", "dispatchEvent", "(", "event", ")", ";", "return", "null", ";", "}", "catch", "(", "error", ")", "{", "return", "error", ";", "}", "}", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "page", ",", "ph", ")", ";", "return", ";", "}", "callback", "(", "null", ",", "page", ",", "ph", ")", ";", "}", ",", "selectorAndIndex", ")", ";", "}" ]
Change the dropdown index of a dropdown box @param page @param ph @param {array} selectorAndIndex index 0 - selector index 1 - value @param {pageCallback} callback
[ "Change", "the", "dropdown", "index", "of", "a", "dropdown", "box" ]
562dd4e7a6bacb9c8b51c1344a5e336545177516
https://github.com/jiahaog/Revenant/blob/562dd4e7a6bacb9c8b51c1344a5e336545177516/lib/actions.js#L16-L42
train
jiahaog/Revenant
lib/actions.js
clickElement
function clickElement(page, ph, selectorAndOptions, callback) { var selector = selectorAndOptions[0]; var options = selectorAndOptions[1]; function clickSelector(selector) { try { var button = document.querySelector(selector); var ev = document.createEvent("MouseEvent"); ev.initMouseEvent( "click", true /* bubble */, true /* cancelable */, window, null, 0, 0, 0, 0, /* coordinates */ false, false, false, false, /* modifier keys */ 0 /*left*/, null ); button.dispatchEvent(ev); } catch (error) { return error } } var oldUrl; async.waterfall([ function (callback) { page.get('url', function (url) { oldUrl = url; callback(); }); }, function (callback) { page.evaluate(clickSelector, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error, page, ph); return; } checks.ajaxCallback(page, ph, oldUrl, options, callback); }, selector); } ], function (error, page, ph) { callback(error, page, ph); }); }
javascript
function clickElement(page, ph, selectorAndOptions, callback) { var selector = selectorAndOptions[0]; var options = selectorAndOptions[1]; function clickSelector(selector) { try { var button = document.querySelector(selector); var ev = document.createEvent("MouseEvent"); ev.initMouseEvent( "click", true /* bubble */, true /* cancelable */, window, null, 0, 0, 0, 0, /* coordinates */ false, false, false, false, /* modifier keys */ 0 /*left*/, null ); button.dispatchEvent(ev); } catch (error) { return error } } var oldUrl; async.waterfall([ function (callback) { page.get('url', function (url) { oldUrl = url; callback(); }); }, function (callback) { page.evaluate(clickSelector, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error, page, ph); return; } checks.ajaxCallback(page, ph, oldUrl, options, callback); }, selector); } ], function (error, page, ph) { callback(error, page, ph); }); }
[ "function", "clickElement", "(", "page", ",", "ph", ",", "selectorAndOptions", ",", "callback", ")", "{", "var", "selector", "=", "selectorAndOptions", "[", "0", "]", ";", "var", "options", "=", "selectorAndOptions", "[", "1", "]", ";", "function", "clickSelector", "(", "selector", ")", "{", "try", "{", "var", "button", "=", "document", ".", "querySelector", "(", "selector", ")", ";", "var", "ev", "=", "document", ".", "createEvent", "(", "\"MouseEvent\"", ")", ";", "ev", ".", "initMouseEvent", "(", "\"click\"", ",", "true", ",", "true", ",", "window", ",", "null", ",", "0", ",", "0", ",", "0", ",", "0", ",", "false", ",", "false", ",", "false", ",", "false", ",", "0", ",", "null", ")", ";", "button", ".", "dispatchEvent", "(", "ev", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "error", "}", "}", "var", "oldUrl", ";", "async", ".", "waterfall", "(", "[", "function", "(", "callback", ")", "{", "page", ".", "get", "(", "'url'", ",", "function", "(", "url", ")", "{", "oldUrl", "=", "url", ";", "callback", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "page", ".", "evaluate", "(", "clickSelector", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "page", ",", "ph", ")", ";", "return", ";", "}", "checks", ".", "ajaxCallback", "(", "page", ",", "ph", ",", "oldUrl", ",", "options", ",", "callback", ")", ";", "}", ",", "selector", ")", ";", "}", "]", ",", "function", "(", "error", ",", "page", ",", "ph", ")", "{", "callback", "(", "error", ",", "page", ",", "ph", ")", ";", "}", ")", ";", "}" ]
Clicks a css selector on the page @param page @param ph @param {array} selectorAndOptions Index 0 - {string} selector CSS Selector Index 1 - {int} options 0 – callback immediately 1 – expect ajax, callback when the dom changes 2 – expect page navigation, callback when the url changes and document is ready @param {pageCallback} callback
[ "Clicks", "a", "css", "selector", "on", "the", "page" ]
562dd4e7a6bacb9c8b51c1344a5e336545177516
https://github.com/jiahaog/Revenant/blob/562dd4e7a6bacb9c8b51c1344a5e336545177516/lib/actions.js#L55-L101
train
jiahaog/Revenant
lib/actions.js
setCheckboxState
function setCheckboxState(page, ph, selectorAndState, callback) { page.evaluate(function (selectorAndState) { try { var selector = selectorAndState[0]; var state = selectorAndState[1]; var element = document.querySelector(selector); element.checked = state; // event is needed because listeners to the change do not react to // programmatic changes var event = document.createEvent('Event'); event.initEvent('change', true, false); element.dispatchEvent(event); return null; } catch (error) { return error; } }, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error, page, ph); return; } callback(null, page, ph); }, selectorAndState); }
javascript
function setCheckboxState(page, ph, selectorAndState, callback) { page.evaluate(function (selectorAndState) { try { var selector = selectorAndState[0]; var state = selectorAndState[1]; var element = document.querySelector(selector); element.checked = state; // event is needed because listeners to the change do not react to // programmatic changes var event = document.createEvent('Event'); event.initEvent('change', true, false); element.dispatchEvent(event); return null; } catch (error) { return error; } }, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error, page, ph); return; } callback(null, page, ph); }, selectorAndState); }
[ "function", "setCheckboxState", "(", "page", ",", "ph", ",", "selectorAndState", ",", "callback", ")", "{", "page", ".", "evaluate", "(", "function", "(", "selectorAndState", ")", "{", "try", "{", "var", "selector", "=", "selectorAndState", "[", "0", "]", ";", "var", "state", "=", "selectorAndState", "[", "1", "]", ";", "var", "element", "=", "document", ".", "querySelector", "(", "selector", ")", ";", "element", ".", "checked", "=", "state", ";", "var", "event", "=", "document", ".", "createEvent", "(", "'Event'", ")", ";", "event", ".", "initEvent", "(", "'change'", ",", "true", ",", "false", ")", ";", "element", ".", "dispatchEvent", "(", "event", ")", ";", "return", "null", ";", "}", "catch", "(", "error", ")", "{", "return", "error", ";", "}", "}", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "page", ",", "ph", ")", ";", "return", ";", "}", "callback", "(", "null", ",", "page", ",", "ph", ")", ";", "}", ",", "selectorAndState", ")", ";", "}" ]
Sets the state of a checkbox @param page @param ph @param {Array} selectorAndState index 0 - {string} selector index 1 - {boolean} state @param {pageCallback} callback
[ "Sets", "the", "state", "of", "a", "checkbox" ]
562dd4e7a6bacb9c8b51c1344a5e336545177516
https://github.com/jiahaog/Revenant/blob/562dd4e7a6bacb9c8b51c1344a5e336545177516/lib/actions.js#L111-L136
train
jiahaog/Revenant
lib/actions.js
fillForm
function fillForm(page, ph, selectorAndValue, callback) { page.evaluate(function (selectorAndValue) { try { var selector = selectorAndValue[0]; var value = selectorAndValue[1]; document.querySelector(selector).value = value; return null; } catch (error) { return error; } }, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error, page, ph); return; } callback(null, page, ph); }, selectorAndValue); }
javascript
function fillForm(page, ph, selectorAndValue, callback) { page.evaluate(function (selectorAndValue) { try { var selector = selectorAndValue[0]; var value = selectorAndValue[1]; document.querySelector(selector).value = value; return null; } catch (error) { return error; } }, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error, page, ph); return; } callback(null, page, ph); }, selectorAndValue); }
[ "function", "fillForm", "(", "page", ",", "ph", ",", "selectorAndValue", ",", "callback", ")", "{", "page", ".", "evaluate", "(", "function", "(", "selectorAndValue", ")", "{", "try", "{", "var", "selector", "=", "selectorAndValue", "[", "0", "]", ";", "var", "value", "=", "selectorAndValue", "[", "1", "]", ";", "document", ".", "querySelector", "(", "selector", ")", ".", "value", "=", "value", ";", "return", "null", ";", "}", "catch", "(", "error", ")", "{", "return", "error", ";", "}", "}", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "page", ",", "ph", ")", ";", "return", ";", "}", "callback", "(", "null", ",", "page", ",", "ph", ")", ";", "}", ",", "selectorAndValue", ")", ";", "}" ]
Fills a form on the page @param page @param ph @param {Array} selectorAndValue index 0 - {string} selector index 1 - {string} value @param {pageCallback} callback
[ "Fills", "a", "form", "on", "the", "page" ]
562dd4e7a6bacb9c8b51c1344a5e336545177516
https://github.com/jiahaog/Revenant/blob/562dd4e7a6bacb9c8b51c1344a5e336545177516/lib/actions.js#L146-L164
train
jiahaog/Revenant
lib/actions.js
submitForm
function submitForm(page, ph, callback) { var oldUrl; async.waterfall([ function (callback) { page.get('url', function (url) { oldUrl = url; callback(); }); }, function (callback) { page.evaluate(function () { try { document.forms[0].submit(); return null; } catch (error) { return error; } }, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error); return; } callback() }); }, function (callback) { checks.pageHasChanged(page, oldUrl, function (error) { callback(error); }); } ], function (error) { callback(error, page, ph); }); }
javascript
function submitForm(page, ph, callback) { var oldUrl; async.waterfall([ function (callback) { page.get('url', function (url) { oldUrl = url; callback(); }); }, function (callback) { page.evaluate(function () { try { document.forms[0].submit(); return null; } catch (error) { return error; } }, function (error) { // do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph); if (error) { callback(error); return; } callback() }); }, function (callback) { checks.pageHasChanged(page, oldUrl, function (error) { callback(error); }); } ], function (error) { callback(error, page, ph); }); }
[ "function", "submitForm", "(", "page", ",", "ph", ",", "callback", ")", "{", "var", "oldUrl", ";", "async", ".", "waterfall", "(", "[", "function", "(", "callback", ")", "{", "page", ".", "get", "(", "'url'", ",", "function", "(", "url", ")", "{", "oldUrl", "=", "url", ";", "callback", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "page", ".", "evaluate", "(", "function", "(", ")", "{", "try", "{", "document", ".", "forms", "[", "0", "]", ".", "submit", "(", ")", ";", "return", "null", ";", "}", "catch", "(", "error", ")", "{", "return", "error", ";", "}", "}", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "return", ";", "}", "callback", "(", ")", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "checks", ".", "pageHasChanged", "(", "page", ",", "oldUrl", ",", "function", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", ")", ";", "}", "]", ",", "function", "(", "error", ")", "{", "callback", "(", "error", ",", "page", ",", "ph", ")", ";", "}", ")", ";", "}" ]
Submits a form on the page @param page @param ph @param {pageCallback} callback
[ "Submits", "a", "form", "on", "the", "page" ]
562dd4e7a6bacb9c8b51c1344a5e336545177516
https://github.com/jiahaog/Revenant/blob/562dd4e7a6bacb9c8b51c1344a5e336545177516/lib/actions.js#L172-L205
train
jaruba/multipass-torrent
stremio-addon/addon.js
validate
function validate(args) { var meta = args.query; if (! (args.query || args.infoHash)) return { code: 0, message: "query/infoHash required" }; if (meta && !meta.imdb_id) return { code: 1, message: "imdb_id required" }; if (meta && (meta.type == "series" && !(meta.hasOwnProperty("episode") && meta.hasOwnProperty("season")))) return { code: 2, message: "season and episode required for series type" }; return false; }
javascript
function validate(args) { var meta = args.query; if (! (args.query || args.infoHash)) return { code: 0, message: "query/infoHash required" }; if (meta && !meta.imdb_id) return { code: 1, message: "imdb_id required" }; if (meta && (meta.type == "series" && !(meta.hasOwnProperty("episode") && meta.hasOwnProperty("season")))) return { code: 2, message: "season and episode required for series type" }; return false; }
[ "function", "validate", "(", "args", ")", "{", "var", "meta", "=", "args", ".", "query", ";", "if", "(", "!", "(", "args", ".", "query", "||", "args", ".", "infoHash", ")", ")", "return", "{", "code", ":", "0", ",", "message", ":", "\"query/infoHash required\"", "}", ";", "if", "(", "meta", "&&", "!", "meta", ".", "imdb_id", ")", "return", "{", "code", ":", "1", ",", "message", ":", "\"imdb_id required\"", "}", ";", "if", "(", "meta", "&&", "(", "meta", ".", "type", "==", "\"series\"", "&&", "!", "(", "meta", ".", "hasOwnProperty", "(", "\"episode\"", ")", "&&", "meta", ".", "hasOwnProperty", "(", "\"season\"", ")", ")", ")", ")", "return", "{", "code", ":", "2", ",", "message", ":", "\"season and episode required for series type\"", "}", ";", "return", "false", ";", "}" ]
Basic validation of args
[ "Basic", "validation", "of", "args" ]
3cfa821760d956d3d104af04365c2a9d85226a9f
https://github.com/jaruba/multipass-torrent/blob/3cfa821760d956d3d104af04365c2a9d85226a9f/stremio-addon/addon.js#L64-L71
train
Blackening999/passport-linkedin-token-oauth2
lib/passport-linkedin-token-oauth2/strategy.js
LinkedinTokenStrategy
function LinkedinTokenStrategy(options, verify) { options = options || {} options.authorizationURL = options.authorizationURL || 'https://www.linkedin.com'; options.tokenURL = options.tokenURL || 'https://www.linkedin.com/uas/oauth2/accessToken'; options.scopeSeparator = options.scopeSeparator || ','; this._passReqToCallback = options.passReqToCallback; OAuth2Strategy.call(this, options, verify); this.profileUrl = options.profileURL || 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,public-profile-url)?format=json'; this.name = 'linkedin-token'; }
javascript
function LinkedinTokenStrategy(options, verify) { options = options || {} options.authorizationURL = options.authorizationURL || 'https://www.linkedin.com'; options.tokenURL = options.tokenURL || 'https://www.linkedin.com/uas/oauth2/accessToken'; options.scopeSeparator = options.scopeSeparator || ','; this._passReqToCallback = options.passReqToCallback; OAuth2Strategy.call(this, options, verify); this.profileUrl = options.profileURL || 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,public-profile-url)?format=json'; this.name = 'linkedin-token'; }
[ "function", "LinkedinTokenStrategy", "(", "options", ",", "verify", ")", "{", "options", "=", "options", "||", "{", "}", "options", ".", "authorizationURL", "=", "options", ".", "authorizationURL", "||", "'https://www.linkedin.com'", ";", "options", ".", "tokenURL", "=", "options", ".", "tokenURL", "||", "'https://www.linkedin.com/uas/oauth2/accessToken'", ";", "options", ".", "scopeSeparator", "=", "options", ".", "scopeSeparator", "||", "','", ";", "this", ".", "_passReqToCallback", "=", "options", ".", "passReqToCallback", ";", "OAuth2Strategy", ".", "call", "(", "this", ",", "options", ",", "verify", ")", ";", "this", ".", "profileUrl", "=", "options", ".", "profileURL", "||", "'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,public-profile-url)?format=json'", ";", "this", ".", "name", "=", "'linkedin-token'", ";", "}" ]
`LinkedinTokenStrategy` constructor. The Linkedin authentication strategy authenticates requests by delegating to Linkedin using the OAuth 2.0 protocol. And accepts only access_tokens. Specialy designed for client-side flow (implicit grant flow) Applications must supply a `verify` callback which accepts an `accessToken`, `refreshToken` and service-specific `profile`, and then calls the `done` callback supplying a `user`, which should be set to `false` if the credentials are not valid. If an exception occured, `err` should be set. Options: - `clientID` your Linkedin application's App ID - `clientSecret` your Linkedin application's App Secret Examples: passport.use(new LinkedinTokenStrategy({ clientID: '123-456-789', clientSecret: 'shhh-its-a-secret' }, function(accessToken, refreshToken, profile, done) { User.findOrCreate(..., function (err, user) { done(err, user); }); } )); @param {Object} options @param {Function} verify @api public
[ "LinkedinTokenStrategy", "constructor", "." ]
d3d3c8bce5eaae2f8f0c962748fa3dbc03891c64
https://github.com/Blackening999/passport-linkedin-token-oauth2/blob/d3d3c8bce5eaae2f8f0c962748fa3dbc03891c64/lib/passport-linkedin-token-oauth2/strategy.js#L43-L54
train
SkidX/tweene
src/tween-pro.js
getProperty
function getProperty(style, name) { if(style[name] !== void 0) { return [name, style[name]]; } if(name in propertyNames) { return [propertyNames[name], style[propertyNames[name]]]; } name = name.substr(0, 1).toUpperCase() + name.substr(1); var prefixes = ['webkit', 'moz', 'ms', 'o'], fullName; for(var i = 0, end = prefixes.length; i < end; i++) { fullName = prefixes[i] + name; if(style[fullName] !== void 0) { propertyNames[name] = fullName; return [fullName, style[fullName]]; } } return [name, void 0]; }
javascript
function getProperty(style, name) { if(style[name] !== void 0) { return [name, style[name]]; } if(name in propertyNames) { return [propertyNames[name], style[propertyNames[name]]]; } name = name.substr(0, 1).toUpperCase() + name.substr(1); var prefixes = ['webkit', 'moz', 'ms', 'o'], fullName; for(var i = 0, end = prefixes.length; i < end; i++) { fullName = prefixes[i] + name; if(style[fullName] !== void 0) { propertyNames[name] = fullName; return [fullName, style[fullName]]; } } return [name, void 0]; }
[ "function", "getProperty", "(", "style", ",", "name", ")", "{", "if", "(", "style", "[", "name", "]", "!==", "void", "0", ")", "{", "return", "[", "name", ",", "style", "[", "name", "]", "]", ";", "}", "if", "(", "name", "in", "propertyNames", ")", "{", "return", "[", "propertyNames", "[", "name", "]", ",", "style", "[", "propertyNames", "[", "name", "]", "]", "]", ";", "}", "name", "=", "name", ".", "substr", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "name", ".", "substr", "(", "1", ")", ";", "var", "prefixes", "=", "[", "'webkit'", ",", "'moz'", ",", "'ms'", ",", "'o'", "]", ",", "fullName", ";", "for", "(", "var", "i", "=", "0", ",", "end", "=", "prefixes", ".", "length", ";", "i", "<", "end", ";", "i", "++", ")", "{", "fullName", "=", "prefixes", "[", "i", "]", "+", "name", ";", "if", "(", "style", "[", "fullName", "]", "!==", "void", "0", ")", "{", "propertyNames", "[", "name", "]", "=", "fullName", ";", "return", "[", "fullName", ",", "style", "[", "fullName", "]", "]", ";", "}", "}", "return", "[", "name", ",", "void", "0", "]", ";", "}" ]
Get style real name and value, checking for browser prefixes if needed @param {object} style @param {string} name @returns {array} - return [realName, value]
[ "Get", "style", "real", "name", "and", "value", "checking", "for", "browser", "prefixes", "if", "needed" ]
86f941f7b3f3cff566f90ebb570b674fc640488b
https://github.com/SkidX/tweene/blob/86f941f7b3f3cff566f90ebb570b674fc640488b/src/tween-pro.js#L25-L47
train
jaredhanson/jsonb
lib/index.js
parse
function parse(str, options) { var obj = options.object || 'obj' , space = options.pretty ? 2 : 0 , space = options.spaces ? options.spaces : space , js = str; return '' + 'var ' + obj + ' = factory();\n' + (options.self ? 'var self = locals || {};\n' + js : 'with (locals || {}) {\n' + js + '\n}\n') + 'return JSON.stringify(' + obj + ', null, ' + space + ')'; }
javascript
function parse(str, options) { var obj = options.object || 'obj' , space = options.pretty ? 2 : 0 , space = options.spaces ? options.spaces : space , js = str; return '' + 'var ' + obj + ' = factory();\n' + (options.self ? 'var self = locals || {};\n' + js : 'with (locals || {}) {\n' + js + '\n}\n') + 'return JSON.stringify(' + obj + ', null, ' + space + ')'; }
[ "function", "parse", "(", "str", ",", "options", ")", "{", "var", "obj", "=", "options", ".", "object", "||", "'obj'", ",", "space", "=", "options", ".", "pretty", "?", "2", ":", "0", ",", "space", "=", "options", ".", "spaces", "?", "options", ".", "spaces", ":", "space", ",", "js", "=", "str", ";", "return", "''", "+", "'var '", "+", "obj", "+", "' = factory();\\n'", "+", "\\n", "+", "(", "options", ".", "self", "?", "'var self = locals || {};\\n'", "+", "\\n", ":", "js", ")", "+", "'with (locals || {}) {\\n'", "+", "\\n", "+", "js", "+", "'\\n}\\n'", "+", "\\n", "+", "\\n", ";", "}" ]
Parse the given `str` of JSON builder and return a function body. @param {String} str @param {Object} options @return {String} @api private
[ "Parse", "the", "given", "str", "of", "JSON", "builder", "and", "return", "a", "function", "body", "." ]
f629a3da2fdda115581fb70f5dc67175401e70b9
https://github.com/jaredhanson/jsonb/blob/f629a3da2fdda115581fb70f5dc67175401e70b9/lib/index.js#L65-L77
train
manifoldco/node-signature
lib/verifier.js
Verifier
function Verifier(givenMasterKey) { var masterKey = givenMasterKey || MASTER_KEY; if (!masterKey) { throw new errors.ValidationFailed('invalid master key'); } this.masterKey = base64url.toBuffer(masterKey); }
javascript
function Verifier(givenMasterKey) { var masterKey = givenMasterKey || MASTER_KEY; if (!masterKey) { throw new errors.ValidationFailed('invalid master key'); } this.masterKey = base64url.toBuffer(masterKey); }
[ "function", "Verifier", "(", "givenMasterKey", ")", "{", "var", "masterKey", "=", "givenMasterKey", "||", "MASTER_KEY", ";", "if", "(", "!", "masterKey", ")", "{", "throw", "new", "errors", ".", "ValidationFailed", "(", "'invalid master key'", ")", ";", "}", "this", ".", "masterKey", "=", "base64url", ".", "toBuffer", "(", "masterKey", ")", ";", "}" ]
Create a new verifier instance for the given master key @constructor @param {string} masterKey - Master key base64url string
[ "Create", "a", "new", "verifier", "instance", "for", "the", "given", "master", "key" ]
15f8cedf442f1b4cde8476b42481b69fb0972ce3
https://github.com/manifoldco/node-signature/blob/15f8cedf442f1b4cde8476b42481b69fb0972ce3/lib/verifier.js#L22-L28
train
SkidX/tweene
src/tweene.js
inArray
function inArray(array, search) { if(!isArray(array)) { throw 'expected an array as first param'; } if(array.indexOf) { return array.indexOf(search); } for(var i = 0, end = array.length; i < end; i++) { if(array[i] === search) { return i; } } return -1; }
javascript
function inArray(array, search) { if(!isArray(array)) { throw 'expected an array as first param'; } if(array.indexOf) { return array.indexOf(search); } for(var i = 0, end = array.length; i < end; i++) { if(array[i] === search) { return i; } } return -1; }
[ "function", "inArray", "(", "array", ",", "search", ")", "{", "if", "(", "!", "isArray", "(", "array", ")", ")", "{", "throw", "'expected an array as first param'", ";", "}", "if", "(", "array", ".", "indexOf", ")", "{", "return", "array", ".", "indexOf", "(", "search", ")", ";", "}", "for", "(", "var", "i", "=", "0", ",", "end", "=", "array", ".", "length", ";", "i", "<", "end", ";", "i", "++", ")", "{", "if", "(", "array", "[", "i", "]", "===", "search", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
simplified version of Array.indexOf polyfill
[ "simplified", "version", "of", "Array", ".", "indexOf", "polyfill" ]
86f941f7b3f3cff566f90ebb570b674fc640488b
https://github.com/SkidX/tweene/blob/86f941f7b3f3cff566f90ebb570b674fc640488b/src/tweene.js#L283-L303
train
SkidX/tweene
src/tweene.js
toArray
function toArray(args, pos) { if(pos === void 0) { pos = 0; } return Array.prototype.slice.call(args, pos); }
javascript
function toArray(args, pos) { if(pos === void 0) { pos = 0; } return Array.prototype.slice.call(args, pos); }
[ "function", "toArray", "(", "args", ",", "pos", ")", "{", "if", "(", "pos", "===", "void", "0", ")", "{", "pos", "=", "0", ";", "}", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ",", "pos", ")", ";", "}" ]
used to convert arguments to real array
[ "used", "to", "convert", "arguments", "to", "real", "array" ]
86f941f7b3f3cff566f90ebb570b674fc640488b
https://github.com/SkidX/tweene/blob/86f941f7b3f3cff566f90ebb570b674fc640488b/src/tweene.js#L307-L314
train
SkidX/tweene
src/tweene.js
convertTime
function convertTime(value, fromUnit, toUnit) { if(fromUnit != toUnit && value !== 0) { return value * (toUnit == 's'? 0.001 : 1000); } return value; }
javascript
function convertTime(value, fromUnit, toUnit) { if(fromUnit != toUnit && value !== 0) { return value * (toUnit == 's'? 0.001 : 1000); } return value; }
[ "function", "convertTime", "(", "value", ",", "fromUnit", ",", "toUnit", ")", "{", "if", "(", "fromUnit", "!=", "toUnit", "&&", "value", "!==", "0", ")", "{", "return", "value", "*", "(", "toUnit", "==", "'s'", "?", "0.001", ":", "1000", ")", ";", "}", "return", "value", ";", "}" ]
convert time from seconds to milliseconds and vice versa @param {number} value @param {string} fromUnit - 's' | 'ms' @param {string} toUnit - 's' | 'ms' @returns {Number}
[ "convert", "time", "from", "seconds", "to", "milliseconds", "and", "vice", "versa" ]
86f941f7b3f3cff566f90ebb570b674fc640488b
https://github.com/SkidX/tweene/blob/86f941f7b3f3cff566f90ebb570b674fc640488b/src/tweene.js#L325-L332
train
SkidX/tweene
src/tweene.js
compoundMapping
function compoundMapping(name, value) { var parts, nameParts, prefix, suffix, dirs, values = {}, easing, i; if(isArray(value)) { value = value[0]; easing = value[1]; } else { easing = null; } parts = String(value).split(/\s+/); switch(parts.length) { case 1: parts = [parts[0], parts[0], parts[0], parts[0]]; break; case 2: parts = [parts[0], parts[1], parts[0], parts[1]]; break; case 3: parts = [parts[0], parts[1], parts[2], parts[1]]; break; } nameParts = decamelize(name).split('-'); prefix = nameParts[0]; suffix = nameParts.length > 1? nameParts[1].substr(0, 1).toUpperCase() + nameParts[1].substr(1) : ''; dirs = name == 'borderRadius'? radiusDirections : compoundDirections; for(i = 0; i < 4; i++) { values[prefix + dirs[i] + suffix] = easing? [parts[i], easing] : parts[i]; } return values; }
javascript
function compoundMapping(name, value) { var parts, nameParts, prefix, suffix, dirs, values = {}, easing, i; if(isArray(value)) { value = value[0]; easing = value[1]; } else { easing = null; } parts = String(value).split(/\s+/); switch(parts.length) { case 1: parts = [parts[0], parts[0], parts[0], parts[0]]; break; case 2: parts = [parts[0], parts[1], parts[0], parts[1]]; break; case 3: parts = [parts[0], parts[1], parts[2], parts[1]]; break; } nameParts = decamelize(name).split('-'); prefix = nameParts[0]; suffix = nameParts.length > 1? nameParts[1].substr(0, 1).toUpperCase() + nameParts[1].substr(1) : ''; dirs = name == 'borderRadius'? radiusDirections : compoundDirections; for(i = 0; i < 4; i++) { values[prefix + dirs[i] + suffix] = easing? [parts[i], easing] : parts[i]; } return values; }
[ "function", "compoundMapping", "(", "name", ",", "value", ")", "{", "var", "parts", ",", "nameParts", ",", "prefix", ",", "suffix", ",", "dirs", ",", "values", "=", "{", "}", ",", "easing", ",", "i", ";", "if", "(", "isArray", "(", "value", ")", ")", "{", "value", "=", "value", "[", "0", "]", ";", "easing", "=", "value", "[", "1", "]", ";", "}", "else", "{", "easing", "=", "null", ";", "}", "parts", "=", "String", "(", "value", ")", ".", "split", "(", "/", "\\s+", "/", ")", ";", "switch", "(", "parts", ".", "length", ")", "{", "case", "1", ":", "parts", "=", "[", "parts", "[", "0", "]", ",", "parts", "[", "0", "]", ",", "parts", "[", "0", "]", ",", "parts", "[", "0", "]", "]", ";", "break", ";", "case", "2", ":", "parts", "=", "[", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", ",", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", "]", ";", "break", ";", "case", "3", ":", "parts", "=", "[", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", ",", "parts", "[", "2", "]", ",", "parts", "[", "1", "]", "]", ";", "break", ";", "}", "nameParts", "=", "decamelize", "(", "name", ")", ".", "split", "(", "'-'", ")", ";", "prefix", "=", "nameParts", "[", "0", "]", ";", "suffix", "=", "nameParts", ".", "length", ">", "1", "?", "nameParts", "[", "1", "]", ".", "substr", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "nameParts", "[", "1", "]", ".", "substr", "(", "1", ")", ":", "''", ";", "dirs", "=", "name", "==", "'borderRadius'", "?", "radiusDirections", ":", "compoundDirections", ";", "for", "(", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "values", "[", "prefix", "+", "dirs", "[", "i", "]", "+", "suffix", "]", "=", "easing", "?", "[", "parts", "[", "i", "]", ",", "easing", "]", ":", "parts", "[", "i", "]", ";", "}", "return", "values", ";", "}" ]
take as input compound properties defined as a space separated string of values and return the list of single value properties padding: 5 => paddingTop: 5, paddingRight: 5, paddingBottom: 5, paddingLeft: 5 border-width: 2px 1px => borderTopWidth: 2px, borderRightWidth: 1px, borderBottomWidth: 2px, borderLeftWidth: 1px @param {string} name @param {string} value @returns {object}
[ "take", "as", "input", "compound", "properties", "defined", "as", "a", "space", "separated", "string", "of", "values", "and", "return", "the", "list", "of", "single", "value", "properties" ]
86f941f7b3f3cff566f90ebb570b674fc640488b
https://github.com/SkidX/tweene/blob/86f941f7b3f3cff566f90ebb570b674fc640488b/src/tweene.js#L386-L419
train
SkidX/tweene
src/tweene.js
transformMapping
function transformMapping(name, value) { var easing, dirs = ['X', 'Y', 'Z'], values = {}, parts, baseName; if(isArray(value)) { value = value[0]; easing = value[1]; } else { easing = null; } parts = String(value).split(/\s*,\s*/); baseName = name.indexOf('3') !== -1? name.substr(0, name.length - 2) : name; if(name == 'rotate3d') { if(parts.length == 4) { dirs = [parts[0] == '1'? 'X' : (parts[1] == '1'? 'Y' : 'Z')]; parts[0] = parts[3]; } else { throw 'invalid rotate 3d value'; } } else { switch(parts.length) { // for rotations, a single value is passed as Z-value, while for other transforms it is applied to X and Y case 1: parts = baseName == 'rotate' || baseName == 'rotation'? [null, null, parts[0]] : [parts[0], parts[0], null]; break; case 2: parts = [parts[0], parts[1], null]; break; } } for(var i = 0; i < dirs.length; i++) { if(parts[i] !== null) { values[baseName + dirs[i]] = easing? [parts[i], easing] : parts[i]; } } return values; }
javascript
function transformMapping(name, value) { var easing, dirs = ['X', 'Y', 'Z'], values = {}, parts, baseName; if(isArray(value)) { value = value[0]; easing = value[1]; } else { easing = null; } parts = String(value).split(/\s*,\s*/); baseName = name.indexOf('3') !== -1? name.substr(0, name.length - 2) : name; if(name == 'rotate3d') { if(parts.length == 4) { dirs = [parts[0] == '1'? 'X' : (parts[1] == '1'? 'Y' : 'Z')]; parts[0] = parts[3]; } else { throw 'invalid rotate 3d value'; } } else { switch(parts.length) { // for rotations, a single value is passed as Z-value, while for other transforms it is applied to X and Y case 1: parts = baseName == 'rotate' || baseName == 'rotation'? [null, null, parts[0]] : [parts[0], parts[0], null]; break; case 2: parts = [parts[0], parts[1], null]; break; } } for(var i = 0; i < dirs.length; i++) { if(parts[i] !== null) { values[baseName + dirs[i]] = easing? [parts[i], easing] : parts[i]; } } return values; }
[ "function", "transformMapping", "(", "name", ",", "value", ")", "{", "var", "easing", ",", "dirs", "=", "[", "'X'", ",", "'Y'", ",", "'Z'", "]", ",", "values", "=", "{", "}", ",", "parts", ",", "baseName", ";", "if", "(", "isArray", "(", "value", ")", ")", "{", "value", "=", "value", "[", "0", "]", ";", "easing", "=", "value", "[", "1", "]", ";", "}", "else", "{", "easing", "=", "null", ";", "}", "parts", "=", "String", "(", "value", ")", ".", "split", "(", "/", "\\s*,\\s*", "/", ")", ";", "baseName", "=", "name", ".", "indexOf", "(", "'3'", ")", "!==", "-", "1", "?", "name", ".", "substr", "(", "0", ",", "name", ".", "length", "-", "2", ")", ":", "name", ";", "if", "(", "name", "==", "'rotate3d'", ")", "{", "if", "(", "parts", ".", "length", "==", "4", ")", "{", "dirs", "=", "[", "parts", "[", "0", "]", "==", "'1'", "?", "'X'", ":", "(", "parts", "[", "1", "]", "==", "'1'", "?", "'Y'", ":", "'Z'", ")", "]", ";", "parts", "[", "0", "]", "=", "parts", "[", "3", "]", ";", "}", "else", "{", "throw", "'invalid rotate 3d value'", ";", "}", "}", "else", "{", "switch", "(", "parts", ".", "length", ")", "{", "case", "1", ":", "parts", "=", "baseName", "==", "'rotate'", "||", "baseName", "==", "'rotation'", "?", "[", "null", ",", "null", ",", "parts", "[", "0", "]", "]", ":", "[", "parts", "[", "0", "]", ",", "parts", "[", "0", "]", ",", "null", "]", ";", "break", ";", "case", "2", ":", "parts", "=", "[", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", ",", "null", "]", ";", "break", ";", "}", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "dirs", ".", "length", ";", "i", "++", ")", "{", "if", "(", "parts", "[", "i", "]", "!==", "null", ")", "{", "values", "[", "baseName", "+", "dirs", "[", "i", "]", "]", "=", "easing", "?", "[", "parts", "[", "i", "]", ",", "easing", "]", ":", "parts", "[", "i", "]", ";", "}", "}", "return", "values", ";", "}" ]
split commpound transform values scale: 1.2 => scaleX: 1.2, scaleY: 1.2 rotate3d: 30, 60, 40 => rotateX: 30, rotateY: 60, rotateZ: 40 @param {string} name @param {string} value @returns {object}
[ "split", "commpound", "transform", "values" ]
86f941f7b3f3cff566f90ebb570b674fc640488b
https://github.com/SkidX/tweene/blob/86f941f7b3f3cff566f90ebb570b674fc640488b/src/tweene.js#L432-L484
train
SkidX/tweene
src/tweene.js
parseSpeed
function parseSpeed(value) { if(value in speeds) { value = speeds[value]; } value = parseFloat(value); if(isNaN(value) || !value || value <= 0) { value = 1; } return value; }
javascript
function parseSpeed(value) { if(value in speeds) { value = speeds[value]; } value = parseFloat(value); if(isNaN(value) || !value || value <= 0) { value = 1; } return value; }
[ "function", "parseSpeed", "(", "value", ")", "{", "if", "(", "value", "in", "speeds", ")", "{", "value", "=", "speeds", "[", "value", "]", ";", "}", "value", "=", "parseFloat", "(", "value", ")", ";", "if", "(", "isNaN", "(", "value", ")", "||", "!", "value", "||", "value", "<=", "0", ")", "{", "value", "=", "1", ";", "}", "return", "value", ";", "}" ]
accept a speed name shortcuts or a number and give back an acceptable positive value. Fallback to 1 if value is out of valid range @param {string|number} value @returns {number}
[ "accept", "a", "speed", "name", "shortcuts", "or", "a", "number", "and", "give", "back", "an", "acceptable", "positive", "value", ".", "Fallback", "to", "1", "if", "value", "is", "out", "of", "valid", "range" ]
86f941f7b3f3cff566f90ebb570b674fc640488b
https://github.com/SkidX/tweene/blob/86f941f7b3f3cff566f90ebb570b674fc640488b/src/tweene.js#L517-L530
train
hyperstart/hyperapp-devtools
dist/hyperapp-devtools.es.js
get
function get(target, path) { var result = target; for (var i = 0; i < path.length; i++) { result = result ? result[path[i]] : result; } return result; }
javascript
function get(target, path) { var result = target; for (var i = 0; i < path.length; i++) { result = result ? result[path[i]] : result; } return result; }
[ "function", "get", "(", "target", ",", "path", ")", "{", "var", "result", "=", "target", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "path", ".", "length", ";", "i", "++", ")", "{", "result", "=", "result", "?", "result", "[", "path", "[", "i", "]", "]", ":", "result", ";", "}", "return", "result", ";", "}" ]
Get the value at the given path in the given target, or undefined if path doesn't exists.
[ "Get", "the", "value", "at", "the", "given", "path", "in", "the", "given", "target", "or", "undefined", "if", "path", "doesn", "t", "exists", "." ]
08abd1ad56fd7719bcb967c204881150ba07be70
https://github.com/hyperstart/hyperapp-devtools/blob/08abd1ad56fd7719bcb967c204881150ba07be70/dist/hyperapp-devtools.es.js#L810-L816
train
jrburke/adapt-pkg-main
index.js
findOneJsInArray
function findOneJsInArray(ary) { var found, count = 0; ary.forEach(function(entry) { if (jsExtRegExp.test(entry)) { count += 1; found = entry; } }); return count === 1 ? found : null; }
javascript
function findOneJsInArray(ary) { var found, count = 0; ary.forEach(function(entry) { if (jsExtRegExp.test(entry)) { count += 1; found = entry; } }); return count === 1 ? found : null; }
[ "function", "findOneJsInArray", "(", "ary", ")", "{", "var", "found", ",", "count", "=", "0", ";", "ary", ".", "forEach", "(", "function", "(", "entry", ")", "{", "if", "(", "jsExtRegExp", ".", "test", "(", "entry", ")", ")", "{", "count", "+=", "1", ";", "found", "=", "entry", ";", "}", "}", ")", ";", "return", "count", "===", "1", "?", "found", ":", "null", ";", "}" ]
Given an array of file paths, only return a value if there is only one that ends in a .js extension.
[ "Given", "an", "array", "of", "file", "paths", "only", "return", "a", "value", "if", "there", "is", "only", "one", "that", "ends", "in", "a", ".", "js", "extension", "." ]
fe5e208ec3c61f0efee2593ecd3d9107935490ff
https://github.com/jrburke/adapt-pkg-main/blob/fe5e208ec3c61f0efee2593ecd3d9107935490ff/index.js#L43-L54
train
manifoldco/node-signature
lib/errors.js
InvalidSignature
function InvalidSignature(reason) { Error.captureStackTrace(this, this.constructor); this.type = 'unauthorized'; this.statusCode = 401; this.message = 'Invalid request signature'; this.reason = reason; }
javascript
function InvalidSignature(reason) { Error.captureStackTrace(this, this.constructor); this.type = 'unauthorized'; this.statusCode = 401; this.message = 'Invalid request signature'; this.reason = reason; }
[ "function", "InvalidSignature", "(", "reason", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "type", "=", "'unauthorized'", ";", "this", ".", "statusCode", "=", "401", ";", "this", ".", "message", "=", "'Invalid request signature'", ";", "this", ".", "reason", "=", "reason", ";", "}" ]
InvalidSignature returns the proper status code and type
[ "InvalidSignature", "returns", "the", "proper", "status", "code", "and", "type" ]
15f8cedf442f1b4cde8476b42481b69fb0972ce3
https://github.com/manifoldco/node-signature/blob/15f8cedf442f1b4cde8476b42481b69fb0972ce3/lib/errors.js#L9-L15
train
manifoldco/node-signature
lib/errors.js
ValidationFailed
function ValidationFailed(reason) { Error.captureStackTrace(this, this.constructor); this.type = 'bad_request'; this.statusCode = 400; this.message = 'Request validation failed'; this.reason = reason; }
javascript
function ValidationFailed(reason) { Error.captureStackTrace(this, this.constructor); this.type = 'bad_request'; this.statusCode = 400; this.message = 'Request validation failed'; this.reason = reason; }
[ "function", "ValidationFailed", "(", "reason", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "type", "=", "'bad_request'", ";", "this", ".", "statusCode", "=", "400", ";", "this", ".", "message", "=", "'Request validation failed'", ";", "this", ".", "reason", "=", "reason", ";", "}" ]
ValidationFailed returns the proper status code and type
[ "ValidationFailed", "returns", "the", "proper", "status", "code", "and", "type" ]
15f8cedf442f1b4cde8476b42481b69fb0972ce3
https://github.com/manifoldco/node-signature/blob/15f8cedf442f1b4cde8476b42481b69fb0972ce3/lib/errors.js#L23-L29
train
manifoldco/node-signature
lib/signature.js
Signature
function Signature(req, buf) { this.req = req; this.rawBody = buf || req.rawBody; this.xSignature = (req.headers['x-signature'] || '').split(' '); this.signature = base64url.toBuffer(this.xSignature[0] || ''); this.publicKey = base64url.toBuffer(this.xSignature[1] || ''); this.endorsement = base64url.toBuffer(this.xSignature[2] || ''); this.date = Date.parse(req.headers.date); }
javascript
function Signature(req, buf) { this.req = req; this.rawBody = buf || req.rawBody; this.xSignature = (req.headers['x-signature'] || '').split(' '); this.signature = base64url.toBuffer(this.xSignature[0] || ''); this.publicKey = base64url.toBuffer(this.xSignature[1] || ''); this.endorsement = base64url.toBuffer(this.xSignature[2] || ''); this.date = Date.parse(req.headers.date); }
[ "function", "Signature", "(", "req", ",", "buf", ")", "{", "this", ".", "req", "=", "req", ";", "this", ".", "rawBody", "=", "buf", "||", "req", ".", "rawBody", ";", "this", ".", "xSignature", "=", "(", "req", ".", "headers", "[", "'x-signature'", "]", "||", "''", ")", ".", "split", "(", "' '", ")", ";", "this", ".", "signature", "=", "base64url", ".", "toBuffer", "(", "this", ".", "xSignature", "[", "0", "]", "||", "''", ")", ";", "this", ".", "publicKey", "=", "base64url", ".", "toBuffer", "(", "this", ".", "xSignature", "[", "1", "]", "||", "''", ")", ";", "this", ".", "endorsement", "=", "base64url", ".", "toBuffer", "(", "this", ".", "xSignature", "[", "2", "]", "||", "''", ")", ";", "this", ".", "date", "=", "Date", ".", "parse", "(", "req", ".", "headers", ".", "date", ")", ";", "}" ]
5 minutes Create a new signature instance for the given request @constructor @param {object} req - Request object
[ "5", "minutes", "Create", "a", "new", "signature", "instance", "for", "the", "given", "request" ]
15f8cedf442f1b4cde8476b42481b69fb0972ce3
https://github.com/manifoldco/node-signature/blob/15f8cedf442f1b4cde8476b42481b69fb0972ce3/lib/signature.js#L22-L32
train
olalonde/proof-of-solvency
lib/index.js
function (cb) { get(SOLVENCY_SERVER + domain, function (roots) { roots = roots || []; roots.forEach(function (root) { files.push({ path: 'root', type: 'root', content: root }); }); cb(); }); }
javascript
function (cb) { get(SOLVENCY_SERVER + domain, function (roots) { roots = roots || []; roots.forEach(function (root) { files.push({ path: 'root', type: 'root', content: root }); }); cb(); }); }
[ "function", "(", "cb", ")", "{", "get", "(", "SOLVENCY_SERVER", "+", "domain", ",", "function", "(", "roots", ")", "{", "roots", "=", "roots", "||", "[", "]", ";", "roots", ".", "forEach", "(", "function", "(", "root", ")", "{", "files", ".", "push", "(", "{", "path", ":", "'root'", ",", "type", ":", "'root'", ",", "content", ":", "root", "}", ")", ";", "}", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}" ]
Fetch liability roots using solvency server The server is used as a proxy to make sure we don't get served custom root.
[ "Fetch", "liability", "roots", "using", "solvency", "server", "The", "server", "is", "used", "as", "a", "proxy", "to", "make", "sure", "we", "don", "t", "get", "served", "custom", "root", "." ]
d7ee19075eac3b523b9fe5f463e147811d57231c
https://github.com/olalonde/proof-of-solvency/blob/d7ee19075eac3b523b9fe5f463e147811d57231c/lib/index.js#L70-L78
train
olalonde/proof-of-solvency
lib/index.js
function (cb) { files.forEach(function (file) { var proof = file.content; if (!proof) return; if (!proof.id) { errors.push(file.path + ' has no ID property.'); return; } res[proof.id] = res[proof.id] || {}; res[proof.id][file.type] = proof; }); cb(); }
javascript
function (cb) { files.forEach(function (file) { var proof = file.content; if (!proof) return; if (!proof.id) { errors.push(file.path + ' has no ID property.'); return; } res[proof.id] = res[proof.id] || {}; res[proof.id][file.type] = proof; }); cb(); }
[ "function", "(", "cb", ")", "{", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "proof", "=", "file", ".", "content", ";", "if", "(", "!", "proof", ")", "return", ";", "if", "(", "!", "proof", ".", "id", ")", "{", "errors", ".", "push", "(", "file", ".", "path", "+", "' has no ID property.'", ")", ";", "return", ";", "}", "res", "[", "proof", ".", "id", "]", "=", "res", "[", "proof", ".", "id", "]", "||", "{", "}", ";", "res", "[", "proof", ".", "id", "]", "[", "file", ".", "type", "]", "=", "proof", ";", "}", ")", ";", "cb", "(", ")", ";", "}" ]
Group files by ID and set on result
[ "Group", "files", "by", "ID", "and", "set", "on", "result" ]
d7ee19075eac3b523b9fe5f463e147811d57231c
https://github.com/olalonde/proof-of-solvency/blob/d7ee19075eac3b523b9fe5f463e147811d57231c/lib/index.js#L80-L92
train
wildhaber/gluebert
src/polyfills/resources/IntersectionObserverPolyfill.js
throttle
function throttle(fn, timeout) { var timer = null; return function () { if (!timer) { timer = setTimeout(function() { fn(); timer = null; }, timeout); } }; }
javascript
function throttle(fn, timeout) { var timer = null; return function () { if (!timer) { timer = setTimeout(function() { fn(); timer = null; }, timeout); } }; }
[ "function", "throttle", "(", "fn", ",", "timeout", ")", "{", "var", "timer", "=", "null", ";", "return", "function", "(", ")", "{", "if", "(", "!", "timer", ")", "{", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "fn", "(", ")", ";", "timer", "=", "null", ";", "}", ",", "timeout", ")", ";", "}", "}", ";", "}" ]
Throttles a function and delays its executiong, so it's only called at most once within a given time period. @param {Function} fn The function to throttle. @param {number} timeout The amount of time that must pass before the function can be called again. @return {Function} The throttled function.
[ "Throttles", "a", "function", "and", "delays", "its", "executiong", "so", "it", "s", "only", "called", "at", "most", "once", "within", "a", "given", "time", "period", "." ]
b17d38a69fd006f22d5864ce27caa85a012ca4dd
https://github.com/wildhaber/gluebert/blob/b17d38a69fd006f22d5864ce27caa85a012ca4dd/src/polyfills/resources/IntersectionObserverPolyfill.js#L556-L566
train
wildhaber/gluebert
src/polyfills/resources/IntersectionObserverPolyfill.js
addEvent
function addEvent(node, event, fn, opt_useCapture) { if (typeof node.addEventListener == 'function') { node.addEventListener(event, fn, opt_useCapture || false); } else if (typeof node.attachEvent == 'function') { node.attachEvent('on' + event, fn); } }
javascript
function addEvent(node, event, fn, opt_useCapture) { if (typeof node.addEventListener == 'function') { node.addEventListener(event, fn, opt_useCapture || false); } else if (typeof node.attachEvent == 'function') { node.attachEvent('on' + event, fn); } }
[ "function", "addEvent", "(", "node", ",", "event", ",", "fn", ",", "opt_useCapture", ")", "{", "if", "(", "typeof", "node", ".", "addEventListener", "==", "'function'", ")", "{", "node", ".", "addEventListener", "(", "event", ",", "fn", ",", "opt_useCapture", "||", "false", ")", ";", "}", "else", "if", "(", "typeof", "node", ".", "attachEvent", "==", "'function'", ")", "{", "node", ".", "attachEvent", "(", "'on'", "+", "event", ",", "fn", ")", ";", "}", "}" ]
Adds an event handler to a DOM node ensuring cross-browser compatibility. @param {Node} node The DOM node to add the event handler to. @param {string} event The event name. @param {Function} fn The event handler to add. @param {boolean} opt_useCapture Optionally adds the even to the capture phase. Note: this only works in modern browsers.
[ "Adds", "an", "event", "handler", "to", "a", "DOM", "node", "ensuring", "cross", "-", "browser", "compatibility", "." ]
b17d38a69fd006f22d5864ce27caa85a012ca4dd
https://github.com/wildhaber/gluebert/blob/b17d38a69fd006f22d5864ce27caa85a012ca4dd/src/polyfills/resources/IntersectionObserverPolyfill.js#L577-L584
train
wildhaber/gluebert
src/polyfills/resources/IntersectionObserverPolyfill.js
removeEvent
function removeEvent(node, event, fn, opt_useCapture) { if (typeof node.removeEventListener == 'function') { node.removeEventListener(event, fn, opt_useCapture || false); } else if (typeof node.detatchEvent == 'function') { node.detatchEvent('on' + event, fn); } }
javascript
function removeEvent(node, event, fn, opt_useCapture) { if (typeof node.removeEventListener == 'function') { node.removeEventListener(event, fn, opt_useCapture || false); } else if (typeof node.detatchEvent == 'function') { node.detatchEvent('on' + event, fn); } }
[ "function", "removeEvent", "(", "node", ",", "event", ",", "fn", ",", "opt_useCapture", ")", "{", "if", "(", "typeof", "node", ".", "removeEventListener", "==", "'function'", ")", "{", "node", ".", "removeEventListener", "(", "event", ",", "fn", ",", "opt_useCapture", "||", "false", ")", ";", "}", "else", "if", "(", "typeof", "node", ".", "detatchEvent", "==", "'function'", ")", "{", "node", ".", "detatchEvent", "(", "'on'", "+", "event", ",", "fn", ")", ";", "}", "}" ]
Removes a previously added event handler from a DOM node. @param {Node} node The DOM node to remove the event handler from. @param {string} event The event name. @param {Function} fn The event handler to remove. @param {boolean} opt_useCapture If the event handler was added with this flag set to true, it should be set to true here in order to remove it.
[ "Removes", "a", "previously", "added", "event", "handler", "from", "a", "DOM", "node", "." ]
b17d38a69fd006f22d5864ce27caa85a012ca4dd
https://github.com/wildhaber/gluebert/blob/b17d38a69fd006f22d5864ce27caa85a012ca4dd/src/polyfills/resources/IntersectionObserverPolyfill.js#L595-L602
train
wildhaber/gluebert
src/polyfills/resources/IntersectionObserverPolyfill.js
computeRectIntersection
function computeRectIntersection(rect1, rect2) { var top = Math.max(rect1.top, rect2.top); var bottom = Math.min(rect1.bottom, rect2.bottom); var left = Math.max(rect1.left, rect2.left); var right = Math.min(rect1.right, rect2.right); var width = right - left; var height = bottom - top; return (width >= 0 && height >= 0) && { top: top, bottom: bottom, left: left, right: right, width: width, height: height }; }
javascript
function computeRectIntersection(rect1, rect2) { var top = Math.max(rect1.top, rect2.top); var bottom = Math.min(rect1.bottom, rect2.bottom); var left = Math.max(rect1.left, rect2.left); var right = Math.min(rect1.right, rect2.right); var width = right - left; var height = bottom - top; return (width >= 0 && height >= 0) && { top: top, bottom: bottom, left: left, right: right, width: width, height: height }; }
[ "function", "computeRectIntersection", "(", "rect1", ",", "rect2", ")", "{", "var", "top", "=", "Math", ".", "max", "(", "rect1", ".", "top", ",", "rect2", ".", "top", ")", ";", "var", "bottom", "=", "Math", ".", "min", "(", "rect1", ".", "bottom", ",", "rect2", ".", "bottom", ")", ";", "var", "left", "=", "Math", ".", "max", "(", "rect1", ".", "left", ",", "rect2", ".", "left", ")", ";", "var", "right", "=", "Math", ".", "min", "(", "rect1", ".", "right", ",", "rect2", ".", "right", ")", ";", "var", "width", "=", "right", "-", "left", ";", "var", "height", "=", "bottom", "-", "top", ";", "return", "(", "width", ">=", "0", "&&", "height", ">=", "0", ")", "&&", "{", "top", ":", "top", ",", "bottom", ":", "bottom", ",", "left", ":", "left", ",", "right", ":", "right", ",", "width", ":", "width", ",", "height", ":", "height", "}", ";", "}" ]
Returns the intersection between two rect objects. @param {Object} rect1 The first rect. @param {Object} rect2 The second rect. @return {?Object} The intersection rect or undefined if no intersection is found.
[ "Returns", "the", "intersection", "between", "two", "rect", "objects", "." ]
b17d38a69fd006f22d5864ce27caa85a012ca4dd
https://github.com/wildhaber/gluebert/blob/b17d38a69fd006f22d5864ce27caa85a012ca4dd/src/polyfills/resources/IntersectionObserverPolyfill.js#L612-L628
train
wildhaber/gluebert
src/polyfills/resources/IntersectionObserverPolyfill.js
getBoundingClientRect
function getBoundingClientRect(el) { var rect; try { rect = el.getBoundingClientRect(); } catch (err) { // Ignore Windows 7 IE11 "Unspecified error" // https://github.com/WICG/IntersectionObserver/pull/205 } if (!rect) return getEmptyRect(); // Older IE if (!(rect.width && rect.height)) { rect = { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.right - rect.left, height: rect.bottom - rect.top }; } return rect; }
javascript
function getBoundingClientRect(el) { var rect; try { rect = el.getBoundingClientRect(); } catch (err) { // Ignore Windows 7 IE11 "Unspecified error" // https://github.com/WICG/IntersectionObserver/pull/205 } if (!rect) return getEmptyRect(); // Older IE if (!(rect.width && rect.height)) { rect = { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.right - rect.left, height: rect.bottom - rect.top }; } return rect; }
[ "function", "getBoundingClientRect", "(", "el", ")", "{", "var", "rect", ";", "try", "{", "rect", "=", "el", ".", "getBoundingClientRect", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "}", "if", "(", "!", "rect", ")", "return", "getEmptyRect", "(", ")", ";", "if", "(", "!", "(", "rect", ".", "width", "&&", "rect", ".", "height", ")", ")", "{", "rect", "=", "{", "top", ":", "rect", ".", "top", ",", "right", ":", "rect", ".", "right", ",", "bottom", ":", "rect", ".", "bottom", ",", "left", ":", "rect", ".", "left", ",", "width", ":", "rect", ".", "right", "-", "rect", ".", "left", ",", "height", ":", "rect", ".", "bottom", "-", "rect", ".", "top", "}", ";", "}", "return", "rect", ";", "}" ]
Shims the native getBoundingClientRect for compatibility with older IE. @param {Element} el The element whose bounding rect to get. @return {Object} The (possibly shimmed) rect of the element.
[ "Shims", "the", "native", "getBoundingClientRect", "for", "compatibility", "with", "older", "IE", "." ]
b17d38a69fd006f22d5864ce27caa85a012ca4dd
https://github.com/wildhaber/gluebert/blob/b17d38a69fd006f22d5864ce27caa85a012ca4dd/src/polyfills/resources/IntersectionObserverPolyfill.js#L636-L660
train
wildhaber/gluebert
src/polyfills/resources/IntersectionObserverPolyfill.js
getParentNode
function getParentNode(node) { var parent = node.parentNode; if (parent && parent.nodeType == 11 && parent.host) { // If the parent is a shadow root, return the host element. return parent.host; } return parent; }
javascript
function getParentNode(node) { var parent = node.parentNode; if (parent && parent.nodeType == 11 && parent.host) { // If the parent is a shadow root, return the host element. return parent.host; } return parent; }
[ "function", "getParentNode", "(", "node", ")", "{", "var", "parent", "=", "node", ".", "parentNode", ";", "if", "(", "parent", "&&", "parent", ".", "nodeType", "==", "11", "&&", "parent", ".", "host", ")", "{", "return", "parent", ".", "host", ";", "}", "return", "parent", ";", "}" ]
Gets the parent node of an element or its host element if the parent node is a shadow root. @param {Node} node The node whose parent to get. @return {Node|null} The parent node or null if no parent exists.
[ "Gets", "the", "parent", "node", "of", "an", "element", "or", "its", "host", "element", "if", "the", "parent", "node", "is", "a", "shadow", "root", "." ]
b17d38a69fd006f22d5864ce27caa85a012ca4dd
https://github.com/wildhaber/gluebert/blob/b17d38a69fd006f22d5864ce27caa85a012ca4dd/src/polyfills/resources/IntersectionObserverPolyfill.js#L703-L711
train
TeaEntityLab/fpEs
fp.js
compact
function compact(list,typ) { if(arguments.length === 1) { if (Array.isArray(list)) { // if the only one param is an array return list.filter(x=>x); } else { // Curry it manually typ = list; return function (list) {return compact(list, typ)}; } } return list.filter(x=> typeof x === typeof typ); }
javascript
function compact(list,typ) { if(arguments.length === 1) { if (Array.isArray(list)) { // if the only one param is an array return list.filter(x=>x); } else { // Curry it manually typ = list; return function (list) {return compact(list, typ)}; } } return list.filter(x=> typeof x === typeof typ); }
[ "function", "compact", "(", "list", ",", "typ", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "if", "(", "Array", ".", "isArray", "(", "list", ")", ")", "{", "return", "list", ".", "filter", "(", "x", "=>", "x", ")", ";", "}", "else", "{", "typ", "=", "list", ";", "return", "function", "(", "list", ")", "{", "return", "compact", "(", "list", ",", "typ", ")", "}", ";", "}", "}", "return", "list", ".", "filter", "(", "x", "=>", "typeof", "x", "===", "typeof", "typ", ")", ";", "}" ]
Returns truthy values from an array. When typ is supplied, returns new array of specified type
[ "Returns", "truthy", "values", "from", "an", "array", ".", "When", "typ", "is", "supplied", "returns", "new", "array", "of", "specified", "type" ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L191-L203
train
TeaEntityLab/fpEs
fp.js
drop
function drop(list,dropCount=1,direction="left",fn=null) { // If the first argument is not kind of `array`-like. if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => drop(list, ...args); } if(dropCount === 0 && !fn) { return Array.prototype.slice.call(list, 0) }; if(arguments.length === 1 || direction === "left") { if (!fn) { return Array.prototype.slice.call(list, +dropCount); } return (Array.prototype.slice.call(list, +dropCount)).filter(x=>fn(x)); } if(direction === "right"){ if(!fn) { return Array.prototype.slice.call(list, 0, list.length-(+dropCount)); } if(dropCount === 0) {return (Array.prototype.slice.call(list, 0)).filter(x=>fn(x))}; return (Array.prototype.slice.call(list, 0, list.length-(+dropCount))).filter(x=>fn(x)); } }
javascript
function drop(list,dropCount=1,direction="left",fn=null) { // If the first argument is not kind of `array`-like. if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => drop(list, ...args); } if(dropCount === 0 && !fn) { return Array.prototype.slice.call(list, 0) }; if(arguments.length === 1 || direction === "left") { if (!fn) { return Array.prototype.slice.call(list, +dropCount); } return (Array.prototype.slice.call(list, +dropCount)).filter(x=>fn(x)); } if(direction === "right"){ if(!fn) { return Array.prototype.slice.call(list, 0, list.length-(+dropCount)); } if(dropCount === 0) {return (Array.prototype.slice.call(list, 0)).filter(x=>fn(x))}; return (Array.prototype.slice.call(list, 0, list.length-(+dropCount))).filter(x=>fn(x)); } }
[ "function", "drop", "(", "list", ",", "dropCount", "=", "1", ",", "direction", "=", "\"left\"", ",", "fn", "=", "null", ")", "{", "if", "(", "!", "(", "list", "&&", "Array", ".", "isArray", "(", "list", ")", ")", ")", "{", "let", "args", "=", "arguments", ";", "return", "(", "list", ")", "=>", "drop", "(", "list", ",", "...", "args", ")", ";", "}", "if", "(", "dropCount", "===", "0", "&&", "!", "fn", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "list", ",", "0", ")", "}", ";", "if", "(", "arguments", ".", "length", "===", "1", "||", "direction", "===", "\"left\"", ")", "{", "if", "(", "!", "fn", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "list", ",", "+", "dropCount", ")", ";", "}", "return", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "list", ",", "+", "dropCount", ")", ")", ".", "filter", "(", "x", "=>", "fn", "(", "x", ")", ")", ";", "}", "if", "(", "direction", "===", "\"right\"", ")", "{", "if", "(", "!", "fn", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "list", ",", "0", ",", "list", ".", "length", "-", "(", "+", "dropCount", ")", ")", ";", "}", "if", "(", "dropCount", "===", "0", ")", "{", "return", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "list", ",", "0", ")", ")", ".", "filter", "(", "x", "=>", "fn", "(", "x", ")", ")", "}", ";", "return", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "list", ",", "0", ",", "list", ".", "length", "-", "(", "+", "dropCount", ")", ")", ")", ".", "filter", "(", "x", "=>", "fn", "(", "x", ")", ")", ";", "}", "}" ]
Drops specified number of values from array either through left or right. Uses passed in function to filter remaining array after values dropped. Default dropCount = 1
[ "Drops", "specified", "number", "of", "values", "from", "array", "either", "through", "left", "or", "right", ".", "Uses", "passed", "in", "function", "to", "filter", "remaining", "array", "after", "values", "dropped", ".", "Default", "dropCount", "=", "1" ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L241-L269
train
TeaEntityLab/fpEs
fp.js
fill
function fill(list, value, startIndex=0, endIndex=list.length){ if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => fill(list, ...args); } return Array(...list).map((x,i)=> { if(i>= startIndex && i <= endIndex) { return x=value; } else { return x; } }); }
javascript
function fill(list, value, startIndex=0, endIndex=list.length){ if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => fill(list, ...args); } return Array(...list).map((x,i)=> { if(i>= startIndex && i <= endIndex) { return x=value; } else { return x; } }); }
[ "function", "fill", "(", "list", ",", "value", ",", "startIndex", "=", "0", ",", "endIndex", "=", "list", ".", "length", ")", "{", "if", "(", "!", "(", "list", "&&", "Array", ".", "isArray", "(", "list", ")", ")", ")", "{", "let", "args", "=", "arguments", ";", "return", "(", "list", ")", "=>", "fill", "(", "list", ",", "...", "args", ")", ";", "}", "return", "Array", "(", "...", "list", ")", ".", "map", "(", "(", "x", ",", "i", ")", "=>", "{", "if", "(", "i", ">=", "startIndex", "&&", "i", "<=", "endIndex", ")", "{", "return", "x", "=", "value", ";", "}", "else", "{", "return", "x", ";", "}", "}", ")", ";", "}" ]
Fills array using specified values. Can optionally pass in start and index of array to fill. Default startIndex = 0. Default endIndex = length of array.
[ "Fills", "array", "using", "specified", "values", ".", "Can", "optionally", "pass", "in", "start", "and", "index", "of", "array", "to", "fill", ".", "Default", "startIndex", "=", "0", ".", "Default", "endIndex", "=", "length", "of", "array", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L275-L289
train
TeaEntityLab/fpEs
fp.js
function (...values) { let list = []; let {main, follower} = reuseables.getMainAndFollower(values); main.forEach(x=>{ if(list.indexOf(x) ==-1) { if(follower.indexOf(x) >=0) { if(list[x] ==undefined) list.push(x) } } }) return list; }
javascript
function (...values) { let list = []; let {main, follower} = reuseables.getMainAndFollower(values); main.forEach(x=>{ if(list.indexOf(x) ==-1) { if(follower.indexOf(x) >=0) { if(list[x] ==undefined) list.push(x) } } }) return list; }
[ "function", "(", "...", "values", ")", "{", "let", "list", "=", "[", "]", ";", "let", "{", "main", ",", "follower", "}", "=", "reuseables", ".", "getMainAndFollower", "(", "values", ")", ";", "main", ".", "forEach", "(", "x", "=>", "{", "if", "(", "list", ".", "indexOf", "(", "x", ")", "==", "-", "1", ")", "{", "if", "(", "follower", ".", "indexOf", "(", "x", ")", ">=", "0", ")", "{", "if", "(", "list", "[", "x", "]", "==", "undefined", ")", "list", ".", "push", "(", "x", ")", "}", "}", "}", ")", "return", "list", ";", "}" ]
Returns values in two comparing arrays without repetition. Arrangement of resulting array is determined by main array. @param 1st Any number of individual arrays @param 2nd {number} Position number of array to be used as main @param 3rd {number} Position number of to be used as follower @returns values found in both arrays
[ "Returns", "values", "in", "two", "comparing", "arrays", "without", "repetition", ".", "Arrangement", "of", "resulting", "array", "is", "determined", "by", "main", "array", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L363-L374
train
TeaEntityLab/fpEs
fp.js
join
function join(joiner, ...values) { if (values.length > 0) { return concat([],...values).join(joiner); } // Manually currying return (...values) => join(joiner, ...values); }
javascript
function join(joiner, ...values) { if (values.length > 0) { return concat([],...values).join(joiner); } // Manually currying return (...values) => join(joiner, ...values); }
[ "function", "join", "(", "joiner", ",", "...", "values", ")", "{", "if", "(", "values", ".", "length", ">", "0", ")", "{", "return", "concat", "(", "[", "]", ",", "...", "values", ")", ".", "join", "(", "joiner", ")", ";", "}", "return", "(", "...", "values", ")", "=>", "join", "(", "joiner", ",", "...", "values", ")", ";", "}" ]
Converts array elements to string joined by specified joiner. @param joiner Joins array elements @param values different individual arrays
[ "Converts", "array", "elements", "to", "string", "joined", "by", "specified", "joiner", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L380-L387
train
TeaEntityLab/fpEs
fp.js
nth
function nth(list, indexNum) { if (arguments.length == 1) { // Manually currying indexNum = list; return (list) => nth(list, indexNum); } if(indexNum >= 0) { return list[+indexNum] }; return [...list].reverse()[list.length+indexNum]; }
javascript
function nth(list, indexNum) { if (arguments.length == 1) { // Manually currying indexNum = list; return (list) => nth(list, indexNum); } if(indexNum >= 0) { return list[+indexNum] }; return [...list].reverse()[list.length+indexNum]; }
[ "function", "nth", "(", "list", ",", "indexNum", ")", "{", "if", "(", "arguments", ".", "length", "==", "1", ")", "{", "indexNum", "=", "list", ";", "return", "(", "list", ")", "=>", "nth", "(", "list", ",", "indexNum", ")", ";", "}", "if", "(", "indexNum", ">=", "0", ")", "{", "return", "list", "[", "+", "indexNum", "]", "}", ";", "return", "[", "...", "list", "]", ".", "reverse", "(", ")", "[", "list", ".", "length", "+", "indexNum", "]", ";", "}" ]
Returns the nth value at the specified index. If index is negative, it returns value starting from the right @param list the array to be operated on @param indexNum the index number of the value to be retrieved
[ "Returns", "the", "nth", "value", "at", "the", "specified", "index", ".", "If", "index", "is", "negative", "it", "returns", "value", "starting", "from", "the", "right" ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L394-L405
train
TeaEntityLab/fpEs
fp.js
sortedIndex
function sortedIndex(list, value, valueIndex) { if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => sortedIndex(list, ...args); } return reuseables.sorter(list, value, valueIndex); }
javascript
function sortedIndex(list, value, valueIndex) { if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => sortedIndex(list, ...args); } return reuseables.sorter(list, value, valueIndex); }
[ "function", "sortedIndex", "(", "list", ",", "value", ",", "valueIndex", ")", "{", "if", "(", "!", "(", "list", "&&", "Array", ".", "isArray", "(", "list", ")", ")", ")", "{", "let", "args", "=", "arguments", ";", "return", "(", "list", ")", "=>", "sortedIndex", "(", "list", ",", "...", "args", ")", ";", "}", "return", "reuseables", ".", "sorter", "(", "list", ",", "value", ",", "valueIndex", ")", ";", "}" ]
Returns the lowest index number of a value if it is to be added to an array. @param list {Array} array that value will be added to @param value value to evaluate @param valueIndex {string} accepts either 'first' or 'last'. Specifies either to return the first or last index if the value is to be added to the array. Default is 'first' @returns {number}
[ "Returns", "the", "lowest", "index", "number", "of", "a", "value", "if", "it", "is", "to", "be", "added", "to", "an", "array", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L424-L432
train
TeaEntityLab/fpEs
fp.js
function(list){ const listNoDuplicate = difference([],list); if(typeof list[0] == "number") { return listNoDuplicate.sort((a,b)=>a-b); } return listNoDuplicate.sort(); }
javascript
function(list){ const listNoDuplicate = difference([],list); if(typeof list[0] == "number") { return listNoDuplicate.sort((a,b)=>a-b); } return listNoDuplicate.sort(); }
[ "function", "(", "list", ")", "{", "const", "listNoDuplicate", "=", "difference", "(", "[", "]", ",", "list", ")", ";", "if", "(", "typeof", "list", "[", "0", "]", "==", "\"number\"", ")", "{", "return", "listNoDuplicate", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", "-", "b", ")", ";", "}", "return", "listNoDuplicate", ".", "sort", "(", ")", ";", "}" ]
Returns sorted array without duplicates @param list {Array} array to be sorted @returns {Array} sorted array
[ "Returns", "sorted", "array", "without", "duplicates" ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L438-L445
train
TeaEntityLab/fpEs
fp.js
union
function union(list1, list2, duplicate=false) { if ( arguments.length < 2 ) { // Manually currying let args1 = arguments; return (...args2) => union(...args1, ...args2); } else if (arguments.length === 2 && (! Array.isArray(list2))) { // curring union(_, list, duplicate) cases // Manually currying let args = arguments; return (list) => union(list, ...args); } if(duplicate) { return differenceWithDup([],list1.concat(list2)); } return difference([],list1.concat(list2)); }
javascript
function union(list1, list2, duplicate=false) { if ( arguments.length < 2 ) { // Manually currying let args1 = arguments; return (...args2) => union(...args1, ...args2); } else if (arguments.length === 2 && (! Array.isArray(list2))) { // curring union(_, list, duplicate) cases // Manually currying let args = arguments; return (list) => union(list, ...args); } if(duplicate) { return differenceWithDup([],list1.concat(list2)); } return difference([],list1.concat(list2)); }
[ "function", "union", "(", "list1", ",", "list2", ",", "duplicate", "=", "false", ")", "{", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "let", "args1", "=", "arguments", ";", "return", "(", "...", "args2", ")", "=>", "union", "(", "...", "args1", ",", "...", "args2", ")", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "2", "&&", "(", "!", "Array", ".", "isArray", "(", "list2", ")", ")", ")", "{", "let", "args", "=", "arguments", ";", "return", "(", "list", ")", "=>", "union", "(", "list", ",", "...", "args", ")", ";", "}", "if", "(", "duplicate", ")", "{", "return", "differenceWithDup", "(", "[", "]", ",", "list1", ".", "concat", "(", "list2", ")", ")", ";", "}", "return", "difference", "(", "[", "]", ",", "list1", ".", "concat", "(", "list2", ")", ")", ";", "}" ]
Returns unified array with or without duplicates. @param list1 {Array} first array @param list2 {Array} second array @param duplicate {boolean} boolean to include duplicates @returns {Array} array with/without duplicates
[ "Returns", "unified", "array", "with", "or", "without", "duplicates", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L453-L470
train
jaruba/multipass-torrent
lib/indexer.js
merge
function merge(torrents) { // NOTE: here, on the merge logic, we can set properties that should always be set // Or just rip out the model logic from LinvoDB into a separate module and use it return torrents.reduce(function(a, b) { return _.merge(a, b, function(x, y) { // this is for the files array, and we want more complicated behaviour if (_.isArray(a) && _.isArray(b)) return b; }) }) }
javascript
function merge(torrents) { // NOTE: here, on the merge logic, we can set properties that should always be set // Or just rip out the model logic from LinvoDB into a separate module and use it return torrents.reduce(function(a, b) { return _.merge(a, b, function(x, y) { // this is for the files array, and we want more complicated behaviour if (_.isArray(a) && _.isArray(b)) return b; }) }) }
[ "function", "merge", "(", "torrents", ")", "{", "return", "torrents", ".", "reduce", "(", "function", "(", "a", ",", "b", ")", "{", "return", "_", ".", "merge", "(", "a", ",", "b", ",", "function", "(", "x", ",", "y", ")", "{", "if", "(", "_", ".", "isArray", "(", "a", ")", "&&", "_", ".", "isArray", "(", "b", ")", ")", "return", "b", ";", "}", ")", "}", ")", "}" ]
Conflict resolution logic is here
[ "Conflict", "resolution", "logic", "is", "here" ]
3cfa821760d956d3d104af04365c2a9d85226a9f
https://github.com/jaruba/multipass-torrent/blob/3cfa821760d956d3d104af04365c2a9d85226a9f/lib/indexer.js#L106-L116
train
cody-greene/scssify
lib/index.js
through
function through(transform, flush, objectMode) { const stream = new TransformStream({objectMode}) stream._transform = transform || pass if (flush) stream._flush = flush return stream }
javascript
function through(transform, flush, objectMode) { const stream = new TransformStream({objectMode}) stream._transform = transform || pass if (flush) stream._flush = flush return stream }
[ "function", "through", "(", "transform", ",", "flush", ",", "objectMode", ")", "{", "const", "stream", "=", "new", "TransformStream", "(", "{", "objectMode", "}", ")", "stream", ".", "_transform", "=", "transform", "||", "pass", "if", "(", "flush", ")", "stream", ".", "_flush", "=", "flush", "return", "stream", "}" ]
Quickly create a object-mode duplex stream @param {function?} transform(chunk, encoding, done) @param {function?} flush(done) @param {boolean} objectMode @return {DuplexStream}
[ "Quickly", "create", "a", "object", "-", "mode", "duplex", "stream" ]
1db5ea75e0039ba17fc1c898e3a4ea6c32a655bf
https://github.com/cody-greene/scssify/blob/1db5ea75e0039ba17fc1c898e3a4ea6c32a655bf/lib/index.js#L143-L148
train
eddyystop/feathers-service-verify-reset
src/index.js
patchUser
function patchUser(user, patchToUser) { return users.patch(user.id || user._id, patchToUser, {}) // needs users from closure .then(() => Object.assign(user, patchToUser)); }
javascript
function patchUser(user, patchToUser) { return users.patch(user.id || user._id, patchToUser, {}) // needs users from closure .then(() => Object.assign(user, patchToUser)); }
[ "function", "patchUser", "(", "user", ",", "patchToUser", ")", "{", "return", "users", ".", "patch", "(", "user", ".", "id", "||", "user", ".", "_id", ",", "patchToUser", ",", "{", "}", ")", ".", "then", "(", "(", ")", "=>", "Object", ".", "assign", "(", "user", ",", "patchToUser", ")", ")", ";", "}" ]
Helpers requiring this closure
[ "Helpers", "requiring", "this", "closure" ]
dee9722dda8642ac1169120f7fe305684eb616c0
https://github.com/eddyystop/feathers-service-verify-reset/blob/dee9722dda8642ac1169120f7fe305684eb616c0/src/index.js#L724-L727
train
SchizoDuckie/CreateReadUpdateDelete.js
cli/entitybuilder.js
injectForeignFields
function injectForeignFields(targetEntity) { switch (type) { case '1:1': return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) { fields.push(entity.primary); entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields)); return targetEntity; }); case '1:many': break; case 'many:1': return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) { fields.push(entity.primary); entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields)); return targetEntity; }); case 'many:many': break; } }
javascript
function injectForeignFields(targetEntity) { switch (type) { case '1:1': return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) { fields.push(entity.primary); entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields)); return targetEntity; }); case '1:many': break; case 'many:1': return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) { fields.push(entity.primary); entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields)); return targetEntity; }); case 'many:many': break; } }
[ "function", "injectForeignFields", "(", "targetEntity", ")", "{", "switch", "(", "type", ")", "{", "case", "'1:1'", ":", "return", "entityModifier", ".", "readEntityProperty", "(", "targetEntity", ",", "'fields'", ")", ".", "then", "(", "function", "(", "fields", ")", "{", "fields", ".", "push", "(", "entity", ".", "primary", ")", ";", "entityModifier", ".", "modifyEntityProperty", "(", "targetEntity", ",", "'fields'", ",", "JSON", ".", "stringify", "(", "fields", ")", ")", ";", "return", "targetEntity", ";", "}", ")", ";", "case", "'1:many'", ":", "break", ";", "case", "'many:1'", ":", "return", "entityModifier", ".", "readEntityProperty", "(", "targetEntity", ",", "'fields'", ")", ".", "then", "(", "function", "(", "fields", ")", "{", "fields", ".", "push", "(", "entity", ".", "primary", ")", ";", "entityModifier", ".", "modifyEntityProperty", "(", "targetEntity", ",", "'fields'", ",", "JSON", ".", "stringify", "(", "fields", ")", ")", ";", "return", "targetEntity", ";", "}", ")", ";", "case", "'many:many'", ":", "break", ";", "}", "}" ]
- find foreign entities to modify - inject foreign keys where needed - output changes to foreign entity
[ "-", "find", "foreign", "entities", "to", "modify", "-", "inject", "foreign", "keys", "where", "needed", "-", "output", "changes", "to", "foreign", "entity" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/entitybuilder.js#L69-L88
train
graphology/graphology-layout-forceatlas2
supervisor.js
FA2LayoutSupervisor
function FA2LayoutSupervisor(graph, params) { params = params || {}; // Validation if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2/worker: the given graph is not a valid graphology instance.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2/worker: ' + validationError.message); // Properties this.worker = new Worker(); this.graph = graph; this.settings = settings; this.matrices = null; this.running = false; this.killed = false; // Binding listeners this.handleMessage = this.handleMessage.bind(this); this.worker.addEventListener('message', this.handleMessage.bind(this)); }
javascript
function FA2LayoutSupervisor(graph, params) { params = params || {}; // Validation if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2/worker: the given graph is not a valid graphology instance.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2/worker: ' + validationError.message); // Properties this.worker = new Worker(); this.graph = graph; this.settings = settings; this.matrices = null; this.running = false; this.killed = false; // Binding listeners this.handleMessage = this.handleMessage.bind(this); this.worker.addEventListener('message', this.handleMessage.bind(this)); }
[ "function", "FA2LayoutSupervisor", "(", "graph", ",", "params", ")", "{", "params", "=", "params", "||", "{", "}", ";", "if", "(", "!", "isGraph", "(", "graph", ")", ")", "throw", "new", "Error", "(", "'graphology-layout-forceatlas2/worker: the given graph is not a valid graphology instance.'", ")", ";", "var", "settings", "=", "helpers", ".", "assign", "(", "{", "}", ",", "DEFAULT_SETTINGS", ",", "params", ".", "settings", ")", ",", "validationError", "=", "helpers", ".", "validateSettings", "(", "settings", ")", ";", "if", "(", "validationError", ")", "throw", "new", "Error", "(", "'graphology-layout-forceatlas2/worker: '", "+", "validationError", ".", "message", ")", ";", "this", ".", "worker", "=", "new", "Worker", "(", ")", ";", "this", ".", "graph", "=", "graph", ";", "this", ".", "settings", "=", "settings", ";", "this", ".", "matrices", "=", "null", ";", "this", ".", "running", "=", "false", ";", "this", ".", "killed", "=", "false", ";", "this", ".", "handleMessage", "=", "this", ".", "handleMessage", ".", "bind", "(", "this", ")", ";", "this", ".", "worker", ".", "addEventListener", "(", "'message'", ",", "this", ".", "handleMessage", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Class representing a FA2 layout run by a webworker. @constructor @param {Graph} graph - Target graph. @param {object|number} params - Parameters: @param {object} [settings] - Settings.
[ "Class", "representing", "a", "FA2", "layout", "run", "by", "a", "webworker", "." ]
87c8664603ab15f8aa0e7aeb4960b9425a2811e2
https://github.com/graphology/graphology-layout-forceatlas2/blob/87c8664603ab15f8aa0e7aeb4960b9425a2811e2/supervisor.js#L22-L48
train
lemire/StablePriorityQueue.js
StablePriorityQueue.js
StablePriorityQueue
function StablePriorityQueue(comparator) { this.array = []; this.size = 0; this.runningcounter = 0; this.compare = comparator || defaultcomparator; this.stable_compare = function(a, b) { var cmp = this.compare(a.value,b.value); return (cmp < 0) || ( (cmp == 0) && (a.counter < b.counter) ); } }
javascript
function StablePriorityQueue(comparator) { this.array = []; this.size = 0; this.runningcounter = 0; this.compare = comparator || defaultcomparator; this.stable_compare = function(a, b) { var cmp = this.compare(a.value,b.value); return (cmp < 0) || ( (cmp == 0) && (a.counter < b.counter) ); } }
[ "function", "StablePriorityQueue", "(", "comparator", ")", "{", "this", ".", "array", "=", "[", "]", ";", "this", ".", "size", "=", "0", ";", "this", ".", "runningcounter", "=", "0", ";", "this", ".", "compare", "=", "comparator", "||", "defaultcomparator", ";", "this", ".", "stable_compare", "=", "function", "(", "a", ",", "b", ")", "{", "var", "cmp", "=", "this", ".", "compare", "(", "a", ".", "value", ",", "b", ".", "value", ")", ";", "return", "(", "cmp", "<", "0", ")", "||", "(", "(", "cmp", "==", "0", ")", "&&", "(", "a", ".", "counter", "<", "b", ".", "counter", ")", ")", ";", "}", "}" ]
the provided comparator function should take a, b and return a negative number when a < b and equality when a == b
[ "the", "provided", "comparator", "function", "should", "take", "a", "b", "and", "return", "a", "negative", "number", "when", "a", "<", "b", "and", "equality", "when", "a", "==", "b" ]
4cd847cb93cae050f87b6dddba8d2252f947ac6d
https://github.com/lemire/StablePriorityQueue.js/blob/4cd847cb93cae050f87b6dddba8d2252f947ac6d/StablePriorityQueue.js#L36-L45
train
lemire/StablePriorityQueue.js
StablePriorityQueue.js
function () { // main code var x = new StablePriorityQueue(function (a, b) { return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0) ; }); x.add({name:"Jack", age:31}); x.add({name:"Anna", age:111}); x.add({name:"Jack", age:46}); x.add({name:"Jack", age:11}); x.add({name:"Abba", age:31}); x.add({name:"Abba", age:30}); while (!x.isEmpty()) { console.log(x.poll()); } x = new StablePriorityQueue(function(a, b) { return a.energy - b.energy; }); [{ name: 'player', energy: 10}, { name: 'monster1', energy: 10}, { name: 'monster2', energy: 10}, { name: 'monster3', energy: 10} ].forEach(function(o){ x.add(o); }) while (!x.isEmpty()) { console.log(x.poll()); } }
javascript
function () { // main code var x = new StablePriorityQueue(function (a, b) { return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0) ; }); x.add({name:"Jack", age:31}); x.add({name:"Anna", age:111}); x.add({name:"Jack", age:46}); x.add({name:"Jack", age:11}); x.add({name:"Abba", age:31}); x.add({name:"Abba", age:30}); while (!x.isEmpty()) { console.log(x.poll()); } x = new StablePriorityQueue(function(a, b) { return a.energy - b.energy; }); [{ name: 'player', energy: 10}, { name: 'monster1', energy: 10}, { name: 'monster2', energy: 10}, { name: 'monster3', energy: 10} ].forEach(function(o){ x.add(o); }) while (!x.isEmpty()) { console.log(x.poll()); } }
[ "function", "(", ")", "{", "var", "x", "=", "new", "StablePriorityQueue", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "name", "<", "b", ".", "name", "?", "-", "1", ":", "(", "a", ".", "name", ">", "b", ".", "name", "?", "1", ":", "0", ")", ";", "}", ")", ";", "x", ".", "add", "(", "{", "name", ":", "\"Jack\"", ",", "age", ":", "31", "}", ")", ";", "x", ".", "add", "(", "{", "name", ":", "\"Anna\"", ",", "age", ":", "111", "}", ")", ";", "x", ".", "add", "(", "{", "name", ":", "\"Jack\"", ",", "age", ":", "46", "}", ")", ";", "x", ".", "add", "(", "{", "name", ":", "\"Jack\"", ",", "age", ":", "11", "}", ")", ";", "x", ".", "add", "(", "{", "name", ":", "\"Abba\"", ",", "age", ":", "31", "}", ")", ";", "x", ".", "add", "(", "{", "name", ":", "\"Abba\"", ",", "age", ":", "30", "}", ")", ";", "while", "(", "!", "x", ".", "isEmpty", "(", ")", ")", "{", "console", ".", "log", "(", "x", ".", "poll", "(", ")", ")", ";", "}", "x", "=", "new", "StablePriorityQueue", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "energy", "-", "b", ".", "energy", ";", "}", ")", ";", "[", "{", "name", ":", "'player'", ",", "energy", ":", "10", "}", ",", "{", "name", ":", "'monster1'", ",", "energy", ":", "10", "}", ",", "{", "name", ":", "'monster2'", ",", "energy", ":", "10", "}", ",", "{", "name", ":", "'monster3'", ",", "energy", ":", "10", "}", "]", ".", "forEach", "(", "function", "(", "o", ")", "{", "x", ".", "add", "(", "o", ")", ";", "}", ")", "while", "(", "!", "x", ".", "isEmpty", "(", ")", ")", "{", "console", ".", "log", "(", "x", ".", "poll", "(", ")", ")", ";", "}", "}" ]
just for illustration purposes
[ "just", "for", "illustration", "purposes" ]
4cd847cb93cae050f87b6dddba8d2252f947ac6d
https://github.com/lemire/StablePriorityQueue.js/blob/4cd847cb93cae050f87b6dddba8d2252f947ac6d/StablePriorityQueue.js#L185-L213
train
FormidableLabs/express-winston-middleware
Gruntfile.js
function (obj) { var toc = [], tocTmpl = _.template("* [<%= heading %>](#<%= id %>)\n"), sectionTmpl = _.template("### <%= summary %>\n\n<%= body %>\n"); // Finesse comment markdown data. // Also, statefully create TOC. var sections = _.chain(obj) .filter(function (c) { return !c.isPrivate && !c.ignore && _.any(c.tags, function (t) { return t.type === "api" && t.visibility === "public"; }); }) .map(function (c) { // Add to TOC. toc.push(tocTmpl({ heading: c.description.summary, id: _headingId(c.description.summary) })); return sectionTmpl(c.description); }) .value() .join(""); return "\n" + toc.join("") + "\n" + sections; }
javascript
function (obj) { var toc = [], tocTmpl = _.template("* [<%= heading %>](#<%= id %>)\n"), sectionTmpl = _.template("### <%= summary %>\n\n<%= body %>\n"); // Finesse comment markdown data. // Also, statefully create TOC. var sections = _.chain(obj) .filter(function (c) { return !c.isPrivate && !c.ignore && _.any(c.tags, function (t) { return t.type === "api" && t.visibility === "public"; }); }) .map(function (c) { // Add to TOC. toc.push(tocTmpl({ heading: c.description.summary, id: _headingId(c.description.summary) })); return sectionTmpl(c.description); }) .value() .join(""); return "\n" + toc.join("") + "\n" + sections; }
[ "function", "(", "obj", ")", "{", "var", "toc", "=", "[", "]", ",", "tocTmpl", "=", "_", ".", "template", "(", "\"* [<%= heading %>](#<%= id %>)\\n\"", ")", ",", "\\n", ";", "sectionTmpl", "=", "_", ".", "template", "(", "\"### <%= summary %>\\n\\n<%= body %>\\n\"", ")", "\\n", "}" ]
Generate Markdown API snippets from dox object.
[ "Generate", "Markdown", "API", "snippets", "from", "dox", "object", "." ]
50714a16eaf191adfba03f00d0827e56ed4a30f9
https://github.com/FormidableLabs/express-winston-middleware/blob/50714a16eaf191adfba03f00d0827e56ed4a30f9/Gruntfile.js#L10-L36
train
graphology/graphology-layout-forceatlas2
index.js
abstractSynchronousLayout
function abstractSynchronousLayout(assign, graph, params) { if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2: the given graph is not a valid graphology instance.'); if (typeof params === 'number') params = {iterations: params}; var iterations = params.iterations; if (typeof iterations !== 'number') throw new Error('graphology-layout-forceatlas2: invalid number of iterations.'); if (iterations <= 0) throw new Error('graphology-layout-forceatlas2: you should provide a positive number of iterations.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2: ' + validationError.message); // Building matrices var matrices = helpers.graphToByteArrays(graph), i; // Iterating for (i = 0; i < iterations; i++) iterate(settings, matrices.nodes, matrices.edges); // Applying if (assign) { helpers.applyLayoutChanges(graph, matrices.nodes); return; } return helpers.collectLayoutChanges(graph, matrices.nodes); }
javascript
function abstractSynchronousLayout(assign, graph, params) { if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2: the given graph is not a valid graphology instance.'); if (typeof params === 'number') params = {iterations: params}; var iterations = params.iterations; if (typeof iterations !== 'number') throw new Error('graphology-layout-forceatlas2: invalid number of iterations.'); if (iterations <= 0) throw new Error('graphology-layout-forceatlas2: you should provide a positive number of iterations.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2: ' + validationError.message); // Building matrices var matrices = helpers.graphToByteArrays(graph), i; // Iterating for (i = 0; i < iterations; i++) iterate(settings, matrices.nodes, matrices.edges); // Applying if (assign) { helpers.applyLayoutChanges(graph, matrices.nodes); return; } return helpers.collectLayoutChanges(graph, matrices.nodes); }
[ "function", "abstractSynchronousLayout", "(", "assign", ",", "graph", ",", "params", ")", "{", "if", "(", "!", "isGraph", "(", "graph", ")", ")", "throw", "new", "Error", "(", "'graphology-layout-forceatlas2: the given graph is not a valid graphology instance.'", ")", ";", "if", "(", "typeof", "params", "===", "'number'", ")", "params", "=", "{", "iterations", ":", "params", "}", ";", "var", "iterations", "=", "params", ".", "iterations", ";", "if", "(", "typeof", "iterations", "!==", "'number'", ")", "throw", "new", "Error", "(", "'graphology-layout-forceatlas2: invalid number of iterations.'", ")", ";", "if", "(", "iterations", "<=", "0", ")", "throw", "new", "Error", "(", "'graphology-layout-forceatlas2: you should provide a positive number of iterations.'", ")", ";", "var", "settings", "=", "helpers", ".", "assign", "(", "{", "}", ",", "DEFAULT_SETTINGS", ",", "params", ".", "settings", ")", ",", "validationError", "=", "helpers", ".", "validateSettings", "(", "settings", ")", ";", "if", "(", "validationError", ")", "throw", "new", "Error", "(", "'graphology-layout-forceatlas2: '", "+", "validationError", ".", "message", ")", ";", "var", "matrices", "=", "helpers", ".", "graphToByteArrays", "(", "graph", ")", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "iterations", ";", "i", "++", ")", "iterate", "(", "settings", ",", "matrices", ".", "nodes", ",", "matrices", ".", "edges", ")", ";", "if", "(", "assign", ")", "{", "helpers", ".", "applyLayoutChanges", "(", "graph", ",", "matrices", ".", "nodes", ")", ";", "return", ";", "}", "return", "helpers", ".", "collectLayoutChanges", "(", "graph", ",", "matrices", ".", "nodes", ")", ";", "}" ]
Asbtract function used to run a certain number of iterations. @param {boolean} assign - Whether to assign positions. @param {Graph} graph - Target graph. @param {object|number} params - If number, params.iterations, else: @param {number} iterations - Number of iterations. @param {object} [settings] - Settings. @return {object|undefined}
[ "Asbtract", "function", "used", "to", "run", "a", "certain", "number", "of", "iterations", "." ]
87c8664603ab15f8aa0e7aeb4960b9425a2811e2
https://github.com/graphology/graphology-layout-forceatlas2/blob/87c8664603ab15f8aa0e7aeb4960b9425a2811e2/index.js#L23-L60
train