repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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 | train |
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'",
")",
"?",
"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",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | 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 | train |
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'",
")",
";",
"}",
")",
";",
"return",
"gulp",
".",
"src",
"(",
"'test/fixtures/*.coffee'",
")",
".",
"pipe",
"(",
"coffee",
"(",
")",
")",
".",
"pipe",
"(",
"concat",
"(",
"'fn.js'",
")",
")",
".",
"pipe",
"(",
"dest",
")",
";",
"}"
] | 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 | train |
|
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",
")",
"{",
"RED",
".",
"nodes",
".",
"createNode",
"(",
"this",
",",
"n",
")",
";",
"var",
"node",
"=",
"this",
";",
"node",
".",
"options",
"=",
"{",
"}",
";",
"node",
".",
"options",
".",
"name",
"=",
"n",
".",
"name",
";",
"node",
".",
"options",
".",
"port",
"=",
"n",
".",
"port",
";",
"node",
".",
"_inputNodes",
"=",
"[",
"]",
";",
"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",
"(",
")",
"{",
"node",
".",
"log",
"(",
"'CoAP Server Started'",
")",
";",
"}",
")",
";",
"node",
".",
"on",
"(",
"\"close\"",
",",
"function",
"(",
")",
"{",
"node",
".",
"_inputNodes",
"=",
"[",
"]",
";",
"node",
".",
"server",
".",
"close",
"(",
")",
";",
"}",
")",
";",
"}"
] | 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 | train |
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",
"(",
"new",
"Option",
"(",
"Message",
".",
"Option",
".",
"URI_PATH",
",",
"new",
"Buffer",
"(",
"\"s\"",
")",
")",
")",
";",
"msg",
".",
"addOption",
"(",
"new",
"Option",
"(",
"Message",
".",
"Option",
".",
"URI_QUERY",
",",
"b",
")",
")",
";",
"return",
"msg",
";",
"}",
";",
"}"
] | 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 | train |
|
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",
")",
"stream",
".",
"on",
"(",
"'data'",
",",
"onData",
")",
"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",
"]",
")",
"}",
"}",
"}",
"}"
] | 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 | train |
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",
")",
";",
"}",
"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",
"(",
")",
";",
"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",
"(",
")",
";",
"}",
"}",
"else",
"{",
"logger",
".",
"log",
"(",
"'msg object had no getPayload fn'",
")",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"logger",
".",
"log",
"(",
"'error while parsing hello payload '",
",",
"ex",
")",
";",
"}",
"this",
".",
"stage",
"++",
";",
"this",
".",
"nextStep",
"(",
")",
";",
"}"
] | 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 | train |
|
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",
"(",
")",
"{",
"this",
".",
"client",
".",
"secureOut",
"=",
"this",
".",
"secureOut",
";",
"this",
".",
"client",
".",
"sendCounter",
"=",
"CryptoLib",
".",
"getRandomUINT16",
"(",
")",
";",
"this",
".",
"client",
".",
"sendMessage",
"(",
"\"Hello\"",
",",
"{",
"}",
",",
"null",
",",
"null",
")",
";",
"this",
".",
"stage",
"++",
";",
"this",
".",
"nextStep",
"(",
")",
";",
"}"
] | 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 | train |
|
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",
")",
";",
"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",
"(",
")",
";",
"}"
] | 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 | train |
|
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",
".",
"getHexCoreID",
"(",
")",
"}",
")",
";",
"return",
";",
"}",
"this",
".",
"_lastMessageTime",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"msgCode",
"=",
"msg",
".",
"getCode",
"(",
")",
";",
"if",
"(",
"(",
"msgCode",
">",
"Message",
".",
"Code",
".",
"EMPTY",
")",
"&&",
"(",
"msgCode",
"<=",
"Message",
".",
"Code",
".",
"DELETE",
")",
")",
"{",
"msg",
".",
"_type",
"=",
"messages",
".",
"getRequestType",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"!",
"msg",
".",
"_type",
")",
"{",
"msg",
".",
"_type",
"=",
"this",
".",
"getResponseType",
"(",
"msg",
".",
"getTokenString",
"(",
")",
")",
";",
"}",
"if",
"(",
"msg",
".",
"isAcknowledgement",
"(",
")",
")",
"{",
"if",
"(",
"!",
"msg",
".",
"_type",
")",
"{",
"msg",
".",
"_type",
"=",
"'PingAck'",
";",
"}",
"this",
".",
"emit",
"(",
"(",
"'msg_'",
"+",
"msg",
".",
"_type",
")",
".",
"toLowerCase",
"(",
")",
",",
"msg",
")",
";",
"return",
";",
"}",
"var",
"nextPeerCounter",
"=",
"++",
"this",
".",
"recvCounter",
";",
"if",
"(",
"nextPeerCounter",
">",
"65535",
")",
"{",
"this",
".",
"recvCounter",
"=",
"nextPeerCounter",
"=",
"0",
";",
"}",
"if",
"(",
"msg",
".",
"isEmpty",
"(",
")",
"&&",
"msg",
".",
"isConfirmable",
"(",
")",
")",
"{",
"this",
".",
"_lastCorePing",
"=",
"new",
"Date",
"(",
")",
";",
"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\"",
")",
"{",
"this",
".",
"disconnect",
"(",
"\"Got an Ignore\"",
")",
";",
"return",
";",
"}",
"this",
".",
"disconnect",
"(",
"\"Bad Counter\"",
")",
";",
"return",
";",
"}",
"this",
".",
"emit",
"(",
"(",
"'msg_'",
"+",
"msg",
".",
"_type",
")",
".",
"toLowerCase",
"(",
")",
",",
"msg",
")",
";",
"}"
] | 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 | train |
|
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",
".",
"showVerboseCoreLogs",
";",
"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",
"(",
")",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"this",
".",
"on",
"(",
"evtName",
",",
"handler",
")",
";",
"return",
"handler",
";",
"}"
] | 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 | train |
|
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",
"(",
"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",
"(",
")",
")",
"{",
"performRequest",
"(",
")",
";",
"}",
"else",
"{",
"when",
"(",
"this",
".",
"ensureWeHaveIntrospectionData",
"(",
")",
")",
".",
"then",
"(",
"performRequest",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"null",
",",
"null",
",",
"\"Problem requesting variable: \"",
"+",
"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
@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 | train |
|
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",
")",
";",
"var",
"token",
"=",
"this",
".",
"sendMessage",
"(",
"\"RaiseYourHand\"",
",",
"{",
"_writeCoapUri",
":",
"messages",
".",
"raiseYourHandUrlGenerator",
"(",
"showSignal",
")",
"}",
",",
"null",
")",
";",
"this",
".",
"listenFor",
"(",
"\"RaiseYourHandReturn\"",
",",
"null",
",",
"token",
",",
"function",
"(",
")",
"{",
"clearTimeout",
"(",
"timer",
")",
";",
"callback",
"(",
"true",
")",
";",
"}",
",",
"true",
")",
";",
"}"
] | 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 | train |
|
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",
"(",
")",
"{",
"var",
"buf",
"=",
"that",
".",
"_transformArguments",
"(",
"name",
",",
"args",
")",
";",
"if",
"(",
"buf",
")",
"{",
"ready",
".",
"resolve",
"(",
"buf",
")",
";",
"}",
"else",
"{",
"ready",
".",
"reject",
"(",
"\"Unknown Function: \"",
"+",
"name",
")",
";",
"}",
"}",
",",
"function",
"(",
"msg",
")",
"{",
"ready",
".",
"reject",
"(",
"msg",
")",
";",
"}",
")",
";",
"return",
"ready",
".",
"promise",
";",
"}"
] | 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 | train |
|
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\"",
";",
"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",
";",
"}"
] | 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 | train |
|
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",
")",
"{",
"if",
"(",
"!",
"args",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"this",
".",
"hasFnState",
"(",
")",
")",
"{",
"logger",
".",
"error",
"(",
"\"_transformArguments called without any function state!\"",
",",
"{",
"coreID",
":",
"this",
".",
"getHexCoreID",
"(",
")",
"}",
")",
";",
"return",
"null",
";",
"}",
"name",
"=",
"name",
".",
"toLowerCase",
"(",
")",
";",
"var",
"fn",
"=",
"this",
".",
"coreFnState",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"fn",
"||",
"!",
"fn",
".",
"args",
")",
"{",
"var",
"f",
"=",
"this",
".",
"coreFnState",
".",
"f",
";",
"if",
"(",
"f",
"&&",
"utilities",
".",
"arrayContainsLower",
"(",
"f",
",",
"name",
")",
")",
"{",
"fn",
"=",
"{",
"returns",
":",
"\"int\"",
",",
"args",
":",
"[",
"[",
"null",
",",
"\"string\"",
"]",
"]",
"}",
";",
"}",
"}",
"if",
"(",
"!",
"fn",
"||",
"!",
"fn",
".",
"args",
")",
"{",
"return",
"null",
";",
"}",
"return",
"messages",
".",
"buildArguments",
"(",
"args",
",",
"fn",
".",
"args",
")",
";",
"}"
] | 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 | train |
|
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",
"(",
"!",
"this",
".",
"_describeDfd",
")",
"{",
"this",
".",
"sendMessage",
"(",
"\"Describe\"",
")",
";",
"this",
".",
"_describeDfd",
"=",
"when",
".",
"defer",
"(",
")",
";",
"}",
"return",
"this",
".",
"_describeDfd",
".",
"promise",
";",
"}"
] | 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 | train |
|
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",
")",
"{",
"var",
"loaded",
"=",
"(",
"this",
".",
"loadFnState",
"(",
"msg",
".",
"getPayload",
"(",
")",
")",
")",
";",
"if",
"(",
"this",
".",
"_describeDfd",
")",
"{",
"if",
"(",
"loaded",
")",
"{",
"this",
".",
"_describeDfd",
".",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"this",
".",
"_describeDfd",
".",
"reject",
"(",
"\"something went wrong parsing function state\"",
")",
"}",
"}",
"}"
] | 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 | train |
|
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",
")",
"{",
"var",
"stamp",
"=",
"moment",
"(",
")",
".",
"utc",
"(",
")",
".",
"unix",
"(",
")",
";",
"var",
"binVal",
"=",
"messages",
".",
"ToBinary",
"(",
"stamp",
",",
"\"uint32\"",
")",
";",
"this",
".",
"sendReply",
"(",
"\"GetTimeReturn\"",
",",
"msg",
".",
"getId",
"(",
")",
",",
"binVal",
",",
"msg",
".",
"getToken",
"(",
")",
")",
";",
"}"
] | 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 | train |
|
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",
"&&",
"(",
"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",
")",
";",
"}"
] | 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 | train |
|
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",
"=",
"null",
";",
"this",
".",
"clearWatch",
"(",
"\"CompleteTransfer\"",
")",
";",
"this",
".",
"stage",
"=",
"Flasher",
".",
"stages",
".",
"TEARDOWN",
";",
"this",
".",
"nextStep",
"(",
")",
";",
"}"
] | 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 | train |
|
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",
"[",
"name",
"]",
")",
";",
"delete",
"this",
".",
"_timers",
"[",
"name",
"]",
";",
"}",
"else",
"{",
"this",
".",
"_timers",
"[",
"name",
"]",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"\"failed waiting on \"",
"+",
"name",
")",
";",
"}",
"}",
",",
"seconds",
"*",
"1000",
")",
";",
"}",
"}"
] | 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 | train |
|
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",
")",
";",
"logger",
".",
"error",
"(",
"ex",
".",
"stack",
")",
";",
"logger",
".",
"log",
"(",
"'error bubbled up '",
"+",
"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 | train |
|
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",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"continue",
";",
"}",
"matches",
"&=",
"(",
"left",
"[",
"prop",
"]",
"==",
"right",
"[",
"prop",
"]",
")",
";",
"}",
"return",
"matches",
";",
"}"
] | 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 | train |
|
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",
"(",
"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",
";",
"}"
] | 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 | train |
|
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",
"{",
"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",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"process",
".",
"nextTick",
"(",
"doNext",
")",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"logger",
".",
"error",
"(",
"\"pdas error: \"",
"+",
"ex",
")",
";",
"}",
"}",
";",
"process",
".",
"nextTick",
"(",
"doNext",
")",
";",
"return",
"tmp",
".",
"promise",
";",
"}"
] | 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 | train |
|
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",
"++",
")",
"{",
"val",
"=",
"b",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"if",
"(",
"has",
"(",
"a",
",",
"val",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | contains any of... | [
"contains",
"any",
"of",
"..."
] | 550c3e1f73e61587cabc1f28eb75f4c2264f138c | https://github.com/chjj/tiny/blob/550c3e1f73e61587cabc1f28eb75f4c2264f138c/lib/tiny.json.js#L1011-L1023 | train |
|
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",
";",
"i",
"++",
")",
"{",
"val",
"=",
"b",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"if",
"(",
"has",
"(",
"a",
",",
"val",
")",
")",
"found",
"++",
";",
"}",
"return",
"found",
"===",
"l",
";",
"}"
] | contains all... | [
"contains",
"all",
"..."
] | 550c3e1f73e61587cabc1f28eb75f4c2264f138c | https://github.com/chjj/tiny/blob/550c3e1f73e61587cabc1f28eb75f4c2264f138c/lib/tiny.json.js#L1029-L1042 | train |
|
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",
")",
"{",
"const",
"match",
"=",
"regexp",
".",
"exec",
"(",
"tag",
")",
";",
"if",
"(",
"match",
")",
"{",
"attributes",
".",
"push",
"(",
"{",
"key",
":",
"match",
"[",
"1",
"]",
",",
"value",
":",
"match",
"[",
"2",
"]",
"}",
")",
"}",
"else",
"{",
"running",
"=",
"false",
";",
"}",
"}",
"return",
"attributes",
";",
"}"
] | 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 | train |
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",
"]",
"[",
"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",
"(",
"`",
"`",
")",
")",
".",
"message",
")",
";",
"}",
"else",
"{",
"gutil",
".",
"log",
"(",
"`",
"${",
"pluginName",
"}",
"`",
",",
"new",
"gutil",
".",
"PluginError",
"(",
"pluginName",
",",
"gutil",
".",
"colors",
".",
"red",
"(",
"`",
"${",
"options",
".",
"basePath",
"+",
"sourcePath",
"}",
"`",
")",
")",
".",
"message",
")",
";",
"}",
"return",
"replaceAttributes",
"(",
"file",
",",
"splitAttr",
"[",
"1",
"]",
")",
";",
"}"
] | 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 | train |
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",
"+",
"attrObj",
".",
"key",
",",
"attrObj",
".",
"value",
")",
",",
"file",
"&&",
"file",
".",
"toString",
"(",
")",
"||",
"''",
")",
";",
"}"
] | 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 | train |
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",
"=",
"{",
"}",
"glob",
".",
"sync",
"(",
"PAGE_PATH",
"+",
"'/*/main.js'",
")",
".",
"forEach",
"(",
"filePath",
"=>",
"{",
"const",
"pageName",
"=",
"path",
".",
"basename",
"(",
"path",
".",
"dirname",
"(",
"filePath",
")",
")",
"if",
"(",
"entry",
"&&",
"entry",
"!==",
"pageName",
")",
"return",
"pages",
"[",
"pageName",
"]",
"=",
"{",
"entry",
":",
"filePath",
",",
"fileName",
":",
"`",
"${",
"pageName",
"===",
"'index'",
"?",
"''",
":",
"pageName",
"+",
"'/'",
"}",
"`",
",",
"template",
":",
"path",
".",
"dirname",
"(",
"filePath",
")",
"+",
"'/index.html'",
",",
"chunks",
":",
"[",
"'vue-common'",
",",
"'iview'",
",",
"'echarts'",
",",
"'vendors'",
",",
"'manifest'",
",",
"pageName",
"]",
"}",
"}",
")",
"return",
"pages",
"}"
] | 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 | train |
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",
"(",
"allowedMethods",
")",
".",
"join",
"(",
"','",
")",
")",
";",
"let",
"params",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"req",
".",
"params",
"||",
"{",
"}",
")",
";",
"delete",
"params",
".",
"service",
";",
"delete",
"params",
".",
"id",
";",
"delete",
"params",
".",
"subresources",
";",
"delete",
"params",
"[",
"0",
"]",
";",
"req",
".",
"feathers",
"=",
"{",
"provider",
":",
"'rest'",
"}",
";",
"let",
"query",
"=",
"req",
".",
"query",
"||",
"{",
"}",
";",
"let",
"headers",
"=",
"fp",
".",
"dissoc",
"(",
"'cookie'",
",",
"req",
".",
"headers",
"||",
"{",
"}",
")",
";",
"let",
"cookies",
"=",
"req",
".",
"cookies",
"||",
"{",
"}",
";",
"params",
"=",
"Object",
".",
"assign",
"(",
"{",
"query",
",",
"headers",
"}",
",",
"params",
",",
"req",
".",
"feathers",
")",
";",
"if",
"(",
"req",
".",
"file",
")",
"{",
"params",
".",
"file",
"=",
"req",
".",
"file",
";",
"}",
"if",
"(",
"(",
"method",
"===",
"'update'",
"||",
"method",
"===",
"'patch'",
")",
"&&",
"params",
".",
"query",
".",
"$method",
"&&",
"params",
".",
"query",
".",
"$method",
".",
"toLowerCase",
"(",
")",
"===",
"'patch'",
")",
"{",
"method",
"=",
"'patch'",
"delete",
"params",
".",
"query",
".",
"$method",
"}",
"const",
"[",
"service",
",",
"...",
"args",
"]",
"=",
"getArgs",
"(",
"req",
",",
"res",
",",
"next",
")",
";",
"debug",
"(",
"`",
"\\'",
"${",
"service",
"}",
"\\'",
"`",
",",
"{",
"cmd",
":",
"method",
",",
"path",
":",
"req",
".",
"path",
",",
"}",
")",
";",
"const",
"callback",
"=",
"function",
"(",
"err",
",",
"data",
")",
"{",
"debug",
"(",
"`",
"${",
"service",
"}",
"${",
"method",
"}",
"`",
",",
"err",
"||",
"{",
"status",
":",
"data",
"&&",
"data",
".",
"status",
",",
"size",
":",
"data",
"&&",
"JSON",
".",
"stringify",
"(",
"data",
")",
".",
"length",
"}",
")",
";",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
".",
"cause",
"||",
"err",
")",
";",
"res",
".",
"data",
"=",
"data",
";",
"if",
"(",
"!",
"data",
")",
"{",
"debug",
"(",
"`",
"${",
"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",
")",
";",
"}",
";",
"}"
] | 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 | train |
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",
",",
"node_ver",
":",
"process",
".",
"versions",
".",
"node",
",",
"timestamp",
":",
"Date",
".",
"now",
"(",
")",
",",
"hostname",
":",
"os",
".",
"hostname",
"(",
")",
",",
"uptime",
":",
"process",
".",
"uptime",
"(",
")",
",",
"loadavg",
":",
"os",
".",
"loadavg",
"(",
")",
"[",
"0",
"]",
"}",
";",
"cb",
"(",
"null",
",",
"data",
")",
";",
"}"
] | Get system informaton
@param {Function} cb | [
"Get",
"system",
"informaton"
] | 49eee19a5c29f1b2e456461162acca31e110843f | https://github.com/MostlyJS/mostly-feathers-rest/blob/49eee19a5c29f1b2e456461162acca31e110843f/src/ping.js#L23-L37 | train |
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",
")",
".",
"value",
"(",
")",
"}"
] | 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 | train |
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",
"=",
"{",
"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",
"}"
] | 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 | train |
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",
".",
"get",
"(",
"char",
")",
"||",
"1",
"characters",
"+=",
"size",
"}",
")",
"if",
"(",
"replaceByChar",
"!==",
"' '",
")",
"characters",
"=",
"characters",
"/",
"charSizes",
".",
"get",
"(",
"replaceByChar",
")",
"return",
"Math",
".",
"round",
"(",
"characters",
")",
"}"
] | 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",
"displayed",
"in",
"monospace",
"font",
"."
] | 30607ce682d0ea79d5ebc30f02ac918b48ca3507 | https://github.com/MikeKovarik/rollup-plugin-notify/blob/30607ce682d0ea79d5ebc30f02ac918b48ca3507/index.js#L47-L59 | train |
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",
")",
"{",
"lines",
"=",
"stripAnsi",
"(",
"frame",
")",
".",
"replace",
"(",
"/",
"\\r",
"/",
"g",
",",
"''",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"map",
"(",
"l",
"=>",
"l",
".",
"replace",
"(",
"/",
"\\t",
"/",
"g",
",",
"' '",
")",
")",
"var",
"leftCaretLine",
"=",
"lines",
".",
"find",
"(",
"l",
"=>",
"l",
".",
"startsWith",
"(",
"'>'",
")",
")",
"if",
"(",
"leftCaretLine",
")",
"{",
"lines",
"[",
"lines",
".",
"indexOf",
"(",
"leftCaretLine",
")",
"]",
"=",
"leftCaretLine",
".",
"replace",
"(",
"'>'",
",",
"' '",
")",
"}",
"while",
"(",
"lines",
".",
"find",
"(",
"l",
"=>",
"!",
"l",
".",
"startsWith",
"(",
"' '",
")",
")",
"==",
"undefined",
")",
"{",
"lines",
"=",
"lines",
".",
"map",
"(",
"l",
"=>",
"l",
".",
"slice",
"(",
"1",
")",
")",
"}",
"}"
] | Babel is the worst offender. | [
"Babel",
"is",
"the",
"worst",
"offender",
"."
] | 30607ce682d0ea79d5ebc30f02ac918b48ca3507 | https://github.com/MikeKovarik/rollup-plugin-notify/blob/30607ce682d0ea79d5ebc30f02ac918b48ca3507/index.js#L62-L79 | train |
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'",
")",
"{",
"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",
"}"
] | 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 | train |
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",
".",
"path",
")",
",",
"options",
")",
"return",
"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 | train |
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",
".",
"contents",
"||",
"''",
",",
"options",
")",
"}"
] | 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 | train |
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 | train |
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",
".",
"privateKey",
";",
"this",
".",
"cert",
"=",
"this",
".",
"createCertificate",
"(",
"certparams",
")",
";",
"this",
".",
"keycred",
"=",
"null",
";",
"this",
".",
"digest",
"=",
"null",
";",
"}"
] | 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 | train |
|
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",
")",
"{",
"if",
"(",
"now",
"-",
"entry",
".",
"created",
">",
"entry",
".",
"ttl",
")",
"{",
"forDeletion",
".",
"push",
"(",
"key",
")",
"}",
"}",
"const",
"forDeletionLength",
"=",
"forDeletion",
".",
"length",
"if",
"(",
"forDeletionLength",
"===",
"0",
")",
"{",
"return",
"0",
"}",
"debug",
"(",
"`",
"${",
"forDeletion",
"}",
"`",
")",
"forDeletion",
".",
"forEach",
"(",
"key",
"=>",
"store",
".",
"delete",
"(",
"key",
")",
")",
"return",
"forDeletionLength",
"}"
] | 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 | train |
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",
")",
"return",
"!",
"!",
"entry",
"&&",
"Date",
".",
"now",
"(",
")",
"-",
"entry",
".",
"created",
"<",
"entry",
".",
"ttl",
"}"
] | 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 | train |
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",
",",
"accumulator",
".",
"entityOverrides",
"[",
"entity",
".",
"entityType",
"]",
".",
"params",
")",
"}",
"return",
"entity",
".",
"params",
"}"
] | 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 | train |
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",
"=",
"errorInfoCb",
"(",
"id",
")",
"const",
"e",
"=",
"new",
"Error",
"(",
"errorInfo",
".",
"message",
")",
"e",
".",
"name",
"=",
"errorInfo",
".",
"name",
"throw",
"e",
"}",
"return",
"value",
"}"
] | 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 | train |
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",
")",
"===",
"currentEntryKey",
"}"
] | 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 | train |
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",
")",
"{",
"const",
"{",
"resolveStaleWhileRevalidate",
",",
"isRevalidatingCacheKey",
",",
"shouldTriggerRevalidate",
",",
"revalidateEntry",
"}",
"=",
"module",
".",
"exports",
"if",
"(",
"isRevalidatingCacheKey",
"(",
"ctx",
",",
"entryKey",
")",
")",
"{",
"return",
"undefined",
"}",
"const",
"staleWhileRevalidate",
"=",
"resolveStaleWhileRevalidate",
"(",
"service",
")",
"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",
")",
")",
"{",
"revalidateEntry",
"(",
"service",
",",
"entryKey",
",",
"cache",
",",
"ctx",
")",
"}",
"return",
"staleEntry",
"}",
")",
"}"
] | 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",
"chain",
"."
] | ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e | https://github.com/ViacomInc/data-point/blob/ac8668ed2b9a81c2df17a40d42c62e71eed4ff3e/packages/data-point-service/lib/cache-middleware.js#L190-L230 | train |
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",
")",
"{",
"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",
"&&",
"(",
"d",
"in",
"a",
"||",
"(",
"a",
"[",
"d",
"]",
"=",
"function",
"(",
"b",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"c",
"=",
"new",
"a",
";",
"return",
"c",
"[",
"b",
"]",
".",
"apply",
"(",
"c",
",",
"arguments",
")",
"}",
"}",
"(",
"b",
")",
",",
"l",
"(",
"a",
",",
"d",
",",
"b",
")",
")",
",",
"d",
"in",
"a",
".",
"prototype",
"||",
"l",
"(",
"a",
".",
"prototype",
",",
"b",
",",
"d",
")",
")",
"}",
"return",
"a",
"}"
] | 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 | train |
|
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 | train |
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",
".",
"inverse",
"(",
")",
".",
"mulVector3",
"(",
"transform",
".",
"position",
".",
"sub",
"(",
"transform",
".",
"parent",
".",
"position",
")",
")",
";",
"}"
] | 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 | train |
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",
".",
"add",
"(",
"transform",
".",
"parent",
".",
"rotation",
".",
"mulVector3",
"(",
"transform",
".",
"localPosition",
")",
")",
";",
"}"
] | 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 | train |
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",
".",
"inverse",
"(",
")",
".",
"mul",
"(",
"transform",
".",
"rotation",
")",
";",
"}"
] | 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 | train |
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",
".",
"mul",
"(",
"transform",
".",
"localRotation",
")",
";",
"}"
] | 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 | train |
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",
"=",
"_getWorldPositionFromLocalPosition",
"(",
"child",
")",
";",
"}",
")",
";",
"}"
] | 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 | train |
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 | train |
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 | train |
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 | train |
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",
"=>",
"{",
"const",
"{",
"lastActiveTime",
",",
"status",
"}",
"=",
"entries",
"[",
"page",
"]",
";",
"if",
"(",
"status",
"!==",
"BUILT",
")",
"return",
";",
"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",
"(",
"`",
"${",
"disposingPages",
".",
"join",
"(",
"', '",
")",
"}",
"`",
")",
";",
"devMiddleware",
".",
"invalidate",
"(",
")",
";",
"}",
"}"
] | 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 | train |
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",
"(",
"accumulator",
",",
"specOptions",
")",
".",
"then",
"(",
"acc",
"=>",
"{",
"const",
"options",
"=",
"getRequestOptions",
"(",
"url",
",",
"acc",
".",
"value",
")",
"return",
"utils",
".",
"assign",
"(",
"accumulator",
",",
"{",
"options",
"}",
")",
"}",
")",
"}"
] | 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 | train |
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 | train |
|
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",
".",
"bind",
"(",
"null",
",",
"cache",
")",
"return",
"cache",
"}"
] | 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 | train |
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",
"(",
"[",
"]",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"matrix",
".",
"size",
".",
"columns",
";",
"j",
"++",
")",
"rows",
"[",
"i",
"]",
".",
"push",
"(",
"matrix",
".",
"values",
"[",
"matrix",
".",
"size",
".",
"columns",
"*",
"i",
"+",
"j",
"]",
")",
";",
"}",
"return",
"rows",
";",
"}"
] | 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 | train |
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",
"(",
"[",
"]",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"matrix",
".",
"size",
".",
"rows",
";",
"j",
"++",
")",
"cols",
"[",
"i",
"]",
".",
"push",
"(",
"matrix",
".",
"values",
"[",
"i",
"+",
"j",
"*",
"matrix",
".",
"size",
".",
"columns",
"]",
")",
";",
"}",
"return",
"cols",
";",
"}"
] | 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 | train |
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 | train |
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",
"[",
"3",
"]",
")",
";",
"}"
] | 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 | train |
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",
"(",
"magnitude",
"===",
"0",
")",
"return",
"this",
";",
"return",
"{",
"\"x\"",
":",
"x",
"/",
"magnitude",
",",
"\"y\"",
":",
"y",
"/",
"magnitude",
",",
"\"z\"",
":",
"z",
"/",
"magnitude",
",",
"\"w\"",
":",
"w",
"/",
"magnitude",
"}",
";",
"}"
] | 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 | train |
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",
"(",
"axis",
".",
"x",
"*",
"s",
",",
"axis",
".",
"y",
"*",
"s",
",",
"axis",
".",
"z",
"*",
"s",
",",
"c",
")",
";",
"}"
] | 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 | train |
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",
"Vector3",
"(",
"quaternion",
".",
"x",
"/",
"sqrt",
",",
"quaternion",
".",
"y",
"/",
"sqrt",
",",
"quaternion",
".",
"z",
"/",
"sqrt",
")",
",",
"angle",
":",
"2",
"*",
"Math",
".",
"acos",
"(",
"quaternion",
".",
"w",
")",
"*",
"radToDeg",
"}",
";",
"}",
"}"
] | 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 | train |
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",
")",
"{",
"result",
"=",
"result",
"[",
"0",
"]",
"}",
"return",
"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 | train |
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",
")",
"{",
"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",
")",
"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",
"}"
] | 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 | train |
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",
"]",
";",
"return",
"Math",
".",
"sqrt",
"(",
"result",
")",
";",
"}"
] | 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 | train |
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",
".",
"traceNode",
")",
"return",
"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 | train |
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",
"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",
")",
"}",
"}",
"}",
"}"
] | 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 | train |
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",
")",
"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",
"(",
")",
"}",
"}",
"}",
"}"
] | 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 | train |
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 | train |
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",
"(",
")",
".",
"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",
")",
";",
"}"
] | 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 | train |
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'",
")",
";",
"this",
".",
"define",
"(",
"'isCollection'",
",",
"true",
")",
";",
"this",
".",
"use",
"(",
"utils",
".",
"option",
"(",
")",
")",
";",
"this",
".",
"use",
"(",
"utils",
".",
"plugin",
"(",
")",
")",
";",
"this",
".",
"init",
"(",
"options",
"||",
"{",
"}",
")",
";",
"}"
] | 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 | train |
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",
",",
"arguments",
")",
";",
"return",
"prop",
"?",
"res",
"[",
"prop",
"]",
":",
"res",
";",
"}",
")",
";",
"}"
] | 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 | train |
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",
".",
"path",
")",
";",
"file",
".",
"currentLayout",
"=",
"obj",
".",
"layout",
";",
"file",
".",
"define",
"(",
"'layoutStack'",
",",
"stats",
".",
"history",
")",
";",
"app",
".",
"handleOnce",
"(",
"'onLayout'",
",",
"file",
")",
";",
"delete",
"file",
".",
"currentLayout",
";",
"}"
] | 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 | train |
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",
"=",
"{",
"}",
";",
"var",
"collections",
"=",
"app",
".",
"viewTypes",
".",
"layout",
";",
"var",
"len",
"=",
"collections",
".",
"length",
";",
"var",
"idx",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"idx",
"<",
"len",
")",
"{",
"var",
"collection",
"=",
"app",
"[",
"collections",
"[",
"idx",
"]",
"]",
";",
"if",
"(",
"!",
"layoutExists",
"&&",
"collection",
".",
"getView",
"(",
"name",
")",
")",
"{",
"layoutExists",
"=",
"true",
";",
"}",
"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",
";",
"}"
] | 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 | train |
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",
")",
";",
"this",
".",
"is",
"(",
"'Collection'",
")",
";",
"this",
".",
"items",
"=",
"{",
"}",
";",
"this",
".",
"use",
"(",
"utils",
".",
"option",
"(",
")",
")",
";",
"this",
".",
"use",
"(",
"utils",
".",
"plugin",
"(",
")",
")",
";",
"this",
".",
"init",
"(",
"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 | train |
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",
".",
"is",
"(",
"'templates'",
")",
";",
"this",
".",
"define",
"(",
"'isApp'",
",",
"true",
")",
";",
"this",
".",
"use",
"(",
"utils",
".",
"option",
"(",
")",
")",
";",
"this",
".",
"use",
"(",
"utils",
".",
"plugin",
"(",
")",
")",
";",
"this",
".",
"initTemplates",
"(",
")",
";",
"}"
] | 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 | train |
jonschlinkert/templates | lib/plugins/context.js | setHelperOptions | function setHelperOptions(context, key) {
var optsHelper = context.options.helper || {};
if (optsHelper.hasOwnProperty(key)) {
context.helper.options = optsHelper[key];
}
} | javascript | function setHelperOptions(context, key) {
var optsHelper = context.options.helper || {};
if (optsHelper.hasOwnProperty(key)) {
context.helper.options = optsHelper[key];
}
} | [
"function",
"setHelperOptions",
"(",
"context",
",",
"key",
")",
"{",
"var",
"optsHelper",
"=",
"context",
".",
"options",
".",
"helper",
"||",
"{",
"}",
";",
"if",
"(",
"optsHelper",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"context",
".",
"helper",
".",
"options",
"=",
"optsHelper",
"[",
"key",
"]",
";",
"}",
"}"
] | Update context in a helper so that `this.helper.options` is
the options for that specific helper.
@param {Object} `context`
@param {String} `key`
@api public | [
"Update",
"context",
"in",
"a",
"helper",
"so",
"that",
"this",
".",
"helper",
".",
"options",
"is",
"the",
"options",
"for",
"that",
"specific",
"helper",
"."
] | f030d2c2906ea9a703868f83574151badb427573 | https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/plugins/context.js#L120-L125 | train |
jonschlinkert/templates | lib/plugins/context.js | Context | function Context(app, view, context, helpers) {
this.helper = {};
this.helper.options = createHelperOptions(app, view, helpers);
this.context = context;
utils.define(this.context, 'view', view);
this.options = utils.merge({}, app.options, view.options, this.helper.options);
// make `this.options.handled` non-enumberable
utils.define(this.options, 'handled', this.options.handled);
decorate(this.context);
decorate(this.options);
decorate(this);
this.view = view;
this.app = app;
this.ctx = function() {
return helperContext.apply(this, arguments);
};
} | javascript | function Context(app, view, context, helpers) {
this.helper = {};
this.helper.options = createHelperOptions(app, view, helpers);
this.context = context;
utils.define(this.context, 'view', view);
this.options = utils.merge({}, app.options, view.options, this.helper.options);
// make `this.options.handled` non-enumberable
utils.define(this.options, 'handled', this.options.handled);
decorate(this.context);
decorate(this.options);
decorate(this);
this.view = view;
this.app = app;
this.ctx = function() {
return helperContext.apply(this, arguments);
};
} | [
"function",
"Context",
"(",
"app",
",",
"view",
",",
"context",
",",
"helpers",
")",
"{",
"this",
".",
"helper",
"=",
"{",
"}",
";",
"this",
".",
"helper",
".",
"options",
"=",
"createHelperOptions",
"(",
"app",
",",
"view",
",",
"helpers",
")",
";",
"this",
".",
"context",
"=",
"context",
";",
"utils",
".",
"define",
"(",
"this",
".",
"context",
",",
"'view'",
",",
"view",
")",
";",
"this",
".",
"options",
"=",
"utils",
".",
"merge",
"(",
"{",
"}",
",",
"app",
".",
"options",
",",
"view",
".",
"options",
",",
"this",
".",
"helper",
".",
"options",
")",
";",
"utils",
".",
"define",
"(",
"this",
".",
"options",
",",
"'handled'",
",",
"this",
".",
"options",
".",
"handled",
")",
";",
"decorate",
"(",
"this",
".",
"context",
")",
";",
"decorate",
"(",
"this",
".",
"options",
")",
";",
"decorate",
"(",
"this",
")",
";",
"this",
".",
"view",
"=",
"view",
";",
"this",
".",
"app",
"=",
"app",
";",
"this",
".",
"ctx",
"=",
"function",
"(",
")",
"{",
"return",
"helperContext",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}"
] | Create a new context object to expose inside helpers.
```js
app.helper('lowercase', function(str) {
// the 'this' object is the _helper_ context
console.log(this);
// 'this.app' => the application instance, e.g. templates, assemble, verb etc.
// 'this.view' => the current view being rendered
// 'this.helper' => helper name and options
// 'this.context' => view context (as opposed to _helper_ context)
// 'this.options' => options created for the specified helper being called
});
```
@param {Object} `app` The application instance
@param {Object} `view` The view being rendered
@param {Object} `context` The view's context
@param {Object} `options` | [
"Create",
"a",
"new",
"context",
"object",
"to",
"expose",
"inside",
"helpers",
"."
] | f030d2c2906ea9a703868f83574151badb427573 | https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/plugins/context.js#L147-L167 | train |
jonschlinkert/templates | lib/plugins/context.js | decorate | function decorate(obj) {
utils.define(obj, 'merge', function() {
var args = [].concat.apply([], [].slice.call(arguments));
var len = args.length;
var idx = -1;
while (++idx < len) {
var val = args[idx];
if (!utils.isObject(val)) continue;
if (val.hasOwnProperty('hash')) {
// shallow clone and delete the `data` object
val = utils.merge({}, val, val.hash);
delete val.data;
}
utils.merge(obj, val);
}
// ensure methods aren't overwritten
decorate(obj);
if (obj.hasOwnProperty('app') && obj.hasOwnProperty('options')) {
decorate(obj.options);
}
return obj;
});
utils.define(obj, 'get', function(prop) {
return utils.get(obj, prop);
});
utils.define(obj, 'set', function(key, val) {
return utils.set(obj, key, val);
});
} | javascript | function decorate(obj) {
utils.define(obj, 'merge', function() {
var args = [].concat.apply([], [].slice.call(arguments));
var len = args.length;
var idx = -1;
while (++idx < len) {
var val = args[idx];
if (!utils.isObject(val)) continue;
if (val.hasOwnProperty('hash')) {
// shallow clone and delete the `data` object
val = utils.merge({}, val, val.hash);
delete val.data;
}
utils.merge(obj, val);
}
// ensure methods aren't overwritten
decorate(obj);
if (obj.hasOwnProperty('app') && obj.hasOwnProperty('options')) {
decorate(obj.options);
}
return obj;
});
utils.define(obj, 'get', function(prop) {
return utils.get(obj, prop);
});
utils.define(obj, 'set', function(key, val) {
return utils.set(obj, key, val);
});
} | [
"function",
"decorate",
"(",
"obj",
")",
"{",
"utils",
".",
"define",
"(",
"obj",
",",
"'merge'",
",",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"]",
".",
"concat",
".",
"apply",
"(",
"[",
"]",
",",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
")",
";",
"var",
"len",
"=",
"args",
".",
"length",
";",
"var",
"idx",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"idx",
"<",
"len",
")",
"{",
"var",
"val",
"=",
"args",
"[",
"idx",
"]",
";",
"if",
"(",
"!",
"utils",
".",
"isObject",
"(",
"val",
")",
")",
"continue",
";",
"if",
"(",
"val",
".",
"hasOwnProperty",
"(",
"'hash'",
")",
")",
"{",
"val",
"=",
"utils",
".",
"merge",
"(",
"{",
"}",
",",
"val",
",",
"val",
".",
"hash",
")",
";",
"delete",
"val",
".",
"data",
";",
"}",
"utils",
".",
"merge",
"(",
"obj",
",",
"val",
")",
";",
"}",
"decorate",
"(",
"obj",
")",
";",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"'app'",
")",
"&&",
"obj",
".",
"hasOwnProperty",
"(",
"'options'",
")",
")",
"{",
"decorate",
"(",
"obj",
".",
"options",
")",
";",
"}",
"return",
"obj",
";",
"}",
")",
";",
"utils",
".",
"define",
"(",
"obj",
",",
"'get'",
",",
"function",
"(",
"prop",
")",
"{",
"return",
"utils",
".",
"get",
"(",
"obj",
",",
"prop",
")",
";",
"}",
")",
";",
"utils",
".",
"define",
"(",
"obj",
",",
"'set'",
",",
"function",
"(",
"key",
",",
"val",
")",
"{",
"return",
"utils",
".",
"set",
"(",
"obj",
",",
"key",
",",
"val",
")",
";",
"}",
")",
";",
"}"
] | Decorate the given object with `merge`, `set` and `get` methods | [
"Decorate",
"the",
"given",
"object",
"with",
"merge",
"set",
"and",
"get",
"methods"
] | f030d2c2906ea9a703868f83574151badb427573 | https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/plugins/context.js#L247-L278 | train |
jonschlinkert/templates | lib/plugins/context.js | mergePartials | function mergePartials(options) {
var opts = utils.merge({}, this.options, options);
var names = opts.mergeTypes || this.viewTypes.partial;
var partials = {};
var self = this;
names.forEach(function(name) {
var collection = self.views[name];
for (var key in collection) {
var view = collection[key];
// handle `onMerge` middleware
self.handleOnce('onMerge', view, function(err, res) {
if (err) throw err;
view = res;
});
if (view.options.nomerge) continue;
if (opts.mergePartials !== false) {
name = 'partials';
}
// convert the partial to:
//=> {'foo.hbs': 'some content...'};
partials[name] = partials[name] || {};
partials[name][key] = view.content;
}
});
return partials;
} | javascript | function mergePartials(options) {
var opts = utils.merge({}, this.options, options);
var names = opts.mergeTypes || this.viewTypes.partial;
var partials = {};
var self = this;
names.forEach(function(name) {
var collection = self.views[name];
for (var key in collection) {
var view = collection[key];
// handle `onMerge` middleware
self.handleOnce('onMerge', view, function(err, res) {
if (err) throw err;
view = res;
});
if (view.options.nomerge) continue;
if (opts.mergePartials !== false) {
name = 'partials';
}
// convert the partial to:
//=> {'foo.hbs': 'some content...'};
partials[name] = partials[name] || {};
partials[name][key] = view.content;
}
});
return partials;
} | [
"function",
"mergePartials",
"(",
"options",
")",
"{",
"var",
"opts",
"=",
"utils",
".",
"merge",
"(",
"{",
"}",
",",
"this",
".",
"options",
",",
"options",
")",
";",
"var",
"names",
"=",
"opts",
".",
"mergeTypes",
"||",
"this",
".",
"viewTypes",
".",
"partial",
";",
"var",
"partials",
"=",
"{",
"}",
";",
"var",
"self",
"=",
"this",
";",
"names",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"var",
"collection",
"=",
"self",
".",
"views",
"[",
"name",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"collection",
")",
"{",
"var",
"view",
"=",
"collection",
"[",
"key",
"]",
";",
"self",
".",
"handleOnce",
"(",
"'onMerge'",
",",
"view",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"view",
"=",
"res",
";",
"}",
")",
";",
"if",
"(",
"view",
".",
"options",
".",
"nomerge",
")",
"continue",
";",
"if",
"(",
"opts",
".",
"mergePartials",
"!==",
"false",
")",
"{",
"name",
"=",
"'partials'",
";",
"}",
"partials",
"[",
"name",
"]",
"=",
"partials",
"[",
"name",
"]",
"||",
"{",
"}",
";",
"partials",
"[",
"name",
"]",
"[",
"key",
"]",
"=",
"view",
".",
"content",
";",
"}",
"}",
")",
";",
"return",
"partials",
";",
"}"
] | Merge "partials" view types. This is necessary for template
engines have no support for partials or only support one
type of partials.
@name .mergePartials
@param {Object} `options` Optionally pass an array of `viewTypes` to include on `options.viewTypes`
@return {Object} Merged partials
@api public | [
"Merge",
"partials",
"view",
"types",
".",
"This",
"is",
"necessary",
"for",
"template",
"engines",
"have",
"no",
"support",
"for",
"partials",
"or",
"only",
"support",
"one",
"type",
"of",
"partials",
"."
] | f030d2c2906ea9a703868f83574151badb427573 | https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/plugins/context.js#L322-L351 | train |
jeneser/rsa-node | src/index.js | FixEncryptLength | function FixEncryptLength(text) {
var len = text.length;
var stdLens = [256, 512, 1024, 2048, 4096];
var stdLen, i, j;
for (i = 0; i < stdLens.length; i++) {
stdLen = stdLens[i];
if (len === stdLen) {
return text;
} else if (len < stdLen) {
var times = stdLen - len;
var preText = '';
for (j = 0; j < times; j++) {
preText += '0';
}
return preText + text;
}
}
return text;
} | javascript | function FixEncryptLength(text) {
var len = text.length;
var stdLens = [256, 512, 1024, 2048, 4096];
var stdLen, i, j;
for (i = 0; i < stdLens.length; i++) {
stdLen = stdLens[i];
if (len === stdLen) {
return text;
} else if (len < stdLen) {
var times = stdLen - len;
var preText = '';
for (j = 0; j < times; j++) {
preText += '0';
}
return preText + text;
}
}
return text;
} | [
"function",
"FixEncryptLength",
"(",
"text",
")",
"{",
"var",
"len",
"=",
"text",
".",
"length",
";",
"var",
"stdLens",
"=",
"[",
"256",
",",
"512",
",",
"1024",
",",
"2048",
",",
"4096",
"]",
";",
"var",
"stdLen",
",",
"i",
",",
"j",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"stdLens",
".",
"length",
";",
"i",
"++",
")",
"{",
"stdLen",
"=",
"stdLens",
"[",
"i",
"]",
";",
"if",
"(",
"len",
"===",
"stdLen",
")",
"{",
"return",
"text",
";",
"}",
"else",
"if",
"(",
"len",
"<",
"stdLen",
")",
"{",
"var",
"times",
"=",
"stdLen",
"-",
"len",
";",
"var",
"preText",
"=",
"''",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"times",
";",
"j",
"++",
")",
"{",
"preText",
"+=",
"'0'",
";",
"}",
"return",
"preText",
"+",
"text",
";",
"}",
"}",
"return",
"text",
";",
"}"
] | If the length of the encrypted text is not enough,add 0 in front | [
"If",
"the",
"length",
"of",
"the",
"encrypted",
"text",
"is",
"not",
"enough",
"add",
"0",
"in",
"front"
] | 7a54643b63259d44f7ff475ec0c1270f40171b01 | https://github.com/jeneser/rsa-node/blob/7a54643b63259d44f7ff475ec0c1270f40171b01/src/index.js#L838-L856 | train |
jonschlinkert/templates | lib/group.js | Group | function Group(config) {
if (!(this instanceof Group)) {
return new Group(config);
}
Base.call(this, config);
this.is('Group');
this.use(utils.option());
this.use(utils.plugin());
this.init();
} | javascript | function Group(config) {
if (!(this instanceof Group)) {
return new Group(config);
}
Base.call(this, config);
this.is('Group');
this.use(utils.option());
this.use(utils.plugin());
this.init();
} | [
"function",
"Group",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Group",
")",
")",
"{",
"return",
"new",
"Group",
"(",
"config",
")",
";",
"}",
"Base",
".",
"call",
"(",
"this",
",",
"config",
")",
";",
"this",
".",
"is",
"(",
"'Group'",
")",
";",
"this",
".",
"use",
"(",
"utils",
".",
"option",
"(",
")",
")",
";",
"this",
".",
"use",
"(",
"utils",
".",
"plugin",
"(",
")",
")",
";",
"this",
".",
"init",
"(",
")",
";",
"}"
] | Create an instance of `Group` with the given `options`.
```js
var group = new Group({
'foo': { items: [1,2,3] }
});
```
@param {Object} `options`
@api public | [
"Create",
"an",
"instance",
"of",
"Group",
"with",
"the",
"given",
"options",
"."
] | f030d2c2906ea9a703868f83574151badb427573 | https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/group.js#L25-L35 | train |
jonschlinkert/templates | lib/group.js | handleErrors | function handleErrors(group, val) {
if (utils.isObject(val)) {
var List = group.List;
var keys = Object.keys(List.prototype);
keys.forEach(function(key) {
if (typeof val[key] !== 'undefined') return;
utils.define(val, key, function() {
throw new Error(key + ' can only be used with an array of `List` items.');
});
});
}
} | javascript | function handleErrors(group, val) {
if (utils.isObject(val)) {
var List = group.List;
var keys = Object.keys(List.prototype);
keys.forEach(function(key) {
if (typeof val[key] !== 'undefined') return;
utils.define(val, key, function() {
throw new Error(key + ' can only be used with an array of `List` items.');
});
});
}
} | [
"function",
"handleErrors",
"(",
"group",
",",
"val",
")",
"{",
"if",
"(",
"utils",
".",
"isObject",
"(",
"val",
")",
")",
"{",
"var",
"List",
"=",
"group",
".",
"List",
";",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"List",
".",
"prototype",
")",
";",
"keys",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"typeof",
"val",
"[",
"key",
"]",
"!==",
"'undefined'",
")",
"return",
";",
"utils",
".",
"define",
"(",
"val",
",",
"key",
",",
"function",
"(",
")",
"{",
"throw",
"new",
"Error",
"(",
"key",
"+",
"' can only be used with an array of `List` items.'",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}"
] | When `get` returns a non-Array object, we decorate
noop `List` methods onto the object to throw errors when list methods
are used, since list array methods do not work on groups.
@param {Object} `group`
@param {Object} `val` Value returned from `group.get()` | [
"When",
"get",
"returns",
"a",
"non",
"-",
"Array",
"object",
"we",
"decorate",
"noop",
"List",
"methods",
"onto",
"the",
"object",
"to",
"throw",
"errors",
"when",
"list",
"methods",
"are",
"used",
"since",
"list",
"array",
"methods",
"do",
"not",
"work",
"on",
"groups",
"."
] | f030d2c2906ea9a703868f83574151badb427573 | https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/group.js#L93-L106 | train |
wikimedia/KafkaSSE | lib/utils.js | objectFactory | function objectFactory(data) {
// if we are given an object Object, no-op and return it now.
if (_.isPlainObject(data)) {
return data;
}
// If we are given a byte Buffer, parse it as utf-8
if (data instanceof Buffer) {
data = data.toString('utf-8');
}
// If we now have a string, then assume it is a JSON string.
if (_.isString(data)) {
data = JSON.parse(data);
}
else {
throw new Error(
'Could not convert data into an object. ' +
'Data must be a utf-8 byte buffer or a JSON string'
);
}
return data;
} | javascript | function objectFactory(data) {
// if we are given an object Object, no-op and return it now.
if (_.isPlainObject(data)) {
return data;
}
// If we are given a byte Buffer, parse it as utf-8
if (data instanceof Buffer) {
data = data.toString('utf-8');
}
// If we now have a string, then assume it is a JSON string.
if (_.isString(data)) {
data = JSON.parse(data);
}
else {
throw new Error(
'Could not convert data into an object. ' +
'Data must be a utf-8 byte buffer or a JSON string'
);
}
return data;
} | [
"function",
"objectFactory",
"(",
"data",
")",
"{",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"data",
")",
")",
"{",
"return",
"data",
";",
"}",
"if",
"(",
"data",
"instanceof",
"Buffer",
")",
"{",
"data",
"=",
"data",
".",
"toString",
"(",
"'utf-8'",
")",
";",
"}",
"if",
"(",
"_",
".",
"isString",
"(",
"data",
")",
")",
"{",
"data",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Could not convert data into an object. '",
"+",
"'Data must be a utf-8 byte buffer or a JSON string'",
")",
";",
"}",
"return",
"data",
";",
"}"
] | Converts a utf-8 byte buffer or a JSON string into
an object and returns it. | [
"Converts",
"a",
"utf",
"-",
"8",
"byte",
"buffer",
"or",
"a",
"JSON",
"string",
"into",
"an",
"object",
"and",
"returns",
"it",
"."
] | eb4568b0d2929057771508afd74ac83884252c95 | https://github.com/wikimedia/KafkaSSE/blob/eb4568b0d2929057771508afd74ac83884252c95/lib/utils.js#L16-L40 | train |
wikimedia/KafkaSSE | lib/utils.js | createKafkaConsumerAsync | function createKafkaConsumerAsync(kafkaConfig) {
let topicConfig = {};
if ('default_topic_config' in kafkaConfig) {
topicConfig = kafkaConfig.default_topic_config;
delete kafkaConfig.default_topic_config;
}
const consumer = P.promisifyAll(
new kafka.KafkaConsumer(kafkaConfig, topicConfig)
);
return consumer.connectAsync(undefined)
.thenReturn(consumer);
} | javascript | function createKafkaConsumerAsync(kafkaConfig) {
let topicConfig = {};
if ('default_topic_config' in kafkaConfig) {
topicConfig = kafkaConfig.default_topic_config;
delete kafkaConfig.default_topic_config;
}
const consumer = P.promisifyAll(
new kafka.KafkaConsumer(kafkaConfig, topicConfig)
);
return consumer.connectAsync(undefined)
.thenReturn(consumer);
} | [
"function",
"createKafkaConsumerAsync",
"(",
"kafkaConfig",
")",
"{",
"let",
"topicConfig",
"=",
"{",
"}",
";",
"if",
"(",
"'default_topic_config'",
"in",
"kafkaConfig",
")",
"{",
"topicConfig",
"=",
"kafkaConfig",
".",
"default_topic_config",
";",
"delete",
"kafkaConfig",
".",
"default_topic_config",
";",
"}",
"const",
"consumer",
"=",
"P",
".",
"promisifyAll",
"(",
"new",
"kafka",
".",
"KafkaConsumer",
"(",
"kafkaConfig",
",",
"topicConfig",
")",
")",
";",
"return",
"consumer",
".",
"connectAsync",
"(",
"undefined",
")",
".",
"thenReturn",
"(",
"consumer",
")",
";",
"}"
] | Returns a Promise of a promisified and connected rdkafka.KafkaConsumer.
@param {Object} kafkaConfig
@return {Promise<KafkaConsumer>} Promisified KafkaConsumer | [
"Returns",
"a",
"Promise",
"of",
"a",
"promisified",
"and",
"connected",
"rdkafka",
".",
"KafkaConsumer",
"."
] | eb4568b0d2929057771508afd74ac83884252c95 | https://github.com/wikimedia/KafkaSSE/blob/eb4568b0d2929057771508afd74ac83884252c95/lib/utils.js#L49-L62 | train |
wikimedia/KafkaSSE | lib/utils.js | getAvailableTopics | function getAvailableTopics(topicsInfo, allowedTopics) {
const existentTopics = topicsInfo.map(
e => e.name
)
.filter(t => t !== '__consumer_offsets');
if (allowedTopics) {
return existentTopics.filter(t => _.includes(allowedTopics, t));
}
else {
return existentTopics;
}
} | javascript | function getAvailableTopics(topicsInfo, allowedTopics) {
const existentTopics = topicsInfo.map(
e => e.name
)
.filter(t => t !== '__consumer_offsets');
if (allowedTopics) {
return existentTopics.filter(t => _.includes(allowedTopics, t));
}
else {
return existentTopics;
}
} | [
"function",
"getAvailableTopics",
"(",
"topicsInfo",
",",
"allowedTopics",
")",
"{",
"const",
"existentTopics",
"=",
"topicsInfo",
".",
"map",
"(",
"e",
"=>",
"e",
".",
"name",
")",
".",
"filter",
"(",
"t",
"=>",
"t",
"!==",
"'__consumer_offsets'",
")",
";",
"if",
"(",
"allowedTopics",
")",
"{",
"return",
"existentTopics",
".",
"filter",
"(",
"t",
"=>",
"_",
".",
"includes",
"(",
"allowedTopics",
",",
"t",
")",
")",
";",
"}",
"else",
"{",
"return",
"existentTopics",
";",
"}",
"}"
] | Return the intersection of existent topics and allowedTopics,
or just all existent topics if allowedTopics is undefined.
@param {Array} topicsInfo topic metadata object, _metadata.topics.
@param {Array} allowedTopics topics allowed to be consumed.
@return {Array} available topics | [
"Return",
"the",
"intersection",
"of",
"existent",
"topics",
"and",
"allowedTopics",
"or",
"just",
"all",
"existent",
"topics",
"if",
"allowedTopics",
"is",
"undefined",
"."
] | eb4568b0d2929057771508afd74ac83884252c95 | https://github.com/wikimedia/KafkaSSE/blob/eb4568b0d2929057771508afd74ac83884252c95/lib/utils.js#L73-L85 | train |
wikimedia/KafkaSSE | lib/utils.js | assignmentsForTimesAsync | function assignmentsForTimesAsync(kafkaConsumer, assignments) {
const assignmentsWithTimestamps = assignments.filter(a => 'timestamp' in a && !('offset' in a)).map((a) => {
return {topic: a.topic, partition: a.partition, offset: a.timestamp };
});
// If there were no timestamps to resolve, just return assignments as is.
if (assignmentsWithTimestamps.length == 0) {
return new P((resolve, reject) => resolve(assignments));
}
// Else resolve all timestamp assignments to offsets.
else {
// Get offsets for the timestamp based assignments.
// If no offset was found for any timestamp, this will return -1, which
// we can use for offset: -1 as end of partition.
return kafkaConsumer.offsetsForTimesAsync(assignmentsWithTimestamps)
.then(offsetsForTimes => {
// console.log({ withTimestamps: assignmentsWithTimestamps, got: offsetsForTimes}, 'got offsets for times');
// merge offsetsForTimes with any non-timestamp based assignments.
// This merged object will only have assignments with offsets specified, no timestamps.
return _.flatten([
assignments.filter(a => !('timestamp' in a) && 'offset' in a),
offsetsForTimes
]);
})
}
} | javascript | function assignmentsForTimesAsync(kafkaConsumer, assignments) {
const assignmentsWithTimestamps = assignments.filter(a => 'timestamp' in a && !('offset' in a)).map((a) => {
return {topic: a.topic, partition: a.partition, offset: a.timestamp };
});
// If there were no timestamps to resolve, just return assignments as is.
if (assignmentsWithTimestamps.length == 0) {
return new P((resolve, reject) => resolve(assignments));
}
// Else resolve all timestamp assignments to offsets.
else {
// Get offsets for the timestamp based assignments.
// If no offset was found for any timestamp, this will return -1, which
// we can use for offset: -1 as end of partition.
return kafkaConsumer.offsetsForTimesAsync(assignmentsWithTimestamps)
.then(offsetsForTimes => {
// console.log({ withTimestamps: assignmentsWithTimestamps, got: offsetsForTimes}, 'got offsets for times');
// merge offsetsForTimes with any non-timestamp based assignments.
// This merged object will only have assignments with offsets specified, no timestamps.
return _.flatten([
assignments.filter(a => !('timestamp' in a) && 'offset' in a),
offsetsForTimes
]);
})
}
} | [
"function",
"assignmentsForTimesAsync",
"(",
"kafkaConsumer",
",",
"assignments",
")",
"{",
"const",
"assignmentsWithTimestamps",
"=",
"assignments",
".",
"filter",
"(",
"a",
"=>",
"'timestamp'",
"in",
"a",
"&&",
"!",
"(",
"'offset'",
"in",
"a",
")",
")",
".",
"map",
"(",
"(",
"a",
")",
"=>",
"{",
"return",
"{",
"topic",
":",
"a",
".",
"topic",
",",
"partition",
":",
"a",
".",
"partition",
",",
"offset",
":",
"a",
".",
"timestamp",
"}",
";",
"}",
")",
";",
"if",
"(",
"assignmentsWithTimestamps",
".",
"length",
"==",
"0",
")",
"{",
"return",
"new",
"P",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"resolve",
"(",
"assignments",
")",
")",
";",
"}",
"else",
"{",
"return",
"kafkaConsumer",
".",
"offsetsForTimesAsync",
"(",
"assignmentsWithTimestamps",
")",
".",
"then",
"(",
"offsetsForTimes",
"=>",
"{",
"return",
"_",
".",
"flatten",
"(",
"[",
"assignments",
".",
"filter",
"(",
"a",
"=>",
"!",
"(",
"'timestamp'",
"in",
"a",
")",
"&&",
"'offset'",
"in",
"a",
")",
",",
"offsetsForTimes",
"]",
")",
";",
"}",
")",
"}",
"}"
] | Given a a Kafka assignemnts array, this will look for any occurances
of 'timestamp' instead of 'offset'. For those found, it will issue
a offsetsForTimes request on the kafkaConsumer. The returned
offsets will be merged with any provided non-timestamp based assignments,
and returned as a Promise of assignments array with only offsets.
If no timestamps based assignments are given, this will just return a Promise
of the provided assignments.
@param {KafkaConsumer} kafkaConsumer
@param {Array} assignments
@return {Promise} Array of timestamp resolved assignment objects with offsets. | [
"Given",
"a",
"a",
"Kafka",
"assignemnts",
"array",
"this",
"will",
"look",
"for",
"any",
"occurances",
"of",
"timestamp",
"instead",
"of",
"offset",
".",
"For",
"those",
"found",
"it",
"will",
"issue",
"a",
"offsetsForTimes",
"request",
"on",
"the",
"kafkaConsumer",
".",
"The",
"returned",
"offsets",
"will",
"be",
"merged",
"with",
"any",
"provided",
"non",
"-",
"timestamp",
"based",
"assignments",
"and",
"returned",
"as",
"a",
"Promise",
"of",
"assignments",
"array",
"with",
"only",
"offsets",
"."
] | eb4568b0d2929057771508afd74ac83884252c95 | https://github.com/wikimedia/KafkaSSE/blob/eb4568b0d2929057771508afd74ac83884252c95/lib/utils.js#L249-L274 | train |
wikimedia/KafkaSSE | lib/utils.js | deserializeKafkaMessage | function deserializeKafkaMessage(kafkaMessage) {
kafkaMessage.message = objectFactory(kafkaMessage.value);
kafkaMessage.message._kafka = {
topic: kafkaMessage.topic,
partition: kafkaMessage.partition,
offset: kafkaMessage.offset,
timestamp: kafkaMessage.timestamp || null,
key: kafkaMessage.key,
};
return kafkaMessage;
} | javascript | function deserializeKafkaMessage(kafkaMessage) {
kafkaMessage.message = objectFactory(kafkaMessage.value);
kafkaMessage.message._kafka = {
topic: kafkaMessage.topic,
partition: kafkaMessage.partition,
offset: kafkaMessage.offset,
timestamp: kafkaMessage.timestamp || null,
key: kafkaMessage.key,
};
return kafkaMessage;
} | [
"function",
"deserializeKafkaMessage",
"(",
"kafkaMessage",
")",
"{",
"kafkaMessage",
".",
"message",
"=",
"objectFactory",
"(",
"kafkaMessage",
".",
"value",
")",
";",
"kafkaMessage",
".",
"message",
".",
"_kafka",
"=",
"{",
"topic",
":",
"kafkaMessage",
".",
"topic",
",",
"partition",
":",
"kafkaMessage",
".",
"partition",
",",
"offset",
":",
"kafkaMessage",
".",
"offset",
",",
"timestamp",
":",
"kafkaMessage",
".",
"timestamp",
"||",
"null",
",",
"key",
":",
"kafkaMessage",
".",
"key",
",",
"}",
";",
"return",
"kafkaMessage",
";",
"}"
] | Parses kafkaMessage.message as a JSON string and then
augments the object with kafka message metadata.
in the message._kafka sub object.
@param {KafkaMesssage} kafkaMessage
@return {Object} | [
"Parses",
"kafkaMessage",
".",
"message",
"as",
"a",
"JSON",
"string",
"and",
"then",
"augments",
"the",
"object",
"with",
"kafka",
"message",
"metadata",
".",
"in",
"the",
"message",
".",
"_kafka",
"sub",
"object",
"."
] | eb4568b0d2929057771508afd74ac83884252c95 | https://github.com/wikimedia/KafkaSSE/blob/eb4568b0d2929057771508afd74ac83884252c95/lib/utils.js#L286-L298 | train |
jonschlinkert/templates | lib/plugins/render.js | findView | function findView(app, name) {
var keys = app.viewTypes.renderable;
var len = keys.length;
var i = -1;
var res = null;
while (++i < len) {
res = app.find(name, keys[i]);
if (res) {
break;
}
}
return res;
} | javascript | function findView(app, name) {
var keys = app.viewTypes.renderable;
var len = keys.length;
var i = -1;
var res = null;
while (++i < len) {
res = app.find(name, keys[i]);
if (res) {
break;
}
}
return res;
} | [
"function",
"findView",
"(",
"app",
",",
"name",
")",
"{",
"var",
"keys",
"=",
"app",
".",
"viewTypes",
".",
"renderable",
";",
"var",
"len",
"=",
"keys",
".",
"length",
";",
"var",
"i",
"=",
"-",
"1",
";",
"var",
"res",
"=",
"null",
";",
"while",
"(",
"++",
"i",
"<",
"len",
")",
"{",
"res",
"=",
"app",
".",
"find",
"(",
"name",
",",
"keys",
"[",
"i",
"]",
")",
";",
"if",
"(",
"res",
")",
"{",
"break",
";",
"}",
"}",
"return",
"res",
";",
"}"
] | Iterates over `renderable` view collections
and returns the first view that matches the
given `view` name | [
"Iterates",
"over",
"renderable",
"view",
"collections",
"and",
"returns",
"the",
"first",
"view",
"that",
"matches",
"the",
"given",
"view",
"name"
] | f030d2c2906ea9a703868f83574151badb427573 | https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/plugins/render.js#L38-L51 | train |
jonschlinkert/templates | lib/plugins/render.js | getView | function getView(app, view) {
if (typeof view !== 'string') {
return view;
}
if (app.isCollection) {
view = app.getView(view);
} else if (app.isList) {
view = app.getItem(view);
} else {
view = findView(app, view);
}
return view;
} | javascript | function getView(app, view) {
if (typeof view !== 'string') {
return view;
}
if (app.isCollection) {
view = app.getView(view);
} else if (app.isList) {
view = app.getItem(view);
} else {
view = findView(app, view);
}
return view;
} | [
"function",
"getView",
"(",
"app",
",",
"view",
")",
"{",
"if",
"(",
"typeof",
"view",
"!==",
"'string'",
")",
"{",
"return",
"view",
";",
"}",
"if",
"(",
"app",
".",
"isCollection",
")",
"{",
"view",
"=",
"app",
".",
"getView",
"(",
"view",
")",
";",
"}",
"else",
"if",
"(",
"app",
".",
"isList",
")",
"{",
"view",
"=",
"app",
".",
"getItem",
"(",
"view",
")",
";",
"}",
"else",
"{",
"view",
"=",
"findView",
"(",
"app",
",",
"view",
")",
";",
"}",
"return",
"view",
";",
"}"
] | Get a view from the specified collection, or list,
or iterate over view collections until the view
is found. | [
"Get",
"a",
"view",
"from",
"the",
"specified",
"collection",
"or",
"list",
"or",
"iterate",
"over",
"view",
"collections",
"until",
"the",
"view",
"is",
"found",
"."
] | f030d2c2906ea9a703868f83574151badb427573 | https://github.com/jonschlinkert/templates/blob/f030d2c2906ea9a703868f83574151badb427573/lib/plugins/render.js#L59-L73 | train |
audiojs/audio-generator | direct.js | Generator | function Generator (fn, opts) {
if (fn instanceof Function) {
if (typeof opts === 'number') {
opts = {duration: opts};
}
else {
opts = opts || {};
}
opts.generate = fn;
}
else {
opts = fn || {};
}
//sort out arguments
opts = extend({
//total duration of a stream
duration: Infinity,
//time repeat period, in seconds, or 1/frequency
period: Infinity,
//inferred from period
//frequency: 0,
/**
* Generate sample value for a time.
* Returns [L, R, ...] or a number for each channel
*
* @param {number} time current time
*/
generate: Math.random
}, pcm.defaults, opts);
//align frequency/period
if (opts.frequency != null) {
opts.period = 1 / opts.frequency;
} else {
opts.frequency = 1 / opts.period;
}
let time = 0, count = 0;
return generate;
//return sync source/map
function generate (buffer) {
if (!buffer) buffer = util.create(opts.samplesPerFrame, opts.channels, opts.sampleRate);
//get audio buffer channels data in array
var data = util.data(buffer);
//enough?
if (time + buffer.length / opts.sampleRate > opts.duration) return null;
//generate [channeled] samples
for (var i = 0; i < buffer.length; i++) {
var moment = time + i / opts.sampleRate;
//rotate by period
if (opts.period !== Infinity) {
moment %= opts.period;
}
var gen = opts.generate(moment);
//treat null as end
if (gen === null) {
return gen;
}
//wrap number value
if (!Array.isArray(gen)) {
gen = [gen || 0];
}
//distribute generated data by channels
for (var channel = 0; channel < buffer.numberOfChannels; channel++) {
data[channel][i] = (gen[channel] == null ? gen[0] : gen[channel]);
}
}
//update counters
count += buffer.length;
time = count / opts.sampleRate;
return buffer;
}
} | javascript | function Generator (fn, opts) {
if (fn instanceof Function) {
if (typeof opts === 'number') {
opts = {duration: opts};
}
else {
opts = opts || {};
}
opts.generate = fn;
}
else {
opts = fn || {};
}
//sort out arguments
opts = extend({
//total duration of a stream
duration: Infinity,
//time repeat period, in seconds, or 1/frequency
period: Infinity,
//inferred from period
//frequency: 0,
/**
* Generate sample value for a time.
* Returns [L, R, ...] or a number for each channel
*
* @param {number} time current time
*/
generate: Math.random
}, pcm.defaults, opts);
//align frequency/period
if (opts.frequency != null) {
opts.period = 1 / opts.frequency;
} else {
opts.frequency = 1 / opts.period;
}
let time = 0, count = 0;
return generate;
//return sync source/map
function generate (buffer) {
if (!buffer) buffer = util.create(opts.samplesPerFrame, opts.channels, opts.sampleRate);
//get audio buffer channels data in array
var data = util.data(buffer);
//enough?
if (time + buffer.length / opts.sampleRate > opts.duration) return null;
//generate [channeled] samples
for (var i = 0; i < buffer.length; i++) {
var moment = time + i / opts.sampleRate;
//rotate by period
if (opts.period !== Infinity) {
moment %= opts.period;
}
var gen = opts.generate(moment);
//treat null as end
if (gen === null) {
return gen;
}
//wrap number value
if (!Array.isArray(gen)) {
gen = [gen || 0];
}
//distribute generated data by channels
for (var channel = 0; channel < buffer.numberOfChannels; channel++) {
data[channel][i] = (gen[channel] == null ? gen[0] : gen[channel]);
}
}
//update counters
count += buffer.length;
time = count / opts.sampleRate;
return buffer;
}
} | [
"function",
"Generator",
"(",
"fn",
",",
"opts",
")",
"{",
"if",
"(",
"fn",
"instanceof",
"Function",
")",
"{",
"if",
"(",
"typeof",
"opts",
"===",
"'number'",
")",
"{",
"opts",
"=",
"{",
"duration",
":",
"opts",
"}",
";",
"}",
"else",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"}",
"opts",
".",
"generate",
"=",
"fn",
";",
"}",
"else",
"{",
"opts",
"=",
"fn",
"||",
"{",
"}",
";",
"}",
"opts",
"=",
"extend",
"(",
"{",
"duration",
":",
"Infinity",
",",
"period",
":",
"Infinity",
",",
"generate",
":",
"Math",
".",
"random",
"}",
",",
"pcm",
".",
"defaults",
",",
"opts",
")",
";",
"if",
"(",
"opts",
".",
"frequency",
"!=",
"null",
")",
"{",
"opts",
".",
"period",
"=",
"1",
"/",
"opts",
".",
"frequency",
";",
"}",
"else",
"{",
"opts",
".",
"frequency",
"=",
"1",
"/",
"opts",
".",
"period",
";",
"}",
"let",
"time",
"=",
"0",
",",
"count",
"=",
"0",
";",
"return",
"generate",
";",
"function",
"generate",
"(",
"buffer",
")",
"{",
"if",
"(",
"!",
"buffer",
")",
"buffer",
"=",
"util",
".",
"create",
"(",
"opts",
".",
"samplesPerFrame",
",",
"opts",
".",
"channels",
",",
"opts",
".",
"sampleRate",
")",
";",
"var",
"data",
"=",
"util",
".",
"data",
"(",
"buffer",
")",
";",
"if",
"(",
"time",
"+",
"buffer",
".",
"length",
"/",
"opts",
".",
"sampleRate",
">",
"opts",
".",
"duration",
")",
"return",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"buffer",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"moment",
"=",
"time",
"+",
"i",
"/",
"opts",
".",
"sampleRate",
";",
"if",
"(",
"opts",
".",
"period",
"!==",
"Infinity",
")",
"{",
"moment",
"%=",
"opts",
".",
"period",
";",
"}",
"var",
"gen",
"=",
"opts",
".",
"generate",
"(",
"moment",
")",
";",
"if",
"(",
"gen",
"===",
"null",
")",
"{",
"return",
"gen",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"gen",
")",
")",
"{",
"gen",
"=",
"[",
"gen",
"||",
"0",
"]",
";",
"}",
"for",
"(",
"var",
"channel",
"=",
"0",
";",
"channel",
"<",
"buffer",
".",
"numberOfChannels",
";",
"channel",
"++",
")",
"{",
"data",
"[",
"channel",
"]",
"[",
"i",
"]",
"=",
"(",
"gen",
"[",
"channel",
"]",
"==",
"null",
"?",
"gen",
"[",
"0",
"]",
":",
"gen",
"[",
"channel",
"]",
")",
";",
"}",
"}",
"count",
"+=",
"buffer",
".",
"length",
";",
"time",
"=",
"count",
"/",
"opts",
".",
"sampleRate",
";",
"return",
"buffer",
";",
"}",
"}"
] | Sync map constructor
@constructor | [
"Sync",
"map",
"constructor"
] | 74f71214f6dbc227c7427d0e8410d8fc7301dcd7 | https://github.com/audiojs/audio-generator/blob/74f71214f6dbc227c7427d0e8410d8fc7301dcd7/direct.js#L18-L106 | train |
Hustle/parse-mockdb | src/parse-mockdb.js | deserializeQueryParam | function deserializeQueryParam(param) {
if (!!param && (typeof param === 'object')) {
if (param.__type === 'Date') {
return new Date(param.iso);
}
}
return param;
} | javascript | function deserializeQueryParam(param) {
if (!!param && (typeof param === 'object')) {
if (param.__type === 'Date') {
return new Date(param.iso);
}
}
return param;
} | [
"function",
"deserializeQueryParam",
"(",
"param",
")",
"{",
"if",
"(",
"!",
"!",
"param",
"&&",
"(",
"typeof",
"param",
"===",
"'object'",
")",
")",
"{",
"if",
"(",
"param",
".",
"__type",
"===",
"'Date'",
")",
"{",
"return",
"new",
"Date",
"(",
"param",
".",
"iso",
")",
";",
"}",
"}",
"return",
"param",
";",
"}"
] | Deserialize an encoded query parameter if necessary | [
"Deserialize",
"an",
"encoded",
"query",
"parameter",
"if",
"necessary"
] | b33a113debcba3c80477b50c7fae557f5941d494 | https://github.com/Hustle/parse-mockdb/blob/b33a113debcba3c80477b50c7fae557f5941d494/src/parse-mockdb.js#L47-L54 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.