id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
21,900
canalplus/canal-js-utils
rx-lite.js
Subject
function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; }
javascript
function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; }
[ "function", "Subject", "(", ")", "{", "__super__", ".", "call", "(", "this", ",", "subscribe", ")", ";", "this", ".", "isDisposed", "=", "false", ",", "this", ".", "isStopped", "=", "false", ",", "this", ".", "observers", "=", "[", "]", ";", "this", ".", "hasError", "=", "false", ";", "}" ]
Creates a subject.
[ "Creates", "a", "subject", "." ]
671b1229230083148c11177aabd909fa7d275b2b
https://github.com/canalplus/canal-js-utils/blob/671b1229230083148c11177aabd909fa7d275b2b/rx-lite.js#L5204-L5210
21,901
canalplus/canal-js-utils
rx-lite.js
BehaviorSubject
function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; }
javascript
function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; }
[ "function", "BehaviorSubject", "(", "value", ")", "{", "__super__", ".", "call", "(", "this", ",", "subscribe", ")", ";", "this", ".", "value", "=", "value", ",", "this", ".", "observers", "=", "[", "]", ",", "this", ".", "isDisposed", "=", "false", ",", "this", ".", "isStopped", "=", "false", ",", "this", ".", "hasError", "=", "false", ";", "}" ]
Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
[ "Initializes", "a", "new", "instance", "of", "the", "BehaviorSubject", "class", "which", "creates", "a", "subject", "that", "caches", "its", "last", "value", "and", "starts", "with", "the", "specified", "value", "." ]
671b1229230083148c11177aabd909fa7d275b2b
https://github.com/canalplus/canal-js-utils/blob/671b1229230083148c11177aabd909fa7d275b2b/rx-lite.js#L5455-L5462
21,902
canalplus/canal-js-utils
rx-lite.js
ReplaySubject
function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); }
javascript
function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); }
[ "function", "ReplaySubject", "(", "bufferSize", ",", "windowSize", ",", "scheduler", ")", "{", "this", ".", "bufferSize", "=", "bufferSize", "==", "null", "?", "maxSafeInteger", ":", "bufferSize", ";", "this", ".", "windowSize", "=", "windowSize", "==", "null", "?", "maxSafeInteger", ":", "windowSize", ";", "this", ".", "scheduler", "=", "scheduler", "||", "currentThreadScheduler", ";", "this", ".", "q", "=", "[", "]", ";", "this", ".", "observers", "=", "[", "]", ";", "this", ".", "isStopped", "=", "false", ";", "this", ".", "isDisposed", "=", "false", ";", "this", ".", "hasError", "=", "false", ";", "this", ".", "error", "=", "null", ";", "__super__", ".", "call", "(", "this", ",", "subscribe", ")", ";", "}" ]
Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. @param {Number} [bufferSize] Maximum element count of the replay buffer. @param {Number} [windowSize] Maximum time length of the replay buffer. @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
[ "Initializes", "a", "new", "instance", "of", "the", "ReplaySubject", "class", "with", "the", "specified", "buffer", "size", "window", "size", "and", "scheduler", "." ]
671b1229230083148c11177aabd909fa7d275b2b
https://github.com/canalplus/canal-js-utils/blob/671b1229230083148c11177aabd909fa7d275b2b/rx-lite.js#L5584-L5595
21,903
stackgl/gl-toy
index.js
toy
function toy(frag, cb) { const canvas = document.body.appendChild(document.createElement('canvas')) const gl = context(canvas, render) const shader = Shader(gl, vert, frag) const fitter = fit(canvas) render.update = update render.resize = fitter render.shader = shader render.canvas = canvas render.gl = gl window.addEventListener('resize', fitter, false) return render function render() { const width = gl.drawingBufferWidth const height = gl.drawingBufferHeight gl.viewport(0, 0, width, height) shader.bind() cb(gl, shader) triangle(gl) } function update(frag) { shader.update(vert, frag) } }
javascript
function toy(frag, cb) { const canvas = document.body.appendChild(document.createElement('canvas')) const gl = context(canvas, render) const shader = Shader(gl, vert, frag) const fitter = fit(canvas) render.update = update render.resize = fitter render.shader = shader render.canvas = canvas render.gl = gl window.addEventListener('resize', fitter, false) return render function render() { const width = gl.drawingBufferWidth const height = gl.drawingBufferHeight gl.viewport(0, 0, width, height) shader.bind() cb(gl, shader) triangle(gl) } function update(frag) { shader.update(vert, frag) } }
[ "function", "toy", "(", "frag", ",", "cb", ")", "{", "const", "canvas", "=", "document", ".", "body", ".", "appendChild", "(", "document", ".", "createElement", "(", "'canvas'", ")", ")", "const", "gl", "=", "context", "(", "canvas", ",", "render", ")", "const", "shader", "=", "Shader", "(", "gl", ",", "vert", ",", "frag", ")", "const", "fitter", "=", "fit", "(", "canvas", ")", "render", ".", "update", "=", "update", "render", ".", "resize", "=", "fitter", "render", ".", "shader", "=", "shader", "render", ".", "canvas", "=", "canvas", "render", ".", "gl", "=", "gl", "window", ".", "addEventListener", "(", "'resize'", ",", "fitter", ",", "false", ")", "return", "render", "function", "render", "(", ")", "{", "const", "width", "=", "gl", ".", "drawingBufferWidth", "const", "height", "=", "gl", ".", "drawingBufferHeight", "gl", ".", "viewport", "(", "0", ",", "0", ",", "width", ",", "height", ")", "shader", ".", "bind", "(", ")", "cb", "(", "gl", ",", "shader", ")", "triangle", "(", "gl", ")", "}", "function", "update", "(", "frag", ")", "{", "shader", ".", "update", "(", "vert", ",", "frag", ")", "}", "}" ]
String -> WebGLRenderingContext, Shader
[ "String", "-", ">", "WebGLRenderingContext", "Shader" ]
152e2f59e15fda14217a87d7f6ec953ccb127323
https://github.com/stackgl/gl-toy/blob/152e2f59e15fda14217a87d7f6ec953ccb127323/index.js#L19-L47
21,904
DeMille/dnssd.js
lib/hash.js
stringify
function stringify(val) { if (typeof val === 'string') return JSON.stringify(val.toLowerCase()); if (Array.isArray(val)) return '[' + val.map(stringify) + ']'; if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && '' + val === '[object Object]') { var str = Object.keys(val).sort().map(function (key) { return stringify(key) + ':' + stringify(val[key]); }).join(','); return '{' + str + '}'; } return JSON.stringify(val); }
javascript
function stringify(val) { if (typeof val === 'string') return JSON.stringify(val.toLowerCase()); if (Array.isArray(val)) return '[' + val.map(stringify) + ']'; if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && '' + val === '[object Object]') { var str = Object.keys(val).sort().map(function (key) { return stringify(key) + ':' + stringify(val[key]); }).join(','); return '{' + str + '}'; } return JSON.stringify(val); }
[ "function", "stringify", "(", "val", ")", "{", "if", "(", "typeof", "val", "===", "'string'", ")", "return", "JSON", ".", "stringify", "(", "val", ".", "toLowerCase", "(", ")", ")", ";", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "return", "'['", "+", "val", ".", "map", "(", "stringify", ")", "+", "']'", ";", "if", "(", "(", "typeof", "val", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "val", ")", ")", "===", "'object'", "&&", "''", "+", "val", "===", "'[object Object]'", ")", "{", "var", "str", "=", "Object", ".", "keys", "(", "val", ")", ".", "sort", "(", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "stringify", "(", "key", ")", "+", "':'", "+", "stringify", "(", "val", "[", "key", "]", ")", ";", "}", ")", ".", "join", "(", "','", ")", ";", "return", "'{'", "+", "str", "+", "'}'", ";", "}", "return", "JSON", ".", "stringify", "(", "val", ")", ";", "}" ]
Deterministic JSON.stringify for resource record stuff Object keys are sorted so strings are always the same independent of what order properties were added in. Strings are lowercased because record names, TXT keys, SRV target names, etc. need to be compared case-insensitively. @param {*} val @return {string}
[ "Deterministic", "JSON", ".", "stringify", "for", "resource", "record", "stuff" ]
d66f0dd6c62300f3a2df38186c23c6ffacc02afc
https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/lib/hash.js#L16-L30
21,905
DeMille/dnssd.js
src/Browser.js
Browser
function Browser(type, options = {}) { if (!(this instanceof Browser)) return new Browser(type, options); EventEmitter.call(this); // convert argument ServiceType to validate it (might throw) const serviceType = (type instanceof ServiceType) ? type : new ServiceType(type); // can't search for multiple subtypes at the same time if (serviceType.subtypes.length > 1) { throw new Error('Too many subtypes. Can only browse one at a time.'); } this._id = serviceType.toString(); debug(`Creating new browser for "${this._id}"`); this._resolvers = {}; // active service resolvers (when browsing services) this._serviceTypes = {}; // active service types (when browsing service types) this._protocol = serviceType.protocol; this._serviceName = serviceType.name; this._subtype = serviceType.subtypes[0]; this._isWildcard = serviceType.isEnumerator; this._domain = options.domain || 'local.'; this._maintain = ('maintain' in options) ? options.maintain : true; this._resolve = ('resolve' in options) ? options.resolve : true; this._interface = NetworkInterface.get(options.interface); this._state = STATE.STOPPED; // emitter used to stop child queries instead of holding onto a reference // for each one this._offswitch = new EventEmitter(); }
javascript
function Browser(type, options = {}) { if (!(this instanceof Browser)) return new Browser(type, options); EventEmitter.call(this); // convert argument ServiceType to validate it (might throw) const serviceType = (type instanceof ServiceType) ? type : new ServiceType(type); // can't search for multiple subtypes at the same time if (serviceType.subtypes.length > 1) { throw new Error('Too many subtypes. Can only browse one at a time.'); } this._id = serviceType.toString(); debug(`Creating new browser for "${this._id}"`); this._resolvers = {}; // active service resolvers (when browsing services) this._serviceTypes = {}; // active service types (when browsing service types) this._protocol = serviceType.protocol; this._serviceName = serviceType.name; this._subtype = serviceType.subtypes[0]; this._isWildcard = serviceType.isEnumerator; this._domain = options.domain || 'local.'; this._maintain = ('maintain' in options) ? options.maintain : true; this._resolve = ('resolve' in options) ? options.resolve : true; this._interface = NetworkInterface.get(options.interface); this._state = STATE.STOPPED; // emitter used to stop child queries instead of holding onto a reference // for each one this._offswitch = new EventEmitter(); }
[ "function", "Browser", "(", "type", ",", "options", "=", "{", "}", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Browser", ")", ")", "return", "new", "Browser", "(", "type", ",", "options", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "// convert argument ServiceType to validate it (might throw)", "const", "serviceType", "=", "(", "type", "instanceof", "ServiceType", ")", "?", "type", ":", "new", "ServiceType", "(", "type", ")", ";", "// can't search for multiple subtypes at the same time", "if", "(", "serviceType", ".", "subtypes", ".", "length", ">", "1", ")", "{", "throw", "new", "Error", "(", "'Too many subtypes. Can only browse one at a time.'", ")", ";", "}", "this", ".", "_id", "=", "serviceType", ".", "toString", "(", ")", ";", "debug", "(", "`", "${", "this", ".", "_id", "}", "`", ")", ";", "this", ".", "_resolvers", "=", "{", "}", ";", "// active service resolvers (when browsing services)", "this", ".", "_serviceTypes", "=", "{", "}", ";", "// active service types (when browsing service types)", "this", ".", "_protocol", "=", "serviceType", ".", "protocol", ";", "this", ".", "_serviceName", "=", "serviceType", ".", "name", ";", "this", ".", "_subtype", "=", "serviceType", ".", "subtypes", "[", "0", "]", ";", "this", ".", "_isWildcard", "=", "serviceType", ".", "isEnumerator", ";", "this", ".", "_domain", "=", "options", ".", "domain", "||", "'local.'", ";", "this", ".", "_maintain", "=", "(", "'maintain'", "in", "options", ")", "?", "options", ".", "maintain", ":", "true", ";", "this", ".", "_resolve", "=", "(", "'resolve'", "in", "options", ")", "?", "options", ".", "resolve", ":", "true", ";", "this", ".", "_interface", "=", "NetworkInterface", ".", "get", "(", "options", ".", "interface", ")", ";", "this", ".", "_state", "=", "STATE", ".", "STOPPED", ";", "// emitter used to stop child queries instead of holding onto a reference", "// for each one", "this", ".", "_offswitch", "=", "new", "EventEmitter", "(", ")", ";", "}" ]
Creates a new Browser @emits 'serviceUp' @emits 'serviceChanged' @emits 'serviceDown' @emits 'error' @param {ServiceType|Object|String|Array} type - the service to browse @param {Object} [options]
[ "Creates", "a", "new", "Browser" ]
d66f0dd6c62300f3a2df38186c23c6ffacc02afc
https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/src/Browser.js#L27-L57
21,906
DeMille/dnssd.js
lib/misc.js
visualPad
function visualPad(str, num) { var needed = num - str.replace(remove_colors_re, '').length; return needed > 0 ? str + ' '.repeat(needed) : str; }
javascript
function visualPad(str, num) { var needed = num - str.replace(remove_colors_re, '').length; return needed > 0 ? str + ' '.repeat(needed) : str; }
[ "function", "visualPad", "(", "str", ",", "num", ")", "{", "var", "needed", "=", "num", "-", "str", ".", "replace", "(", "remove_colors_re", ",", "''", ")", ".", "length", ";", "return", "needed", ">", "0", "?", "str", "+", "' '", ".", "repeat", "(", "needed", ")", ":", "str", ";", "}" ]
Visually padEnd. Adding colors to strings adds escape sequences that make it a color but also adds characters to str.length that aren't displayed. @param {string} str @param {number} num @return {string}
[ "Visually", "padEnd", ".", "Adding", "colors", "to", "strings", "adds", "escape", "sequences", "that", "make", "it", "a", "color", "but", "also", "adds", "characters", "to", "str", ".", "length", "that", "aren", "t", "displayed", "." ]
d66f0dd6c62300f3a2df38186c23c6ffacc02afc
https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/lib/misc.js#L107-L111
21,907
DeMille/dnssd.js
lib/misc.js
alignRecords
function alignRecords() { var colWidths = []; var result = void 0; // Get max size for each column (have to look at all records) for (var _len2 = arguments.length, groups = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { groups[_key2] = arguments[_key2]; } result = groups.map(function (records) { return records.map(function (record) { // break record into parts var parts = record.toParts(); parts.forEach(function (part, i) { var len = part.replace(remove_colors_re, '').length; if (!colWidths[i]) colWidths[i] = 0; if (len > colWidths[i]) colWidths[i] = len; }); return parts; }); }); // Add padding: result = result.map(function (records) { return records.map(function (recordParts) { return recordParts.map(function (part, i) { return visualPad(part, colWidths[i]); }).join(' '); }); }); return result; }
javascript
function alignRecords() { var colWidths = []; var result = void 0; // Get max size for each column (have to look at all records) for (var _len2 = arguments.length, groups = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { groups[_key2] = arguments[_key2]; } result = groups.map(function (records) { return records.map(function (record) { // break record into parts var parts = record.toParts(); parts.forEach(function (part, i) { var len = part.replace(remove_colors_re, '').length; if (!colWidths[i]) colWidths[i] = 0; if (len > colWidths[i]) colWidths[i] = len; }); return parts; }); }); // Add padding: result = result.map(function (records) { return records.map(function (recordParts) { return recordParts.map(function (part, i) { return visualPad(part, colWidths[i]); }).join(' '); }); }); return result; }
[ "function", "alignRecords", "(", ")", "{", "var", "colWidths", "=", "[", "]", ";", "var", "result", "=", "void", "0", ";", "// Get max size for each column (have to look at all records)", "for", "(", "var", "_len2", "=", "arguments", ".", "length", ",", "groups", "=", "Array", "(", "_len2", ")", ",", "_key2", "=", "0", ";", "_key2", "<", "_len2", ";", "_key2", "++", ")", "{", "groups", "[", "_key2", "]", "=", "arguments", "[", "_key2", "]", ";", "}", "result", "=", "groups", ".", "map", "(", "function", "(", "records", ")", "{", "return", "records", ".", "map", "(", "function", "(", "record", ")", "{", "// break record into parts", "var", "parts", "=", "record", ".", "toParts", "(", ")", ";", "parts", ".", "forEach", "(", "function", "(", "part", ",", "i", ")", "{", "var", "len", "=", "part", ".", "replace", "(", "remove_colors_re", ",", "''", ")", ".", "length", ";", "if", "(", "!", "colWidths", "[", "i", "]", ")", "colWidths", "[", "i", "]", "=", "0", ";", "if", "(", "len", ">", "colWidths", "[", "i", "]", ")", "colWidths", "[", "i", "]", "=", "len", ";", "}", ")", ";", "return", "parts", ";", "}", ")", ";", "}", ")", ";", "// Add padding:", "result", "=", "result", ".", "map", "(", "function", "(", "records", ")", "{", "return", "records", ".", "map", "(", "function", "(", "recordParts", ")", "{", "return", "recordParts", ".", "map", "(", "function", "(", "part", ",", "i", ")", "{", "return", "visualPad", "(", "part", ",", "colWidths", "[", "i", "]", ")", ";", "}", ")", ".", "join", "(", "' '", ")", ";", "}", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Make a table of records strings that have equal column lengths. Ex, turn groups of records: [ [ Host.local. * QU, ] [ Host.local. A 10 169.254.132.42, Host.local. AAAA 10 fe80::c17c:ec1c:530d:842a, ] ] into a more readable form that can be printed: [ [ 'Host.local. * QU' ] [ 'Host.local. A 10 169.254.132.42' 'Host.local. AAAA 10 fe80::c17c:ec1c:530d:842a' ] ] @param {...ResourceRecords[]} groups @return {string[][]}
[ "Make", "a", "table", "of", "records", "strings", "that", "have", "equal", "column", "lengths", "." ]
d66f0dd6c62300f3a2df38186c23c6ffacc02afc
https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/lib/misc.js#L141-L177
21,908
DeMille/dnssd.js
src/Advertisement.js
Advertisement
function Advertisement(type, port, options = {}) { if (!(this instanceof Advertisement)) { return new Advertisement(type, port, options); } EventEmitter.call(this); // convert argument ServiceType to validate it (might throw) const serviceType = (!(type instanceof ServiceType)) ? new ServiceType(type) : type; // validate other inputs (throws on invalid) validate.port(port); if (options.txt) validate.txt(options.txt); if (options.name) validate.label(options.name, 'Instance'); if (options.host) validate.label(options.host, 'Hostname'); this.serviceName = serviceType.name; this.protocol = serviceType.protocol; this.subtypes = (options.subtypes) ? options.subtypes : serviceType.subtypes; this.port = port; this.instanceName = options.name || misc.hostname(); this.hostname = options.host || misc.hostname(); this.txt = options.txt || {}; // Domain notes: // 1- link-local only, so this is the only possible value // 2- "_domain" used instead of "domain" because "domain" is an instance var // in older versions of EventEmitter. Using "domain" messes up `this.emit()` this._domain = 'local'; this._id = misc.fqdn(this.instanceName, this.serviceName, this.protocol, 'local'); debug(`Creating new advertisement for "${this._id}" on ${port}`); this.state = STATE.STOPPED; this._interface = NetworkInterface.get(options.interface); this._defaultAddresses = null; this._hostnameResponder = null; this._serviceResponder = null; }
javascript
function Advertisement(type, port, options = {}) { if (!(this instanceof Advertisement)) { return new Advertisement(type, port, options); } EventEmitter.call(this); // convert argument ServiceType to validate it (might throw) const serviceType = (!(type instanceof ServiceType)) ? new ServiceType(type) : type; // validate other inputs (throws on invalid) validate.port(port); if (options.txt) validate.txt(options.txt); if (options.name) validate.label(options.name, 'Instance'); if (options.host) validate.label(options.host, 'Hostname'); this.serviceName = serviceType.name; this.protocol = serviceType.protocol; this.subtypes = (options.subtypes) ? options.subtypes : serviceType.subtypes; this.port = port; this.instanceName = options.name || misc.hostname(); this.hostname = options.host || misc.hostname(); this.txt = options.txt || {}; // Domain notes: // 1- link-local only, so this is the only possible value // 2- "_domain" used instead of "domain" because "domain" is an instance var // in older versions of EventEmitter. Using "domain" messes up `this.emit()` this._domain = 'local'; this._id = misc.fqdn(this.instanceName, this.serviceName, this.protocol, 'local'); debug(`Creating new advertisement for "${this._id}" on ${port}`); this.state = STATE.STOPPED; this._interface = NetworkInterface.get(options.interface); this._defaultAddresses = null; this._hostnameResponder = null; this._serviceResponder = null; }
[ "function", "Advertisement", "(", "type", ",", "port", ",", "options", "=", "{", "}", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Advertisement", ")", ")", "{", "return", "new", "Advertisement", "(", "type", ",", "port", ",", "options", ")", ";", "}", "EventEmitter", ".", "call", "(", "this", ")", ";", "// convert argument ServiceType to validate it (might throw)", "const", "serviceType", "=", "(", "!", "(", "type", "instanceof", "ServiceType", ")", ")", "?", "new", "ServiceType", "(", "type", ")", ":", "type", ";", "// validate other inputs (throws on invalid)", "validate", ".", "port", "(", "port", ")", ";", "if", "(", "options", ".", "txt", ")", "validate", ".", "txt", "(", "options", ".", "txt", ")", ";", "if", "(", "options", ".", "name", ")", "validate", ".", "label", "(", "options", ".", "name", ",", "'Instance'", ")", ";", "if", "(", "options", ".", "host", ")", "validate", ".", "label", "(", "options", ".", "host", ",", "'Hostname'", ")", ";", "this", ".", "serviceName", "=", "serviceType", ".", "name", ";", "this", ".", "protocol", "=", "serviceType", ".", "protocol", ";", "this", ".", "subtypes", "=", "(", "options", ".", "subtypes", ")", "?", "options", ".", "subtypes", ":", "serviceType", ".", "subtypes", ";", "this", ".", "port", "=", "port", ";", "this", ".", "instanceName", "=", "options", ".", "name", "||", "misc", ".", "hostname", "(", ")", ";", "this", ".", "hostname", "=", "options", ".", "host", "||", "misc", ".", "hostname", "(", ")", ";", "this", ".", "txt", "=", "options", ".", "txt", "||", "{", "}", ";", "// Domain notes:", "// 1- link-local only, so this is the only possible value", "// 2- \"_domain\" used instead of \"domain\" because \"domain\" is an instance var", "// in older versions of EventEmitter. Using \"domain\" messes up `this.emit()`", "this", ".", "_domain", "=", "'local'", ";", "this", ".", "_id", "=", "misc", ".", "fqdn", "(", "this", ".", "instanceName", ",", "this", ".", "serviceName", ",", "this", ".", "protocol", ",", "'local'", ")", ";", "debug", "(", "`", "${", "this", ".", "_id", "}", "${", "port", "}", "`", ")", ";", "this", ".", "state", "=", "STATE", ".", "STOPPED", ";", "this", ".", "_interface", "=", "NetworkInterface", ".", "get", "(", "options", ".", "interface", ")", ";", "this", ".", "_defaultAddresses", "=", "null", ";", "this", ".", "_hostnameResponder", "=", "null", ";", "this", ".", "_serviceResponder", "=", "null", ";", "}" ]
Creates a new Advertisement @emits 'error' @emits 'stopped' when the advertisement is stopped @emits 'instanceRenamed' when the service instance is renamed @emits 'hostRenamed' when the hostname has to be renamed @param {ServiceType|Object|String|Array} type - type of service to advertise @param {Number} port - port to advertise @param {Object} [options] @param {Object} options.name - instance name @param {Object} options.host - hostname to use @param {Object} options.txt - TXT record @param {Object} options.subtypes - subtypes to register @param {Object} options.interface - interface name or address to use
[ "Creates", "a", "new", "Advertisement" ]
d66f0dd6c62300f3a2df38186c23c6ffacc02afc
https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/src/Advertisement.js#L40-L81
21,909
DeMille/dnssd.js
lib/Response.js
legacyify
function legacyify(record) { var clone = record.clone(); clone.isUnique = false; clone.ttl = 10; return clone; }
javascript
function legacyify(record) { var clone = record.clone(); clone.isUnique = false; clone.ttl = 10; return clone; }
[ "function", "legacyify", "(", "record", ")", "{", "var", "clone", "=", "record", ".", "clone", "(", ")", ";", "clone", ".", "isUnique", "=", "false", ";", "clone", ".", "ttl", "=", "10", ";", "return", "clone", ";", "}" ]
Set TTL=10 on records for legacy responses. Use clones to prevent altering the original record set.
[ "Set", "TTL", "=", "10", "on", "records", "for", "legacy", "responses", ".", "Use", "clones", "to", "prevent", "altering", "the", "original", "record", "set", "." ]
d66f0dd6c62300f3a2df38186c23c6ffacc02afc
https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/lib/Response.js#L452-L457
21,910
cheng-kang/wildfire
src/auto.js
loadJSSequentially
function loadJSSequentially (aList, finished) { if (aList.length === 0) { console.log('Finished loadJSSequentially.') if (finished) { finished() } return } let item = aList.shift() let newScript = document.createElement('script') let url = null let shouldSkip = null let loaded = null if (typeof item === 'object') { ({ url, shouldSkip, loaded } = item) if (shouldSkip()) { console.log('Skipped loading', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) if (loaded) { loaded() } loadJSSequentially(aList, finished) } else { newScript.onload = () => { console.log('Loaded:', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) if (loaded) { loaded() } loadJSSequentially(aList, finished) } } } else if (typeof item === 'string') { url = item newScript.onload = () => { console.log('Loaded:', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) loadJSSequentially(aList, finished) } } newScript.src = url document.head.appendChild(newScript) console.time(`\tLoading time of "${url}"\n\t`) }
javascript
function loadJSSequentially (aList, finished) { if (aList.length === 0) { console.log('Finished loadJSSequentially.') if (finished) { finished() } return } let item = aList.shift() let newScript = document.createElement('script') let url = null let shouldSkip = null let loaded = null if (typeof item === 'object') { ({ url, shouldSkip, loaded } = item) if (shouldSkip()) { console.log('Skipped loading', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) if (loaded) { loaded() } loadJSSequentially(aList, finished) } else { newScript.onload = () => { console.log('Loaded:', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) if (loaded) { loaded() } loadJSSequentially(aList, finished) } } } else if (typeof item === 'string') { url = item newScript.onload = () => { console.log('Loaded:', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) loadJSSequentially(aList, finished) } } newScript.src = url document.head.appendChild(newScript) console.time(`\tLoading time of "${url}"\n\t`) }
[ "function", "loadJSSequentially", "(", "aList", ",", "finished", ")", "{", "if", "(", "aList", ".", "length", "===", "0", ")", "{", "console", ".", "log", "(", "'Finished loadJSSequentially.'", ")", "if", "(", "finished", ")", "{", "finished", "(", ")", "}", "return", "}", "let", "item", "=", "aList", ".", "shift", "(", ")", "let", "newScript", "=", "document", ".", "createElement", "(", "'script'", ")", "let", "url", "=", "null", "let", "shouldSkip", "=", "null", "let", "loaded", "=", "null", "if", "(", "typeof", "item", "===", "'object'", ")", "{", "(", "{", "url", ",", "shouldSkip", ",", "loaded", "}", "=", "item", ")", "if", "(", "shouldSkip", "(", ")", ")", "{", "console", ".", "log", "(", "'Skipped loading'", ",", "url", ")", "console", ".", "timeEnd", "(", "`", "\\t", "${", "url", "}", "\\n", "\\t", "`", ")", "if", "(", "loaded", ")", "{", "loaded", "(", ")", "}", "loadJSSequentially", "(", "aList", ",", "finished", ")", "}", "else", "{", "newScript", ".", "onload", "=", "(", ")", "=>", "{", "console", ".", "log", "(", "'Loaded:'", ",", "url", ")", "console", ".", "timeEnd", "(", "`", "\\t", "${", "url", "}", "\\n", "\\t", "`", ")", "if", "(", "loaded", ")", "{", "loaded", "(", ")", "}", "loadJSSequentially", "(", "aList", ",", "finished", ")", "}", "}", "}", "else", "if", "(", "typeof", "item", "===", "'string'", ")", "{", "url", "=", "item", "newScript", ".", "onload", "=", "(", ")", "=>", "{", "console", ".", "log", "(", "'Loaded:'", ",", "url", ")", "console", ".", "timeEnd", "(", "`", "\\t", "${", "url", "}", "\\n", "\\t", "`", ")", "loadJSSequentially", "(", "aList", ",", "finished", ")", "}", "}", "newScript", ".", "src", "=", "url", "document", ".", "head", ".", "appendChild", "(", "newScript", ")", "console", ".", "time", "(", "`", "\\t", "${", "url", "}", "\\n", "\\t", "`", ")", "}" ]
Dynamically load a list JS files sequentially. @param {(string|Object)[]} aList The list of JS files to load @param {string} aList[].url The url of the JS file to load @param {function} aList[].loaded Callback when the file is loaded @param {function} aList[].shouldSkip Check before loading the file. Note: if `loaded` is set, it will be called no matter this loading is skiped or not. Skipping loading means only to skip the loading part. @param {function} finished Callback when all files loaded Example: 1. `loadJSSequentially([ 'https://unpkg.com/vue', 'https://unpkg.com/vuefire' ], () => { console.log('Finished loading!') })` 2. `loadJSSequentially([ { url: 'https://unpkg.com/vue', shouldSkip: () => window.Vue !== undefined, loaded: () => { console.log('Loaded Vue!') } }, 'https://unpkg.com/vuefire' ], () => { console.log('Finished loading!') })`
[ "Dynamically", "load", "a", "list", "JS", "files", "sequentially", "." ]
85639018887ca657b94ef7edf30a7ef73eb247f8
https://github.com/cheng-kang/wildfire/blob/85639018887ca657b94ef7edf30a7ef73eb247f8/src/auto.js#L57-L103
21,911
cheng-kang/wildfire
src/auto.js
WfI18n
function WfI18n (translation = {}, fallback = null, locale = 'en') { this.translation = translation this.locale = locale this.fallback = fallback this.t = (key) => { let result = this.translation[this.locale] if (!result) { result = this.translation[this.fallback] } if (!result) { throw new WfException(`Translation for locale "${this.locale}" not found.`) } const keys = key.split('.') if (keys.length === 0) { throw new WfException('Empty translation key.') } for (let i = 0; i < keys.length; i++) { result = result[keys[i]] if (!result) { setTimeout(() => { throw new WfException(`Translation for key "${key}" not found.`) }) return key } } return result } return { t: this.t } }
javascript
function WfI18n (translation = {}, fallback = null, locale = 'en') { this.translation = translation this.locale = locale this.fallback = fallback this.t = (key) => { let result = this.translation[this.locale] if (!result) { result = this.translation[this.fallback] } if (!result) { throw new WfException(`Translation for locale "${this.locale}" not found.`) } const keys = key.split('.') if (keys.length === 0) { throw new WfException('Empty translation key.') } for (let i = 0; i < keys.length; i++) { result = result[keys[i]] if (!result) { setTimeout(() => { throw new WfException(`Translation for key "${key}" not found.`) }) return key } } return result } return { t: this.t } }
[ "function", "WfI18n", "(", "translation", "=", "{", "}", ",", "fallback", "=", "null", ",", "locale", "=", "'en'", ")", "{", "this", ".", "translation", "=", "translation", "this", ".", "locale", "=", "locale", "this", ".", "fallback", "=", "fallback", "this", ".", "t", "=", "(", "key", ")", "=>", "{", "let", "result", "=", "this", ".", "translation", "[", "this", ".", "locale", "]", "if", "(", "!", "result", ")", "{", "result", "=", "this", ".", "translation", "[", "this", ".", "fallback", "]", "}", "if", "(", "!", "result", ")", "{", "throw", "new", "WfException", "(", "`", "${", "this", ".", "locale", "}", "`", ")", "}", "const", "keys", "=", "key", ".", "split", "(", "'.'", ")", "if", "(", "keys", ".", "length", "===", "0", ")", "{", "throw", "new", "WfException", "(", "'Empty translation key.'", ")", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "result", "=", "result", "[", "keys", "[", "i", "]", "]", "if", "(", "!", "result", ")", "{", "setTimeout", "(", "(", ")", "=>", "{", "throw", "new", "WfException", "(", "`", "${", "key", "}", "`", ")", "}", ")", "return", "key", "}", "}", "return", "result", "}", "return", "{", "t", ":", "this", ".", "t", "}", "}" ]
Custom translator to replace `i18next`
[ "Custom", "translator", "to", "replace", "i18next" ]
85639018887ca657b94ef7edf30a7ef73eb247f8
https://github.com/cheng-kang/wildfire/blob/85639018887ca657b94ef7edf30a7ef73eb247f8/src/auto.js#L114-L139
21,912
depoio/node-telegram-bot
lib/Bot.js
Bot
function Bot(options) { this.base_url = 'https://api.telegram.org/'; this.id = ''; this.first_name = ''; this.username = ''; this.token = options.token; this.offset = options.offset ? options.offset : 0; this.interval = options.interval ? options.interval : 500; this.webhook = options.webhook ? options.webhook : false; this.parseCommand = options.parseCommand ? options.parseCommand : true; this.maxAttempts = options.maxAttempts ? options.maxAttempts : 5; this.polling = false; this.pollingRequest = null; this.analytics = null; this.timeout = options.timeout ? options.timeout : 60; //specify in seconds // define the messageType's this.NORMAL_MESSAGE = 1; this.EDITED_MESSAGE = 2; }
javascript
function Bot(options) { this.base_url = 'https://api.telegram.org/'; this.id = ''; this.first_name = ''; this.username = ''; this.token = options.token; this.offset = options.offset ? options.offset : 0; this.interval = options.interval ? options.interval : 500; this.webhook = options.webhook ? options.webhook : false; this.parseCommand = options.parseCommand ? options.parseCommand : true; this.maxAttempts = options.maxAttempts ? options.maxAttempts : 5; this.polling = false; this.pollingRequest = null; this.analytics = null; this.timeout = options.timeout ? options.timeout : 60; //specify in seconds // define the messageType's this.NORMAL_MESSAGE = 1; this.EDITED_MESSAGE = 2; }
[ "function", "Bot", "(", "options", ")", "{", "this", ".", "base_url", "=", "'https://api.telegram.org/'", ";", "this", ".", "id", "=", "''", ";", "this", ".", "first_name", "=", "''", ";", "this", ".", "username", "=", "''", ";", "this", ".", "token", "=", "options", ".", "token", ";", "this", ".", "offset", "=", "options", ".", "offset", "?", "options", ".", "offset", ":", "0", ";", "this", ".", "interval", "=", "options", ".", "interval", "?", "options", ".", "interval", ":", "500", ";", "this", ".", "webhook", "=", "options", ".", "webhook", "?", "options", ".", "webhook", ":", "false", ";", "this", ".", "parseCommand", "=", "options", ".", "parseCommand", "?", "options", ".", "parseCommand", ":", "true", ";", "this", ".", "maxAttempts", "=", "options", ".", "maxAttempts", "?", "options", ".", "maxAttempts", ":", "5", ";", "this", ".", "polling", "=", "false", ";", "this", ".", "pollingRequest", "=", "null", ";", "this", ".", "analytics", "=", "null", ";", "this", ".", "timeout", "=", "options", ".", "timeout", "?", "options", ".", "timeout", ":", "60", ";", "//specify in seconds", "// define the messageType's", "this", ".", "NORMAL_MESSAGE", "=", "1", ";", "this", ".", "EDITED_MESSAGE", "=", "2", ";", "}" ]
Constructor for Telegram Bot API Client. @class Bot @constructor @param {Object} options Configurations for the client @param {String} options.token Bot token @see https://core.telegram.org/bots/api
[ "Constructor", "for", "Telegram", "Bot", "API", "Client", "." ]
0abe096364b34469de304c1cc5ec28d8599233ca
https://github.com/depoio/node-telegram-bot/blob/0abe096364b34469de304c1cc5ec28d8599233ca/lib/Bot.js#L24-L42
21,913
Callidon/sparql-engine
src/engine/property-paths.js
transformPath
function transformPath (bgp, group, options) { let i = 0 var queryChange = false var ret = [bgp, null, []] while (i < bgp.length && !queryChange) { var curr = bgp[i] if (typeof curr.predicate !== 'string' && curr.predicate.type === 'path') { switch (curr.predicate.pathType) { case '/': ret = pathSeq(bgp, curr, i, group, ret[2], options) if (ret[1] != null) { queryChange = true } break case '^': ret = pathInv(bgp, curr, i, group, ret[2], options) if (ret[1] != null) { queryChange = true } break case '|': ret = pathAlt(bgp, curr, i, group, ret[2], options) queryChange = true break case '!': ret = pathNeg(bgp, curr, i, group, ret[2], options) queryChange = true break default: break } } i++ } return ret }
javascript
function transformPath (bgp, group, options) { let i = 0 var queryChange = false var ret = [bgp, null, []] while (i < bgp.length && !queryChange) { var curr = bgp[i] if (typeof curr.predicate !== 'string' && curr.predicate.type === 'path') { switch (curr.predicate.pathType) { case '/': ret = pathSeq(bgp, curr, i, group, ret[2], options) if (ret[1] != null) { queryChange = true } break case '^': ret = pathInv(bgp, curr, i, group, ret[2], options) if (ret[1] != null) { queryChange = true } break case '|': ret = pathAlt(bgp, curr, i, group, ret[2], options) queryChange = true break case '!': ret = pathNeg(bgp, curr, i, group, ret[2], options) queryChange = true break default: break } } i++ } return ret }
[ "function", "transformPath", "(", "bgp", ",", "group", ",", "options", ")", "{", "let", "i", "=", "0", "var", "queryChange", "=", "false", "var", "ret", "=", "[", "bgp", ",", "null", ",", "[", "]", "]", "while", "(", "i", "<", "bgp", ".", "length", "&&", "!", "queryChange", ")", "{", "var", "curr", "=", "bgp", "[", "i", "]", "if", "(", "typeof", "curr", ".", "predicate", "!==", "'string'", "&&", "curr", ".", "predicate", ".", "type", "===", "'path'", ")", "{", "switch", "(", "curr", ".", "predicate", ".", "pathType", ")", "{", "case", "'/'", ":", "ret", "=", "pathSeq", "(", "bgp", ",", "curr", ",", "i", ",", "group", ",", "ret", "[", "2", "]", ",", "options", ")", "if", "(", "ret", "[", "1", "]", "!=", "null", ")", "{", "queryChange", "=", "true", "}", "break", "case", "'^'", ":", "ret", "=", "pathInv", "(", "bgp", ",", "curr", ",", "i", ",", "group", ",", "ret", "[", "2", "]", ",", "options", ")", "if", "(", "ret", "[", "1", "]", "!=", "null", ")", "{", "queryChange", "=", "true", "}", "break", "case", "'|'", ":", "ret", "=", "pathAlt", "(", "bgp", ",", "curr", ",", "i", ",", "group", ",", "ret", "[", "2", "]", ",", "options", ")", "queryChange", "=", "true", "break", "case", "'!'", ":", "ret", "=", "pathNeg", "(", "bgp", ",", "curr", ",", "i", ",", "group", ",", "ret", "[", "2", "]", ",", "options", ")", "queryChange", "=", "true", "break", "default", ":", "break", "}", "}", "i", "++", "}", "return", "ret", "}" ]
rewriting rules for property paths
[ "rewriting", "rules", "for", "property", "paths" ]
bf4c602df3dd5ac190f99e8593aa134eba5cc084
https://github.com/Callidon/sparql-engine/blob/bf4c602df3dd5ac190f99e8593aa134eba5cc084/src/engine/property-paths.js#L31-L66
21,914
101100/xbee-rx
examples/temp-upload.js
xivelyPost
function xivelyPost(feedId, streamId, apiKey, currentValue) { var dataPoint = { "version":"1.0.0", "datastreams" : [ { "id" : streamId, "current_value" : currentValue }, ] }; var requestUrl = "https://api.xively.com/v2/feeds/" + feedId; var options = { url: requestUrl, headers: { "X-ApiKey" : apiKey, "Content-Type": "application/json", "Accept": "*/*", "User-Agent": "nodejs" }, body: JSON.stringify(dataPoint) }; return requestPut(options); }
javascript
function xivelyPost(feedId, streamId, apiKey, currentValue) { var dataPoint = { "version":"1.0.0", "datastreams" : [ { "id" : streamId, "current_value" : currentValue }, ] }; var requestUrl = "https://api.xively.com/v2/feeds/" + feedId; var options = { url: requestUrl, headers: { "X-ApiKey" : apiKey, "Content-Type": "application/json", "Accept": "*/*", "User-Agent": "nodejs" }, body: JSON.stringify(dataPoint) }; return requestPut(options); }
[ "function", "xivelyPost", "(", "feedId", ",", "streamId", ",", "apiKey", ",", "currentValue", ")", "{", "var", "dataPoint", "=", "{", "\"version\"", ":", "\"1.0.0\"", ",", "\"datastreams\"", ":", "[", "{", "\"id\"", ":", "streamId", ",", "\"current_value\"", ":", "currentValue", "}", ",", "]", "}", ";", "var", "requestUrl", "=", "\"https://api.xively.com/v2/feeds/\"", "+", "feedId", ";", "var", "options", "=", "{", "url", ":", "requestUrl", ",", "headers", ":", "{", "\"X-ApiKey\"", ":", "apiKey", ",", "\"Content-Type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"*/*\"", ",", "\"User-Agent\"", ":", "\"nodejs\"", "}", ",", "body", ":", "JSON", ".", "stringify", "(", "dataPoint", ")", "}", ";", "return", "requestPut", "(", "options", ")", ";", "}" ]
Creates a new observable that will make a HTTP or HTTPS POST request to the given url and will give the results as a single event in the stream.
[ "Creates", "a", "new", "observable", "that", "will", "make", "a", "HTTP", "or", "HTTPS", "POST", "request", "to", "the", "given", "url", "and", "will", "give", "the", "results", "as", "a", "single", "event", "in", "the", "stream", "." ]
248edb7e82dba41c0e352feffa952581d7967253
https://github.com/101100/xbee-rx/blob/248edb7e82dba41c0e352feffa952581d7967253/examples/temp-upload.js#L33-L60
21,915
101100/xbee-rx
lib/xbee-rx.js
_lookupByNodeIdentifier
function _lookupByNodeIdentifier(nodeIdentifier, timeoutMs) { // if the address is cached, return that if (cachedNodes[nodeIdentifier]) { return rx.of({ destination64: cachedNodes[nodeIdentifier]}); } if (debug) { console.log("Looking up", nodeIdentifier); } return _localCommand("DN", timeoutMs, nodeIdentifier).pipe( rx.operators.catchError(function() { return rx.throwError(new Error("Node not found")); }), rx.operators.map(_extractDestination64), rx.operators.tap(function(address64) { cachedNodes[nodeIdentifier] = address64; }), rx.operators.map(function(address64) { return { destination64: address64 }; }) ); }
javascript
function _lookupByNodeIdentifier(nodeIdentifier, timeoutMs) { // if the address is cached, return that if (cachedNodes[nodeIdentifier]) { return rx.of({ destination64: cachedNodes[nodeIdentifier]}); } if (debug) { console.log("Looking up", nodeIdentifier); } return _localCommand("DN", timeoutMs, nodeIdentifier).pipe( rx.operators.catchError(function() { return rx.throwError(new Error("Node not found")); }), rx.operators.map(_extractDestination64), rx.operators.tap(function(address64) { cachedNodes[nodeIdentifier] = address64; }), rx.operators.map(function(address64) { return { destination64: address64 }; }) ); }
[ "function", "_lookupByNodeIdentifier", "(", "nodeIdentifier", ",", "timeoutMs", ")", "{", "// if the address is cached, return that", "if", "(", "cachedNodes", "[", "nodeIdentifier", "]", ")", "{", "return", "rx", ".", "of", "(", "{", "destination64", ":", "cachedNodes", "[", "nodeIdentifier", "]", "}", ")", ";", "}", "if", "(", "debug", ")", "{", "console", ".", "log", "(", "\"Looking up\"", ",", "nodeIdentifier", ")", ";", "}", "return", "_localCommand", "(", "\"DN\"", ",", "timeoutMs", ",", "nodeIdentifier", ")", ".", "pipe", "(", "rx", ".", "operators", ".", "catchError", "(", "function", "(", ")", "{", "return", "rx", ".", "throwError", "(", "new", "Error", "(", "\"Node not found\"", ")", ")", ";", "}", ")", ",", "rx", ".", "operators", ".", "map", "(", "_extractDestination64", ")", ",", "rx", ".", "operators", ".", "tap", "(", "function", "(", "address64", ")", "{", "cachedNodes", "[", "nodeIdentifier", "]", "=", "address64", ";", "}", ")", ",", "rx", ".", "operators", ".", "map", "(", "function", "(", "address64", ")", "{", "return", "{", "destination64", ":", "address64", "}", ";", "}", ")", ")", ";", "}" ]
Returns a stream that will emit the 64 bit address of the node with the given node identifier.
[ "Returns", "a", "stream", "that", "will", "emit", "the", "64", "bit", "address", "of", "the", "node", "with", "the", "given", "node", "identifier", "." ]
248edb7e82dba41c0e352feffa952581d7967253
https://github.com/101100/xbee-rx/blob/248edb7e82dba41c0e352feffa952581d7967253/lib/xbee-rx.js#L172-L194
21,916
101100/xbee-rx
lib/xbee-rx.js
_remoteCommand
function _remoteCommand(command, destination64, destination16, timeoutMs, commandParameter, broadcast) { var frame = { type: xbee_api.constants.FRAME_TYPE.REMOTE_AT_COMMAND_REQUEST, command: command, commandParameter: commandParameter, destination64: destination64, destination16: destination16 }, responseStream; if (debug) { console.log("Sending", command, "to", destination64, "with parameter", commandParameter || []); } responseStream = _sendFrameStreamResponse(frame, timeoutMs, xbee_api.constants.FRAME_TYPE.REMOTE_COMMAND_RESPONSE).pipe( rx.operators.flatMap(function(frame) { if (frame.commandStatus === xbee_api.constants.COMMAND_STATUS.REMOTE_CMD_TRANS_FAILURE) { // if there was a remote command transmission failure, throw error return rx.throwError(new Error(xbee_api.constants.COMMAND_STATUS[frame.commandStatus])); } // any other response is returned return rx.of(frame); }) ); if (broadcast) { return responseStream; } else { // if not broadcast, there can be only one response packet return responseStream.pipe(rx.operators.take(1)); } }
javascript
function _remoteCommand(command, destination64, destination16, timeoutMs, commandParameter, broadcast) { var frame = { type: xbee_api.constants.FRAME_TYPE.REMOTE_AT_COMMAND_REQUEST, command: command, commandParameter: commandParameter, destination64: destination64, destination16: destination16 }, responseStream; if (debug) { console.log("Sending", command, "to", destination64, "with parameter", commandParameter || []); } responseStream = _sendFrameStreamResponse(frame, timeoutMs, xbee_api.constants.FRAME_TYPE.REMOTE_COMMAND_RESPONSE).pipe( rx.operators.flatMap(function(frame) { if (frame.commandStatus === xbee_api.constants.COMMAND_STATUS.REMOTE_CMD_TRANS_FAILURE) { // if there was a remote command transmission failure, throw error return rx.throwError(new Error(xbee_api.constants.COMMAND_STATUS[frame.commandStatus])); } // any other response is returned return rx.of(frame); }) ); if (broadcast) { return responseStream; } else { // if not broadcast, there can be only one response packet return responseStream.pipe(rx.operators.take(1)); } }
[ "function", "_remoteCommand", "(", "command", ",", "destination64", ",", "destination16", ",", "timeoutMs", ",", "commandParameter", ",", "broadcast", ")", "{", "var", "frame", "=", "{", "type", ":", "xbee_api", ".", "constants", ".", "FRAME_TYPE", ".", "REMOTE_AT_COMMAND_REQUEST", ",", "command", ":", "command", ",", "commandParameter", ":", "commandParameter", ",", "destination64", ":", "destination64", ",", "destination16", ":", "destination16", "}", ",", "responseStream", ";", "if", "(", "debug", ")", "{", "console", ".", "log", "(", "\"Sending\"", ",", "command", ",", "\"to\"", ",", "destination64", ",", "\"with parameter\"", ",", "commandParameter", "||", "[", "]", ")", ";", "}", "responseStream", "=", "_sendFrameStreamResponse", "(", "frame", ",", "timeoutMs", ",", "xbee_api", ".", "constants", ".", "FRAME_TYPE", ".", "REMOTE_COMMAND_RESPONSE", ")", ".", "pipe", "(", "rx", ".", "operators", ".", "flatMap", "(", "function", "(", "frame", ")", "{", "if", "(", "frame", ".", "commandStatus", "===", "xbee_api", ".", "constants", ".", "COMMAND_STATUS", ".", "REMOTE_CMD_TRANS_FAILURE", ")", "{", "// if there was a remote command transmission failure, throw error", "return", "rx", ".", "throwError", "(", "new", "Error", "(", "xbee_api", ".", "constants", ".", "COMMAND_STATUS", "[", "frame", ".", "commandStatus", "]", ")", ")", ";", "}", "// any other response is returned", "return", "rx", ".", "of", "(", "frame", ")", ";", "}", ")", ")", ";", "if", "(", "broadcast", ")", "{", "return", "responseStream", ";", "}", "else", "{", "// if not broadcast, there can be only one response packet", "return", "responseStream", ".", "pipe", "(", "rx", ".", "operators", ".", "take", "(", "1", ")", ")", ";", "}", "}" ]
Sends a the given command and parameter to the given destination. A stream is returned that will emit to the resulting command data on success or end in an Error with the failed status as the text. Only one of destination64 or destination16 should be given; the other should be undefined.
[ "Sends", "a", "the", "given", "command", "and", "parameter", "to", "the", "given", "destination", ".", "A", "stream", "is", "returned", "that", "will", "emit", "to", "the", "resulting", "command", "data", "on", "success", "or", "end", "in", "an", "Error", "with", "the", "failed", "status", "as", "the", "text", ".", "Only", "one", "of", "destination64", "or", "destination16", "should", "be", "given", ";", "the", "other", "should", "be", "undefined", "." ]
248edb7e82dba41c0e352feffa952581d7967253
https://github.com/101100/xbee-rx/blob/248edb7e82dba41c0e352feffa952581d7967253/lib/xbee-rx.js#L283-L314
21,917
101100/xbee-rx
lib/xbee-rx.js
_remoteTransmit
function _remoteTransmit(destination64, destination16, data, timeoutMs) { var frame = { data: data, type: xbee_api.constants.FRAME_TYPE.ZIGBEE_TRANSMIT_REQUEST, destination64: destination64, destination16: destination16 }, responseFrameType = xbee_api.constants.FRAME_TYPE.ZIGBEE_TRANSMIT_STATUS; if (module === "802.15.4") { responseFrameType = xbee_api.constants.FRAME_TYPE.TX_STATUS; frame.type = destination64 ? xbee_api.constants.FRAME_TYPE.TX_REQUEST_64 : xbee_api.constants.FRAME_TYPE.TX_REQUEST_16; } if (debug) { console.log("Sending '" + data + "' to", destination64 || destination16); } return _sendFrameStreamResponse(frame, timeoutMs, responseFrameType).pipe( rx.operators.take(1), rx.operators.flatMap(function(frame) { if (frame.deliveryStatus === xbee_api.constants.DELIVERY_STATUS.SUCCESS) { return rx.of(true); } // if not OK, throw error return rx.throwError(new Error(xbee_api.constants.DELIVERY_STATUS[frame.deliveryStatus])); }) ); }
javascript
function _remoteTransmit(destination64, destination16, data, timeoutMs) { var frame = { data: data, type: xbee_api.constants.FRAME_TYPE.ZIGBEE_TRANSMIT_REQUEST, destination64: destination64, destination16: destination16 }, responseFrameType = xbee_api.constants.FRAME_TYPE.ZIGBEE_TRANSMIT_STATUS; if (module === "802.15.4") { responseFrameType = xbee_api.constants.FRAME_TYPE.TX_STATUS; frame.type = destination64 ? xbee_api.constants.FRAME_TYPE.TX_REQUEST_64 : xbee_api.constants.FRAME_TYPE.TX_REQUEST_16; } if (debug) { console.log("Sending '" + data + "' to", destination64 || destination16); } return _sendFrameStreamResponse(frame, timeoutMs, responseFrameType).pipe( rx.operators.take(1), rx.operators.flatMap(function(frame) { if (frame.deliveryStatus === xbee_api.constants.DELIVERY_STATUS.SUCCESS) { return rx.of(true); } // if not OK, throw error return rx.throwError(new Error(xbee_api.constants.DELIVERY_STATUS[frame.deliveryStatus])); }) ); }
[ "function", "_remoteTransmit", "(", "destination64", ",", "destination16", ",", "data", ",", "timeoutMs", ")", "{", "var", "frame", "=", "{", "data", ":", "data", ",", "type", ":", "xbee_api", ".", "constants", ".", "FRAME_TYPE", ".", "ZIGBEE_TRANSMIT_REQUEST", ",", "destination64", ":", "destination64", ",", "destination16", ":", "destination16", "}", ",", "responseFrameType", "=", "xbee_api", ".", "constants", ".", "FRAME_TYPE", ".", "ZIGBEE_TRANSMIT_STATUS", ";", "if", "(", "module", "===", "\"802.15.4\"", ")", "{", "responseFrameType", "=", "xbee_api", ".", "constants", ".", "FRAME_TYPE", ".", "TX_STATUS", ";", "frame", ".", "type", "=", "destination64", "?", "xbee_api", ".", "constants", ".", "FRAME_TYPE", ".", "TX_REQUEST_64", ":", "xbee_api", ".", "constants", ".", "FRAME_TYPE", ".", "TX_REQUEST_16", ";", "}", "if", "(", "debug", ")", "{", "console", ".", "log", "(", "\"Sending '\"", "+", "data", "+", "\"' to\"", ",", "destination64", "||", "destination16", ")", ";", "}", "return", "_sendFrameStreamResponse", "(", "frame", ",", "timeoutMs", ",", "responseFrameType", ")", ".", "pipe", "(", "rx", ".", "operators", ".", "take", "(", "1", ")", ",", "rx", ".", "operators", ".", "flatMap", "(", "function", "(", "frame", ")", "{", "if", "(", "frame", ".", "deliveryStatus", "===", "xbee_api", ".", "constants", ".", "DELIVERY_STATUS", ".", "SUCCESS", ")", "{", "return", "rx", ".", "of", "(", "true", ")", ";", "}", "// if not OK, throw error", "return", "rx", ".", "throwError", "(", "new", "Error", "(", "xbee_api", ".", "constants", ".", "DELIVERY_STATUS", "[", "frame", ".", "deliveryStatus", "]", ")", ")", ";", "}", ")", ")", ";", "}" ]
Sends a the given data to the given destination. A stream is returned that will complete on success or end in an Error with the failed status as the text. Only one of destination64 or destination16 should be given; the other should be undefined.
[ "Sends", "a", "the", "given", "data", "to", "the", "given", "destination", ".", "A", "stream", "is", "returned", "that", "will", "complete", "on", "success", "or", "end", "in", "an", "Error", "with", "the", "failed", "status", "as", "the", "text", ".", "Only", "one", "of", "destination64", "or", "destination16", "should", "be", "given", ";", "the", "other", "should", "be", "undefined", "." ]
248edb7e82dba41c0e352feffa952581d7967253
https://github.com/101100/xbee-rx/blob/248edb7e82dba41c0e352feffa952581d7967253/lib/xbee-rx.js#L321-L351
21,918
glennjones/microformat-node
static/javascript/parse.js
getResults
function getResults( form, url, callback ){ var formData = new FormData( form ); var request = new XMLHttpRequest(); request.open("POST", url); request.send(formData); request.onload = function(e) { if (request.status == 200) { callback(null, JSON.parse(request.responseText)); } else { callback("Error " + request.status + ' - ' + request.responseText, null); } }; }
javascript
function getResults( form, url, callback ){ var formData = new FormData( form ); var request = new XMLHttpRequest(); request.open("POST", url); request.send(formData); request.onload = function(e) { if (request.status == 200) { callback(null, JSON.parse(request.responseText)); } else { callback("Error " + request.status + ' - ' + request.responseText, null); } }; }
[ "function", "getResults", "(", "form", ",", "url", ",", "callback", ")", "{", "var", "formData", "=", "new", "FormData", "(", "form", ")", ";", "var", "request", "=", "new", "XMLHttpRequest", "(", ")", ";", "request", ".", "open", "(", "\"POST\"", ",", "url", ")", ";", "request", ".", "send", "(", "formData", ")", ";", "request", ".", "onload", "=", "function", "(", "e", ")", "{", "if", "(", "request", ".", "status", "==", "200", ")", "{", "callback", "(", "null", ",", "JSON", ".", "parse", "(", "request", ".", "responseText", ")", ")", ";", "}", "else", "{", "callback", "(", "\"Error \"", "+", "request", ".", "status", "+", "' - '", "+", "request", ".", "responseText", ",", "null", ")", ";", "}", "}", ";", "}" ]
post form and returns JSON
[ "post", "form", "and", "returns", "JSON" ]
d817ebf484dedb1d042e635eccc0707afd46d7f7
https://github.com/glennjones/microformat-node/blob/d817ebf484dedb1d042e635eccc0707afd46d7f7/static/javascript/parse.js#L64-L77
21,919
glennjones/microformat-node
app.js
buildOptions
function buildOptions(request, callback) { let options = {}; let err = null; if (request.payload.html !== undefined) { options.html = request.payload.html.trim(); } if (request.payload.baseUrl !== undefined) { options.baseUrl = request.payload.baseUrl.trim(); } if (request.payload.filters !== undefined) { if (request.payload.filters.indexOf(',') > -1) { options.filters = trimArray(request.payload.filters.split(',')) } else { options.filters = trimArray(request.payload.filters) } if (options.filters.length === 0) { delete options.filters; } } if (request.payload.dateFormat !== undefined) { options.dateFormat = request.payload.dateFormat; } if (request.payload.textFormat !== undefined) { options.textFormat = request.payload.textFormat; } if (request.payload.overlappingVersions !== undefined) { options.overlappingVersions = request.payload.overlappingVersions } if (request.payload.impliedPropertiesByVersion !== undefined) { options.impliedPropertiesByVersion = request.payload.impliedPropertiesByVersion } if (request.payload.parseLatLonGeo !== undefined) { options.parseLatLonGeo = request.payload.parseLatLonGeo } if (request.payload.url !== undefined) { Request(request.payload.url, function (error, response, body) { err = error; if(!err && response && response.statusCode === 200){ options.html = body; callback(null, options); }else{ callback(err, null); } }); }else{ callback(err, options); } }
javascript
function buildOptions(request, callback) { let options = {}; let err = null; if (request.payload.html !== undefined) { options.html = request.payload.html.trim(); } if (request.payload.baseUrl !== undefined) { options.baseUrl = request.payload.baseUrl.trim(); } if (request.payload.filters !== undefined) { if (request.payload.filters.indexOf(',') > -1) { options.filters = trimArray(request.payload.filters.split(',')) } else { options.filters = trimArray(request.payload.filters) } if (options.filters.length === 0) { delete options.filters; } } if (request.payload.dateFormat !== undefined) { options.dateFormat = request.payload.dateFormat; } if (request.payload.textFormat !== undefined) { options.textFormat = request.payload.textFormat; } if (request.payload.overlappingVersions !== undefined) { options.overlappingVersions = request.payload.overlappingVersions } if (request.payload.impliedPropertiesByVersion !== undefined) { options.impliedPropertiesByVersion = request.payload.impliedPropertiesByVersion } if (request.payload.parseLatLonGeo !== undefined) { options.parseLatLonGeo = request.payload.parseLatLonGeo } if (request.payload.url !== undefined) { Request(request.payload.url, function (error, response, body) { err = error; if(!err && response && response.statusCode === 200){ options.html = body; callback(null, options); }else{ callback(err, null); } }); }else{ callback(err, options); } }
[ "function", "buildOptions", "(", "request", ",", "callback", ")", "{", "let", "options", "=", "{", "}", ";", "let", "err", "=", "null", ";", "if", "(", "request", ".", "payload", ".", "html", "!==", "undefined", ")", "{", "options", ".", "html", "=", "request", ".", "payload", ".", "html", ".", "trim", "(", ")", ";", "}", "if", "(", "request", ".", "payload", ".", "baseUrl", "!==", "undefined", ")", "{", "options", ".", "baseUrl", "=", "request", ".", "payload", ".", "baseUrl", ".", "trim", "(", ")", ";", "}", "if", "(", "request", ".", "payload", ".", "filters", "!==", "undefined", ")", "{", "if", "(", "request", ".", "payload", ".", "filters", ".", "indexOf", "(", "','", ")", ">", "-", "1", ")", "{", "options", ".", "filters", "=", "trimArray", "(", "request", ".", "payload", ".", "filters", ".", "split", "(", "','", ")", ")", "}", "else", "{", "options", ".", "filters", "=", "trimArray", "(", "request", ".", "payload", ".", "filters", ")", "}", "if", "(", "options", ".", "filters", ".", "length", "===", "0", ")", "{", "delete", "options", ".", "filters", ";", "}", "}", "if", "(", "request", ".", "payload", ".", "dateFormat", "!==", "undefined", ")", "{", "options", ".", "dateFormat", "=", "request", ".", "payload", ".", "dateFormat", ";", "}", "if", "(", "request", ".", "payload", ".", "textFormat", "!==", "undefined", ")", "{", "options", ".", "textFormat", "=", "request", ".", "payload", ".", "textFormat", ";", "}", "if", "(", "request", ".", "payload", ".", "overlappingVersions", "!==", "undefined", ")", "{", "options", ".", "overlappingVersions", "=", "request", ".", "payload", ".", "overlappingVersions", "}", "if", "(", "request", ".", "payload", ".", "impliedPropertiesByVersion", "!==", "undefined", ")", "{", "options", ".", "impliedPropertiesByVersion", "=", "request", ".", "payload", ".", "impliedPropertiesByVersion", "}", "if", "(", "request", ".", "payload", ".", "parseLatLonGeo", "!==", "undefined", ")", "{", "options", ".", "parseLatLonGeo", "=", "request", ".", "payload", ".", "parseLatLonGeo", "}", "if", "(", "request", ".", "payload", ".", "url", "!==", "undefined", ")", "{", "Request", "(", "request", ".", "payload", ".", "url", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "err", "=", "error", ";", "if", "(", "!", "err", "&&", "response", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "options", ".", "html", "=", "body", ";", "callback", "(", "null", ",", "options", ")", ";", "}", "else", "{", "callback", "(", "err", ",", "null", ")", ";", "}", "}", ")", ";", "}", "else", "{", "callback", "(", "err", ",", "options", ")", ";", "}", "}" ]
create options from form input
[ "create", "options", "from", "form", "input" ]
d817ebf484dedb1d042e635eccc0707afd46d7f7
https://github.com/glennjones/microformat-node/blob/d817ebf484dedb1d042e635eccc0707afd46d7f7/app.js#L73-L134
21,920
not-an-aardvark/eslint-rule-composer
lib/rule-composer.js
normalizeMessagePlaceholders
function normalizeMessagePlaceholders(descriptor, messageIds) { const message = typeof descriptor.messageId === 'string' ? messageIds[descriptor.messageId] : descriptor.message; if (!descriptor.data) { return { message, data: typeof descriptor.messageId === 'string' ? {} : null, }; } const normalizedData = Object.create(null); const interpolatedMessage = message.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (fullMatch, term) => { if (term in descriptor.data) { normalizedData[term] = descriptor.data[term]; return descriptor.data[term]; } return fullMatch; }); return { message: interpolatedMessage, data: Object.freeze(normalizedData), }; }
javascript
function normalizeMessagePlaceholders(descriptor, messageIds) { const message = typeof descriptor.messageId === 'string' ? messageIds[descriptor.messageId] : descriptor.message; if (!descriptor.data) { return { message, data: typeof descriptor.messageId === 'string' ? {} : null, }; } const normalizedData = Object.create(null); const interpolatedMessage = message.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (fullMatch, term) => { if (term in descriptor.data) { normalizedData[term] = descriptor.data[term]; return descriptor.data[term]; } return fullMatch; }); return { message: interpolatedMessage, data: Object.freeze(normalizedData), }; }
[ "function", "normalizeMessagePlaceholders", "(", "descriptor", ",", "messageIds", ")", "{", "const", "message", "=", "typeof", "descriptor", ".", "messageId", "===", "'string'", "?", "messageIds", "[", "descriptor", ".", "messageId", "]", ":", "descriptor", ".", "message", ";", "if", "(", "!", "descriptor", ".", "data", ")", "{", "return", "{", "message", ",", "data", ":", "typeof", "descriptor", ".", "messageId", "===", "'string'", "?", "{", "}", ":", "null", ",", "}", ";", "}", "const", "normalizedData", "=", "Object", ".", "create", "(", "null", ")", ";", "const", "interpolatedMessage", "=", "message", ".", "replace", "(", "/", "\\{\\{\\s*([^{}]+?)\\s*\\}\\}", "/", "g", ",", "(", "fullMatch", ",", "term", ")", "=>", "{", "if", "(", "term", "in", "descriptor", ".", "data", ")", "{", "normalizedData", "[", "term", "]", "=", "descriptor", ".", "data", "[", "term", "]", ";", "return", "descriptor", ".", "data", "[", "term", "]", ";", "}", "return", "fullMatch", ";", "}", ")", ";", "return", "{", "message", ":", "interpolatedMessage", ",", "data", ":", "Object", ".", "freeze", "(", "normalizedData", ")", ",", "}", ";", "}" ]
Interpolates data placeholders in report messages @param {MessageDescriptor} descriptor The report message descriptor. @param {Object} messageIds Message IDs from rule metadata @returns {{message: string, data: Object}} The interpolated message and data for the descriptor
[ "Interpolates", "data", "placeholders", "in", "report", "messages" ]
7e8ec43d3e62d9766e87b09c1958ce2863b421f4
https://github.com/not-an-aardvark/eslint-rule-composer/blob/7e8ec43d3e62d9766e87b09c1958ce2863b421f4/lib/rule-composer.js#L57-L80
21,921
smallalso/v-verify
src/utils.js
classOf
function classOf (obj) { const class2type = {} 'Boolean Number String Function Array Date RegExp Object tips'.split(' ') .forEach((e, i) => { class2type['[object ' + e + ']'] = e.toLowerCase() }) if (obj == null) { return String(obj) } return typeof obj === 'object' || typeof obj === 'function' ? class2type[ class2type.toString.call(obj) ] || 'object' : typeof obj }
javascript
function classOf (obj) { const class2type = {} 'Boolean Number String Function Array Date RegExp Object tips'.split(' ') .forEach((e, i) => { class2type['[object ' + e + ']'] = e.toLowerCase() }) if (obj == null) { return String(obj) } return typeof obj === 'object' || typeof obj === 'function' ? class2type[ class2type.toString.call(obj) ] || 'object' : typeof obj }
[ "function", "classOf", "(", "obj", ")", "{", "const", "class2type", "=", "{", "}", "'Boolean Number String Function Array Date RegExp Object tips'", ".", "split", "(", "' '", ")", ".", "forEach", "(", "(", "e", ",", "i", ")", "=>", "{", "class2type", "[", "'[object '", "+", "e", "+", "']'", "]", "=", "e", ".", "toLowerCase", "(", ")", "}", ")", "if", "(", "obj", "==", "null", ")", "{", "return", "String", "(", "obj", ")", "}", "return", "typeof", "obj", "===", "'object'", "||", "typeof", "obj", "===", "'function'", "?", "class2type", "[", "class2type", ".", "toString", ".", "call", "(", "obj", ")", "]", "||", "'object'", ":", "typeof", "obj", "}" ]
javscript data type judgment @param {*} obj
[ "javscript", "data", "type", "judgment" ]
36b389f560b6060e26c7a475902d4add1a644e1a
https://github.com/smallalso/v-verify/blob/36b389f560b6060e26c7a475902d4add1a644e1a/src/utils.js#L7-L19
21,922
smallalso/v-verify
src/index.js
install
function install (Vue, options = {}) { options.lang = options.lang || 'zh_cn' Object.assign(validator, options.validators) Object.assign(lang[options.lang], options.messages) try { const directive = new Directive(Vue, { mode: options.mode, errorIcon: options.errorIcon, errorClass: options.errorClass || null, errorForm: options.errorForm, validators: validator, messages: lang[options.lang] }) directive.install(Vue) } catch (e) { console.error(`${e}\nfrom v-verify`) } }
javascript
function install (Vue, options = {}) { options.lang = options.lang || 'zh_cn' Object.assign(validator, options.validators) Object.assign(lang[options.lang], options.messages) try { const directive = new Directive(Vue, { mode: options.mode, errorIcon: options.errorIcon, errorClass: options.errorClass || null, errorForm: options.errorForm, validators: validator, messages: lang[options.lang] }) directive.install(Vue) } catch (e) { console.error(`${e}\nfrom v-verify`) } }
[ "function", "install", "(", "Vue", ",", "options", "=", "{", "}", ")", "{", "options", ".", "lang", "=", "options", ".", "lang", "||", "'zh_cn'", "Object", ".", "assign", "(", "validator", ",", "options", ".", "validators", ")", "Object", ".", "assign", "(", "lang", "[", "options", ".", "lang", "]", ",", "options", ".", "messages", ")", "try", "{", "const", "directive", "=", "new", "Directive", "(", "Vue", ",", "{", "mode", ":", "options", ".", "mode", ",", "errorIcon", ":", "options", ".", "errorIcon", ",", "errorClass", ":", "options", ".", "errorClass", "||", "null", ",", "errorForm", ":", "options", ".", "errorForm", ",", "validators", ":", "validator", ",", "messages", ":", "lang", "[", "options", ".", "lang", "]", "}", ")", "directive", ".", "install", "(", "Vue", ")", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "`", "${", "e", "}", "\\n", "`", ")", "}", "}" ]
VUE plugin registed function @param {Object} Vue object @param {Object} plugin config object
[ "VUE", "plugin", "registed", "function" ]
36b389f560b6060e26c7a475902d4add1a644e1a
https://github.com/smallalso/v-verify/blob/36b389f560b6060e26c7a475902d4add1a644e1a/src/index.js#L11-L28
21,923
trooba/trooba
index.js
add
function add(message) { if (!message.order || // no keep order needed message.inProcess) {// or already in process return false; // should continue } var queue = this.getQueue(message.context); queue.unshift(message); // FIFO message.pointId = this.pipe._id; var moreInQueue = queue.length > 1; message.inProcess = !moreInQueue; return moreInQueue; }
javascript
function add(message) { if (!message.order || // no keep order needed message.inProcess) {// or already in process return false; // should continue } var queue = this.getQueue(message.context); queue.unshift(message); // FIFO message.pointId = this.pipe._id; var moreInQueue = queue.length > 1; message.inProcess = !moreInQueue; return moreInQueue; }
[ "function", "add", "(", "message", ")", "{", "if", "(", "!", "message", ".", "order", "||", "// no keep order needed", "message", ".", "inProcess", ")", "{", "// or already in process", "return", "false", ";", "// should continue", "}", "var", "queue", "=", "this", ".", "getQueue", "(", "message", ".", "context", ")", ";", "queue", ".", "unshift", "(", "message", ")", ";", "// FIFO", "message", ".", "pointId", "=", "this", ".", "pipe", ".", "_id", ";", "var", "moreInQueue", "=", "queue", ".", "length", ">", "1", ";", "message", ".", "inProcess", "=", "!", "moreInQueue", ";", "return", "moreInQueue", ";", "}" ]
return true, if message prcessing should be paused
[ "return", "true", "if", "message", "prcessing", "should", "be", "paused" ]
fdfd1e0d329d419cff581835c8f7aaf213ea9f1f
https://github.com/trooba/trooba/blob/fdfd1e0d329d419cff581835c8f7aaf213ea9f1f/index.js#L700-L713
21,924
Pagawa/PgwSlider
pgwslider.js
function(elementId, apiController, direction) { if (elementId == pgwSlider.currentSlide) { return false; } var element = pgwSlider.data[elementId - 1]; if (typeof element == 'undefined') { throw new Error('PgwSlider - The element ' + elementId + ' is undefined'); return false; } if (typeof direction == 'undefined') { direction = 'left'; } // Before slide if (typeof pgwSlider.config.beforeSlide == 'function') { pgwSlider.config.beforeSlide(elementId); } if (typeof pgwSlider.plugin.find('.ps-caption').fadeOut == 'function') { pgwSlider.plugin.find('.ps-caption, .ps-prev, .ps-next').fadeOut(pgwSlider.config.transitionDuration / 2); } else { pgwSlider.plugin.find('.ps-caption, .ps-prev, .ps-next').hide(); } // Choose the transition effect if (pgwSlider.config.transitionEffect == 'sliding') { slideElement(element, direction); } else { fadeElement(element); } // Reset interval to avoid a half interval after an API control if (typeof apiController != 'undefined' && pgwSlider.config.autoSlide) { activateInterval(); } return true; }
javascript
function(elementId, apiController, direction) { if (elementId == pgwSlider.currentSlide) { return false; } var element = pgwSlider.data[elementId - 1]; if (typeof element == 'undefined') { throw new Error('PgwSlider - The element ' + elementId + ' is undefined'); return false; } if (typeof direction == 'undefined') { direction = 'left'; } // Before slide if (typeof pgwSlider.config.beforeSlide == 'function') { pgwSlider.config.beforeSlide(elementId); } if (typeof pgwSlider.plugin.find('.ps-caption').fadeOut == 'function') { pgwSlider.plugin.find('.ps-caption, .ps-prev, .ps-next').fadeOut(pgwSlider.config.transitionDuration / 2); } else { pgwSlider.plugin.find('.ps-caption, .ps-prev, .ps-next').hide(); } // Choose the transition effect if (pgwSlider.config.transitionEffect == 'sliding') { slideElement(element, direction); } else { fadeElement(element); } // Reset interval to avoid a half interval after an API control if (typeof apiController != 'undefined' && pgwSlider.config.autoSlide) { activateInterval(); } return true; }
[ "function", "(", "elementId", ",", "apiController", ",", "direction", ")", "{", "if", "(", "elementId", "==", "pgwSlider", ".", "currentSlide", ")", "{", "return", "false", ";", "}", "var", "element", "=", "pgwSlider", ".", "data", "[", "elementId", "-", "1", "]", ";", "if", "(", "typeof", "element", "==", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'PgwSlider - The element '", "+", "elementId", "+", "' is undefined'", ")", ";", "return", "false", ";", "}", "if", "(", "typeof", "direction", "==", "'undefined'", ")", "{", "direction", "=", "'left'", ";", "}", "// Before slide", "if", "(", "typeof", "pgwSlider", ".", "config", ".", "beforeSlide", "==", "'function'", ")", "{", "pgwSlider", ".", "config", ".", "beforeSlide", "(", "elementId", ")", ";", "}", "if", "(", "typeof", "pgwSlider", ".", "plugin", ".", "find", "(", "'.ps-caption'", ")", ".", "fadeOut", "==", "'function'", ")", "{", "pgwSlider", ".", "plugin", ".", "find", "(", "'.ps-caption, .ps-prev, .ps-next'", ")", ".", "fadeOut", "(", "pgwSlider", ".", "config", ".", "transitionDuration", "/", "2", ")", ";", "}", "else", "{", "pgwSlider", ".", "plugin", ".", "find", "(", "'.ps-caption, .ps-prev, .ps-next'", ")", ".", "hide", "(", ")", ";", "}", "// Choose the transition effect", "if", "(", "pgwSlider", ".", "config", ".", "transitionEffect", "==", "'sliding'", ")", "{", "slideElement", "(", "element", ",", "direction", ")", ";", "}", "else", "{", "fadeElement", "(", "element", ")", ";", "}", "// Reset interval to avoid a half interval after an API control", "if", "(", "typeof", "apiController", "!=", "'undefined'", "&&", "pgwSlider", ".", "config", ".", "autoSlide", ")", "{", "activateInterval", "(", ")", ";", "}", "return", "true", ";", "}" ]
Display the current element
[ "Display", "the", "current", "element" ]
f180a3378d7446216cc927f21fff1714579e769f
https://github.com/Pagawa/PgwSlider/blob/f180a3378d7446216cc927f21fff1714579e769f/pgwslider.js#L580-L621
21,925
kuzzleio/koncorde
lib/storage/removeOperands.js
destroy
function destroy(foPairs, index, collection, operand) { if (foPairs[index][collection].size === 1) { if (containsOne(foPairs[index])) { delete foPairs[index]; } else { delete foPairs[index][collection]; } }else { foPairs[index][collection].delete(operand); } }
javascript
function destroy(foPairs, index, collection, operand) { if (foPairs[index][collection].size === 1) { if (containsOne(foPairs[index])) { delete foPairs[index]; } else { delete foPairs[index][collection]; } }else { foPairs[index][collection].delete(operand); } }
[ "function", "destroy", "(", "foPairs", ",", "index", ",", "collection", ",", "operand", ")", "{", "if", "(", "foPairs", "[", "index", "]", "[", "collection", "]", ".", "size", "===", "1", ")", "{", "if", "(", "containsOne", "(", "foPairs", "[", "index", "]", ")", ")", "{", "delete", "foPairs", "[", "index", "]", ";", "}", "else", "{", "delete", "foPairs", "[", "index", "]", "[", "collection", "]", ";", "}", "}", "else", "{", "foPairs", "[", "index", "]", "[", "collection", "]", ".", "delete", "(", "operand", ")", ";", "}", "}" ]
Performs a cascading removal of a field-operand pair @param foPairs @param index @param collection @param operand
[ "Performs", "a", "cascading", "removal", "of", "a", "field", "-", "operand", "pair" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/storage/removeOperands.js#L336-L346
21,926
kuzzleio/koncorde
lib/transform/canonical.js
evalFilter
function evalFilter(filters, results, pos = {value: 0}) { const key = Object.keys(filters)[0]; if (['and', 'or', 'not'].indexOf(key) === -1 || filters._isLeaf) { pos.value++; return results[pos.value - 1]; } if (key === 'not') { return !evalFilter(filters[key], results, pos); } return filters[key].reduce((p, c) => { const r = evalFilter(c, results, pos); if (p === null) { return r; } return key === 'and' ? p && r : p || r; }, null); }
javascript
function evalFilter(filters, results, pos = {value: 0}) { const key = Object.keys(filters)[0]; if (['and', 'or', 'not'].indexOf(key) === -1 || filters._isLeaf) { pos.value++; return results[pos.value - 1]; } if (key === 'not') { return !evalFilter(filters[key], results, pos); } return filters[key].reduce((p, c) => { const r = evalFilter(c, results, pos); if (p === null) { return r; } return key === 'and' ? p && r : p || r; }, null); }
[ "function", "evalFilter", "(", "filters", ",", "results", ",", "pos", "=", "{", "value", ":", "0", "}", ")", "{", "const", "key", "=", "Object", ".", "keys", "(", "filters", ")", "[", "0", "]", ";", "if", "(", "[", "'and'", ",", "'or'", ",", "'not'", "]", ".", "indexOf", "(", "key", ")", "===", "-", "1", "||", "filters", ".", "_isLeaf", ")", "{", "pos", ".", "value", "++", ";", "return", "results", "[", "pos", ".", "value", "-", "1", "]", ";", "}", "if", "(", "key", "===", "'not'", ")", "{", "return", "!", "evalFilter", "(", "filters", "[", "key", "]", ",", "results", ",", "pos", ")", ";", "}", "return", "filters", "[", "key", "]", ".", "reduce", "(", "(", "p", ",", "c", ")", "=>", "{", "const", "r", "=", "evalFilter", "(", "c", ",", "results", ",", "pos", ")", ";", "if", "(", "p", "===", "null", ")", "{", "return", "r", ";", "}", "return", "key", "===", "'and'", "?", "p", "&&", "r", ":", "p", "||", "r", ";", "}", ",", "null", ")", ";", "}" ]
Given a boolean array containing the conditions results, returns a boolean indicating the whole filter result @param {object} filters @param {Array} results - condition results, contains booleans @param {object} [pos] - current condition position @returns {boolean}
[ "Given", "a", "boolean", "array", "containing", "the", "conditions", "results", "returns", "a", "boolean", "indicating", "the", "whole", "filter", "result" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/canonical.js#L403-L424
21,927
kuzzleio/koncorde
lib/transform/standardize.js
onlyOneFieldAttribute
function onlyOneFieldAttribute(fieldsList, keyword) { if (fieldsList.length > 1) { return Bluebird.reject(new BadRequestError(`"${keyword}" can contain only one attribute`)); } return Bluebird.resolve(fieldsList); }
javascript
function onlyOneFieldAttribute(fieldsList, keyword) { if (fieldsList.length > 1) { return Bluebird.reject(new BadRequestError(`"${keyword}" can contain only one attribute`)); } return Bluebird.resolve(fieldsList); }
[ "function", "onlyOneFieldAttribute", "(", "fieldsList", ",", "keyword", ")", "{", "if", "(", "fieldsList", ".", "length", ">", "1", ")", "{", "return", "Bluebird", ".", "reject", "(", "new", "BadRequestError", "(", "`", "${", "keyword", "}", "`", ")", ")", ";", "}", "return", "Bluebird", ".", "resolve", "(", "fieldsList", ")", ";", "}" ]
Verifies that "filter" contains only 1 field @param {Array} fieldsList @param {string} keyword @returns {Promise} Promise resolving to the provided fields list
[ "Verifies", "that", "filter", "contains", "only", "1", "field" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L691-L697
21,928
kuzzleio/koncorde
lib/transform/standardize.js
requireAttribute
function requireAttribute(filter, keyword, attribute) { if (!filter[attribute]) { return Bluebird.reject(new BadRequestError(`"${keyword}" requires the following attribute: ${attribute}`)); } return Bluebird.resolve(); }
javascript
function requireAttribute(filter, keyword, attribute) { if (!filter[attribute]) { return Bluebird.reject(new BadRequestError(`"${keyword}" requires the following attribute: ${attribute}`)); } return Bluebird.resolve(); }
[ "function", "requireAttribute", "(", "filter", ",", "keyword", ",", "attribute", ")", "{", "if", "(", "!", "filter", "[", "attribute", "]", ")", "{", "return", "Bluebird", ".", "reject", "(", "new", "BadRequestError", "(", "`", "${", "keyword", "}", "${", "attribute", "}", "`", ")", ")", ";", "}", "return", "Bluebird", ".", "resolve", "(", ")", ";", "}" ]
Verifies that "filter.attribute' exists @param filter @param keyword @param attribute @returns {Promise}
[ "Verifies", "that", "filter", ".", "attribute", "exists" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L706-L712
21,929
kuzzleio/koncorde
lib/transform/standardize.js
mustBeNonEmptyObject
function mustBeNonEmptyObject(filter, keyword) { if (!filter || typeof filter !== 'object' || Array.isArray(filter)) { return Bluebird.reject(new BadRequestError(`"${keyword}" must be a non-empty object`)); } const fields = Object.keys(filter); if (fields.length === 0) { return Bluebird.reject(new BadRequestError(`"${keyword}" must be a non-empty object`)); } return Bluebird.resolve(fields); }
javascript
function mustBeNonEmptyObject(filter, keyword) { if (!filter || typeof filter !== 'object' || Array.isArray(filter)) { return Bluebird.reject(new BadRequestError(`"${keyword}" must be a non-empty object`)); } const fields = Object.keys(filter); if (fields.length === 0) { return Bluebird.reject(new BadRequestError(`"${keyword}" must be a non-empty object`)); } return Bluebird.resolve(fields); }
[ "function", "mustBeNonEmptyObject", "(", "filter", ",", "keyword", ")", "{", "if", "(", "!", "filter", "||", "typeof", "filter", "!==", "'object'", "||", "Array", ".", "isArray", "(", "filter", ")", ")", "{", "return", "Bluebird", ".", "reject", "(", "new", "BadRequestError", "(", "`", "${", "keyword", "}", "`", ")", ")", ";", "}", "const", "fields", "=", "Object", ".", "keys", "(", "filter", ")", ";", "if", "(", "fields", ".", "length", "===", "0", ")", "{", "return", "Bluebird", ".", "reject", "(", "new", "BadRequestError", "(", "`", "${", "keyword", "}", "`", ")", ")", ";", "}", "return", "Bluebird", ".", "resolve", "(", "fields", ")", ";", "}" ]
Tests if "filter" is a non-object @param {object} filter @param {string} keyword @returns {Promise} Promise resolving to the object's keys
[ "Tests", "if", "filter", "is", "a", "non", "-", "object" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L720-L732
21,930
kuzzleio/koncorde
lib/transform/standardize.js
mustBeScalar
function mustBeScalar(filter, keyword, field) { if (filter[field] instanceof Object || filter[field] === undefined) { return Bluebird.reject(new BadRequestError(`"${field}" in "${keyword}" must be either a string, a number, a boolean or null`)); } return Bluebird.resolve(); }
javascript
function mustBeScalar(filter, keyword, field) { if (filter[field] instanceof Object || filter[field] === undefined) { return Bluebird.reject(new BadRequestError(`"${field}" in "${keyword}" must be either a string, a number, a boolean or null`)); } return Bluebird.resolve(); }
[ "function", "mustBeScalar", "(", "filter", ",", "keyword", ",", "field", ")", "{", "if", "(", "filter", "[", "field", "]", "instanceof", "Object", "||", "filter", "[", "field", "]", "===", "undefined", ")", "{", "return", "Bluebird", ".", "reject", "(", "new", "BadRequestError", "(", "`", "${", "field", "}", "${", "keyword", "}", "`", ")", ")", ";", "}", "return", "Bluebird", ".", "resolve", "(", ")", ";", "}" ]
Checks that filter.field is a scalar value @param filter @param keyword @param field @returns {*}
[ "Checks", "that", "filter", ".", "field", "is", "a", "scalar", "value" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L741-L747
21,931
kuzzleio/koncorde
lib/transform/standardize.js
mustBeString
function mustBeString(filter, keyword, field) { if (typeof filter[field] !== 'string') { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be a string`)); } return Bluebird.resolve(); }
javascript
function mustBeString(filter, keyword, field) { if (typeof filter[field] !== 'string') { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be a string`)); } return Bluebird.resolve(); }
[ "function", "mustBeString", "(", "filter", ",", "keyword", ",", "field", ")", "{", "if", "(", "typeof", "filter", "[", "field", "]", "!==", "'string'", ")", "{", "return", "Bluebird", ".", "reject", "(", "new", "BadRequestError", "(", "`", "${", "field", "}", "${", "keyword", "}", "`", ")", ")", ";", "}", "return", "Bluebird", ".", "resolve", "(", ")", ";", "}" ]
Verifies that filter.field is a string @param filter @param keyword @param field @returns {Promise}
[ "Verifies", "that", "filter", ".", "field", "is", "a", "string" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L756-L762
21,932
kuzzleio/koncorde
lib/transform/standardize.js
mustBeNonEmptyArray
function mustBeNonEmptyArray(filter, keyword, field) { if (!Array.isArray(filter[field])) { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be an array`)); } if (filter[field].length === 0) { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" cannot be empty`)); } return Bluebird.resolve(); }
javascript
function mustBeNonEmptyArray(filter, keyword, field) { if (!Array.isArray(filter[field])) { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be an array`)); } if (filter[field].length === 0) { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" cannot be empty`)); } return Bluebird.resolve(); }
[ "function", "mustBeNonEmptyArray", "(", "filter", ",", "keyword", ",", "field", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "filter", "[", "field", "]", ")", ")", "{", "return", "Bluebird", ".", "reject", "(", "new", "BadRequestError", "(", "`", "${", "field", "}", "${", "keyword", "}", "`", ")", ")", ";", "}", "if", "(", "filter", "[", "field", "]", ".", "length", "===", "0", ")", "{", "return", "Bluebird", ".", "reject", "(", "new", "BadRequestError", "(", "`", "${", "field", "}", "${", "keyword", "}", "`", ")", ")", ";", "}", "return", "Bluebird", ".", "resolve", "(", ")", ";", "}" ]
Verifies that filter.field is an array @param filter @param keyword @param field @returns {Promise}
[ "Verifies", "that", "filter", ".", "field", "is", "an", "array" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L771-L781
21,933
kuzzleio/koncorde
lib/storage/storeOperands.js
storeGeoshape
function storeGeoshape(index, type, id, shape) { switch (type) { case 'geoBoundingBox': index.addBoundingBox(id, shape.bottom, shape.left, shape.top, shape.right ); break; case 'geoDistance': index.addCircle(id, shape.lat, shape.lon, shape.distance); break; case 'geoDistanceRange': index.addAnnulus(id, shape.lat, shape.lon, shape.to, shape.from); break; case 'geoPolygon': index.addPolygon(id, shape); break; default: break; } }
javascript
function storeGeoshape(index, type, id, shape) { switch (type) { case 'geoBoundingBox': index.addBoundingBox(id, shape.bottom, shape.left, shape.top, shape.right ); break; case 'geoDistance': index.addCircle(id, shape.lat, shape.lon, shape.distance); break; case 'geoDistanceRange': index.addAnnulus(id, shape.lat, shape.lon, shape.to, shape.from); break; case 'geoPolygon': index.addPolygon(id, shape); break; default: break; } }
[ "function", "storeGeoshape", "(", "index", ",", "type", ",", "id", ",", "shape", ")", "{", "switch", "(", "type", ")", "{", "case", "'geoBoundingBox'", ":", "index", ".", "addBoundingBox", "(", "id", ",", "shape", ".", "bottom", ",", "shape", ".", "left", ",", "shape", ".", "top", ",", "shape", ".", "right", ")", ";", "break", ";", "case", "'geoDistance'", ":", "index", ".", "addCircle", "(", "id", ",", "shape", ".", "lat", ",", "shape", ".", "lon", ",", "shape", ".", "distance", ")", ";", "break", ";", "case", "'geoDistanceRange'", ":", "index", ".", "addAnnulus", "(", "id", ",", "shape", ".", "lat", ",", "shape", ".", "lon", ",", "shape", ".", "to", ",", "shape", ".", "from", ")", ";", "break", ";", "case", "'geoPolygon'", ":", "index", ".", "addPolygon", "(", "id", ",", "shape", ")", ";", "break", ";", "default", ":", "break", ";", "}", "}" ]
Stores a geospatial shape in the provided index object. @param {object} index @param {string} type @param {string} id @param {Object|Array} shape
[ "Stores", "a", "geospatial", "shape", "in", "the", "provided", "index", "object", "." ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/storage/storeOperands.js#L299-L321
21,934
kuzzleio/koncorde
lib/util/convertGeopoint.js
convertGeopoint
function convertGeopoint (point) { const t = typeof point; if (!point || (t !== 'string' && t !== 'object')) { return null; } // Format: "lat, lon" or "geohash" if (t === 'string') { return fromString(point); } // Format: [lat, lon] if (Array.isArray(point)) { if (point.length === 2) { return toCoordinate(point[0], point[1]); } return null; } const camelCased = geoLocationToCamelCase(point); // Format: { lat, lon } if (camelCased.hasOwnProperty('lat') && camelCased.hasOwnProperty('lon')) { return toCoordinate(camelCased.lat, camelCased.lon); } if (camelCased.latLon) { // Format: { latLon: [lat, lon] } if (Array.isArray(camelCased.latLon)) { if (camelCased.latLon.length === 2) { return toCoordinate(camelCased.latLon[0], camelCased.latLon[1]); } return null; } // Format: { latLon: { lat, lon } } if (typeof camelCased.latLon === 'object' && camelCased.latLon.hasOwnProperty('lat') && camelCased.latLon.hasOwnProperty('lon')) { return toCoordinate(camelCased.latLon.lat, camelCased.latLon.lon); } if (typeof camelCased.latLon === 'string') { return fromString(camelCased.latLon); } } return null; }
javascript
function convertGeopoint (point) { const t = typeof point; if (!point || (t !== 'string' && t !== 'object')) { return null; } // Format: "lat, lon" or "geohash" if (t === 'string') { return fromString(point); } // Format: [lat, lon] if (Array.isArray(point)) { if (point.length === 2) { return toCoordinate(point[0], point[1]); } return null; } const camelCased = geoLocationToCamelCase(point); // Format: { lat, lon } if (camelCased.hasOwnProperty('lat') && camelCased.hasOwnProperty('lon')) { return toCoordinate(camelCased.lat, camelCased.lon); } if (camelCased.latLon) { // Format: { latLon: [lat, lon] } if (Array.isArray(camelCased.latLon)) { if (camelCased.latLon.length === 2) { return toCoordinate(camelCased.latLon[0], camelCased.latLon[1]); } return null; } // Format: { latLon: { lat, lon } } if (typeof camelCased.latLon === 'object' && camelCased.latLon.hasOwnProperty('lat') && camelCased.latLon.hasOwnProperty('lon')) { return toCoordinate(camelCased.latLon.lat, camelCased.latLon.lon); } if (typeof camelCased.latLon === 'string') { return fromString(camelCased.latLon); } } return null; }
[ "function", "convertGeopoint", "(", "point", ")", "{", "const", "t", "=", "typeof", "point", ";", "if", "(", "!", "point", "||", "(", "t", "!==", "'string'", "&&", "t", "!==", "'object'", ")", ")", "{", "return", "null", ";", "}", "// Format: \"lat, lon\" or \"geohash\"", "if", "(", "t", "===", "'string'", ")", "{", "return", "fromString", "(", "point", ")", ";", "}", "// Format: [lat, lon]", "if", "(", "Array", ".", "isArray", "(", "point", ")", ")", "{", "if", "(", "point", ".", "length", "===", "2", ")", "{", "return", "toCoordinate", "(", "point", "[", "0", "]", ",", "point", "[", "1", "]", ")", ";", "}", "return", "null", ";", "}", "const", "camelCased", "=", "geoLocationToCamelCase", "(", "point", ")", ";", "// Format: { lat, lon }", "if", "(", "camelCased", ".", "hasOwnProperty", "(", "'lat'", ")", "&&", "camelCased", ".", "hasOwnProperty", "(", "'lon'", ")", ")", "{", "return", "toCoordinate", "(", "camelCased", ".", "lat", ",", "camelCased", ".", "lon", ")", ";", "}", "if", "(", "camelCased", ".", "latLon", ")", "{", "// Format: { latLon: [lat, lon] }", "if", "(", "Array", ".", "isArray", "(", "camelCased", ".", "latLon", ")", ")", "{", "if", "(", "camelCased", ".", "latLon", ".", "length", "===", "2", ")", "{", "return", "toCoordinate", "(", "camelCased", ".", "latLon", "[", "0", "]", ",", "camelCased", ".", "latLon", "[", "1", "]", ")", ";", "}", "return", "null", ";", "}", "// Format: { latLon: { lat, lon } }", "if", "(", "typeof", "camelCased", ".", "latLon", "===", "'object'", "&&", "camelCased", ".", "latLon", ".", "hasOwnProperty", "(", "'lat'", ")", "&&", "camelCased", ".", "latLon", ".", "hasOwnProperty", "(", "'lon'", ")", ")", "{", "return", "toCoordinate", "(", "camelCased", ".", "latLon", ".", "lat", ",", "camelCased", ".", "latLon", ".", "lon", ")", ";", "}", "if", "(", "typeof", "camelCased", ".", "latLon", "===", "'string'", ")", "{", "return", "fromString", "(", "camelCased", ".", "latLon", ")", ";", "}", "}", "return", "null", ";", "}" ]
Converts one of the accepted geopoint format into a standardized version @param {*} point - geopoint field to convert @returns {Coordinate} or null if no accepted format is found
[ "Converts", "one", "of", "the", "accepted", "geopoint", "format", "into", "a", "standardized", "version" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/util/convertGeopoint.js#L40-L89
21,935
kuzzleio/koncorde
lib/util/convertGeopoint.js
fromString
function fromString(str) { let tmp = str.match(regexLatLon), converted = null; // Format: "latitude, longitude" if (tmp !== null) { converted = toCoordinate(tmp[1], tmp[2]); } // Format: "<geohash>" else if (regexGeohash.test(str)) { tmp = geohash.decode(str); converted = toCoordinate(tmp.latitude, tmp.longitude); } return converted; }
javascript
function fromString(str) { let tmp = str.match(regexLatLon), converted = null; // Format: "latitude, longitude" if (tmp !== null) { converted = toCoordinate(tmp[1], tmp[2]); } // Format: "<geohash>" else if (regexGeohash.test(str)) { tmp = geohash.decode(str); converted = toCoordinate(tmp.latitude, tmp.longitude); } return converted; }
[ "function", "fromString", "(", "str", ")", "{", "let", "tmp", "=", "str", ".", "match", "(", "regexLatLon", ")", ",", "converted", "=", "null", ";", "// Format: \"latitude, longitude\"", "if", "(", "tmp", "!==", "null", ")", "{", "converted", "=", "toCoordinate", "(", "tmp", "[", "1", "]", ",", "tmp", "[", "2", "]", ")", ";", "}", "// Format: \"<geohash>\"", "else", "if", "(", "regexGeohash", ".", "test", "(", "str", ")", ")", "{", "tmp", "=", "geohash", ".", "decode", "(", "str", ")", ";", "converted", "=", "toCoordinate", "(", "tmp", ".", "latitude", ",", "tmp", ".", "longitude", ")", ";", "}", "return", "converted", ";", "}" ]
Converts a geopoint from a string description @param {string} str @return {Coordinate}
[ "Converts", "a", "geopoint", "from", "a", "string", "description" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/util/convertGeopoint.js#L97-L113
21,936
kuzzleio/koncorde
lib/util/geoLocationToCamelCase.js
geoLocationToCamelCase
function geoLocationToCamelCase (obj) { const converted = {}, keys = Object.keys(obj); let i; // NOSONAR for(i = 0; i < keys.length; i++) { const k = keys[i], idx = ['lat_lon', 'top_left', 'bottom_right'].indexOf(k); if (idx === -1) { converted[k] = obj[k]; } else { converted[k .split('_') .map((v,j) => j === 0 ? v : v.charAt(0).toUpperCase() + v.substring(1)) .join('')] = obj[k]; } } return converted; }
javascript
function geoLocationToCamelCase (obj) { const converted = {}, keys = Object.keys(obj); let i; // NOSONAR for(i = 0; i < keys.length; i++) { const k = keys[i], idx = ['lat_lon', 'top_left', 'bottom_right'].indexOf(k); if (idx === -1) { converted[k] = obj[k]; } else { converted[k .split('_') .map((v,j) => j === 0 ? v : v.charAt(0).toUpperCase() + v.substring(1)) .join('')] = obj[k]; } } return converted; }
[ "function", "geoLocationToCamelCase", "(", "obj", ")", "{", "const", "converted", "=", "{", "}", ",", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "let", "i", ";", "// NOSONAR", "for", "(", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "const", "k", "=", "keys", "[", "i", "]", ",", "idx", "=", "[", "'lat_lon'", ",", "'top_left'", ",", "'bottom_right'", "]", ".", "indexOf", "(", "k", ")", ";", "if", "(", "idx", "===", "-", "1", ")", "{", "converted", "[", "k", "]", "=", "obj", "[", "k", "]", ";", "}", "else", "{", "converted", "[", "k", ".", "split", "(", "'_'", ")", ".", "map", "(", "(", "v", ",", "j", ")", "=>", "j", "===", "0", "?", "v", ":", "v", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "v", ".", "substring", "(", "1", ")", ")", ".", "join", "(", "''", ")", "]", "=", "obj", "[", "k", "]", ";", "}", "}", "return", "converted", ";", "}" ]
Converts known geolocation fields from snake_case to camelCase Other fields are copied without change @param {object} obj - object containing geolocation fields @returns {object} new object with converted fields
[ "Converts", "known", "geolocation", "fields", "from", "snake_case", "to", "camelCase", "Other", "fields", "are", "copied", "without", "change" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/util/geoLocationToCamelCase.js#L31-L54
21,937
kuzzleio/koncorde
lib/util/convertDistance.js
convertDistance
function convertDistance (distance) { let cleaned, converted; // clean up to ensure node-units will be able to convert it // for instance: "3 258,55 Ft" => "3258.55 ft" cleaned = distance .replace(/[-\s]/g, '') .replace(/,/g, '.') .toLowerCase() .replace(/([0-9])([a-z])/, '$1 $2'); try { converted = units.convert(cleaned + ' to m'); } catch (e) { throw new BadRequestError(`unable to parse distance value "${distance}"`); } return converted; }
javascript
function convertDistance (distance) { let cleaned, converted; // clean up to ensure node-units will be able to convert it // for instance: "3 258,55 Ft" => "3258.55 ft" cleaned = distance .replace(/[-\s]/g, '') .replace(/,/g, '.') .toLowerCase() .replace(/([0-9])([a-z])/, '$1 $2'); try { converted = units.convert(cleaned + ' to m'); } catch (e) { throw new BadRequestError(`unable to parse distance value "${distance}"`); } return converted; }
[ "function", "convertDistance", "(", "distance", ")", "{", "let", "cleaned", ",", "converted", ";", "// clean up to ensure node-units will be able to convert it", "// for instance: \"3 258,55 Ft\" => \"3258.55 ft\"", "cleaned", "=", "distance", ".", "replace", "(", "/", "[-\\s]", "/", "g", ",", "''", ")", ".", "replace", "(", "/", ",", "/", "g", ",", "'.'", ")", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "([0-9])([a-z])", "/", ",", "'$1 $2'", ")", ";", "try", "{", "converted", "=", "units", ".", "convert", "(", "cleaned", "+", "' to m'", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "BadRequestError", "(", "`", "${", "distance", "}", "`", ")", ";", "}", "return", "converted", ";", "}" ]
Converts a distance string value to a number of meters @param {string} distance - client-provided distance @returns {number} resolves to converted distance
[ "Converts", "a", "distance", "string", "value", "to", "a", "number", "of", "meters" ]
e23403920517494f86b7a566acf89d527065c4a2
https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/util/convertDistance.js#L33-L52
21,938
tiaanduplessis/react-native-modest-cache
index.js
dateAdd
function dateAdd (date, interval, units) { let result = new Date(date) switch (interval.toLowerCase()) { case 'year': result.setFullYear(result.getFullYear() + units) break case 'quarter': result.setMonth(result.getMonth() + 3 * units) break case 'month': result.setMonth(result.getMonth() + units) break case 'week': result.setDate(result.getDate() + 7 * units) break case 'day': result.setDate(result.getDate() + units) break case 'hour': result.setTime(result.getTime() + units * 3600000) break case 'minute': result.setTime(result.getTime() + units * 60000) break case 'second': result.setTime(result.getTime() + units * 1000) break default: result = undefined break } return result }
javascript
function dateAdd (date, interval, units) { let result = new Date(date) switch (interval.toLowerCase()) { case 'year': result.setFullYear(result.getFullYear() + units) break case 'quarter': result.setMonth(result.getMonth() + 3 * units) break case 'month': result.setMonth(result.getMonth() + units) break case 'week': result.setDate(result.getDate() + 7 * units) break case 'day': result.setDate(result.getDate() + units) break case 'hour': result.setTime(result.getTime() + units * 3600000) break case 'minute': result.setTime(result.getTime() + units * 60000) break case 'second': result.setTime(result.getTime() + units * 1000) break default: result = undefined break } return result }
[ "function", "dateAdd", "(", "date", ",", "interval", ",", "units", ")", "{", "let", "result", "=", "new", "Date", "(", "date", ")", "switch", "(", "interval", ".", "toLowerCase", "(", ")", ")", "{", "case", "'year'", ":", "result", ".", "setFullYear", "(", "result", ".", "getFullYear", "(", ")", "+", "units", ")", "break", "case", "'quarter'", ":", "result", ".", "setMonth", "(", "result", ".", "getMonth", "(", ")", "+", "3", "*", "units", ")", "break", "case", "'month'", ":", "result", ".", "setMonth", "(", "result", ".", "getMonth", "(", ")", "+", "units", ")", "break", "case", "'week'", ":", "result", ".", "setDate", "(", "result", ".", "getDate", "(", ")", "+", "7", "*", "units", ")", "break", "case", "'day'", ":", "result", ".", "setDate", "(", "result", ".", "getDate", "(", ")", "+", "units", ")", "break", "case", "'hour'", ":", "result", ".", "setTime", "(", "result", ".", "getTime", "(", ")", "+", "units", "*", "3600000", ")", "break", "case", "'minute'", ":", "result", ".", "setTime", "(", "result", ".", "getTime", "(", ")", "+", "units", "*", "60000", ")", "break", "case", "'second'", ":", "result", ".", "setTime", "(", "result", ".", "getTime", "(", ")", "+", "units", "*", "1000", ")", "break", "default", ":", "result", "=", "undefined", "break", "}", "return", "result", "}" ]
Utility function to add units to date based on interval @param {Date} date @param {String} interval @param {Number} units
[ "Utility", "function", "to", "add", "units", "to", "date", "based", "on", "interval" ]
308de78c66c894b83da169ff43d7cbd356b88c76
https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L12-L45
21,939
tiaanduplessis/react-native-modest-cache
index.js
set
function set (key, value, time = 60) { let expireTime const cacheKey = `${prefix}${key}` const expireKey = `${expire}${key}` if (typeof time === 'number') { expireTime = dateAdd(Date.now(), 'minute', time) } else if (time !== null && typeof time === 'object' && time.interval && time.units) { expireTime = dateAdd(Date.now(), time.interval, time.units) } else { throw new Error('Invalid time provided for set') } return storage.set(expireKey, expireTime).then(() => storage.set(cacheKey, value)) }
javascript
function set (key, value, time = 60) { let expireTime const cacheKey = `${prefix}${key}` const expireKey = `${expire}${key}` if (typeof time === 'number') { expireTime = dateAdd(Date.now(), 'minute', time) } else if (time !== null && typeof time === 'object' && time.interval && time.units) { expireTime = dateAdd(Date.now(), time.interval, time.units) } else { throw new Error('Invalid time provided for set') } return storage.set(expireKey, expireTime).then(() => storage.set(cacheKey, value)) }
[ "function", "set", "(", "key", ",", "value", ",", "time", "=", "60", ")", "{", "let", "expireTime", "const", "cacheKey", "=", "`", "${", "prefix", "}", "${", "key", "}", "`", "const", "expireKey", "=", "`", "${", "expire", "}", "${", "key", "}", "`", "if", "(", "typeof", "time", "===", "'number'", ")", "{", "expireTime", "=", "dateAdd", "(", "Date", ".", "now", "(", ")", ",", "'minute'", ",", "time", ")", "}", "else", "if", "(", "time", "!==", "null", "&&", "typeof", "time", "===", "'object'", "&&", "time", ".", "interval", "&&", "time", ".", "units", ")", "{", "expireTime", "=", "dateAdd", "(", "Date", ".", "now", "(", ")", ",", "time", ".", "interval", ",", "time", ".", "units", ")", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid time provided for set'", ")", "}", "return", "storage", ".", "set", "(", "expireKey", ",", "expireTime", ")", ".", "then", "(", "(", ")", "=>", "storage", ".", "set", "(", "cacheKey", ",", "value", ")", ")", "}" ]
Persist value and expire date of cache. @param {string} key @param {Any} value Value to persist @param {Number or Object} [time=60] Time in minutes @returns {Promise}
[ "Persist", "value", "and", "expire", "date", "of", "cache", "." ]
308de78c66c894b83da169ff43d7cbd356b88c76
https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L55-L69
21,940
tiaanduplessis/react-native-modest-cache
index.js
remove
function remove (key) { if (typeof key !== 'string') { throw new Error('Invalid key provided for remove') } const keys = [`${prefix}${key}`, `${expire}${key}`] return storage.remove(keys) }
javascript
function remove (key) { if (typeof key !== 'string') { throw new Error('Invalid key provided for remove') } const keys = [`${prefix}${key}`, `${expire}${key}`] return storage.remove(keys) }
[ "function", "remove", "(", "key", ")", "{", "if", "(", "typeof", "key", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Invalid key provided for remove'", ")", "}", "const", "keys", "=", "[", "`", "${", "prefix", "}", "${", "key", "}", "`", ",", "`", "${", "expire", "}", "${", "key", "}", "`", "]", "return", "storage", ".", "remove", "(", "keys", ")", "}" ]
Remove cached value from storage @param {String} key
[ "Remove", "cached", "value", "from", "storage" ]
308de78c66c894b83da169ff43d7cbd356b88c76
https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L75-L82
21,941
tiaanduplessis/react-native-modest-cache
index.js
isExpired
function isExpired (key) { const expireKey = `${expire}${key}` return storage .get(expireKey) .then(time => Promise.resolve(Date.now() >= new Date(time).getTime(), time)) }
javascript
function isExpired (key) { const expireKey = `${expire}${key}` return storage .get(expireKey) .then(time => Promise.resolve(Date.now() >= new Date(time).getTime(), time)) }
[ "function", "isExpired", "(", "key", ")", "{", "const", "expireKey", "=", "`", "${", "expire", "}", "${", "key", "}", "`", "return", "storage", ".", "get", "(", "expireKey", ")", ".", "then", "(", "time", "=>", "Promise", ".", "resolve", "(", "Date", ".", "now", "(", ")", ">=", "new", "Date", "(", "time", ")", ".", "getTime", "(", ")", ",", "time", ")", ")", "}" ]
Determine if cache has expired @param {String} key
[ "Determine", "if", "cache", "has", "expired" ]
308de78c66c894b83da169ff43d7cbd356b88c76
https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L88-L93
21,942
tiaanduplessis/react-native-modest-cache
index.js
get
function get (key) { return isExpired(key).then(hasExpired => { if (hasExpired) { return remove(key).then(() => Promise.resolve(undefined)) } else { return storage.get(`${prefix}${key}`) } }) }
javascript
function get (key) { return isExpired(key).then(hasExpired => { if (hasExpired) { return remove(key).then(() => Promise.resolve(undefined)) } else { return storage.get(`${prefix}${key}`) } }) }
[ "function", "get", "(", "key", ")", "{", "return", "isExpired", "(", "key", ")", ".", "then", "(", "hasExpired", "=>", "{", "if", "(", "hasExpired", ")", "{", "return", "remove", "(", "key", ")", ".", "then", "(", "(", ")", "=>", "Promise", ".", "resolve", "(", "undefined", ")", ")", "}", "else", "{", "return", "storage", ".", "get", "(", "`", "${", "prefix", "}", "${", "key", "}", "`", ")", "}", "}", ")", "}" ]
Retrieve value from cache. Remove if expired. @param {String} key
[ "Retrieve", "value", "from", "cache", ".", "Remove", "if", "expired", "." ]
308de78c66c894b83da169ff43d7cbd356b88c76
https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L99-L107
21,943
tiaanduplessis/react-native-modest-cache
index.js
flush
function flush () { return storage.keys().then(keys => { return storage.remove( keys.filter(key => key.indexOf(prefix) === 0 || key.indexOf(expire) === 0) ) }) }
javascript
function flush () { return storage.keys().then(keys => { return storage.remove( keys.filter(key => key.indexOf(prefix) === 0 || key.indexOf(expire) === 0) ) }) }
[ "function", "flush", "(", ")", "{", "return", "storage", ".", "keys", "(", ")", ".", "then", "(", "keys", "=>", "{", "return", "storage", ".", "remove", "(", "keys", ".", "filter", "(", "key", "=>", "key", ".", "indexOf", "(", "prefix", ")", "===", "0", "||", "key", ".", "indexOf", "(", "expire", ")", "===", "0", ")", ")", "}", ")", "}" ]
Remove all cached values from storage
[ "Remove", "all", "cached", "values", "from", "storage" ]
308de78c66c894b83da169ff43d7cbd356b88c76
https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L112-L118
21,944
tiaanduplessis/react-native-modest-cache
index.js
flushExpired
function flushExpired () { return storage.keys().then(keys => { const cacheKeys = keys.filter(key => key.indexOf(expire) === 0) return Promise.all(cacheKeys.map(key => get(key.slice(prefix.length)))) }) }
javascript
function flushExpired () { return storage.keys().then(keys => { const cacheKeys = keys.filter(key => key.indexOf(expire) === 0) return Promise.all(cacheKeys.map(key => get(key.slice(prefix.length)))) }) }
[ "function", "flushExpired", "(", ")", "{", "return", "storage", ".", "keys", "(", ")", ".", "then", "(", "keys", "=>", "{", "const", "cacheKeys", "=", "keys", ".", "filter", "(", "key", "=>", "key", ".", "indexOf", "(", "expire", ")", "===", "0", ")", "return", "Promise", ".", "all", "(", "cacheKeys", ".", "map", "(", "key", "=>", "get", "(", "key", ".", "slice", "(", "prefix", ".", "length", ")", ")", ")", ")", "}", ")", "}" ]
Remove all expired values from storage
[ "Remove", "all", "expired", "values", "from", "storage" ]
308de78c66c894b83da169ff43d7cbd356b88c76
https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L123-L128
21,945
fb55/readabilitySAX
readabilitySAX.js
function(tagName, parent){ this.name = tagName; this.parent = parent; this.attributes = {}; this.children = []; this.tagScore = 0; this.attributeScore = 0; this.totalScore = 0; this.elementData = ""; this.info = { textLength: 0, linkLength: 0, commas: 0, density: 0, tagCount: {} }; this.isCandidate = false; }
javascript
function(tagName, parent){ this.name = tagName; this.parent = parent; this.attributes = {}; this.children = []; this.tagScore = 0; this.attributeScore = 0; this.totalScore = 0; this.elementData = ""; this.info = { textLength: 0, linkLength: 0, commas: 0, density: 0, tagCount: {} }; this.isCandidate = false; }
[ "function", "(", "tagName", ",", "parent", ")", "{", "this", ".", "name", "=", "tagName", ";", "this", ".", "parent", "=", "parent", ";", "this", ".", "attributes", "=", "{", "}", ";", "this", ".", "children", "=", "[", "]", ";", "this", ".", "tagScore", "=", "0", ";", "this", ".", "attributeScore", "=", "0", ";", "this", ".", "totalScore", "=", "0", ";", "this", ".", "elementData", "=", "\"\"", ";", "this", ".", "info", "=", "{", "textLength", ":", "0", ",", "linkLength", ":", "0", ",", "commas", ":", "0", ",", "density", ":", "0", ",", "tagCount", ":", "{", "}", "}", ";", "this", ".", "isCandidate", "=", "false", ";", "}" ]
1. the tree element
[ "1", ".", "the", "tree", "element" ]
ed3566bcc0e841f596612e295b69376ec359938c
https://github.com/fb55/readabilitySAX/blob/ed3566bcc0e841f596612e295b69376ec359938c/readabilitySAX.js#L14-L31
21,946
fb55/readabilitySAX
readabilitySAX.js
function(settings){ //the root node this._currentElement = new Element("document"); this._topCandidate = null; this._origTitle = this._headerTitle = ""; this._scannedLinks = {}; if(settings) this._processSettings(settings); }
javascript
function(settings){ //the root node this._currentElement = new Element("document"); this._topCandidate = null; this._origTitle = this._headerTitle = ""; this._scannedLinks = {}; if(settings) this._processSettings(settings); }
[ "function", "(", "settings", ")", "{", "//the root node", "this", ".", "_currentElement", "=", "new", "Element", "(", "\"document\"", ")", ";", "this", ".", "_topCandidate", "=", "null", ";", "this", ".", "_origTitle", "=", "this", ".", "_headerTitle", "=", "\"\"", ";", "this", ".", "_scannedLinks", "=", "{", "}", ";", "if", "(", "settings", ")", "this", ".", "_processSettings", "(", "settings", ")", ";", "}" ]
3. the readability class
[ "3", ".", "the", "readability", "class" ]
ed3566bcc0e841f596612e295b69376ec359938c
https://github.com/fb55/readabilitySAX/blob/ed3566bcc0e841f596612e295b69376ec359938c/readabilitySAX.js#L190-L197
21,947
silverwind/rrdir
index.js
canInclude
function canInclude(entry, opts) { if (!opts.include || !opts.include.length) return true; return !entry.isDirectory(); }
javascript
function canInclude(entry, opts) { if (!opts.include || !opts.include.length) return true; return !entry.isDirectory(); }
[ "function", "canInclude", "(", "entry", ",", "opts", ")", "{", "if", "(", "!", "opts", ".", "include", "||", "!", "opts", ".", "include", ".", "length", ")", "return", "true", ";", "return", "!", "entry", ".", "isDirectory", "(", ")", ";", "}" ]
when a include pattern is specified, stop yielding directories
[ "when", "a", "include", "pattern", "is", "specified", "stop", "yielding", "directories" ]
340889bb8e84ab81fa212e539266f06fb0778c48
https://github.com/silverwind/rrdir/blob/340889bb8e84ab81fa212e539266f06fb0778c48/index.js#L35-L38
21,948
vasturiano/canvas-color-tracker
example/circle-generator.js
genCircles
function genCircles(width, height, N = 500) { const minR = 1; const maxR = Math.sqrt(width * height / N) * 0.5; return [...Array(N)].map((_, idx) => ({ id: idx, x: Math.round(Math.random() * width), y: Math.round(Math.random() * height), r: Math.max(minR, Math.round(Math.random() * maxR)) })); }
javascript
function genCircles(width, height, N = 500) { const minR = 1; const maxR = Math.sqrt(width * height / N) * 0.5; return [...Array(N)].map((_, idx) => ({ id: idx, x: Math.round(Math.random() * width), y: Math.round(Math.random() * height), r: Math.max(minR, Math.round(Math.random() * maxR)) })); }
[ "function", "genCircles", "(", "width", ",", "height", ",", "N", "=", "500", ")", "{", "const", "minR", "=", "1", ";", "const", "maxR", "=", "Math", ".", "sqrt", "(", "width", "*", "height", "/", "N", ")", "*", "0.5", ";", "return", "[", "...", "Array", "(", "N", ")", "]", ".", "map", "(", "(", "_", ",", "idx", ")", "=>", "(", "{", "id", ":", "idx", ",", "x", ":", "Math", ".", "round", "(", "Math", ".", "random", "(", ")", "*", "width", ")", ",", "y", ":", "Math", ".", "round", "(", "Math", ".", "random", "(", ")", "*", "height", ")", ",", "r", ":", "Math", ".", "max", "(", "minR", ",", "Math", ".", "round", "(", "Math", ".", "random", "(", ")", "*", "maxR", ")", ")", "}", ")", ")", ";", "}" ]
Generate random circles
[ "Generate", "random", "circles" ]
90ac081b236a5d034ae0529f222ca2b0840ec483
https://github.com/vasturiano/canvas-color-tracker/blob/90ac081b236a5d034ae0529f222ca2b0840ec483/example/circle-generator.js#L2-L12
21,949
cloudfour/core-hbs-helpers
lib/toFraction.js
toFraction
function toFraction (value) { var integer = Math.floor(value); var decimal = value - integer; var key = n2f(decimal); var result = value; if (vulgarities.hasOwnProperty(key)) { result = integer + vulgarities[key]; } return result; }
javascript
function toFraction (value) { var integer = Math.floor(value); var decimal = value - integer; var key = n2f(decimal); var result = value; if (vulgarities.hasOwnProperty(key)) { result = integer + vulgarities[key]; } return result; }
[ "function", "toFraction", "(", "value", ")", "{", "var", "integer", "=", "Math", ".", "floor", "(", "value", ")", ";", "var", "decimal", "=", "value", "-", "integer", ";", "var", "key", "=", "n2f", "(", "decimal", ")", ";", "var", "result", "=", "value", ";", "if", "(", "vulgarities", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "result", "=", "integer", "+", "vulgarities", "[", "key", "]", ";", "}", "return", "result", ";", "}" ]
Format a decimal as a fractional HTML entity if possible. @since v0.0.1 @param {Number} value @return {String|Number} @example {{toFraction 1.25}} //=> "1¼" {{toFraction 3.1666}} //=> "3⅙" {{toFraction 2.7}} //=> 2.7
[ "Format", "a", "decimal", "as", "a", "fractional", "HTML", "entity", "if", "possible", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/toFraction.js#L35-L46
21,950
cloudfour/core-hbs-helpers
lib/dummyImgSrc.js
dummyImgSrc
function dummyImgSrc (width, height, options) { if (!R.is(Number, width) || !R.is(Number, height)) { throw new Error('The "dummyImgSrc" helper must be passed two numeric dimensions.'); } var result = encode(create(width, height, options.hash)); return new Handlebars.SafeString(result); }
javascript
function dummyImgSrc (width, height, options) { if (!R.is(Number, width) || !R.is(Number, height)) { throw new Error('The "dummyImgSrc" helper must be passed two numeric dimensions.'); } var result = encode(create(width, height, options.hash)); return new Handlebars.SafeString(result); }
[ "function", "dummyImgSrc", "(", "width", ",", "height", ",", "options", ")", "{", "if", "(", "!", "R", ".", "is", "(", "Number", ",", "width", ")", "||", "!", "R", ".", "is", "(", "Number", ",", "height", ")", ")", "{", "throw", "new", "Error", "(", "'The \"dummyImgSrc\" helper must be passed two numeric dimensions.'", ")", ";", "}", "var", "result", "=", "encode", "(", "create", "(", "width", ",", "height", ",", "options", ".", "hash", ")", ")", ";", "return", "new", "Handlebars", ".", "SafeString", "(", "result", ")", ";", "}" ]
Returns an escaped data URI for a placeholder image that can be used as the src attribute of an img element. @since v0.3.0 @param {Number} width @param {Number} height @param {Object} options @return {String} @example <img src="{{dummyImgSrc 150 50}}"> <img src="{{dummyImgSrc 150 50 text="foo"}}"> <img src="{{dummyImgSrc 150 50 bg="#000"}}"> <img src="{{dummyImgSrc 150 50 fg="pink"}}">
[ "Returns", "an", "escaped", "data", "URI", "for", "a", "placeholder", "image", "that", "can", "be", "used", "as", "the", "src", "attribute", "of", "an", "img", "element", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/dummyImgSrc.js#L70-L78
21,951
cloudfour/core-hbs-helpers
lib/randomItem.js
randomItem
function randomItem () { var items = R.dropLast(1, arguments); if (!items.length) { throw new Error('The helper "randomItem" must be passed at least one argument.'); } if (items.length === 1) { items = R.is(Array, items[0]) ? items[0] : [items[0]]; } return items[Math.floor(Math.random() * items.length)]; }
javascript
function randomItem () { var items = R.dropLast(1, arguments); if (!items.length) { throw new Error('The helper "randomItem" must be passed at least one argument.'); } if (items.length === 1) { items = R.is(Array, items[0]) ? items[0] : [items[0]]; } return items[Math.floor(Math.random() * items.length)]; }
[ "function", "randomItem", "(", ")", "{", "var", "items", "=", "R", ".", "dropLast", "(", "1", ",", "arguments", ")", ";", "if", "(", "!", "items", ".", "length", ")", "{", "throw", "new", "Error", "(", "'The helper \"randomItem\" must be passed at least one argument.'", ")", ";", "}", "if", "(", "items", ".", "length", "===", "1", ")", "{", "items", "=", "R", ".", "is", "(", "Array", ",", "items", "[", "0", "]", ")", "?", "items", "[", "0", "]", ":", "[", "items", "[", "0", "]", "]", ";", "}", "return", "items", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "items", ".", "length", ")", "]", ";", "}" ]
Return only one random item. If only one argument is provided and it is an array, it will return a random item from that array. Otherwise it will return one of the arguments. @since v0.0.1 @param {...*} items @return One random item. @example var beatles = ["John", "Paul", "George", "Ringo"]; {{randomItem beatles}} //=> "George" {{randomItem "John" "Paul" "George" "Ringo"}} //=> "Ringo"
[ "Return", "only", "one", "random", "item", ".", "If", "only", "one", "argument", "is", "provided", "and", "it", "is", "an", "array", "it", "will", "return", "a", "random", "item", "from", "that", "array", ".", "Otherwise", "it", "will", "return", "one", "of", "the", "arguments", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/randomItem.js#L20-L32
21,952
cloudfour/core-hbs-helpers
lib/compare.js
compare
function compare (left, operator, right, options) { var result; if (arguments.length < 3) { throw new Error('The "compare" helper needs two arguments.'); } if (options === undefined) { options = right; right = operator; operator = '==='; } if (operators[operator] === undefined) { throw new Error('The "compare" helper needs a valid operator.') } result = operators[operator](left, right); if (R.isNil(options.fn)) { return result; } return result ? options.fn(this) : options.inverse(this); }
javascript
function compare (left, operator, right, options) { var result; if (arguments.length < 3) { throw new Error('The "compare" helper needs two arguments.'); } if (options === undefined) { options = right; right = operator; operator = '==='; } if (operators[operator] === undefined) { throw new Error('The "compare" helper needs a valid operator.') } result = operators[operator](left, right); if (R.isNil(options.fn)) { return result; } return result ? options.fn(this) : options.inverse(this); }
[ "function", "compare", "(", "left", ",", "operator", ",", "right", ",", "options", ")", "{", "var", "result", ";", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "throw", "new", "Error", "(", "'The \"compare\" helper needs two arguments.'", ")", ";", "}", "if", "(", "options", "===", "undefined", ")", "{", "options", "=", "right", ";", "right", "=", "operator", ";", "operator", "=", "'==='", ";", "}", "if", "(", "operators", "[", "operator", "]", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'The \"compare\" helper needs a valid operator.'", ")", "}", "result", "=", "operators", "[", "operator", "]", "(", "left", ",", "right", ")", ";", "if", "(", "R", ".", "isNil", "(", "options", ".", "fn", ")", ")", "{", "return", "result", ";", "}", "return", "result", "?", "options", ".", "fn", "(", "this", ")", ":", "options", ".", "inverse", "(", "this", ")", ";", "}" ]
Compare two values using logical operators. @credit: github.com/assemble @param {*} left @param {String} operator @param {*} right @param {Object} options @return {(String|Boolean)} formatted html if block, true/false if inline @example: {{#compare 1 "<" 2}} This is true. {{else}} This is false. {{/compare}} {{#if (compare 1 "<" 2)}} Also works inline! {{/if}}
[ "Compare", "two", "values", "using", "logical", "operators", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/compare.js#L38-L62
21,953
cloudfour/core-hbs-helpers
lib/capitalizeWords.js
capitalizeWords
function capitalizeWords (str) { if (R.isNil(str)) { throw new Error('The "capitalizeWords" helper requires one argument.') } if (!R.is(String, str)) { str = str.toString(); } return Capitalize.words(str); }
javascript
function capitalizeWords (str) { if (R.isNil(str)) { throw new Error('The "capitalizeWords" helper requires one argument.') } if (!R.is(String, str)) { str = str.toString(); } return Capitalize.words(str); }
[ "function", "capitalizeWords", "(", "str", ")", "{", "if", "(", "R", ".", "isNil", "(", "str", ")", ")", "{", "throw", "new", "Error", "(", "'The \"capitalizeWords\" helper requires one argument.'", ")", "}", "if", "(", "!", "R", ".", "is", "(", "String", ",", "str", ")", ")", "{", "str", "=", "str", ".", "toString", "(", ")", ";", "}", "return", "Capitalize", ".", "words", "(", "str", ")", ";", "}" ]
Capitalize each word in a String. Works with punctuation and international characters. @since 0.4.0 @param {String|*} str - String to capitalize. Other types will be converted. @return {String} @example: {{capitalizeWords "hello world"}} //=> "Hello World" {{capitalizeWords "hello-cañapolísas"}} //=> "Hello-Cañapolísas" {{capitalizeWords "it's a nice day"}} //=> "It's A Nice Day"
[ "Capitalize", "each", "word", "in", "a", "String", ".", "Works", "with", "punctuation", "and", "international", "characters", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/capitalizeWords.js#L19-L29
21,954
cloudfour/core-hbs-helpers
lib/replaceAll.js
replaceAll
function replaceAll (input, find, replace) { let regex = new RegExp(find, 'g'); return input.toString().replace(regex, replace); }
javascript
function replaceAll (input, find, replace) { let regex = new RegExp(find, 'g'); return input.toString().replace(regex, replace); }
[ "function", "replaceAll", "(", "input", ",", "find", ",", "replace", ")", "{", "let", "regex", "=", "new", "RegExp", "(", "find", ",", "'g'", ")", ";", "return", "input", ".", "toString", "(", ")", ".", "replace", "(", "regex", ",", "replace", ")", ";", "}" ]
Replace all occurrences of a string in another string Can also be used on numbers, though they'll be treated as strings. Case sensitive @since 0.6.1 @return {String} @param {Number|String} input @param {Number|String} find @param {Number|String} replace @example {{replaceAll "9:00" ":00" ""}} //=> "9" {{replaceAll "excellent" "e" ""}} //=> xcllnt {{replaceAll "She sells sea shells by the seashore" "sh" "barb"}} //=> "She sells sea barbells by the seabarbore" {{replaceAll "30 bucks" 30, 1000000000}} //=> "1000000000 bucks"
[ "Replace", "all", "occurrences", "of", "a", "string", "in", "another", "string", "Can", "also", "be", "used", "on", "numbers", "though", "they", "ll", "be", "treated", "as", "strings", ".", "Case", "sensitive" ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/replaceAll.js#L20-L23
21,955
cloudfour/core-hbs-helpers
lib/around.js
around
function around (items, center, padding, block) { var result = ''; var options = (block && block.hash) ? R.merge(defaults, block.hash) : R.clone(defaults); var max, start, end; center = parseFloat(center) + options.offset; padding = parseFloat(padding); max = padding * 2 + 1; if (items.length > max) { start = center - padding; end = center + padding + 1; if (start < 0) { end -= start; start = 0; } if (end > items.length) { start -= end - items.length; end = items.length; } items = items.slice(start, end); } for (var item in items) { result += block.fn(items[item]); } return result; }
javascript
function around (items, center, padding, block) { var result = ''; var options = (block && block.hash) ? R.merge(defaults, block.hash) : R.clone(defaults); var max, start, end; center = parseFloat(center) + options.offset; padding = parseFloat(padding); max = padding * 2 + 1; if (items.length > max) { start = center - padding; end = center + padding + 1; if (start < 0) { end -= start; start = 0; } if (end > items.length) { start -= end - items.length; end = items.length; } items = items.slice(start, end); } for (var item in items) { result += block.fn(items[item]); } return result; }
[ "function", "around", "(", "items", ",", "center", ",", "padding", ",", "block", ")", "{", "var", "result", "=", "''", ";", "var", "options", "=", "(", "block", "&&", "block", ".", "hash", ")", "?", "R", ".", "merge", "(", "defaults", ",", "block", ".", "hash", ")", ":", "R", ".", "clone", "(", "defaults", ")", ";", "var", "max", ",", "start", ",", "end", ";", "center", "=", "parseFloat", "(", "center", ")", "+", "options", ".", "offset", ";", "padding", "=", "parseFloat", "(", "padding", ")", ";", "max", "=", "padding", "*", "2", "+", "1", ";", "if", "(", "items", ".", "length", ">", "max", ")", "{", "start", "=", "center", "-", "padding", ";", "end", "=", "center", "+", "padding", "+", "1", ";", "if", "(", "start", "<", "0", ")", "{", "end", "-=", "start", ";", "start", "=", "0", ";", "}", "if", "(", "end", ">", "items", ".", "length", ")", "{", "start", "-=", "end", "-", "items", ".", "length", ";", "end", "=", "items", ".", "length", ";", "}", "items", "=", "items", ".", "slice", "(", "start", ",", "end", ")", ";", "}", "for", "(", "var", "item", "in", "items", ")", "{", "result", "+=", "block", ".", "fn", "(", "items", "[", "item", "]", ")", ";", "}", "return", "result", ";", "}" ]
Slices a list based on a center-point and a maximum amount of "padding" before and after. Useful for pagination. Supports an optional <code>offset</code> hash option in case your center value isn't matching up with your array indexes. @since v0.0.1 @param {Array} items - Collection to iterate over. @param {Number} center - The center-point of the collection (for example, current page). @param {Number} padding - The amount of items to allow before or after the center. @param {Object} block @return {String} @example <ul> {{#around pages 5 2 offset=-1}} <li><a href="/page/{{num}}">Page {{num}}</a></li> {{/around}} </ul> {{! Output: }} <ul> <li><a href="/page/3">Page 3</a></li> <li><a href="/page/4">Page 4</a></li> <li><a href="/page/5">Page 5</a></li> <li><a href="/page/6">Page 6</a></li> <li><a href="/page/7">Page 7</a></li> </ul>
[ "Slices", "a", "list", "based", "on", "a", "center", "-", "point", "and", "a", "maximum", "amount", "of", "padding", "before", "and", "after", ".", "Useful", "for", "pagination", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/around.js#L39-L70
21,956
cloudfour/core-hbs-helpers
lib/average.js
average
function average (arr, options) { var isArray = Array.isArray(arr); var key = options.hash.key; var sum; if (!isArray) { throw new Error('The helper "average" must be passed an Array.'); } if (key) { arr = arr.map(function (item) { return item[key]; }); } sum = arr.reduce(function (prev, current) { return prev + current; }); return sum / arr.length; }
javascript
function average (arr, options) { var isArray = Array.isArray(arr); var key = options.hash.key; var sum; if (!isArray) { throw new Error('The helper "average" must be passed an Array.'); } if (key) { arr = arr.map(function (item) { return item[key]; }); } sum = arr.reduce(function (prev, current) { return prev + current; }); return sum / arr.length; }
[ "function", "average", "(", "arr", ",", "options", ")", "{", "var", "isArray", "=", "Array", ".", "isArray", "(", "arr", ")", ";", "var", "key", "=", "options", ".", "hash", ".", "key", ";", "var", "sum", ";", "if", "(", "!", "isArray", ")", "{", "throw", "new", "Error", "(", "'The helper \"average\" must be passed an Array.'", ")", ";", "}", "if", "(", "key", ")", "{", "arr", "=", "arr", ".", "map", "(", "function", "(", "item", ")", "{", "return", "item", "[", "key", "]", ";", "}", ")", ";", "}", "sum", "=", "arr", ".", "reduce", "(", "function", "(", "prev", ",", "current", ")", "{", "return", "prev", "+", "current", ";", "}", ")", ";", "return", "sum", "/", "arr", ".", "length", ";", "}" ]
Average an array of numeric values. @since v0.0.1 @param {Array} arr @return {Number} Returns the average of all values. @example var numbers = [1, 2, 3]; var products = [{rating: 1}, {rating: 2}, {rating: 3}]; {{average ratings}} //=> 2 {{average products key="rating"}} //=> 2
[ "Average", "an", "array", "of", "numeric", "values", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/average.js#L17-L34
21,957
cloudfour/core-hbs-helpers
lib/toSlug.js
toSlug
function toSlug (str) { return str .toString() .toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '-') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text }
javascript
function toSlug (str) { return str .toString() .toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '-') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text }
[ "function", "toSlug", "(", "str", ")", "{", "return", "str", ".", "toString", "(", ")", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "'-'", ")", "// Replace spaces with -", ".", "replace", "(", "/", "[^\\w\\-]+", "/", "g", ",", "'-'", ")", "// Remove all non-word chars", ".", "replace", "(", "/", "\\-\\-+", "/", "g", ",", "'-'", ")", "// Replace multiple - with single -", ".", "replace", "(", "/", "^-+", "/", ",", "''", ")", "// Trim - from start of text", ".", "replace", "(", "/", "-+$", "/", ",", "''", ")", ";", "// Trim - from end of text", "}" ]
Format a string as a lowercase, URL-friendly value. @since v0.0.1 @param {String} str @return {String} @example {{toSlug "Well, hello there!"}} //=> "well-hello-there"
[ "Format", "a", "string", "as", "a", "lowercase", "URL", "-", "friendly", "value", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/toSlug.js#L13-L22
21,958
cloudfour/core-hbs-helpers
lib/concat.js
concat
function concat () { var items = R.dropLast(1, arguments); if (!items.length) { throw new Error('The helper "concat" must be passed at least one argument.'); } return items.join(''); }
javascript
function concat () { var items = R.dropLast(1, arguments); if (!items.length) { throw new Error('The helper "concat" must be passed at least one argument.'); } return items.join(''); }
[ "function", "concat", "(", ")", "{", "var", "items", "=", "R", ".", "dropLast", "(", "1", ",", "arguments", ")", ";", "if", "(", "!", "items", ".", "length", ")", "{", "throw", "new", "Error", "(", "'The helper \"concat\" must be passed at least one argument.'", ")", ";", "}", "return", "items", ".", "join", "(", "''", ")", ";", "}" ]
Concatenate items into a single string. @since v0.8.0 @param {...*} items @return string @example {{concat "foo" "bar"}} //=> "foobar"
[ "Concatenate", "items", "into", "a", "single", "string", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/concat.js#L14-L22
21,959
cloudfour/core-hbs-helpers
lib/iterate.js
iterate
function iterate (num, block) { return R.times(function (i) { var data = block.data ? R.merge( Handlebars.createFrame(block.data), { index: i, count: i + 1} ) : null; return block.fn(i, {data: data}); }, num).join(''); }
javascript
function iterate (num, block) { return R.times(function (i) { var data = block.data ? R.merge( Handlebars.createFrame(block.data), { index: i, count: i + 1} ) : null; return block.fn(i, {data: data}); }, num).join(''); }
[ "function", "iterate", "(", "num", ",", "block", ")", "{", "return", "R", ".", "times", "(", "function", "(", "i", ")", "{", "var", "data", "=", "block", ".", "data", "?", "R", ".", "merge", "(", "Handlebars", ".", "createFrame", "(", "block", ".", "data", ")", ",", "{", "index", ":", "i", ",", "count", ":", "i", "+", "1", "}", ")", ":", "null", ";", "return", "block", ".", "fn", "(", "i", ",", "{", "data", ":", "data", "}", ")", ";", "}", ",", "num", ")", ".", "join", "(", "''", ")", ";", "}" ]
Repeat a block a given amount of times. @credit https://github.com/fbrctr/fabricator-assemble @since v0.0.2 @example {{#iterate 10}} <li>Index: {{@index}} Count: {{@count}}</li> {{/iterate}}
[ "Repeat", "a", "block", "a", "given", "amount", "of", "times", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/iterate.js#L17-L26
21,960
cloudfour/core-hbs-helpers
lib/toJSON.js
toJSON
function toJSON (str) { str = str.toString(); try { return JSON.parse(str); } catch (e) { throw new Error( 'The "toJSON" helper must be passed a valid JSON string.' ); } }
javascript
function toJSON (str) { str = str.toString(); try { return JSON.parse(str); } catch (e) { throw new Error( 'The "toJSON" helper must be passed a valid JSON string.' ); } }
[ "function", "toJSON", "(", "str", ")", "{", "str", "=", "str", ".", "toString", "(", ")", ";", "try", "{", "return", "JSON", ".", "parse", "(", "str", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "'The \"toJSON\" helper must be passed a valid JSON string.'", ")", ";", "}", "}" ]
Converts a string to JSON; useful when used in helper sub-expressions. @since v0.0.1 @param {String} str @return {Array|Object} @example {{#each (toJSON '[1,2,3]')}}{{this}}{{/each}} //=> '123'
[ "Converts", "a", "string", "to", "JSON", ";", "useful", "when", "used", "in", "helper", "sub", "-", "expressions", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/toJSON.js#L13-L22
21,961
cloudfour/core-hbs-helpers
lib/capitalize.js
capitalize
function capitalize (str) { if (R.isNil(str)) { throw new Error('The "capitalize" helper requires one argument.') } if (!R.is(String, str)) { str = str.toString(); } return Capitalize(str); }
javascript
function capitalize (str) { if (R.isNil(str)) { throw new Error('The "capitalize" helper requires one argument.') } if (!R.is(String, str)) { str = str.toString(); } return Capitalize(str); }
[ "function", "capitalize", "(", "str", ")", "{", "if", "(", "R", ".", "isNil", "(", "str", ")", ")", "{", "throw", "new", "Error", "(", "'The \"capitalize\" helper requires one argument.'", ")", "}", "if", "(", "!", "R", ".", "is", "(", "String", ",", "str", ")", ")", "{", "str", "=", "str", ".", "toString", "(", ")", ";", "}", "return", "Capitalize", "(", "str", ")", ";", "}" ]
Capitalize the first letter of a String. @since 0.4.0 @param {String|*} str - String to capitalize. Other types will be converted. @return {String} @example: {{capitalize "hello world"}} //=> "Hello world"
[ "Capitalize", "the", "first", "letter", "of", "a", "String", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/capitalize.js#L16-L26
21,962
cloudfour/core-hbs-helpers
lib/math.js
math
function math (left, operator, right, options) { if (arguments.length < 3) { throw new Error('The "math" helper needs at least two arguments.'); } if (options === undefined) { options = right; right = undefined; } left = parseFloat(left); right = parseFloat(right); if (operators[operator] === undefined) { throw new Error ('The "math" helper needs a valid operator.'); } return operators[operator](left, right); }
javascript
function math (left, operator, right, options) { if (arguments.length < 3) { throw new Error('The "math" helper needs at least two arguments.'); } if (options === undefined) { options = right; right = undefined; } left = parseFloat(left); right = parseFloat(right); if (operators[operator] === undefined) { throw new Error ('The "math" helper needs a valid operator.'); } return operators[operator](left, right); }
[ "function", "math", "(", "left", ",", "operator", ",", "right", ",", "options", ")", "{", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "throw", "new", "Error", "(", "'The \"math\" helper needs at least two arguments.'", ")", ";", "}", "if", "(", "options", "===", "undefined", ")", "{", "options", "=", "right", ";", "right", "=", "undefined", ";", "}", "left", "=", "parseFloat", "(", "left", ")", ";", "right", "=", "parseFloat", "(", "right", ")", ";", "if", "(", "operators", "[", "operator", "]", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'The \"math\" helper needs a valid operator.'", ")", ";", "}", "return", "operators", "[", "operator", "]", "(", "left", ",", "right", ")", ";", "}" ]
Perform mathematical operations on one or two values. @param {*} left @param {String} operator @param {*} right @param {Object} options @return {Number} @example: {{math 1 "+" 2}} //=> 3 {{math 2 "-" 1}} //=> 1 {{math 2 "*" 3}} //=> 6 {{math 9 "/" 3}} //=> 3 {{math 17 "%" 3}} //=> 2 {{math 2 "**" 3}} //=> 8 {{math 1 "++"}} //=> 2 {{math 2 "--"}} //=> 1
[ "Perform", "mathematical", "operations", "on", "one", "or", "two", "values", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/math.js#L35-L53
21,963
cloudfour/core-hbs-helpers
lib/defaultTo.js
defaultTo
function defaultTo () { var values = R.append('', R.dropLast(1, arguments)); return R.head(R.reject(R.isNil, values)); }
javascript
function defaultTo () { var values = R.append('', R.dropLast(1, arguments)); return R.head(R.reject(R.isNil, values)); }
[ "function", "defaultTo", "(", ")", "{", "var", "values", "=", "R", ".", "append", "(", "''", ",", "R", ".", "dropLast", "(", "1", ",", "arguments", ")", ")", ";", "return", "R", ".", "head", "(", "R", ".", "reject", "(", "R", ".", "isNil", ",", "values", ")", ")", ";", "}" ]
Output the first provided value that exists, or fallback to a default if none do. @since v0.0.1 @param {...*} value @return {String} @example var doesExist = 'Hello'; {{defaultTo doesExist "Goodbye"}} // => "Hello" {{defaultTo doesNotExist "Goodbye"}} // => "Goodbye" {{defaultTo doesNotExist}} // => "" {{defaultTo doesNotExist doesExist "Goodbye"}} // => "Hello"
[ "Output", "the", "first", "provided", "value", "that", "exists", "or", "fallback", "to", "a", "default", "if", "none", "do", "." ]
26ca9d12b08b83f2c379ea1de4bb27cd85f416f7
https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/defaultTo.js#L21-L24
21,964
ostdotcom/base
lib/ost_web3/ost-web3-providers-ws.js
function(iOstWSProvider) { const oThis = this; oThis.iOstWSProvider = iOstWSProvider; oThis.endPointUrl = iOstWSProvider.endPointUrl; oThis.notificationCallbacks = iOstWSProvider.notificationCallbacks; const options = iOstWSProvider.options; Object.assign(oThis, options); oThis.reconnect(); }
javascript
function(iOstWSProvider) { const oThis = this; oThis.iOstWSProvider = iOstWSProvider; oThis.endPointUrl = iOstWSProvider.endPointUrl; oThis.notificationCallbacks = iOstWSProvider.notificationCallbacks; const options = iOstWSProvider.options; Object.assign(oThis, options); oThis.reconnect(); }
[ "function", "(", "iOstWSProvider", ")", "{", "const", "oThis", "=", "this", ";", "oThis", ".", "iOstWSProvider", "=", "iOstWSProvider", ";", "oThis", ".", "endPointUrl", "=", "iOstWSProvider", ".", "endPointUrl", ";", "oThis", ".", "notificationCallbacks", "=", "iOstWSProvider", ".", "notificationCallbacks", ";", "const", "options", "=", "iOstWSProvider", ".", "options", ";", "Object", ".", "assign", "(", "oThis", ",", "options", ")", ";", "oThis", ".", "reconnect", "(", ")", ";", "}" ]
Reconnector Class.
[ "Reconnector", "Class", "." ]
0f799337ae59e09abeddc4afc8e4a739397533c4
https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/ost_web3/ost-web3-providers-ws.js#L253-L264
21,965
ostdotcom/base
lib/logger/custom_console_logger.js
function(moduleName, logLevel) { var oThis = this; if (moduleName) { oThis.moduleNamePrefix = '[' + moduleName + ']'; } oThis.setLogLevel(logLevel); }
javascript
function(moduleName, logLevel) { var oThis = this; if (moduleName) { oThis.moduleNamePrefix = '[' + moduleName + ']'; } oThis.setLogLevel(logLevel); }
[ "function", "(", "moduleName", ",", "logLevel", ")", "{", "var", "oThis", "=", "this", ";", "if", "(", "moduleName", ")", "{", "oThis", ".", "moduleNamePrefix", "=", "'['", "+", "moduleName", "+", "']'", ";", "}", "oThis", ".", "setLogLevel", "(", "logLevel", ")", ";", "}" ]
Custom Console Logger @constructor
[ "Custom", "Console", "Logger" ]
0f799337ae59e09abeddc4afc8e4a739397533c4
https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/logger/custom_console_logger.js#L91-L99
21,966
ostdotcom/base
lib/logger/custom_console_logger.js
function(requestUrl, requestType) { const oThis = this, d = new Date(), dateTime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '.' + d.getMilliseconds(), message = "Started '" + requestType + "' '" + requestUrl + "' at " + dateTime; oThis.info(message); }
javascript
function(requestUrl, requestType) { const oThis = this, d = new Date(), dateTime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '.' + d.getMilliseconds(), message = "Started '" + requestType + "' '" + requestUrl + "' at " + dateTime; oThis.info(message); }
[ "function", "(", "requestUrl", ",", "requestType", ")", "{", "const", "oThis", "=", "this", ",", "d", "=", "new", "Date", "(", ")", ",", "dateTime", "=", "d", ".", "getFullYear", "(", ")", "+", "'-'", "+", "(", "d", ".", "getMonth", "(", ")", "+", "1", ")", "+", "'-'", "+", "d", ".", "getDate", "(", ")", "+", "' '", "+", "d", ".", "getHours", "(", ")", "+", "':'", "+", "d", ".", "getMinutes", "(", ")", "+", "':'", "+", "d", ".", "getSeconds", "(", ")", "+", "'.'", "+", "d", ".", "getMilliseconds", "(", ")", ",", "message", "=", "\"Started '\"", "+", "requestType", "+", "\"' '\"", "+", "requestUrl", "+", "\"' at \"", "+", "dateTime", ";", "oThis", ".", "info", "(", "message", ")", ";", "}" ]
Method to Log Request Started.
[ "Method", "to", "Log", "Request", "Started", "." ]
0f799337ae59e09abeddc4afc8e4a739397533c4
https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/logger/custom_console_logger.js#L238-L258
21,967
ostdotcom/base
lib/logger/custom_console_logger.js
function() { var oThis = this; var argsPassed = oThis._filterArgs(arguments); var args = [oThis.getPrefix(this.ERR_PRE)]; args = args.concat(Array.prototype.slice.call(argsPassed)); args.push(this.CONSOLE_RESET); console.log.apply(console, args); }
javascript
function() { var oThis = this; var argsPassed = oThis._filterArgs(arguments); var args = [oThis.getPrefix(this.ERR_PRE)]; args = args.concat(Array.prototype.slice.call(argsPassed)); args.push(this.CONSOLE_RESET); console.log.apply(console, args); }
[ "function", "(", ")", "{", "var", "oThis", "=", "this", ";", "var", "argsPassed", "=", "oThis", ".", "_filterArgs", "(", "arguments", ")", ";", "var", "args", "=", "[", "oThis", ".", "getPrefix", "(", "this", ".", "ERR_PRE", ")", "]", ";", "args", "=", "args", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "argsPassed", ")", ")", ";", "args", ".", "push", "(", "this", ".", "CONSOLE_RESET", ")", ";", "console", ".", "log", ".", "apply", "(", "console", ",", "args", ")", ";", "}" ]
Log level error methods
[ "Log", "level", "error", "methods" ]
0f799337ae59e09abeddc4afc8e4a739397533c4
https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/logger/custom_console_logger.js#L291-L300
21,968
ostdotcom/base
lib/InstanceComposer.js
checkAvailability
function checkAvailability(fullGetterName) { if (composerMap.hasOwnProperty(fullGetterName) || shadowMap.hasOwnProperty(fullGetterName)) { console.trace('Duplicate Getter Method name', fullGetterName); throw 'Duplicate Getter Method Name '; } }
javascript
function checkAvailability(fullGetterName) { if (composerMap.hasOwnProperty(fullGetterName) || shadowMap.hasOwnProperty(fullGetterName)) { console.trace('Duplicate Getter Method name', fullGetterName); throw 'Duplicate Getter Method Name '; } }
[ "function", "checkAvailability", "(", "fullGetterName", ")", "{", "if", "(", "composerMap", ".", "hasOwnProperty", "(", "fullGetterName", ")", "||", "shadowMap", ".", "hasOwnProperty", "(", "fullGetterName", ")", ")", "{", "console", ".", "trace", "(", "'Duplicate Getter Method name'", ",", "fullGetterName", ")", ";", "throw", "'Duplicate Getter Method Name '", ";", "}", "}" ]
Check if full getter name is available @param fullGetterName {string} - full getter name Throws error if fullGetterName is not available, i.e. already taken.
[ "Check", "if", "full", "getter", "name", "is", "available" ]
0f799337ae59e09abeddc4afc8e4a739397533c4
https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/InstanceComposer.js#L30-L35
21,969
sapegin/mrm
src/index.js
promiseSeries
function promiseSeries(items, iterator) { return items.reduce((iterable, name) => { return iterable.then(() => iterator(name)); }, Promise.resolve()); }
javascript
function promiseSeries(items, iterator) { return items.reduce((iterable, name) => { return iterable.then(() => iterator(name)); }, Promise.resolve()); }
[ "function", "promiseSeries", "(", "items", ",", "iterator", ")", "{", "return", "items", ".", "reduce", "(", "(", "iterable", ",", "name", ")", "=>", "{", "return", "iterable", ".", "then", "(", "(", ")", "=>", "iterator", "(", "name", ")", ")", ";", "}", ",", "Promise", ".", "resolve", "(", ")", ")", ";", "}" ]
Runs an array of promises in series @method promiseSeries @param {Array} items @param {Function} iterator @return {Promise}
[ "Runs", "an", "array", "of", "promises", "in", "series" ]
f4892d3eee6bc52b3805181f2b813e8ea9eaba7f
https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L53-L57
21,970
sapegin/mrm
src/index.js
getConfigGetter
function getConfigGetter(options) { /** * Return a config value. * * @param {string} prop * @param {any} [defaultValue] * @return {any} */ function config(prop, defaultValue) { console.warn( 'Warning: calling config as a function is deprecated. Use config.values() instead' ); return get(options, prop, defaultValue); } /** * Return an object with all config values. * * @return {Object} */ function values() { return options; } /** * Mark config options as required. * * @param {string[]} names... * @return {Object} this */ function require(...names) { const unknown = names.filter(name => !options[name]); if (unknown.length > 0) { throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, { unknown, }); } return config; } /** * Set default values. * * @param {Object} defaultOptions * @return {any} */ function defaults(defaultOptions) { options = Object.assign({}, defaultOptions, options); return config; } config.require = require; config.defaults = defaults; config.values = values; return config; }
javascript
function getConfigGetter(options) { /** * Return a config value. * * @param {string} prop * @param {any} [defaultValue] * @return {any} */ function config(prop, defaultValue) { console.warn( 'Warning: calling config as a function is deprecated. Use config.values() instead' ); return get(options, prop, defaultValue); } /** * Return an object with all config values. * * @return {Object} */ function values() { return options; } /** * Mark config options as required. * * @param {string[]} names... * @return {Object} this */ function require(...names) { const unknown = names.filter(name => !options[name]); if (unknown.length > 0) { throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, { unknown, }); } return config; } /** * Set default values. * * @param {Object} defaultOptions * @return {any} */ function defaults(defaultOptions) { options = Object.assign({}, defaultOptions, options); return config; } config.require = require; config.defaults = defaults; config.values = values; return config; }
[ "function", "getConfigGetter", "(", "options", ")", "{", "/**\n\t * Return a config value.\n\t *\n\t * @param {string} prop\n\t * @param {any} [defaultValue]\n\t * @return {any}\n\t */", "function", "config", "(", "prop", ",", "defaultValue", ")", "{", "console", ".", "warn", "(", "'Warning: calling config as a function is deprecated. Use config.values() instead'", ")", ";", "return", "get", "(", "options", ",", "prop", ",", "defaultValue", ")", ";", "}", "/**\n\t * Return an object with all config values.\n\t *\n\t * @return {Object}\n\t */", "function", "values", "(", ")", "{", "return", "options", ";", "}", "/**\n\t * Mark config options as required.\n\t *\n\t * @param {string[]} names...\n\t * @return {Object} this\n\t */", "function", "require", "(", "...", "names", ")", "{", "const", "unknown", "=", "names", ".", "filter", "(", "name", "=>", "!", "options", "[", "name", "]", ")", ";", "if", "(", "unknown", ".", "length", ">", "0", ")", "{", "throw", "new", "MrmUndefinedOption", "(", "`", "${", "unknown", ".", "join", "(", "', '", ")", "}", "`", ",", "{", "unknown", ",", "}", ")", ";", "}", "return", "config", ";", "}", "/**\n\t * Set default values.\n\t *\n\t * @param {Object} defaultOptions\n\t * @return {any}\n\t */", "function", "defaults", "(", "defaultOptions", ")", "{", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultOptions", ",", "options", ")", ";", "return", "config", ";", "}", "config", ".", "require", "=", "require", ";", "config", ".", "defaults", "=", "defaults", ";", "config", ".", "values", "=", "values", ";", "return", "config", ";", "}" ]
Return a config getter. @param {Object} options @return {any}
[ "Return", "a", "config", "getter", "." ]
f4892d3eee6bc52b3805181f2b813e8ea9eaba7f
https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L150-L205
21,971
sapegin/mrm
src/index.js
require
function require(...names) { const unknown = names.filter(name => !options[name]); if (unknown.length > 0) { throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, { unknown, }); } return config; }
javascript
function require(...names) { const unknown = names.filter(name => !options[name]); if (unknown.length > 0) { throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, { unknown, }); } return config; }
[ "function", "require", "(", "...", "names", ")", "{", "const", "unknown", "=", "names", ".", "filter", "(", "name", "=>", "!", "options", "[", "name", "]", ")", ";", "if", "(", "unknown", ".", "length", ">", "0", ")", "{", "throw", "new", "MrmUndefinedOption", "(", "`", "${", "unknown", ".", "join", "(", "', '", ")", "}", "`", ",", "{", "unknown", ",", "}", ")", ";", "}", "return", "config", ";", "}" ]
Mark config options as required. @param {string[]} names... @return {Object} this
[ "Mark", "config", "options", "as", "required", "." ]
f4892d3eee6bc52b3805181f2b813e8ea9eaba7f
https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L180-L188
21,972
sapegin/mrm
src/index.js
getConfigFromFile
function getConfigFromFile(directories, filename) { const filepath = tryFile(directories, filename); if (!filepath) { return {}; } return require(filepath); }
javascript
function getConfigFromFile(directories, filename) { const filepath = tryFile(directories, filename); if (!filepath) { return {}; } return require(filepath); }
[ "function", "getConfigFromFile", "(", "directories", ",", "filename", ")", "{", "const", "filepath", "=", "tryFile", "(", "directories", ",", "filename", ")", ";", "if", "(", "!", "filepath", ")", "{", "return", "{", "}", ";", "}", "return", "require", "(", "filepath", ")", ";", "}" ]
Find and load config file. @param {string[]} directories @param {string} filename @return {Object}
[ "Find", "and", "load", "config", "file", "." ]
f4892d3eee6bc52b3805181f2b813e8ea9eaba7f
https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L229-L236
21,973
sapegin/mrm
src/index.js
tryFile
function tryFile(directories, filename) { return firstResult(directories, dir => { const filepath = path.resolve(dir, filename); return fs.existsSync(filepath) ? filepath : undefined; }); }
javascript
function tryFile(directories, filename) { return firstResult(directories, dir => { const filepath = path.resolve(dir, filename); return fs.existsSync(filepath) ? filepath : undefined; }); }
[ "function", "tryFile", "(", "directories", ",", "filename", ")", "{", "return", "firstResult", "(", "directories", ",", "dir", "=>", "{", "const", "filepath", "=", "path", ".", "resolve", "(", "dir", ",", "filename", ")", ";", "return", "fs", ".", "existsSync", "(", "filepath", ")", "?", "filepath", ":", "undefined", ";", "}", ")", ";", "}" ]
Try to load a file from a list of folders. @param {string[]} directories @param {string} filename @return {string|undefined} Absolute path or undefined
[ "Try", "to", "load", "a", "file", "from", "a", "list", "of", "folders", "." ]
f4892d3eee6bc52b3805181f2b813e8ea9eaba7f
https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L261-L266
21,974
sapegin/mrm
src/index.js
firstResult
function firstResult(items, fn) { for (const item of items) { if (!item) { continue; } const result = fn(item); if (result) { return result; } } return undefined; }
javascript
function firstResult(items, fn) { for (const item of items) { if (!item) { continue; } const result = fn(item); if (result) { return result; } } return undefined; }
[ "function", "firstResult", "(", "items", ",", "fn", ")", "{", "for", "(", "const", "item", "of", "items", ")", "{", "if", "(", "!", "item", ")", "{", "continue", ";", "}", "const", "result", "=", "fn", "(", "item", ")", ";", "if", "(", "result", ")", "{", "return", "result", ";", "}", "}", "return", "undefined", ";", "}" ]
Return the first truthy result of a callback. @param {any[]} items @param {Function} fn @return {any}
[ "Return", "the", "first", "truthy", "result", "of", "a", "callback", "." ]
f4892d3eee6bc52b3805181f2b813e8ea9eaba7f
https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L285-L297
21,975
zenozeng/color-hash
lib/color-hash.js
function(RGBArray) { var hex = '#'; RGBArray.forEach(function(value) { if (value < 16) { hex += 0; } hex += value.toString(16); }); return hex; }
javascript
function(RGBArray) { var hex = '#'; RGBArray.forEach(function(value) { if (value < 16) { hex += 0; } hex += value.toString(16); }); return hex; }
[ "function", "(", "RGBArray", ")", "{", "var", "hex", "=", "'#'", ";", "RGBArray", ".", "forEach", "(", "function", "(", "value", ")", "{", "if", "(", "value", "<", "16", ")", "{", "hex", "+=", "0", ";", "}", "hex", "+=", "value", ".", "toString", "(", "16", ")", ";", "}", ")", ";", "return", "hex", ";", "}" ]
Convert RGB Array to HEX @param {Array} RGBArray - [R, G, B] @returns {String} 6 digits hex starting with #
[ "Convert", "RGB", "Array", "to", "HEX" ]
ca0228156c0e0223268274376bbc94850cebe80c
https://github.com/zenozeng/color-hash/blob/ca0228156c0e0223268274376bbc94850cebe80c/lib/color-hash.js#L9-L18
21,976
zenozeng/color-hash
lib/color-hash.js
function(H, S, L) { H /= 360; var q = L < 0.5 ? L * (1 + S) : L + S - L * S; var p = 2 * L - q; return [H + 1/3, H, H - 1/3].map(function(color) { if(color < 0) { color++; } if(color > 1) { color--; } if(color < 1/6) { color = p + (q - p) * 6 * color; } else if(color < 0.5) { color = q; } else if(color < 2/3) { color = p + (q - p) * 6 * (2/3 - color); } else { color = p; } return Math.round(color * 255); }); }
javascript
function(H, S, L) { H /= 360; var q = L < 0.5 ? L * (1 + S) : L + S - L * S; var p = 2 * L - q; return [H + 1/3, H, H - 1/3].map(function(color) { if(color < 0) { color++; } if(color > 1) { color--; } if(color < 1/6) { color = p + (q - p) * 6 * color; } else if(color < 0.5) { color = q; } else if(color < 2/3) { color = p + (q - p) * 6 * (2/3 - color); } else { color = p; } return Math.round(color * 255); }); }
[ "function", "(", "H", ",", "S", ",", "L", ")", "{", "H", "/=", "360", ";", "var", "q", "=", "L", "<", "0.5", "?", "L", "*", "(", "1", "+", "S", ")", ":", "L", "+", "S", "-", "L", "*", "S", ";", "var", "p", "=", "2", "*", "L", "-", "q", ";", "return", "[", "H", "+", "1", "/", "3", ",", "H", ",", "H", "-", "1", "/", "3", "]", ".", "map", "(", "function", "(", "color", ")", "{", "if", "(", "color", "<", "0", ")", "{", "color", "++", ";", "}", "if", "(", "color", ">", "1", ")", "{", "color", "--", ";", "}", "if", "(", "color", "<", "1", "/", "6", ")", "{", "color", "=", "p", "+", "(", "q", "-", "p", ")", "*", "6", "*", "color", ";", "}", "else", "if", "(", "color", "<", "0.5", ")", "{", "color", "=", "q", ";", "}", "else", "if", "(", "color", "<", "2", "/", "3", ")", "{", "color", "=", "p", "+", "(", "q", "-", "p", ")", "*", "6", "*", "(", "2", "/", "3", "-", "color", ")", ";", "}", "else", "{", "color", "=", "p", ";", "}", "return", "Math", ".", "round", "(", "color", "*", "255", ")", ";", "}", ")", ";", "}" ]
Convert HSL to RGB @see {@link http://zh.wikipedia.org/wiki/HSL和HSV色彩空间} for further information. @param {Number} H Hue ∈ [0, 360) @param {Number} S Saturation ∈ [0, 1] @param {Number} L Lightness ∈ [0, 1] @returns {Array} R, G, B ∈ [0, 255]
[ "Convert", "HSL", "to", "RGB" ]
ca0228156c0e0223268274376bbc94850cebe80c
https://github.com/zenozeng/color-hash/blob/ca0228156c0e0223268274376bbc94850cebe80c/lib/color-hash.js#L29-L53
21,977
zenozeng/color-hash
lib/color-hash.js
function(options) { options = options || {}; var LS = [options.lightness, options.saturation].map(function(param) { param = param || [0.35, 0.5, 0.65]; // note that 3 is a prime return isArray(param) ? param.concat() : [param]; }); this.L = LS[0]; this.S = LS[1]; if (typeof options.hue === 'number') { options.hue = {min: options.hue, max: options.hue}; } if (typeof options.hue === 'object' && !isArray(options.hue)) { options.hue = [options.hue]; } if (typeof options.hue === 'undefined') { options.hue = []; } this.hueRanges = options.hue.map(function (range) { return { min: typeof range.min === 'undefined' ? 0 : range.min, max: typeof range.max === 'undefined' ? 360: range.max }; }); this.hash = options.hash || BKDRHash; }
javascript
function(options) { options = options || {}; var LS = [options.lightness, options.saturation].map(function(param) { param = param || [0.35, 0.5, 0.65]; // note that 3 is a prime return isArray(param) ? param.concat() : [param]; }); this.L = LS[0]; this.S = LS[1]; if (typeof options.hue === 'number') { options.hue = {min: options.hue, max: options.hue}; } if (typeof options.hue === 'object' && !isArray(options.hue)) { options.hue = [options.hue]; } if (typeof options.hue === 'undefined') { options.hue = []; } this.hueRanges = options.hue.map(function (range) { return { min: typeof range.min === 'undefined' ? 0 : range.min, max: typeof range.max === 'undefined' ? 360: range.max }; }); this.hash = options.hash || BKDRHash; }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "LS", "=", "[", "options", ".", "lightness", ",", "options", ".", "saturation", "]", ".", "map", "(", "function", "(", "param", ")", "{", "param", "=", "param", "||", "[", "0.35", ",", "0.5", ",", "0.65", "]", ";", "// note that 3 is a prime", "return", "isArray", "(", "param", ")", "?", "param", ".", "concat", "(", ")", ":", "[", "param", "]", ";", "}", ")", ";", "this", ".", "L", "=", "LS", "[", "0", "]", ";", "this", ".", "S", "=", "LS", "[", "1", "]", ";", "if", "(", "typeof", "options", ".", "hue", "===", "'number'", ")", "{", "options", ".", "hue", "=", "{", "min", ":", "options", ".", "hue", ",", "max", ":", "options", ".", "hue", "}", ";", "}", "if", "(", "typeof", "options", ".", "hue", "===", "'object'", "&&", "!", "isArray", "(", "options", ".", "hue", ")", ")", "{", "options", ".", "hue", "=", "[", "options", ".", "hue", "]", ";", "}", "if", "(", "typeof", "options", ".", "hue", "===", "'undefined'", ")", "{", "options", ".", "hue", "=", "[", "]", ";", "}", "this", ".", "hueRanges", "=", "options", ".", "hue", ".", "map", "(", "function", "(", "range", ")", "{", "return", "{", "min", ":", "typeof", "range", ".", "min", "===", "'undefined'", "?", "0", ":", "range", ".", "min", ",", "max", ":", "typeof", "range", ".", "max", "===", "'undefined'", "?", "360", ":", "range", ".", "max", "}", ";", "}", ")", ";", "this", ".", "hash", "=", "options", ".", "hash", "||", "BKDRHash", ";", "}" ]
Color Hash Class @class
[ "Color", "Hash", "Class" ]
ca0228156c0e0223268274376bbc94850cebe80c
https://github.com/zenozeng/color-hash/blob/ca0228156c0e0223268274376bbc94850cebe80c/lib/color-hash.js#L64-L92
21,978
functional-jslib/fjl
dist/amd/function/compose.js
compose
function compose() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return function (arg0) { return (0, _array.reduceRight)(function (value, fn) { return fn(value); }, arg0, args); }; }
javascript
function compose() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return function (arg0) { return (0, _array.reduceRight)(function (value, fn) { return fn(value); }, arg0, args); }; }
[ "function", "compose", "(", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "args", "=", "new", "Array", "(", "_len", ")", ",", "_key", "=", "0", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "args", "[", "_key", "]", "=", "arguments", "[", "_key", "]", ";", "}", "return", "function", "(", "arg0", ")", "{", "return", "(", "0", ",", "_array", ".", "reduceRight", ")", "(", "function", "(", "value", ",", "fn", ")", "{", "return", "fn", "(", "value", ")", ";", "}", ",", "arg0", ",", "args", ")", ";", "}", ";", "}" ]
Composes all functions passed in from right to left passing each functions return value to the function on the left of itself. @function module:function.compose @type {Function} @param args {...{Function}} @returns {Function}
[ "Composes", "all", "functions", "passed", "in", "from", "right", "to", "left", "passing", "each", "functions", "return", "value", "to", "the", "function", "on", "the", "left", "of", "itself", "." ]
5dd1faaf7d86a20e03e54df3044a8cb82f0cde43
https://github.com/functional-jslib/fjl/blob/5dd1faaf7d86a20e03e54df3044a8cb82f0cde43/dist/amd/function/compose.js#L17-L27
21,979
zachowj/node-red-contrib-home-assistant-websocket
lib/mustache-context.js
NodeContext
function NodeContext(msg, parent, nodeContext, serverName) { this.msgContext = new mustache.Context(msg, parent); this.nodeContext = nodeContext; this.serverName = serverName; }
javascript
function NodeContext(msg, parent, nodeContext, serverName) { this.msgContext = new mustache.Context(msg, parent); this.nodeContext = nodeContext; this.serverName = serverName; }
[ "function", "NodeContext", "(", "msg", ",", "parent", ",", "nodeContext", ",", "serverName", ")", "{", "this", ".", "msgContext", "=", "new", "mustache", ".", "Context", "(", "msg", ",", "parent", ")", ";", "this", ".", "nodeContext", "=", "nodeContext", ";", "this", ".", "serverName", "=", "serverName", ";", "}" ]
Custom Mustache Context capable to collect message property and node flow and global context
[ "Custom", "Mustache", "Context", "capable", "to", "collect", "message", "property", "and", "node", "flow", "and", "global", "context" ]
aad4ab10e6307701eae8e3c558428082640f8ace
https://github.com/zachowj/node-red-contrib-home-assistant-websocket/blob/aad4ab10e6307701eae8e3c558428082640f8ace/lib/mustache-context.js#L25-L29
21,980
openshift/origin-web-common
dist/origin-web-common-services.js
function() { window.OPENSHIFT_CONFIG.api.k8s.resources = api.k8s; window.OPENSHIFT_CONFIG.api.openshift.resources = api.openshift; window.OPENSHIFT_CONFIG.apis.groups = apis; if (API_DISCOVERY_ERRORS.length) { window.OPENSHIFT_CONFIG.apis.API_DISCOVERY_ERRORS = API_DISCOVERY_ERRORS; } next(); }
javascript
function() { window.OPENSHIFT_CONFIG.api.k8s.resources = api.k8s; window.OPENSHIFT_CONFIG.api.openshift.resources = api.openshift; window.OPENSHIFT_CONFIG.apis.groups = apis; if (API_DISCOVERY_ERRORS.length) { window.OPENSHIFT_CONFIG.apis.API_DISCOVERY_ERRORS = API_DISCOVERY_ERRORS; } next(); }
[ "function", "(", ")", "{", "window", ".", "OPENSHIFT_CONFIG", ".", "api", ".", "k8s", ".", "resources", "=", "api", ".", "k8s", ";", "window", ".", "OPENSHIFT_CONFIG", ".", "api", ".", "openshift", ".", "resources", "=", "api", ".", "openshift", ";", "window", ".", "OPENSHIFT_CONFIG", ".", "apis", ".", "groups", "=", "apis", ";", "if", "(", "API_DISCOVERY_ERRORS", ".", "length", ")", "{", "window", ".", "OPENSHIFT_CONFIG", ".", "apis", ".", "API_DISCOVERY_ERRORS", "=", "API_DISCOVERY_ERRORS", ";", "}", "next", "(", ")", ";", "}" ]
Will be called on success or failure
[ "Will", "be", "called", "on", "success", "or", "failure" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L566-L574
21,981
openshift/origin-web-common
dist/origin-web-common-services.js
ResourceGroupVersion
function ResourceGroupVersion(resource, group, version) { this.resource = resource; this.group = group; this.version = version; return this; }
javascript
function ResourceGroupVersion(resource, group, version) { this.resource = resource; this.group = group; this.version = version; return this; }
[ "function", "ResourceGroupVersion", "(", "resource", ",", "group", ",", "version", ")", "{", "this", ".", "resource", "=", "resource", ";", "this", ".", "group", "=", "group", ";", "this", ".", "version", "=", "version", ";", "return", "this", ";", "}" ]
ResourceGroupVersion represents a fully qualified resource
[ "ResourceGroupVersion", "represents", "a", "fully", "qualified", "resource" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L611-L616
21,982
openshift/origin-web-common
dist/origin-web-common-services.js
normalizeResource
function normalizeResource(resource) { if (!resource) { return resource; } var i = resource.indexOf('/'); if (i === -1) { return resource.toLowerCase(); } return resource.substring(0, i).toLowerCase() + resource.substring(i); }
javascript
function normalizeResource(resource) { if (!resource) { return resource; } var i = resource.indexOf('/'); if (i === -1) { return resource.toLowerCase(); } return resource.substring(0, i).toLowerCase() + resource.substring(i); }
[ "function", "normalizeResource", "(", "resource", ")", "{", "if", "(", "!", "resource", ")", "{", "return", "resource", ";", "}", "var", "i", "=", "resource", ".", "indexOf", "(", "'/'", ")", ";", "if", "(", "i", "===", "-", "1", ")", "{", "return", "resource", ".", "toLowerCase", "(", ")", ";", "}", "return", "resource", ".", "substring", "(", "0", ",", "i", ")", ".", "toLowerCase", "(", ")", "+", "resource", ".", "substring", "(", "i", ")", ";", "}" ]
normalizeResource lowercases the first segment of the given resource. subresources can be case-sensitive.
[ "normalizeResource", "lowercases", "the", "first", "segment", "of", "the", "given", "resource", ".", "subresources", "can", "be", "case", "-", "sensitive", "." ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L702-L711
21,983
openshift/origin-web-common
dist/origin-web-common-services.js
function(includeClusterScoped) { var kinds = []; var rejectedKinds = _.map(Constants.AVAILABLE_KINDS_BLACKLIST, function(kind) { return _.isString(kind) ? { kind: kind, group: '' } : kind; }); // ignore the legacy openshift kinds, these have been migrated to api groups _.each(_.pickBy(API_CFG, function(value, key) { return key !== 'openshift'; }), function(api) { _.each(api.resources.v1, function(resource) { if (resource.namespaced || includeClusterScoped) { // Exclude subresources and any rejected kinds if (_.includes(resource.name, '/') || _.find(rejectedKinds, { kind: resource.kind, group: '' })) { return; } kinds.push({ kind: resource.kind, group: '' }); } }); }); // Kinds under api groups _.each(APIS_CFG.groups, function(group) { // Use the console's default version first, and the server's preferred version second var preferredVersion = defaultVersion[group.name] || group.preferredVersion; _.each(group.versions[preferredVersion].resources, function(resource) { // Exclude subresources and any rejected kinds if (_.includes(resource.name, '/') || _.find(rejectedKinds, {kind: resource.kind, group: group.name})) { return; } if(excludeKindFromAPIGroupList(group.name, resource.kind)) { return; } if (resource.namespaced || includeClusterScoped) { kinds.push({ kind: resource.kind, group: group.name }); } }); }); return _.uniqBy(kinds, function(value) { return value.group + "/" + value.kind; }); }
javascript
function(includeClusterScoped) { var kinds = []; var rejectedKinds = _.map(Constants.AVAILABLE_KINDS_BLACKLIST, function(kind) { return _.isString(kind) ? { kind: kind, group: '' } : kind; }); // ignore the legacy openshift kinds, these have been migrated to api groups _.each(_.pickBy(API_CFG, function(value, key) { return key !== 'openshift'; }), function(api) { _.each(api.resources.v1, function(resource) { if (resource.namespaced || includeClusterScoped) { // Exclude subresources and any rejected kinds if (_.includes(resource.name, '/') || _.find(rejectedKinds, { kind: resource.kind, group: '' })) { return; } kinds.push({ kind: resource.kind, group: '' }); } }); }); // Kinds under api groups _.each(APIS_CFG.groups, function(group) { // Use the console's default version first, and the server's preferred version second var preferredVersion = defaultVersion[group.name] || group.preferredVersion; _.each(group.versions[preferredVersion].resources, function(resource) { // Exclude subresources and any rejected kinds if (_.includes(resource.name, '/') || _.find(rejectedKinds, {kind: resource.kind, group: group.name})) { return; } if(excludeKindFromAPIGroupList(group.name, resource.kind)) { return; } if (resource.namespaced || includeClusterScoped) { kinds.push({ kind: resource.kind, group: group.name }); } }); }); return _.uniqBy(kinds, function(value) { return value.group + "/" + value.kind; }); }
[ "function", "(", "includeClusterScoped", ")", "{", "var", "kinds", "=", "[", "]", ";", "var", "rejectedKinds", "=", "_", ".", "map", "(", "Constants", ".", "AVAILABLE_KINDS_BLACKLIST", ",", "function", "(", "kind", ")", "{", "return", "_", ".", "isString", "(", "kind", ")", "?", "{", "kind", ":", "kind", ",", "group", ":", "''", "}", ":", "kind", ";", "}", ")", ";", "// ignore the legacy openshift kinds, these have been migrated to api groups", "_", ".", "each", "(", "_", ".", "pickBy", "(", "API_CFG", ",", "function", "(", "value", ",", "key", ")", "{", "return", "key", "!==", "'openshift'", ";", "}", ")", ",", "function", "(", "api", ")", "{", "_", ".", "each", "(", "api", ".", "resources", ".", "v1", ",", "function", "(", "resource", ")", "{", "if", "(", "resource", ".", "namespaced", "||", "includeClusterScoped", ")", "{", "// Exclude subresources and any rejected kinds", "if", "(", "_", ".", "includes", "(", "resource", ".", "name", ",", "'/'", ")", "||", "_", ".", "find", "(", "rejectedKinds", ",", "{", "kind", ":", "resource", ".", "kind", ",", "group", ":", "''", "}", ")", ")", "{", "return", ";", "}", "kinds", ".", "push", "(", "{", "kind", ":", "resource", ".", "kind", ",", "group", ":", "''", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "// Kinds under api groups", "_", ".", "each", "(", "APIS_CFG", ".", "groups", ",", "function", "(", "group", ")", "{", "// Use the console's default version first, and the server's preferred version second", "var", "preferredVersion", "=", "defaultVersion", "[", "group", ".", "name", "]", "||", "group", ".", "preferredVersion", ";", "_", ".", "each", "(", "group", ".", "versions", "[", "preferredVersion", "]", ".", "resources", ",", "function", "(", "resource", ")", "{", "// Exclude subresources and any rejected kinds", "if", "(", "_", ".", "includes", "(", "resource", ".", "name", ",", "'/'", ")", "||", "_", ".", "find", "(", "rejectedKinds", ",", "{", "kind", ":", "resource", ".", "kind", ",", "group", ":", "group", ".", "name", "}", ")", ")", "{", "return", ";", "}", "if", "(", "excludeKindFromAPIGroupList", "(", "group", ".", "name", ",", "resource", ".", "kind", ")", ")", "{", "return", ";", "}", "if", "(", "resource", ".", "namespaced", "||", "includeClusterScoped", ")", "{", "kinds", ".", "push", "(", "{", "kind", ":", "resource", ".", "kind", ",", "group", ":", "group", ".", "name", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "_", ".", "uniqBy", "(", "kinds", ",", "function", "(", "value", ")", "{", "return", "value", ".", "group", "+", "\"/\"", "+", "value", ".", "kind", ";", "}", ")", ";", "}" ]
Returns an array of available kinds, including their group
[ "Returns", "an", "array", "of", "available", "kinds", "including", "their", "group" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L918-L973
21,984
openshift/origin-web-common
dist/origin-web-common-services.js
function() { var user = userStore.getUser(); if (user) { $rootScope.user = user; authLogger.log('AuthService.withUser()', user); return $q.when(user); } else { authLogger.log('AuthService.withUser(), calling startLogin()'); return this.startLogin(); } }
javascript
function() { var user = userStore.getUser(); if (user) { $rootScope.user = user; authLogger.log('AuthService.withUser()', user); return $q.when(user); } else { authLogger.log('AuthService.withUser(), calling startLogin()'); return this.startLogin(); } }
[ "function", "(", ")", "{", "var", "user", "=", "userStore", ".", "getUser", "(", ")", ";", "if", "(", "user", ")", "{", "$rootScope", ".", "user", "=", "user", ";", "authLogger", ".", "log", "(", "'AuthService.withUser()'", ",", "user", ")", ";", "return", "$q", ".", "when", "(", "user", ")", ";", "}", "else", "{", "authLogger", ".", "log", "(", "'AuthService.withUser(), calling startLogin()'", ")", ";", "return", "this", ".", "startLogin", "(", ")", ";", "}", "}" ]
Returns a promise of a user, which is resolved with a logged in user. Triggers a login if needed.
[ "Returns", "a", "promise", "of", "a", "user", "which", "is", "resolved", "with", "a", "logged", "in", "user", ".", "Triggers", "a", "login", "if", "needed", "." ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L1188-L1198
21,985
openshift/origin-web-common
dist/origin-web-common-services.js
function(config) { // Requests that don't require auth can continue if (!AuthService.requestRequiresAuth(config)) { // console.log("No auth required", config.url); return config; } // If we could add auth info, we can continue if (AuthService.addAuthToRequest(config)) { // console.log("Auth added", config.url); return config; } // We should have added auth info, but couldn't // If we were specifically told not to trigger a login, return if (config.auth && config.auth.triggerLogin === false) { return config; } // 1. Set up a deferred and remember this config, so we can add auth info and resume once login is complete var deferred = $q.defer(); pendingRequestConfigs.push([deferred, config, 'request']); // 2. Start the login flow AuthService.startLogin(); // 3. Return the deferred's promise return deferred.promise; }
javascript
function(config) { // Requests that don't require auth can continue if (!AuthService.requestRequiresAuth(config)) { // console.log("No auth required", config.url); return config; } // If we could add auth info, we can continue if (AuthService.addAuthToRequest(config)) { // console.log("Auth added", config.url); return config; } // We should have added auth info, but couldn't // If we were specifically told not to trigger a login, return if (config.auth && config.auth.triggerLogin === false) { return config; } // 1. Set up a deferred and remember this config, so we can add auth info and resume once login is complete var deferred = $q.defer(); pendingRequestConfigs.push([deferred, config, 'request']); // 2. Start the login flow AuthService.startLogin(); // 3. Return the deferred's promise return deferred.promise; }
[ "function", "(", "config", ")", "{", "// Requests that don't require auth can continue", "if", "(", "!", "AuthService", ".", "requestRequiresAuth", "(", "config", ")", ")", "{", "// console.log(\"No auth required\", config.url);", "return", "config", ";", "}", "// If we could add auth info, we can continue", "if", "(", "AuthService", ".", "addAuthToRequest", "(", "config", ")", ")", "{", "// console.log(\"Auth added\", config.url);", "return", "config", ";", "}", "// We should have added auth info, but couldn't", "// If we were specifically told not to trigger a login, return", "if", "(", "config", ".", "auth", "&&", "config", ".", "auth", ".", "triggerLogin", "===", "false", ")", "{", "return", "config", ";", "}", "// 1. Set up a deferred and remember this config, so we can add auth info and resume once login is complete", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "pendingRequestConfigs", ".", "push", "(", "[", "deferred", ",", "config", ",", "'request'", "]", ")", ";", "// 2. Start the login flow", "AuthService", ".", "startLogin", "(", ")", ";", "// 3. Return the deferred's promise", "return", "deferred", ".", "promise", ";", "}" ]
If auth is not needed, or is already present, returns a config If auth is needed and not present, starts a login flow and returns a promise of a config
[ "If", "auth", "is", "not", "needed", "or", "is", "already", "present", "returns", "a", "config", "If", "auth", "is", "needed", "and", "not", "present", "starts", "a", "login", "flow", "and", "returns", "a", "promise", "of", "a", "config" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L1330-L1357
21,986
openshift/origin-web-common
dist/origin-web-common-services.js
function(projectName, forceRefresh) { var deferred = $q.defer(); currentProject = projectName; var projectRules = cachedRulesByProject.get(projectName); var rulesResource = "selfsubjectrulesreviews"; if (!projectRules || projectRules.forceRefresh || forceRefresh) { // Check if APIserver contains 'selfsubjectrulesreviews' resource. If not switch to permissive mode. if (APIService.apiInfo(rulesResource)) { // If a request is already in flight, return the promise for that request. if (inFlightRulesRequests[projectName]) { return inFlightRulesRequests[projectName]; } Logger.log("AuthorizationService, loading user rules for " + projectName + " project"); inFlightRulesRequests[projectName] = deferred.promise; var resourceGroupVersion = { kind: "SelfSubjectRulesReview", apiVersion: "v1" }; DataService.create(rulesResource, null, resourceGroupVersion, {namespace: projectName}).then( function(data) { var normalizedData = normalizeRules(data.status.rules); var canUserAddToProject = canAddToProjectCheck(data.status.rules); cachedRulesByProject.put(projectName, {rules: normalizedData, canAddToProject: canUserAddToProject, forceRefresh: false, cacheTimestamp: _.now() }); deferred.resolve(); }, function() { permissiveMode = true; deferred.resolve(); }).finally(function() { delete inFlightRulesRequests[projectName]; }); } else { Logger.log("AuthorizationService, resource 'selfsubjectrulesreviews' is not part of APIserver. Switching into permissive mode."); permissiveMode = true; deferred.resolve(); } } else { // Using cached data. Logger.log("AuthorizationService, using cached rules for " + projectName + " project"); if ((_.now() - projectRules.cacheTimestamp) >= 600000) { projectRules.forceRefresh = true; } deferred.resolve(); } return deferred.promise; }
javascript
function(projectName, forceRefresh) { var deferred = $q.defer(); currentProject = projectName; var projectRules = cachedRulesByProject.get(projectName); var rulesResource = "selfsubjectrulesreviews"; if (!projectRules || projectRules.forceRefresh || forceRefresh) { // Check if APIserver contains 'selfsubjectrulesreviews' resource. If not switch to permissive mode. if (APIService.apiInfo(rulesResource)) { // If a request is already in flight, return the promise for that request. if (inFlightRulesRequests[projectName]) { return inFlightRulesRequests[projectName]; } Logger.log("AuthorizationService, loading user rules for " + projectName + " project"); inFlightRulesRequests[projectName] = deferred.promise; var resourceGroupVersion = { kind: "SelfSubjectRulesReview", apiVersion: "v1" }; DataService.create(rulesResource, null, resourceGroupVersion, {namespace: projectName}).then( function(data) { var normalizedData = normalizeRules(data.status.rules); var canUserAddToProject = canAddToProjectCheck(data.status.rules); cachedRulesByProject.put(projectName, {rules: normalizedData, canAddToProject: canUserAddToProject, forceRefresh: false, cacheTimestamp: _.now() }); deferred.resolve(); }, function() { permissiveMode = true; deferred.resolve(); }).finally(function() { delete inFlightRulesRequests[projectName]; }); } else { Logger.log("AuthorizationService, resource 'selfsubjectrulesreviews' is not part of APIserver. Switching into permissive mode."); permissiveMode = true; deferred.resolve(); } } else { // Using cached data. Logger.log("AuthorizationService, using cached rules for " + projectName + " project"); if ((_.now() - projectRules.cacheTimestamp) >= 600000) { projectRules.forceRefresh = true; } deferred.resolve(); } return deferred.promise; }
[ "function", "(", "projectName", ",", "forceRefresh", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "currentProject", "=", "projectName", ";", "var", "projectRules", "=", "cachedRulesByProject", ".", "get", "(", "projectName", ")", ";", "var", "rulesResource", "=", "\"selfsubjectrulesreviews\"", ";", "if", "(", "!", "projectRules", "||", "projectRules", ".", "forceRefresh", "||", "forceRefresh", ")", "{", "// Check if APIserver contains 'selfsubjectrulesreviews' resource. If not switch to permissive mode.", "if", "(", "APIService", ".", "apiInfo", "(", "rulesResource", ")", ")", "{", "// If a request is already in flight, return the promise for that request.", "if", "(", "inFlightRulesRequests", "[", "projectName", "]", ")", "{", "return", "inFlightRulesRequests", "[", "projectName", "]", ";", "}", "Logger", ".", "log", "(", "\"AuthorizationService, loading user rules for \"", "+", "projectName", "+", "\" project\"", ")", ";", "inFlightRulesRequests", "[", "projectName", "]", "=", "deferred", ".", "promise", ";", "var", "resourceGroupVersion", "=", "{", "kind", ":", "\"SelfSubjectRulesReview\"", ",", "apiVersion", ":", "\"v1\"", "}", ";", "DataService", ".", "create", "(", "rulesResource", ",", "null", ",", "resourceGroupVersion", ",", "{", "namespace", ":", "projectName", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "var", "normalizedData", "=", "normalizeRules", "(", "data", ".", "status", ".", "rules", ")", ";", "var", "canUserAddToProject", "=", "canAddToProjectCheck", "(", "data", ".", "status", ".", "rules", ")", ";", "cachedRulesByProject", ".", "put", "(", "projectName", ",", "{", "rules", ":", "normalizedData", ",", "canAddToProject", ":", "canUserAddToProject", ",", "forceRefresh", ":", "false", ",", "cacheTimestamp", ":", "_", ".", "now", "(", ")", "}", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "}", ",", "function", "(", ")", "{", "permissiveMode", "=", "true", ";", "deferred", ".", "resolve", "(", ")", ";", "}", ")", ".", "finally", "(", "function", "(", ")", "{", "delete", "inFlightRulesRequests", "[", "projectName", "]", ";", "}", ")", ";", "}", "else", "{", "Logger", ".", "log", "(", "\"AuthorizationService, resource 'selfsubjectrulesreviews' is not part of APIserver. Switching into permissive mode.\"", ")", ";", "permissiveMode", "=", "true", ";", "deferred", ".", "resolve", "(", ")", ";", "}", "}", "else", "{", "// Using cached data.", "Logger", ".", "log", "(", "\"AuthorizationService, using cached rules for \"", "+", "projectName", "+", "\" project\"", ")", ";", "if", "(", "(", "_", ".", "now", "(", ")", "-", "projectRules", ".", "cacheTimestamp", ")", ">=", "600000", ")", "{", "projectRules", ".", "forceRefresh", "=", "true", ";", "}", "deferred", ".", "resolve", "(", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
forceRefresh is a boolean to bust the cache & request new perms
[ "forceRefresh", "is", "a", "boolean", "to", "bust", "the", "cache", "&", "request", "new", "perms" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L1461-L1510
21,987
openshift/origin-web-common
dist/origin-web-common-services.js
function(serviceInstance, application, serviceClass, parameters) { var parametersSecretName; if (!_.isEmpty(parameters)) { parametersSecretName = generateSecretName(serviceInstance.metadata.name + '-bind-parameters-'); } var newBinding = makeBinding(serviceInstance, application, parametersSecretName); var context = { namespace: serviceInstance.metadata.namespace }; var promise = DataService.create(serviceBindingsVersion, null, newBinding, context); if (!parametersSecretName) { return promise; } // Create the secret as well if the binding has parameters. return promise.then(function(binding) { var parametersSecret = makeParametersSecret(parametersSecretName, parameters, binding); return DataService.create(secretsVersion, null, parametersSecret, context).then(function() { return binding; }); }); }
javascript
function(serviceInstance, application, serviceClass, parameters) { var parametersSecretName; if (!_.isEmpty(parameters)) { parametersSecretName = generateSecretName(serviceInstance.metadata.name + '-bind-parameters-'); } var newBinding = makeBinding(serviceInstance, application, parametersSecretName); var context = { namespace: serviceInstance.metadata.namespace }; var promise = DataService.create(serviceBindingsVersion, null, newBinding, context); if (!parametersSecretName) { return promise; } // Create the secret as well if the binding has parameters. return promise.then(function(binding) { var parametersSecret = makeParametersSecret(parametersSecretName, parameters, binding); return DataService.create(secretsVersion, null, parametersSecret, context).then(function() { return binding; }); }); }
[ "function", "(", "serviceInstance", ",", "application", ",", "serviceClass", ",", "parameters", ")", "{", "var", "parametersSecretName", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "parameters", ")", ")", "{", "parametersSecretName", "=", "generateSecretName", "(", "serviceInstance", ".", "metadata", ".", "name", "+", "'-bind-parameters-'", ")", ";", "}", "var", "newBinding", "=", "makeBinding", "(", "serviceInstance", ",", "application", ",", "parametersSecretName", ")", ";", "var", "context", "=", "{", "namespace", ":", "serviceInstance", ".", "metadata", ".", "namespace", "}", ";", "var", "promise", "=", "DataService", ".", "create", "(", "serviceBindingsVersion", ",", "null", ",", "newBinding", ",", "context", ")", ";", "if", "(", "!", "parametersSecretName", ")", "{", "return", "promise", ";", "}", "// Create the secret as well if the binding has parameters.", "return", "promise", ".", "then", "(", "function", "(", "binding", ")", "{", "var", "parametersSecret", "=", "makeParametersSecret", "(", "parametersSecretName", ",", "parameters", ",", "binding", ")", ";", "return", "DataService", ".", "create", "(", "secretsVersion", ",", "null", ",", "parametersSecret", ",", "context", ")", ".", "then", "(", "function", "(", ")", "{", "return", "binding", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create a binding for `serviceInstance`. If an `application` API object is specified, also create a pod preset for that application using its `spec.selector`. `serviceClass` is required to determine if any parameters need to be set when creating the binding.
[ "Create", "a", "binding", "for", "serviceInstance", ".", "If", "an", "application", "API", "object", "is", "specified", "also", "create", "a", "pod", "preset", "for", "that", "application", "using", "its", "spec", ".", "selector", ".", "serviceClass", "is", "required", "to", "determine", "if", "any", "parameters", "need", "to", "be", "set", "when", "creating", "the", "binding", "." ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L1796-L1819
21,988
openshift/origin-web-common
dist/origin-web-common-services.js
function(id) { if (openQueue[id]) { delete openQueue[id]; } if (messageQueue[id]) { delete messageQueue[id]; } if (closeQueue[id]) { delete closeQueue[id]; } if (errorQueue[id]) { delete errorQueue[id]; } }
javascript
function(id) { if (openQueue[id]) { delete openQueue[id]; } if (messageQueue[id]) { delete messageQueue[id]; } if (closeQueue[id]) { delete closeQueue[id]; } if (errorQueue[id]) { delete errorQueue[id]; } }
[ "function", "(", "id", ")", "{", "if", "(", "openQueue", "[", "id", "]", ")", "{", "delete", "openQueue", "[", "id", "]", ";", "}", "if", "(", "messageQueue", "[", "id", "]", ")", "{", "delete", "messageQueue", "[", "id", "]", ";", "}", "if", "(", "closeQueue", "[", "id", "]", ")", "{", "delete", "closeQueue", "[", "id", "]", ";", "}", "if", "(", "errorQueue", "[", "id", "]", ")", "{", "delete", "errorQueue", "[", "id", "]", ";", "}", "}" ]
can remove any callback from open, message, close or error
[ "can", "remove", "any", "callback", "from", "open", "message", "close", "or", "error" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L2451-L2456
21,989
openshift/origin-web-common
dist/origin-web-common-services.js
function(params) { var keys = _.keysIn( _.pick( params, ['fieldSelector', 'labelSelector']) ).sort(); return _.reduce( keys, function(result, key, i) { return result + key + '=' + encodeURIComponent(params[key]) + ((i < (keys.length-1)) ? '&' : ''); }, '?'); }
javascript
function(params) { var keys = _.keysIn( _.pick( params, ['fieldSelector', 'labelSelector']) ).sort(); return _.reduce( keys, function(result, key, i) { return result + key + '=' + encodeURIComponent(params[key]) + ((i < (keys.length-1)) ? '&' : ''); }, '?'); }
[ "function", "(", "params", ")", "{", "var", "keys", "=", "_", ".", "keysIn", "(", "_", ".", "pick", "(", "params", ",", "[", "'fieldSelector'", ",", "'labelSelector'", "]", ")", ")", ".", "sort", "(", ")", ";", "return", "_", ".", "reduce", "(", "keys", ",", "function", "(", "result", ",", "key", ",", "i", ")", "{", "return", "result", "+", "key", "+", "'='", "+", "encodeURIComponent", "(", "params", "[", "key", "]", ")", "+", "(", "(", "i", "<", "(", "keys", ".", "length", "-", "1", ")", ")", "?", "'&'", ":", "''", ")", ";", "}", ",", "'?'", ")", ";", "}" ]
will take an object, filter & sort it for consistent unique key generation uses encodeURIComponent internally because keys can have special characters, such as '='
[ "will", "take", "an", "object", "filter", "&", "sort", "it", "for", "consistent", "unique", "key", "generation", "uses", "encodeURIComponent", "internally", "because", "keys", "can", "have", "special", "characters", "such", "as", "=" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L2819-L2832
21,990
openshift/origin-web-common
dist/origin-web-common-services.js
function(objects, filterFields, keywords) { if (_.isEmpty(keywords)) { return []; } var results = []; _.each(objects, function(object) { // Keep a score for matches, weighted by field. var score = 0; _.each(keywords, function(regex) { var matchesKeyword = false; _.each(filterFields, function(field) { var value = _.get(object, field.path); if (!value) { return; } if (regex.test(value)) { // For each matching keyword, add the field weight to the score. score += field.weight; matchesKeyword = true; } }); if (!matchesKeyword) { // We've missed a keyword. Set score to 0 and short circuit the loop. score = 0; return false; } }); if (score > 0) { results.push({ object: object, score: score }); } }); // Sort first by score, then by display name for items that have the same score. var orderedResult = _.orderBy(results, ['score', displayName], ['desc', 'asc']); return _.map(orderedResult, 'object'); }
javascript
function(objects, filterFields, keywords) { if (_.isEmpty(keywords)) { return []; } var results = []; _.each(objects, function(object) { // Keep a score for matches, weighted by field. var score = 0; _.each(keywords, function(regex) { var matchesKeyword = false; _.each(filterFields, function(field) { var value = _.get(object, field.path); if (!value) { return; } if (regex.test(value)) { // For each matching keyword, add the field weight to the score. score += field.weight; matchesKeyword = true; } }); if (!matchesKeyword) { // We've missed a keyword. Set score to 0 and short circuit the loop. score = 0; return false; } }); if (score > 0) { results.push({ object: object, score: score }); } }); // Sort first by score, then by display name for items that have the same score. var orderedResult = _.orderBy(results, ['score', displayName], ['desc', 'asc']); return _.map(orderedResult, 'object'); }
[ "function", "(", "objects", ",", "filterFields", ",", "keywords", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "keywords", ")", ")", "{", "return", "[", "]", ";", "}", "var", "results", "=", "[", "]", ";", "_", ".", "each", "(", "objects", ",", "function", "(", "object", ")", "{", "// Keep a score for matches, weighted by field.", "var", "score", "=", "0", ";", "_", ".", "each", "(", "keywords", ",", "function", "(", "regex", ")", "{", "var", "matchesKeyword", "=", "false", ";", "_", ".", "each", "(", "filterFields", ",", "function", "(", "field", ")", "{", "var", "value", "=", "_", ".", "get", "(", "object", ",", "field", ".", "path", ")", ";", "if", "(", "!", "value", ")", "{", "return", ";", "}", "if", "(", "regex", ".", "test", "(", "value", ")", ")", "{", "// For each matching keyword, add the field weight to the score.", "score", "+=", "field", ".", "weight", ";", "matchesKeyword", "=", "true", ";", "}", "}", ")", ";", "if", "(", "!", "matchesKeyword", ")", "{", "// We've missed a keyword. Set score to 0 and short circuit the loop.", "score", "=", "0", ";", "return", "false", ";", "}", "}", ")", ";", "if", "(", "score", ">", "0", ")", "{", "results", ".", "push", "(", "{", "object", ":", "object", ",", "score", ":", "score", "}", ")", ";", "}", "}", ")", ";", "// Sort first by score, then by display name for items that have the same score.", "var", "orderedResult", "=", "_", ".", "orderBy", "(", "results", ",", "[", "'score'", ",", "displayName", "]", ",", "[", "'desc'", ",", "'asc'", "]", ")", ";", "return", "_", ".", "map", "(", "orderedResult", ",", "'object'", ")", ";", "}" ]
Perform a simple weighted search. weightedSearch is like filterForKeywords, except each field has a weight and the result is a sorted array of matches. filterFields is an array of objects with keys `path` and `weight`.
[ "Perform", "a", "simple", "weighted", "search", ".", "weightedSearch", "is", "like", "filterForKeywords", "except", "each", "field", "has", "a", "weight", "and", "the", "result", "is", "a", "sorted", "array", "of", "matches", ".", "filterFields", "is", "an", "array", "of", "objects", "with", "keys", "path", "and", "weight", "." ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L3418-L3460
21,991
openshift/origin-web-common
dist/origin-web-common-services.js
function(forceRefresh) { if (cachedProjectData && !forceRefresh) { Logger.debug('ProjectsService: returning cached project data'); return $q.when(cachedProjectData); } Logger.debug('ProjectsService: listing projects, force refresh', forceRefresh); return DataService.list(projectsVersion, {}).then(function(projectData) { cachedProjectData = projectData; return projectData; }, function(error) { // If the request fails, don't try to list projects again without `forceRefresh`. cachedProjectData = DataService.createData([]); cachedProjectDataIncomplete = true; return $q.reject(); }); }
javascript
function(forceRefresh) { if (cachedProjectData && !forceRefresh) { Logger.debug('ProjectsService: returning cached project data'); return $q.when(cachedProjectData); } Logger.debug('ProjectsService: listing projects, force refresh', forceRefresh); return DataService.list(projectsVersion, {}).then(function(projectData) { cachedProjectData = projectData; return projectData; }, function(error) { // If the request fails, don't try to list projects again without `forceRefresh`. cachedProjectData = DataService.createData([]); cachedProjectDataIncomplete = true; return $q.reject(); }); }
[ "function", "(", "forceRefresh", ")", "{", "if", "(", "cachedProjectData", "&&", "!", "forceRefresh", ")", "{", "Logger", ".", "debug", "(", "'ProjectsService: returning cached project data'", ")", ";", "return", "$q", ".", "when", "(", "cachedProjectData", ")", ";", "}", "Logger", ".", "debug", "(", "'ProjectsService: listing projects, force refresh'", ",", "forceRefresh", ")", ";", "return", "DataService", ".", "list", "(", "projectsVersion", ",", "{", "}", ")", ".", "then", "(", "function", "(", "projectData", ")", "{", "cachedProjectData", "=", "projectData", ";", "return", "projectData", ";", "}", ",", "function", "(", "error", ")", "{", "// If the request fails, don't try to list projects again without `forceRefresh`.", "cachedProjectData", "=", "DataService", ".", "createData", "(", "[", "]", ")", ";", "cachedProjectDataIncomplete", "=", "true", ";", "return", "$q", ".", "reject", "(", ")", ";", "}", ")", ";", "}" ]
List the projects the user has access to. This method returns cached data if the projects had previously been fetched to avoid requesting them again and again, which is a problem for admins who might have hundreds or more.
[ "List", "the", "projects", "the", "user", "has", "access", "to", ".", "This", "method", "returns", "cached", "data", "if", "the", "projects", "had", "previously", "been", "fetched", "to", "avoid", "requesting", "them", "again", "and", "again", "which", "is", "a", "problem", "for", "admins", "who", "might", "have", "hundreds", "or", "more", "." ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L3808-L3824
21,992
openshift/origin-web-common
dist/origin-web-common-services.js
function(params, stateData) { // Handle an error response from the OAuth server if (params.error) { authLogger.log("RedirectLoginService.finish(), error", params.error, params.error_description, params.error_uri); return $q.reject({ error: params.error, error_description: params.error_description, error_uri: params.error_uri }); } // Handle an access_token fragment response if (params.access_token) { return $q.when({ token: params.access_token, ttl: params.expires_in, then: stateData.then, verified: stateData.verified }); } // No token and no error is invalid return $q.reject({ error: "invalid_request", error_description: "No API token returned" }); }
javascript
function(params, stateData) { // Handle an error response from the OAuth server if (params.error) { authLogger.log("RedirectLoginService.finish(), error", params.error, params.error_description, params.error_uri); return $q.reject({ error: params.error, error_description: params.error_description, error_uri: params.error_uri }); } // Handle an access_token fragment response if (params.access_token) { return $q.when({ token: params.access_token, ttl: params.expires_in, then: stateData.then, verified: stateData.verified }); } // No token and no error is invalid return $q.reject({ error: "invalid_request", error_description: "No API token returned" }); }
[ "function", "(", "params", ",", "stateData", ")", "{", "// Handle an error response from the OAuth server", "if", "(", "params", ".", "error", ")", "{", "authLogger", ".", "log", "(", "\"RedirectLoginService.finish(), error\"", ",", "params", ".", "error", ",", "params", ".", "error_description", ",", "params", ".", "error_uri", ")", ";", "return", "$q", ".", "reject", "(", "{", "error", ":", "params", ".", "error", ",", "error_description", ":", "params", ".", "error_description", ",", "error_uri", ":", "params", ".", "error_uri", "}", ")", ";", "}", "// Handle an access_token fragment response", "if", "(", "params", ".", "access_token", ")", "{", "return", "$q", ".", "when", "(", "{", "token", ":", "params", ".", "access_token", ",", "ttl", ":", "params", ".", "expires_in", ",", "then", ":", "stateData", ".", "then", ",", "verified", ":", "stateData", ".", "verified", "}", ")", ";", "}", "// No token and no error is invalid", "return", "$q", ".", "reject", "(", "{", "error", ":", "\"invalid_request\"", ",", "error_description", ":", "\"No API token returned\"", "}", ")", ";", "}" ]
handleParams handles error or access_token responses
[ "handleParams", "handles", "error", "or", "access_token", "responses" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L4183-L4209
21,993
openshift/origin-web-common
dist/origin-web-common.js
function (notification) { if (!notification.id) { return false; } return _.some(notifications, function(next) { return !next.hidden && notification.id === next.id; }); }
javascript
function (notification) { if (!notification.id) { return false; } return _.some(notifications, function(next) { return !next.hidden && notification.id === next.id; }); }
[ "function", "(", "notification", ")", "{", "if", "(", "!", "notification", ".", "id", ")", "{", "return", "false", ";", "}", "return", "_", ".", "some", "(", "notifications", ",", "function", "(", "next", ")", "{", "return", "!", "next", ".", "hidden", "&&", "notification", ".", "id", "===", "next", ".", "id", ";", "}", ")", ";", "}" ]
Is there a visible toast notification with the same ID right now?
[ "Is", "there", "a", "visible", "toast", "notification", "with", "the", "same", "ID", "right", "now?" ]
a56152ba5a42b95bd91c0e65531f6104b9a4dc8f
https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common.js#L6024-L6032
21,994
toomuchdesign/offside
dist/offside.js
_factoryDomInit
function _factoryDomInit() { // Add class to sliding elements slidingElements.forEach( function( item ) { addClass( item, slidingElementsClass ); }); // DOM Fallbacks when CSS transform 3d not available if ( !has3d ) { // No CSS 3d Transform fallback addClass( document.documentElement, 'no-csstransforms3d' ); //Adds Modernizr-like class to HTML element when CSS 3D Transforms not available } // Add init class to body addClass( body, initClass ); }
javascript
function _factoryDomInit() { // Add class to sliding elements slidingElements.forEach( function( item ) { addClass( item, slidingElementsClass ); }); // DOM Fallbacks when CSS transform 3d not available if ( !has3d ) { // No CSS 3d Transform fallback addClass( document.documentElement, 'no-csstransforms3d' ); //Adds Modernizr-like class to HTML element when CSS 3D Transforms not available } // Add init class to body addClass( body, initClass ); }
[ "function", "_factoryDomInit", "(", ")", "{", "// Add class to sliding elements", "slidingElements", ".", "forEach", "(", "function", "(", "item", ")", "{", "addClass", "(", "item", ",", "slidingElementsClass", ")", ";", "}", ")", ";", "// DOM Fallbacks when CSS transform 3d not available", "if", "(", "!", "has3d", ")", "{", "// No CSS 3d Transform fallback", "addClass", "(", "document", ".", "documentElement", ",", "'no-csstransforms3d'", ")", ";", "//Adds Modernizr-like class to HTML element when CSS 3D Transforms not available", "}", "// Add init class to body", "addClass", "(", "body", ",", "initClass", ")", ";", "}" ]
Offside singleton-factory Dom initialization It's called just once on Offside singleton-factory init.
[ "Offside", "singleton", "-", "factory", "Dom", "initialization", "It", "s", "called", "just", "once", "on", "Offside", "singleton", "-", "factory", "init", "." ]
17f0936eaeb4a4abdfafe991fa4471d456b71e5d
https://github.com/toomuchdesign/offside/blob/17f0936eaeb4a4abdfafe991fa4471d456b71e5d/dist/offside.js#L148-L163
21,995
toomuchdesign/offside
dist/offside.js
function( el, options ) { // Get length of instantiated Offsides array var offsideId = instantiatedOffsides.length || 0, // Instantiate new Offside instance offsideInstance = createOffsideInstance( el, options, offsideId ); // If Offside instance is sccessfully created if ( offsideInstance !== null ) { // Push new instance into "instantiatedOffsides" array and return it /*jshint -W093 */ return instantiatedOffsides[ offsideId ] = offsideInstance; /*jshint +W093 */ } }
javascript
function( el, options ) { // Get length of instantiated Offsides array var offsideId = instantiatedOffsides.length || 0, // Instantiate new Offside instance offsideInstance = createOffsideInstance( el, options, offsideId ); // If Offside instance is sccessfully created if ( offsideInstance !== null ) { // Push new instance into "instantiatedOffsides" array and return it /*jshint -W093 */ return instantiatedOffsides[ offsideId ] = offsideInstance; /*jshint +W093 */ } }
[ "function", "(", "el", ",", "options", ")", "{", "// Get length of instantiated Offsides array", "var", "offsideId", "=", "instantiatedOffsides", ".", "length", "||", "0", ",", "// Instantiate new Offside instance", "offsideInstance", "=", "createOffsideInstance", "(", "el", ",", "options", ",", "offsideId", ")", ";", "// If Offside instance is sccessfully created", "if", "(", "offsideInstance", "!==", "null", ")", "{", "// Push new instance into \"instantiatedOffsides\" array and return it", "/*jshint -W093 */", "return", "instantiatedOffsides", "[", "offsideId", "]", "=", "offsideInstance", ";", "/*jshint +W093 */", "}", "}" ]
This is the method responsible for creating a new Offside instance and register it into "instantiatedOffsides" array
[ "This", "is", "the", "method", "responsible", "for", "creating", "a", "new", "Offside", "instance", "and", "register", "it", "into", "instantiatedOffsides", "array" ]
17f0936eaeb4a4abdfafe991fa4471d456b71e5d
https://github.com/toomuchdesign/offside/blob/17f0936eaeb4a4abdfafe991fa4471d456b71e5d/dist/offside.js#L437-L456
21,996
toomuchdesign/offside
dist/offside.js
function ( el, options ) { /* * When Offside is called for the first time, * inject a singleton-factory object * as a static method in "offside.factory". * * Offside factory serves the following purposes: * - DOM initialization * - Centralized Offside instances management and initialization */ if ( !singleton.getInstance.factory ) { singleton.getInstance.factory = initOffsideFactory( options ); } return singleton.getInstance.factory.getOffsideInstance( el, options ); }
javascript
function ( el, options ) { /* * When Offside is called for the first time, * inject a singleton-factory object * as a static method in "offside.factory". * * Offside factory serves the following purposes: * - DOM initialization * - Centralized Offside instances management and initialization */ if ( !singleton.getInstance.factory ) { singleton.getInstance.factory = initOffsideFactory( options ); } return singleton.getInstance.factory.getOffsideInstance( el, options ); }
[ "function", "(", "el", ",", "options", ")", "{", "/*\n * When Offside is called for the first time,\n * inject a singleton-factory object\n * as a static method in \"offside.factory\".\n *\n * Offside factory serves the following purposes:\n * - DOM initialization\n * - Centralized Offside instances management and initialization\n */", "if", "(", "!", "singleton", ".", "getInstance", ".", "factory", ")", "{", "singleton", ".", "getInstance", ".", "factory", "=", "initOffsideFactory", "(", "options", ")", ";", "}", "return", "singleton", ".", "getInstance", ".", "factory", ".", "getOffsideInstance", "(", "el", ",", "options", ")", ";", "}" ]
Get the Singleton instance if one exists or create one if it doesn't
[ "Get", "the", "Singleton", "instance", "if", "one", "exists", "or", "create", "one", "if", "it", "doesn", "t" ]
17f0936eaeb4a4abdfafe991fa4471d456b71e5d
https://github.com/toomuchdesign/offside/blob/17f0936eaeb4a4abdfafe991fa4471d456b71e5d/dist/offside.js#L466-L482
21,997
tensorflow/tfjs-tsne
examples/synthetic_data/index.js
start
async function start() { const numDimensions = 100; const numPoints = 10000; const data = generateData(numDimensions, numPoints); const coordinates = await computeEmbedding(data, numPoints); showEmbedding(coordinates); }
javascript
async function start() { const numDimensions = 100; const numPoints = 10000; const data = generateData(numDimensions, numPoints); const coordinates = await computeEmbedding(data, numPoints); showEmbedding(coordinates); }
[ "async", "function", "start", "(", ")", "{", "const", "numDimensions", "=", "100", ";", "const", "numPoints", "=", "10000", ";", "const", "data", "=", "generateData", "(", "numDimensions", ",", "numPoints", ")", ";", "const", "coordinates", "=", "await", "computeEmbedding", "(", "data", ",", "numPoints", ")", ";", "showEmbedding", "(", "coordinates", ")", ";", "}" ]
Run the example
[ "Run", "the", "example" ]
7757693607dbc363660f81e609cbc00f392a1c35
https://github.com/tensorflow/tfjs-tsne/blob/7757693607dbc363660f81e609cbc00f392a1c35/examples/synthetic_data/index.js#L26-L33
21,998
tensorflow/tfjs-tsne
examples/synthetic_data/index.js
showEmbedding
function showEmbedding(data) { const margin = {top: 20, right: 15, bottom: 60, left: 60}; const width = 800 - margin.left - margin.right; const height = 800 - margin.top - margin.bottom; const x = d3.scaleLinear().domain([0, 1]).range([0, width]); const y = d3.scaleLinear().domain([0, 1]).range([height, 0]); const chart = d3.select('body') .append('svg') .attr('width', width + margin.right + margin.left) .attr('height', height + margin.top + margin.bottom) .attr('class', 'chart'); const main = chart.append('g') .attr( 'transform', 'translate(' + margin.left + ',' + margin.top + ')') .attr('width', width) .attr('height', height) .attr('class', 'main'); const xAxis = d3.axisBottom(x); main.append('g') .attr('transform', 'translate(0,' + height + ')') .attr('class', 'main axis date') .call(xAxis); const yAxis = d3.axisLeft(y); main.append('g') .attr('transform', 'translate(0,0)') .attr('class', 'main axis date') .call(yAxis); const dots = main.append('g'); dots.selectAll('scatter-dots') .data(data) .enter() .append('svg:circle') .attr('cx', (d) => x(d[0])) .attr('cy', (d) => y(d[1])) .attr('stroke-width', 0.25) .attr('stroke', '#1f77b4') .attr('fill', 'none') .attr('r', 5); }
javascript
function showEmbedding(data) { const margin = {top: 20, right: 15, bottom: 60, left: 60}; const width = 800 - margin.left - margin.right; const height = 800 - margin.top - margin.bottom; const x = d3.scaleLinear().domain([0, 1]).range([0, width]); const y = d3.scaleLinear().domain([0, 1]).range([height, 0]); const chart = d3.select('body') .append('svg') .attr('width', width + margin.right + margin.left) .attr('height', height + margin.top + margin.bottom) .attr('class', 'chart'); const main = chart.append('g') .attr( 'transform', 'translate(' + margin.left + ',' + margin.top + ')') .attr('width', width) .attr('height', height) .attr('class', 'main'); const xAxis = d3.axisBottom(x); main.append('g') .attr('transform', 'translate(0,' + height + ')') .attr('class', 'main axis date') .call(xAxis); const yAxis = d3.axisLeft(y); main.append('g') .attr('transform', 'translate(0,0)') .attr('class', 'main axis date') .call(yAxis); const dots = main.append('g'); dots.selectAll('scatter-dots') .data(data) .enter() .append('svg:circle') .attr('cx', (d) => x(d[0])) .attr('cy', (d) => y(d[1])) .attr('stroke-width', 0.25) .attr('stroke', '#1f77b4') .attr('fill', 'none') .attr('r', 5); }
[ "function", "showEmbedding", "(", "data", ")", "{", "const", "margin", "=", "{", "top", ":", "20", ",", "right", ":", "15", ",", "bottom", ":", "60", ",", "left", ":", "60", "}", ";", "const", "width", "=", "800", "-", "margin", ".", "left", "-", "margin", ".", "right", ";", "const", "height", "=", "800", "-", "margin", ".", "top", "-", "margin", ".", "bottom", ";", "const", "x", "=", "d3", ".", "scaleLinear", "(", ")", ".", "domain", "(", "[", "0", ",", "1", "]", ")", ".", "range", "(", "[", "0", ",", "width", "]", ")", ";", "const", "y", "=", "d3", ".", "scaleLinear", "(", ")", ".", "domain", "(", "[", "0", ",", "1", "]", ")", ".", "range", "(", "[", "height", ",", "0", "]", ")", ";", "const", "chart", "=", "d3", ".", "select", "(", "'body'", ")", ".", "append", "(", "'svg'", ")", ".", "attr", "(", "'width'", ",", "width", "+", "margin", ".", "right", "+", "margin", ".", "left", ")", ".", "attr", "(", "'height'", ",", "height", "+", "margin", ".", "top", "+", "margin", ".", "bottom", ")", ".", "attr", "(", "'class'", ",", "'chart'", ")", ";", "const", "main", "=", "chart", ".", "append", "(", "'g'", ")", ".", "attr", "(", "'transform'", ",", "'translate('", "+", "margin", ".", "left", "+", "','", "+", "margin", ".", "top", "+", "')'", ")", ".", "attr", "(", "'width'", ",", "width", ")", ".", "attr", "(", "'height'", ",", "height", ")", ".", "attr", "(", "'class'", ",", "'main'", ")", ";", "const", "xAxis", "=", "d3", ".", "axisBottom", "(", "x", ")", ";", "main", ".", "append", "(", "'g'", ")", ".", "attr", "(", "'transform'", ",", "'translate(0,'", "+", "height", "+", "')'", ")", ".", "attr", "(", "'class'", ",", "'main axis date'", ")", ".", "call", "(", "xAxis", ")", ";", "const", "yAxis", "=", "d3", ".", "axisLeft", "(", "y", ")", ";", "main", ".", "append", "(", "'g'", ")", ".", "attr", "(", "'transform'", ",", "'translate(0,0)'", ")", ".", "attr", "(", "'class'", ",", "'main axis date'", ")", ".", "call", "(", "yAxis", ")", ";", "const", "dots", "=", "main", ".", "append", "(", "'g'", ")", ";", "dots", ".", "selectAll", "(", "'scatter-dots'", ")", ".", "data", "(", "data", ")", ".", "enter", "(", ")", ".", "append", "(", "'svg:circle'", ")", ".", "attr", "(", "'cx'", ",", "(", "d", ")", "=>", "x", "(", "d", "[", "0", "]", ")", ")", ".", "attr", "(", "'cy'", ",", "(", "d", ")", "=>", "y", "(", "d", "[", "1", "]", ")", ")", ".", "attr", "(", "'stroke-width'", ",", "0.25", ")", ".", "attr", "(", "'stroke'", ",", "'#1f77b4'", ")", ".", "attr", "(", "'fill'", ",", "'none'", ")", ".", "attr", "(", "'r'", ",", "5", ")", ";", "}" ]
This will add a new plot visualizing the embedding space on a scatterplot.
[ "This", "will", "add", "a", "new", "plot", "visualizing", "the", "embedding", "space", "on", "a", "scatterplot", "." ]
7757693607dbc363660f81e609cbc00f392a1c35
https://github.com/tensorflow/tfjs-tsne/blob/7757693607dbc363660f81e609cbc00f392a1c35/examples/synthetic_data/index.js#L75-L121
21,999
web-perf/react-worker-dom
src/worker/ReactWWComponent.js
extractEventHandlers
function extractEventHandlers(props) { let result = { eventHandlers: {}, options: {} }; for (let key in props) { if (ReactBrowserEventEmitter.registrationNameModules.hasOwnProperty(key)) { result.eventHandlers[key] = props[key]; } else { result.options[key] = props[key]; } } return result; }
javascript
function extractEventHandlers(props) { let result = { eventHandlers: {}, options: {} }; for (let key in props) { if (ReactBrowserEventEmitter.registrationNameModules.hasOwnProperty(key)) { result.eventHandlers[key] = props[key]; } else { result.options[key] = props[key]; } } return result; }
[ "function", "extractEventHandlers", "(", "props", ")", "{", "let", "result", "=", "{", "eventHandlers", ":", "{", "}", ",", "options", ":", "{", "}", "}", ";", "for", "(", "let", "key", "in", "props", ")", "{", "if", "(", "ReactBrowserEventEmitter", ".", "registrationNameModules", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "result", ".", "eventHandlers", "[", "key", "]", "=", "props", "[", "key", "]", ";", "}", "else", "{", "result", ".", "options", "[", "key", "]", "=", "props", "[", "key", "]", ";", "}", "}", "return", "result", ";", "}" ]
Function to separate event Handlers and regular props @param {Object} props Props passed to a React Component @return {eventHandlers: {}, options: {}} An object containing eventHandlers and options
[ "Function", "to", "separate", "event", "Handlers", "and", "regular", "props" ]
8fc5c011bc5c5ff43c6f5b184b60f6edd5872a6b
https://github.com/web-perf/react-worker-dom/blob/8fc5c011bc5c5ff43c6f5b184b60f6edd5872a6b/src/worker/ReactWWComponent.js#L14-L27