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
33,500
iconic/grunt-svg-toolkit
tasks/lib/colorize-svg.js
svgcolor
function svgcolor(el, color) { var styles = window.getComputedStyle(el, null); var fill = styles['fill']; var stroke = styles['stroke']; var isFill, isStroke; if (!fill && !stroke) { isFill = true; } else { if (fill && fill !== 'none') { isFill = true; } if (stroke && stroke !== 'none') { isStroke = true; } } if (isStroke) { el.style.stroke = null; el.setAttribute('stroke', color || stroke); } if (isFill) { el.style.fill = null; el.setAttribute('fill', color || fill); } }
javascript
function svgcolor(el, color) { var styles = window.getComputedStyle(el, null); var fill = styles['fill']; var stroke = styles['stroke']; var isFill, isStroke; if (!fill && !stroke) { isFill = true; } else { if (fill && fill !== 'none') { isFill = true; } if (stroke && stroke !== 'none') { isStroke = true; } } if (isStroke) { el.style.stroke = null; el.setAttribute('stroke', color || stroke); } if (isFill) { el.style.fill = null; el.setAttribute('fill', color || fill); } }
[ "function", "svgcolor", "(", "el", ",", "color", ")", "{", "var", "styles", "=", "window", ".", "getComputedStyle", "(", "el", ",", "null", ")", ";", "var", "fill", "=", "styles", "[", "'fill'", "]", ";", "var", "stroke", "=", "styles", "[", "'stroke...
Given an element, color it by inlining a fill or stroke attribute. If color isn't define, it will use the current computed style for use when applying styles via CSS
[ "Given", "an", "element", "color", "it", "by", "inlining", "a", "fill", "or", "stroke", "attribute", ".", "If", "color", "isn", "t", "define", "it", "will", "use", "the", "current", "computed", "style", "for", "use", "when", "applying", "styles", "via", ...
6d3b6c820e5a400e856264708c5d32571f35f486
https://github.com/iconic/grunt-svg-toolkit/blob/6d3b6c820e5a400e856264708c5d32571f35f486/tasks/lib/colorize-svg.js#L42-L71
33,501
cssinjs/jss-default-unit
src/index.js
addCamelCasedVersion
function addCamelCasedVersion(obj) { const regExp = /(-[a-z])/g const replace = str => str[1].toUpperCase() const newObj = {} for (const key in obj) { newObj[key] = obj[key] newObj[key.replace(regExp, replace)] = obj[key] } return newObj }
javascript
function addCamelCasedVersion(obj) { const regExp = /(-[a-z])/g const replace = str => str[1].toUpperCase() const newObj = {} for (const key in obj) { newObj[key] = obj[key] newObj[key.replace(regExp, replace)] = obj[key] } return newObj }
[ "function", "addCamelCasedVersion", "(", "obj", ")", "{", "const", "regExp", "=", "/", "(-[a-z])", "/", "g", "const", "replace", "=", "str", "=>", "str", "[", "1", "]", ".", "toUpperCase", "(", ")", "const", "newObj", "=", "{", "}", "for", "(", "cons...
Clones the object and adds a camel cased property version.
[ "Clones", "the", "object", "and", "adds", "a", "camel", "cased", "property", "version", "." ]
ab30fa08a3b037ddaa0b0bd6bd257cee7f6b46f7
https://github.com/cssinjs/jss-default-unit/blob/ab30fa08a3b037ddaa0b0bd6bd257cee7f6b46f7/src/index.js#L6-L15
33,502
cssinjs/jss-default-unit
src/index.js
iterate
function iterate(prop, value, options) { if (!value) return value let convertedValue = value let type = typeof value if (type === 'object' && Array.isArray(value)) type = 'array' switch (type) { case 'object': if (prop === 'fallbacks') { for (const innerProp in value) { value[innerProp] = iterate(innerProp, value[innerProp], options) } break } for (const innerProp in value) { value[innerProp] = iterate(`${prop}-${innerProp}`, value[innerProp], options) } break case 'array': for (let i = 0; i < value.length; i++) { value[i] = iterate(prop, value[i], options) } break case 'number': if (value !== 0) { convertedValue = value + (options[prop] || units[prop] || '') } break default: break } return convertedValue }
javascript
function iterate(prop, value, options) { if (!value) return value let convertedValue = value let type = typeof value if (type === 'object' && Array.isArray(value)) type = 'array' switch (type) { case 'object': if (prop === 'fallbacks') { for (const innerProp in value) { value[innerProp] = iterate(innerProp, value[innerProp], options) } break } for (const innerProp in value) { value[innerProp] = iterate(`${prop}-${innerProp}`, value[innerProp], options) } break case 'array': for (let i = 0; i < value.length; i++) { value[i] = iterate(prop, value[i], options) } break case 'number': if (value !== 0) { convertedValue = value + (options[prop] || units[prop] || '') } break default: break } return convertedValue }
[ "function", "iterate", "(", "prop", ",", "value", ",", "options", ")", "{", "if", "(", "!", "value", ")", "return", "value", "let", "convertedValue", "=", "value", "let", "type", "=", "typeof", "value", "if", "(", "type", "===", "'object'", "&&", "Arra...
Recursive deep style passing function @param {String} current property @param {(Object|Array|Number|String)} property value @param {Object} options @return {(Object|Array|Number|String)} resulting value
[ "Recursive", "deep", "style", "passing", "function" ]
ab30fa08a3b037ddaa0b0bd6bd257cee7f6b46f7
https://github.com/cssinjs/jss-default-unit/blob/ab30fa08a3b037ddaa0b0bd6bd257cee7f6b46f7/src/index.js#L27-L62
33,503
kaazing/http2.js
lib/protocol/flow.js
Flow
function Flow(flowControlId) { Duplex.call(this, { objectMode: true }); this._window = this._initialWindow = INITIAL_WINDOW_SIZE; this._flowControlId = flowControlId; this._queue = []; this._ended = false; this._received = 0; this._blocked = false; }
javascript
function Flow(flowControlId) { Duplex.call(this, { objectMode: true }); this._window = this._initialWindow = INITIAL_WINDOW_SIZE; this._flowControlId = flowControlId; this._queue = []; this._ended = false; this._received = 0; this._blocked = false; }
[ "function", "Flow", "(", "flowControlId", ")", "{", "Duplex", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "_window", "=", "this", ".", "_initialWindow", "=", "INITIAL_WINDOW_SIZE", ";", "this", ".", "_flowCo...
`flowControlId` is needed if only specific WINDOW_UPDATEs should be watched.
[ "flowControlId", "is", "needed", "if", "only", "specific", "WINDOW_UPDATEs", "should", "be", "watched", "." ]
ffc7a2b9a38cd5b0e68d98792264b3587a325088
https://github.com/kaazing/http2.js/blob/ffc7a2b9a38cd5b0e68d98792264b3587a325088/lib/protocol/flow.js#L61-L70
33,504
GitbookIO/plugin-sharing
index.js
function(cfg) { var sharingLink = _.get(cfg, 'links.sharing', {}); cfg.pluginsConfig.sharing = _.defaults(cfg.pluginsConfig.sharing || {}, {}); _.each(sharingLink, function(enabled, type) { if (enabled != false) return; if (type == 'all') cfg.pluginsConfig.sharing[type] = []; else cfg.pluginsConfig.sharing[type] = false; }); return cfg; }
javascript
function(cfg) { var sharingLink = _.get(cfg, 'links.sharing', {}); cfg.pluginsConfig.sharing = _.defaults(cfg.pluginsConfig.sharing || {}, {}); _.each(sharingLink, function(enabled, type) { if (enabled != false) return; if (type == 'all') cfg.pluginsConfig.sharing[type] = []; else cfg.pluginsConfig.sharing[type] = false; }); return cfg; }
[ "function", "(", "cfg", ")", "{", "var", "sharingLink", "=", "_", ".", "get", "(", "cfg", ",", "'links.sharing'", ",", "{", "}", ")", ";", "cfg", ".", "pluginsConfig", ".", "sharing", "=", "_", ".", "defaults", "(", "cfg", ".", "pluginsConfig", ".", ...
Compatibility layer for gitbook < 2.5.0
[ "Compatibility", "layer", "for", "gitbook", "<", "2", ".", "5", ".", "0" ]
728a267fc9e8f3be0c076150a8b6bbdf2bcab4de
https://github.com/GitbookIO/plugin-sharing/blob/728a267fc9e8f3be0c076150a8b6bbdf2bcab4de/index.js#L12-L24
33,505
klayveR/poe-log-monitor
index.js
readLogStream
async function readLogStream(file, instance) { return new Promise(resolve => { var stream = fs.createReadStream(file, { encoding: 'utf8', highWaterMark: instance.chunkSize }); var hasStarted = false; // Split data into chunks so we dont stall the client stream.on('data', chunk => { if (!hasStarted) instance.emit("parsingStarted"); hasStarted = true; var lines = chunk.toString().split("\n"); // Pause stream until this chunk is completed to avoid spamming the thread stream.pause(); async.each(lines, function (line, callback) { instance.registerMatch(line); callback(); }, function (err) { setTimeout(() => { stream.resume(); }, instance.chunkInterval); }); }); stream.on('end', () => { instance.emit("parsingComplete"); resolve(); stream.close(); }); }); }
javascript
async function readLogStream(file, instance) { return new Promise(resolve => { var stream = fs.createReadStream(file, { encoding: 'utf8', highWaterMark: instance.chunkSize }); var hasStarted = false; // Split data into chunks so we dont stall the client stream.on('data', chunk => { if (!hasStarted) instance.emit("parsingStarted"); hasStarted = true; var lines = chunk.toString().split("\n"); // Pause stream until this chunk is completed to avoid spamming the thread stream.pause(); async.each(lines, function (line, callback) { instance.registerMatch(line); callback(); }, function (err) { setTimeout(() => { stream.resume(); }, instance.chunkInterval); }); }); stream.on('end', () => { instance.emit("parsingComplete"); resolve(); stream.close(); }); }); }
[ "async", "function", "readLogStream", "(", "file", ",", "instance", ")", "{", "return", "new", "Promise", "(", "resolve", "=>", "{", "var", "stream", "=", "fs", ".", "createReadStream", "(", "file", ",", "{", "encoding", ":", "'utf8'", ",", "highWaterMark"...
Reads the file and emits events for each included event
[ "Reads", "the", "file", "and", "emits", "events", "for", "each", "included", "event" ]
ba668a275ea653cdb777325fb1d8b1c5610b348a
https://github.com/klayveR/poe-log-monitor/blob/ba668a275ea653cdb777325fb1d8b1c5610b348a/index.js#L71-L97
33,506
imrvelj/moment-random
src/index.js
momentRandom
function momentRandom(end = moment(), start) { const endTime = +moment(end); const randomNumber = (to, from = 0) => Math.floor(Math.random() * (to - from) + from); if (start) { const startTime = +moment(start); if (startTime > endTime) { throw new Error('End date is before start date!'); } return moment(randomNumber(endTime, startTime)); } return moment(randomNumber(endTime)); }
javascript
function momentRandom(end = moment(), start) { const endTime = +moment(end); const randomNumber = (to, from = 0) => Math.floor(Math.random() * (to - from) + from); if (start) { const startTime = +moment(start); if (startTime > endTime) { throw new Error('End date is before start date!'); } return moment(randomNumber(endTime, startTime)); } return moment(randomNumber(endTime)); }
[ "function", "momentRandom", "(", "end", "=", "moment", "(", ")", ",", "start", ")", "{", "const", "endTime", "=", "+", "moment", "(", "end", ")", ";", "const", "randomNumber", "=", "(", "to", ",", "from", "=", "0", ")", "=>", "Math", ".", "floor", ...
Generates a random moment.js object @param {any} end - END date [Anything a moment constructor accepts] @param {any} start - START date [Anything a moment constructor accepts] @returns
[ "Generates", "a", "random", "moment", ".", "js", "object" ]
5945140e303a5964ce24846ecd58a48e1fccd451
https://github.com/imrvelj/moment-random/blob/5945140e303a5964ce24846ecd58a48e1fccd451/src/index.js#L10-L23
33,507
openchain/openchain-js
lib/apiclient.js
ApiClient
function ApiClient(endpoint) { if (endpoint.length > 0 && endpoint.slice(-1) != "/") { endpoint += "/"; } this.endpoint = endpoint; this.namespace = null; }
javascript
function ApiClient(endpoint) { if (endpoint.length > 0 && endpoint.slice(-1) != "/") { endpoint += "/"; } this.endpoint = endpoint; this.namespace = null; }
[ "function", "ApiClient", "(", "endpoint", ")", "{", "if", "(", "endpoint", ".", "length", ">", "0", "&&", "endpoint", ".", "slice", "(", "-", "1", ")", "!=", "\"/\"", ")", "{", "endpoint", "+=", "\"/\"", ";", "}", "this", ".", "endpoint", "=", "end...
Represents an Openchain client bound to a specific Openchain endpoint. @constructor @param {string} endpoint The base URL of the endpoint.
[ "Represents", "an", "Openchain", "client", "bound", "to", "a", "specific", "Openchain", "endpoint", "." ]
41ae72504a29ba3067236f489e5117a4bda8d9d6
https://github.com/openchain/openchain-js/blob/41ae72504a29ba3067236f489e5117a4bda8d9d6/lib/apiclient.js#L31-L38
33,508
jesseskinner/hover
src/util/react/mixin.js
SubscribeMixin
function SubscribeMixin(subscribe, key) { var unsubscribe; return { componentDidMount: function () { // this should never happen if (unsubscribe) { throw new Error('Cannot reuse a mixin.'); } unsubscribe = subscribe(function (data) { // by default, use the store's state as the component's state var state = data; // but if a key is provided, map the data to that key if (key) { state = {}; state[key] = data; } // update the component's state this.setState(state); }.bind(this)); }, componentWillUnmount: function () { // call the unsubscribe function returned from store.getState above if (unsubscribe) { unsubscribe(); // wipe the unsubscribe, so the mixin can be used again maybe unsubscribe = null; } } }; }
javascript
function SubscribeMixin(subscribe, key) { var unsubscribe; return { componentDidMount: function () { // this should never happen if (unsubscribe) { throw new Error('Cannot reuse a mixin.'); } unsubscribe = subscribe(function (data) { // by default, use the store's state as the component's state var state = data; // but if a key is provided, map the data to that key if (key) { state = {}; state[key] = data; } // update the component's state this.setState(state); }.bind(this)); }, componentWillUnmount: function () { // call the unsubscribe function returned from store.getState above if (unsubscribe) { unsubscribe(); // wipe the unsubscribe, so the mixin can be used again maybe unsubscribe = null; } } }; }
[ "function", "SubscribeMixin", "(", "subscribe", ",", "key", ")", "{", "var", "unsubscribe", ";", "return", "{", "componentDidMount", ":", "function", "(", ")", "{", "// this should never happen", "if", "(", "unsubscribe", ")", "{", "throw", "new", "Error", "("...
React mixin, for easily subscribing and unsubscribing to a Hover store Usage: var SubscribeMixin = require('hover/src/util/mixin'); React.createClass({ mixins: [ this will map the state of myStore to this.state.store SubscribeMixin(myStore, 'store') ], render: function () { use this.state.store } }); NOTE: Do not reuse a mixin, each mixin should be only used once.
[ "React", "mixin", "for", "easily", "subscribing", "and", "unsubscribing", "to", "a", "Hover", "store" ]
b2f024eb73f9f3a32a47856321f553c3dec61afb
https://github.com/jesseskinner/hover/blob/b2f024eb73f9f3a32a47856321f553c3dec61afb/src/util/react/mixin.js#L21-L56
33,509
jaredhanson/junction
lib/junction/application.js
prepareRes
function prepareRes(stanza) { var res = null; if (stanza.is('iq') && (stanza.attr('type') == 'get' || stanza.attr('type') == 'set')) { // TODO: When connected as a component, the from field needs to be set // eplicitly (from = stanza.attrs.to). res = new xmpp.Stanza('iq', { id: stanza.attr('id'), to: stanza.attr('from'), type: 'result' }) } // TODO: Prepare presence and message stanzas (which are optional to send) return res; }
javascript
function prepareRes(stanza) { var res = null; if (stanza.is('iq') && (stanza.attr('type') == 'get' || stanza.attr('type') == 'set')) { // TODO: When connected as a component, the from field needs to be set // eplicitly (from = stanza.attrs.to). res = new xmpp.Stanza('iq', { id: stanza.attr('id'), to: stanza.attr('from'), type: 'result' }) } // TODO: Prepare presence and message stanzas (which are optional to send) return res; }
[ "function", "prepareRes", "(", "stanza", ")", "{", "var", "res", "=", "null", ";", "if", "(", "stanza", ".", "is", "(", "'iq'", ")", "&&", "(", "stanza", ".", "attr", "(", "'type'", ")", "==", "'get'", "||", "stanza", ".", "attr", "(", "'type'", ...
Prepare a response to `stanza`. @api private
[ "Prepare", "a", "response", "to", "stanza", "." ]
28854611428687602506b6aed6d2559878b0d6ea
https://github.com/jaredhanson/junction/blob/28854611428687602506b6aed6d2559878b0d6ea/lib/junction/application.js#L255-L268
33,510
openchain/openchain-js
lib/mutationsigner.js
MutationSigner
function MutationSigner(privateKey) { this.publicKey = ByteBuffer.wrap(privateKey.publicKey.toBuffer()); this._signer = bitcore.crypto.ECDSA().set({ endian: "big", privkey: privateKey.privateKey }); }
javascript
function MutationSigner(privateKey) { this.publicKey = ByteBuffer.wrap(privateKey.publicKey.toBuffer()); this._signer = bitcore.crypto.ECDSA().set({ endian: "big", privkey: privateKey.privateKey }); }
[ "function", "MutationSigner", "(", "privateKey", ")", "{", "this", ".", "publicKey", "=", "ByteBuffer", ".", "wrap", "(", "privateKey", ".", "publicKey", ".", "toBuffer", "(", ")", ")", ";", "this", ".", "_signer", "=", "bitcore", ".", "crypto", ".", "EC...
Provides the ability to sign a mutation. @constructor @param {!HDPrivateKey} privateKey The private key used to sign the mutations.
[ "Provides", "the", "ability", "to", "sign", "a", "mutation", "." ]
41ae72504a29ba3067236f489e5117a4bda8d9d6
https://github.com/openchain/openchain-js/blob/41ae72504a29ba3067236f489e5117a4bda8d9d6/lib/mutationsigner.js#L26-L32
33,511
gristlabs/yaml-cfn
index.js
splitOne
function splitOne(str, sep) { let index = str.indexOf(sep); return index < 0 ? null : [str.slice(0, index), str.slice(index + sep.length)]; }
javascript
function splitOne(str, sep) { let index = str.indexOf(sep); return index < 0 ? null : [str.slice(0, index), str.slice(index + sep.length)]; }
[ "function", "splitOne", "(", "str", ",", "sep", ")", "{", "let", "index", "=", "str", ".", "indexOf", "(", "sep", ")", ";", "return", "index", "<", "0", "?", "null", ":", "[", "str", ".", "slice", "(", "0", ",", "index", ")", ",", "str", ".", ...
Split a string on the given separator just once, returning an array of two parts, or null.
[ "Split", "a", "string", "on", "the", "given", "separator", "just", "once", "returning", "an", "array", "of", "two", "parts", "or", "null", "." ]
8ef43fd002fa29221f058d2be0762e4da6735103
https://github.com/gristlabs/yaml-cfn/blob/8ef43fd002fa29221f058d2be0762e4da6735103/index.js#L19-L22
33,512
gristlabs/yaml-cfn
index.js
checkType
function checkType(obj, keyName) { return obj && typeof obj === 'object' && Object.keys(obj).length === 1 && obj.hasOwnProperty(keyName); }
javascript
function checkType(obj, keyName) { return obj && typeof obj === 'object' && Object.keys(obj).length === 1 && obj.hasOwnProperty(keyName); }
[ "function", "checkType", "(", "obj", ",", "keyName", ")", "{", "return", "obj", "&&", "typeof", "obj", "===", "'object'", "&&", "Object", ".", "keys", "(", "obj", ")", ".", "length", "===", "1", "&&", "obj", ".", "hasOwnProperty", "(", "keyName", ")", ...
Returns true if obj is a representation of a CloudFormation intrinsic, i.e. an object with a single property at key keyName.
[ "Returns", "true", "if", "obj", "is", "a", "representation", "of", "a", "CloudFormation", "intrinsic", "i", ".", "e", ".", "an", "object", "with", "a", "single", "property", "at", "key", "keyName", "." ]
8ef43fd002fa29221f058d2be0762e4da6735103
https://github.com/gristlabs/yaml-cfn/blob/8ef43fd002fa29221f058d2be0762e4da6735103/index.js#L28-L31
33,513
jaredhanson/junction
lib/junction/stanzaerror.js
StanzaError
function StanzaError(message, type, condition) { Error.apply(this, arguments); Error.captureStackTrace(this, arguments.callee); this.name = 'StanzaError'; this.message = message || null; this.type = type || 'wait'; this.condition = condition || 'internal-server-error'; }
javascript
function StanzaError(message, type, condition) { Error.apply(this, arguments); Error.captureStackTrace(this, arguments.callee); this.name = 'StanzaError'; this.message = message || null; this.type = type || 'wait'; this.condition = condition || 'internal-server-error'; }
[ "function", "StanzaError", "(", "message", ",", "type", ",", "condition", ")", "{", "Error", ".", "apply", "(", "this", ",", "arguments", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", ";", "this", ".", ...
Initialize a new `StanzaError`. @param {String} message @param {String} type @param {String} condition @api public
[ "Initialize", "a", "new", "StanzaError", "." ]
28854611428687602506b6aed6d2559878b0d6ea
https://github.com/jaredhanson/junction/blob/28854611428687602506b6aed6d2559878b0d6ea/lib/junction/stanzaerror.js#L14-L21
33,514
jaredhanson/junction
lib/junction/index.js
create
function create() { function app(stanza) { app.handle(stanza); } utils.merge(app, application); app._stack = []; app._filters = []; for (var i = 0; i < arguments.length; ++i) { app.use(arguments[i]); } return app; }
javascript
function create() { function app(stanza) { app.handle(stanza); } utils.merge(app, application); app._stack = []; app._filters = []; for (var i = 0; i < arguments.length; ++i) { app.use(arguments[i]); } return app; }
[ "function", "create", "(", ")", "{", "function", "app", "(", "stanza", ")", "{", "app", ".", "handle", "(", "stanza", ")", ";", "}", "utils", ".", "merge", "(", "app", ",", "application", ")", ";", "app", ".", "_stack", "=", "[", "]", ";", "app",...
Create a Junction application. @return {Function} @api public
[ "Create", "a", "Junction", "application", "." ]
28854611428687602506b6aed6d2559878b0d6ea
https://github.com/jaredhanson/junction/blob/28854611428687602506b6aed6d2559878b0d6ea/lib/junction/index.js#L28-L37
33,515
openchain/openchain-js
lib/transactionbuilder.js
TransactionBuilder
function TransactionBuilder(apiClient) { if (typeof apiClient.namespace === "undefined" || apiClient.namespace === null) { throw new Error("The API client has not been initialized"); } this.client = apiClient; this.records = []; this.keys = []; this.metadata = ByteBuffer.fromHex(""); }
javascript
function TransactionBuilder(apiClient) { if (typeof apiClient.namespace === "undefined" || apiClient.namespace === null) { throw new Error("The API client has not been initialized"); } this.client = apiClient; this.records = []; this.keys = []; this.metadata = ByteBuffer.fromHex(""); }
[ "function", "TransactionBuilder", "(", "apiClient", ")", "{", "if", "(", "typeof", "apiClient", ".", "namespace", "===", "\"undefined\"", "||", "apiClient", ".", "namespace", "===", "null", ")", "{", "throw", "new", "Error", "(", "\"The API client has not been ini...
Provides the ability to build an Openchain mutation. @constructor @param {!ApiClient} apiClient The API client representing the endpoint on which the mutation should be submitted.
[ "Provides", "the", "ability", "to", "build", "an", "Openchain", "mutation", "." ]
41ae72504a29ba3067236f489e5117a4bda8d9d6
https://github.com/openchain/openchain-js/blob/41ae72504a29ba3067236f489e5117a4bda8d9d6/lib/transactionbuilder.js#L28-L38
33,516
openchain/openchain-js
lib/recordkey.js
RecordKey
function RecordKey(path, recordType, name) { this.path = LedgerPath.parse(path); this.recordType = recordType; this.name = name; }
javascript
function RecordKey(path, recordType, name) { this.path = LedgerPath.parse(path); this.recordType = recordType; this.name = name; }
[ "function", "RecordKey", "(", "path", ",", "recordType", ",", "name", ")", "{", "this", ".", "path", "=", "LedgerPath", ".", "parse", "(", "path", ")", ";", "this", ".", "recordType", "=", "recordType", ";", "this", ".", "name", "=", "name", ";", "}"...
Represents the key to a record. @constructor @param {string} path The path of the record. @param {string} recordType The type of the record. @param {string} name The name of the record.
[ "Represents", "the", "key", "to", "a", "record", "." ]
41ae72504a29ba3067236f489e5117a4bda8d9d6
https://github.com/openchain/openchain-js/blob/41ae72504a29ba3067236f489e5117a4bda8d9d6/lib/recordkey.js#L29-L33
33,517
jaredhanson/junction
lib/junction/middleware/pending.js
pending
function pending(options) { options = options || {}; var store = options.store; var autoRemove = (typeof options.autoRemove === 'undefined') ? true : options.autoRemove; if (!store) throw new Error('pending middleware requires a store'); return function pending(stanza, next) { if (!stanza.id || !(stanza.type == 'result' || stanza.type == 'error')) { return next(); } var key = stanza.from + ':' + stanza.id; store.get(key, function(err, data) { if (err) { next(err); } else if (!data) { next(); } else { stanza.irt = stanza.inReplyTo = stanza.inResponseTo = stanza.regarding = data; if (autoRemove) { store.remove(key); } next(); } }); } }
javascript
function pending(options) { options = options || {}; var store = options.store; var autoRemove = (typeof options.autoRemove === 'undefined') ? true : options.autoRemove; if (!store) throw new Error('pending middleware requires a store'); return function pending(stanza, next) { if (!stanza.id || !(stanza.type == 'result' || stanza.type == 'error')) { return next(); } var key = stanza.from + ':' + stanza.id; store.get(key, function(err, data) { if (err) { next(err); } else if (!data) { next(); } else { stanza.irt = stanza.inReplyTo = stanza.inResponseTo = stanza.regarding = data; if (autoRemove) { store.remove(key); } next(); } }); } }
[ "function", "pending", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "store", "=", "options", ".", "store", ";", "var", "autoRemove", "=", "(", "typeof", "options", ".", "autoRemove", "===", "'undefined'", ")", "?", "...
Setup pending store with the given `options`. This middleware processes incoming response stanzas, restoring any pending data set when the corresponding request was sent. Pending data is typically set by applying `filter()`'s to the connection. The pending data can be accessed via the `stanza.irt` property, also aliased to `stanza.inReplyTo`, `stanza.inResponseTo` and `stanza.regarding`. Data is (generally) serialized as JSON by the store. This allows a stateless, shared-nothing architecture to be utilized in XMPP-based systems. This is particularly advantageous in systems employing XMPP component connections with round-robin load balancing strategies. In such a scenario, requests can be sent via one component instance, while the result can be received and processed by an entirely separate component instance. Options: - `store` pending store instance - `autoRemove` automatically remove data when the response is received. Defaults to `true` Examples: connection.use(junction.pending({ store: new junction.pending.MemoryStore() })); var store = new junction.pending.MemoryStore(); connection.filter(disco.filters.infoQuery()); connection.filter(junction.filters.pending({ store: store })); connection.use(junction.pending({ store: store })); connection.use(function(stanza, next) { if (stanza.inResponseTo) { console.log('response received!'); return; } next(); }); @param {Object} options @return {Function} @api public
[ "Setup", "pending", "store", "with", "the", "given", "options", "." ]
28854611428687602506b6aed6d2559878b0d6ea
https://github.com/jaredhanson/junction/blob/28854611428687602506b6aed6d2559878b0d6ea/lib/junction/middleware/pending.js#L55-L83
33,518
shama/grunt-gulp
Gruntfile.js
function() { var dest = gulp.dest('tmp/'); dest.on('end', function() { grunt.log.ok('Created tmp/fn.js'); }); return gulp.src('test/fixtures/*.coffee') .pipe(coffee()) .pipe(concat('fn.js')) .pipe(dest); }
javascript
function() { var dest = gulp.dest('tmp/'); dest.on('end', function() { grunt.log.ok('Created tmp/fn.js'); }); return gulp.src('test/fixtures/*.coffee') .pipe(coffee()) .pipe(concat('fn.js')) .pipe(dest); }
[ "function", "(", ")", "{", "var", "dest", "=", "gulp", ".", "dest", "(", "'tmp/'", ")", ";", "dest", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "grunt", ".", "log", ".", "ok", "(", "'Created tmp/fn.js'", ")", ";", "}", ")", ";", "...
Or bypass everything while still integrating gulp
[ "Or", "bypass", "everything", "while", "still", "integrating", "gulp" ]
172312d45a96d4d3023271ede4d16606524bfe67
https://github.com/shama/grunt-gulp/blob/172312d45a96d4d3023271ede4d16606524bfe67/Gruntfile.js#L34-L43
33,519
reederz/node-red-contrib-coap
coap/coap-in.js
CoapServerNode
function CoapServerNode(n) { // Create a RED node RED.nodes.createNode(this,n); var node = this; // Store local copies of the node configuration (as defined in the .html) node.options = {}; node.options.name = n.name; node.options.port = n.port; node._inputNodes = []; // collection of "coap in" nodes that represent coap resources // Setup node-coap server and start node.server = new coap.createServer(); node.server.on('request', function(req, res) { node.handleRequest(req, res); res.on('error', function(err) { node.log('server error'); node.log(err); }); }); node.server.listen(node.options.port, function() { //console.log('server started'); node.log('CoAP Server Started'); }); node.on("close", function() { node._inputNodes = []; node.server.close(); }); }
javascript
function CoapServerNode(n) { // Create a RED node RED.nodes.createNode(this,n); var node = this; // Store local copies of the node configuration (as defined in the .html) node.options = {}; node.options.name = n.name; node.options.port = n.port; node._inputNodes = []; // collection of "coap in" nodes that represent coap resources // Setup node-coap server and start node.server = new coap.createServer(); node.server.on('request', function(req, res) { node.handleRequest(req, res); res.on('error', function(err) { node.log('server error'); node.log(err); }); }); node.server.listen(node.options.port, function() { //console.log('server started'); node.log('CoAP Server Started'); }); node.on("close", function() { node._inputNodes = []; node.server.close(); }); }
[ "function", "CoapServerNode", "(", "n", ")", "{", "// Create a RED node", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "var", "node", "=", "this", ";", "// Store local copies of the node configuration (as defined in the .html)", "node", "...
A node red node that sets up a local coap server
[ "A", "node", "red", "node", "that", "sets", "up", "a", "local", "coap", "server" ]
b9335b4ccb3bad42d889db2ee4897f55607a9e2e
https://github.com/reederz/node-red-contrib-coap/blob/b9335b4ccb3bad42d889db2ee4897f55607a9e2e/coap/coap-in.js#L6-L36
33,520
particle-iot/spark-protocol
js/lib/Messages.js
function (showSignal) { return function (msg) { var b = new Buffer(1); b.writeUInt8(showSignal ? 1 : 0, 0); msg.addOption(new Option(Message.Option.URI_PATH, new Buffer("s"))); msg.addOption(new Option(Message.Option.URI_QUERY, b)); return msg; }; }
javascript
function (showSignal) { return function (msg) { var b = new Buffer(1); b.writeUInt8(showSignal ? 1 : 0, 0); msg.addOption(new Option(Message.Option.URI_PATH, new Buffer("s"))); msg.addOption(new Option(Message.Option.URI_QUERY, b)); return msg; }; }
[ "function", "(", "showSignal", ")", "{", "return", "function", "(", "msg", ")", "{", "var", "b", "=", "new", "Buffer", "(", "1", ")", ";", "b", ".", "writeUInt8", "(", "showSignal", "?", "1", ":", "0", ",", "0", ")", ";", "msg", ".", "addOption",...
does the special URL writing needed directly to the COAP message object, since the URI requires non-text values @param showSignal @returns {Function}
[ "does", "the", "special", "URL", "writing", "needed", "directly", "to", "the", "COAP", "message", "object", "since", "the", "URI", "requires", "non", "-", "text", "values" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/Messages.js#L109-L118
33,521
stream-utils/pause
index.js
pause
function pause (stream) { var events = [] var onData = createEventListener('data', events) var onEnd = createEventListener('end', events) // buffer data stream.on('data', onData) // buffer end stream.on('end', onEnd) return { end: function end () { stream.removeListener('data', onData) stream.removeListener('end', onEnd) }, resume: function resume () { this.end() for (var i = 0; i < events.length; i++) { stream.emit.apply(stream, events[i]) } } } }
javascript
function pause (stream) { var events = [] var onData = createEventListener('data', events) var onEnd = createEventListener('end', events) // buffer data stream.on('data', onData) // buffer end stream.on('end', onEnd) return { end: function end () { stream.removeListener('data', onData) stream.removeListener('end', onEnd) }, resume: function resume () { this.end() for (var i = 0; i < events.length; i++) { stream.emit.apply(stream, events[i]) } } } }
[ "function", "pause", "(", "stream", ")", "{", "var", "events", "=", "[", "]", "var", "onData", "=", "createEventListener", "(", "'data'", ",", "events", ")", "var", "onEnd", "=", "createEventListener", "(", "'end'", ",", "events", ")", "// buffer data", "s...
Pause the data events on a stream. @param {object} stream @public
[ "Pause", "the", "data", "events", "on", "a", "stream", "." ]
d0b5b118988784466f44e4610868ae84f0372489
https://github.com/stream-utils/pause/blob/d0b5b118988784466f44e4610868ae84f0372489/index.js#L24-L48
33,522
particle-iot/spark-protocol
js/lib/Handshake.js
function (data) { var that = this; if (!data) { if (this._socketTimeout) { clearTimeout(this._socketTimeout); //just in case } //waiting on data. //logger.log("server: waiting on hello"); this._socketTimeout = setTimeout(function () { that.handshakeFail("get_hello timed out"); }, 30 * 1000); return; } clearTimeout(this._socketTimeout); var env = this.client.parseMessage(data); var msg = (env && env.hello) ? env.hello : env; if (!msg) { this.handshakeFail("failed to parse hello"); return; } this.client.recvCounter = msg.getId(); //logger.log("server: got a good hello! Counter was: " + msg.getId()); try { if (msg.getPayload) { var payload = msg.getPayload(); if (payload.length > 0) { var r = new buffers.BufferReader(payload); this.client.spark_product_id = r.shiftUInt16(); this.client.product_firmware_version = r.shiftUInt16(); //logger.log('version of core firmware is ', this.client.spark_product_id, this.client.product_firmware_version); } } else { logger.log('msg object had no getPayload fn'); } } catch (ex) { logger.log('error while parsing hello payload ', ex); } // //remind ourselves later that this key worked. // if (that.corePublicKeyWasUncertain) { // process.nextTick(function () { // try { // //set preferred key for device // //that.coreFullPublicKeyObject // } // catch (ex) { // logger.error("error marking key as valid " + ex); // } // }); // } this.stage++; this.nextStep(); }
javascript
function (data) { var that = this; if (!data) { if (this._socketTimeout) { clearTimeout(this._socketTimeout); //just in case } //waiting on data. //logger.log("server: waiting on hello"); this._socketTimeout = setTimeout(function () { that.handshakeFail("get_hello timed out"); }, 30 * 1000); return; } clearTimeout(this._socketTimeout); var env = this.client.parseMessage(data); var msg = (env && env.hello) ? env.hello : env; if (!msg) { this.handshakeFail("failed to parse hello"); return; } this.client.recvCounter = msg.getId(); //logger.log("server: got a good hello! Counter was: " + msg.getId()); try { if (msg.getPayload) { var payload = msg.getPayload(); if (payload.length > 0) { var r = new buffers.BufferReader(payload); this.client.spark_product_id = r.shiftUInt16(); this.client.product_firmware_version = r.shiftUInt16(); //logger.log('version of core firmware is ', this.client.spark_product_id, this.client.product_firmware_version); } } else { logger.log('msg object had no getPayload fn'); } } catch (ex) { logger.log('error while parsing hello payload ', ex); } // //remind ourselves later that this key worked. // if (that.corePublicKeyWasUncertain) { // process.nextTick(function () { // try { // //set preferred key for device // //that.coreFullPublicKeyObject // } // catch (ex) { // logger.error("error marking key as valid " + ex); // } // }); // } this.stage++; this.nextStep(); }
[ "function", "(", "data", ")", "{", "var", "that", "=", "this", ";", "if", "(", "!", "data", ")", "{", "if", "(", "this", ".", "_socketTimeout", ")", "{", "clearTimeout", "(", "this", ".", "_socketTimeout", ")", ";", "//just in case", "}", "//waiting on...
receive a hello from the client, taking note of the counter
[ "receive", "a", "hello", "from", "the", "client", "taking", "note", "of", "the", "counter" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/Handshake.js#L501-L561
33,523
particle-iot/spark-protocol
js/lib/Handshake.js
function () { //client will set the counter property on the message //logger.log("server: send hello"); this.client.secureOut = this.secureOut; this.client.sendCounter = CryptoLib.getRandomUINT16(); this.client.sendMessage("Hello", {}, null, null); this.stage++; this.nextStep(); }
javascript
function () { //client will set the counter property on the message //logger.log("server: send hello"); this.client.secureOut = this.secureOut; this.client.sendCounter = CryptoLib.getRandomUINT16(); this.client.sendMessage("Hello", {}, null, null); this.stage++; this.nextStep(); }
[ "function", "(", ")", "{", "//client will set the counter property on the message", "//logger.log(\"server: send hello\");", "this", ".", "client", ".", "secureOut", "=", "this", ".", "secureOut", ";", "this", ".", "client", ".", "sendCounter", "=", "CryptoLib", ".", ...
send a hello to the client, with our new random counter
[ "send", "a", "hello", "to", "the", "client", "with", "our", "new", "random", "counter" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/Handshake.js#L566-L575
33,524
particle-iot/spark-protocol
js/clients/SparkCore.js
function () { var that = this; this.socket.setNoDelay(true); this.socket.setKeepAlive(true, 15 * 1000); //every 15 second(s) this.socket.on('error', function (err) { that.disconnect("socket error " + err); }); this.socket.on('close', function (err) { that.disconnect("socket close " + err); }); this.socket.on('timeout', function (err) { that.disconnect("socket timeout " + err); }); this.handshake(); }
javascript
function () { var that = this; this.socket.setNoDelay(true); this.socket.setKeepAlive(true, 15 * 1000); //every 15 second(s) this.socket.on('error', function (err) { that.disconnect("socket error " + err); }); this.socket.on('close', function (err) { that.disconnect("socket close " + err); }); this.socket.on('timeout', function (err) { that.disconnect("socket timeout " + err); }); this.handshake(); }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "this", ".", "socket", ".", "setNoDelay", "(", "true", ")", ";", "this", ".", "socket", ".", "setKeepAlive", "(", "true", ",", "15", "*", "1000", ")", ";", "//every 15 second(s)", "this", "....
configure our socket and start the handshake
[ "configure", "our", "socket", "and", "start", "the", "handshake" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L106-L118
33,525
particle-iot/spark-protocol
js/clients/SparkCore.js
function (data) { var msg = messages.unwrap(data); if (!msg) { logger.error("routeMessage got a NULL coap message ", { coreID: this.getHexCoreID() }); return; } this._lastMessageTime = new Date(); //should be adequate var msgCode = msg.getCode(); if ((msgCode > Message.Code.EMPTY) && (msgCode <= Message.Code.DELETE)) { //probably a request msg._type = messages.getRequestType(msg); } if (!msg._type) { msg._type = this.getResponseType(msg.getTokenString()); } //console.log("core got message of type " + msg._type + " with token " + msg.getTokenString() + " " + messages.getRequestType(msg)); if (msg.isAcknowledgement()) { if (!msg._type) { //no type, can't route it. msg._type = 'PingAck'; } this.emit(('msg_' + msg._type).toLowerCase(), msg); return; } var nextPeerCounter = ++this.recvCounter; if (nextPeerCounter > 65535) { //TODO: clean me up! (I need settings, and maybe belong elsewhere) this.recvCounter = nextPeerCounter = 0; } if (msg.isEmpty() && msg.isConfirmable()) { this._lastCorePing = new Date(); //var delta = (this._lastCorePing - this._connStartTime) / 1000.0; //logger.log("core ping @ ", delta, " seconds ", { coreID: this.getHexCoreID() }); this.sendReply("PingAck", msg.getId()); return; } if (!msg || (msg.getId() != nextPeerCounter)) { logger.log("got counter ", msg.getId(), " expecting ", nextPeerCounter, { coreID: this.getHexCoreID() }); if (msg._type == "Ignored") { //don't ignore an ignore... this.disconnect("Got an Ignore"); return; } //this.sendMessage("Ignored", null, {}, null, null); this.disconnect("Bad Counter"); return; } this.emit(('msg_' + msg._type).toLowerCase(), msg); }
javascript
function (data) { var msg = messages.unwrap(data); if (!msg) { logger.error("routeMessage got a NULL coap message ", { coreID: this.getHexCoreID() }); return; } this._lastMessageTime = new Date(); //should be adequate var msgCode = msg.getCode(); if ((msgCode > Message.Code.EMPTY) && (msgCode <= Message.Code.DELETE)) { //probably a request msg._type = messages.getRequestType(msg); } if (!msg._type) { msg._type = this.getResponseType(msg.getTokenString()); } //console.log("core got message of type " + msg._type + " with token " + msg.getTokenString() + " " + messages.getRequestType(msg)); if (msg.isAcknowledgement()) { if (!msg._type) { //no type, can't route it. msg._type = 'PingAck'; } this.emit(('msg_' + msg._type).toLowerCase(), msg); return; } var nextPeerCounter = ++this.recvCounter; if (nextPeerCounter > 65535) { //TODO: clean me up! (I need settings, and maybe belong elsewhere) this.recvCounter = nextPeerCounter = 0; } if (msg.isEmpty() && msg.isConfirmable()) { this._lastCorePing = new Date(); //var delta = (this._lastCorePing - this._connStartTime) / 1000.0; //logger.log("core ping @ ", delta, " seconds ", { coreID: this.getHexCoreID() }); this.sendReply("PingAck", msg.getId()); return; } if (!msg || (msg.getId() != nextPeerCounter)) { logger.log("got counter ", msg.getId(), " expecting ", nextPeerCounter, { coreID: this.getHexCoreID() }); if (msg._type == "Ignored") { //don't ignore an ignore... this.disconnect("Got an Ignore"); return; } //this.sendMessage("Ignored", null, {}, null, null); this.disconnect("Bad Counter"); return; } this.emit(('msg_' + msg._type).toLowerCase(), msg); }
[ "function", "(", "data", ")", "{", "var", "msg", "=", "messages", ".", "unwrap", "(", "data", ")", ";", "if", "(", "!", "msg", ")", "{", "logger", ".", "error", "(", "\"routeMessage got a NULL coap message \"", ",", "{", "coreID", ":", "this", ".", "ge...
Deals with messages coming from the core over our secure connection @param data
[ "Deals", "with", "messages", "coming", "from", "the", "core", "over", "our", "secure", "connection" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L340-L401
33,526
particle-iot/spark-protocol
js/clients/SparkCore.js
function (name, uri, token, callback, once) { var tokenHex = (token) ? utilities.toHexString(token) : null; var beVerbose = settings.showVerboseCoreLogs; //TODO: failWatch? What kind of timeout do we want here? //adds a one time event var that = this, evtName = ('msg_' + name).toLowerCase(), handler = function (msg) { if (uri && (msg.getUriPath().indexOf(uri) != 0)) { if (beVerbose) { logger.log("uri filter did not match", uri, msg.getUriPath(), { coreID: that.getHexCoreID() }); } return; } if (tokenHex && (tokenHex != msg.getTokenString())) { if (beVerbose) { logger.log("Tokens did not match ", tokenHex, msg.getTokenString(), { coreID: that.getHexCoreID() }); } return; } if (once) { that.removeListener(evtName, handler); } process.nextTick(function () { try { if (beVerbose) { logger.log('heard ', name, { coreID: that.coreID }); } callback(msg); } catch (ex) { logger.error("listenFor - caught error: ", ex, ex.stack, { coreID: that.getHexCoreID() }); } }); }; //logger.log('listening for ', evtName); this.on(evtName, handler); return handler; }
javascript
function (name, uri, token, callback, once) { var tokenHex = (token) ? utilities.toHexString(token) : null; var beVerbose = settings.showVerboseCoreLogs; //TODO: failWatch? What kind of timeout do we want here? //adds a one time event var that = this, evtName = ('msg_' + name).toLowerCase(), handler = function (msg) { if (uri && (msg.getUriPath().indexOf(uri) != 0)) { if (beVerbose) { logger.log("uri filter did not match", uri, msg.getUriPath(), { coreID: that.getHexCoreID() }); } return; } if (tokenHex && (tokenHex != msg.getTokenString())) { if (beVerbose) { logger.log("Tokens did not match ", tokenHex, msg.getTokenString(), { coreID: that.getHexCoreID() }); } return; } if (once) { that.removeListener(evtName, handler); } process.nextTick(function () { try { if (beVerbose) { logger.log('heard ', name, { coreID: that.coreID }); } callback(msg); } catch (ex) { logger.error("listenFor - caught error: ", ex, ex.stack, { coreID: that.getHexCoreID() }); } }); }; //logger.log('listening for ', evtName); this.on(evtName, handler); return handler; }
[ "function", "(", "name", ",", "uri", ",", "token", ",", "callback", ",", "once", ")", "{", "var", "tokenHex", "=", "(", "token", ")", "?", "utilities", ".", "toHexString", "(", "token", ")", ":", "null", ";", "var", "beVerbose", "=", "settings", ".",...
Adds a listener to our secure message stream @param name the message type we're waiting on @param uri - a particular function / variable? @param token - what message does this go with? (should come from sendMessage) @param callback what we should call when we're done @param [once] whether or not we should keep the listener after we've had a match
[ "Adds", "a", "listener", "to", "our", "secure", "message", "stream" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L489-L535
33,527
particle-iot/spark-protocol
js/clients/SparkCore.js
function (name, type, callback) { var that = this; var performRequest = function () { if (!that.HasSparkVariable(name)) { callback(null, null, "Variable not found"); return; } var token = this.sendMessage("VariableRequest", { name: name }); var varTransformer = this.transformVariableGenerator(name, callback); this.listenFor("VariableValue", null, token, varTransformer, true); }.bind(this); if (this.hasFnState()) { //slight short-circuit, saves ~5 seconds every 100,000 requests... performRequest(); } else { when(this.ensureWeHaveIntrospectionData()) .then( performRequest, function (err) { callback(null, null, "Problem requesting variable: " + err); }); } }
javascript
function (name, type, callback) { var that = this; var performRequest = function () { if (!that.HasSparkVariable(name)) { callback(null, null, "Variable not found"); return; } var token = this.sendMessage("VariableRequest", { name: name }); var varTransformer = this.transformVariableGenerator(name, callback); this.listenFor("VariableValue", null, token, varTransformer, true); }.bind(this); if (this.hasFnState()) { //slight short-circuit, saves ~5 seconds every 100,000 requests... performRequest(); } else { when(this.ensureWeHaveIntrospectionData()) .then( performRequest, function (err) { callback(null, null, "Problem requesting variable: " + err); }); } }
[ "function", "(", "name", ",", "type", ",", "callback", ")", "{", "var", "that", "=", "this", ";", "var", "performRequest", "=", "function", "(", ")", "{", "if", "(", "!", "that", ".", "HasSparkVariable", "(", "name", ")", ")", "{", "callback", "(", ...
Ensures we have introspection data from the core, and then requests a variable value to be sent, when received it transforms the response into the appropriate type @param name @param type @param callback - expects (value, buf, err)
[ "Ensures", "we", "have", "introspection", "data", "from", "the", "core", "and", "then", "requests", "a", "variable", "value", "to", "be", "sent", "when", "received", "it", "transforms", "the", "response", "into", "the", "appropriate", "type" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L607-L631
33,528
particle-iot/spark-protocol
js/clients/SparkCore.js
function (showSignal, callback) { var timer = setTimeout(function () { callback(false); }, 30 * 1000); //TODO: that.stopListeningFor("RaiseYourHandReturn", listenHandler); //TODO: var listenHandler = this.listenFor("RaiseYourHandReturn", ... ); //logger.log("RaiseYourHand: asking core to signal? " + showSignal); var token = this.sendMessage("RaiseYourHand", { _writeCoapUri: messages.raiseYourHandUrlGenerator(showSignal) }, null); this.listenFor("RaiseYourHandReturn", null, token, function () { clearTimeout(timer); callback(true); }, true); }
javascript
function (showSignal, callback) { var timer = setTimeout(function () { callback(false); }, 30 * 1000); //TODO: that.stopListeningFor("RaiseYourHandReturn", listenHandler); //TODO: var listenHandler = this.listenFor("RaiseYourHandReturn", ... ); //logger.log("RaiseYourHand: asking core to signal? " + showSignal); var token = this.sendMessage("RaiseYourHand", { _writeCoapUri: messages.raiseYourHandUrlGenerator(showSignal) }, null); this.listenFor("RaiseYourHandReturn", null, token, function () { clearTimeout(timer); callback(true); }, true); }
[ "function", "(", "showSignal", ",", "callback", ")", "{", "var", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "callback", "(", "false", ")", ";", "}", ",", "30", "*", "1000", ")", ";", "//TODO: that.stopListeningFor(\"RaiseYourHandReturn\", list...
Asks the core to start or stop its "raise your hand" signal @param showSignal - whether it should show the signal or not @param callback - what to call when we're done or timed out...
[ "Asks", "the", "core", "to", "start", "or", "stop", "its", "raise", "your", "hand", "signal" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L679-L692
33,529
particle-iot/spark-protocol
js/clients/SparkCore.js
function (name, args) { var ready = when.defer(); var that = this; when(this.ensureWeHaveIntrospectionData()).then( function () { var buf = that._transformArguments(name, args); if (buf) { ready.resolve(buf); } else { //NOTE! The API looks for "Unknown Function" in the error response. ready.reject("Unknown Function: " + name); } }, function (msg) { ready.reject(msg); } ); return ready.promise; }
javascript
function (name, args) { var ready = when.defer(); var that = this; when(this.ensureWeHaveIntrospectionData()).then( function () { var buf = that._transformArguments(name, args); if (buf) { ready.resolve(buf); } else { //NOTE! The API looks for "Unknown Function" in the error response. ready.reject("Unknown Function: " + name); } }, function (msg) { ready.reject(msg); } ); return ready.promise; }
[ "function", "(", "name", ",", "args", ")", "{", "var", "ready", "=", "when", ".", "defer", "(", ")", ";", "var", "that", "=", "this", ";", "when", "(", "this", ".", "ensureWeHaveIntrospectionData", "(", ")", ")", ".", "then", "(", "function", "(", ...
makes sure we have our introspection data, then transforms our object into the right coap query string @param name @param args @returns {*}
[ "makes", "sure", "we", "have", "our", "introspection", "data", "then", "transforms", "our", "object", "into", "the", "right", "coap", "query", "string" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L779-L800
33,530
particle-iot/spark-protocol
js/clients/SparkCore.js
function (name, msg, callback) { var varType = "int32"; //if the core doesn't specify, assume it's a "uint32" //var fnState = (this.coreFnState) ? this.coreFnState.f : null; //if (fnState && fnState[name] && fnState[name].returns) { // varType = fnState[name].returns; //} var niceResult = null; try { if (msg && msg.getPayload) { niceResult = messages.FromBinary(msg.getPayload(), varType); } } catch (ex) { logger.error("transformFunctionResult - error transforming response " + ex); } process.nextTick(function () { try { callback(niceResult); } catch (ex) { logger.error("transformFunctionResult - error in callback " + ex); } }); return null; }
javascript
function (name, msg, callback) { var varType = "int32"; //if the core doesn't specify, assume it's a "uint32" //var fnState = (this.coreFnState) ? this.coreFnState.f : null; //if (fnState && fnState[name] && fnState[name].returns) { // varType = fnState[name].returns; //} var niceResult = null; try { if (msg && msg.getPayload) { niceResult = messages.FromBinary(msg.getPayload(), varType); } } catch (ex) { logger.error("transformFunctionResult - error transforming response " + ex); } process.nextTick(function () { try { callback(niceResult); } catch (ex) { logger.error("transformFunctionResult - error in callback " + ex); } }); return null; }
[ "function", "(", "name", ",", "msg", ",", "callback", ")", "{", "var", "varType", "=", "\"int32\"", ";", "//if the core doesn't specify, assume it's a \"uint32\"", "//var fnState = (this.coreFnState) ? this.coreFnState.f : null;", "//if (fnState && fnState[name] && fnState[name].retu...
Transforms the result from a core function to the correct type. @param name @param msg @param callback @returns {null}
[ "Transforms", "the", "result", "from", "a", "core", "function", "to", "the", "correct", "type", "." ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L869-L896
33,531
particle-iot/spark-protocol
js/clients/SparkCore.js
function (name, args) { //logger.log('transform args', { coreID: this.getHexCoreID() }); if (!args) { return null; } if (!this.hasFnState()) { logger.error("_transformArguments called without any function state!", { coreID: this.getHexCoreID() }); return null; } //TODO: lowercase function keys on new state format name = name.toLowerCase(); var fn = this.coreFnState[name]; if (!fn || !fn.args) { //maybe it's the old protocol? var f = this.coreFnState.f; if (f && utilities.arrayContainsLower(f, name)) { //logger.log("_transformArguments - using old format", { coreID: this.getHexCoreID() }); //current / simplified function format (one string arg, int return type) fn = { returns: "int", args: [ [null, "string" ] ] }; } } if (!fn || !fn.args) { //logger.error("_transformArguments: core doesn't know fn: ", { coreID: this.getHexCoreID(), name: name, state: this.coreFnState }); return null; } // "HelloWorld": { returns: "string", args: [ {"name": "string"}, {"adjective": "string"} ]} }; return messages.buildArguments(args, fn.args); }
javascript
function (name, args) { //logger.log('transform args', { coreID: this.getHexCoreID() }); if (!args) { return null; } if (!this.hasFnState()) { logger.error("_transformArguments called without any function state!", { coreID: this.getHexCoreID() }); return null; } //TODO: lowercase function keys on new state format name = name.toLowerCase(); var fn = this.coreFnState[name]; if (!fn || !fn.args) { //maybe it's the old protocol? var f = this.coreFnState.f; if (f && utilities.arrayContainsLower(f, name)) { //logger.log("_transformArguments - using old format", { coreID: this.getHexCoreID() }); //current / simplified function format (one string arg, int return type) fn = { returns: "int", args: [ [null, "string" ] ] }; } } if (!fn || !fn.args) { //logger.error("_transformArguments: core doesn't know fn: ", { coreID: this.getHexCoreID(), name: name, state: this.coreFnState }); return null; } // "HelloWorld": { returns: "string", args: [ {"name": "string"}, {"adjective": "string"} ]} }; return messages.buildArguments(args, fn.args); }
[ "function", "(", "name", ",", "args", ")", "{", "//logger.log('transform args', { coreID: this.getHexCoreID() });", "if", "(", "!", "args", ")", "{", "return", "null", ";", "}", "if", "(", "!", "this", ".", "hasFnState", "(", ")", ")", "{", "logger", ".", ...
transforms our object into a nice coap query string @param name @param args @private
[ "transforms", "our", "object", "into", "a", "nice", "coap", "query", "string" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L904-L940
33,532
particle-iot/spark-protocol
js/clients/SparkCore.js
function () { if (this.hasFnState()) { return when.resolve(); } //if we don't have a message pending, send one. if (!this._describeDfd) { this.sendMessage("Describe"); this._describeDfd = when.defer(); } //let everybody else queue up on this promise return this._describeDfd.promise; }
javascript
function () { if (this.hasFnState()) { return when.resolve(); } //if we don't have a message pending, send one. if (!this._describeDfd) { this.sendMessage("Describe"); this._describeDfd = when.defer(); } //let everybody else queue up on this promise return this._describeDfd.promise; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "hasFnState", "(", ")", ")", "{", "return", "when", ".", "resolve", "(", ")", ";", "}", "//if we don't have a message pending, send one.", "if", "(", "!", "this", ".", "_describeDfd", ")", "{", "this", "...
Checks our cache to see if we have the function state, otherwise requests it from the core, listens for it, and resolves our deferred on success @returns {*}
[ "Checks", "our", "cache", "to", "see", "if", "we", "have", "the", "function", "state", "otherwise", "requests", "it", "from", "the", "core", "listens", "for", "it", "and", "resolves", "our", "deferred", "on", "success" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L947-L960
33,533
particle-iot/spark-protocol
js/clients/SparkCore.js
function(msg) { //got a description, is it any good? var loaded = (this.loadFnState(msg.getPayload())); if (this._describeDfd) { if (loaded) { this._describeDfd.resolve(); } else { this._describeDfd.reject("something went wrong parsing function state") } } //else { //hmm, unsolicited response, that's okay. } }
javascript
function(msg) { //got a description, is it any good? var loaded = (this.loadFnState(msg.getPayload())); if (this._describeDfd) { if (loaded) { this._describeDfd.resolve(); } else { this._describeDfd.reject("something went wrong parsing function state") } } //else { //hmm, unsolicited response, that's okay. } }
[ "function", "(", "msg", ")", "{", "//got a description, is it any good?", "var", "loaded", "=", "(", "this", ".", "loadFnState", "(", "msg", ".", "getPayload", "(", ")", ")", ")", ";", "if", "(", "this", ".", "_describeDfd", ")", "{", "if", "(", "loaded"...
On any describe return back from the core @param msg
[ "On", "any", "describe", "return", "back", "from", "the", "core" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L967-L980
33,534
particle-iot/spark-protocol
js/clients/SparkCore.js
function(msg) { //moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch). var stamp = moment().utc().unix(); var binVal = messages.ToBinary(stamp, "uint32"); this.sendReply("GetTimeReturn", msg.getId(), binVal, msg.getToken()); }
javascript
function(msg) { //moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch). var stamp = moment().utc().unix(); var binVal = messages.ToBinary(stamp, "uint32"); this.sendReply("GetTimeReturn", msg.getId(), binVal, msg.getToken()); }
[ "function", "(", "msg", ")", "{", "//moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch).", "var", "stamp", "=", "moment", "(", ")", ".", "utc", "(", ")", ".", "unix", "(", ")", ";", "var", "binVal", "=", "messages", ".", "ToBinary", ...
The core asked us for the time! @param msg
[ "The", "core", "asked", "us", "for", "the", "time!" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L1070-L1077
33,535
particle-iot/spark-protocol
js/clients/SparkCore.js
function (isPublic, name, data, ttl, published_at, coreid) { var rawFn = function (msg) { try { msg.setMaxAge(parseInt((ttl && (ttl >= 0)) ? ttl : 60)); if (published_at) { msg.setTimestamp(moment(published_at).toDate()); } } catch (ex) { logger.error("onCoreHeard - " + ex); } return msg; }; var msgName = (isPublic) ? "PublicEvent" : "PrivateEvent"; var userID = (this.userID || "").toLowerCase() + "/"; name = (name) ? name.toString() : name; if (name && name.indexOf && (name.indexOf(userID) == 0)) { name = name.substring(userID.length); } data = (data) ? data.toString() : data; this.sendNONTypeMessage(msgName, { event_name: name, _raw: rawFn }, data); }
javascript
function (isPublic, name, data, ttl, published_at, coreid) { var rawFn = function (msg) { try { msg.setMaxAge(parseInt((ttl && (ttl >= 0)) ? ttl : 60)); if (published_at) { msg.setTimestamp(moment(published_at).toDate()); } } catch (ex) { logger.error("onCoreHeard - " + ex); } return msg; }; var msgName = (isPublic) ? "PublicEvent" : "PrivateEvent"; var userID = (this.userID || "").toLowerCase() + "/"; name = (name) ? name.toString() : name; if (name && name.indexOf && (name.indexOf(userID) == 0)) { name = name.substring(userID.length); } data = (data) ? data.toString() : data; this.sendNONTypeMessage(msgName, { event_name: name, _raw: rawFn }, data); }
[ "function", "(", "isPublic", ",", "name", ",", "data", ",", "ttl", ",", "published_at", ",", "coreid", ")", "{", "var", "rawFn", "=", "function", "(", "msg", ")", "{", "try", "{", "msg", ".", "setMaxAge", "(", "parseInt", "(", "(", "ttl", "&&", "("...
sends a received event down to a core @param isPublic @param name @param data @param ttl @param published_at
[ "sends", "a", "received", "event", "down", "to", "a", "core" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/clients/SparkCore.js#L1128-L1151
33,536
particle-iot/spark-protocol
js/lib/Flasher.js
function() { if (this._chunkReceivedHandler) { this.client.removeListener("ChunkReceived", this._chunkReceivedHandler); } this._chunkReceivedHandler = null; // logger.log("HERE - _waitForMissedChunks done waiting! ", this.getLogInfo()); this.clearWatch("CompleteTransfer"); this.stage = Flasher.stages.TEARDOWN; this.nextStep(); }
javascript
function() { if (this._chunkReceivedHandler) { this.client.removeListener("ChunkReceived", this._chunkReceivedHandler); } this._chunkReceivedHandler = null; // logger.log("HERE - _waitForMissedChunks done waiting! ", this.getLogInfo()); this.clearWatch("CompleteTransfer"); this.stage = Flasher.stages.TEARDOWN; this.nextStep(); }
[ "function", "(", ")", "{", "if", "(", "this", ".", "_chunkReceivedHandler", ")", "{", "this", ".", "client", ".", "removeListener", "(", "\"ChunkReceived\"", ",", "this", ".", "_chunkReceivedHandler", ")", ";", "}", "this", ".", "_chunkReceivedHandler", "=", ...
fast ota - done sticking around for missing chunks @private
[ "fast", "ota", "-", "done", "sticking", "around", "for", "missing", "chunks" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/Flasher.js#L498-L510
33,537
particle-iot/spark-protocol
js/lib/Flasher.js
function (name, seconds, callback) { if (!this._timers) { this._timers = {}; } if (!seconds) { clearTimeout(this._timers[name]); delete this._timers[name]; } else { this._timers[name] = setTimeout(function () { //logger.error("Flasher failWatch failed waiting on " + name); if (callback) { callback("failed waiting on " + name); } }, seconds * 1000); } }
javascript
function (name, seconds, callback) { if (!this._timers) { this._timers = {}; } if (!seconds) { clearTimeout(this._timers[name]); delete this._timers[name]; } else { this._timers[name] = setTimeout(function () { //logger.error("Flasher failWatch failed waiting on " + name); if (callback) { callback("failed waiting on " + name); } }, seconds * 1000); } }
[ "function", "(", "name", ",", "seconds", ",", "callback", ")", "{", "if", "(", "!", "this", ".", "_timers", ")", "{", "this", ".", "_timers", "=", "{", "}", ";", "}", "if", "(", "!", "seconds", ")", "{", "clearTimeout", "(", "this", ".", "_timers...
Helper for managing a set of named timers and failure callbacks @param name @param seconds @param callback
[ "Helper", "for", "managing", "a", "set", "of", "named", "timers", "and", "failure", "callbacks" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/Flasher.js#L597-L613
33,538
particle-iot/spark-protocol
js/lib/utilities.js
function (fn, scope) { return function () { try { return fn.apply(scope, arguments); } catch (ex) { logger.error(ex); logger.error(ex.stack); logger.log('error bubbled up ' + ex); } }; }
javascript
function (fn, scope) { return function () { try { return fn.apply(scope, arguments); } catch (ex) { logger.error(ex); logger.error(ex.stack); logger.log('error bubbled up ' + ex); } }; }
[ "function", "(", "fn", ",", "scope", ")", "{", "return", "function", "(", ")", "{", "try", "{", "return", "fn", ".", "apply", "(", "scope", ",", "arguments", ")", ";", "}", "catch", "(", "ex", ")", "{", "logger", ".", "error", "(", "ex", ")", "...
ensures the function in the provided scope @param fn @param scope @returns {Function}
[ "ensures", "the", "function", "in", "the", "provided", "scope" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/utilities.js#L39-L50
33,539
particle-iot/spark-protocol
js/lib/utilities.js
function (left, right) { if (!left && !right) { return true; } var matches = true; for (var prop in right) { if (!right.hasOwnProperty(prop)) { continue; } matches &= (left[prop] == right[prop]); } return matches; }
javascript
function (left, right) { if (!left && !right) { return true; } var matches = true; for (var prop in right) { if (!right.hasOwnProperty(prop)) { continue; } matches &= (left[prop] == right[prop]); } return matches; }
[ "function", "(", "left", ",", "right", ")", "{", "if", "(", "!", "left", "&&", "!", "right", ")", "{", "return", "true", ";", "}", "var", "matches", "=", "true", ";", "for", "(", "var", "prop", "in", "right", ")", "{", "if", "(", "!", "right", ...
Iterates over the properties of the right object, checking to make sure the properties on the left object match. @param left @param right
[ "Iterates", "over", "the", "properties", "of", "the", "right", "object", "checking", "to", "make", "sure", "the", "properties", "on", "the", "left", "object", "match", "." ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/utilities.js#L94-L107
33,540
particle-iot/spark-protocol
js/lib/utilities.js
function (dir, search, excludedDirs) { excludedDirs = excludedDirs || []; var result = []; var files = fs.readdirSync(dir); for (var i = 0; i < files.length; i++) { var fullpath = path.join(dir, files[i]); var stat = fs.statSync(fullpath); if (stat.isDirectory() && (!excludedDirs.contains(fullpath))) { result = result.concat(utilities.recursiveFindFiles(fullpath, search)); } else if (!search || (fullpath.indexOf(search) >= 0)) { result.push(fullpath); } } return result; }
javascript
function (dir, search, excludedDirs) { excludedDirs = excludedDirs || []; var result = []; var files = fs.readdirSync(dir); for (var i = 0; i < files.length; i++) { var fullpath = path.join(dir, files[i]); var stat = fs.statSync(fullpath); if (stat.isDirectory() && (!excludedDirs.contains(fullpath))) { result = result.concat(utilities.recursiveFindFiles(fullpath, search)); } else if (!search || (fullpath.indexOf(search) >= 0)) { result.push(fullpath); } } return result; }
[ "function", "(", "dir", ",", "search", ",", "excludedDirs", ")", "{", "excludedDirs", "=", "excludedDirs", "||", "[", "]", ";", "var", "result", "=", "[", "]", ";", "var", "files", "=", "fs", ".", "readdirSync", "(", "dir", ")", ";", "for", "(", "v...
recursively create a list of all files in a directory and all subdirectories @param dir @param search @returns {Array}
[ "recursively", "create", "a", "list", "of", "all", "files", "in", "a", "directory", "and", "all", "subdirectories" ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/utilities.js#L235-L251
33,541
particle-iot/spark-protocol
js/lib/utilities.js
function (arr, handler) { var tmp = when.defer(); var index = -1; var results = []; var doNext = function () { try { index++; if (index > arr.length) { tmp.resolve(results); } var file = arr[index]; var promise = handler(file); if (promise) { when(promise).then(function (result) { results.push(result); process.nextTick(doNext); }, function () { process.nextTick(doNext); }); // when(promise).ensure(function () { // process.nextTick(doNext); // }); } else { //logger.log('skipping bad promise'); process.nextTick(doNext); } } catch (ex) { logger.error("pdas error: " + ex); } }; process.nextTick(doNext); return tmp.promise; }
javascript
function (arr, handler) { var tmp = when.defer(); var index = -1; var results = []; var doNext = function () { try { index++; if (index > arr.length) { tmp.resolve(results); } var file = arr[index]; var promise = handler(file); if (promise) { when(promise).then(function (result) { results.push(result); process.nextTick(doNext); }, function () { process.nextTick(doNext); }); // when(promise).ensure(function () { // process.nextTick(doNext); // }); } else { //logger.log('skipping bad promise'); process.nextTick(doNext); } } catch (ex) { logger.error("pdas error: " + ex); } }; process.nextTick(doNext); return tmp.promise; }
[ "function", "(", "arr", ",", "handler", ")", "{", "var", "tmp", "=", "when", ".", "defer", "(", ")", ";", "var", "index", "=", "-", "1", ";", "var", "results", "=", "[", "]", ";", "var", "doNext", "=", "function", "(", ")", "{", "try", "{", "...
handle an array of stuff, in order, and don't stop if something fails. @param arr @param handler @returns {promise|*|Function|Promise|when.promise}
[ "handle", "an", "array", "of", "stuff", "in", "order", "and", "don", "t", "stop", "if", "something", "fails", "." ]
2c745e7d12fe1d68c60cdcd7322bd9ab359ea532
https://github.com/particle-iot/spark-protocol/blob/2c745e7d12fe1d68c60cdcd7322bd9ab359ea532/js/lib/utilities.js#L259-L298
33,542
chjj/tiny
lib/tiny.json.js
function(a, b) { var keys = Object.keys(b) , i = 0 , l = keys.length , val; for (; i < l; i++) { val = b[keys[i]]; if (has(a, val)) return true; } return false; }
javascript
function(a, b) { var keys = Object.keys(b) , i = 0 , l = keys.length , val; for (; i < l; i++) { val = b[keys[i]]; if (has(a, val)) return true; } return false; }
[ "function", "(", "a", ",", "b", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "b", ")", ",", "i", "=", "0", ",", "l", "=", "keys", ".", "length", ",", "val", ";", "for", "(", ";", "i", "<", "l", ";", "i", "++", ")", "{", "va...
contains any of...
[ "contains", "any", "of", "..." ]
550c3e1f73e61587cabc1f28eb75f4c2264f138c
https://github.com/chjj/tiny/blob/550c3e1f73e61587cabc1f28eb75f4c2264f138c/lib/tiny.json.js#L1011-L1023
33,543
chjj/tiny
lib/tiny.json.js
function(a, b) { var found = 0 , keys = Object.keys(b) , i = 0 , l = keys.length , val; for (; i < l; i++) { val = b[keys[i]]; if (has(a, val)) found++; } return found === l; }
javascript
function(a, b) { var found = 0 , keys = Object.keys(b) , i = 0 , l = keys.length , val; for (; i < l; i++) { val = b[keys[i]]; if (has(a, val)) found++; } return found === l; }
[ "function", "(", "a", ",", "b", ")", "{", "var", "found", "=", "0", ",", "keys", "=", "Object", ".", "keys", "(", "b", ")", ",", "i", "=", "0", ",", "l", "=", "keys", ".", "length", ",", "val", ";", "for", "(", ";", "i", "<", "l", ";", ...
contains all...
[ "contains", "all", "..." ]
550c3e1f73e61587cabc1f28eb75f4c2264f138c
https://github.com/chjj/tiny/blob/550c3e1f73e61587cabc1f28eb75f4c2264f138c/lib/tiny.json.js#L1029-L1042
33,544
xkxd/gulp-html-partial
gulp-html-partial.js
getAttributes
function getAttributes(tag) { let running = true; const attributes = []; const regexp = /(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/g; while (running) { const match = regexp.exec(tag); if (match) { attributes.push({ key: match[1], value: match[2] }) } else { running = false; } } return attributes; }
javascript
function getAttributes(tag) { let running = true; const attributes = []; const regexp = /(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/g; while (running) { const match = regexp.exec(tag); if (match) { attributes.push({ key: match[1], value: match[2] }) } else { running = false; } } return attributes; }
[ "function", "getAttributes", "(", "tag", ")", "{", "let", "running", "=", "true", ";", "const", "attributes", "=", "[", "]", ";", "const", "regexp", "=", "/", "(\\S+)=[\"']?((?:.(?![\"']?\\s+(?:\\S+)=|[>\"']))+.)[\"']?", "/", "g", ";", "while", "(", "running", ...
Extracts attributes from template tags as an array of objects @example of output [ { key: 'src', value: 'partial.html' }, { key: 'title', value: 'Some title' } ] @param {String} tag - tag to replace @returns {Array.<Object>}
[ "Extracts", "attributes", "from", "template", "tags", "as", "an", "array", "of", "objects" ]
0ff4ac130cbfb4c6c898e83d933df5dbb416be78
https://github.com/xkxd/gulp-html-partial/blob/0ff4ac130cbfb4c6c898e83d933df5dbb416be78/gulp-html-partial.js#L56-L75
33,545
xkxd/gulp-html-partial
gulp-html-partial.js
getPartial
function getPartial(attributes) { const splitAttr = partition(attributes, (attribute) => attribute.key === 'src'); const sourcePath = splitAttr[0][0] && splitAttr[0][0].value; let file; if (sourcePath && fs.existsSync(options.basePath + sourcePath)) { file = injectHTML(fs.readFileSync(options.basePath + sourcePath)) } else if (!sourcePath) { gutil.log(`${pluginName}:`, new gutil.PluginError(pluginName, gutil.colors.red(`Some partial does not have 'src' attribute`)).message); } else { gutil.log(`${pluginName}:`, new gutil.PluginError(pluginName, gutil.colors.red(`File ${options.basePath + sourcePath} does not exist.`)).message); } return replaceAttributes(file, splitAttr[1]); }
javascript
function getPartial(attributes) { const splitAttr = partition(attributes, (attribute) => attribute.key === 'src'); const sourcePath = splitAttr[0][0] && splitAttr[0][0].value; let file; if (sourcePath && fs.existsSync(options.basePath + sourcePath)) { file = injectHTML(fs.readFileSync(options.basePath + sourcePath)) } else if (!sourcePath) { gutil.log(`${pluginName}:`, new gutil.PluginError(pluginName, gutil.colors.red(`Some partial does not have 'src' attribute`)).message); } else { gutil.log(`${pluginName}:`, new gutil.PluginError(pluginName, gutil.colors.red(`File ${options.basePath + sourcePath} does not exist.`)).message); } return replaceAttributes(file, splitAttr[1]); }
[ "function", "getPartial", "(", "attributes", ")", "{", "const", "splitAttr", "=", "partition", "(", "attributes", ",", "(", "attribute", ")", "=>", "attribute", ".", "key", "===", "'src'", ")", ";", "const", "sourcePath", "=", "splitAttr", "[", "0", "]", ...
Gets file using node.js' file system based on src attribute @param {Array.<Object>} attributes - tag @returns {String}
[ "Gets", "file", "using", "node", ".", "js", "file", "system", "based", "on", "src", "attribute" ]
0ff4ac130cbfb4c6c898e83d933df5dbb416be78
https://github.com/xkxd/gulp-html-partial/blob/0ff4ac130cbfb4c6c898e83d933df5dbb416be78/gulp-html-partial.js#L83-L97
33,546
xkxd/gulp-html-partial
gulp-html-partial.js
replaceAttributes
function replaceAttributes(file, attributes) { return (attributes || []).reduce((html, attrObj) => html.replace(options.variablePrefix + attrObj.key, attrObj.value), file && file.toString() || ''); }
javascript
function replaceAttributes(file, attributes) { return (attributes || []).reduce((html, attrObj) => html.replace(options.variablePrefix + attrObj.key, attrObj.value), file && file.toString() || ''); }
[ "function", "replaceAttributes", "(", "file", ",", "attributes", ")", "{", "return", "(", "attributes", "||", "[", "]", ")", ".", "reduce", "(", "(", "html", ",", "attrObj", ")", "=>", "html", ".", "replace", "(", "options", ".", "variablePrefix", "+", ...
Replaces partial content with given attributes @param {Object|undefined} file - through2's file object @param {Array.<Object>} attributes - tag @returns {String}
[ "Replaces", "partial", "content", "with", "given", "attributes" ]
0ff4ac130cbfb4c6c898e83d933df5dbb416be78
https://github.com/xkxd/gulp-html-partial/blob/0ff4ac130cbfb4c6c898e83d933df5dbb416be78/gulp-html-partial.js#L106-L109
33,547
Kuaizi-co/vue-cli-plugin-auto-router
example/vue.config.js
getPagesConfig
function getPagesConfig(entry) { const pages = {} // 规范中定义每个单页文件结构 // index.html,main.js,App.vue glob.sync(PAGE_PATH + '/*/main.js') .forEach(filePath => { const pageName = path.basename(path.dirname(filePath)) if (entry && entry !== pageName) return pages[pageName] = { entry: filePath, // 除了首页,其他按第二级目录输出 // 浏览器中直接访问/news,省去/news.html fileName: `${pageName === 'index' ? '' : pageName + '/'}index.html`, template: path.dirname(filePath) + '/index.html', chunks: ['vue-common', 'iview', 'echarts', 'vendors', 'manifest', pageName] } }) return pages }
javascript
function getPagesConfig(entry) { const pages = {} // 规范中定义每个单页文件结构 // index.html,main.js,App.vue glob.sync(PAGE_PATH + '/*/main.js') .forEach(filePath => { const pageName = path.basename(path.dirname(filePath)) if (entry && entry !== pageName) return pages[pageName] = { entry: filePath, // 除了首页,其他按第二级目录输出 // 浏览器中直接访问/news,省去/news.html fileName: `${pageName === 'index' ? '' : pageName + '/'}index.html`, template: path.dirname(filePath) + '/index.html', chunks: ['vue-common', 'iview', 'echarts', 'vendors', 'manifest', pageName] } }) return pages }
[ "function", "getPagesConfig", "(", "entry", ")", "{", "const", "pages", "=", "{", "}", "// 规范中定义每个单页文件结构", "// index.html,main.js,App.vue", "glob", ".", "sync", "(", "PAGE_PATH", "+", "'/*/main.js'", ")", ".", "forEach", "(", "filePath", "=>", "{", "const", "p...
const webpackPluginAutoRouter = require("@kuaizi/webpack-plugin-auto-router") 获取多页面配置对象
[ "const", "webpackPluginAutoRouter", "=", "require", "(" ]
bdca7fbc252420a4bab2eac319ea13acafc9ed18
https://github.com/Kuaizi-co/vue-cli-plugin-auto-router/blob/bdca7fbc252420a4bab2eac319ea13acafc9ed18/example/vue.config.js#L19-L37
33,548
MostlyJS/mostly-feathers-rest
src/wrappers.js
getHandler
function getHandler (method, getArgs, trans, domain = 'feathers') { return function (req, res, next) { res.setHeader('Allow', Object.values(allowedMethods).join(',')); let params = Object.assign({}, req.params || {}); delete params.service; delete params.id; delete params.subresources; delete params[0]; req.feathers = { provider: 'rest' }; // Grab the service parameters. Use req.feathers and set the query to req.query let query = req.query || {}; let headers = fp.dissoc('cookie', req.headers || {}); let cookies = req.cookies || {}; params = Object.assign({ query, headers }, params, req.feathers); // Transfer the received file if (req.file) { params.file = req.file; } // method override if ((method === 'update' || method === 'patch') && params.query.$method && params.query.$method.toLowerCase() === 'patch') { method = 'patch' delete params.query.$method } // Run the getArgs callback, if available, for additional parameters const [service, ...args] = getArgs(req, res, next); debug(`REST handler calling service \'${service}\'`, { cmd: method, path: req.path, //args: args, //params: params, //feathers: req.feathers }); // The service success callback which sets res.data or calls next() with the error const callback = function (err, data) { debug(`${service}.${method} response:`, err || { status: data && data.status, size: data && JSON.stringify(data).length }); if (err) return next(err.cause || err); res.data = data; if (!data) { debug(`No content returned for '${req.url}'`); res.status(statusCodes.noContent); } else if (method === 'create') { res.status(statusCodes.created); } return next(); }; trans.act({ topic: `${domain}.${service}`, cmd: method, path: req.path, args: args, params: params, feathers: req.feathers }, callback); }; }
javascript
function getHandler (method, getArgs, trans, domain = 'feathers') { return function (req, res, next) { res.setHeader('Allow', Object.values(allowedMethods).join(',')); let params = Object.assign({}, req.params || {}); delete params.service; delete params.id; delete params.subresources; delete params[0]; req.feathers = { provider: 'rest' }; // Grab the service parameters. Use req.feathers and set the query to req.query let query = req.query || {}; let headers = fp.dissoc('cookie', req.headers || {}); let cookies = req.cookies || {}; params = Object.assign({ query, headers }, params, req.feathers); // Transfer the received file if (req.file) { params.file = req.file; } // method override if ((method === 'update' || method === 'patch') && params.query.$method && params.query.$method.toLowerCase() === 'patch') { method = 'patch' delete params.query.$method } // Run the getArgs callback, if available, for additional parameters const [service, ...args] = getArgs(req, res, next); debug(`REST handler calling service \'${service}\'`, { cmd: method, path: req.path, //args: args, //params: params, //feathers: req.feathers }); // The service success callback which sets res.data or calls next() with the error const callback = function (err, data) { debug(`${service}.${method} response:`, err || { status: data && data.status, size: data && JSON.stringify(data).length }); if (err) return next(err.cause || err); res.data = data; if (!data) { debug(`No content returned for '${req.url}'`); res.status(statusCodes.noContent); } else if (method === 'create') { res.status(statusCodes.created); } return next(); }; trans.act({ topic: `${domain}.${service}`, cmd: method, path: req.path, args: args, params: params, feathers: req.feathers }, callback); }; }
[ "function", "getHandler", "(", "method", ",", "getArgs", ",", "trans", ",", "domain", "=", "'feathers'", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "setHeader", "(", "'Allow'", ",", "Object", ".", "values...
A function that returns the middleware for a given method `getArgs` is a function that should return additional leading service arguments
[ "A", "function", "that", "returns", "the", "middleware", "for", "a", "given", "method", "getArgs", "is", "a", "function", "that", "should", "return", "additional", "leading", "service", "arguments" ]
49eee19a5c29f1b2e456461162acca31e110843f
https://github.com/MostlyJS/mostly-feathers-rest/blob/49eee19a5c29f1b2e456461162acca31e110843f/src/wrappers.js#L23-L95
33,549
MostlyJS/mostly-feathers-rest
src/ping.js
info
function info (cb) { var data = { name: pjson.name, message: 'pong', version: pjson.version, node_env: process.env.NODE_ENV, node_ver: process.versions.node, timestamp: Date.now(), hostname: os.hostname(), uptime: process.uptime(), loadavg: os.loadavg()[0] }; cb(null, data); }
javascript
function info (cb) { var data = { name: pjson.name, message: 'pong', version: pjson.version, node_env: process.env.NODE_ENV, node_ver: process.versions.node, timestamp: Date.now(), hostname: os.hostname(), uptime: process.uptime(), loadavg: os.loadavg()[0] }; cb(null, data); }
[ "function", "info", "(", "cb", ")", "{", "var", "data", "=", "{", "name", ":", "pjson", ".", "name", ",", "message", ":", "'pong'", ",", "version", ":", "pjson", ".", "version", ",", "node_env", ":", "process", ".", "env", ".", "NODE_ENV", ",", "no...
Get system informaton @param {Function} cb
[ "Get", "system", "informaton" ]
49eee19a5c29f1b2e456461162acca31e110843f
https://github.com/MostlyJS/mostly-feathers-rest/blob/49eee19a5c29f1b2e456461162acca31e110843f/src/ping.js#L23-L37
33,550
ViacomInc/data-point
packages/data-point/lib/entity-types/entity-control/factory.js
parseCaseStatements
function parseCaseStatements (spec) { return _(spec) .remove(statement => !_.isUndefined(statement.case)) .map(parseCaseStatement) .value() }
javascript
function parseCaseStatements (spec) { return _(spec) .remove(statement => !_.isUndefined(statement.case)) .map(parseCaseStatement) .value() }
[ "function", "parseCaseStatements", "(", "spec", ")", "{", "return", "_", "(", "spec", ")", ".", "remove", "(", "statement", "=>", "!", "_", ".", "isUndefined", "(", "statement", ".", "case", ")", ")", ".", "map", "(", "parseCaseStatement", ")", ".", "v...
Parse only case statements @param {hash} spec - key/value where each value will be mapped into a reducer @returns
[ "Parse", "only", "case", "statements" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/entity-types/entity-control/factory.js#L24-L29
33,551
ViacomInc/data-point
packages/data-point/lib/accumulator/factory.js
create
function create (spec) { const accumulator = new Accumulator() accumulator.value = spec.value accumulator.context = spec.context accumulator.reducer = { spec: spec.context } accumulator.entityOverrides = merge({}, spec.entityOverrides) accumulator.locals = merge({}, spec.locals) accumulator.values = spec.values accumulator.trace = spec.trace accumulator.debug = debug return accumulator }
javascript
function create (spec) { const accumulator = new Accumulator() accumulator.value = spec.value accumulator.context = spec.context accumulator.reducer = { spec: spec.context } accumulator.entityOverrides = merge({}, spec.entityOverrides) accumulator.locals = merge({}, spec.locals) accumulator.values = spec.values accumulator.trace = spec.trace accumulator.debug = debug return accumulator }
[ "function", "create", "(", "spec", ")", "{", "const", "accumulator", "=", "new", "Accumulator", "(", ")", "accumulator", ".", "value", "=", "spec", ".", "value", "accumulator", ".", "context", "=", "spec", ".", "context", "accumulator", ".", "reducer", "="...
creates new Accumulator based on spec @param {Object} spec - acumulator spec @return {Source}
[ "creates", "new", "Accumulator", "based", "on", "spec" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/accumulator/factory.js#L24-L39
33,552
MikeKovarik/rollup-plugin-notify
index.js
calculateCountOfReplacementChar
function calculateCountOfReplacementChar(string, replaceByChar = ' ') { var characters = 0 string .split('') .forEach(char => { var size = charSizes.get(char) || 1 characters += size }) // All sizes were measured against space char. Recalculate if needed. if (replaceByChar !== ' ') characters = characters / charSizes.get(replaceByChar) return Math.round(characters) }
javascript
function calculateCountOfReplacementChar(string, replaceByChar = ' ') { var characters = 0 string .split('') .forEach(char => { var size = charSizes.get(char) || 1 characters += size }) // All sizes were measured against space char. Recalculate if needed. if (replaceByChar !== ' ') characters = characters / charSizes.get(replaceByChar) return Math.round(characters) }
[ "function", "calculateCountOfReplacementChar", "(", "string", ",", "replaceByChar", "=", "' '", ")", "{", "var", "characters", "=", "0", "string", ".", "split", "(", "''", ")", ".", "forEach", "(", "char", "=>", "{", "var", "size", "=", "charSizes", ".", ...
Calculates how many space characters should be displayed in place of given string argument. We sum widths of each character in the string because the text cannot be displayed in monospace font.
[ "Calculates", "how", "many", "space", "characters", "should", "be", "displayed", "in", "place", "of", "given", "string", "argument", ".", "We", "sum", "widths", "of", "each", "character", "in", "the", "string", "because", "the", "text", "cannot", "be", "disp...
30607ce682d0ea79d5ebc30f02ac918b48ca3507
https://github.com/MikeKovarik/rollup-plugin-notify/blob/30607ce682d0ea79d5ebc30f02ac918b48ca3507/index.js#L47-L59
33,553
MikeKovarik/rollup-plugin-notify
index.js
sanitizeLines
function sanitizeLines(frame) { // Sanitize newlines & replace tabs. lines = stripAnsi(frame) .replace(/\r/g, '') .split('\n') .map(l => l.replace(/\t/g, ' ')) // Remove left caret. var leftCaretLine = lines.find(l => l.startsWith('>')) if (leftCaretLine) { lines[lines.indexOf(leftCaretLine)] = leftCaretLine.replace('>', ' ') } // Remove left padding. // Loop while all lines start with space and strip the space from all lines. while (lines.find(l => !l.startsWith(' ')) == undefined) { lines = lines.map(l => l.slice(1)) } return lines }
javascript
function sanitizeLines(frame) { // Sanitize newlines & replace tabs. lines = stripAnsi(frame) .replace(/\r/g, '') .split('\n') .map(l => l.replace(/\t/g, ' ')) // Remove left caret. var leftCaretLine = lines.find(l => l.startsWith('>')) if (leftCaretLine) { lines[lines.indexOf(leftCaretLine)] = leftCaretLine.replace('>', ' ') } // Remove left padding. // Loop while all lines start with space and strip the space from all lines. while (lines.find(l => !l.startsWith(' ')) == undefined) { lines = lines.map(l => l.slice(1)) } return lines }
[ "function", "sanitizeLines", "(", "frame", ")", "{", "// Sanitize newlines & replace tabs.", "lines", "=", "stripAnsi", "(", "frame", ")", ".", "replace", "(", "/", "\\r", "/", "g", ",", "''", ")", ".", "split", "(", "'\\n'", ")", ".", "map", "(", "l", ...
Babel is the worst offender.
[ "Babel", "is", "the", "worst", "offender", "." ]
30607ce682d0ea79d5ebc30f02ac918b48ca3507
https://github.com/MikeKovarik/rollup-plugin-notify/blob/30607ce682d0ea79d5ebc30f02ac918b48ca3507/index.js#L62-L79
33,554
MikeKovarik/rollup-plugin-notify
index.js
extractMessage
function extractMessage(error) { var {message} = error if (error.plugin === 'babel') { // Hey Babel, you're not helping! var filepath = error.id var message = error.message function stripFilePath() { var index = message.indexOf(filepath) console.log(index, filepath.length) message = message.slice(0, index) + message.slice(filepath.length + 1) message = message.trim() } if (message.includes(filepath)) { stripFilePath() } else { filepath = filepath.replace(/\\/g, '/') if (message.includes(filepath)) stripFilePath() } } return message }
javascript
function extractMessage(error) { var {message} = error if (error.plugin === 'babel') { // Hey Babel, you're not helping! var filepath = error.id var message = error.message function stripFilePath() { var index = message.indexOf(filepath) console.log(index, filepath.length) message = message.slice(0, index) + message.slice(filepath.length + 1) message = message.trim() } if (message.includes(filepath)) { stripFilePath() } else { filepath = filepath.replace(/\\/g, '/') if (message.includes(filepath)) stripFilePath() } } return message }
[ "function", "extractMessage", "(", "error", ")", "{", "var", "{", "message", "}", "=", "error", "if", "(", "error", ".", "plugin", "===", "'babel'", ")", "{", "// Hey Babel, you're not helping!", "var", "filepath", "=", "error", ".", "id", "var", "message", ...
Extract only the error message and strip it from file path that might be in there as well.
[ "Extract", "only", "the", "error", "message", "and", "strip", "it", "from", "file", "path", "that", "might", "be", "in", "there", "as", "well", "." ]
30607ce682d0ea79d5ebc30f02ac918b48ca3507
https://github.com/MikeKovarik/rollup-plugin-notify/blob/30607ce682d0ea79d5ebc30f02ac918b48ca3507/index.js#L82-L103
33,555
vfile/to-vfile
lib/sync.js
readSync
function readSync(description, options) { var file = vfile(description) file.contents = fs.readFileSync(path.resolve(file.cwd, file.path), options) return file }
javascript
function readSync(description, options) { var file = vfile(description) file.contents = fs.readFileSync(path.resolve(file.cwd, file.path), options) return file }
[ "function", "readSync", "(", "description", ",", "options", ")", "{", "var", "file", "=", "vfile", "(", "description", ")", "file", ".", "contents", "=", "fs", ".", "readFileSync", "(", "path", ".", "resolve", "(", "file", ".", "cwd", ",", "file", ".",...
Create a virtual file and read it in, synchronously.
[ "Create", "a", "virtual", "file", "and", "read", "it", "in", "synchronously", "." ]
a7abc68bb48536c4ef60959a003c612599e57ad9
https://github.com/vfile/to-vfile/blob/a7abc68bb48536c4ef60959a003c612599e57ad9/lib/sync.js#L11-L15
33,556
vfile/to-vfile
lib/sync.js
writeSync
function writeSync(description, options) { var file = vfile(description) fs.writeFileSync( path.resolve(file.cwd, file.path), file.contents || '', options ) }
javascript
function writeSync(description, options) { var file = vfile(description) fs.writeFileSync( path.resolve(file.cwd, file.path), file.contents || '', options ) }
[ "function", "writeSync", "(", "description", ",", "options", ")", "{", "var", "file", "=", "vfile", "(", "description", ")", "fs", ".", "writeFileSync", "(", "path", ".", "resolve", "(", "file", ".", "cwd", ",", "file", ".", "path", ")", ",", "file", ...
Create a virtual file and write it out, synchronously.
[ "Create", "a", "virtual", "file", "and", "write", "it", "out", "synchronously", "." ]
a7abc68bb48536c4ef60959a003c612599e57ad9
https://github.com/vfile/to-vfile/blob/a7abc68bb48536c4ef60959a003c612599e57ad9/lib/sync.js#L18-L25
33,557
ViacomInc/data-point
packages/data-point/lib/utils/index.js
set
function set (target, key, value) { const obj = {} obj[key] = value return Object.assign({}, target, obj) }
javascript
function set (target, key, value) { const obj = {} obj[key] = value return Object.assign({}, target, obj) }
[ "function", "set", "(", "target", ",", "key", ",", "value", ")", "{", "const", "obj", "=", "{", "}", "obj", "[", "key", "]", "=", "value", "return", "Object", ".", "assign", "(", "{", "}", ",", "target", ",", "obj", ")", "}" ]
sets key to value of a copy of target. target stays untouched, if key is an object, then the key will be taken as an object and merged with target @param {Object} target @param {string|Object} key @param {*} value
[ "sets", "key", "to", "value", "of", "a", "copy", "of", "target", ".", "target", "stays", "untouched", "if", "key", "is", "an", "object", "then", "the", "key", "will", "be", "taken", "as", "an", "object", "and", "merged", "with", "target" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/utils/index.js#L11-L15
33,558
formio/keycred
keycred.js
function (certparams) { var keys = forge.pki.rsa.generateKeyPair(2048); this.publicKey = keys.publicKey; this.privateKey = keys.privateKey; this.cert = this.createCertificate(certparams); this.keycred = null; this.digest = null; }
javascript
function (certparams) { var keys = forge.pki.rsa.generateKeyPair(2048); this.publicKey = keys.publicKey; this.privateKey = keys.privateKey; this.cert = this.createCertificate(certparams); this.keycred = null; this.digest = null; }
[ "function", "(", "certparams", ")", "{", "var", "keys", "=", "forge", ".", "pki", ".", "rsa", ".", "generateKeyPair", "(", "2048", ")", ";", "this", ".", "publicKey", "=", "keys", ".", "publicKey", ";", "this", ".", "privateKey", "=", "keys", ".", "p...
Generate a new KeyCred using cert parameters. @param certparams @constructor
[ "Generate", "a", "new", "KeyCred", "using", "cert", "parameters", "." ]
a16dd88cfb40639aed5ad1ac0b6d448aeecfce22
https://github.com/formio/keycred/blob/a16dd88cfb40639aed5ad1ac0b6d448aeecfce22/keycred.js#L9-L16
33,559
ViacomInc/data-point
packages/data-point-service/lib/revalidation-store.js
clear
function clear (store) { const forDeletion = [] const now = Date.now() for (const [key, entry] of store) { // mark for deletion entries that have timed out if (now - entry.created > entry.ttl) { forDeletion.push(key) } } const forDeletionLength = forDeletion.length // if nothing to clean then exit if (forDeletionLength === 0) { return 0 } debug(`local revalidation flags that timed out: ${forDeletion}`) forDeletion.forEach(key => store.delete(key)) return forDeletionLength }
javascript
function clear (store) { const forDeletion = [] const now = Date.now() for (const [key, entry] of store) { // mark for deletion entries that have timed out if (now - entry.created > entry.ttl) { forDeletion.push(key) } } const forDeletionLength = forDeletion.length // if nothing to clean then exit if (forDeletionLength === 0) { return 0 } debug(`local revalidation flags that timed out: ${forDeletion}`) forDeletion.forEach(key => store.delete(key)) return forDeletionLength }
[ "function", "clear", "(", "store", ")", "{", "const", "forDeletion", "=", "[", "]", "const", "now", "=", "Date", ".", "now", "(", ")", "for", "(", "const", "[", "key", ",", "entry", "]", "of", "store", ")", "{", "// mark for deletion entries that have ti...
It marks and deletes all the keys that have their ttl expired @param {Map} store Map Object that stores all the cached keys @returns {Number} ammount of entries deleted
[ "It", "marks", "and", "deletes", "all", "the", "keys", "that", "have", "their", "ttl", "expired" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point-service/lib/revalidation-store.js#L23-L43
33,560
ViacomInc/data-point
packages/data-point-service/lib/revalidation-store.js
exists
function exists (store, key) { const entry = store.get(key) // checks entry exists and it has not timed-out return !!entry && Date.now() - entry.created < entry.ttl }
javascript
function exists (store, key) { const entry = store.get(key) // checks entry exists and it has not timed-out return !!entry && Date.now() - entry.created < entry.ttl }
[ "function", "exists", "(", "store", ",", "key", ")", "{", "const", "entry", "=", "store", ".", "get", "(", "key", ")", "// checks entry exists and it has not timed-out", "return", "!", "!", "entry", "&&", "Date", ".", "now", "(", ")", "-", "entry", ".", ...
True if a key exists, and it has not expired @param {Map} store Map Object that stores all the cached keys @param {String} key key value @returns {Boolean} true if key exists, false otherwise
[ "True", "if", "a", "key", "exists", "and", "it", "has", "not", "expired" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point-service/lib/revalidation-store.js#L75-L79
33,561
ViacomInc/data-point
packages/data-point/lib/entity-types/base-entity/resolve.js
assignParamsHelper
function assignParamsHelper (accumulator, entity) { if (accumulator.entityOverrides[entity.entityType]) { return merge( {}, entity.params, accumulator.entityOverrides[entity.entityType].params ) } return entity.params }
javascript
function assignParamsHelper (accumulator, entity) { if (accumulator.entityOverrides[entity.entityType]) { return merge( {}, entity.params, accumulator.entityOverrides[entity.entityType].params ) } return entity.params }
[ "function", "assignParamsHelper", "(", "accumulator", ",", "entity", ")", "{", "if", "(", "accumulator", ".", "entityOverrides", "[", "entity", ".", "entityType", "]", ")", "{", "return", "merge", "(", "{", "}", ",", "entity", ".", "params", ",", "accumula...
Incase there is an override present, assigns parameters to the correct entity. @param {*} accumulator @param {*} entity
[ "Incase", "there", "is", "an", "override", "present", "assigns", "parameters", "to", "the", "correct", "entity", "." ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/entity-types/base-entity/resolve.js#L123-L132
33,562
ViacomInc/data-point
packages/data-point/lib/stores/store-manager.js
get
function get (manager, errorInfoCb, id) { const value = manager.store.get(id) if (_.isUndefined(value)) { const errorInfo = errorInfoCb(id) const e = new Error(errorInfo.message) e.name = errorInfo.name throw e } return value }
javascript
function get (manager, errorInfoCb, id) { const value = manager.store.get(id) if (_.isUndefined(value)) { const errorInfo = errorInfoCb(id) const e = new Error(errorInfo.message) e.name = errorInfo.name throw e } return value }
[ "function", "get", "(", "manager", ",", "errorInfoCb", ",", "id", ")", "{", "const", "value", "=", "manager", ".", "store", ".", "get", "(", "id", ")", "if", "(", "_", ".", "isUndefined", "(", "value", ")", ")", "{", "const", "errorInfo", "=", "err...
get value by id @throws if value for id is undefined @param {Object} manager @param {Function} errorInfoCb @param {string} id - model id @return {*}
[ "get", "value", "by", "id" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/stores/store-manager.js#L34-L44
33,563
ViacomInc/data-point
packages/data-point-service/lib/cache-middleware.js
isRevalidatingCacheKey
function isRevalidatingCacheKey (ctx, currentEntryKey) { const revalidatingCache = ctx.locals.revalidatingCache return (revalidatingCache && revalidatingCache.entryKey) === currentEntryKey }
javascript
function isRevalidatingCacheKey (ctx, currentEntryKey) { const revalidatingCache = ctx.locals.revalidatingCache return (revalidatingCache && revalidatingCache.entryKey) === currentEntryKey }
[ "function", "isRevalidatingCacheKey", "(", "ctx", ",", "currentEntryKey", ")", "{", "const", "revalidatingCache", "=", "ctx", ".", "locals", ".", "revalidatingCache", "return", "(", "revalidatingCache", "&&", "revalidatingCache", ".", "entryKey", ")", "===", "curren...
Checks if the current entry key is the one being revalidated @param {DataPoint.Accumulator} ctx DataPoint Accumulator object @param {String} currentEntryKey entry key @returns {Boolean} true if revalidating entryKey matches current key
[ "Checks", "if", "the", "current", "entry", "key", "is", "the", "one", "being", "revalidated" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point-service/lib/cache-middleware.js#L164-L167
33,564
ViacomInc/data-point
packages/data-point-service/lib/cache-middleware.js
resolveStaleWhileRevalidateEntry
function resolveStaleWhileRevalidateEntry (service, entryKey, cache, ctx) { // NOTE: pulling through module.exports allows us to test if they were called const { resolveStaleWhileRevalidate, isRevalidatingCacheKey, shouldTriggerRevalidate, revalidateEntry } = module.exports // IMPORTANT: we only want to bypass an entity that is being revalidated and // that matches the same cache entry key, otherwise all child entities will // be needlesly resolved if (isRevalidatingCacheKey(ctx, entryKey)) { // bypass the rest forces entity to get resolved return undefined } const staleWhileRevalidate = resolveStaleWhileRevalidate(service) // cleanup on a new tick so it does not block current process, the clear // method is throttled for performance setTimeout(staleWhileRevalidate.invalidateLocalFlags, 0) const tasks = [ staleWhileRevalidate.getRevalidationState(entryKey), staleWhileRevalidate.getEntry(entryKey) ] return Promise.all(tasks).then(results => { const revalidationState = results[0] const staleEntry = results[1] if (shouldTriggerRevalidate(staleEntry, revalidationState)) { // IMPORTANT: revalidateEntry operates on a new thread revalidateEntry(service, entryKey, cache, ctx) } // Otherwise means its a cold start and must be resolved outside // return stale entry regardless return staleEntry }) }
javascript
function resolveStaleWhileRevalidateEntry (service, entryKey, cache, ctx) { // NOTE: pulling through module.exports allows us to test if they were called const { resolveStaleWhileRevalidate, isRevalidatingCacheKey, shouldTriggerRevalidate, revalidateEntry } = module.exports // IMPORTANT: we only want to bypass an entity that is being revalidated and // that matches the same cache entry key, otherwise all child entities will // be needlesly resolved if (isRevalidatingCacheKey(ctx, entryKey)) { // bypass the rest forces entity to get resolved return undefined } const staleWhileRevalidate = resolveStaleWhileRevalidate(service) // cleanup on a new tick so it does not block current process, the clear // method is throttled for performance setTimeout(staleWhileRevalidate.invalidateLocalFlags, 0) const tasks = [ staleWhileRevalidate.getRevalidationState(entryKey), staleWhileRevalidate.getEntry(entryKey) ] return Promise.all(tasks).then(results => { const revalidationState = results[0] const staleEntry = results[1] if (shouldTriggerRevalidate(staleEntry, revalidationState)) { // IMPORTANT: revalidateEntry operates on a new thread revalidateEntry(service, entryKey, cache, ctx) } // Otherwise means its a cold start and must be resolved outside // return stale entry regardless return staleEntry }) }
[ "function", "resolveStaleWhileRevalidateEntry", "(", "service", ",", "entryKey", ",", "cache", ",", "ctx", ")", "{", "// NOTE: pulling through module.exports allows us to test if they were called", "const", "{", "resolveStaleWhileRevalidate", ",", "isRevalidatingCacheKey", ",", ...
If stale entry exists and control entry has expired it will fire a new thread to resolve the entity, this thread is not meant to be chained to the main Promise chain. When this function returns undefined it is telling the caller it should make a standard resolution of the entity instead of using the stale-while-revalidate process. @param {Service} service Service instance @param {String} entryKey entry key @param {Object} cache cache configuration @param {DataPoint.Accumulator} ctx DataPoint Accumulator object @returns {Promise<Object|undefined>} cached stale value
[ "If", "stale", "entry", "exists", "and", "control", "entry", "has", "expired", "it", "will", "fire", "a", "new", "thread", "to", "resolve", "the", "entity", "this", "thread", "is", "not", "meant", "to", "be", "chained", "to", "the", "main", "Promise", "c...
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point-service/lib/cache-middleware.js#L190-L230
33,565
guillaumepotier/validator.js
dist/validator.min.js
function(a){ // Copy prototype properties. for(var b in a.prototype){var c=b.match(/^(.*?[A-Z]{2,})(.*)$/),d=j(b);null!==c&&(d=c[1]+j(c[2])),d!==b&&( // Add static methods as aliases. d in a||(a[d]=function(b){return function(){var c=new a;return c[b].apply(c,arguments)}}(b),l(a,d,b)), // Create `camelCase` aliases. d in a.prototype||l(a.prototype,b,d))}return a}
javascript
function(a){ // Copy prototype properties. for(var b in a.prototype){var c=b.match(/^(.*?[A-Z]{2,})(.*)$/),d=j(b);null!==c&&(d=c[1]+j(c[2])),d!==b&&( // Add static methods as aliases. d in a||(a[d]=function(b){return function(){var c=new a;return c[b].apply(c,arguments)}}(b),l(a,d,b)), // Create `camelCase` aliases. d in a.prototype||l(a.prototype,b,d))}return a}
[ "function", "(", "a", ")", "{", "// Copy prototype properties.", "for", "(", "var", "b", "in", "a", ".", "prototype", ")", "{", "var", "c", "=", "b", ".", "match", "(", "/", "^(.*?[A-Z]{2,})(.*)$", "/", ")", ",", "d", "=", "j", "(", "b", ")", ";", ...
Test if object is empty, useful for Constraint violations check
[ "Test", "if", "object", "is", "empty", "useful", "for", "Constraint", "violations", "check" ]
18546fa34e47c1d3b910b2edec0d60544e845b6b
https://github.com/guillaumepotier/validator.js/blob/18546fa34e47c1d3b910b2edec0d60544e845b6b/dist/validator.min.js#L72-L78
33,566
ViacomInc/data-point
packages/data-point-service/lib/redis-controller.js
setSWRStaleEntry
function setSWRStaleEntry (service, key, value, ttl) { return setEntry(service, createSWRStaleKey(key), value, ttl) }
javascript
function setSWRStaleEntry (service, key, value, ttl) { return setEntry(service, createSWRStaleKey(key), value, ttl) }
[ "function", "setSWRStaleEntry", "(", "service", ",", "key", ",", "value", ",", "ttl", ")", "{", "return", "setEntry", "(", "service", ",", "createSWRStaleKey", "(", "key", ")", ",", "value", ",", "ttl", ")", "}" ]
When stale is provided the value is calculated as ttl + stale @param {Service} service Service instance @param {String} key entry key @param {Object} value entry value @param {Number|String} ttl time to live value supported by https://github.com/zeit/ms @returns {Promise}
[ "When", "stale", "is", "provided", "the", "value", "is", "calculated", "as", "ttl", "+", "stale" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point-service/lib/redis-controller.js#L72-L74
33,567
adragonite/math3d
src/Transform.js
_getLocalPositionFromWorldPosition
function _getLocalPositionFromWorldPosition(transform) { if (transform.parent === undefined) return transform.position; else return transform.parent.rotation.inverse().mulVector3(transform.position.sub(transform.parent.position)); }
javascript
function _getLocalPositionFromWorldPosition(transform) { if (transform.parent === undefined) return transform.position; else return transform.parent.rotation.inverse().mulVector3(transform.position.sub(transform.parent.position)); }
[ "function", "_getLocalPositionFromWorldPosition", "(", "transform", ")", "{", "if", "(", "transform", ".", "parent", "===", "undefined", ")", "return", "transform", ".", "position", ";", "else", "return", "transform", ".", "parent", ".", "rotation", ".", "invers...
Sets the local position of the transform according to the world position @param {Transform} transform
[ "Sets", "the", "local", "position", "of", "the", "transform", "according", "to", "the", "world", "position" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Transform.js#L17-L22
33,568
adragonite/math3d
src/Transform.js
_getWorldPositionFromLocalPosition
function _getWorldPositionFromLocalPosition(transform) { if (transform.parent === undefined) return transform.localPosition; else return transform.parent.position.add(transform.parent.rotation.mulVector3(transform.localPosition)); }
javascript
function _getWorldPositionFromLocalPosition(transform) { if (transform.parent === undefined) return transform.localPosition; else return transform.parent.position.add(transform.parent.rotation.mulVector3(transform.localPosition)); }
[ "function", "_getWorldPositionFromLocalPosition", "(", "transform", ")", "{", "if", "(", "transform", ".", "parent", "===", "undefined", ")", "return", "transform", ".", "localPosition", ";", "else", "return", "transform", ".", "parent", ".", "position", ".", "a...
Sets the world position of the transform according to the local position @param {Transform} transform
[ "Sets", "the", "world", "position", "of", "the", "transform", "according", "to", "the", "local", "position" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Transform.js#L29-L34
33,569
adragonite/math3d
src/Transform.js
_getLocalRotationFromWorldRotation
function _getLocalRotationFromWorldRotation(transform) { if(transform.parent === undefined) return transform.rotation; else return transform.parent.rotation.inverse().mul(transform.rotation); }
javascript
function _getLocalRotationFromWorldRotation(transform) { if(transform.parent === undefined) return transform.rotation; else return transform.parent.rotation.inverse().mul(transform.rotation); }
[ "function", "_getLocalRotationFromWorldRotation", "(", "transform", ")", "{", "if", "(", "transform", ".", "parent", "===", "undefined", ")", "return", "transform", ".", "rotation", ";", "else", "return", "transform", ".", "parent", ".", "rotation", ".", "invers...
Sets the local rotation of the transform according to the world rotation @param {Transform} transform
[ "Sets", "the", "local", "rotation", "of", "the", "transform", "according", "to", "the", "world", "rotation" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Transform.js#L41-L46
33,570
adragonite/math3d
src/Transform.js
_getWorldRotationFromLocalRotation
function _getWorldRotationFromLocalRotation(transform) { if(transform.parent === undefined) return transform.localRotation; else return transform.parent.rotation.mul(transform.localRotation); }
javascript
function _getWorldRotationFromLocalRotation(transform) { if(transform.parent === undefined) return transform.localRotation; else return transform.parent.rotation.mul(transform.localRotation); }
[ "function", "_getWorldRotationFromLocalRotation", "(", "transform", ")", "{", "if", "(", "transform", ".", "parent", "===", "undefined", ")", "return", "transform", ".", "localRotation", ";", "else", "return", "transform", ".", "parent", ".", "rotation", ".", "m...
Sets the world rotation of the transform according to the local rotation @param {Transform} transform
[ "Sets", "the", "world", "rotation", "of", "the", "transform", "according", "to", "the", "local", "rotation" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Transform.js#L53-L58
33,571
adragonite/math3d
src/Transform.js
_adjustChildren
function _adjustChildren(children) { children.forEach(function (child) { child.rotation = _getWorldRotationFromLocalRotation(child); child.position = _getWorldPositionFromLocalPosition(child); }); }
javascript
function _adjustChildren(children) { children.forEach(function (child) { child.rotation = _getWorldRotationFromLocalRotation(child); child.position = _getWorldPositionFromLocalPosition(child); }); }
[ "function", "_adjustChildren", "(", "children", ")", "{", "children", ".", "forEach", "(", "function", "(", "child", ")", "{", "child", ".", "rotation", "=", "_getWorldRotationFromLocalRotation", "(", "child", ")", ";", "child", ".", "position", "=", "_getWorl...
Adjusts position and rotation of the given children array @param {Array} children
[ "Adjusts", "position", "and", "rotation", "of", "the", "given", "children", "array" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Transform.js#L65-L70
33,572
adragonite/math3d
src/Transform.js
_getLocalToWorldMatrix
function _getLocalToWorldMatrix(transform) { return function() { return Matrix4x4.LocalToWorldMatrix(transform.position, transform.rotation, Vector3.one); } }
javascript
function _getLocalToWorldMatrix(transform) { return function() { return Matrix4x4.LocalToWorldMatrix(transform.position, transform.rotation, Vector3.one); } }
[ "function", "_getLocalToWorldMatrix", "(", "transform", ")", "{", "return", "function", "(", ")", "{", "return", "Matrix4x4", ".", "LocalToWorldMatrix", "(", "transform", ".", "position", ",", "transform", ".", "rotation", ",", "Vector3", ".", "one", ")", ";",...
Returns a matrix that transforms a point from local space to world space @param {Transform} transform @returns {Matrix4x4} local to world matrix
[ "Returns", "a", "matrix", "that", "transforms", "a", "point", "from", "local", "space", "to", "world", "space" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Transform.js#L114-L118
33,573
adragonite/math3d
src/Transform.js
_getWorldtoLocalMatrix
function _getWorldtoLocalMatrix(transform) { return function() { return Matrix4x4.WorldToLocalMatrix(transform.position, transform.rotation, Vector3.one); } }
javascript
function _getWorldtoLocalMatrix(transform) { return function() { return Matrix4x4.WorldToLocalMatrix(transform.position, transform.rotation, Vector3.one); } }
[ "function", "_getWorldtoLocalMatrix", "(", "transform", ")", "{", "return", "function", "(", ")", "{", "return", "Matrix4x4", ".", "WorldToLocalMatrix", "(", "transform", ".", "position", ",", "transform", ".", "rotation", ",", "Vector3", ".", "one", ")", ";",...
Returns a matrix that transforms a point from world space to local space @param {Transform} transform @returns {Matrix4x4} local to world matrix
[ "Returns", "a", "matrix", "that", "transforms", "a", "point", "from", "world", "space", "to", "local", "space" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Transform.js#L126-L130
33,574
adragonite/math3d
src/Transform.js
_getRoot
function _getRoot(transform) { return function() { var parent = transform.parent; return parent === undefined ? transform : parent.root; } }
javascript
function _getRoot(transform) { return function() { var parent = transform.parent; return parent === undefined ? transform : parent.root; } }
[ "function", "_getRoot", "(", "transform", ")", "{", "return", "function", "(", ")", "{", "var", "parent", "=", "transform", ".", "parent", ";", "return", "parent", "===", "undefined", "?", "transform", ":", "parent", ".", "root", ";", "}", "}" ]
Returns the topmost transform in the hierarchy @param {Transform} transform @returns {Transform} root transform
[ "Returns", "the", "topmost", "transform", "in", "the", "hierarchy" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Transform.js#L138-L143
33,575
avetjs/avet
packages/avet-build/lib/server/on-demand-entry-handler.js
disposeInactiveEntries
function disposeInactiveEntries( devMiddleware, entries, lastAccessPages, maxInactiveAge ) { const disposingPages = []; Object.keys(entries).forEach(page => { const { lastActiveTime, status } = entries[page]; // This means this entry is currently building or just added // We don't need to dispose those entries. if (status !== BUILT) return; // We should not build the last accessed page even we didn't get any pings // Sometimes, it's possible our XHR ping to wait before completing other requests. // In that case, we should not dispose the current viewing page if (lastAccessPages[0] === page) return; if (Date.now() - lastActiveTime > maxInactiveAge) { disposingPages.push(page); } }); if (disposingPages.length > 0) { disposingPages.forEach(page => { delete entries[page]; }); console.log(`> Disposing inactive page(s): ${disposingPages.join(', ')}`); devMiddleware.invalidate(); } }
javascript
function disposeInactiveEntries( devMiddleware, entries, lastAccessPages, maxInactiveAge ) { const disposingPages = []; Object.keys(entries).forEach(page => { const { lastActiveTime, status } = entries[page]; // This means this entry is currently building or just added // We don't need to dispose those entries. if (status !== BUILT) return; // We should not build the last accessed page even we didn't get any pings // Sometimes, it's possible our XHR ping to wait before completing other requests. // In that case, we should not dispose the current viewing page if (lastAccessPages[0] === page) return; if (Date.now() - lastActiveTime > maxInactiveAge) { disposingPages.push(page); } }); if (disposingPages.length > 0) { disposingPages.forEach(page => { delete entries[page]; }); console.log(`> Disposing inactive page(s): ${disposingPages.join(', ')}`); devMiddleware.invalidate(); } }
[ "function", "disposeInactiveEntries", "(", "devMiddleware", ",", "entries", ",", "lastAccessPages", ",", "maxInactiveAge", ")", "{", "const", "disposingPages", "=", "[", "]", ";", "Object", ".", "keys", "(", "entries", ")", ".", "forEach", "(", "page", "=>", ...
dispose inactive pages
[ "dispose", "inactive", "pages" ]
58aa606f0f0c7a75dfcfd57c02dc48809ccfa094
https://github.com/avetjs/avet/blob/58aa606f0f0c7a75dfcfd57c02dc48809ccfa094/packages/avet-build/lib/server/on-demand-entry-handler.js#L285-L317
33,576
ViacomInc/data-point
packages/data-point/lib/entity-types/entity-request/resolve.js
resolveOptions
function resolveOptions (accumulator, resolveReducer) { const url = resolveUrl(accumulator) const specOptions = accumulator.reducer.spec.options return resolveReducer(accumulator, specOptions).then(acc => { const options = getRequestOptions(url, acc.value) return utils.assign(accumulator, { options }) }) }
javascript
function resolveOptions (accumulator, resolveReducer) { const url = resolveUrl(accumulator) const specOptions = accumulator.reducer.spec.options return resolveReducer(accumulator, specOptions).then(acc => { const options = getRequestOptions(url, acc.value) return utils.assign(accumulator, { options }) }) }
[ "function", "resolveOptions", "(", "accumulator", ",", "resolveReducer", ")", "{", "const", "url", "=", "resolveUrl", "(", "accumulator", ")", "const", "specOptions", "=", "accumulator", ".", "reducer", ".", "spec", ".", "options", "return", "resolveReducer", "(...
Resolve options object @param {Accumulator} accumulator @param {Function} resolveReducer @return {Promise<Accumulator>}
[ "Resolve", "options", "object" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/entity-types/entity-request/resolve.js#L45-L52
33,577
rodrigowirth/react-flot
flot/jquery.flot.tooltip.js
function (p1x, p1y, p2x, p2y) { return Math.sqrt((p2x - p1x) * (p2x - p1x) + (p2y - p1y) * (p2y - p1y)); }
javascript
function (p1x, p1y, p2x, p2y) { return Math.sqrt((p2x - p1x) * (p2x - p1x) + (p2y - p1y) * (p2y - p1y)); }
[ "function", "(", "p1x", ",", "p1y", ",", "p2x", ",", "p2y", ")", "{", "return", "Math", ".", "sqrt", "(", "(", "p2x", "-", "p1x", ")", "*", "(", "p2x", "-", "p1x", ")", "+", "(", "p2y", "-", "p1y", ")", "*", "(", "p2y", "-", "p1y", ")", "...
Simple distance formula.
[ "Simple", "distance", "formula", "." ]
801c14d7225c80c2c7b31f576c52e03d29efb739
https://github.com/rodrigowirth/react-flot/blob/801c14d7225c80c2c7b31f576c52e03d29efb739/flot/jquery.flot.tooltip.js#L148-L150
33,578
ViacomInc/data-point
packages/data-point-cache/lib/cache.js
bootstrapAPI
function bootstrapAPI (cache) { cache.set = set.bind(null, cache) cache.get = get.bind(null, cache) cache.del = del.bind(null, cache) return cache }
javascript
function bootstrapAPI (cache) { cache.set = set.bind(null, cache) cache.get = get.bind(null, cache) cache.del = del.bind(null, cache) return cache }
[ "function", "bootstrapAPI", "(", "cache", ")", "{", "cache", ".", "set", "=", "set", ".", "bind", "(", "null", ",", "cache", ")", "cache", ".", "get", "=", "get", ".", "bind", "(", "null", ",", "cache", ")", "cache", ".", "del", "=", "del", ".", ...
Decorates the cache object to add the API @param {Object} cache object to be decorated
[ "Decorates", "the", "cache", "object", "to", "add", "the", "API" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point-cache/lib/cache.js#L74-L79
33,579
adragonite/math3d
src/Matrix.js
_getRows
function _getRows(matrix) { var rows = []; for (var i=0; i<matrix.size.rows; i++) { rows.push([]); for (var j=0; j<matrix.size.columns; j++) rows[i].push(matrix.values[matrix.size.columns * i + j]); } return rows; }
javascript
function _getRows(matrix) { var rows = []; for (var i=0; i<matrix.size.rows; i++) { rows.push([]); for (var j=0; j<matrix.size.columns; j++) rows[i].push(matrix.values[matrix.size.columns * i + j]); } return rows; }
[ "function", "_getRows", "(", "matrix", ")", "{", "var", "rows", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "matrix", ".", "size", ".", "rows", ";", "i", "++", ")", "{", "rows", ".", "push", "(", "[", "]", ")", ";",...
Creates an array of the rows of a matrix @param {Matrix} matrix @returns {Array} rows array: two-dimensional
[ "Creates", "an", "array", "of", "the", "rows", "of", "a", "matrix" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Matrix.js#L16-L24
33,580
adragonite/math3d
src/Matrix.js
_getColumns
function _getColumns(matrix) { var cols = []; for (var i=0; i<matrix.size.columns; i++) { cols.push([]); for (var j=0; j<matrix.size.rows; j++) cols[i].push(matrix.values[i + j * matrix.size.columns]); } return cols; }
javascript
function _getColumns(matrix) { var cols = []; for (var i=0; i<matrix.size.columns; i++) { cols.push([]); for (var j=0; j<matrix.size.rows; j++) cols[i].push(matrix.values[i + j * matrix.size.columns]); } return cols; }
[ "function", "_getColumns", "(", "matrix", ")", "{", "var", "cols", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "matrix", ".", "size", ".", "columns", ";", "i", "++", ")", "{", "cols", ".", "push", "(", "[", "]", ")", ...
Creates an array of the columns of a matrix @param {Matrix} matrix @returns {Array} columns array: two-dimensional
[ "Creates", "an", "array", "of", "the", "columns", "of", "a", "matrix" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Matrix.js#L32-L40
33,581
adragonite/math3d
src/Matrix.js
_sizesMatch
function _sizesMatch(matrix1, matrix2) { return matrix1.size.rows == matrix2.size.rows && matrix1.size.columns == matrix2.size.columns; }
javascript
function _sizesMatch(matrix1, matrix2) { return matrix1.size.rows == matrix2.size.rows && matrix1.size.columns == matrix2.size.columns; }
[ "function", "_sizesMatch", "(", "matrix1", ",", "matrix2", ")", "{", "return", "matrix1", ".", "size", ".", "rows", "==", "matrix2", ".", "size", ".", "rows", "&&", "matrix1", ".", "size", ".", "columns", "==", "matrix2", ".", "size", ".", "columns", "...
Checks if both the number of rows and columns match for two matrices @param {Matrix} matrix1, matrix2 @returns {Boolean} match
[ "Checks", "if", "both", "the", "number", "of", "rows", "and", "columns", "match", "for", "two", "matrices" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Matrix.js#L48-L51
33,582
adragonite/math3d
src/Vector4.js
_fromVector
function _fromVector(vector) { return new _Vector4(vector.values[0], vector.values[1], vector.values[2], vector.values[3]); }
javascript
function _fromVector(vector) { return new _Vector4(vector.values[0], vector.values[1], vector.values[2], vector.values[3]); }
[ "function", "_fromVector", "(", "vector", ")", "{", "return", "new", "_Vector4", "(", "vector", ".", "values", "[", "0", "]", ",", "vector", ".", "values", "[", "1", "]", ",", "vector", ".", "values", "[", "2", "]", ",", "vector", ".", "values", "[...
Creates a Vector4 from a Vector @param {Vector} vector @returns {Vector4} vector4
[ "Creates", "a", "Vector4", "from", "a", "Vector" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Vector4.js#L16-L18
33,583
adragonite/math3d
src/Quaternion.js
_normalizedCoordinates
function _normalizedCoordinates(x, y, z, w) { var magnitude = Math.sqrt(x * x + y * y + z * z + w * w); if (magnitude === 0) return this; return { "x": x / magnitude, "y": y / magnitude, "z": z / magnitude, "w": w / magnitude}; }
javascript
function _normalizedCoordinates(x, y, z, w) { var magnitude = Math.sqrt(x * x + y * y + z * z + w * w); if (magnitude === 0) return this; return { "x": x / magnitude, "y": y / magnitude, "z": z / magnitude, "w": w / magnitude}; }
[ "function", "_normalizedCoordinates", "(", "x", ",", "y", ",", "z", ",", "w", ")", "{", "var", "magnitude", "=", "Math", ".", "sqrt", "(", "x", "*", "x", "+", "y", "*", "y", "+", "z", "*", "z", "+", "w", "*", "w", ")", ";", "if", "(", "magn...
Returns the normalized coordinates of the given quaternion coordinates @param {Number} x y z w @returns {Object} normalized coordinates
[ "Returns", "the", "normalized", "coordinates", "of", "the", "given", "quaternion", "coordinates" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Quaternion.js#L20-L30
33,584
adragonite/math3d
src/Quaternion.js
_fromAngleAxis
function _fromAngleAxis(axis, angle) { var s = Math.sin(angle/2); var c = Math.cos(angle/2); return new _Quaternion(axis.x * s, axis.y * s, axis.z * s, c); }
javascript
function _fromAngleAxis(axis, angle) { var s = Math.sin(angle/2); var c = Math.cos(angle/2); return new _Quaternion(axis.x * s, axis.y * s, axis.z * s, c); }
[ "function", "_fromAngleAxis", "(", "axis", ",", "angle", ")", "{", "var", "s", "=", "Math", ".", "sin", "(", "angle", "/", "2", ")", ";", "var", "c", "=", "Math", ".", "cos", "(", "angle", "/", "2", ")", ";", "return", "new", "_Quaternion", "(", ...
Returns a quaternion for the given unit axis and angles in radians @param {Vector3} axis: unit vector @param {Number} angle: in radians @returns {Quaternion} quaternion
[ "Returns", "a", "quaternion", "for", "the", "given", "unit", "axis", "and", "angles", "in", "radians" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Quaternion.js#L65-L70
33,585
adragonite/math3d
src/Quaternion.js
_getAngleAxis
function _getAngleAxis(quaternion) { return function() { var sqrt = Math.sqrt(1 - quaternion.w * quaternion.w); return { axis: new Vector3(quaternion.x / sqrt, quaternion.y / sqrt, quaternion.z / sqrt), angle: 2 * Math.acos(quaternion.w) * radToDeg }; } }
javascript
function _getAngleAxis(quaternion) { return function() { var sqrt = Math.sqrt(1 - quaternion.w * quaternion.w); return { axis: new Vector3(quaternion.x / sqrt, quaternion.y / sqrt, quaternion.z / sqrt), angle: 2 * Math.acos(quaternion.w) * radToDeg }; } }
[ "function", "_getAngleAxis", "(", "quaternion", ")", "{", "return", "function", "(", ")", "{", "var", "sqrt", "=", "Math", ".", "sqrt", "(", "1", "-", "quaternion", ".", "w", "*", "quaternion", ".", "w", ")", ";", "return", "{", "axis", ":", "new", ...
Returns the angle axis representation for the quaternion with angle in degrees @param {Quternion} quaternion @returns {Object} angleAxis: {axis:_Vector3_, angle:_}
[ "Returns", "the", "angle", "axis", "representation", "for", "the", "quaternion", "with", "angle", "in", "degrees" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Quaternion.js#L120-L128
33,586
ViacomInc/data-point
packages/data-point/lib/reducer-types/factory.js
normalizeInput
function normalizeInput (source) { let result = ReducerList.parse(source) if (result.length === 1) { // do not create a ReducerList that only contains a single reducer result = result[0] } return result }
javascript
function normalizeInput (source) { let result = ReducerList.parse(source) if (result.length === 1) { // do not create a ReducerList that only contains a single reducer result = result[0] } return result }
[ "function", "normalizeInput", "(", "source", ")", "{", "let", "result", "=", "ReducerList", ".", "parse", "(", "source", ")", "if", "(", "result", ".", "length", "===", "1", ")", "{", "// do not create a ReducerList that only contains a single reducer", "result", ...
this is here because ReducerLists can be arrays or | separated strings @param {*} source @returns {Array<reducer>|reducer}
[ "this", "is", "here", "because", "ReducerLists", "can", "be", "arrays", "or", "|", "separated", "strings" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/reducer-types/factory.js#L39-L47
33,587
ViacomInc/data-point
packages/data-point/lib/reducer-types/resolve.js
resolveReducer
function resolveReducer (manager, accumulator, reducer) { // this conditional is here because BaseEntity#resolve // does not check that lifecycle methods are defined // before trying to resolve them if (!reducer) { return Promise.resolve(accumulator) } const isTracing = accumulator.trace const acc = isTracing ? trace.augmentAccumulatorTrace(accumulator, reducer) : accumulator const traceNode = acc.traceNode const resolve = getResolveFunction(reducer) // NOTE: recursive call let result = resolve(manager, resolveReducer, acc, reducer) if (hasDefault(reducer)) { const _default = reducer[DEFAULT_VALUE].value const resolveDefault = reducers.ReducerDefault.resolve result = result.then(acc => resolveDefault(acc, _default)) } if (isTracing) { result = result.then(trace.augmentTraceNodeDuration(traceNode)) } return result }
javascript
function resolveReducer (manager, accumulator, reducer) { // this conditional is here because BaseEntity#resolve // does not check that lifecycle methods are defined // before trying to resolve them if (!reducer) { return Promise.resolve(accumulator) } const isTracing = accumulator.trace const acc = isTracing ? trace.augmentAccumulatorTrace(accumulator, reducer) : accumulator const traceNode = acc.traceNode const resolve = getResolveFunction(reducer) // NOTE: recursive call let result = resolve(manager, resolveReducer, acc, reducer) if (hasDefault(reducer)) { const _default = reducer[DEFAULT_VALUE].value const resolveDefault = reducers.ReducerDefault.resolve result = result.then(acc => resolveDefault(acc, _default)) } if (isTracing) { result = result.then(trace.augmentTraceNodeDuration(traceNode)) } return result }
[ "function", "resolveReducer", "(", "manager", ",", "accumulator", ",", "reducer", ")", "{", "// this conditional is here because BaseEntity#resolve", "// does not check that lifecycle methods are defined", "// before trying to resolve them", "if", "(", "!", "reducer", ")", "{", ...
Applies a Reducer to an accumulator If Accumulator.trace is true it will execute tracing actions @param {Object} manager @param {Accumulator} accumulator @param {Reducer} reducer @returns {Promise<Accumulator>}
[ "Applies", "a", "Reducer", "to", "an", "accumulator" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/reducer-types/resolve.js#L57-L89
33,588
adragonite/math3d
src/Vector.js
_magnitudeOf
function _magnitudeOf(values) { var result = 0; for (var i = 0; i < values.length; i++) result += values[i] * values[i]; return Math.sqrt(result); }
javascript
function _magnitudeOf(values) { var result = 0; for (var i = 0; i < values.length; i++) result += values[i] * values[i]; return Math.sqrt(result); }
[ "function", "_magnitudeOf", "(", "values", ")", "{", "var", "result", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "result", "+=", "values", "[", "i", "]", "*", "values", "[", "i"...
Returns the magnitude of the vector Given v = (x1, x2, ... xN) magnitude is defined as n = x1 * x1 + x2 * x2 + ... + xN * xN @param {Array} values: values of the vector @returns {Number} maginitude
[ "Returns", "the", "magnitude", "of", "the", "vector" ]
37224c25bd26ca74f6ff720bf0fa91725b83ca79
https://github.com/adragonite/math3d/blob/37224c25bd26ca74f6ff720bf0fa91725b83ca79/src/Vector.js#L18-L25
33,589
ViacomInc/data-point
packages/data-point/lib/trace/trace-resolve.js
augmentAccumulatorTrace
function augmentAccumulatorTrace (accumulator, reducer) { const acc = module.exports.createTracedAccumulator(accumulator, reducer) acc.traceGraph.push(acc.traceNode) return acc }
javascript
function augmentAccumulatorTrace (accumulator, reducer) { const acc = module.exports.createTracedAccumulator(accumulator, reducer) acc.traceGraph.push(acc.traceNode) return acc }
[ "function", "augmentAccumulatorTrace", "(", "accumulator", ",", "reducer", ")", "{", "const", "acc", "=", "module", ".", "exports", ".", "createTracedAccumulator", "(", "accumulator", ",", "reducer", ")", "acc", ".", "traceGraph", ".", "push", "(", "acc", ".",...
Creates and adds new traceNode to traceGraph @param {Accumulator} accumulator current accumulator @returns {Accumulator} traced accumulator
[ "Creates", "and", "adds", "new", "traceNode", "to", "traceGraph" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point/lib/trace/trace-resolve.js#L45-L49
33,590
vfile/to-vfile
lib/async.js
read
function read(description, options, callback) { var file = vfile(description) if (!callback && typeof options === 'function') { callback = options options = null } if (!callback) { return new Promise(executor) } executor(resolve, callback) function resolve(result) { callback(null, result) } function executor(resolve, reject) { var fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.readFile(fp, options, done) function done(error, res) { if (error) { reject(error) } else { file.contents = res resolve(file) } } } }
javascript
function read(description, options, callback) { var file = vfile(description) if (!callback && typeof options === 'function') { callback = options options = null } if (!callback) { return new Promise(executor) } executor(resolve, callback) function resolve(result) { callback(null, result) } function executor(resolve, reject) { var fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.readFile(fp, options, done) function done(error, res) { if (error) { reject(error) } else { file.contents = res resolve(file) } } } }
[ "function", "read", "(", "description", ",", "options", ",", "callback", ")", "{", "var", "file", "=", "vfile", "(", "description", ")", "if", "(", "!", "callback", "&&", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", "op...
Create a virtual file and read it in, asynchronously.
[ "Create", "a", "virtual", "file", "and", "read", "it", "in", "asynchronously", "." ]
a7abc68bb48536c4ef60959a003c612599e57ad9
https://github.com/vfile/to-vfile/blob/a7abc68bb48536c4ef60959a003c612599e57ad9/lib/async.js#L11-L49
33,591
vfile/to-vfile
lib/async.js
write
function write(description, options, callback) { var file = vfile(description) // Weird, right? Otherwise `fs` doesn’t accept it. if (!callback && typeof options === 'function') { callback = options options = undefined } if (!callback) { return new Promise(executor) } executor(resolve, callback) function resolve(result) { callback(null, result) } function executor(resolve, reject) { var fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.writeFile(fp, file.contents || '', options, done) function done(error) { if (error) { reject(error) } else { resolve() } } } }
javascript
function write(description, options, callback) { var file = vfile(description) // Weird, right? Otherwise `fs` doesn’t accept it. if (!callback && typeof options === 'function') { callback = options options = undefined } if (!callback) { return new Promise(executor) } executor(resolve, callback) function resolve(result) { callback(null, result) } function executor(resolve, reject) { var fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.writeFile(fp, file.contents || '', options, done) function done(error) { if (error) { reject(error) } else { resolve() } } } }
[ "function", "write", "(", "description", ",", "options", ",", "callback", ")", "{", "var", "file", "=", "vfile", "(", "description", ")", "// Weird, right? Otherwise `fs` doesn’t accept it.", "if", "(", "!", "callback", "&&", "typeof", "options", "===", "'function...
Create a virtual file and write it out, asynchronously.
[ "Create", "a", "virtual", "file", "and", "write", "it", "out", "asynchronously", "." ]
a7abc68bb48536c4ef60959a003c612599e57ad9
https://github.com/vfile/to-vfile/blob/a7abc68bb48536c4ef60959a003c612599e57ad9/lib/async.js#L52-L90
33,592
ViacomInc/data-point
packages/data-point-service/lib/entity-cache-params.js
warnLooseParamsCacheDeprecation
function warnLooseParamsCacheDeprecation (params) { if (params.ttl || params.cacheKey || params.staleWhileRevalidate) { module.exports.looseCacheParamsDeprecationWarning() } }
javascript
function warnLooseParamsCacheDeprecation (params) { if (params.ttl || params.cacheKey || params.staleWhileRevalidate) { module.exports.looseCacheParamsDeprecationWarning() } }
[ "function", "warnLooseParamsCacheDeprecation", "(", "params", ")", "{", "if", "(", "params", ".", "ttl", "||", "params", ".", "cacheKey", "||", "params", ".", "staleWhileRevalidate", ")", "{", "module", ".", "exports", ".", "looseCacheParamsDeprecationWarning", "(...
Logs deprecation warning if loose cache params were used @param {Object} params entity's custom params
[ "Logs", "deprecation", "warning", "if", "loose", "cache", "params", "were", "used" ]
ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e
https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point-service/lib/entity-cache-params.js#L12-L16
33,593
nfroidure/knifecycle
src/index.js
_shutdownNextServices
async function _shutdownNextServices(reversedServiceSequence) { if (0 === reversedServiceSequence.length) { return; } await Promise.all( reversedServiceSequence.pop().map(async serviceName => { const singletonServiceDescriptor = await _this._pickupSingletonServiceDescriptorPromise( serviceName, ); const serviceDescriptor = singletonServiceDescriptor || (await siloContext.servicesDescriptors.get(serviceName)); let serviceShutdownPromise = _this._singletonsServicesShutdownsPromises.get(serviceName) || siloContext.servicesShutdownsPromises.get(serviceName); if (serviceShutdownPromise) { debug('Reusing a service shutdown promise:', serviceName); return serviceShutdownPromise; } if ( reversedServiceSequence.some(servicesDeclarations => servicesDeclarations.includes(serviceName), ) ) { debug('Delaying service shutdown:', serviceName); return Promise.resolve(); } if (singletonServiceDescriptor) { const handleSet = _this._singletonsServicesHandles.get( serviceName, ); handleSet.delete(siloContext.name); if (handleSet.size) { debug('Singleton is used elsewhere:', serviceName, handleSet); return Promise.resolve(); } _this._singletonsServicesDescriptors.delete(serviceName); } debug('Shutting down a service:', serviceName); serviceShutdownPromise = serviceDescriptor.dispose ? serviceDescriptor.dispose() : Promise.resolve(); if (singletonServiceDescriptor) { _this._singletonsServicesShutdownsPromises.set( serviceName, serviceShutdownPromise, ); } siloContext.servicesShutdownsPromises.set( serviceName, serviceShutdownPromise, ); return serviceShutdownPromise; }), ); await _shutdownNextServices(reversedServiceSequence); }
javascript
async function _shutdownNextServices(reversedServiceSequence) { if (0 === reversedServiceSequence.length) { return; } await Promise.all( reversedServiceSequence.pop().map(async serviceName => { const singletonServiceDescriptor = await _this._pickupSingletonServiceDescriptorPromise( serviceName, ); const serviceDescriptor = singletonServiceDescriptor || (await siloContext.servicesDescriptors.get(serviceName)); let serviceShutdownPromise = _this._singletonsServicesShutdownsPromises.get(serviceName) || siloContext.servicesShutdownsPromises.get(serviceName); if (serviceShutdownPromise) { debug('Reusing a service shutdown promise:', serviceName); return serviceShutdownPromise; } if ( reversedServiceSequence.some(servicesDeclarations => servicesDeclarations.includes(serviceName), ) ) { debug('Delaying service shutdown:', serviceName); return Promise.resolve(); } if (singletonServiceDescriptor) { const handleSet = _this._singletonsServicesHandles.get( serviceName, ); handleSet.delete(siloContext.name); if (handleSet.size) { debug('Singleton is used elsewhere:', serviceName, handleSet); return Promise.resolve(); } _this._singletonsServicesDescriptors.delete(serviceName); } debug('Shutting down a service:', serviceName); serviceShutdownPromise = serviceDescriptor.dispose ? serviceDescriptor.dispose() : Promise.resolve(); if (singletonServiceDescriptor) { _this._singletonsServicesShutdownsPromises.set( serviceName, serviceShutdownPromise, ); } siloContext.servicesShutdownsPromises.set( serviceName, serviceShutdownPromise, ); return serviceShutdownPromise; }), ); await _shutdownNextServices(reversedServiceSequence); }
[ "async", "function", "_shutdownNextServices", "(", "reversedServiceSequence", ")", "{", "if", "(", "0", "===", "reversedServiceSequence", ".", "length", ")", "{", "return", ";", "}", "await", "Promise", ".", "all", "(", "reversedServiceSequence", ".", "pop", "("...
Shutdown services in their instanciation order
[ "Shutdown", "services", "in", "their", "instanciation", "order" ]
babfd6e9ae1b37a76e2107635b183d8324774165
https://github.com/nfroidure/knifecycle/blob/babfd6e9ae1b37a76e2107635b183d8324774165/src/index.js#L504-L565
33,594
jonschlinkert/templates
lib/list.js
List
function List(options) { if (!(this instanceof List)) { return new List(options); } Base.call(this); this.is('list'); this.define('isCollection', true); this.use(utils.option()); this.use(utils.plugin()); this.init(options || {}); }
javascript
function List(options) { if (!(this instanceof List)) { return new List(options); } Base.call(this); this.is('list'); this.define('isCollection', true); this.use(utils.option()); this.use(utils.plugin()); this.init(options || {}); }
[ "function", "List", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "List", ")", ")", "{", "return", "new", "List", "(", "options", ")", ";", "}", "Base", ".", "call", "(", "this", ")", ";", "this", ".", "is", "(", "'list'", ...
Create an instance of `List` with the given `options`. Lists differ from collections in that items are stored as an array, allowing items to be paginated, sorted, and grouped. ```js var list = new List(); list.addItem('foo', {content: 'bar'}); ``` @param {Object} `options` @api public
[ "Create", "an", "instance", "of", "List", "with", "the", "given", "options", ".", "Lists", "differ", "from", "collections", "in", "that", "items", "are", "stored", "as", "an", "array", "allowing", "items", "to", "be", "paginated", "sorted", "and", "grouped",...
f030d2c2906ea9a703868f83574151badb427573
https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/list.js#L29-L41
33,595
jonschlinkert/templates
lib/list.js
decorate
function decorate(list, method, prop) { utils.define(list.items, method, function() { var res = list[method].apply(list, arguments); return prop ? res[prop] : res; }); }
javascript
function decorate(list, method, prop) { utils.define(list.items, method, function() { var res = list[method].apply(list, arguments); return prop ? res[prop] : res; }); }
[ "function", "decorate", "(", "list", ",", "method", ",", "prop", ")", "{", "utils", ".", "define", "(", "list", ".", "items", ",", "method", ",", "function", "(", ")", "{", "var", "res", "=", "list", "[", "method", "]", ".", "apply", "(", "list", ...
Helper function for decorating methods onto the `list.items` array
[ "Helper", "function", "for", "decorating", "methods", "onto", "the", "list", ".", "items", "array" ]
f030d2c2906ea9a703868f83574151badb427573
https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/list.js#L558-L563
33,596
jonschlinkert/templates
lib/plugins/layout.js
handleLayout
function handleLayout(obj, stats, depth) { var layoutName = obj.layout.basename; debug('applied layout (#%d) "%s", to file "%s"', depth, layoutName, file.path); file.currentLayout = obj.layout; file.define('layoutStack', stats.history); app.handleOnce('onLayout', file); delete file.currentLayout; }
javascript
function handleLayout(obj, stats, depth) { var layoutName = obj.layout.basename; debug('applied layout (#%d) "%s", to file "%s"', depth, layoutName, file.path); file.currentLayout = obj.layout; file.define('layoutStack', stats.history); app.handleOnce('onLayout', file); delete file.currentLayout; }
[ "function", "handleLayout", "(", "obj", ",", "stats", ",", "depth", ")", "{", "var", "layoutName", "=", "obj", ".", "layout", ".", "basename", ";", "debug", "(", "'applied layout (#%d) \"%s\", to file \"%s\"'", ",", "depth", ",", "layoutName", ",", "file", "."...
Handle each layout before it's applied to a file
[ "Handle", "each", "layout", "before", "it", "s", "applied", "to", "a", "file" ]
f030d2c2906ea9a703868f83574151badb427573
https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/plugins/layout.js#L121-L129
33,597
jonschlinkert/templates
lib/plugins/layout.js
buildStack
function buildStack(app, name, view) { var layoutExists = false; var registered = 0; var layouts = {}; // get all collections with `viewType` layout var collections = app.viewTypes.layout; var len = collections.length; var idx = -1; while (++idx < len) { var collection = app[collections[idx]]; // detect if at least one of the collections has // our starting layout if (!layoutExists && collection.getView(name)) { layoutExists = true; } // add the collection views to the layouts object for (var key in collection.views) { layouts[key] = collection.views[key]; registered++; } } if (registered === 0) { throw app.formatError('layouts', 'registered', name, view); } if (layoutExists === false) { throw app.formatError('layouts', 'notfound', name, view); } return layouts; }
javascript
function buildStack(app, name, view) { var layoutExists = false; var registered = 0; var layouts = {}; // get all collections with `viewType` layout var collections = app.viewTypes.layout; var len = collections.length; var idx = -1; while (++idx < len) { var collection = app[collections[idx]]; // detect if at least one of the collections has // our starting layout if (!layoutExists && collection.getView(name)) { layoutExists = true; } // add the collection views to the layouts object for (var key in collection.views) { layouts[key] = collection.views[key]; registered++; } } if (registered === 0) { throw app.formatError('layouts', 'registered', name, view); } if (layoutExists === false) { throw app.formatError('layouts', 'notfound', name, view); } return layouts; }
[ "function", "buildStack", "(", "app", ",", "name", ",", "view", ")", "{", "var", "layoutExists", "=", "false", ";", "var", "registered", "=", "0", ";", "var", "layouts", "=", "{", "}", ";", "// get all collections with `viewType` layout", "var", "collections",...
Get the layout stack by creating an object from all collections with the "layout" `viewType` @param {Object} `app` @param {String} `name` The starting layout name @param {Object} `view` @return {Object} Returns the layout stack.
[ "Get", "the", "layout", "stack", "by", "creating", "an", "object", "from", "all", "collections", "with", "the", "layout", "viewType" ]
f030d2c2906ea9a703868f83574151badb427573
https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/plugins/layout.js#L165-L199
33,598
jonschlinkert/templates
lib/collection.js
Collection
function Collection(options) { if (!(this instanceof Collection)) { return new Collection(options); } Base.call(this, {}, options); this.is('Collection'); this.items = {}; this.use(utils.option()); this.use(utils.plugin()); this.init(options || {}); }
javascript
function Collection(options) { if (!(this instanceof Collection)) { return new Collection(options); } Base.call(this, {}, options); this.is('Collection'); this.items = {}; this.use(utils.option()); this.use(utils.plugin()); this.init(options || {}); }
[ "function", "Collection", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Collection", ")", ")", "{", "return", "new", "Collection", "(", "options", ")", ";", "}", "Base", ".", "call", "(", "this", ",", "{", "}", ",", "options",...
Create an instance of `Collection` with the given `options`. ```js var collection = new Collection(); collection.addItem('foo', {content: 'bar'}); ``` @param {Object} `options` @api public
[ "Create", "an", "instance", "of", "Collection", "with", "the", "given", "options", "." ]
f030d2c2906ea9a703868f83574151badb427573
https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/collection.js#L25-L37
33,599
jonschlinkert/templates
index.js
Templates
function Templates(options) { if (!(this instanceof Templates)) { return new Templates(options); } Base.call(this, null, options); this.is('templates'); this.define('isApp', true); this.use(utils.option()); this.use(utils.plugin()); this.initTemplates(); }
javascript
function Templates(options) { if (!(this instanceof Templates)) { return new Templates(options); } Base.call(this, null, options); this.is('templates'); this.define('isApp', true); this.use(utils.option()); this.use(utils.plugin()); this.initTemplates(); }
[ "function", "Templates", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Templates", ")", ")", "{", "return", "new", "Templates", "(", "options", ")", ";", "}", "Base", ".", "call", "(", "this", ",", "null", ",", "options", ")",...
This function is the main export of the templates module. Initialize an instance of `templates` to create your application. ```js var templates = require('templates'); var app = templates(); ``` @param {Object} `options` @api public
[ "This", "function", "is", "the", "main", "export", "of", "the", "templates", "module", ".", "Initialize", "an", "instance", "of", "templates", "to", "create", "your", "application", "." ]
f030d2c2906ea9a703868f83574151badb427573
https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/index.js#L36-L47