id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
19,600
|
nodertc/stun
|
src/index.js
|
createMessage
|
function createMessage(type, transaction) {
const msg = new StunMessage();
msg.setType(type);
msg.setTransactionID(transaction || createTransaction());
return msg;
}
|
javascript
|
function createMessage(type, transaction) {
const msg = new StunMessage();
msg.setType(type);
msg.setTransactionID(transaction || createTransaction());
return msg;
}
|
[
"function",
"createMessage",
"(",
"type",
",",
"transaction",
")",
"{",
"const",
"msg",
"=",
"new",
"StunMessage",
"(",
")",
";",
"msg",
".",
"setType",
"(",
"type",
")",
";",
"msg",
".",
"setTransactionID",
"(",
"transaction",
"||",
"createTransaction",
"(",
")",
")",
";",
"return",
"msg",
";",
"}"
] |
Creates a new STUN message.
@param {number} type - Message type (see constants).
@param {Buffer} [transaction] - Message `transaction` field, random by default.
@returns {StunMessage} StunMessage instance.
|
[
"Creates",
"a",
"new",
"STUN",
"message",
"."
] |
08f75eda77a5bf2a56af266630e4ffb814fb09b1
|
https://github.com/nodertc/stun/blob/08f75eda77a5bf2a56af266630e4ffb814fb09b1/src/index.js#L48-L55
|
19,601
|
nodertc/stun
|
src/index.js
|
createDgramServer
|
function createDgramServer(options = {}) {
let isExternalSocket = false;
if (options.socket instanceof dgram.Socket) {
isExternalSocket = true;
}
const socket = isExternalSocket ? options.socket : dgram.createSocket('udp4');
const server = new StunServer(socket);
if (!isExternalSocket) {
socket.on('error', error => server.emit('error', error));
server.once('close', () => socket.close());
}
return server;
}
|
javascript
|
function createDgramServer(options = {}) {
let isExternalSocket = false;
if (options.socket instanceof dgram.Socket) {
isExternalSocket = true;
}
const socket = isExternalSocket ? options.socket : dgram.createSocket('udp4');
const server = new StunServer(socket);
if (!isExternalSocket) {
socket.on('error', error => server.emit('error', error));
server.once('close', () => socket.close());
}
return server;
}
|
[
"function",
"createDgramServer",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"let",
"isExternalSocket",
"=",
"false",
";",
"if",
"(",
"options",
".",
"socket",
"instanceof",
"dgram",
".",
"Socket",
")",
"{",
"isExternalSocket",
"=",
"true",
";",
"}",
"const",
"socket",
"=",
"isExternalSocket",
"?",
"options",
".",
"socket",
":",
"dgram",
".",
"createSocket",
"(",
"'udp4'",
")",
";",
"const",
"server",
"=",
"new",
"StunServer",
"(",
"socket",
")",
";",
"if",
"(",
"!",
"isExternalSocket",
")",
"{",
"socket",
".",
"on",
"(",
"'error'",
",",
"error",
"=>",
"server",
".",
"emit",
"(",
"'error'",
",",
"error",
")",
")",
";",
"server",
".",
"once",
"(",
"'close'",
",",
"(",
")",
"=>",
"socket",
".",
"close",
"(",
")",
")",
";",
"}",
"return",
"server",
";",
"}"
] |
Creates dgram STUN server.
@param {Object} [options]
@param {dgram.Socket} [options.socket] - Optional udp socket.
@returns {StunServer}
|
[
"Creates",
"dgram",
"STUN",
"server",
"."
] |
08f75eda77a5bf2a56af266630e4ffb814fb09b1
|
https://github.com/nodertc/stun/blob/08f75eda77a5bf2a56af266630e4ffb814fb09b1/src/index.js#L81-L97
|
19,602
|
mapbox/geojson-normalize
|
index.js
|
normalize
|
function normalize(gj) {
if (!gj || !gj.type) return null;
var type = types[gj.type];
if (!type) return null;
if (type === 'geometry') {
return {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: gj
}]
};
} else if (type === 'feature') {
return {
type: 'FeatureCollection',
features: [gj]
};
} else if (type === 'featurecollection') {
return gj;
}
}
|
javascript
|
function normalize(gj) {
if (!gj || !gj.type) return null;
var type = types[gj.type];
if (!type) return null;
if (type === 'geometry') {
return {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: gj
}]
};
} else if (type === 'feature') {
return {
type: 'FeatureCollection',
features: [gj]
};
} else if (type === 'featurecollection') {
return gj;
}
}
|
[
"function",
"normalize",
"(",
"gj",
")",
"{",
"if",
"(",
"!",
"gj",
"||",
"!",
"gj",
".",
"type",
")",
"return",
"null",
";",
"var",
"type",
"=",
"types",
"[",
"gj",
".",
"type",
"]",
";",
"if",
"(",
"!",
"type",
")",
"return",
"null",
";",
"if",
"(",
"type",
"===",
"'geometry'",
")",
"{",
"return",
"{",
"type",
":",
"'FeatureCollection'",
",",
"features",
":",
"[",
"{",
"type",
":",
"'Feature'",
",",
"properties",
":",
"{",
"}",
",",
"geometry",
":",
"gj",
"}",
"]",
"}",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'feature'",
")",
"{",
"return",
"{",
"type",
":",
"'FeatureCollection'",
",",
"features",
":",
"[",
"gj",
"]",
"}",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'featurecollection'",
")",
"{",
"return",
"gj",
";",
"}",
"}"
] |
Normalize a GeoJSON feature into a FeatureCollection.
@param {object} gj geojson data
@returns {object} normalized geojson data
|
[
"Normalize",
"a",
"GeoJSON",
"feature",
"into",
"a",
"FeatureCollection",
"."
] |
d7468124635c92e0c8bee8c086ee3ec495d37f20
|
https://github.com/mapbox/geojson-normalize/blob/d7468124635c92e0c8bee8c086ee3ec495d37f20/index.js#L21-L43
|
19,603
|
haven-life/amorphic
|
lib/session/establishServerSession.js
|
establishServerSession
|
function establishServerSession(req, path, newPage, reset, newControllerId, sessions, controllers, nonObjTemplatelogLevel) {
let applicationConfig = AmorphicContext.applicationConfig;
// Retrieve configuration information
let config = applicationConfig[path];
if (!config) {
throw new Error('Semotus: establishServerSession called with a path of ' + path + ' which was not registered');
}
let initObjectTemplate = config.initObjectTemplate;
let controllerPath = config.appPath + '/' + (config.appConfig.controller || 'controller.js');
let objectCacheExpiration = config.objectCacheExpiration;
let sessionExpiration = config.sessionExpiration;
let sessionStore = config.sessionStore;
let appVersion = config.appVersion;
let session = req.session;
let sessionData = getSessionCache(path, req.session.id, false, sessions);
if (newPage === 'initial') {
sessionData.sequence = 1;
// For a new page determine if a controller is to be omitted
if (config.appConfig.createControllerFor && !session.semotus) {
let referer = '';
if (req.headers['referer']) {
referer = url.parse(req.headers['referer'], true).path;
}
let createControllerFor = config.appConfig.createControllerFor;
if (!referer.match(createControllerFor) && createControllerFor !== 'yes') {
return establishInitialServerSession(req, controllerPath, initObjectTemplate, path,
appVersion, sessionExpiration);
}
}
}
return establishContinuedServerSession(req, controllerPath, initObjectTemplate, path, appVersion,
sessionExpiration, session, sessionStore, newControllerId, objectCacheExpiration, newPage,
controllers, nonObjTemplatelogLevel, sessions, reset);
}
|
javascript
|
function establishServerSession(req, path, newPage, reset, newControllerId, sessions, controllers, nonObjTemplatelogLevel) {
let applicationConfig = AmorphicContext.applicationConfig;
// Retrieve configuration information
let config = applicationConfig[path];
if (!config) {
throw new Error('Semotus: establishServerSession called with a path of ' + path + ' which was not registered');
}
let initObjectTemplate = config.initObjectTemplate;
let controllerPath = config.appPath + '/' + (config.appConfig.controller || 'controller.js');
let objectCacheExpiration = config.objectCacheExpiration;
let sessionExpiration = config.sessionExpiration;
let sessionStore = config.sessionStore;
let appVersion = config.appVersion;
let session = req.session;
let sessionData = getSessionCache(path, req.session.id, false, sessions);
if (newPage === 'initial') {
sessionData.sequence = 1;
// For a new page determine if a controller is to be omitted
if (config.appConfig.createControllerFor && !session.semotus) {
let referer = '';
if (req.headers['referer']) {
referer = url.parse(req.headers['referer'], true).path;
}
let createControllerFor = config.appConfig.createControllerFor;
if (!referer.match(createControllerFor) && createControllerFor !== 'yes') {
return establishInitialServerSession(req, controllerPath, initObjectTemplate, path,
appVersion, sessionExpiration);
}
}
}
return establishContinuedServerSession(req, controllerPath, initObjectTemplate, path, appVersion,
sessionExpiration, session, sessionStore, newControllerId, objectCacheExpiration, newPage,
controllers, nonObjTemplatelogLevel, sessions, reset);
}
|
[
"function",
"establishServerSession",
"(",
"req",
",",
"path",
",",
"newPage",
",",
"reset",
",",
"newControllerId",
",",
"sessions",
",",
"controllers",
",",
"nonObjTemplatelogLevel",
")",
"{",
"let",
"applicationConfig",
"=",
"AmorphicContext",
".",
"applicationConfig",
";",
"// Retrieve configuration information",
"let",
"config",
"=",
"applicationConfig",
"[",
"path",
"]",
";",
"if",
"(",
"!",
"config",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Semotus: establishServerSession called with a path of '",
"+",
"path",
"+",
"' which was not registered'",
")",
";",
"}",
"let",
"initObjectTemplate",
"=",
"config",
".",
"initObjectTemplate",
";",
"let",
"controllerPath",
"=",
"config",
".",
"appPath",
"+",
"'/'",
"+",
"(",
"config",
".",
"appConfig",
".",
"controller",
"||",
"'controller.js'",
")",
";",
"let",
"objectCacheExpiration",
"=",
"config",
".",
"objectCacheExpiration",
";",
"let",
"sessionExpiration",
"=",
"config",
".",
"sessionExpiration",
";",
"let",
"sessionStore",
"=",
"config",
".",
"sessionStore",
";",
"let",
"appVersion",
"=",
"config",
".",
"appVersion",
";",
"let",
"session",
"=",
"req",
".",
"session",
";",
"let",
"sessionData",
"=",
"getSessionCache",
"(",
"path",
",",
"req",
".",
"session",
".",
"id",
",",
"false",
",",
"sessions",
")",
";",
"if",
"(",
"newPage",
"===",
"'initial'",
")",
"{",
"sessionData",
".",
"sequence",
"=",
"1",
";",
"// For a new page determine if a controller is to be omitted",
"if",
"(",
"config",
".",
"appConfig",
".",
"createControllerFor",
"&&",
"!",
"session",
".",
"semotus",
")",
"{",
"let",
"referer",
"=",
"''",
";",
"if",
"(",
"req",
".",
"headers",
"[",
"'referer'",
"]",
")",
"{",
"referer",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"headers",
"[",
"'referer'",
"]",
",",
"true",
")",
".",
"path",
";",
"}",
"let",
"createControllerFor",
"=",
"config",
".",
"appConfig",
".",
"createControllerFor",
";",
"if",
"(",
"!",
"referer",
".",
"match",
"(",
"createControllerFor",
")",
"&&",
"createControllerFor",
"!==",
"'yes'",
")",
"{",
"return",
"establishInitialServerSession",
"(",
"req",
",",
"controllerPath",
",",
"initObjectTemplate",
",",
"path",
",",
"appVersion",
",",
"sessionExpiration",
")",
";",
"}",
"}",
"}",
"return",
"establishContinuedServerSession",
"(",
"req",
",",
"controllerPath",
",",
"initObjectTemplate",
",",
"path",
",",
"appVersion",
",",
"sessionExpiration",
",",
"session",
",",
"sessionStore",
",",
"newControllerId",
",",
"objectCacheExpiration",
",",
"newPage",
",",
"controllers",
",",
"nonObjTemplatelogLevel",
",",
"sessions",
",",
"reset",
")",
";",
"}"
] |
Establish a server session
The entire session mechanism is predicated on the fact that there is a unique instance
of object templates for each session. There are three main use cases:
1) newPage == true means the browser wants to get everything sent to it mostly because it is arriving on a new page
or a refresh or recovery from an error (refresh)
2) reset == true - clear the current session and start fresh
3) newControllerID - if specified the browser has created a controller and will be sending the data to the server
@param {Object} req - Express request object.
@param {String} path - The app name, used to identify future requests from XML.
@param {Boolean|String} newPage - force returning everything since this is likely a session continuation on a
new web page.
@param {unknown} reset - create new clean empty controller losing all data
@param {unknown} newControllerId - client is sending us data for a new controller that it has created
@param {unknown} sessions unknown
@param {unknown} controllers unknown
@returns {Promise<Object>} Promise that resolves to server session object.
|
[
"Establish",
"a",
"server",
"session"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/session/establishServerSession.js#L33-L79
|
19,604
|
haven-life/amorphic
|
lib/routes/processPost.js
|
processPost
|
function processPost(req, res, sessions, controllers, nonObjTemplatelogLevel) {
let session = req.session;
let path = url.parse(req.originalUrl, true).query.path;
establishServerSession(req, path, false, false, null, sessions, controllers, nonObjTemplatelogLevel)
.then(function ff(semotus) {
let ourObjectTemplate = semotus.objectTemplate;
let remoteSessionId = req.session.id;
if (typeof(ourObjectTemplate.controller.processPost) === 'function') {
Bluebird.resolve(ourObjectTemplate.controller.processPost(null, req.body))
.then(function gg(controllerResp) {
ourObjectTemplate.setSession(remoteSessionId);
semotus.save(path, session, req);
res.writeHead(controllerResp.status, controllerResp.headers || {'Content-Type': 'text/plain'});
res.end(controllerResp.body);
})
.catch(function hh(e) {
ourObjectTemplate.logger.info({
component: 'amorphic',
module: 'processPost', activity: 'error'
}, 'Error ' + e.message + e.stack);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Error');
});
}
else {
throw 'Not Accepting Posts';
}
})
.catch(function ii(error) {
logMessage('Error establishing session for processPost ', req.session.id, error.message + error.stack);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Error');
});
}
|
javascript
|
function processPost(req, res, sessions, controllers, nonObjTemplatelogLevel) {
let session = req.session;
let path = url.parse(req.originalUrl, true).query.path;
establishServerSession(req, path, false, false, null, sessions, controllers, nonObjTemplatelogLevel)
.then(function ff(semotus) {
let ourObjectTemplate = semotus.objectTemplate;
let remoteSessionId = req.session.id;
if (typeof(ourObjectTemplate.controller.processPost) === 'function') {
Bluebird.resolve(ourObjectTemplate.controller.processPost(null, req.body))
.then(function gg(controllerResp) {
ourObjectTemplate.setSession(remoteSessionId);
semotus.save(path, session, req);
res.writeHead(controllerResp.status, controllerResp.headers || {'Content-Type': 'text/plain'});
res.end(controllerResp.body);
})
.catch(function hh(e) {
ourObjectTemplate.logger.info({
component: 'amorphic',
module: 'processPost', activity: 'error'
}, 'Error ' + e.message + e.stack);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Error');
});
}
else {
throw 'Not Accepting Posts';
}
})
.catch(function ii(error) {
logMessage('Error establishing session for processPost ', req.session.id, error.message + error.stack);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Error');
});
}
|
[
"function",
"processPost",
"(",
"req",
",",
"res",
",",
"sessions",
",",
"controllers",
",",
"nonObjTemplatelogLevel",
")",
"{",
"let",
"session",
"=",
"req",
".",
"session",
";",
"let",
"path",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"originalUrl",
",",
"true",
")",
".",
"query",
".",
"path",
";",
"establishServerSession",
"(",
"req",
",",
"path",
",",
"false",
",",
"false",
",",
"null",
",",
"sessions",
",",
"controllers",
",",
"nonObjTemplatelogLevel",
")",
".",
"then",
"(",
"function",
"ff",
"(",
"semotus",
")",
"{",
"let",
"ourObjectTemplate",
"=",
"semotus",
".",
"objectTemplate",
";",
"let",
"remoteSessionId",
"=",
"req",
".",
"session",
".",
"id",
";",
"if",
"(",
"typeof",
"(",
"ourObjectTemplate",
".",
"controller",
".",
"processPost",
")",
"===",
"'function'",
")",
"{",
"Bluebird",
".",
"resolve",
"(",
"ourObjectTemplate",
".",
"controller",
".",
"processPost",
"(",
"null",
",",
"req",
".",
"body",
")",
")",
".",
"then",
"(",
"function",
"gg",
"(",
"controllerResp",
")",
"{",
"ourObjectTemplate",
".",
"setSession",
"(",
"remoteSessionId",
")",
";",
"semotus",
".",
"save",
"(",
"path",
",",
"session",
",",
"req",
")",
";",
"res",
".",
"writeHead",
"(",
"controllerResp",
".",
"status",
",",
"controllerResp",
".",
"headers",
"||",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"controllerResp",
".",
"body",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"hh",
"(",
"e",
")",
"{",
"ourObjectTemplate",
".",
"logger",
".",
"info",
"(",
"{",
"component",
":",
"'amorphic'",
",",
"module",
":",
"'processPost'",
",",
"activity",
":",
"'error'",
"}",
",",
"'Error '",
"+",
"e",
".",
"message",
"+",
"e",
".",
"stack",
")",
";",
"res",
".",
"writeHead",
"(",
"500",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"'Internal Error'",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"throw",
"'Not Accepting Posts'",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"ii",
"(",
"error",
")",
"{",
"logMessage",
"(",
"'Error establishing session for processPost '",
",",
"req",
".",
"session",
".",
"id",
",",
"error",
".",
"message",
"+",
"error",
".",
"stack",
")",
";",
"res",
".",
"writeHead",
"(",
"500",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"'Internal Error'",
")",
";",
"}",
")",
";",
"}"
] |
Process a post request by establishing a session and calling the controllers processPost method
which can return a response to be sent back
@param {unknown} req unknown
@param {unknown} res unknown
@param {unknown} sessions unknown
@param {unknown} controllers unknown
|
[
"Process",
"a",
"post",
"request",
"by",
"establishing",
"a",
"session",
"and",
"calling",
"the",
"controllers",
"processPost",
"method",
"which",
"can",
"return",
"a",
"response",
"to",
"be",
"sent",
"back"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/routes/processPost.js#L19-L57
|
19,605
|
haven-life/amorphic
|
client.js
|
function () {
if (this.state == 'zombie') {
this.expireController(); // Toss anything that might have happened
RemoteObjectTemplate.enableSendMessage(true, this.sendMessage); // Re-enable sending
this.state = 'live';
this.rootId = null; // Cancel forcing our controller on server
this.refreshSession();
console.log('Getting live again - fetching state from server');
}
this.setCookie('session' + this.app, this.session, 0);
}
|
javascript
|
function () {
if (this.state == 'zombie') {
this.expireController(); // Toss anything that might have happened
RemoteObjectTemplate.enableSendMessage(true, this.sendMessage); // Re-enable sending
this.state = 'live';
this.rootId = null; // Cancel forcing our controller on server
this.refreshSession();
console.log('Getting live again - fetching state from server');
}
this.setCookie('session' + this.app, this.session, 0);
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"state",
"==",
"'zombie'",
")",
"{",
"this",
".",
"expireController",
"(",
")",
";",
"// Toss anything that might have happened",
"RemoteObjectTemplate",
".",
"enableSendMessage",
"(",
"true",
",",
"this",
".",
"sendMessage",
")",
";",
"// Re-enable sending",
"this",
".",
"state",
"=",
"'live'",
";",
"this",
".",
"rootId",
"=",
"null",
";",
"// Cancel forcing our controller on server",
"this",
".",
"refreshSession",
"(",
")",
";",
"console",
".",
"log",
"(",
"'Getting live again - fetching state from server'",
")",
";",
"}",
"this",
".",
"setCookie",
"(",
"'session'",
"+",
"this",
".",
"app",
",",
"this",
".",
"session",
",",
"0",
")",
";",
"}"
] |
When a zombie gets focus it wakes up. Pushing it's cookie makes other live windows into zombies
|
[
"When",
"a",
"zombie",
"gets",
"focus",
"it",
"wakes",
"up",
".",
"Pushing",
"it",
"s",
"cookie",
"makes",
"other",
"live",
"windows",
"into",
"zombies"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/client.js#L331-L345
|
|
19,606
|
haven-life/amorphic
|
client.js
|
function () {
if (RemoteObjectTemplate.getPendingCallCount() == 0 && this.getCookie('session' + this.app) != this.session) {
if (this.state != 'zombie') {
this.state = 'zombie';
this.expireController();
RemoteObjectTemplate.enableSendMessage(false); // Queue stuff as a zombie we will toss it later
console.log('Another browser took over, entering zombie state');
}
}
}
|
javascript
|
function () {
if (RemoteObjectTemplate.getPendingCallCount() == 0 && this.getCookie('session' + this.app) != this.session) {
if (this.state != 'zombie') {
this.state = 'zombie';
this.expireController();
RemoteObjectTemplate.enableSendMessage(false); // Queue stuff as a zombie we will toss it later
console.log('Another browser took over, entering zombie state');
}
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"RemoteObjectTemplate",
".",
"getPendingCallCount",
"(",
")",
"==",
"0",
"&&",
"this",
".",
"getCookie",
"(",
"'session'",
"+",
"this",
".",
"app",
")",
"!=",
"this",
".",
"session",
")",
"{",
"if",
"(",
"this",
".",
"state",
"!=",
"'zombie'",
")",
"{",
"this",
".",
"state",
"=",
"'zombie'",
";",
"this",
".",
"expireController",
"(",
")",
";",
"RemoteObjectTemplate",
".",
"enableSendMessage",
"(",
"false",
")",
";",
"// Queue stuff as a zombie we will toss it later",
"console",
".",
"log",
"(",
"'Another browser took over, entering zombie state'",
")",
";",
"}",
"}",
"}"
] |
Anytime we see some other windows session has been stored we become a zombie
|
[
"Anytime",
"we",
"see",
"some",
"other",
"windows",
"session",
"has",
"been",
"stored",
"we",
"become",
"a",
"zombie"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/client.js#L348-L359
|
|
19,607
|
haven-life/amorphic
|
client.js
|
function () {
var self = this;
self.activity = false;
if (self.heartBeat) {
clearTimeout(self.heartBeat);
}
self.heartBeat = setTimeout(function () {
if (self.state == 'live') {
if (self.activity) {
console.log('Server session ready to expire, activity detected, keeping alive');
self.pingSession(); // Will setup new timer
}
else if (self.controller.clientExpire && this.controller.clientExpire()) { // See if expiration handled by controller
console.log('Server session ready to expire, controller resetting itself to be offline');
return; // No new timer
}
else {
console.log('Server session ready to expire, resetting controller to be offline');
self.expireController();
}
}
}, self.sessionExpiration - self.sessionExpirationCushion);
}
|
javascript
|
function () {
var self = this;
self.activity = false;
if (self.heartBeat) {
clearTimeout(self.heartBeat);
}
self.heartBeat = setTimeout(function () {
if (self.state == 'live') {
if (self.activity) {
console.log('Server session ready to expire, activity detected, keeping alive');
self.pingSession(); // Will setup new timer
}
else if (self.controller.clientExpire && this.controller.clientExpire()) { // See if expiration handled by controller
console.log('Server session ready to expire, controller resetting itself to be offline');
return; // No new timer
}
else {
console.log('Server session ready to expire, resetting controller to be offline');
self.expireController();
}
}
}, self.sessionExpiration - self.sessionExpirationCushion);
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"activity",
"=",
"false",
";",
"if",
"(",
"self",
".",
"heartBeat",
")",
"{",
"clearTimeout",
"(",
"self",
".",
"heartBeat",
")",
";",
"}",
"self",
".",
"heartBeat",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"state",
"==",
"'live'",
")",
"{",
"if",
"(",
"self",
".",
"activity",
")",
"{",
"console",
".",
"log",
"(",
"'Server session ready to expire, activity detected, keeping alive'",
")",
";",
"self",
".",
"pingSession",
"(",
")",
";",
"// Will setup new timer",
"}",
"else",
"if",
"(",
"self",
".",
"controller",
".",
"clientExpire",
"&&",
"this",
".",
"controller",
".",
"clientExpire",
"(",
")",
")",
"{",
"// See if expiration handled by controller",
"console",
".",
"log",
"(",
"'Server session ready to expire, controller resetting itself to be offline'",
")",
";",
"return",
";",
"// No new timer",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'Server session ready to expire, resetting controller to be offline'",
")",
";",
"self",
".",
"expireController",
"(",
")",
";",
"}",
"}",
"}",
",",
"self",
".",
"sessionExpiration",
"-",
"self",
".",
"sessionExpirationCushion",
")",
";",
"}"
] |
Manage session expiration by listening for 'activity' and pinging the
the server just before the session expires
|
[
"Manage",
"session",
"expiration",
"by",
"listening",
"for",
"activity",
"and",
"pinging",
"the",
"the",
"server",
"just",
"before",
"the",
"session",
"expires"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/client.js#L365-L390
|
|
19,608
|
haven-life/amorphic
|
lib/startApplication.js
|
setUpInjectObjectTemplate
|
function setUpInjectObjectTemplate(appName, config, schema) {
let amorphicOptions = AmorphicContext.amorphicOptions || {};
let dbConfig = buildDbConfig(appName, config);
let connectToDbIfNeedBe = Bluebird.resolve(false); // Default to no need.
if (dbConfig.dbName && dbConfig.dbPath) {
if (dbConfig.dbDriver === 'mongo') {
let MongoClient = require('mongodb-bluebird');
connectToDbIfNeedBe = MongoClient.connect(dbConfig.dbPath + dbConfig.dbName);
}
else if (dbConfig.dbDriver === 'knex') {
let knex = require('knex')({
client: dbConfig.dbType,
debug: dbConfig.knexDebug,
connection: {
host: dbConfig.dbPath,
database: dbConfig.dbName,
user: dbConfig.dbUser,
password: dbConfig.dbPassword,
port: dbConfig.dbPort,
application_name: appName
},
pool: {
min: 0,
max: dbConfig.dbConnections
},
acquireConnectionTimeout: dbConfig.dbConnectionTimeout
});
connectToDbIfNeedBe = Bluebird.resolve(knex); // require('knex') is a synchronous call that already connects
}
}
return connectToDbIfNeedBe
.then(returnBoundInjectTemplate.bind(this, amorphicOptions, config, dbConfig, schema));
}
|
javascript
|
function setUpInjectObjectTemplate(appName, config, schema) {
let amorphicOptions = AmorphicContext.amorphicOptions || {};
let dbConfig = buildDbConfig(appName, config);
let connectToDbIfNeedBe = Bluebird.resolve(false); // Default to no need.
if (dbConfig.dbName && dbConfig.dbPath) {
if (dbConfig.dbDriver === 'mongo') {
let MongoClient = require('mongodb-bluebird');
connectToDbIfNeedBe = MongoClient.connect(dbConfig.dbPath + dbConfig.dbName);
}
else if (dbConfig.dbDriver === 'knex') {
let knex = require('knex')({
client: dbConfig.dbType,
debug: dbConfig.knexDebug,
connection: {
host: dbConfig.dbPath,
database: dbConfig.dbName,
user: dbConfig.dbUser,
password: dbConfig.dbPassword,
port: dbConfig.dbPort,
application_name: appName
},
pool: {
min: 0,
max: dbConfig.dbConnections
},
acquireConnectionTimeout: dbConfig.dbConnectionTimeout
});
connectToDbIfNeedBe = Bluebird.resolve(knex); // require('knex') is a synchronous call that already connects
}
}
return connectToDbIfNeedBe
.then(returnBoundInjectTemplate.bind(this, amorphicOptions, config, dbConfig, schema));
}
|
[
"function",
"setUpInjectObjectTemplate",
"(",
"appName",
",",
"config",
",",
"schema",
")",
"{",
"let",
"amorphicOptions",
"=",
"AmorphicContext",
".",
"amorphicOptions",
"||",
"{",
"}",
";",
"let",
"dbConfig",
"=",
"buildDbConfig",
"(",
"appName",
",",
"config",
")",
";",
"let",
"connectToDbIfNeedBe",
"=",
"Bluebird",
".",
"resolve",
"(",
"false",
")",
";",
"// Default to no need.",
"if",
"(",
"dbConfig",
".",
"dbName",
"&&",
"dbConfig",
".",
"dbPath",
")",
"{",
"if",
"(",
"dbConfig",
".",
"dbDriver",
"===",
"'mongo'",
")",
"{",
"let",
"MongoClient",
"=",
"require",
"(",
"'mongodb-bluebird'",
")",
";",
"connectToDbIfNeedBe",
"=",
"MongoClient",
".",
"connect",
"(",
"dbConfig",
".",
"dbPath",
"+",
"dbConfig",
".",
"dbName",
")",
";",
"}",
"else",
"if",
"(",
"dbConfig",
".",
"dbDriver",
"===",
"'knex'",
")",
"{",
"let",
"knex",
"=",
"require",
"(",
"'knex'",
")",
"(",
"{",
"client",
":",
"dbConfig",
".",
"dbType",
",",
"debug",
":",
"dbConfig",
".",
"knexDebug",
",",
"connection",
":",
"{",
"host",
":",
"dbConfig",
".",
"dbPath",
",",
"database",
":",
"dbConfig",
".",
"dbName",
",",
"user",
":",
"dbConfig",
".",
"dbUser",
",",
"password",
":",
"dbConfig",
".",
"dbPassword",
",",
"port",
":",
"dbConfig",
".",
"dbPort",
",",
"application_name",
":",
"appName",
"}",
",",
"pool",
":",
"{",
"min",
":",
"0",
",",
"max",
":",
"dbConfig",
".",
"dbConnections",
"}",
",",
"acquireConnectionTimeout",
":",
"dbConfig",
".",
"dbConnectionTimeout",
"}",
")",
";",
"connectToDbIfNeedBe",
"=",
"Bluebird",
".",
"resolve",
"(",
"knex",
")",
";",
"// require('knex') is a synchronous call that already connects",
"}",
"}",
"return",
"connectToDbIfNeedBe",
".",
"then",
"(",
"returnBoundInjectTemplate",
".",
"bind",
"(",
"this",
",",
"amorphicOptions",
",",
"config",
",",
"dbConfig",
",",
"schema",
")",
")",
";",
"}"
] |
Sets up the injectObjectTemplate function used when loading templates to make them PersistableSemotable or
simply Persistable.
@param {String} appName - The app name.
@param {Object} config - The app specific config from the config store.
@param {String} schema - The app schema.
@returns {Function} A bound function to be used when loading templates.
|
[
"Sets",
"up",
"the",
"injectObjectTemplate",
"function",
"used",
"when",
"loading",
"templates",
"to",
"make",
"them",
"PersistableSemotable",
"or",
"simply",
"Persistable",
"."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/startApplication.js#L64-L99
|
19,609
|
haven-life/amorphic
|
lib/startApplication.js
|
buildDbConfig
|
function buildDbConfig(appName, config) {
var dbDriver = fetchFromConfig(appName, config, 'dbDriver') || 'mongo';
var defaultPort = dbDriver === 'mongo' ? 27017 : 5432;
return {
dbName: fetchFromConfig(appName, config, 'dbName'),
dbPath: fetchFromConfig(appName, config, 'dbPath'),
dbDriver: dbDriver,
dbType: fetchFromConfig(appName, config, 'dbType') || 'mongo',
dbUser: fetchFromConfig(appName, config, 'dbUser') || 'nodejs',
dbPassword: fetchFromConfig(appName, config, 'dbPassword') || null,
dbConnections: parseInt(fetchFromConfig(appName, config, 'dbConnections')) || 20,
dbConcurrency: parseInt(fetchFromConfig(appName, config, 'dbConcurrency')) || 5,
dbConnectionTimeout: parseInt(fetchFromConfig(appName, config, 'dbConnectionTimeout')) || 60000,
dbPort: fetchFromConfig(appName, config, 'dbPort') || defaultPort,
knexDebug: fetchFromConfig(appName, config, 'knexDebug') || false
};
}
|
javascript
|
function buildDbConfig(appName, config) {
var dbDriver = fetchFromConfig(appName, config, 'dbDriver') || 'mongo';
var defaultPort = dbDriver === 'mongo' ? 27017 : 5432;
return {
dbName: fetchFromConfig(appName, config, 'dbName'),
dbPath: fetchFromConfig(appName, config, 'dbPath'),
dbDriver: dbDriver,
dbType: fetchFromConfig(appName, config, 'dbType') || 'mongo',
dbUser: fetchFromConfig(appName, config, 'dbUser') || 'nodejs',
dbPassword: fetchFromConfig(appName, config, 'dbPassword') || null,
dbConnections: parseInt(fetchFromConfig(appName, config, 'dbConnections')) || 20,
dbConcurrency: parseInt(fetchFromConfig(appName, config, 'dbConcurrency')) || 5,
dbConnectionTimeout: parseInt(fetchFromConfig(appName, config, 'dbConnectionTimeout')) || 60000,
dbPort: fetchFromConfig(appName, config, 'dbPort') || defaultPort,
knexDebug: fetchFromConfig(appName, config, 'knexDebug') || false
};
}
|
[
"function",
"buildDbConfig",
"(",
"appName",
",",
"config",
")",
"{",
"var",
"dbDriver",
"=",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbDriver'",
")",
"||",
"'mongo'",
";",
"var",
"defaultPort",
"=",
"dbDriver",
"===",
"'mongo'",
"?",
"27017",
":",
"5432",
";",
"return",
"{",
"dbName",
":",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbName'",
")",
",",
"dbPath",
":",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbPath'",
")",
",",
"dbDriver",
":",
"dbDriver",
",",
"dbType",
":",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbType'",
")",
"||",
"'mongo'",
",",
"dbUser",
":",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbUser'",
")",
"||",
"'nodejs'",
",",
"dbPassword",
":",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbPassword'",
")",
"||",
"null",
",",
"dbConnections",
":",
"parseInt",
"(",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbConnections'",
")",
")",
"||",
"20",
",",
"dbConcurrency",
":",
"parseInt",
"(",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbConcurrency'",
")",
")",
"||",
"5",
",",
"dbConnectionTimeout",
":",
"parseInt",
"(",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbConnectionTimeout'",
")",
")",
"||",
"60000",
",",
"dbPort",
":",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'dbPort'",
")",
"||",
"defaultPort",
",",
"knexDebug",
":",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'knexDebug'",
")",
"||",
"false",
"}",
";",
"}"
] |
Builds a data base config, pulling options from the app config.
@param {String} appName - The app name.
@param {Object} config - The app specific config from the config store.
@returns {Object} An object containing all the dbconfig options.
|
[
"Builds",
"a",
"data",
"base",
"config",
"pulling",
"options",
"from",
"the",
"app",
"config",
"."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/startApplication.js#L109-L125
|
19,610
|
haven-life/amorphic
|
lib/startApplication.js
|
fetchFromConfig
|
function fetchFromConfig(appName, config, toFetch) {
let lowerCase = toFetch.toLowerCase();
return config.nconf.get(appName + '_' + toFetch) || config.nconf.get(toFetch) || config.nconf.get(lowerCase);
}
|
javascript
|
function fetchFromConfig(appName, config, toFetch) {
let lowerCase = toFetch.toLowerCase();
return config.nconf.get(appName + '_' + toFetch) || config.nconf.get(toFetch) || config.nconf.get(lowerCase);
}
|
[
"function",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"toFetch",
")",
"{",
"let",
"lowerCase",
"=",
"toFetch",
".",
"toLowerCase",
"(",
")",
";",
"return",
"config",
".",
"nconf",
".",
"get",
"(",
"appName",
"+",
"'_'",
"+",
"toFetch",
")",
"||",
"config",
".",
"nconf",
".",
"get",
"(",
"toFetch",
")",
"||",
"config",
".",
"nconf",
".",
"get",
"(",
"lowerCase",
")",
";",
"}"
] |
Attempts to fetch a value out of the config file by first looking for the property's name in
camelCase proceeded by an underscore, then looking for the name in camelCase, then in lowercase.
@param {String} appName - The app name.
@param {Object} config - The app specific config from the config store.
@param {String} toFetch - The property you want to fetch from the config.
@returns {String|Boolean} The configuration property you requested if found, otherwise false.
|
[
"Attempts",
"to",
"fetch",
"a",
"value",
"out",
"of",
"the",
"config",
"file",
"by",
"first",
"looking",
"for",
"the",
"property",
"s",
"name",
"in",
"camelCase",
"proceeded",
"by",
"an",
"underscore",
"then",
"looking",
"for",
"the",
"name",
"in",
"camelCase",
"then",
"in",
"lowercase",
"."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/startApplication.js#L137-L141
|
19,611
|
haven-life/amorphic
|
lib/startApplication.js
|
returnBoundInjectTemplate
|
function returnBoundInjectTemplate(amorphicOptions, config, dbConfig, schema, db) {
// Return the bound version so we always keep the config and dbConfig.
return injectObjectTemplate.bind(null, amorphicOptions, config, dbConfig, db, schema);
}
|
javascript
|
function returnBoundInjectTemplate(amorphicOptions, config, dbConfig, schema, db) {
// Return the bound version so we always keep the config and dbConfig.
return injectObjectTemplate.bind(null, amorphicOptions, config, dbConfig, db, schema);
}
|
[
"function",
"returnBoundInjectTemplate",
"(",
"amorphicOptions",
",",
"config",
",",
"dbConfig",
",",
"schema",
",",
"db",
")",
"{",
"// Return the bound version so we always keep the config and dbConfig.",
"return",
"injectObjectTemplate",
".",
"bind",
"(",
"null",
",",
"amorphicOptions",
",",
"config",
",",
"dbConfig",
",",
"db",
",",
"schema",
")",
";",
"}"
] |
Returns a bound version of injectObjectTemplate. Needed because...
@param {Object} amorphicOptions - unknown
@param {Object} config - The app specific config from the config store.
@param {Object} dbConfig - An object containing all the dbconfig options.
@param {String} schema - The app schema.
@param {Object} db - A connection to the database.
@returns {Function} A bound version of injectObjectTemplate.
|
[
"Returns",
"a",
"bound",
"version",
"of",
"injectObjectTemplate",
".",
"Needed",
"because",
"..."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/startApplication.js#L154-L157
|
19,612
|
haven-life/amorphic
|
lib/startApplication.js
|
loadAppConfigToContext
|
function loadAppConfigToContext(appName, config, path, commonPath, initObjectTemplateFunc, sessionStore) {
let amorphicOptions = AmorphicContext.amorphicOptions;
AmorphicContext.applicationConfig[appName] = {
appPath: path,
commonPath: commonPath,
initObjectTemplate: initObjectTemplateFunc,
sessionExpiration: amorphicOptions.sessionExpiration,
objectCacheExpiration: amorphicOptions.objectCacheExpiration,
sessionStore: sessionStore,
appVersion: config.ver,
appConfig: config,
logLevel: fetchFromConfig(appName, config, 'logLevel') || 'info'
};
}
|
javascript
|
function loadAppConfigToContext(appName, config, path, commonPath, initObjectTemplateFunc, sessionStore) {
let amorphicOptions = AmorphicContext.amorphicOptions;
AmorphicContext.applicationConfig[appName] = {
appPath: path,
commonPath: commonPath,
initObjectTemplate: initObjectTemplateFunc,
sessionExpiration: amorphicOptions.sessionExpiration,
objectCacheExpiration: amorphicOptions.objectCacheExpiration,
sessionStore: sessionStore,
appVersion: config.ver,
appConfig: config,
logLevel: fetchFromConfig(appName, config, 'logLevel') || 'info'
};
}
|
[
"function",
"loadAppConfigToContext",
"(",
"appName",
",",
"config",
",",
"path",
",",
"commonPath",
",",
"initObjectTemplateFunc",
",",
"sessionStore",
")",
"{",
"let",
"amorphicOptions",
"=",
"AmorphicContext",
".",
"amorphicOptions",
";",
"AmorphicContext",
".",
"applicationConfig",
"[",
"appName",
"]",
"=",
"{",
"appPath",
":",
"path",
",",
"commonPath",
":",
"commonPath",
",",
"initObjectTemplate",
":",
"initObjectTemplateFunc",
",",
"sessionExpiration",
":",
"amorphicOptions",
".",
"sessionExpiration",
",",
"objectCacheExpiration",
":",
"amorphicOptions",
".",
"objectCacheExpiration",
",",
"sessionStore",
":",
"sessionStore",
",",
"appVersion",
":",
"config",
".",
"ver",
",",
"appConfig",
":",
"config",
",",
"logLevel",
":",
"fetchFromConfig",
"(",
"appName",
",",
"config",
",",
"'logLevel'",
")",
"||",
"'info'",
"}",
";",
"}"
] |
Loads the the applicationConfig for a given app.
@param {String} appName - The app name.
@param {Object} config - The app specific config from the config store.
@param {String} path - The path for app files.
@param {String} commonPath - The path for common files.
@param {Function} initObjectTemplateFunc - The function to inject props on all templates.
@param {Object} sessionStore - unknown
|
[
"Loads",
"the",
"the",
"applicationConfig",
"for",
"a",
"given",
"app",
"."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/startApplication.js#L213-L227
|
19,613
|
haven-life/amorphic
|
lib/startApplication.js
|
loadTemplates
|
function loadTemplates(appName) {
let appConfig = AmorphicContext.applicationConfig[appName] || {};
let applicationSource = AmorphicContext.applicationSource;
let applicationSourceMap = AmorphicContext.applicationSourceMap;
let controllerPath = (appConfig.appConfig.controller || 'controller.js');
let matches = controllerPath.match(/(.*?)([0-9A-Za-z_]*)\.js$/);
let prop = matches[2];
let baseTemplate = buildBaseTemplate(appConfig);
applicationSource[appName] = '';
applicationSourceMap[appName] = '';
// Inject into it any db or persist attributes needed for application
if (appConfig.initObjectTemplate && typeof appConfig.initObjectTemplate === 'function') {
appConfig.initObjectTemplate(baseTemplate);
}
return [
baseTemplate,
getTemplates(baseTemplate, appConfig.appPath, [prop + '.js'], appConfig, appName)
];
}
|
javascript
|
function loadTemplates(appName) {
let appConfig = AmorphicContext.applicationConfig[appName] || {};
let applicationSource = AmorphicContext.applicationSource;
let applicationSourceMap = AmorphicContext.applicationSourceMap;
let controllerPath = (appConfig.appConfig.controller || 'controller.js');
let matches = controllerPath.match(/(.*?)([0-9A-Za-z_]*)\.js$/);
let prop = matches[2];
let baseTemplate = buildBaseTemplate(appConfig);
applicationSource[appName] = '';
applicationSourceMap[appName] = '';
// Inject into it any db or persist attributes needed for application
if (appConfig.initObjectTemplate && typeof appConfig.initObjectTemplate === 'function') {
appConfig.initObjectTemplate(baseTemplate);
}
return [
baseTemplate,
getTemplates(baseTemplate, appConfig.appPath, [prop + '.js'], appConfig, appName)
];
}
|
[
"function",
"loadTemplates",
"(",
"appName",
")",
"{",
"let",
"appConfig",
"=",
"AmorphicContext",
".",
"applicationConfig",
"[",
"appName",
"]",
"||",
"{",
"}",
";",
"let",
"applicationSource",
"=",
"AmorphicContext",
".",
"applicationSource",
";",
"let",
"applicationSourceMap",
"=",
"AmorphicContext",
".",
"applicationSourceMap",
";",
"let",
"controllerPath",
"=",
"(",
"appConfig",
".",
"appConfig",
".",
"controller",
"||",
"'controller.js'",
")",
";",
"let",
"matches",
"=",
"controllerPath",
".",
"match",
"(",
"/",
"(.*?)([0-9A-Za-z_]*)\\.js$",
"/",
")",
";",
"let",
"prop",
"=",
"matches",
"[",
"2",
"]",
";",
"let",
"baseTemplate",
"=",
"buildBaseTemplate",
"(",
"appConfig",
")",
";",
"applicationSource",
"[",
"appName",
"]",
"=",
"''",
";",
"applicationSourceMap",
"[",
"appName",
"]",
"=",
"''",
";",
"// Inject into it any db or persist attributes needed for application",
"if",
"(",
"appConfig",
".",
"initObjectTemplate",
"&&",
"typeof",
"appConfig",
".",
"initObjectTemplate",
"===",
"'function'",
")",
"{",
"appConfig",
".",
"initObjectTemplate",
"(",
"baseTemplate",
")",
";",
"}",
"return",
"[",
"baseTemplate",
",",
"getTemplates",
"(",
"baseTemplate",
",",
"appConfig",
".",
"appPath",
",",
"[",
"prop",
"+",
"'.js'",
"]",
",",
"appConfig",
",",
"appName",
")",
"]",
";",
"}"
] |
Loads templates for an app at start up time.
@param {String} appName - The app name.
@returns {[Object, Object]} unknown
|
[
"Loads",
"templates",
"for",
"an",
"app",
"at",
"start",
"up",
"time",
"."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/startApplication.js#L236-L258
|
19,614
|
haven-life/amorphic
|
lib/startApplication.js
|
checkTypes
|
function checkTypes(classes) {
var classCount = 0, nullType = 0, nullOf = 0, propCount = 0;
for (var classKey in classes) {
++classCount;
for (var definePropertyKey in classes[classKey].amorphicProperties) {
var defineProperty = classes[classKey].amorphicProperties[definePropertyKey];
if (!defineProperty.type) {
++nullType;
console.log('Warning: ' + classKey + '.' + definePropertyKey + ' has no type');
}
if (defineProperty instanceof Array && !defineProperty.of) {
console.log('Warning: ' + classKey + '.' + definePropertyKey + ' has no of');
++nullOf
}
++propCount;
}
}
console.log(classCount + ' classes loaded with ' + propCount + ' properties (' + nullType + ' null types, ' + nullOf + ' null ofs)');
}
|
javascript
|
function checkTypes(classes) {
var classCount = 0, nullType = 0, nullOf = 0, propCount = 0;
for (var classKey in classes) {
++classCount;
for (var definePropertyKey in classes[classKey].amorphicProperties) {
var defineProperty = classes[classKey].amorphicProperties[definePropertyKey];
if (!defineProperty.type) {
++nullType;
console.log('Warning: ' + classKey + '.' + definePropertyKey + ' has no type');
}
if (defineProperty instanceof Array && !defineProperty.of) {
console.log('Warning: ' + classKey + '.' + definePropertyKey + ' has no of');
++nullOf
}
++propCount;
}
}
console.log(classCount + ' classes loaded with ' + propCount + ' properties (' + nullType + ' null types, ' + nullOf + ' null ofs)');
}
|
[
"function",
"checkTypes",
"(",
"classes",
")",
"{",
"var",
"classCount",
"=",
"0",
",",
"nullType",
"=",
"0",
",",
"nullOf",
"=",
"0",
",",
"propCount",
"=",
"0",
";",
"for",
"(",
"var",
"classKey",
"in",
"classes",
")",
"{",
"++",
"classCount",
";",
"for",
"(",
"var",
"definePropertyKey",
"in",
"classes",
"[",
"classKey",
"]",
".",
"amorphicProperties",
")",
"{",
"var",
"defineProperty",
"=",
"classes",
"[",
"classKey",
"]",
".",
"amorphicProperties",
"[",
"definePropertyKey",
"]",
";",
"if",
"(",
"!",
"defineProperty",
".",
"type",
")",
"{",
"++",
"nullType",
";",
"console",
".",
"log",
"(",
"'Warning: '",
"+",
"classKey",
"+",
"'.'",
"+",
"definePropertyKey",
"+",
"' has no type'",
")",
";",
"}",
"if",
"(",
"defineProperty",
"instanceof",
"Array",
"&&",
"!",
"defineProperty",
".",
"of",
")",
"{",
"console",
".",
"log",
"(",
"'Warning: '",
"+",
"classKey",
"+",
"'.'",
"+",
"definePropertyKey",
"+",
"' has no of'",
")",
";",
"++",
"nullOf",
"}",
"++",
"propCount",
";",
"}",
"}",
"console",
".",
"log",
"(",
"classCount",
"+",
"' classes loaded with '",
"+",
"propCount",
"+",
"' properties ('",
"+",
"nullType",
"+",
"' null types, '",
"+",
"nullOf",
"+",
"' null ofs)'",
")",
";",
"}"
] |
Make sure there are no null types
@param {Object> classes - amorphic dictionary from getClasses()
|
[
"Make",
"sure",
"there",
"are",
"no",
"null",
"types"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/startApplication.js#L301-L319
|
19,615
|
haven-life/amorphic
|
lib/session/establishContinuedServerSession.js
|
establishContinuedServerSession
|
function establishContinuedServerSession(req, controllerPath, initObjectTemplate, path, appVersion,
sessionExpiration, session, sessionStore,
newControllerId, objectCacheExpiration, newPage,
controllers, nonObjTemplatelogLevel, sessions, reset) {
let applicationConfig = AmorphicContext.applicationConfig;
let applicationPersistorProps = AmorphicContext.applicationPersistorProps;
let config = applicationConfig[path];
newControllerId = newControllerId || null;
// Create or restore the controller
let shouldReset = false;
let newSession = false;
let controller;
let ret;
if (!session.semotus || !session.semotus.controllers[path] || reset || newControllerId) {
shouldReset = true;
// TODO what is newSession, why do this?
newSession = !newControllerId;
if (!session.semotus) {
session.semotus = getDefaultSemotus();
}
if (!session.semotus.loggingContext[path]) {
session.semotus.loggingContext[path] = getLoggingContext(path, null);
}
}
controller = getController(path, controllerPath, initObjectTemplate, session, objectCacheExpiration, sessionStore, newPage, shouldReset, newControllerId, req, controllers, nonObjTemplatelogLevel, sessions);
let sessionData = getSessionCache(path, req.session.id, true, sessions);
let ourObjectTemplate = getObjectTemplate(controller);
ourObjectTemplate.memSession = sessionData;
ourObjectTemplate.reqSession = req.session;
controller.__request = req;
controller.__sessionExpiration = sessionExpiration;
req.amorphicTracking.addServerTask({name: 'Create Controller'}, process.hrtime());
ret = {
appVersion: appVersion,
newSession: newSession,
objectTemplate: ourObjectTemplate,
getMessage: function gotMessage() {
let message = this.objectTemplate.getMessage(session.id, true);
// TODO Why is newSession always true here?
message.newSession = true;
message.rootId = controller.__id__;
message.startingSequence = this.objectTemplate.maxClientSequence + 100000;
message.sessionExpiration = sessionExpiration;
message.ver = this.appVersion;
return message;
},
getServerConnectString: function yelo() {
return JSON.stringify({
url: '/amorphic/xhr?path=' + path,
message: this.getMessage()
});
},
getServerConfigString: function yolo() {
return getServerConfigString(config);
},
save: function surve(path, session, req) {
saveSession(path, session, controller, req, sessions);
},
restoreSession: function rastaSess() {
return restoreSession(path, session, controller, sessions);
},
getPersistorProps: function getPersistorProps() {
return applicationPersistorProps[path] || (this.getPersistorProps ? this.getPersistorProps() : {});
}
};
if (newPage) {
saveSession(path, session, controller, req, sessions);
}
return Bluebird.try(function g() {
return ret;
});
}
|
javascript
|
function establishContinuedServerSession(req, controllerPath, initObjectTemplate, path, appVersion,
sessionExpiration, session, sessionStore,
newControllerId, objectCacheExpiration, newPage,
controllers, nonObjTemplatelogLevel, sessions, reset) {
let applicationConfig = AmorphicContext.applicationConfig;
let applicationPersistorProps = AmorphicContext.applicationPersistorProps;
let config = applicationConfig[path];
newControllerId = newControllerId || null;
// Create or restore the controller
let shouldReset = false;
let newSession = false;
let controller;
let ret;
if (!session.semotus || !session.semotus.controllers[path] || reset || newControllerId) {
shouldReset = true;
// TODO what is newSession, why do this?
newSession = !newControllerId;
if (!session.semotus) {
session.semotus = getDefaultSemotus();
}
if (!session.semotus.loggingContext[path]) {
session.semotus.loggingContext[path] = getLoggingContext(path, null);
}
}
controller = getController(path, controllerPath, initObjectTemplate, session, objectCacheExpiration, sessionStore, newPage, shouldReset, newControllerId, req, controllers, nonObjTemplatelogLevel, sessions);
let sessionData = getSessionCache(path, req.session.id, true, sessions);
let ourObjectTemplate = getObjectTemplate(controller);
ourObjectTemplate.memSession = sessionData;
ourObjectTemplate.reqSession = req.session;
controller.__request = req;
controller.__sessionExpiration = sessionExpiration;
req.amorphicTracking.addServerTask({name: 'Create Controller'}, process.hrtime());
ret = {
appVersion: appVersion,
newSession: newSession,
objectTemplate: ourObjectTemplate,
getMessage: function gotMessage() {
let message = this.objectTemplate.getMessage(session.id, true);
// TODO Why is newSession always true here?
message.newSession = true;
message.rootId = controller.__id__;
message.startingSequence = this.objectTemplate.maxClientSequence + 100000;
message.sessionExpiration = sessionExpiration;
message.ver = this.appVersion;
return message;
},
getServerConnectString: function yelo() {
return JSON.stringify({
url: '/amorphic/xhr?path=' + path,
message: this.getMessage()
});
},
getServerConfigString: function yolo() {
return getServerConfigString(config);
},
save: function surve(path, session, req) {
saveSession(path, session, controller, req, sessions);
},
restoreSession: function rastaSess() {
return restoreSession(path, session, controller, sessions);
},
getPersistorProps: function getPersistorProps() {
return applicationPersistorProps[path] || (this.getPersistorProps ? this.getPersistorProps() : {});
}
};
if (newPage) {
saveSession(path, session, controller, req, sessions);
}
return Bluebird.try(function g() {
return ret;
});
}
|
[
"function",
"establishContinuedServerSession",
"(",
"req",
",",
"controllerPath",
",",
"initObjectTemplate",
",",
"path",
",",
"appVersion",
",",
"sessionExpiration",
",",
"session",
",",
"sessionStore",
",",
"newControllerId",
",",
"objectCacheExpiration",
",",
"newPage",
",",
"controllers",
",",
"nonObjTemplatelogLevel",
",",
"sessions",
",",
"reset",
")",
"{",
"let",
"applicationConfig",
"=",
"AmorphicContext",
".",
"applicationConfig",
";",
"let",
"applicationPersistorProps",
"=",
"AmorphicContext",
".",
"applicationPersistorProps",
";",
"let",
"config",
"=",
"applicationConfig",
"[",
"path",
"]",
";",
"newControllerId",
"=",
"newControllerId",
"||",
"null",
";",
"// Create or restore the controller",
"let",
"shouldReset",
"=",
"false",
";",
"let",
"newSession",
"=",
"false",
";",
"let",
"controller",
";",
"let",
"ret",
";",
"if",
"(",
"!",
"session",
".",
"semotus",
"||",
"!",
"session",
".",
"semotus",
".",
"controllers",
"[",
"path",
"]",
"||",
"reset",
"||",
"newControllerId",
")",
"{",
"shouldReset",
"=",
"true",
";",
"// TODO what is newSession, why do this?",
"newSession",
"=",
"!",
"newControllerId",
";",
"if",
"(",
"!",
"session",
".",
"semotus",
")",
"{",
"session",
".",
"semotus",
"=",
"getDefaultSemotus",
"(",
")",
";",
"}",
"if",
"(",
"!",
"session",
".",
"semotus",
".",
"loggingContext",
"[",
"path",
"]",
")",
"{",
"session",
".",
"semotus",
".",
"loggingContext",
"[",
"path",
"]",
"=",
"getLoggingContext",
"(",
"path",
",",
"null",
")",
";",
"}",
"}",
"controller",
"=",
"getController",
"(",
"path",
",",
"controllerPath",
",",
"initObjectTemplate",
",",
"session",
",",
"objectCacheExpiration",
",",
"sessionStore",
",",
"newPage",
",",
"shouldReset",
",",
"newControllerId",
",",
"req",
",",
"controllers",
",",
"nonObjTemplatelogLevel",
",",
"sessions",
")",
";",
"let",
"sessionData",
"=",
"getSessionCache",
"(",
"path",
",",
"req",
".",
"session",
".",
"id",
",",
"true",
",",
"sessions",
")",
";",
"let",
"ourObjectTemplate",
"=",
"getObjectTemplate",
"(",
"controller",
")",
";",
"ourObjectTemplate",
".",
"memSession",
"=",
"sessionData",
";",
"ourObjectTemplate",
".",
"reqSession",
"=",
"req",
".",
"session",
";",
"controller",
".",
"__request",
"=",
"req",
";",
"controller",
".",
"__sessionExpiration",
"=",
"sessionExpiration",
";",
"req",
".",
"amorphicTracking",
".",
"addServerTask",
"(",
"{",
"name",
":",
"'Create Controller'",
"}",
",",
"process",
".",
"hrtime",
"(",
")",
")",
";",
"ret",
"=",
"{",
"appVersion",
":",
"appVersion",
",",
"newSession",
":",
"newSession",
",",
"objectTemplate",
":",
"ourObjectTemplate",
",",
"getMessage",
":",
"function",
"gotMessage",
"(",
")",
"{",
"let",
"message",
"=",
"this",
".",
"objectTemplate",
".",
"getMessage",
"(",
"session",
".",
"id",
",",
"true",
")",
";",
"// TODO Why is newSession always true here?",
"message",
".",
"newSession",
"=",
"true",
";",
"message",
".",
"rootId",
"=",
"controller",
".",
"__id__",
";",
"message",
".",
"startingSequence",
"=",
"this",
".",
"objectTemplate",
".",
"maxClientSequence",
"+",
"100000",
";",
"message",
".",
"sessionExpiration",
"=",
"sessionExpiration",
";",
"message",
".",
"ver",
"=",
"this",
".",
"appVersion",
";",
"return",
"message",
";",
"}",
",",
"getServerConnectString",
":",
"function",
"yelo",
"(",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"{",
"url",
":",
"'/amorphic/xhr?path='",
"+",
"path",
",",
"message",
":",
"this",
".",
"getMessage",
"(",
")",
"}",
")",
";",
"}",
",",
"getServerConfigString",
":",
"function",
"yolo",
"(",
")",
"{",
"return",
"getServerConfigString",
"(",
"config",
")",
";",
"}",
",",
"save",
":",
"function",
"surve",
"(",
"path",
",",
"session",
",",
"req",
")",
"{",
"saveSession",
"(",
"path",
",",
"session",
",",
"controller",
",",
"req",
",",
"sessions",
")",
";",
"}",
",",
"restoreSession",
":",
"function",
"rastaSess",
"(",
")",
"{",
"return",
"restoreSession",
"(",
"path",
",",
"session",
",",
"controller",
",",
"sessions",
")",
";",
"}",
",",
"getPersistorProps",
":",
"function",
"getPersistorProps",
"(",
")",
"{",
"return",
"applicationPersistorProps",
"[",
"path",
"]",
"||",
"(",
"this",
".",
"getPersistorProps",
"?",
"this",
".",
"getPersistorProps",
"(",
")",
":",
"{",
"}",
")",
";",
"}",
"}",
";",
"if",
"(",
"newPage",
")",
"{",
"saveSession",
"(",
"path",
",",
"session",
",",
"controller",
",",
"req",
",",
"sessions",
")",
";",
"}",
"return",
"Bluebird",
".",
"try",
"(",
"function",
"g",
"(",
")",
"{",
"return",
"ret",
";",
"}",
")",
";",
"}"
] |
Continues an already establised session.
@param {Object} req - Express request object.
@param {String} controllerPath - The path to the main controller js file.
@param {Function} initObjectTemplate - Function that injects properties and functions onto each object template.
@param {String} path - The app name.
@param {unknown} appVersion unknown
@param {unknown} sessionExpiration unknown
@param {unknown} session unknown
@param {unknown} sessionStore unknown
@param {unknown} newControllerId unknown
@param {unknown} objectCacheExpiration unknown
@param {unknown} newPage unknown
@param {unknown} controllers unknown
@param {unknown} sessions unknown
@param {unknown} reset unknown
@returns {Object} unknown
|
[
"Continues",
"an",
"already",
"establised",
"session",
"."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/session/establishContinuedServerSession.js#L34-L125
|
19,616
|
haven-life/amorphic
|
index.js
|
Remoteable
|
function Remoteable (Base) {
return (function n(_super) {
__extends(classOne, _super);
function classOne() {
return _super !== null && _super.apply(this, arguments) || this;
}
return classOne;
}(Base));
}
|
javascript
|
function Remoteable (Base) {
return (function n(_super) {
__extends(classOne, _super);
function classOne() {
return _super !== null && _super.apply(this, arguments) || this;
}
return classOne;
}(Base));
}
|
[
"function",
"Remoteable",
"(",
"Base",
")",
"{",
"return",
"(",
"function",
"n",
"(",
"_super",
")",
"{",
"__extends",
"(",
"classOne",
",",
"_super",
")",
";",
"function",
"classOne",
"(",
")",
"{",
"return",
"_super",
"!==",
"null",
"&&",
"_super",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
"||",
"this",
";",
"}",
"return",
"classOne",
";",
"}",
"(",
"Base",
")",
")",
";",
"}"
] |
Mixin class implementation
@param {unknown} Base unknown
@constructor
@returns {unknown} unknown.
|
[
"Mixin",
"class",
"implementation"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/index.js#L99-L109
|
19,617
|
haven-life/amorphic
|
lib/typescript.js
|
bindDecorators
|
function bindDecorators (objectTemplate) {
// TODO: In what situation would objectTemplate be null and why is it acceptable just to use this as a replacement?
objectTemplate = objectTemplate || this;
this.Amorphic = objectTemplate;
this.amorphicStatic = objectTemplate;
/**
* Purpose unknown
*
* @param {unknown} target unknown
* @param {unknown} props unknown
*
* @returns {unknown} unknown.
*/
this.supertypeClass = function supertypeClass(target, props) {
if (objectTemplate.supertypeClass) {
return objectTemplate.supertypeClass(target, props, objectTemplate);
}
else {
return SupertypeDefinition.supertypeClass(target, props, objectTemplate);
}
};
/**
* Purpose unknown
*
* @returns {unknown} unknown.
*/
this.Supertype = function Supertype() {
if (objectTemplate.Supertype) {
return objectTemplate.Supertype.call(this, objectTemplate);
}
else {
return SupertypeDefinition.Supertype.call(this, objectTemplate);
}
};
this.Supertype.prototype = SupertypeDefinition.Supertype.prototype;
/**
* Purpose unknown
*
* @param {unknown} props unknown
*
* @returns {unknown} unknown.
*/
this.property = function property(props) {
if (objectTemplate.property) {
return objectTemplate.property(props, objectTemplate);
}
else {
return SupertypeDefinition.property(props, objectTemplate);
}
};
/**
* Purpose unknown
*
* @param {unknown} defineProperty unknown
*
* @returns {unknown} unknown.
*/
this.remote = function remote(defineProperty) {
if (objectTemplate.remote) {
return objectTemplate.remote(defineProperty, objectTemplate);
}
else {
return SupertypeDefinition.remote(defineProperty, objectTemplate);
}
};
/**
* Purpose unknown
*
* @returns {unknown} unknown.
*/
this.Amorphic.create = function create() {
objectTemplate.connect = unitTestConfig.startup;
return objectTemplate;
};
this.Amorphic.getInstance = function getInstance() {
return objectTemplate;
};
}
|
javascript
|
function bindDecorators (objectTemplate) {
// TODO: In what situation would objectTemplate be null and why is it acceptable just to use this as a replacement?
objectTemplate = objectTemplate || this;
this.Amorphic = objectTemplate;
this.amorphicStatic = objectTemplate;
/**
* Purpose unknown
*
* @param {unknown} target unknown
* @param {unknown} props unknown
*
* @returns {unknown} unknown.
*/
this.supertypeClass = function supertypeClass(target, props) {
if (objectTemplate.supertypeClass) {
return objectTemplate.supertypeClass(target, props, objectTemplate);
}
else {
return SupertypeDefinition.supertypeClass(target, props, objectTemplate);
}
};
/**
* Purpose unknown
*
* @returns {unknown} unknown.
*/
this.Supertype = function Supertype() {
if (objectTemplate.Supertype) {
return objectTemplate.Supertype.call(this, objectTemplate);
}
else {
return SupertypeDefinition.Supertype.call(this, objectTemplate);
}
};
this.Supertype.prototype = SupertypeDefinition.Supertype.prototype;
/**
* Purpose unknown
*
* @param {unknown} props unknown
*
* @returns {unknown} unknown.
*/
this.property = function property(props) {
if (objectTemplate.property) {
return objectTemplate.property(props, objectTemplate);
}
else {
return SupertypeDefinition.property(props, objectTemplate);
}
};
/**
* Purpose unknown
*
* @param {unknown} defineProperty unknown
*
* @returns {unknown} unknown.
*/
this.remote = function remote(defineProperty) {
if (objectTemplate.remote) {
return objectTemplate.remote(defineProperty, objectTemplate);
}
else {
return SupertypeDefinition.remote(defineProperty, objectTemplate);
}
};
/**
* Purpose unknown
*
* @returns {unknown} unknown.
*/
this.Amorphic.create = function create() {
objectTemplate.connect = unitTestConfig.startup;
return objectTemplate;
};
this.Amorphic.getInstance = function getInstance() {
return objectTemplate;
};
}
|
[
"function",
"bindDecorators",
"(",
"objectTemplate",
")",
"{",
"// TODO: In what situation would objectTemplate be null and why is it acceptable just to use this as a replacement?",
"objectTemplate",
"=",
"objectTemplate",
"||",
"this",
";",
"this",
".",
"Amorphic",
"=",
"objectTemplate",
";",
"this",
".",
"amorphicStatic",
"=",
"objectTemplate",
";",
"/**\n * Purpose unknown\n *\n * @param {unknown} target unknown\n * @param {unknown} props unknown\n *\n * @returns {unknown} unknown.\n */",
"this",
".",
"supertypeClass",
"=",
"function",
"supertypeClass",
"(",
"target",
",",
"props",
")",
"{",
"if",
"(",
"objectTemplate",
".",
"supertypeClass",
")",
"{",
"return",
"objectTemplate",
".",
"supertypeClass",
"(",
"target",
",",
"props",
",",
"objectTemplate",
")",
";",
"}",
"else",
"{",
"return",
"SupertypeDefinition",
".",
"supertypeClass",
"(",
"target",
",",
"props",
",",
"objectTemplate",
")",
";",
"}",
"}",
";",
"/**\n * Purpose unknown\n *\n * @returns {unknown} unknown.\n */",
"this",
".",
"Supertype",
"=",
"function",
"Supertype",
"(",
")",
"{",
"if",
"(",
"objectTemplate",
".",
"Supertype",
")",
"{",
"return",
"objectTemplate",
".",
"Supertype",
".",
"call",
"(",
"this",
",",
"objectTemplate",
")",
";",
"}",
"else",
"{",
"return",
"SupertypeDefinition",
".",
"Supertype",
".",
"call",
"(",
"this",
",",
"objectTemplate",
")",
";",
"}",
"}",
";",
"this",
".",
"Supertype",
".",
"prototype",
"=",
"SupertypeDefinition",
".",
"Supertype",
".",
"prototype",
";",
"/**\n * Purpose unknown\n *\n * @param {unknown} props unknown\n *\n * @returns {unknown} unknown.\n */",
"this",
".",
"property",
"=",
"function",
"property",
"(",
"props",
")",
"{",
"if",
"(",
"objectTemplate",
".",
"property",
")",
"{",
"return",
"objectTemplate",
".",
"property",
"(",
"props",
",",
"objectTemplate",
")",
";",
"}",
"else",
"{",
"return",
"SupertypeDefinition",
".",
"property",
"(",
"props",
",",
"objectTemplate",
")",
";",
"}",
"}",
";",
"/**\n * Purpose unknown\n *\n * @param {unknown} defineProperty unknown\n *\n * @returns {unknown} unknown.\n */",
"this",
".",
"remote",
"=",
"function",
"remote",
"(",
"defineProperty",
")",
"{",
"if",
"(",
"objectTemplate",
".",
"remote",
")",
"{",
"return",
"objectTemplate",
".",
"remote",
"(",
"defineProperty",
",",
"objectTemplate",
")",
";",
"}",
"else",
"{",
"return",
"SupertypeDefinition",
".",
"remote",
"(",
"defineProperty",
",",
"objectTemplate",
")",
";",
"}",
"}",
";",
"/**\n * Purpose unknown\n *\n * @returns {unknown} unknown.\n */",
"this",
".",
"Amorphic",
".",
"create",
"=",
"function",
"create",
"(",
")",
"{",
"objectTemplate",
".",
"connect",
"=",
"unitTestConfig",
".",
"startup",
";",
"return",
"objectTemplate",
";",
"}",
";",
"this",
".",
"Amorphic",
".",
"getInstance",
"=",
"function",
"getInstance",
"(",
")",
"{",
"return",
"objectTemplate",
";",
"}",
";",
"}"
] |
Passed the main index export. Will bind the decorators to either Persistor or Semotus
|
[
"Passed",
"the",
"main",
"index",
"export",
".",
"Will",
"bind",
"the",
"decorators",
"to",
"either",
"Persistor",
"or",
"Semotus"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/typescript.js#L6-L92
|
19,618
|
haven-life/amorphic
|
lib/getController.js
|
teamOutAction
|
function teamOutAction() {
sessionStore.get(sessionId, function aa(_error, expressSession) {
if (!expressSession) {
log(1, sessionId, 'Session has expired', nonObjTemplatelogLevel);
}
if (!expressSession ||
cachedController.controller.__template__.objectTemplate.getPendingCallCount() === 0) {
controllers[sessionId + path] = null;
log(1, sessionId, 'Expiring controller cache for ' + path, nonObjTemplatelogLevel);
}
else {
cachedController.timeout = setTimeout(timeoutAction, objectCacheExpiration);
log(2, sessionId, 'Extending controller cache timeout because of pending calls for ' + path,
- nonObjTemplatelogLevel);
}
});
}
|
javascript
|
function teamOutAction() {
sessionStore.get(sessionId, function aa(_error, expressSession) {
if (!expressSession) {
log(1, sessionId, 'Session has expired', nonObjTemplatelogLevel);
}
if (!expressSession ||
cachedController.controller.__template__.objectTemplate.getPendingCallCount() === 0) {
controllers[sessionId + path] = null;
log(1, sessionId, 'Expiring controller cache for ' + path, nonObjTemplatelogLevel);
}
else {
cachedController.timeout = setTimeout(timeoutAction, objectCacheExpiration);
log(2, sessionId, 'Extending controller cache timeout because of pending calls for ' + path,
- nonObjTemplatelogLevel);
}
});
}
|
[
"function",
"teamOutAction",
"(",
")",
"{",
"sessionStore",
".",
"get",
"(",
"sessionId",
",",
"function",
"aa",
"(",
"_error",
",",
"expressSession",
")",
"{",
"if",
"(",
"!",
"expressSession",
")",
"{",
"log",
"(",
"1",
",",
"sessionId",
",",
"'Session has expired'",
",",
"nonObjTemplatelogLevel",
")",
";",
"}",
"if",
"(",
"!",
"expressSession",
"||",
"cachedController",
".",
"controller",
".",
"__template__",
".",
"objectTemplate",
".",
"getPendingCallCount",
"(",
")",
"===",
"0",
")",
"{",
"controllers",
"[",
"sessionId",
"+",
"path",
"]",
"=",
"null",
";",
"log",
"(",
"1",
",",
"sessionId",
",",
"'Expiring controller cache for '",
"+",
"path",
",",
"nonObjTemplatelogLevel",
")",
";",
"}",
"else",
"{",
"cachedController",
".",
"timeout",
"=",
"setTimeout",
"(",
"timeoutAction",
",",
"objectCacheExpiration",
")",
";",
"log",
"(",
"2",
",",
"sessionId",
",",
"'Extending controller cache timeout because of pending calls for '",
"+",
"path",
",",
"-",
"nonObjTemplatelogLevel",
")",
";",
"}",
"}",
")",
";",
"}"
] |
We cache the controller object which will reference the object template and expire it as long as there are no pending calls. Note that with a memory store session manager the act of referencing the session will expire it if needed
|
[
"We",
"cache",
"the",
"controller",
"object",
"which",
"will",
"reference",
"the",
"object",
"template",
"and",
"expire",
"it",
"as",
"long",
"as",
"there",
"are",
"no",
"pending",
"calls",
".",
"Note",
"that",
"with",
"a",
"memory",
"store",
"session",
"manager",
"the",
"act",
"of",
"referencing",
"the",
"session",
"will",
"expire",
"it",
"if",
"needed"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/getController.js#L63-L80
|
19,619
|
haven-life/amorphic
|
lib/utils/readFile.js
|
readFile
|
function readFile(file) {
if (file && fs.existsSync(file)) {
return fs.readFileSync(file);
}
return null;
}
|
javascript
|
function readFile(file) {
if (file && fs.existsSync(file)) {
return fs.readFileSync(file);
}
return null;
}
|
[
"function",
"readFile",
"(",
"file",
")",
"{",
"if",
"(",
"file",
"&&",
"fs",
".",
"existsSync",
"(",
"file",
")",
")",
"{",
"return",
"fs",
".",
"readFileSync",
"(",
"file",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Checks if a file exists and if it does returns it's contents.
Otherwise returns null.
@param {String} file The path to a file.
@returns {String|null} The contents of the file if it exists.
|
[
"Checks",
"if",
"a",
"file",
"exists",
"and",
"if",
"it",
"does",
"returns",
"it",
"s",
"contents",
".",
"Otherwise",
"returns",
"null",
"."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/utils/readFile.js#L13-L20
|
19,620
|
haven-life/amorphic
|
lib/utils/logger.js
|
setupLogger
|
function setupLogger(logger, path, context, applicationConfig) {
logger.startContext(context);
logger.setLevel(applicationConfig[path].logLevel);
if (AmorphicContext.appContext.sendToLog) {
logger.sendToLog = AmorphicContext.appContext.sendToLog;
}
}
|
javascript
|
function setupLogger(logger, path, context, applicationConfig) {
logger.startContext(context);
logger.setLevel(applicationConfig[path].logLevel);
if (AmorphicContext.appContext.sendToLog) {
logger.sendToLog = AmorphicContext.appContext.sendToLog;
}
}
|
[
"function",
"setupLogger",
"(",
"logger",
",",
"path",
",",
"context",
",",
"applicationConfig",
")",
"{",
"logger",
".",
"startContext",
"(",
"context",
")",
";",
"logger",
".",
"setLevel",
"(",
"applicationConfig",
"[",
"path",
"]",
".",
"logLevel",
")",
";",
"if",
"(",
"AmorphicContext",
".",
"appContext",
".",
"sendToLog",
")",
"{",
"logger",
".",
"sendToLog",
"=",
"AmorphicContext",
".",
"appContext",
".",
"sendToLog",
";",
"}",
"}"
] |
To setup the logger based on a sendToLog function that is passed in from the application
to the listen function.
@param {unknown} logger unknown
@param {unknown} path unknown
@param {unknown} context unknown
@param {unknown} applicationConfig unknown
|
[
"To",
"setup",
"the",
"logger",
"based",
"on",
"a",
"sendToLog",
"function",
"that",
"is",
"passed",
"in",
"from",
"the",
"application",
"to",
"the",
"listen",
"function",
"."
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/utils/logger.js#L70-L77
|
19,621
|
haven-life/amorphic
|
lib/session/getSessionCache.js
|
getSessionCache
|
function getSessionCache(path, sessionId, keepTimeout, sessions) {
let key = path + '-' + sessionId;
let session = sessions[key] || {sequence: 1, serializationTimeStamp: null, timeout: null, semotus: {}};
sessions[key] = session;
if (!keepTimeout) {
if (session.timeout) {
clearTimeout(session.timeout);
}
session.timeout = setTimeout(function jj() {
if (sessions[key]) {
delete sessions[key];
}
}, AmorphicContext.amorphicOptions.sessionExpiration);
}
return session;
}
|
javascript
|
function getSessionCache(path, sessionId, keepTimeout, sessions) {
let key = path + '-' + sessionId;
let session = sessions[key] || {sequence: 1, serializationTimeStamp: null, timeout: null, semotus: {}};
sessions[key] = session;
if (!keepTimeout) {
if (session.timeout) {
clearTimeout(session.timeout);
}
session.timeout = setTimeout(function jj() {
if (sessions[key]) {
delete sessions[key];
}
}, AmorphicContext.amorphicOptions.sessionExpiration);
}
return session;
}
|
[
"function",
"getSessionCache",
"(",
"path",
",",
"sessionId",
",",
"keepTimeout",
",",
"sessions",
")",
"{",
"let",
"key",
"=",
"path",
"+",
"'-'",
"+",
"sessionId",
";",
"let",
"session",
"=",
"sessions",
"[",
"key",
"]",
"||",
"{",
"sequence",
":",
"1",
",",
"serializationTimeStamp",
":",
"null",
",",
"timeout",
":",
"null",
",",
"semotus",
":",
"{",
"}",
"}",
";",
"sessions",
"[",
"key",
"]",
"=",
"session",
";",
"if",
"(",
"!",
"keepTimeout",
")",
"{",
"if",
"(",
"session",
".",
"timeout",
")",
"{",
"clearTimeout",
"(",
"session",
".",
"timeout",
")",
";",
"}",
"session",
".",
"timeout",
"=",
"setTimeout",
"(",
"function",
"jj",
"(",
")",
"{",
"if",
"(",
"sessions",
"[",
"key",
"]",
")",
"{",
"delete",
"sessions",
"[",
"key",
"]",
";",
"}",
"}",
",",
"AmorphicContext",
".",
"amorphicOptions",
".",
"sessionExpiration",
")",
";",
"}",
"return",
"session",
";",
"}"
] |
Manage a set of data keyed by the session id used for message sequence and serialization tracking
@param {String} path - The app name.
@param {unknown} sessionId unknown
@param {unknown} keepTimeout unknown
@param {unknown} sessions unknown
@returns {*|{sequence: number, serializationTimeStamp: null, timeout: null}}
|
[
"Manage",
"a",
"set",
"of",
"data",
"keyed",
"by",
"the",
"session",
"id",
"used",
"for",
"message",
"sequence",
"and",
"serialization",
"tracking"
] |
71617053161cd8e080f2eb1deb908f3f9e9ce6bf
|
https://github.com/haven-life/amorphic/blob/71617053161cd8e080f2eb1deb908f3f9e9ce6bf/lib/session/getSessionCache.js#L15-L33
|
19,622
|
edx/edx-ui-toolkit
|
src/js/disclosure/disclosure-view.js
|
function(isVisible) {
var self = this,
$textEl = self.$el.find(self.options.toggleTextSelector);
if (isVisible) {
$textEl.text(self.$el.data('expanded-text'));
} else {
$textEl.text(self.$el.data('collapsed-text'));
}
$textEl.attr('aria-expanded', isVisible);
self.$el.toggleClass(self.options.isCollapsedClass, !isVisible);
}
|
javascript
|
function(isVisible) {
var self = this,
$textEl = self.$el.find(self.options.toggleTextSelector);
if (isVisible) {
$textEl.text(self.$el.data('expanded-text'));
} else {
$textEl.text(self.$el.data('collapsed-text'));
}
$textEl.attr('aria-expanded', isVisible);
self.$el.toggleClass(self.options.isCollapsedClass, !isVisible);
}
|
[
"function",
"(",
"isVisible",
")",
"{",
"var",
"self",
"=",
"this",
",",
"$textEl",
"=",
"self",
".",
"$el",
".",
"find",
"(",
"self",
".",
"options",
".",
"toggleTextSelector",
")",
";",
"if",
"(",
"isVisible",
")",
"{",
"$textEl",
".",
"text",
"(",
"self",
".",
"$el",
".",
"data",
"(",
"'expanded-text'",
")",
")",
";",
"}",
"else",
"{",
"$textEl",
".",
"text",
"(",
"self",
".",
"$el",
".",
"data",
"(",
"'collapsed-text'",
")",
")",
";",
"}",
"$textEl",
".",
"attr",
"(",
"'aria-expanded'",
",",
"isVisible",
")",
";",
"self",
".",
"$el",
".",
"toggleClass",
"(",
"self",
".",
"options",
".",
"isCollapsedClass",
",",
"!",
"isVisible",
")",
";",
"}"
] |
Toggles the visibility of the section.
@param {boolean} isVisible True if the section should be visible (default: false).
|
[
"Toggles",
"the",
"visibility",
"of",
"the",
"section",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/disclosure/disclosure-view.js#L33-L44
|
|
19,623
|
edx/edx-ui-toolkit
|
src/js/utils/global-loader.js
|
function(name, path) {
return function(requiredPaths, moduleFunction) {
var requiredModules = [],
pathCount = requiredPaths.length,
requiredModule,
module,
i;
for (i = 0; i < pathCount; i += 1) {
requiredModule = registeredModules[requiredPaths[i]];
requiredModules.push(requiredModule);
}
module = moduleFunction.apply(GlobalLoader, requiredModules);
registeredModules[path] = module;
edx[name] = module;
};
}
|
javascript
|
function(name, path) {
return function(requiredPaths, moduleFunction) {
var requiredModules = [],
pathCount = requiredPaths.length,
requiredModule,
module,
i;
for (i = 0; i < pathCount; i += 1) {
requiredModule = registeredModules[requiredPaths[i]];
requiredModules.push(requiredModule);
}
module = moduleFunction.apply(GlobalLoader, requiredModules);
registeredModules[path] = module;
edx[name] = module;
};
}
|
[
"function",
"(",
"name",
",",
"path",
")",
"{",
"return",
"function",
"(",
"requiredPaths",
",",
"moduleFunction",
")",
"{",
"var",
"requiredModules",
"=",
"[",
"]",
",",
"pathCount",
"=",
"requiredPaths",
".",
"length",
",",
"requiredModule",
",",
"module",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"pathCount",
";",
"i",
"+=",
"1",
")",
"{",
"requiredModule",
"=",
"registeredModules",
"[",
"requiredPaths",
"[",
"i",
"]",
"]",
";",
"requiredModules",
".",
"push",
"(",
"requiredModule",
")",
";",
"}",
"module",
"=",
"moduleFunction",
".",
"apply",
"(",
"GlobalLoader",
",",
"requiredModules",
")",
";",
"registeredModules",
"[",
"path",
"]",
"=",
"module",
";",
"edx",
"[",
"name",
"]",
"=",
"module",
";",
"}",
";",
"}"
] |
Define a module that can be accessed globally in the edx namespace.
This function will typically be used in situations where UI Toolkit
functionally is needed in code where RequireJS is not available.
The module definition should be wrapped in boilerplate as follows:
~~~ javascript
;(function(define) {
'use strict';
define([...], function(...) {
...
});
}).call(
this,
// Pick a define function as follows:
// 1. Use the default 'define' function if it is available
// 2. If not, use 'RequireJS.define' if that is available
// 3. else use the GlobalLoader to install the class into the edx namespace
typeof define === 'function' && define.amd ? define :
(typeof RequireJS !== 'undefined' ? RequireJS.define :
edx.GlobalLoader.defineAs('ModuleName', 'PATH/TO/MODULE'))
);
~~~
@param {string} name The name by which the module will be accessed.
@param {string} path The module's path.
@returns {Function} A function that will create the module.
|
[
"Define",
"a",
"module",
"that",
"can",
"be",
"accessed",
"globally",
"in",
"the",
"edx",
"namespace",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/utils/global-loader.js#L49-L64
|
|
19,624
|
edx/edx-ui-toolkit
|
src/js/pagination/paging-collection.js
|
function(page) {
var oldPage = this.state.currentPage,
self = this,
deferred = $.Deferred();
this.getPage(page - (1 - this.state.firstPage), {reset: true}).then(
function() {
self.isStale = false;
self.trigger('page_changed');
deferred.resolve();
},
function() {
self.state.currentPage = oldPage;
deferred.fail();
}
);
return deferred.promise();
}
|
javascript
|
function(page) {
var oldPage = this.state.currentPage,
self = this,
deferred = $.Deferred();
this.getPage(page - (1 - this.state.firstPage), {reset: true}).then(
function() {
self.isStale = false;
self.trigger('page_changed');
deferred.resolve();
},
function() {
self.state.currentPage = oldPage;
deferred.fail();
}
);
return deferred.promise();
}
|
[
"function",
"(",
"page",
")",
"{",
"var",
"oldPage",
"=",
"this",
".",
"state",
".",
"currentPage",
",",
"self",
"=",
"this",
",",
"deferred",
"=",
"$",
".",
"Deferred",
"(",
")",
";",
"this",
".",
"getPage",
"(",
"page",
"-",
"(",
"1",
"-",
"this",
".",
"state",
".",
"firstPage",
")",
",",
"{",
"reset",
":",
"true",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"self",
".",
"isStale",
"=",
"false",
";",
"self",
".",
"trigger",
"(",
"'page_changed'",
")",
";",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"self",
".",
"state",
".",
"currentPage",
"=",
"oldPage",
";",
"deferred",
".",
"fail",
"(",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
"(",
")",
";",
"}"
] |
Sets the current page of the collection. Page is assumed
to be one indexed, regardless of the indexing of the
underlying server API. If there is an error fetching the
page, the Backbone 'error' event is triggered and the
page does not change. A 'page_changed' event is triggered
on a successful page change.
@param page {integer} one-indexed page to change to.
|
[
"Sets",
"the",
"current",
"page",
"of",
"the",
"collection",
".",
"Page",
"is",
"assumed",
"to",
"be",
"one",
"indexed",
"regardless",
"of",
"the",
"indexing",
"of",
"the",
"underlying",
"server",
"API",
".",
"If",
"there",
"is",
"an",
"error",
"fetching",
"the",
"page",
"the",
"Backbone",
"error",
"event",
"is",
"triggered",
"and",
"the",
"page",
"does",
"not",
"change",
".",
"A",
"page_changed",
"event",
"is",
"triggered",
"on",
"a",
"successful",
"page",
"change",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/pagination/paging-collection.js#L132-L148
|
|
19,625
|
edx/edx-ui-toolkit
|
src/js/pagination/paging-collection.js
|
function() {
var deferred = $.Deferred();
if (this.isStale) {
this.setPage(1)
.done(function() {
deferred.resolve();
});
} else {
deferred.resolve();
}
return deferred.promise();
}
|
javascript
|
function() {
var deferred = $.Deferred();
if (this.isStale) {
this.setPage(1)
.done(function() {
deferred.resolve();
});
} else {
deferred.resolve();
}
return deferred.promise();
}
|
[
"function",
"(",
")",
"{",
"var",
"deferred",
"=",
"$",
".",
"Deferred",
"(",
")",
";",
"if",
"(",
"this",
".",
"isStale",
")",
"{",
"this",
".",
"setPage",
"(",
"1",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"return",
"deferred",
".",
"promise",
"(",
")",
";",
"}"
] |
Refreshes the collection if it has been marked as stale.
@returns {promise} Returns a promise representing the
refresh.
|
[
"Refreshes",
"the",
"collection",
"if",
"it",
"has",
"been",
"marked",
"as",
"stale",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/pagination/paging-collection.js#L156-L167
|
|
19,626
|
edx/edx-ui-toolkit
|
src/js/pagination/paging-collection.js
|
function(fields, fieldName, displayName) {
var newField = {};
newField[fieldName] = {
displayName: displayName
};
_.extend(fields, newField);
}
|
javascript
|
function(fields, fieldName, displayName) {
var newField = {};
newField[fieldName] = {
displayName: displayName
};
_.extend(fields, newField);
}
|
[
"function",
"(",
"fields",
",",
"fieldName",
",",
"displayName",
")",
"{",
"var",
"newField",
"=",
"{",
"}",
";",
"newField",
"[",
"fieldName",
"]",
"=",
"{",
"displayName",
":",
"displayName",
"}",
";",
"_",
".",
"extend",
"(",
"fields",
",",
"newField",
")",
";",
"}"
] |
For internal use only. Adds the given field to the given
collection of fields.
@param fields {object} object of existing fields
@param fieldName {string} name of the field for the server API
@param displayName {string} name of the field to display to the
user
|
[
"For",
"internal",
"use",
"only",
".",
"Adds",
"the",
"given",
"field",
"to",
"the",
"given",
"collection",
"of",
"fields",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/pagination/paging-collection.js#L239-L245
|
|
19,627
|
edx/edx-ui-toolkit
|
src/js/pagination/paging-collection.js
|
function(fieldName, toggleDirection) {
var direction = toggleDirection ? 0 - this.state.order : this.state.order;
if (fieldName !== this.state.sortKey || toggleDirection) {
this.setSorting(fieldName, direction);
this.isStale = true;
}
}
|
javascript
|
function(fieldName, toggleDirection) {
var direction = toggleDirection ? 0 - this.state.order : this.state.order;
if (fieldName !== this.state.sortKey || toggleDirection) {
this.setSorting(fieldName, direction);
this.isStale = true;
}
}
|
[
"function",
"(",
"fieldName",
",",
"toggleDirection",
")",
"{",
"var",
"direction",
"=",
"toggleDirection",
"?",
"0",
"-",
"this",
".",
"state",
".",
"order",
":",
"this",
".",
"state",
".",
"order",
";",
"if",
"(",
"fieldName",
"!==",
"this",
".",
"state",
".",
"sortKey",
"||",
"toggleDirection",
")",
"{",
"this",
".",
"setSorting",
"(",
"fieldName",
",",
"direction",
")",
";",
"this",
".",
"isStale",
"=",
"true",
";",
"}",
"}"
] |
Sets the field to sort on and marks the collection as
stale.
@param fieldName {string} name of the field to sort on
@param toggleDirection {boolean} if true, the sort direction is
toggled if the given field was already set
|
[
"Sets",
"the",
"field",
"to",
"sort",
"on",
"and",
"marks",
"the",
"collection",
"as",
"stale",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/pagination/paging-collection.js#L284-L290
|
|
19,628
|
edx/edx-ui-toolkit
|
src/js/pagination/paging-collection.js
|
function(fieldName) {
return _.has(this.filterableFields, fieldName) &&
!_.isUndefined(this.filterableFields[fieldName].displayName);
}
|
javascript
|
function(fieldName) {
return _.has(this.filterableFields, fieldName) &&
!_.isUndefined(this.filterableFields[fieldName].displayName);
}
|
[
"function",
"(",
"fieldName",
")",
"{",
"return",
"_",
".",
"has",
"(",
"this",
".",
"filterableFields",
",",
"fieldName",
")",
"&&",
"!",
"_",
".",
"isUndefined",
"(",
"this",
".",
"filterableFields",
"[",
"fieldName",
"]",
".",
"displayName",
")",
";",
"}"
] |
Returns whether this collection has defined a given
filterable field.
@param fieldName {string} querystring parameter name for the
filterable field
@return {boolean} Returns true if this collection has the specified field.
|
[
"Returns",
"whether",
"this",
"collection",
"has",
"defined",
"a",
"given",
"filterable",
"field",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/pagination/paging-collection.js#L346-L349
|
|
19,629
|
edx/edx-ui-toolkit
|
src/js/pagination/paging-collection.js
|
function(fieldName) {
return _.has(this.filterableFields, fieldName) && !_.isNull(this.filterableFields[fieldName].value);
}
|
javascript
|
function(fieldName) {
return _.has(this.filterableFields, fieldName) && !_.isNull(this.filterableFields[fieldName].value);
}
|
[
"function",
"(",
"fieldName",
")",
"{",
"return",
"_",
".",
"has",
"(",
"this",
".",
"filterableFields",
",",
"fieldName",
")",
"&&",
"!",
"_",
".",
"isNull",
"(",
"this",
".",
"filterableFields",
"[",
"fieldName",
"]",
".",
"value",
")",
";",
"}"
] |
Returns whether this collection has set a filterable field.
@param fieldName {string} querystring parameter name for the
filterable field
@return {boolean} Returns true if this collection has set the specified field.
|
[
"Returns",
"whether",
"this",
"collection",
"has",
"set",
"a",
"filterable",
"field",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/pagination/paging-collection.js#L358-L360
|
|
19,630
|
edx/edx-ui-toolkit
|
src/js/pagination/paging-collection.js
|
function(filterFieldName) {
var val = this.getActiveFilterFields(true)[filterFieldName];
return (_.isNull(val) || _.isUndefined(val)) ? null : val;
}
|
javascript
|
function(filterFieldName) {
var val = this.getActiveFilterFields(true)[filterFieldName];
return (_.isNull(val) || _.isUndefined(val)) ? null : val;
}
|
[
"function",
"(",
"filterFieldName",
")",
"{",
"var",
"val",
"=",
"this",
".",
"getActiveFilterFields",
"(",
"true",
")",
"[",
"filterFieldName",
"]",
";",
"return",
"(",
"_",
".",
"isNull",
"(",
"val",
")",
"||",
"_",
".",
"isUndefined",
"(",
"val",
")",
")",
"?",
"null",
":",
"val",
";",
"}"
] |
Gets the value of the given filter field.
@returns {String} the current value of the requested filter
field. null means that the filter field is not active.
|
[
"Gets",
"the",
"value",
"of",
"the",
"given",
"filter",
"field",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/pagination/paging-collection.js#L390-L393
|
|
19,631
|
edx/edx-ui-toolkit
|
src/js/pagination/paging-collection.js
|
function(fieldName, value) {
var queryStringValue;
if (!this.hasRegisteredFilterField(fieldName)) {
this.registerFilterableField(fieldName, '');
}
this.filterableFields[fieldName].value = value;
if (_.isArray(value)) {
queryStringValue = value.join(',');
} else {
queryStringValue = value;
}
this.queryParams[fieldName] = function() {
return queryStringValue || null;
};
this.isStale = true;
}
|
javascript
|
function(fieldName, value) {
var queryStringValue;
if (!this.hasRegisteredFilterField(fieldName)) {
this.registerFilterableField(fieldName, '');
}
this.filterableFields[fieldName].value = value;
if (_.isArray(value)) {
queryStringValue = value.join(',');
} else {
queryStringValue = value;
}
this.queryParams[fieldName] = function() {
return queryStringValue || null;
};
this.isStale = true;
}
|
[
"function",
"(",
"fieldName",
",",
"value",
")",
"{",
"var",
"queryStringValue",
";",
"if",
"(",
"!",
"this",
".",
"hasRegisteredFilterField",
"(",
"fieldName",
")",
")",
"{",
"this",
".",
"registerFilterableField",
"(",
"fieldName",
",",
"''",
")",
";",
"}",
"this",
".",
"filterableFields",
"[",
"fieldName",
"]",
".",
"value",
"=",
"value",
";",
"if",
"(",
"_",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"queryStringValue",
"=",
"value",
".",
"join",
"(",
"','",
")",
";",
"}",
"else",
"{",
"queryStringValue",
"=",
"value",
";",
"}",
"this",
".",
"queryParams",
"[",
"fieldName",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"queryStringValue",
"||",
"null",
";",
"}",
";",
"this",
".",
"isStale",
"=",
"true",
";",
"}"
] |
Sets a filter field to a given value and marks the
collection as stale.
@param fieldName {string} querystring parameter name for the
filterable field
@param value {*} value for the filterable field
|
[
"Sets",
"a",
"filter",
"field",
"to",
"a",
"given",
"value",
"and",
"marks",
"the",
"collection",
"as",
"stale",
"."
] |
02b0f0d25d021bdf2dca326795ed2cb10546545c
|
https://github.com/edx/edx-ui-toolkit/blob/02b0f0d25d021bdf2dca326795ed2cb10546545c/src/js/pagination/paging-collection.js#L403-L418
|
|
19,632
|
mapbox/appropriate-images
|
lib/optimize.js
|
writeOptimizedImages
|
function writeOptimizedImages(imageData) {
return Promise.all(
imageData.map(item =>
pify(fs.writeFile)(item.path, item.data).then(() => item.path)
)
);
}
|
javascript
|
function writeOptimizedImages(imageData) {
return Promise.all(
imageData.map(item =>
pify(fs.writeFile)(item.path, item.data).then(() => item.path)
)
);
}
|
[
"function",
"writeOptimizedImages",
"(",
"imageData",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"imageData",
".",
"map",
"(",
"item",
"=>",
"pify",
"(",
"fs",
".",
"writeFile",
")",
"(",
"item",
".",
"path",
",",
"item",
".",
"data",
")",
".",
"then",
"(",
"(",
")",
"=>",
"item",
".",
"path",
")",
")",
")",
";",
"}"
] |
Given output from imagemin, write image files.
@param {Array<{ path: string, data: Buffer }>} imageData - imagemin output.
@return {Promise<Array<string>>} - Resolves with an array of filenames for optimized images that
have been written.
|
[
"Given",
"output",
"from",
"imagemin",
"write",
"image",
"files",
"."
] |
35e0b8fa411c032a049287516a61416f20d4a246
|
https://github.com/mapbox/appropriate-images/blob/35e0b8fa411c032a049287516a61416f20d4a246/lib/optimize.js#L18-L24
|
19,633
|
mapbox/appropriate-images
|
lib/generate.js
|
createSizeSuffix
|
function createSizeSuffix(width, height) {
let result = String(width);
if (height !== undefined) result += `x${String(height)}`;
return result;
}
|
javascript
|
function createSizeSuffix(width, height) {
let result = String(width);
if (height !== undefined) result += `x${String(height)}`;
return result;
}
|
[
"function",
"createSizeSuffix",
"(",
"width",
",",
"height",
")",
"{",
"let",
"result",
"=",
"String",
"(",
"width",
")",
";",
"if",
"(",
"height",
"!==",
"undefined",
")",
"result",
"+=",
"`",
"${",
"String",
"(",
"height",
")",
"}",
"`",
";",
"return",
"result",
";",
"}"
] |
Put width and height together into a dimension-representing suffix.
@param {number} [width]
@param {number} [height]
@return {string}
|
[
"Put",
"width",
"and",
"height",
"together",
"into",
"a",
"dimension",
"-",
"representing",
"suffix",
"."
] |
35e0b8fa411c032a049287516a61416f20d4a246
|
https://github.com/mapbox/appropriate-images/blob/35e0b8fa411c032a049287516a61416f20d4a246/lib/generate.js#L25-L29
|
19,634
|
mapbox/appropriate-images
|
lib/generate.js
|
getCropper
|
function getCropper(name) {
// See http://sharp.dimens.io/en/stable/api-resize/#crop
//
// Possible attributes of sharp.gravity are north, northeast, east, southeast, south,
// southwest, west, northwest, center and centre.
if (sharp.gravity[name] !== undefined) {
return sharp.gravity[name];
}
// The experimental strategy-based approach resizes so one dimension is at its target
// length then repeatedly ranks edge regions, discarding the edge with the lowest
// score based on the selected strategy.
// - entropy: focus on the region with the highest Shannon entropy.
// - attention: focus on the region with the highest luminance frequency,
// colour saturation and presence of skin tones.
if (sharp.strategy[name] !== undefined) {
return sharp.strategy[name];
}
throw new UsageError(
`"${name}" is not a valid crop value. Consult http://sharp.dimens.io/en/stable/api-resize/#crop`
);
}
|
javascript
|
function getCropper(name) {
// See http://sharp.dimens.io/en/stable/api-resize/#crop
//
// Possible attributes of sharp.gravity are north, northeast, east, southeast, south,
// southwest, west, northwest, center and centre.
if (sharp.gravity[name] !== undefined) {
return sharp.gravity[name];
}
// The experimental strategy-based approach resizes so one dimension is at its target
// length then repeatedly ranks edge regions, discarding the edge with the lowest
// score based on the selected strategy.
// - entropy: focus on the region with the highest Shannon entropy.
// - attention: focus on the region with the highest luminance frequency,
// colour saturation and presence of skin tones.
if (sharp.strategy[name] !== undefined) {
return sharp.strategy[name];
}
throw new UsageError(
`"${name}" is not a valid crop value. Consult http://sharp.dimens.io/en/stable/api-resize/#crop`
);
}
|
[
"function",
"getCropper",
"(",
"name",
")",
"{",
"// See http://sharp.dimens.io/en/stable/api-resize/#crop",
"//",
"// Possible attributes of sharp.gravity are north, northeast, east, southeast, south,",
"// southwest, west, northwest, center and centre.",
"if",
"(",
"sharp",
".",
"gravity",
"[",
"name",
"]",
"!==",
"undefined",
")",
"{",
"return",
"sharp",
".",
"gravity",
"[",
"name",
"]",
";",
"}",
"// The experimental strategy-based approach resizes so one dimension is at its target",
"// length then repeatedly ranks edge regions, discarding the edge with the lowest",
"// score based on the selected strategy.",
"// - entropy: focus on the region with the highest Shannon entropy.",
"// - attention: focus on the region with the highest luminance frequency,",
"// colour saturation and presence of skin tones.",
"if",
"(",
"sharp",
".",
"strategy",
"[",
"name",
"]",
"!==",
"undefined",
")",
"{",
"return",
"sharp",
".",
"strategy",
"[",
"name",
"]",
";",
"}",
"throw",
"new",
"UsageError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
";",
"}"
] |
Get a cropper constant from sharp.
@param {string} name
@return {string}
|
[
"Get",
"a",
"cropper",
"constant",
"from",
"sharp",
"."
] |
35e0b8fa411c032a049287516a61416f20d4a246
|
https://github.com/mapbox/appropriate-images/blob/35e0b8fa411c032a049287516a61416f20d4a246/lib/generate.js#L37-L58
|
19,635
|
mapbox/appropriate-images
|
lib/generate.js
|
generateSizes
|
function generateSizes(entry, inputDirectory, outputDirectory) {
const imageFileName = path.join(inputDirectory, entry.basename);
return pify(fs.readFile)(imageFileName).then(imageBuffer => {
const sharpFile = sharp(imageBuffer);
return Promise.all(
entry.sizes.map(size => {
const sizeSuffix = createSizeSuffix(size.width, size.height);
const ext = path.extname(entry.basename);
const extlessBasename = path.basename(entry.basename, ext);
const outputFilename = path.join(
outputDirectory,
`${extlessBasename}-${sizeSuffix}${ext}`
);
const transform = sharpFile.resize(size.width, size.height);
if (size.crop !== undefined) {
transform.crop(getCropper(size.crop));
}
return transform.toFile(outputFilename).then(() => outputFilename);
})
);
});
}
|
javascript
|
function generateSizes(entry, inputDirectory, outputDirectory) {
const imageFileName = path.join(inputDirectory, entry.basename);
return pify(fs.readFile)(imageFileName).then(imageBuffer => {
const sharpFile = sharp(imageBuffer);
return Promise.all(
entry.sizes.map(size => {
const sizeSuffix = createSizeSuffix(size.width, size.height);
const ext = path.extname(entry.basename);
const extlessBasename = path.basename(entry.basename, ext);
const outputFilename = path.join(
outputDirectory,
`${extlessBasename}-${sizeSuffix}${ext}`
);
const transform = sharpFile.resize(size.width, size.height);
if (size.crop !== undefined) {
transform.crop(getCropper(size.crop));
}
return transform.toFile(outputFilename).then(() => outputFilename);
})
);
});
}
|
[
"function",
"generateSizes",
"(",
"entry",
",",
"inputDirectory",
",",
"outputDirectory",
")",
"{",
"const",
"imageFileName",
"=",
"path",
".",
"join",
"(",
"inputDirectory",
",",
"entry",
".",
"basename",
")",
";",
"return",
"pify",
"(",
"fs",
".",
"readFile",
")",
"(",
"imageFileName",
")",
".",
"then",
"(",
"imageBuffer",
"=>",
"{",
"const",
"sharpFile",
"=",
"sharp",
"(",
"imageBuffer",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"entry",
".",
"sizes",
".",
"map",
"(",
"size",
"=>",
"{",
"const",
"sizeSuffix",
"=",
"createSizeSuffix",
"(",
"size",
".",
"width",
",",
"size",
".",
"height",
")",
";",
"const",
"ext",
"=",
"path",
".",
"extname",
"(",
"entry",
".",
"basename",
")",
";",
"const",
"extlessBasename",
"=",
"path",
".",
"basename",
"(",
"entry",
".",
"basename",
",",
"ext",
")",
";",
"const",
"outputFilename",
"=",
"path",
".",
"join",
"(",
"outputDirectory",
",",
"`",
"${",
"extlessBasename",
"}",
"${",
"sizeSuffix",
"}",
"${",
"ext",
"}",
"`",
")",
";",
"const",
"transform",
"=",
"sharpFile",
".",
"resize",
"(",
"size",
".",
"width",
",",
"size",
".",
"height",
")",
";",
"if",
"(",
"size",
".",
"crop",
"!==",
"undefined",
")",
"{",
"transform",
".",
"crop",
"(",
"getCropper",
"(",
"size",
".",
"crop",
")",
")",
";",
"}",
"return",
"transform",
".",
"toFile",
"(",
"outputFilename",
")",
".",
"then",
"(",
"(",
")",
"=>",
"outputFilename",
")",
";",
"}",
")",
")",
";",
"}",
")",
";",
"}"
] |
Generate all the size variants of an image.
@param {Object} entry - Entry in the image config.
@param {string} inputDirectory
@param {string} outputDirectory
@return {Promise<Array<string>>} - Resolves with an array of the output filenames.
|
[
"Generate",
"all",
"the",
"size",
"variants",
"of",
"an",
"image",
"."
] |
35e0b8fa411c032a049287516a61416f20d4a246
|
https://github.com/mapbox/appropriate-images/blob/35e0b8fa411c032a049287516a61416f20d4a246/lib/generate.js#L68-L89
|
19,636
|
mapbox/appropriate-images
|
lib/generate.js
|
clearPriorOutput
|
function clearPriorOutput(directory, sourceImageBasename) {
const ext = path.extname(sourceImageBasename);
const extlessBasename = path.basename(sourceImageBasename, ext);
return del(path.join(directory, `${extlessBasename}*.*`));
}
|
javascript
|
function clearPriorOutput(directory, sourceImageBasename) {
const ext = path.extname(sourceImageBasename);
const extlessBasename = path.basename(sourceImageBasename, ext);
return del(path.join(directory, `${extlessBasename}*.*`));
}
|
[
"function",
"clearPriorOutput",
"(",
"directory",
",",
"sourceImageBasename",
")",
"{",
"const",
"ext",
"=",
"path",
".",
"extname",
"(",
"sourceImageBasename",
")",
";",
"const",
"extlessBasename",
"=",
"path",
".",
"basename",
"(",
"sourceImageBasename",
",",
"ext",
")",
";",
"return",
"del",
"(",
"path",
".",
"join",
"(",
"directory",
",",
"`",
"${",
"extlessBasename",
"}",
"`",
")",
")",
";",
"}"
] |
Delete all prior generated versions of an image source file.
@param {string} directory
@param {string} sourceImageBasename
@return {Promise<void>} - Resolves when the versions are deleted.
|
[
"Delete",
"all",
"prior",
"generated",
"versions",
"of",
"an",
"image",
"source",
"file",
"."
] |
35e0b8fa411c032a049287516a61416f20d4a246
|
https://github.com/mapbox/appropriate-images/blob/35e0b8fa411c032a049287516a61416f20d4a246/lib/generate.js#L98-L102
|
19,637
|
sapegin/mrm-core
|
src/npm.js
|
install
|
function install(deps, options, exec) {
options = options || {};
const dev = options.dev !== false;
const run = options.yarn || isUsingYarn() ? runYarn : runNpm;
// options.versions is a min versions mapping,
// the list of packages to install will be taken from deps
let versions = options.versions || {};
if (_.isPlainObject(deps)) {
// deps is an object with required versions
versions = deps;
deps = Object.keys(deps);
}
deps = _.castArray(deps);
const newDeps = getUnsatisfiedDeps(deps, versions, { dev });
if (newDeps.length === 0) {
return;
}
log.info(`Installing ${listify(newDeps)}...`);
const versionedDeps = newDeps.map(dep => getVersionedDep(dep, versions));
run(versionedDeps, { dev }, exec);
}
|
javascript
|
function install(deps, options, exec) {
options = options || {};
const dev = options.dev !== false;
const run = options.yarn || isUsingYarn() ? runYarn : runNpm;
// options.versions is a min versions mapping,
// the list of packages to install will be taken from deps
let versions = options.versions || {};
if (_.isPlainObject(deps)) {
// deps is an object with required versions
versions = deps;
deps = Object.keys(deps);
}
deps = _.castArray(deps);
const newDeps = getUnsatisfiedDeps(deps, versions, { dev });
if (newDeps.length === 0) {
return;
}
log.info(`Installing ${listify(newDeps)}...`);
const versionedDeps = newDeps.map(dep => getVersionedDep(dep, versions));
run(versionedDeps, { dev }, exec);
}
|
[
"function",
"install",
"(",
"deps",
",",
"options",
",",
"exec",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"const",
"dev",
"=",
"options",
".",
"dev",
"!==",
"false",
";",
"const",
"run",
"=",
"options",
".",
"yarn",
"||",
"isUsingYarn",
"(",
")",
"?",
"runYarn",
":",
"runNpm",
";",
"// options.versions is a min versions mapping,",
"// the list of packages to install will be taken from deps",
"let",
"versions",
"=",
"options",
".",
"versions",
"||",
"{",
"}",
";",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"deps",
")",
")",
"{",
"// deps is an object with required versions",
"versions",
"=",
"deps",
";",
"deps",
"=",
"Object",
".",
"keys",
"(",
"deps",
")",
";",
"}",
"deps",
"=",
"_",
".",
"castArray",
"(",
"deps",
")",
";",
"const",
"newDeps",
"=",
"getUnsatisfiedDeps",
"(",
"deps",
",",
"versions",
",",
"{",
"dev",
"}",
")",
";",
"if",
"(",
"newDeps",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"log",
".",
"info",
"(",
"`",
"${",
"listify",
"(",
"newDeps",
")",
"}",
"`",
")",
";",
"const",
"versionedDeps",
"=",
"newDeps",
".",
"map",
"(",
"dep",
"=>",
"getVersionedDep",
"(",
"dep",
",",
"versions",
")",
")",
";",
"run",
"(",
"versionedDeps",
",",
"{",
"dev",
"}",
",",
"exec",
")",
";",
"}"
] |
Install or update given npm packages if needed
|
[
"Install",
"or",
"update",
"given",
"npm",
"packages",
"if",
"needed"
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/npm.js#L12-L36
|
19,638
|
sapegin/mrm-core
|
src/npm.js
|
runNpm
|
function runNpm(deps, options, exec) {
options = options || {};
exec = exec || spawnSync;
const args = [
options.remove ? 'uninstall' : 'install',
options.dev ? '--save-dev' : '--save',
].concat(deps);
return exec('npm', args, {
stdio: options.stdio === undefined ? 'inherit' : options.stdio,
cwd: options.cwd,
});
}
|
javascript
|
function runNpm(deps, options, exec) {
options = options || {};
exec = exec || spawnSync;
const args = [
options.remove ? 'uninstall' : 'install',
options.dev ? '--save-dev' : '--save',
].concat(deps);
return exec('npm', args, {
stdio: options.stdio === undefined ? 'inherit' : options.stdio,
cwd: options.cwd,
});
}
|
[
"function",
"runNpm",
"(",
"deps",
",",
"options",
",",
"exec",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"exec",
"=",
"exec",
"||",
"spawnSync",
";",
"const",
"args",
"=",
"[",
"options",
".",
"remove",
"?",
"'uninstall'",
":",
"'install'",
",",
"options",
".",
"dev",
"?",
"'--save-dev'",
":",
"'--save'",
",",
"]",
".",
"concat",
"(",
"deps",
")",
";",
"return",
"exec",
"(",
"'npm'",
",",
"args",
",",
"{",
"stdio",
":",
"options",
".",
"stdio",
"===",
"undefined",
"?",
"'inherit'",
":",
"options",
".",
"stdio",
",",
"cwd",
":",
"options",
".",
"cwd",
",",
"}",
")",
";",
"}"
] |
Install given npm packages
@param {Array|string} deps
@param {Object} [options]
@param {boolean} [options.dev=true] --save-dev (--save by default)
@param {boolean} [options.remove=false] uninstall package (install by default)
@param {Function} [exec]
@return {Object}
|
[
"Install",
"given",
"npm",
"packages"
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/npm.js#L67-L80
|
19,639
|
sapegin/mrm-core
|
src/npm.js
|
runYarn
|
function runYarn(deps, options, exec) {
options = options || {};
exec = exec || spawnSync;
const add = options.dev ? ['add', '--dev'] : ['add'];
const remove = ['remove'];
const args = (options.remove ? remove : add).concat(deps);
return exec('yarn', args, {
stdio: options.stdio === undefined ? 'inherit' : options.stdio,
cwd: options.cwd,
});
}
|
javascript
|
function runYarn(deps, options, exec) {
options = options || {};
exec = exec || spawnSync;
const add = options.dev ? ['add', '--dev'] : ['add'];
const remove = ['remove'];
const args = (options.remove ? remove : add).concat(deps);
return exec('yarn', args, {
stdio: options.stdio === undefined ? 'inherit' : options.stdio,
cwd: options.cwd,
});
}
|
[
"function",
"runYarn",
"(",
"deps",
",",
"options",
",",
"exec",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"exec",
"=",
"exec",
"||",
"spawnSync",
";",
"const",
"add",
"=",
"options",
".",
"dev",
"?",
"[",
"'add'",
",",
"'--dev'",
"]",
":",
"[",
"'add'",
"]",
";",
"const",
"remove",
"=",
"[",
"'remove'",
"]",
";",
"const",
"args",
"=",
"(",
"options",
".",
"remove",
"?",
"remove",
":",
"add",
")",
".",
"concat",
"(",
"deps",
")",
";",
"return",
"exec",
"(",
"'yarn'",
",",
"args",
",",
"{",
"stdio",
":",
"options",
".",
"stdio",
"===",
"undefined",
"?",
"'inherit'",
":",
"options",
".",
"stdio",
",",
"cwd",
":",
"options",
".",
"cwd",
",",
"}",
")",
";",
"}"
] |
Install given Yarn packages
@param {Array|string} deps
@param {Object} [options]
@param {boolean} [options.dev=true] --dev (production by default)
@param {boolean} [options.remove=false] uninstall package (install by default)
@param {Function} [exec]
@return {Object}
|
[
"Install",
"given",
"Yarn",
"packages"
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/npm.js#L92-L104
|
19,640
|
sapegin/mrm-core
|
src/npm.js
|
getUnsatisfiedDeps
|
function getUnsatisfiedDeps(deps, versions, options) {
const ownDependencies = getOwnDependencies(options);
return deps.filter(dep => {
const required = versions[dep];
if (required && !semver.validRange(required)) {
throw new MrmError(
`Invalid npm version: ${required}. Use proper semver range syntax.`
);
}
const installed = getInstalledVersion(dep);
// Package isn’t installed yet
if (!installed) {
return true;
}
// Module is installed but not in package.json dependencies
if (!ownDependencies[dep]) {
return true;
}
// No required version specified
if (!required) {
// Install if the pacakge isn’t installed
return !installed;
}
// Install if installed version doesn't satisfy range
return !semver.satisfies(installed, required);
});
}
|
javascript
|
function getUnsatisfiedDeps(deps, versions, options) {
const ownDependencies = getOwnDependencies(options);
return deps.filter(dep => {
const required = versions[dep];
if (required && !semver.validRange(required)) {
throw new MrmError(
`Invalid npm version: ${required}. Use proper semver range syntax.`
);
}
const installed = getInstalledVersion(dep);
// Package isn’t installed yet
if (!installed) {
return true;
}
// Module is installed but not in package.json dependencies
if (!ownDependencies[dep]) {
return true;
}
// No required version specified
if (!required) {
// Install if the pacakge isn’t installed
return !installed;
}
// Install if installed version doesn't satisfy range
return !semver.satisfies(installed, required);
});
}
|
[
"function",
"getUnsatisfiedDeps",
"(",
"deps",
",",
"versions",
",",
"options",
")",
"{",
"const",
"ownDependencies",
"=",
"getOwnDependencies",
"(",
"options",
")",
";",
"return",
"deps",
".",
"filter",
"(",
"dep",
"=>",
"{",
"const",
"required",
"=",
"versions",
"[",
"dep",
"]",
";",
"if",
"(",
"required",
"&&",
"!",
"semver",
".",
"validRange",
"(",
"required",
")",
")",
"{",
"throw",
"new",
"MrmError",
"(",
"`",
"${",
"required",
"}",
"`",
")",
";",
"}",
"const",
"installed",
"=",
"getInstalledVersion",
"(",
"dep",
")",
";",
"// Package isn’t installed yet",
"if",
"(",
"!",
"installed",
")",
"{",
"return",
"true",
";",
"}",
"// Module is installed but not in package.json dependencies",
"if",
"(",
"!",
"ownDependencies",
"[",
"dep",
"]",
")",
"{",
"return",
"true",
";",
"}",
"// No required version specified",
"if",
"(",
"!",
"required",
")",
"{",
"// Install if the pacakge isn’t installed",
"return",
"!",
"installed",
";",
"}",
"// Install if installed version doesn't satisfy range",
"return",
"!",
"semver",
".",
"satisfies",
"(",
"installed",
",",
"required",
")",
";",
"}",
")",
";",
"}"
] |
Return only not installed dependencies, or dependencies which installed
version doesn't satisfy range.
@param {string[]} deps
@param {object} [versions]
@return {string[]}
|
[
"Return",
"only",
"not",
"installed",
"dependencies",
"or",
"dependencies",
"which",
"installed",
"version",
"doesn",
"t",
"satisfy",
"range",
"."
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/npm.js#L148-L181
|
19,641
|
sapegin/mrm-core
|
src/editorconfig.js
|
getStyleForFile
|
function getStyleForFile(filepath) {
const editorconfigFile = findEditorConfig(filepath);
if (editorconfigFile) {
return editorconfig.parseFromFilesSync(filepath, [
{ name: editorconfigFile, contents: readFile(editorconfigFile) },
]);
}
return {};
}
|
javascript
|
function getStyleForFile(filepath) {
const editorconfigFile = findEditorConfig(filepath);
if (editorconfigFile) {
return editorconfig.parseFromFilesSync(filepath, [
{ name: editorconfigFile, contents: readFile(editorconfigFile) },
]);
}
return {};
}
|
[
"function",
"getStyleForFile",
"(",
"filepath",
")",
"{",
"const",
"editorconfigFile",
"=",
"findEditorConfig",
"(",
"filepath",
")",
";",
"if",
"(",
"editorconfigFile",
")",
"{",
"return",
"editorconfig",
".",
"parseFromFilesSync",
"(",
"filepath",
",",
"[",
"{",
"name",
":",
"editorconfigFile",
",",
"contents",
":",
"readFile",
"(",
"editorconfigFile",
")",
"}",
",",
"]",
")",
";",
"}",
"return",
"{",
"}",
";",
"}"
] |
Read EditorConfig for a given file.
@param {string} filepath
@return {EditorConfigStyle}
|
[
"Read",
"EditorConfig",
"for",
"a",
"given",
"file",
"."
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/editorconfig.js#L45-L54
|
19,642
|
sapegin/mrm-core
|
src/editorconfig.js
|
format
|
function format(source, style) {
if (style.insert_final_newline !== undefined) {
const has = hasTrailingNewLine(source);
if (style.insert_final_newline && !has) {
source += '\n';
} else if (!style.insert_final_newline && has) {
source = source.replace(TRAILING_NEW_LINE_REGEXP, '');
}
}
return source;
}
|
javascript
|
function format(source, style) {
if (style.insert_final_newline !== undefined) {
const has = hasTrailingNewLine(source);
if (style.insert_final_newline && !has) {
source += '\n';
} else if (!style.insert_final_newline && has) {
source = source.replace(TRAILING_NEW_LINE_REGEXP, '');
}
}
return source;
}
|
[
"function",
"format",
"(",
"source",
",",
"style",
")",
"{",
"if",
"(",
"style",
".",
"insert_final_newline",
"!==",
"undefined",
")",
"{",
"const",
"has",
"=",
"hasTrailingNewLine",
"(",
"source",
")",
";",
"if",
"(",
"style",
".",
"insert_final_newline",
"&&",
"!",
"has",
")",
"{",
"source",
"+=",
"'\\n'",
";",
"}",
"else",
"if",
"(",
"!",
"style",
".",
"insert_final_newline",
"&&",
"has",
")",
"{",
"source",
"=",
"source",
".",
"replace",
"(",
"TRAILING_NEW_LINE_REGEXP",
",",
"''",
")",
";",
"}",
"}",
"return",
"source",
";",
"}"
] |
Reformat text according to a given EditorCofnig style.
Suports: insert_final_newline
@param {string} source
@param {EditorConfigStyle} style
@return {string}
|
[
"Reformat",
"text",
"according",
"to",
"a",
"given",
"EditorCofnig",
"style",
"."
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/editorconfig.js#L65-L76
|
19,643
|
sapegin/mrm-core
|
src/fs.js
|
updateFile
|
function updateFile(filename, content, exists) {
fs.mkdirpSync(path.dirname(filename));
fs.writeFileSync(filename, content);
log.added(`${exists ? 'Update' : 'Create'} ${filename}`);
}
|
javascript
|
function updateFile(filename, content, exists) {
fs.mkdirpSync(path.dirname(filename));
fs.writeFileSync(filename, content);
log.added(`${exists ? 'Update' : 'Create'} ${filename}`);
}
|
[
"function",
"updateFile",
"(",
"filename",
",",
"content",
",",
"exists",
")",
"{",
"fs",
".",
"mkdirpSync",
"(",
"path",
".",
"dirname",
"(",
"filename",
")",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"filename",
",",
"content",
")",
";",
"log",
".",
"added",
"(",
"`",
"${",
"exists",
"?",
"'Update'",
":",
"'Create'",
"}",
"${",
"filename",
"}",
"`",
")",
";",
"}"
] |
Write a file if the content was changed and print a message.
|
[
"Write",
"a",
"file",
"if",
"the",
"content",
"was",
"changed",
"and",
"print",
"a",
"message",
"."
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/fs.js#L19-L23
|
19,644
|
sapegin/mrm-core
|
src/fs.js
|
copyFiles
|
function copyFiles(sourceDir, files, options = {}) {
const { overwrite = true, errorOnExist } = options;
_.castArray(files).forEach(file => {
const sourcePath = path.resolve(sourceDir, file);
if (!fs.existsSync(sourcePath)) {
throw new MrmError(`copyFiles: source file not found: ${sourcePath}`);
}
const targetExist = fs.existsSync(file);
if (targetExist && !overwrite) {
if (errorOnExist) {
throw new MrmError(`copyFiles: target file already exists: ${file}`);
}
return;
}
const content = read(sourcePath);
// Skip copy if file contents are the same
if (content === read(file)) {
return;
}
updateFile(file, content, targetExist);
});
}
|
javascript
|
function copyFiles(sourceDir, files, options = {}) {
const { overwrite = true, errorOnExist } = options;
_.castArray(files).forEach(file => {
const sourcePath = path.resolve(sourceDir, file);
if (!fs.existsSync(sourcePath)) {
throw new MrmError(`copyFiles: source file not found: ${sourcePath}`);
}
const targetExist = fs.existsSync(file);
if (targetExist && !overwrite) {
if (errorOnExist) {
throw new MrmError(`copyFiles: target file already exists: ${file}`);
}
return;
}
const content = read(sourcePath);
// Skip copy if file contents are the same
if (content === read(file)) {
return;
}
updateFile(file, content, targetExist);
});
}
|
[
"function",
"copyFiles",
"(",
"sourceDir",
",",
"files",
",",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"{",
"overwrite",
"=",
"true",
",",
"errorOnExist",
"}",
"=",
"options",
";",
"_",
".",
"castArray",
"(",
"files",
")",
".",
"forEach",
"(",
"file",
"=>",
"{",
"const",
"sourcePath",
"=",
"path",
".",
"resolve",
"(",
"sourceDir",
",",
"file",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"sourcePath",
")",
")",
"{",
"throw",
"new",
"MrmError",
"(",
"`",
"${",
"sourcePath",
"}",
"`",
")",
";",
"}",
"const",
"targetExist",
"=",
"fs",
".",
"existsSync",
"(",
"file",
")",
";",
"if",
"(",
"targetExist",
"&&",
"!",
"overwrite",
")",
"{",
"if",
"(",
"errorOnExist",
")",
"{",
"throw",
"new",
"MrmError",
"(",
"`",
"${",
"file",
"}",
"`",
")",
";",
"}",
"return",
";",
"}",
"const",
"content",
"=",
"read",
"(",
"sourcePath",
")",
";",
"// Skip copy if file contents are the same",
"if",
"(",
"content",
"===",
"read",
"(",
"file",
")",
")",
"{",
"return",
";",
"}",
"updateFile",
"(",
"file",
",",
"content",
",",
"targetExist",
")",
";",
"}",
")",
";",
"}"
] |
Copy files from a given directory to the current working directory
|
[
"Copy",
"files",
"from",
"a",
"given",
"directory",
"to",
"the",
"current",
"working",
"directory"
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/fs.js#L26-L52
|
19,645
|
sapegin/mrm-core
|
src/fs.js
|
deleteFiles
|
function deleteFiles(files) {
_.castArray(files).forEach(file => {
if (!fs.existsSync(file)) {
return;
}
log.removed(`Delete ${file}`);
fs.removeSync(file);
});
}
|
javascript
|
function deleteFiles(files) {
_.castArray(files).forEach(file => {
if (!fs.existsSync(file)) {
return;
}
log.removed(`Delete ${file}`);
fs.removeSync(file);
});
}
|
[
"function",
"deleteFiles",
"(",
"files",
")",
"{",
"_",
".",
"castArray",
"(",
"files",
")",
".",
"forEach",
"(",
"file",
"=>",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"file",
")",
")",
"{",
"return",
";",
"}",
"log",
".",
"removed",
"(",
"`",
"${",
"file",
"}",
"`",
")",
";",
"fs",
".",
"removeSync",
"(",
"file",
")",
";",
"}",
")",
";",
"}"
] |
Delete files or folders
|
[
"Delete",
"files",
"or",
"folders"
] |
155b7b87701f7a5295c0de286e93b6352d1dc0d8
|
https://github.com/sapegin/mrm-core/blob/155b7b87701f7a5295c0de286e93b6352d1dc0d8/src/fs.js#L55-L64
|
19,646
|
OriginProtocol/origin-js
|
src/utils/retries.js
|
withRetries
|
async function withRetries(opts, fn) {
const maxRetries = opts.maxRetries || 7
const verbose = opts.verbose || false
let tryCount = 0
while (tryCount < maxRetries) {
try {
return await fn() // Do our action.
} catch (e) {
// Double wait time each failure
let waitTime = 1000 * 2**(tryCount - 1)
// Randomly jiggle wait time by 20% either way. No thundering herd.
waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4))
// Max out at two minutes
waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS)
if (verbose) {
console.log('retryable error:', e.message)
console.log(`will retry in ${waitTime / 1000} seconds`)
}
tryCount += 1
await new Promise(resolve => setTimeout(resolve, waitTime))
}
}
throw new Error('number of retries exceeded')
}
|
javascript
|
async function withRetries(opts, fn) {
const maxRetries = opts.maxRetries || 7
const verbose = opts.verbose || false
let tryCount = 0
while (tryCount < maxRetries) {
try {
return await fn() // Do our action.
} catch (e) {
// Double wait time each failure
let waitTime = 1000 * 2**(tryCount - 1)
// Randomly jiggle wait time by 20% either way. No thundering herd.
waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4))
// Max out at two minutes
waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS)
if (verbose) {
console.log('retryable error:', e.message)
console.log(`will retry in ${waitTime / 1000} seconds`)
}
tryCount += 1
await new Promise(resolve => setTimeout(resolve, waitTime))
}
}
throw new Error('number of retries exceeded')
}
|
[
"async",
"function",
"withRetries",
"(",
"opts",
",",
"fn",
")",
"{",
"const",
"maxRetries",
"=",
"opts",
".",
"maxRetries",
"||",
"7",
"const",
"verbose",
"=",
"opts",
".",
"verbose",
"||",
"false",
"let",
"tryCount",
"=",
"0",
"while",
"(",
"tryCount",
"<",
"maxRetries",
")",
"{",
"try",
"{",
"return",
"await",
"fn",
"(",
")",
"// Do our action.",
"}",
"catch",
"(",
"e",
")",
"{",
"// Double wait time each failure",
"let",
"waitTime",
"=",
"1000",
"*",
"2",
"**",
"(",
"tryCount",
"-",
"1",
")",
"// Randomly jiggle wait time by 20% either way. No thundering herd.",
"waitTime",
"=",
"Math",
".",
"floor",
"(",
"waitTime",
"*",
"(",
"1.2",
"-",
"Math",
".",
"random",
"(",
")",
"*",
"0.4",
")",
")",
"// Max out at two minutes",
"waitTime",
"=",
"Math",
".",
"min",
"(",
"waitTime",
",",
"MAX_RETRY_WAIT_MS",
")",
"if",
"(",
"verbose",
")",
"{",
"console",
".",
"log",
"(",
"'retryable error:'",
",",
"e",
".",
"message",
")",
"console",
".",
"log",
"(",
"`",
"${",
"waitTime",
"/",
"1000",
"}",
"`",
")",
"}",
"tryCount",
"+=",
"1",
"await",
"new",
"Promise",
"(",
"resolve",
"=>",
"setTimeout",
"(",
"resolve",
",",
"waitTime",
")",
")",
"}",
"}",
"throw",
"new",
"Error",
"(",
"'number of retries exceeded'",
")",
"}"
] |
Retries up to maxRetries times.
@param {object} opts - Options (maxRetries, verbose)
@param {function} fn - Async function to retry.
@returns - Return value of 'fn' if it succeeded.
|
[
"Retries",
"up",
"to",
"maxRetries",
"times",
"."
] |
10191926afa6c52a0468fa5e6532ecff4e5b08fe
|
https://github.com/OriginProtocol/origin-js/blob/10191926afa6c52a0468fa5e6532ecff4e5b08fe/src/utils/retries.js#L9-L33
|
19,647
|
OriginProtocol/origin-js
|
token/faucet/app.js
|
runApp
|
function runApp(config) {
const app = express()
const token = new Token(config)
// Configure rate limiting. Allow at most 1 request per IP every 60 sec.
const opts = {
points: 1, // Point budget.
duration: 60, // Reset points consumption every 60 sec.
}
const rateLimiter = new RateLimiterMemory(opts)
const rateLimiterMiddleware = (req, res, next) => {
// Rate limiting only applies to the /tokens route.
if (req.url.startsWith('/tokens')) {
rateLimiter.consume(req.connection.remoteAddress)
.then(() => {
// Allow request and consume 1 point.
next()
})
.catch((err) => {
// Not enough points. Block the request.
console.log(`Rejecting request due to rate limiting.`)
res.status(429).send('<h2>Too Many Requests</h2>')
})
} else {
next()
}
}
// Note: register rate limiting middleware *before* all routes
// so that it gets executed first.
app.use(rateLimiterMiddleware)
// Configure directory for public assets.
app.use(express.static(__dirname + '/public'))
// Register the /tokens route for crediting tokens.
app.get('/tokens', async function (req, res, next) {
const networkId = req.query.network_id
const wallet = req.query.wallet
if (!req.query.wallet) {
res.send('<h2>Error: A wallet address must be supplied.</h2>')
} else if (!Web3.utils.isAddress(wallet)) {
res.send(`<h2>Error: ${wallet} is a malformed wallet address.</h2>`)
return
}
try {
// Transfer NUM_TOKENS to specified wallet.
const value = token.toNaturalUnit(NUM_TOKENS)
const contractAddress = token.contractAddress(networkId)
const receipt = await token.credit(networkId, wallet, value)
const txHash = receipt.transactionHash
console.log(`${NUM_TOKENS} OGN -> ${wallet} TxHash=${txHash}`)
// Send response back to client.
const resp = `Credited ${NUM_TOKENS} OGN tokens to wallet ${wallet}<br>` +
`TxHash = ${txHash}<br>` +
`OGN token contract address = ${contractAddress}`
res.send(resp)
} catch (err) {
next(err) // Errors will be passed to Express.
}
})
// Start the server.
app.listen(
config.port || DEFAULT_SERVER_PORT,
() => console.log(`Origin faucet app listening on port ${config.port}!`))
}
|
javascript
|
function runApp(config) {
const app = express()
const token = new Token(config)
// Configure rate limiting. Allow at most 1 request per IP every 60 sec.
const opts = {
points: 1, // Point budget.
duration: 60, // Reset points consumption every 60 sec.
}
const rateLimiter = new RateLimiterMemory(opts)
const rateLimiterMiddleware = (req, res, next) => {
// Rate limiting only applies to the /tokens route.
if (req.url.startsWith('/tokens')) {
rateLimiter.consume(req.connection.remoteAddress)
.then(() => {
// Allow request and consume 1 point.
next()
})
.catch((err) => {
// Not enough points. Block the request.
console.log(`Rejecting request due to rate limiting.`)
res.status(429).send('<h2>Too Many Requests</h2>')
})
} else {
next()
}
}
// Note: register rate limiting middleware *before* all routes
// so that it gets executed first.
app.use(rateLimiterMiddleware)
// Configure directory for public assets.
app.use(express.static(__dirname + '/public'))
// Register the /tokens route for crediting tokens.
app.get('/tokens', async function (req, res, next) {
const networkId = req.query.network_id
const wallet = req.query.wallet
if (!req.query.wallet) {
res.send('<h2>Error: A wallet address must be supplied.</h2>')
} else if (!Web3.utils.isAddress(wallet)) {
res.send(`<h2>Error: ${wallet} is a malformed wallet address.</h2>`)
return
}
try {
// Transfer NUM_TOKENS to specified wallet.
const value = token.toNaturalUnit(NUM_TOKENS)
const contractAddress = token.contractAddress(networkId)
const receipt = await token.credit(networkId, wallet, value)
const txHash = receipt.transactionHash
console.log(`${NUM_TOKENS} OGN -> ${wallet} TxHash=${txHash}`)
// Send response back to client.
const resp = `Credited ${NUM_TOKENS} OGN tokens to wallet ${wallet}<br>` +
`TxHash = ${txHash}<br>` +
`OGN token contract address = ${contractAddress}`
res.send(resp)
} catch (err) {
next(err) // Errors will be passed to Express.
}
})
// Start the server.
app.listen(
config.port || DEFAULT_SERVER_PORT,
() => console.log(`Origin faucet app listening on port ${config.port}!`))
}
|
[
"function",
"runApp",
"(",
"config",
")",
"{",
"const",
"app",
"=",
"express",
"(",
")",
"const",
"token",
"=",
"new",
"Token",
"(",
"config",
")",
"// Configure rate limiting. Allow at most 1 request per IP every 60 sec.",
"const",
"opts",
"=",
"{",
"points",
":",
"1",
",",
"// Point budget.",
"duration",
":",
"60",
",",
"// Reset points consumption every 60 sec.",
"}",
"const",
"rateLimiter",
"=",
"new",
"RateLimiterMemory",
"(",
"opts",
")",
"const",
"rateLimiterMiddleware",
"=",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"// Rate limiting only applies to the /tokens route.",
"if",
"(",
"req",
".",
"url",
".",
"startsWith",
"(",
"'/tokens'",
")",
")",
"{",
"rateLimiter",
".",
"consume",
"(",
"req",
".",
"connection",
".",
"remoteAddress",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"// Allow request and consume 1 point.",
"next",
"(",
")",
"}",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"// Not enough points. Block the request.",
"console",
".",
"log",
"(",
"`",
"`",
")",
"res",
".",
"status",
"(",
"429",
")",
".",
"send",
"(",
"'<h2>Too Many Requests</h2>'",
")",
"}",
")",
"}",
"else",
"{",
"next",
"(",
")",
"}",
"}",
"// Note: register rate limiting middleware *before* all routes",
"// so that it gets executed first.",
"app",
".",
"use",
"(",
"rateLimiterMiddleware",
")",
"// Configure directory for public assets.",
"app",
".",
"use",
"(",
"express",
".",
"static",
"(",
"__dirname",
"+",
"'/public'",
")",
")",
"// Register the /tokens route for crediting tokens.",
"app",
".",
"get",
"(",
"'/tokens'",
",",
"async",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"const",
"networkId",
"=",
"req",
".",
"query",
".",
"network_id",
"const",
"wallet",
"=",
"req",
".",
"query",
".",
"wallet",
"if",
"(",
"!",
"req",
".",
"query",
".",
"wallet",
")",
"{",
"res",
".",
"send",
"(",
"'<h2>Error: A wallet address must be supplied.</h2>'",
")",
"}",
"else",
"if",
"(",
"!",
"Web3",
".",
"utils",
".",
"isAddress",
"(",
"wallet",
")",
")",
"{",
"res",
".",
"send",
"(",
"`",
"${",
"wallet",
"}",
"`",
")",
"return",
"}",
"try",
"{",
"// Transfer NUM_TOKENS to specified wallet.",
"const",
"value",
"=",
"token",
".",
"toNaturalUnit",
"(",
"NUM_TOKENS",
")",
"const",
"contractAddress",
"=",
"token",
".",
"contractAddress",
"(",
"networkId",
")",
"const",
"receipt",
"=",
"await",
"token",
".",
"credit",
"(",
"networkId",
",",
"wallet",
",",
"value",
")",
"const",
"txHash",
"=",
"receipt",
".",
"transactionHash",
"console",
".",
"log",
"(",
"`",
"${",
"NUM_TOKENS",
"}",
"${",
"wallet",
"}",
"${",
"txHash",
"}",
"`",
")",
"// Send response back to client.",
"const",
"resp",
"=",
"`",
"${",
"NUM_TOKENS",
"}",
"${",
"wallet",
"}",
"`",
"+",
"`",
"${",
"txHash",
"}",
"`",
"+",
"`",
"${",
"contractAddress",
"}",
"`",
"res",
".",
"send",
"(",
"resp",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"next",
"(",
"err",
")",
"// Errors will be passed to Express.",
"}",
"}",
")",
"// Start the server.",
"app",
".",
"listen",
"(",
"config",
".",
"port",
"||",
"DEFAULT_SERVER_PORT",
",",
"(",
")",
"=>",
"console",
".",
"log",
"(",
"`",
"${",
"config",
".",
"port",
"}",
"`",
")",
")",
"}"
] |
Starts the Express server.
|
[
"Starts",
"the",
"Express",
"server",
"."
] |
10191926afa6c52a0468fa5e6532ecff4e5b08fe
|
https://github.com/OriginProtocol/origin-js/blob/10191926afa6c52a0468fa5e6532ecff4e5b08fe/token/faucet/app.js#L16-L83
|
19,648
|
OriginProtocol/origin-js
|
daemon/indexing/listener/listener.js
|
liveTracking
|
async function liveTracking(config) {
setupOriginJS(config)
const context = await new Context(config).init()
let lastLogBlock = getLastBlock(config)
let lastCheckedBlock = 0
const checkIntervalSeconds = 5
let start
const check = async () => {
await withRetrys(async () => {
start = new Date()
const currentBlockNumber = await web3.eth.getBlockNumber()
if (currentBlockNumber == lastCheckedBlock) {
console.log('No new block.')
return scheduleNextCheck()
}
console.log('New block: ' + currentBlockNumber)
const toBlock = Math.min(lastLogBlock+MAX_BATCH_BLOCKS, currentBlockNumber)
const opts = { fromBlock: lastLogBlock + 1, toBlock: toBlock }
await runBatch(opts, context)
lastLogBlock = toBlock
setLastBlock(config, toBlock)
lastCheckedBlock = currentBlockNumber
return scheduleNextCheck()
})
}
const scheduleNextCheck = async () => {
const elapsed = new Date() - start
const delay = Math.max(checkIntervalSeconds * 1000 - elapsed, 1)
setTimeout(check, delay)
}
check()
}
|
javascript
|
async function liveTracking(config) {
setupOriginJS(config)
const context = await new Context(config).init()
let lastLogBlock = getLastBlock(config)
let lastCheckedBlock = 0
const checkIntervalSeconds = 5
let start
const check = async () => {
await withRetrys(async () => {
start = new Date()
const currentBlockNumber = await web3.eth.getBlockNumber()
if (currentBlockNumber == lastCheckedBlock) {
console.log('No new block.')
return scheduleNextCheck()
}
console.log('New block: ' + currentBlockNumber)
const toBlock = Math.min(lastLogBlock+MAX_BATCH_BLOCKS, currentBlockNumber)
const opts = { fromBlock: lastLogBlock + 1, toBlock: toBlock }
await runBatch(opts, context)
lastLogBlock = toBlock
setLastBlock(config, toBlock)
lastCheckedBlock = currentBlockNumber
return scheduleNextCheck()
})
}
const scheduleNextCheck = async () => {
const elapsed = new Date() - start
const delay = Math.max(checkIntervalSeconds * 1000 - elapsed, 1)
setTimeout(check, delay)
}
check()
}
|
[
"async",
"function",
"liveTracking",
"(",
"config",
")",
"{",
"setupOriginJS",
"(",
"config",
")",
"const",
"context",
"=",
"await",
"new",
"Context",
"(",
"config",
")",
".",
"init",
"(",
")",
"let",
"lastLogBlock",
"=",
"getLastBlock",
"(",
"config",
")",
"let",
"lastCheckedBlock",
"=",
"0",
"const",
"checkIntervalSeconds",
"=",
"5",
"let",
"start",
"const",
"check",
"=",
"async",
"(",
")",
"=>",
"{",
"await",
"withRetrys",
"(",
"async",
"(",
")",
"=>",
"{",
"start",
"=",
"new",
"Date",
"(",
")",
"const",
"currentBlockNumber",
"=",
"await",
"web3",
".",
"eth",
".",
"getBlockNumber",
"(",
")",
"if",
"(",
"currentBlockNumber",
"==",
"lastCheckedBlock",
")",
"{",
"console",
".",
"log",
"(",
"'No new block.'",
")",
"return",
"scheduleNextCheck",
"(",
")",
"}",
"console",
".",
"log",
"(",
"'New block: '",
"+",
"currentBlockNumber",
")",
"const",
"toBlock",
"=",
"Math",
".",
"min",
"(",
"lastLogBlock",
"+",
"MAX_BATCH_BLOCKS",
",",
"currentBlockNumber",
")",
"const",
"opts",
"=",
"{",
"fromBlock",
":",
"lastLogBlock",
"+",
"1",
",",
"toBlock",
":",
"toBlock",
"}",
"await",
"runBatch",
"(",
"opts",
",",
"context",
")",
"lastLogBlock",
"=",
"toBlock",
"setLastBlock",
"(",
"config",
",",
"toBlock",
")",
"lastCheckedBlock",
"=",
"currentBlockNumber",
"return",
"scheduleNextCheck",
"(",
")",
"}",
")",
"}",
"const",
"scheduleNextCheck",
"=",
"async",
"(",
")",
"=>",
"{",
"const",
"elapsed",
"=",
"new",
"Date",
"(",
")",
"-",
"start",
"const",
"delay",
"=",
"Math",
".",
"max",
"(",
"checkIntervalSeconds",
"*",
"1000",
"-",
"elapsed",
",",
"1",
")",
"setTimeout",
"(",
"check",
",",
"delay",
")",
"}",
"check",
"(",
")",
"}"
] |
liveTracking - checks for a new block every checkIntervalSeconds - if new block appeared, look for all events after the last found event
|
[
"liveTracking",
"-",
"checks",
"for",
"a",
"new",
"block",
"every",
"checkIntervalSeconds",
"-",
"if",
"new",
"block",
"appeared",
"look",
"for",
"all",
"events",
"after",
"the",
"last",
"found",
"event"
] |
10191926afa6c52a0468fa5e6532ecff4e5b08fe
|
https://github.com/OriginProtocol/origin-js/blob/10191926afa6c52a0468fa5e6532ecff4e5b08fe/daemon/indexing/listener/listener.js#L132-L166
|
19,649
|
OriginProtocol/origin-js
|
daemon/indexing/listener/listener.js
|
runBatch
|
async function runBatch(opts, context) {
const fromBlock = opts.fromBlock
const toBlock = opts.toBlock
let lastLogBlock = undefined
console.log(
'Looking for logs from block ' + fromBlock + ' to ' + (toBlock || 'Latest')
)
const eventTopics = Object.keys(context.signatureToRules)
const logs = await web3.eth.getPastLogs({
fromBlock: web3.utils.toHex(fromBlock), // Hex required for infura
toBlock: toBlock ? web3.utils.toHex(toBlock) : "latest", // Hex required for infura
topics: [eventTopics]
})
if (logs.length > 0) {
console.log('' + logs.length + ' logs found')
}
for (const log of logs) {
const contractVersion = context.addressToVersion[log.address]
if (contractVersion == undefined) {
continue // Skip - Not a trusted contract
}
const contractName = contractVersion.contractName
const rule = context.signatureToRules[log.topics[0]][contractName]
if (rule == undefined) {
continue // Skip - No handler defined
}
lastLogBlock = log.blockNumber
// Process it
await handleLog(log, rule, contractVersion, context)
}
return lastLogBlock
}
|
javascript
|
async function runBatch(opts, context) {
const fromBlock = opts.fromBlock
const toBlock = opts.toBlock
let lastLogBlock = undefined
console.log(
'Looking for logs from block ' + fromBlock + ' to ' + (toBlock || 'Latest')
)
const eventTopics = Object.keys(context.signatureToRules)
const logs = await web3.eth.getPastLogs({
fromBlock: web3.utils.toHex(fromBlock), // Hex required for infura
toBlock: toBlock ? web3.utils.toHex(toBlock) : "latest", // Hex required for infura
topics: [eventTopics]
})
if (logs.length > 0) {
console.log('' + logs.length + ' logs found')
}
for (const log of logs) {
const contractVersion = context.addressToVersion[log.address]
if (contractVersion == undefined) {
continue // Skip - Not a trusted contract
}
const contractName = contractVersion.contractName
const rule = context.signatureToRules[log.topics[0]][contractName]
if (rule == undefined) {
continue // Skip - No handler defined
}
lastLogBlock = log.blockNumber
// Process it
await handleLog(log, rule, contractVersion, context)
}
return lastLogBlock
}
|
[
"async",
"function",
"runBatch",
"(",
"opts",
",",
"context",
")",
"{",
"const",
"fromBlock",
"=",
"opts",
".",
"fromBlock",
"const",
"toBlock",
"=",
"opts",
".",
"toBlock",
"let",
"lastLogBlock",
"=",
"undefined",
"console",
".",
"log",
"(",
"'Looking for logs from block '",
"+",
"fromBlock",
"+",
"' to '",
"+",
"(",
"toBlock",
"||",
"'Latest'",
")",
")",
"const",
"eventTopics",
"=",
"Object",
".",
"keys",
"(",
"context",
".",
"signatureToRules",
")",
"const",
"logs",
"=",
"await",
"web3",
".",
"eth",
".",
"getPastLogs",
"(",
"{",
"fromBlock",
":",
"web3",
".",
"utils",
".",
"toHex",
"(",
"fromBlock",
")",
",",
"// Hex required for infura",
"toBlock",
":",
"toBlock",
"?",
"web3",
".",
"utils",
".",
"toHex",
"(",
"toBlock",
")",
":",
"\"latest\"",
",",
"// Hex required for infura",
"topics",
":",
"[",
"eventTopics",
"]",
"}",
")",
"if",
"(",
"logs",
".",
"length",
">",
"0",
")",
"{",
"console",
".",
"log",
"(",
"''",
"+",
"logs",
".",
"length",
"+",
"' logs found'",
")",
"}",
"for",
"(",
"const",
"log",
"of",
"logs",
")",
"{",
"const",
"contractVersion",
"=",
"context",
".",
"addressToVersion",
"[",
"log",
".",
"address",
"]",
"if",
"(",
"contractVersion",
"==",
"undefined",
")",
"{",
"continue",
"// Skip - Not a trusted contract",
"}",
"const",
"contractName",
"=",
"contractVersion",
".",
"contractName",
"const",
"rule",
"=",
"context",
".",
"signatureToRules",
"[",
"log",
".",
"topics",
"[",
"0",
"]",
"]",
"[",
"contractName",
"]",
"if",
"(",
"rule",
"==",
"undefined",
")",
"{",
"continue",
"// Skip - No handler defined",
"}",
"lastLogBlock",
"=",
"log",
".",
"blockNumber",
"// Process it",
"await",
"handleLog",
"(",
"log",
",",
"rule",
",",
"contractVersion",
",",
"context",
")",
"}",
"return",
"lastLogBlock",
"}"
] |
runBatch - gets and processes logs for a range of blocks
|
[
"runBatch",
"-",
"gets",
"and",
"processes",
"logs",
"for",
"a",
"range",
"of",
"blocks"
] |
10191926afa6c52a0468fa5e6532ecff4e5b08fe
|
https://github.com/OriginProtocol/origin-js/blob/10191926afa6c52a0468fa5e6532ecff4e5b08fe/daemon/indexing/listener/listener.js#L189-L224
|
19,650
|
OriginProtocol/origin-js
|
daemon/indexing/listener/listener.js
|
withRetrys
|
async function withRetrys(fn) {
let tryCount = 0
while (true) {
try {
return await fn() // Do our action.
} catch (e) {
// Roughly double wait time each failure
let waitTime = Math.pow(100, 1 + tryCount / 6)
// Randomly jiggle wait time by 20% either way. No thundering herd.
waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4))
// Max out at two minutes
waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS)
console.log('ERROR', e)
console.log(`will retry in ${waitTime / 1000} seconds`)
tryCount += 1
await new Promise(resolve => setTimeout(resolve, waitTime))
}
if (tryCount >= MAX_RETRYS) {
console.log('Exiting. Maximum number of retrys reached.')
// Now it's up to our environment to restart us.
// Hopefully with a clean start, things will work better
process.exit(1)
}
}
}
|
javascript
|
async function withRetrys(fn) {
let tryCount = 0
while (true) {
try {
return await fn() // Do our action.
} catch (e) {
// Roughly double wait time each failure
let waitTime = Math.pow(100, 1 + tryCount / 6)
// Randomly jiggle wait time by 20% either way. No thundering herd.
waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4))
// Max out at two minutes
waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS)
console.log('ERROR', e)
console.log(`will retry in ${waitTime / 1000} seconds`)
tryCount += 1
await new Promise(resolve => setTimeout(resolve, waitTime))
}
if (tryCount >= MAX_RETRYS) {
console.log('Exiting. Maximum number of retrys reached.')
// Now it's up to our environment to restart us.
// Hopefully with a clean start, things will work better
process.exit(1)
}
}
}
|
[
"async",
"function",
"withRetrys",
"(",
"fn",
")",
"{",
"let",
"tryCount",
"=",
"0",
"while",
"(",
"true",
")",
"{",
"try",
"{",
"return",
"await",
"fn",
"(",
")",
"// Do our action.",
"}",
"catch",
"(",
"e",
")",
"{",
"// Roughly double wait time each failure",
"let",
"waitTime",
"=",
"Math",
".",
"pow",
"(",
"100",
",",
"1",
"+",
"tryCount",
"/",
"6",
")",
"// Randomly jiggle wait time by 20% either way. No thundering herd.",
"waitTime",
"=",
"Math",
".",
"floor",
"(",
"waitTime",
"*",
"(",
"1.2",
"-",
"Math",
".",
"random",
"(",
")",
"*",
"0.4",
")",
")",
"// Max out at two minutes",
"waitTime",
"=",
"Math",
".",
"min",
"(",
"waitTime",
",",
"MAX_RETRY_WAIT_MS",
")",
"console",
".",
"log",
"(",
"'ERROR'",
",",
"e",
")",
"console",
".",
"log",
"(",
"`",
"${",
"waitTime",
"/",
"1000",
"}",
"`",
")",
"tryCount",
"+=",
"1",
"await",
"new",
"Promise",
"(",
"resolve",
"=>",
"setTimeout",
"(",
"resolve",
",",
"waitTime",
")",
")",
"}",
"if",
"(",
"tryCount",
">=",
"MAX_RETRYS",
")",
"{",
"console",
".",
"log",
"(",
"'Exiting. Maximum number of retrys reached.'",
")",
"// Now it's up to our environment to restart us.",
"// Hopefully with a clean start, things will work better",
"process",
".",
"exit",
"(",
"1",
")",
"}",
"}",
"}"
] |
Retrys up to 10 times, with exponential backoff, then exits the process
|
[
"Retrys",
"up",
"to",
"10",
"times",
"with",
"exponential",
"backoff",
"then",
"exits",
"the",
"process"
] |
10191926afa6c52a0468fa5e6532ecff4e5b08fe
|
https://github.com/OriginProtocol/origin-js/blob/10191926afa6c52a0468fa5e6532ecff4e5b08fe/daemon/indexing/listener/listener.js#L227-L251
|
19,651
|
OriginProtocol/origin-js
|
daemon/indexing/listener/listener.js
|
handleLog
|
async function handleLog(log, rule, contractVersion, context) {
log.decoded = web3.eth.abi.decodeLog(
rule.eventAbi.inputs,
log.data,
log.topics.slice(1)
)
log.contractName = contractVersion.contractName
log.eventName = rule.eventName
log.contractVersionKey = contractVersion.versionKey
log.networkId = context.networkId
console.log(
`Processing log \
blockNumber=${log.blockNumber} \
transactionIndex=${log.transactionIndex} \
eventName=${log.eventName} \
contractName=${log.contractName}`
)
// Note: we run the rule with a retry since we've seen in production cases where we fail loading
// from smart contracts the data pointed to by the event. This may occur due to load balancing
// across ethereum nodes and if some nodes are lagging. For example the ethereum node we
// end up connecting to for reading the data may lag compared to the node received the event from.
let ruleResults = undefined
await withRetrys(async () => {
ruleResults = await rule.ruleFn(log)
})
const output = {
log: log,
related: ruleResults
}
const json = JSON.stringify(output, null, 2)
if (context.config.verbose) {
console.log(json)
console.log('\n----\n')
}
const userAddress = log.decoded.party
const ipfsHash = log.decoded.ipfsHash
//TODO: remove binary data from pictures in a proper way.
const listing = output.related.listing
delete listing.ipfs.data.pictures
const listingId = listing.id
// Data consistency: check listingId from the JSON stored in IPFS
// matches with listingID emitted in the event.
// TODO: use method utils/id.js:parseListingId
// DVF: this should really be handled in origin js - origin.js should throw
// an error if this happens.
const ipfsListingId = listingId.split('-')[2]
if (ipfsListingId !== log.decoded.listingID) {
throw `ListingId mismatch: ${ipfsListingId} !== ${log.decoded.listingID}`
}
// TODO: This kind of verification logic should live in origin.js
if(output.related.listing.ipfs.data.price === undefined){
return
}
if (context.config.elasticsearch) {
console.log('INDEXING ', listingId)
await withRetrys(async () => {
await search.Listing.index(
listingId,
userAddress,
ipfsHash,
listing
)
})
if (output.related.offer !== undefined) {
const offer = output.related.offer
await withRetrys(async () => {
await search.Offer.index(offer, listing)
})
}
if (output.related.seller !== undefined) {
await withRetrys(async () => {
await search.User.index(output.related.seller)
})
}
if (output.related.buyer !== undefined) {
await withRetrys(async () => {
await search.User.index(output.related.buyer)
})
}
}
if (context.config.db) {
await withRetrys(async () => {
await db.Listing.insert(
listingId,
userAddress,
ipfsHash,
listing.ipfs.data
)
})
}
if (context.config.webhook) {
console.log('\n-- WEBHOOK to ' + context.config.webhook + ' --\n')
await withRetrys(async () => {
await postToWebhook(context.config.webhook, json)
})
}
}
|
javascript
|
async function handleLog(log, rule, contractVersion, context) {
log.decoded = web3.eth.abi.decodeLog(
rule.eventAbi.inputs,
log.data,
log.topics.slice(1)
)
log.contractName = contractVersion.contractName
log.eventName = rule.eventName
log.contractVersionKey = contractVersion.versionKey
log.networkId = context.networkId
console.log(
`Processing log \
blockNumber=${log.blockNumber} \
transactionIndex=${log.transactionIndex} \
eventName=${log.eventName} \
contractName=${log.contractName}`
)
// Note: we run the rule with a retry since we've seen in production cases where we fail loading
// from smart contracts the data pointed to by the event. This may occur due to load balancing
// across ethereum nodes and if some nodes are lagging. For example the ethereum node we
// end up connecting to for reading the data may lag compared to the node received the event from.
let ruleResults = undefined
await withRetrys(async () => {
ruleResults = await rule.ruleFn(log)
})
const output = {
log: log,
related: ruleResults
}
const json = JSON.stringify(output, null, 2)
if (context.config.verbose) {
console.log(json)
console.log('\n----\n')
}
const userAddress = log.decoded.party
const ipfsHash = log.decoded.ipfsHash
//TODO: remove binary data from pictures in a proper way.
const listing = output.related.listing
delete listing.ipfs.data.pictures
const listingId = listing.id
// Data consistency: check listingId from the JSON stored in IPFS
// matches with listingID emitted in the event.
// TODO: use method utils/id.js:parseListingId
// DVF: this should really be handled in origin js - origin.js should throw
// an error if this happens.
const ipfsListingId = listingId.split('-')[2]
if (ipfsListingId !== log.decoded.listingID) {
throw `ListingId mismatch: ${ipfsListingId} !== ${log.decoded.listingID}`
}
// TODO: This kind of verification logic should live in origin.js
if(output.related.listing.ipfs.data.price === undefined){
return
}
if (context.config.elasticsearch) {
console.log('INDEXING ', listingId)
await withRetrys(async () => {
await search.Listing.index(
listingId,
userAddress,
ipfsHash,
listing
)
})
if (output.related.offer !== undefined) {
const offer = output.related.offer
await withRetrys(async () => {
await search.Offer.index(offer, listing)
})
}
if (output.related.seller !== undefined) {
await withRetrys(async () => {
await search.User.index(output.related.seller)
})
}
if (output.related.buyer !== undefined) {
await withRetrys(async () => {
await search.User.index(output.related.buyer)
})
}
}
if (context.config.db) {
await withRetrys(async () => {
await db.Listing.insert(
listingId,
userAddress,
ipfsHash,
listing.ipfs.data
)
})
}
if (context.config.webhook) {
console.log('\n-- WEBHOOK to ' + context.config.webhook + ' --\n')
await withRetrys(async () => {
await postToWebhook(context.config.webhook, json)
})
}
}
|
[
"async",
"function",
"handleLog",
"(",
"log",
",",
"rule",
",",
"contractVersion",
",",
"context",
")",
"{",
"log",
".",
"decoded",
"=",
"web3",
".",
"eth",
".",
"abi",
".",
"decodeLog",
"(",
"rule",
".",
"eventAbi",
".",
"inputs",
",",
"log",
".",
"data",
",",
"log",
".",
"topics",
".",
"slice",
"(",
"1",
")",
")",
"log",
".",
"contractName",
"=",
"contractVersion",
".",
"contractName",
"log",
".",
"eventName",
"=",
"rule",
".",
"eventName",
"log",
".",
"contractVersionKey",
"=",
"contractVersion",
".",
"versionKey",
"log",
".",
"networkId",
"=",
"context",
".",
"networkId",
"console",
".",
"log",
"(",
"`",
"\\\n",
"${",
"log",
".",
"blockNumber",
"}",
"\\\n",
"${",
"log",
".",
"transactionIndex",
"}",
"\\\n",
"${",
"log",
".",
"eventName",
"}",
"\\\n",
"${",
"log",
".",
"contractName",
"}",
"`",
")",
"// Note: we run the rule with a retry since we've seen in production cases where we fail loading",
"// from smart contracts the data pointed to by the event. This may occur due to load balancing",
"// across ethereum nodes and if some nodes are lagging. For example the ethereum node we",
"// end up connecting to for reading the data may lag compared to the node received the event from.",
"let",
"ruleResults",
"=",
"undefined",
"await",
"withRetrys",
"(",
"async",
"(",
")",
"=>",
"{",
"ruleResults",
"=",
"await",
"rule",
".",
"ruleFn",
"(",
"log",
")",
"}",
")",
"const",
"output",
"=",
"{",
"log",
":",
"log",
",",
"related",
":",
"ruleResults",
"}",
"const",
"json",
"=",
"JSON",
".",
"stringify",
"(",
"output",
",",
"null",
",",
"2",
")",
"if",
"(",
"context",
".",
"config",
".",
"verbose",
")",
"{",
"console",
".",
"log",
"(",
"json",
")",
"console",
".",
"log",
"(",
"'\\n----\\n'",
")",
"}",
"const",
"userAddress",
"=",
"log",
".",
"decoded",
".",
"party",
"const",
"ipfsHash",
"=",
"log",
".",
"decoded",
".",
"ipfsHash",
"//TODO: remove binary data from pictures in a proper way.",
"const",
"listing",
"=",
"output",
".",
"related",
".",
"listing",
"delete",
"listing",
".",
"ipfs",
".",
"data",
".",
"pictures",
"const",
"listingId",
"=",
"listing",
".",
"id",
"// Data consistency: check listingId from the JSON stored in IPFS",
"// matches with listingID emitted in the event.",
"// TODO: use method utils/id.js:parseListingId",
"// DVF: this should really be handled in origin js - origin.js should throw",
"// an error if this happens.",
"const",
"ipfsListingId",
"=",
"listingId",
".",
"split",
"(",
"'-'",
")",
"[",
"2",
"]",
"if",
"(",
"ipfsListingId",
"!==",
"log",
".",
"decoded",
".",
"listingID",
")",
"{",
"throw",
"`",
"${",
"ipfsListingId",
"}",
"${",
"log",
".",
"decoded",
".",
"listingID",
"}",
"`",
"}",
"// TODO: This kind of verification logic should live in origin.js",
"if",
"(",
"output",
".",
"related",
".",
"listing",
".",
"ipfs",
".",
"data",
".",
"price",
"===",
"undefined",
")",
"{",
"return",
"}",
"if",
"(",
"context",
".",
"config",
".",
"elasticsearch",
")",
"{",
"console",
".",
"log",
"(",
"'INDEXING '",
",",
"listingId",
")",
"await",
"withRetrys",
"(",
"async",
"(",
")",
"=>",
"{",
"await",
"search",
".",
"Listing",
".",
"index",
"(",
"listingId",
",",
"userAddress",
",",
"ipfsHash",
",",
"listing",
")",
"}",
")",
"if",
"(",
"output",
".",
"related",
".",
"offer",
"!==",
"undefined",
")",
"{",
"const",
"offer",
"=",
"output",
".",
"related",
".",
"offer",
"await",
"withRetrys",
"(",
"async",
"(",
")",
"=>",
"{",
"await",
"search",
".",
"Offer",
".",
"index",
"(",
"offer",
",",
"listing",
")",
"}",
")",
"}",
"if",
"(",
"output",
".",
"related",
".",
"seller",
"!==",
"undefined",
")",
"{",
"await",
"withRetrys",
"(",
"async",
"(",
")",
"=>",
"{",
"await",
"search",
".",
"User",
".",
"index",
"(",
"output",
".",
"related",
".",
"seller",
")",
"}",
")",
"}",
"if",
"(",
"output",
".",
"related",
".",
"buyer",
"!==",
"undefined",
")",
"{",
"await",
"withRetrys",
"(",
"async",
"(",
")",
"=>",
"{",
"await",
"search",
".",
"User",
".",
"index",
"(",
"output",
".",
"related",
".",
"buyer",
")",
"}",
")",
"}",
"}",
"if",
"(",
"context",
".",
"config",
".",
"db",
")",
"{",
"await",
"withRetrys",
"(",
"async",
"(",
")",
"=>",
"{",
"await",
"db",
".",
"Listing",
".",
"insert",
"(",
"listingId",
",",
"userAddress",
",",
"ipfsHash",
",",
"listing",
".",
"ipfs",
".",
"data",
")",
"}",
")",
"}",
"if",
"(",
"context",
".",
"config",
".",
"webhook",
")",
"{",
"console",
".",
"log",
"(",
"'\\n-- WEBHOOK to '",
"+",
"context",
".",
"config",
".",
"webhook",
"+",
"' --\\n'",
")",
"await",
"withRetrys",
"(",
"async",
"(",
")",
"=>",
"{",
"await",
"postToWebhook",
"(",
"context",
".",
"config",
".",
"webhook",
",",
"json",
")",
"}",
")",
"}",
"}"
] |
handleLog - annotates, runs rule, and ouputs a particular log
|
[
"handleLog",
"-",
"annotates",
"runs",
"rule",
"and",
"ouputs",
"a",
"particular",
"log"
] |
10191926afa6c52a0468fa5e6532ecff4e5b08fe
|
https://github.com/OriginProtocol/origin-js/blob/10191926afa6c52a0468fa5e6532ecff4e5b08fe/daemon/indexing/listener/listener.js#L254-L361
|
19,652
|
OriginProtocol/origin-js
|
daemon/indexing/apollo/index.js
|
relatedUserResolver
|
function relatedUserResolver(walletAddress, info){
const requestedFields = info.fieldNodes[0].selectionSet.selections
const isIdOnly = requestedFields.filter(x => x.name.value !== 'walletAddress')
.length === 0
if (isIdOnly) {
return { walletAddress: walletAddress }
} else {
return search.User.get(walletAddress)
}
}
|
javascript
|
function relatedUserResolver(walletAddress, info){
const requestedFields = info.fieldNodes[0].selectionSet.selections
const isIdOnly = requestedFields.filter(x => x.name.value !== 'walletAddress')
.length === 0
if (isIdOnly) {
return { walletAddress: walletAddress }
} else {
return search.User.get(walletAddress)
}
}
|
[
"function",
"relatedUserResolver",
"(",
"walletAddress",
",",
"info",
")",
"{",
"const",
"requestedFields",
"=",
"info",
".",
"fieldNodes",
"[",
"0",
"]",
".",
"selectionSet",
".",
"selections",
"const",
"isIdOnly",
"=",
"requestedFields",
".",
"filter",
"(",
"x",
"=>",
"x",
".",
"name",
".",
"value",
"!==",
"'walletAddress'",
")",
".",
"length",
"===",
"0",
"if",
"(",
"isIdOnly",
")",
"{",
"return",
"{",
"walletAddress",
":",
"walletAddress",
"}",
"}",
"else",
"{",
"return",
"search",
".",
"User",
".",
"get",
"(",
"walletAddress",
")",
"}",
"}"
] |
Gets information on a related user.
Includes short-circut code to skip the user look up
if the walletAddress is the only field required.
@param {string} walletAddress
@param {object} info
|
[
"Gets",
"information",
"on",
"a",
"related",
"user",
".",
"Includes",
"short",
"-",
"circut",
"code",
"to",
"skip",
"the",
"user",
"look",
"up",
"if",
"the",
"walletAddress",
"is",
"the",
"only",
"field",
"required",
"."
] |
10191926afa6c52a0468fa5e6532ecff4e5b08fe
|
https://github.com/OriginProtocol/origin-js/blob/10191926afa6c52a0468fa5e6532ecff4e5b08fe/daemon/indexing/apollo/index.js#L344-L353
|
19,653
|
Medium/sculpt
|
lib/map.js
|
Mapper
|
function Mapper(mapper, flusher) {
Transform.call(this, {
objectMode: true,
// Patch from 0.11.7
// https://github.com/joyent/node/commit/ba72570eae938957d10494be28eac28ed75d256f
highWaterMark: 16
})
this.mapper = mapper
this.flusher = flusher
}
|
javascript
|
function Mapper(mapper, flusher) {
Transform.call(this, {
objectMode: true,
// Patch from 0.11.7
// https://github.com/joyent/node/commit/ba72570eae938957d10494be28eac28ed75d256f
highWaterMark: 16
})
this.mapper = mapper
this.flusher = flusher
}
|
[
"function",
"Mapper",
"(",
"mapper",
",",
"flusher",
")",
"{",
"Transform",
".",
"call",
"(",
"this",
",",
"{",
"objectMode",
":",
"true",
",",
"// Patch from 0.11.7",
"// https://github.com/joyent/node/commit/ba72570eae938957d10494be28eac28ed75d256f",
"highWaterMark",
":",
"16",
"}",
")",
"this",
".",
"mapper",
"=",
"mapper",
"this",
".",
"flusher",
"=",
"flusher",
"}"
] |
Transform stream that applies a mapper function to each chunk and pushes
the mapped result.
@param {Function} mapper
@param {Function=} flusher
|
[
"Transform",
"stream",
"that",
"applies",
"a",
"mapper",
"function",
"to",
"each",
"chunk",
"and",
"pushes",
"the",
"mapped",
"result",
"."
] |
8b19472df4bec8eb4036bf7314e518ed8c2cd23a
|
https://github.com/Medium/sculpt/blob/8b19472df4bec8eb4036bf7314e518ed8c2cd23a/lib/map.js#L15-L25
|
19,654
|
auditdrivencrypto/secret-handshake
|
crypto.js
|
assert_length
|
function assert_length(buf, name, length) {
if(buf.length !== length)
throw new Error('expected '+name+' to have length' + length + ', but was:'+buf.length)
}
|
javascript
|
function assert_length(buf, name, length) {
if(buf.length !== length)
throw new Error('expected '+name+' to have length' + length + ', but was:'+buf.length)
}
|
[
"function",
"assert_length",
"(",
"buf",
",",
"name",
",",
"length",
")",
"{",
"if",
"(",
"buf",
".",
"length",
"!==",
"length",
")",
"throw",
"new",
"Error",
"(",
"'expected '",
"+",
"name",
"+",
"' to have length'",
"+",
"length",
"+",
"', but was:'",
"+",
"buf",
".",
"length",
")",
"}"
] |
both client and server
|
[
"both",
"client",
"and",
"server"
] |
fd49faad9e26a3f94ad90b788534149e8914893c
|
https://github.com/auditdrivencrypto/secret-handshake/blob/fd49faad9e26a3f94ad90b788534149e8914893c/crypto.js#L30-L33
|
19,655
|
mapbox/tilelive-overlay
|
index.js
|
Source
|
function Source(id, callback) {
var uri = url.parse(id);
if (!uri || (uri.protocol && uri.protocol !== 'overlaydata:')) {
return callback('Only the overlaydata protocol is supported');
}
var data = id.replace('overlaydata://', '');
var retina = false;
var legacy = false;
if (data.indexOf('2x:') === 0) {
retina = true;
data = data.replace(/^2x:/, '');
}
if (data.indexOf('legacy:') === 0) {
legacy = true;
data = data.replace(/^legacy:/, '');
}
var parsed;
try {
parsed = JSON.parse(data);
} catch(e) {
return callback('invalid geojson');
}
mapnikify(parsed, retina, function(err, xml) {
if (err) return callback(err);
this._xml = xml;
this._size = retina && !legacy ? 512 : 256;
this._bufferSize = retina ? 128 : 64;
callback(null, this);
}.bind(this));
}
|
javascript
|
function Source(id, callback) {
var uri = url.parse(id);
if (!uri || (uri.protocol && uri.protocol !== 'overlaydata:')) {
return callback('Only the overlaydata protocol is supported');
}
var data = id.replace('overlaydata://', '');
var retina = false;
var legacy = false;
if (data.indexOf('2x:') === 0) {
retina = true;
data = data.replace(/^2x:/, '');
}
if (data.indexOf('legacy:') === 0) {
legacy = true;
data = data.replace(/^legacy:/, '');
}
var parsed;
try {
parsed = JSON.parse(data);
} catch(e) {
return callback('invalid geojson');
}
mapnikify(parsed, retina, function(err, xml) {
if (err) return callback(err);
this._xml = xml;
this._size = retina && !legacy ? 512 : 256;
this._bufferSize = retina ? 128 : 64;
callback(null, this);
}.bind(this));
}
|
[
"function",
"Source",
"(",
"id",
",",
"callback",
")",
"{",
"var",
"uri",
"=",
"url",
".",
"parse",
"(",
"id",
")",
";",
"if",
"(",
"!",
"uri",
"||",
"(",
"uri",
".",
"protocol",
"&&",
"uri",
".",
"protocol",
"!==",
"'overlaydata:'",
")",
")",
"{",
"return",
"callback",
"(",
"'Only the overlaydata protocol is supported'",
")",
";",
"}",
"var",
"data",
"=",
"id",
".",
"replace",
"(",
"'overlaydata://'",
",",
"''",
")",
";",
"var",
"retina",
"=",
"false",
";",
"var",
"legacy",
"=",
"false",
";",
"if",
"(",
"data",
".",
"indexOf",
"(",
"'2x:'",
")",
"===",
"0",
")",
"{",
"retina",
"=",
"true",
";",
"data",
"=",
"data",
".",
"replace",
"(",
"/",
"^2x:",
"/",
",",
"''",
")",
";",
"}",
"if",
"(",
"data",
".",
"indexOf",
"(",
"'legacy:'",
")",
"===",
"0",
")",
"{",
"legacy",
"=",
"true",
";",
"data",
"=",
"data",
".",
"replace",
"(",
"/",
"^legacy:",
"/",
",",
"''",
")",
";",
"}",
"var",
"parsed",
";",
"try",
"{",
"parsed",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"callback",
"(",
"'invalid geojson'",
")",
";",
"}",
"mapnikify",
"(",
"parsed",
",",
"retina",
",",
"function",
"(",
"err",
",",
"xml",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"this",
".",
"_xml",
"=",
"xml",
";",
"this",
".",
"_size",
"=",
"retina",
"&&",
"!",
"legacy",
"?",
"512",
":",
"256",
";",
"this",
".",
"_bufferSize",
"=",
"retina",
"?",
"128",
":",
"64",
";",
"callback",
"(",
"null",
",",
"this",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] |
Create a new source that returns tiles from a simplestyle-supporting
GeoJSON object.
@param {string} uri
@param {function} callback
@returns {undefined}
|
[
"Create",
"a",
"new",
"source",
"that",
"returns",
"tiles",
"from",
"a",
"simplestyle",
"-",
"supporting",
"GeoJSON",
"object",
"."
] |
c792d128aad4d81862d87bc17432c2c27dbadaf6
|
https://github.com/mapbox/tilelive-overlay/blob/c792d128aad4d81862d87bc17432c2c27dbadaf6/index.js#L27-L62
|
19,656
|
rdmurphy/journalize
|
src/intcomma.js
|
numberWithCommas
|
function numberWithCommas(n) {
const parts = n.toString().split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return parts.join('.');
}
|
javascript
|
function numberWithCommas(n) {
const parts = n.toString().split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return parts.join('.');
}
|
[
"function",
"numberWithCommas",
"(",
"n",
")",
"{",
"const",
"parts",
"=",
"n",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'.'",
")",
";",
"parts",
"[",
"0",
"]",
"=",
"parts",
"[",
"0",
"]",
".",
"replace",
"(",
"/",
"\\B(?=(\\d{3})+(?!\\d))",
"/",
"g",
",",
"','",
")",
";",
"return",
"parts",
".",
"join",
"(",
"'.'",
")",
";",
"}"
] |
Converts a number to include commas, if necessary.
Source: http://stackoverflow.com/a/2901298
@private
@param {number|string} n
@return {string}
|
[
"Converts",
"a",
"number",
"to",
"include",
"commas",
"if",
"necessary",
"."
] |
394d519a8623abc6976820e3a52951fbbee26aad
|
https://github.com/rdmurphy/journalize/blob/394d519a8623abc6976820e3a52951fbbee26aad/src/intcomma.js#L12-L16
|
19,657
|
expressjs/timeout
|
index.js
|
timeout
|
function timeout (time, options) {
var opts = options || {}
var delay = typeof time === 'string'
? ms(time)
: Number(time || 5000)
var respond = opts.respond === undefined || opts.respond === true
return function (req, res, next) {
var id = setTimeout(function () {
req.timedout = true
req.emit('timeout', delay)
}, delay)
if (respond) {
req.on('timeout', onTimeout(delay, next))
}
req.clearTimeout = function () {
clearTimeout(id)
}
req.timedout = false
onFinished(res, function () {
clearTimeout(id)
})
onHeaders(res, function () {
clearTimeout(id)
})
next()
}
}
|
javascript
|
function timeout (time, options) {
var opts = options || {}
var delay = typeof time === 'string'
? ms(time)
: Number(time || 5000)
var respond = opts.respond === undefined || opts.respond === true
return function (req, res, next) {
var id = setTimeout(function () {
req.timedout = true
req.emit('timeout', delay)
}, delay)
if (respond) {
req.on('timeout', onTimeout(delay, next))
}
req.clearTimeout = function () {
clearTimeout(id)
}
req.timedout = false
onFinished(res, function () {
clearTimeout(id)
})
onHeaders(res, function () {
clearTimeout(id)
})
next()
}
}
|
[
"function",
"timeout",
"(",
"time",
",",
"options",
")",
"{",
"var",
"opts",
"=",
"options",
"||",
"{",
"}",
"var",
"delay",
"=",
"typeof",
"time",
"===",
"'string'",
"?",
"ms",
"(",
"time",
")",
":",
"Number",
"(",
"time",
"||",
"5000",
")",
"var",
"respond",
"=",
"opts",
".",
"respond",
"===",
"undefined",
"||",
"opts",
".",
"respond",
"===",
"true",
"return",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"id",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"req",
".",
"timedout",
"=",
"true",
"req",
".",
"emit",
"(",
"'timeout'",
",",
"delay",
")",
"}",
",",
"delay",
")",
"if",
"(",
"respond",
")",
"{",
"req",
".",
"on",
"(",
"'timeout'",
",",
"onTimeout",
"(",
"delay",
",",
"next",
")",
")",
"}",
"req",
".",
"clearTimeout",
"=",
"function",
"(",
")",
"{",
"clearTimeout",
"(",
"id",
")",
"}",
"req",
".",
"timedout",
"=",
"false",
"onFinished",
"(",
"res",
",",
"function",
"(",
")",
"{",
"clearTimeout",
"(",
"id",
")",
"}",
")",
"onHeaders",
"(",
"res",
",",
"function",
"(",
")",
"{",
"clearTimeout",
"(",
"id",
")",
"}",
")",
"next",
"(",
")",
"}",
"}"
] |
Create a new timeout middleware.
@param {number|string} [time=5000] The timeout as a number of milliseconds or a string for `ms`
@param {object} [options] Additional options for middleware
@param {boolean} [options.respond=true] Automatically emit error when timeout reached
@return {function} middleware
@public
|
[
"Create",
"a",
"new",
"timeout",
"middleware",
"."
] |
f2f520f335f2f2ae255d4778e908e8d38e3a4e68
|
https://github.com/expressjs/timeout/blob/f2f520f335f2f2ae255d4778e908e8d38e3a4e68/index.js#L37-L72
|
19,658
|
anthonykirby/lora-packet
|
lib/packet.js
|
_initialiseFromFields
|
function _initialiseFromFields(userFields) {
if (util.isDefined(userFields.MType)) {
var MTypeNo;
if (util.isNumber(userFields.MType)) {
MTypeNo = userFields.MType;
} else if (util.isString(userFields.MType)) {
var mhdr_idx = constants.MTYPE_DESCRIPTIONS.indexOf(userFields.MType);
if (mhdr_idx >= 0) {
MTypeNo = mhdr_idx;
} else {
throw new Error("MType is unknown");
}
} else {
throw new Error("MType is required in a suitable format");
}
if(MTypeNo == constants.MTYPE_JOIN_REQUEST) {
_initialiseJoinRequestPacketFromFields(userFields);
} else if(MTypeNo == constants.MTYPE_JOIN_ACCEPT) {
_initialiseJoinAcceptPacketFromFields(userFields);
} else {
_initialiseDataPacketFromFields(userFields);
}
} else {
if (_isPlausibleDataPacket(userFields) === true) {
_initialiseDataPacketFromFields(userFields);
} else if (_isPlausibleJoinRequestPacket(userFields) === true) {
_initialiseJoinRequestPacketFromFields(userFields);
} else if (_isPlausibleJoinAcceptPacket(userFields) === true) {
_initialiseJoinAcceptPacketFromFields(userFields);
} else {
throw new Error("No plausible packet");
}
}
}
|
javascript
|
function _initialiseFromFields(userFields) {
if (util.isDefined(userFields.MType)) {
var MTypeNo;
if (util.isNumber(userFields.MType)) {
MTypeNo = userFields.MType;
} else if (util.isString(userFields.MType)) {
var mhdr_idx = constants.MTYPE_DESCRIPTIONS.indexOf(userFields.MType);
if (mhdr_idx >= 0) {
MTypeNo = mhdr_idx;
} else {
throw new Error("MType is unknown");
}
} else {
throw new Error("MType is required in a suitable format");
}
if(MTypeNo == constants.MTYPE_JOIN_REQUEST) {
_initialiseJoinRequestPacketFromFields(userFields);
} else if(MTypeNo == constants.MTYPE_JOIN_ACCEPT) {
_initialiseJoinAcceptPacketFromFields(userFields);
} else {
_initialiseDataPacketFromFields(userFields);
}
} else {
if (_isPlausibleDataPacket(userFields) === true) {
_initialiseDataPacketFromFields(userFields);
} else if (_isPlausibleJoinRequestPacket(userFields) === true) {
_initialiseJoinRequestPacketFromFields(userFields);
} else if (_isPlausibleJoinAcceptPacket(userFields) === true) {
_initialiseJoinAcceptPacketFromFields(userFields);
} else {
throw new Error("No plausible packet");
}
}
}
|
[
"function",
"_initialiseFromFields",
"(",
"userFields",
")",
"{",
"if",
"(",
"util",
".",
"isDefined",
"(",
"userFields",
".",
"MType",
")",
")",
"{",
"var",
"MTypeNo",
";",
"if",
"(",
"util",
".",
"isNumber",
"(",
"userFields",
".",
"MType",
")",
")",
"{",
"MTypeNo",
"=",
"userFields",
".",
"MType",
";",
"}",
"else",
"if",
"(",
"util",
".",
"isString",
"(",
"userFields",
".",
"MType",
")",
")",
"{",
"var",
"mhdr_idx",
"=",
"constants",
".",
"MTYPE_DESCRIPTIONS",
".",
"indexOf",
"(",
"userFields",
".",
"MType",
")",
";",
"if",
"(",
"mhdr_idx",
">=",
"0",
")",
"{",
"MTypeNo",
"=",
"mhdr_idx",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"MType is unknown\"",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"MType is required in a suitable format\"",
")",
";",
"}",
"if",
"(",
"MTypeNo",
"==",
"constants",
".",
"MTYPE_JOIN_REQUEST",
")",
"{",
"_initialiseJoinRequestPacketFromFields",
"(",
"userFields",
")",
";",
"}",
"else",
"if",
"(",
"MTypeNo",
"==",
"constants",
".",
"MTYPE_JOIN_ACCEPT",
")",
"{",
"_initialiseJoinAcceptPacketFromFields",
"(",
"userFields",
")",
";",
"}",
"else",
"{",
"_initialiseDataPacketFromFields",
"(",
"userFields",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"_isPlausibleDataPacket",
"(",
"userFields",
")",
"===",
"true",
")",
"{",
"_initialiseDataPacketFromFields",
"(",
"userFields",
")",
";",
"}",
"else",
"if",
"(",
"_isPlausibleJoinRequestPacket",
"(",
"userFields",
")",
"===",
"true",
")",
"{",
"_initialiseJoinRequestPacketFromFields",
"(",
"userFields",
")",
";",
"}",
"else",
"if",
"(",
"_isPlausibleJoinAcceptPacket",
"(",
"userFields",
")",
"===",
"true",
")",
"{",
"_initialiseJoinAcceptPacketFromFields",
"(",
"userFields",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"No plausible packet\"",
")",
";",
"}",
"}",
"}"
] |
populate anew from whatever the client gives us with defaults for the rest
|
[
"populate",
"anew",
"from",
"whatever",
"the",
"client",
"gives",
"us",
"with",
"defaults",
"for",
"the",
"rest"
] |
e20307c3ef1a9e0b2e1334050018f28d1964813e
|
https://github.com/anthonykirby/lora-packet/blob/e20307c3ef1a9e0b2e1334050018f28d1964813e/lib/packet.js#L502-L536
|
19,659
|
lula/ngx-soap
|
projects/ngx-soap/src/lib/soap/security/ClientSSLSecurity.js
|
ClientSSLSecurity
|
function ClientSSLSecurity(key, cert, ca, defaults) {
if (key) {
if(Buffer.isBuffer(key)) {
this.key = key;
} else if (typeof key === 'string') {
this.key = fs.readFileSync(key);
} else {
throw new Error('key should be a buffer or a string!');
}
}
if (cert) {
if(Buffer.isBuffer(cert)) {
this.cert = cert;
} else if (typeof cert === 'string') {
this.cert = fs.readFileSync(cert);
} else {
throw new Error('cert should be a buffer or a string!');
}
}
if (ca) {
if(Buffer.isBuffer(ca) || Array.isArray(ca)) {
this.ca = ca;
} else if (typeof ca === 'string') {
this.ca = fs.readFileSync(ca);
} else {
defaults = ca;
this.ca = null;
}
}
this.defaults = {};
_.merge(this.defaults, defaults);
this.agent = null;
}
|
javascript
|
function ClientSSLSecurity(key, cert, ca, defaults) {
if (key) {
if(Buffer.isBuffer(key)) {
this.key = key;
} else if (typeof key === 'string') {
this.key = fs.readFileSync(key);
} else {
throw new Error('key should be a buffer or a string!');
}
}
if (cert) {
if(Buffer.isBuffer(cert)) {
this.cert = cert;
} else if (typeof cert === 'string') {
this.cert = fs.readFileSync(cert);
} else {
throw new Error('cert should be a buffer or a string!');
}
}
if (ca) {
if(Buffer.isBuffer(ca) || Array.isArray(ca)) {
this.ca = ca;
} else if (typeof ca === 'string') {
this.ca = fs.readFileSync(ca);
} else {
defaults = ca;
this.ca = null;
}
}
this.defaults = {};
_.merge(this.defaults, defaults);
this.agent = null;
}
|
[
"function",
"ClientSSLSecurity",
"(",
"key",
",",
"cert",
",",
"ca",
",",
"defaults",
")",
"{",
"if",
"(",
"key",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"key",
")",
")",
"{",
"this",
".",
"key",
"=",
"key",
";",
"}",
"else",
"if",
"(",
"typeof",
"key",
"===",
"'string'",
")",
"{",
"this",
".",
"key",
"=",
"fs",
".",
"readFileSync",
"(",
"key",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'key should be a buffer or a string!'",
")",
";",
"}",
"}",
"if",
"(",
"cert",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"cert",
")",
")",
"{",
"this",
".",
"cert",
"=",
"cert",
";",
"}",
"else",
"if",
"(",
"typeof",
"cert",
"===",
"'string'",
")",
"{",
"this",
".",
"cert",
"=",
"fs",
".",
"readFileSync",
"(",
"cert",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'cert should be a buffer or a string!'",
")",
";",
"}",
"}",
"if",
"(",
"ca",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"ca",
")",
"||",
"Array",
".",
"isArray",
"(",
"ca",
")",
")",
"{",
"this",
".",
"ca",
"=",
"ca",
";",
"}",
"else",
"if",
"(",
"typeof",
"ca",
"===",
"'string'",
")",
"{",
"this",
".",
"ca",
"=",
"fs",
".",
"readFileSync",
"(",
"ca",
")",
";",
"}",
"else",
"{",
"defaults",
"=",
"ca",
";",
"this",
".",
"ca",
"=",
"null",
";",
"}",
"}",
"this",
".",
"defaults",
"=",
"{",
"}",
";",
"_",
".",
"merge",
"(",
"this",
".",
"defaults",
",",
"defaults",
")",
";",
"this",
".",
"agent",
"=",
"null",
";",
"}"
] |
activates SSL for an already existing client
@module ClientSSLSecurity
@param {Buffer|String} key
@param {Buffer|String} cert
@param {Buffer|String|Array} [ca]
@param {Object} [defaults]
@constructor
|
[
"activates",
"SSL",
"for",
"an",
"already",
"existing",
"client"
] |
f5ea4b95477838bef2bc8bc38e8b67dd25806be8
|
https://github.com/lula/ngx-soap/blob/f5ea4b95477838bef2bc8bc38e8b67dd25806be8/projects/ngx-soap/src/lib/soap/security/ClientSSLSecurity.js#L17-L53
|
19,660
|
lula/ngx-soap
|
projects/ngx-soap/src/lib/soap/security/ClientSSLSecurityPFX.js
|
ClientSSLSecurityPFX
|
function ClientSSLSecurityPFX(pfx, passphrase, defaults) {
if (typeof passphrase === 'object') {
defaults = passphrase;
}
if (pfx) {
if (Buffer.isBuffer(pfx)) {
this.pfx = pfx;
} else if (typeof pfx === 'string') {
this.pfx = fs.readFileSync(pfx);
} else {
throw new Error('supplied pfx file should be a buffer or a file location');
}
}
if (passphrase) {
if (typeof passphrase === 'string') {
this.passphrase = passphrase;
}
}
this.defaults = {};
_.merge(this.defaults, defaults);
}
|
javascript
|
function ClientSSLSecurityPFX(pfx, passphrase, defaults) {
if (typeof passphrase === 'object') {
defaults = passphrase;
}
if (pfx) {
if (Buffer.isBuffer(pfx)) {
this.pfx = pfx;
} else if (typeof pfx === 'string') {
this.pfx = fs.readFileSync(pfx);
} else {
throw new Error('supplied pfx file should be a buffer or a file location');
}
}
if (passphrase) {
if (typeof passphrase === 'string') {
this.passphrase = passphrase;
}
}
this.defaults = {};
_.merge(this.defaults, defaults);
}
|
[
"function",
"ClientSSLSecurityPFX",
"(",
"pfx",
",",
"passphrase",
",",
"defaults",
")",
"{",
"if",
"(",
"typeof",
"passphrase",
"===",
"'object'",
")",
"{",
"defaults",
"=",
"passphrase",
";",
"}",
"if",
"(",
"pfx",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"pfx",
")",
")",
"{",
"this",
".",
"pfx",
"=",
"pfx",
";",
"}",
"else",
"if",
"(",
"typeof",
"pfx",
"===",
"'string'",
")",
"{",
"this",
".",
"pfx",
"=",
"fs",
".",
"readFileSync",
"(",
"pfx",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'supplied pfx file should be a buffer or a file location'",
")",
";",
"}",
"}",
"if",
"(",
"passphrase",
")",
"{",
"if",
"(",
"typeof",
"passphrase",
"===",
"'string'",
")",
"{",
"this",
".",
"passphrase",
"=",
"passphrase",
";",
"}",
"}",
"this",
".",
"defaults",
"=",
"{",
"}",
";",
"_",
".",
"merge",
"(",
"this",
".",
"defaults",
",",
"defaults",
")",
";",
"}"
] |
activates SSL for an already existing client using a PFX cert
@module ClientSSLSecurityPFX
@param {Buffer|String} pfx
@param {String} passphrase
@constructor
|
[
"activates",
"SSL",
"for",
"an",
"already",
"existing",
"client",
"using",
"a",
"PFX",
"cert"
] |
f5ea4b95477838bef2bc8bc38e8b67dd25806be8
|
https://github.com/lula/ngx-soap/blob/f5ea4b95477838bef2bc8bc38e8b67dd25806be8/projects/ngx-soap/src/lib/soap/security/ClientSSLSecurityPFX.js#L15-L36
|
19,661
|
naikus/svg-gauge
|
dist/gauge.js
|
svg
|
function svg(name, attrs, children) {
var elem = document.createElementNS(SVG_NS, name);
for(var attrName in attrs) {
elem.setAttribute(attrName, attrs[attrName]);
}
if(children) {
children.forEach(function(c) {
elem.appendChild(c);
});
}
return elem;
}
|
javascript
|
function svg(name, attrs, children) {
var elem = document.createElementNS(SVG_NS, name);
for(var attrName in attrs) {
elem.setAttribute(attrName, attrs[attrName]);
}
if(children) {
children.forEach(function(c) {
elem.appendChild(c);
});
}
return elem;
}
|
[
"function",
"svg",
"(",
"name",
",",
"attrs",
",",
"children",
")",
"{",
"var",
"elem",
"=",
"document",
".",
"createElementNS",
"(",
"SVG_NS",
",",
"name",
")",
";",
"for",
"(",
"var",
"attrName",
"in",
"attrs",
")",
"{",
"elem",
".",
"setAttribute",
"(",
"attrName",
",",
"attrs",
"[",
"attrName",
"]",
")",
";",
"}",
"if",
"(",
"children",
")",
"{",
"children",
".",
"forEach",
"(",
"function",
"(",
"c",
")",
"{",
"elem",
".",
"appendChild",
"(",
"c",
")",
";",
"}",
")",
";",
"}",
"return",
"elem",
";",
"}"
] |
A utility function to create SVG dom tree
@param {String} name The SVG element name
@param {Object} attrs The attributes as they appear in DOM e.g. stroke-width and not strokeWidth
@param {Array} children An array of children (can be created by this same function)
@return The SVG element
|
[
"A",
"utility",
"function",
"to",
"create",
"SVG",
"dom",
"tree"
] |
17169a75f748ab73499655584efc7e7f593dc417
|
https://github.com/naikus/svg-gauge/blob/17169a75f748ab73499655584efc7e7f593dc417/dist/gauge.js#L112-L124
|
19,662
|
naikus/svg-gauge
|
dist/gauge.js
|
getDialCoords
|
function getDialCoords(radius, startAngle, endAngle) {
var cx = GaugeDefaults.centerX,
cy = GaugeDefaults.centerY;
return {
end: getCartesian(cx, cy, radius, endAngle),
start: getCartesian(cx, cy, radius, startAngle)
};
}
|
javascript
|
function getDialCoords(radius, startAngle, endAngle) {
var cx = GaugeDefaults.centerX,
cy = GaugeDefaults.centerY;
return {
end: getCartesian(cx, cy, radius, endAngle),
start: getCartesian(cx, cy, radius, startAngle)
};
}
|
[
"function",
"getDialCoords",
"(",
"radius",
",",
"startAngle",
",",
"endAngle",
")",
"{",
"var",
"cx",
"=",
"GaugeDefaults",
".",
"centerX",
",",
"cy",
"=",
"GaugeDefaults",
".",
"centerY",
";",
"return",
"{",
"end",
":",
"getCartesian",
"(",
"cx",
",",
"cy",
",",
"radius",
",",
"endAngle",
")",
",",
"start",
":",
"getCartesian",
"(",
"cx",
",",
"cy",
",",
"radius",
",",
"startAngle",
")",
"}",
";",
"}"
] |
Returns start and end points for dial i.e. starts at 135deg ends at 45deg with large arc flag REMEMBER!! angle=0 starts on X axis and then increases clockwise
|
[
"Returns",
"start",
"and",
"end",
"points",
"for",
"dial",
"i",
".",
"e",
".",
"starts",
"at",
"135deg",
"ends",
"at",
"45deg",
"with",
"large",
"arc",
"flag",
"REMEMBER!!",
"angle",
"=",
"0",
"starts",
"on",
"X",
"axis",
"and",
"then",
"increases",
"clockwise"
] |
17169a75f748ab73499655584efc7e7f593dc417
|
https://github.com/naikus/svg-gauge/blob/17169a75f748ab73499655584efc7e7f593dc417/dist/gauge.js#L167-L174
|
19,663
|
multiformats/js-multibase
|
src/index.js
|
multibase
|
function multibase (nameOrCode, buf) {
if (!buf) {
throw new Error('requires an encoded buffer')
}
const base = getBase(nameOrCode)
const codeBuf = Buffer.from(base.code)
const name = base.name
validEncode(name, buf)
return Buffer.concat([codeBuf, buf])
}
|
javascript
|
function multibase (nameOrCode, buf) {
if (!buf) {
throw new Error('requires an encoded buffer')
}
const base = getBase(nameOrCode)
const codeBuf = Buffer.from(base.code)
const name = base.name
validEncode(name, buf)
return Buffer.concat([codeBuf, buf])
}
|
[
"function",
"multibase",
"(",
"nameOrCode",
",",
"buf",
")",
"{",
"if",
"(",
"!",
"buf",
")",
"{",
"throw",
"new",
"Error",
"(",
"'requires an encoded buffer'",
")",
"}",
"const",
"base",
"=",
"getBase",
"(",
"nameOrCode",
")",
"const",
"codeBuf",
"=",
"Buffer",
".",
"from",
"(",
"base",
".",
"code",
")",
"const",
"name",
"=",
"base",
".",
"name",
"validEncode",
"(",
"name",
",",
"buf",
")",
"return",
"Buffer",
".",
"concat",
"(",
"[",
"codeBuf",
",",
"buf",
"]",
")",
"}"
] |
Create a new buffer with the multibase varint+code.
@param {string|number} nameOrCode - The multibase name or code number.
@param {Buffer} buf - The data to be prefixed with multibase.
@memberof Multibase
@returns {Buffer}
|
[
"Create",
"a",
"new",
"buffer",
"with",
"the",
"multibase",
"varint",
"+",
"code",
"."
] |
1e1dcbc6178f9db5b066bae5452e56ef985a6940
|
https://github.com/multiformats/js-multibase/blob/1e1dcbc6178f9db5b066bae5452e56ef985a6940/src/index.js#L26-L36
|
19,664
|
multiformats/js-multibase
|
src/index.js
|
encode
|
function encode (nameOrCode, buf) {
const base = getBase(nameOrCode)
const name = base.name
return multibase(name, Buffer.from(base.encode(buf)))
}
|
javascript
|
function encode (nameOrCode, buf) {
const base = getBase(nameOrCode)
const name = base.name
return multibase(name, Buffer.from(base.encode(buf)))
}
|
[
"function",
"encode",
"(",
"nameOrCode",
",",
"buf",
")",
"{",
"const",
"base",
"=",
"getBase",
"(",
"nameOrCode",
")",
"const",
"name",
"=",
"base",
".",
"name",
"return",
"multibase",
"(",
"name",
",",
"Buffer",
".",
"from",
"(",
"base",
".",
"encode",
"(",
"buf",
")",
")",
")",
"}"
] |
Encode data with the specified base and add the multibase prefix.
@param {string|number} nameOrCode - The multibase name or code number.
@param {Buffer} buf - The data to be encoded.
@returns {Buffer}
@memberof Multibase
|
[
"Encode",
"data",
"with",
"the",
"specified",
"base",
"and",
"add",
"the",
"multibase",
"prefix",
"."
] |
1e1dcbc6178f9db5b066bae5452e56ef985a6940
|
https://github.com/multiformats/js-multibase/blob/1e1dcbc6178f9db5b066bae5452e56ef985a6940/src/index.js#L46-L51
|
19,665
|
multiformats/js-multibase
|
src/index.js
|
decode
|
function decode (bufOrString) {
if (Buffer.isBuffer(bufOrString)) {
bufOrString = bufOrString.toString()
}
const code = bufOrString.substring(0, 1)
bufOrString = bufOrString.substring(1, bufOrString.length)
if (typeof bufOrString === 'string') {
bufOrString = Buffer.from(bufOrString)
}
const base = getBase(code)
return Buffer.from(base.decode(bufOrString.toString()))
}
|
javascript
|
function decode (bufOrString) {
if (Buffer.isBuffer(bufOrString)) {
bufOrString = bufOrString.toString()
}
const code = bufOrString.substring(0, 1)
bufOrString = bufOrString.substring(1, bufOrString.length)
if (typeof bufOrString === 'string') {
bufOrString = Buffer.from(bufOrString)
}
const base = getBase(code)
return Buffer.from(base.decode(bufOrString.toString()))
}
|
[
"function",
"decode",
"(",
"bufOrString",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"bufOrString",
")",
")",
"{",
"bufOrString",
"=",
"bufOrString",
".",
"toString",
"(",
")",
"}",
"const",
"code",
"=",
"bufOrString",
".",
"substring",
"(",
"0",
",",
"1",
")",
"bufOrString",
"=",
"bufOrString",
".",
"substring",
"(",
"1",
",",
"bufOrString",
".",
"length",
")",
"if",
"(",
"typeof",
"bufOrString",
"===",
"'string'",
")",
"{",
"bufOrString",
"=",
"Buffer",
".",
"from",
"(",
"bufOrString",
")",
"}",
"const",
"base",
"=",
"getBase",
"(",
"code",
")",
"return",
"Buffer",
".",
"from",
"(",
"base",
".",
"decode",
"(",
"bufOrString",
".",
"toString",
"(",
")",
")",
")",
"}"
] |
Takes a buffer or string encoded with multibase header, decodes it and
returns the decoded buffer
@param {Buffer|string} bufOrString
@returns {Buffer}
@memberof Multibase
|
[
"Takes",
"a",
"buffer",
"or",
"string",
"encoded",
"with",
"multibase",
"header",
"decodes",
"it",
"and",
"returns",
"the",
"decoded",
"buffer"
] |
1e1dcbc6178f9db5b066bae5452e56ef985a6940
|
https://github.com/multiformats/js-multibase/blob/1e1dcbc6178f9db5b066bae5452e56ef985a6940/src/index.js#L62-L76
|
19,666
|
multiformats/js-multibase
|
src/index.js
|
isEncoded
|
function isEncoded (bufOrString) {
if (Buffer.isBuffer(bufOrString)) {
bufOrString = bufOrString.toString()
}
// Ensure bufOrString is a string
if (Object.prototype.toString.call(bufOrString) !== '[object String]') {
return false
}
const code = bufOrString.substring(0, 1)
try {
const base = getBase(code)
return base.name
} catch (err) {
return false
}
}
|
javascript
|
function isEncoded (bufOrString) {
if (Buffer.isBuffer(bufOrString)) {
bufOrString = bufOrString.toString()
}
// Ensure bufOrString is a string
if (Object.prototype.toString.call(bufOrString) !== '[object String]') {
return false
}
const code = bufOrString.substring(0, 1)
try {
const base = getBase(code)
return base.name
} catch (err) {
return false
}
}
|
[
"function",
"isEncoded",
"(",
"bufOrString",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"bufOrString",
")",
")",
"{",
"bufOrString",
"=",
"bufOrString",
".",
"toString",
"(",
")",
"}",
"// Ensure bufOrString is a string",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"bufOrString",
")",
"!==",
"'[object String]'",
")",
"{",
"return",
"false",
"}",
"const",
"code",
"=",
"bufOrString",
".",
"substring",
"(",
"0",
",",
"1",
")",
"try",
"{",
"const",
"base",
"=",
"getBase",
"(",
"code",
")",
"return",
"base",
".",
"name",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
"}",
"}"
] |
Is the given data multibase encoded?
@param {Buffer|string} bufOrString
@returns {boolean}
@memberof Multibase
|
[
"Is",
"the",
"given",
"data",
"multibase",
"encoded?"
] |
1e1dcbc6178f9db5b066bae5452e56ef985a6940
|
https://github.com/multiformats/js-multibase/blob/1e1dcbc6178f9db5b066bae5452e56ef985a6940/src/index.js#L85-L102
|
19,667
|
offirgolan/ember-parachute
|
addon/-private/state.js
|
queryParamsState
|
function queryParamsState(queryParamsArray, controller) {
return queryParamsArray.reduce(
(state, qp) => {
let value = qp.value(controller);
state[qp.key] = {
value,
serializedValue: qp.serializedValue(controller),
as: qp.as,
defaultValue: qp.defaultValue,
changed: JSON.stringify(value) !== JSON.stringify(qp.defaultValue)
};
return state;
},
{},
undefined
);
}
|
javascript
|
function queryParamsState(queryParamsArray, controller) {
return queryParamsArray.reduce(
(state, qp) => {
let value = qp.value(controller);
state[qp.key] = {
value,
serializedValue: qp.serializedValue(controller),
as: qp.as,
defaultValue: qp.defaultValue,
changed: JSON.stringify(value) !== JSON.stringify(qp.defaultValue)
};
return state;
},
{},
undefined
);
}
|
[
"function",
"queryParamsState",
"(",
"queryParamsArray",
",",
"controller",
")",
"{",
"return",
"queryParamsArray",
".",
"reduce",
"(",
"(",
"state",
",",
"qp",
")",
"=>",
"{",
"let",
"value",
"=",
"qp",
".",
"value",
"(",
"controller",
")",
";",
"state",
"[",
"qp",
".",
"key",
"]",
"=",
"{",
"value",
",",
"serializedValue",
":",
"qp",
".",
"serializedValue",
"(",
"controller",
")",
",",
"as",
":",
"qp",
".",
"as",
",",
"defaultValue",
":",
"qp",
".",
"defaultValue",
",",
"changed",
":",
"JSON",
".",
"stringify",
"(",
"value",
")",
"!==",
"JSON",
".",
"stringify",
"(",
"qp",
".",
"defaultValue",
")",
"}",
";",
"return",
"state",
";",
"}",
",",
"{",
"}",
",",
"undefined",
")",
";",
"}"
] |
Creates QueryParamsState interface.
@param {Ember.NativeArray} queryParamsArray
@param {Ember.Controller} controller
@returns {object}
|
[
"Creates",
"QueryParamsState",
"interface",
"."
] |
69137ff4c2f4a746baa36773eae61802fef1b658
|
https://github.com/offirgolan/ember-parachute/blob/69137ff4c2f4a746baa36773eae61802fef1b658/addon/-private/state.js#L12-L29
|
19,668
|
transitive-bullshit/snapchat
|
routes/account.js
|
Account
|
function Account (client, opts) {
var self = this
if (!(self instanceof Account)) return new Account(client, opts)
if (!opts) opts = {}
self.client = client
}
|
javascript
|
function Account (client, opts) {
var self = this
if (!(self instanceof Account)) return new Account(client, opts)
if (!opts) opts = {}
self.client = client
}
|
[
"function",
"Account",
"(",
"client",
",",
"opts",
")",
"{",
"var",
"self",
"=",
"this",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"Account",
")",
")",
"return",
"new",
"Account",
"(",
"client",
",",
"opts",
")",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
"self",
".",
"client",
"=",
"client",
"}"
] |
Snapchat wrapper for account-related API calls.
@class
@param {Object} opts
|
[
"Snapchat",
"wrapper",
"for",
"account",
"-",
"related",
"API",
"calls",
"."
] |
14fcd09ec9d3f868c875250605abde9c3e62ed83
|
https://github.com/transitive-bullshit/snapchat/blob/14fcd09ec9d3f868c875250605abde9c3e62ed83/routes/account.js#L16-L22
|
19,669
|
transitive-bullshit/snapchat
|
models/blob.js
|
SKBlob
|
function SKBlob (data) {
var self = this
if (!(self instanceof SKBlob)) return new SKBlob(data)
if (!(data instanceof Buffer)) {
data = new Buffer(data)
}
self._data = data
self._type = fileType(data)
self._isImage = BufferUtils.isImage(data)
self._isMPEG4 = BufferUtils.isMPEG4(data)
self._isVideo = self._isMPEG4
self._isMedia = BufferUtils.isMedia(data)
// TODO
self._overlay = null
}
|
javascript
|
function SKBlob (data) {
var self = this
if (!(self instanceof SKBlob)) return new SKBlob(data)
if (!(data instanceof Buffer)) {
data = new Buffer(data)
}
self._data = data
self._type = fileType(data)
self._isImage = BufferUtils.isImage(data)
self._isMPEG4 = BufferUtils.isMPEG4(data)
self._isVideo = self._isMPEG4
self._isMedia = BufferUtils.isMedia(data)
// TODO
self._overlay = null
}
|
[
"function",
"SKBlob",
"(",
"data",
")",
"{",
"var",
"self",
"=",
"this",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"SKBlob",
")",
")",
"return",
"new",
"SKBlob",
"(",
"data",
")",
"if",
"(",
"!",
"(",
"data",
"instanceof",
"Buffer",
")",
")",
"{",
"data",
"=",
"new",
"Buffer",
"(",
"data",
")",
"}",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_type",
"=",
"fileType",
"(",
"data",
")",
"self",
".",
"_isImage",
"=",
"BufferUtils",
".",
"isImage",
"(",
"data",
")",
"self",
".",
"_isMPEG4",
"=",
"BufferUtils",
".",
"isMPEG4",
"(",
"data",
")",
"self",
".",
"_isVideo",
"=",
"self",
".",
"_isMPEG4",
"self",
".",
"_isMedia",
"=",
"BufferUtils",
".",
"isMedia",
"(",
"data",
")",
"// TODO",
"self",
".",
"_overlay",
"=",
"null",
"}"
] |
Snapchat Blob wrapper
@class
@param {Buffer} data
|
[
"Snapchat",
"Blob",
"wrapper"
] |
14fcd09ec9d3f868c875250605abde9c3e62ed83
|
https://github.com/transitive-bullshit/snapchat/blob/14fcd09ec9d3f868c875250605abde9c3e62ed83/models/blob.js#L14-L32
|
19,670
|
transitive-bullshit/snapchat
|
routes/friends.js
|
Friends
|
function Friends (client, opts) {
var self = this
if (!(self instanceof Friends)) return new Friends(client, opts)
if (!opts) opts = {}
self.client = client
}
|
javascript
|
function Friends (client, opts) {
var self = this
if (!(self instanceof Friends)) return new Friends(client, opts)
if (!opts) opts = {}
self.client = client
}
|
[
"function",
"Friends",
"(",
"client",
",",
"opts",
")",
"{",
"var",
"self",
"=",
"this",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"Friends",
")",
")",
"return",
"new",
"Friends",
"(",
"client",
",",
"opts",
")",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
"self",
".",
"client",
"=",
"client",
"}"
] |
Friends wrapper for friends-related API calls.
@class
@param {Object} opts
|
[
"Friends",
"wrapper",
"for",
"friends",
"-",
"related",
"API",
"calls",
"."
] |
14fcd09ec9d3f868c875250605abde9c3e62ed83
|
https://github.com/transitive-bullshit/snapchat/blob/14fcd09ec9d3f868c875250605abde9c3e62ed83/routes/friends.js#L18-L24
|
19,671
|
transitive-bullshit/snapchat
|
routes/snaps.js
|
Snaps
|
function Snaps (client, opts) {
var self = this
if (!(self instanceof Snaps)) return new Snaps(client, opts)
if (!opts) opts = {}
self.client = client
}
|
javascript
|
function Snaps (client, opts) {
var self = this
if (!(self instanceof Snaps)) return new Snaps(client, opts)
if (!opts) opts = {}
self.client = client
}
|
[
"function",
"Snaps",
"(",
"client",
",",
"opts",
")",
"{",
"var",
"self",
"=",
"this",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"Snaps",
")",
")",
"return",
"new",
"Snaps",
"(",
"client",
",",
"opts",
")",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
"self",
".",
"client",
"=",
"client",
"}"
] |
Snapchat wrapper for Snap-related API calls.
@class
@param {Object} opts
|
[
"Snapchat",
"wrapper",
"for",
"Snap",
"-",
"related",
"API",
"calls",
"."
] |
14fcd09ec9d3f868c875250605abde9c3e62ed83
|
https://github.com/transitive-bullshit/snapchat/blob/14fcd09ec9d3f868c875250605abde9c3e62ed83/routes/snaps.js#L20-L26
|
19,672
|
transitive-bullshit/snapchat
|
routes/stories.js
|
Stories
|
function Stories (client, opts) {
var self = this
if (!(self instanceof Stories)) return new Stories(client, opts)
if (!opts) opts = {}
self.client = client
}
|
javascript
|
function Stories (client, opts) {
var self = this
if (!(self instanceof Stories)) return new Stories(client, opts)
if (!opts) opts = {}
self.client = client
}
|
[
"function",
"Stories",
"(",
"client",
",",
"opts",
")",
"{",
"var",
"self",
"=",
"this",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"Stories",
")",
")",
"return",
"new",
"Stories",
"(",
"client",
",",
"opts",
")",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
"self",
".",
"client",
"=",
"client",
"}"
] |
Snapchat wrapper for story-related API calls.
@class
@param {Object} opts
|
[
"Snapchat",
"wrapper",
"for",
"story",
"-",
"related",
"API",
"calls",
"."
] |
14fcd09ec9d3f868c875250605abde9c3e62ed83
|
https://github.com/transitive-bullshit/snapchat/blob/14fcd09ec9d3f868c875250605abde9c3e62ed83/routes/stories.js#L23-L29
|
19,673
|
transitive-bullshit/snapchat
|
models/location.js
|
SKLocation
|
function SKLocation (params) {
var self = this
if (!(self instanceof SKLocation)) return new SKLocation(params)
self.weather = params['weather']
self.ourStoryAuths = params['our_story_auths']
self.preCacheGeofilters = params['pre_cache_geofilters']
self.filters = params['filters'].map(function (filter) {
return new Filter(filter)
})
}
|
javascript
|
function SKLocation (params) {
var self = this
if (!(self instanceof SKLocation)) return new SKLocation(params)
self.weather = params['weather']
self.ourStoryAuths = params['our_story_auths']
self.preCacheGeofilters = params['pre_cache_geofilters']
self.filters = params['filters'].map(function (filter) {
return new Filter(filter)
})
}
|
[
"function",
"SKLocation",
"(",
"params",
")",
"{",
"var",
"self",
"=",
"this",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"SKLocation",
")",
")",
"return",
"new",
"SKLocation",
"(",
"params",
")",
"self",
".",
"weather",
"=",
"params",
"[",
"'weather'",
"]",
"self",
".",
"ourStoryAuths",
"=",
"params",
"[",
"'our_story_auths'",
"]",
"self",
".",
"preCacheGeofilters",
"=",
"params",
"[",
"'pre_cache_geofilters'",
"]",
"self",
".",
"filters",
"=",
"params",
"[",
"'filters'",
"]",
".",
"map",
"(",
"function",
"(",
"filter",
")",
"{",
"return",
"new",
"Filter",
"(",
"filter",
")",
"}",
")",
"}"
] |
Snapchat location-specific data
@class
@param {Object} params
|
[
"Snapchat",
"location",
"-",
"specific",
"data"
] |
14fcd09ec9d3f868c875250605abde9c3e62ed83
|
https://github.com/transitive-bullshit/snapchat/blob/14fcd09ec9d3f868c875250605abde9c3e62ed83/models/location.js#L11-L22
|
19,674
|
transitive-bullshit/snapchat
|
lib/request.js
|
Request
|
function Request (opts) {
var self = this
if (!(self instanceof Request)) return new Request(opts)
if (!opts) opts = {}
self.HTTPMethod = opts.method
self.HTTPHeaders = {}
self.opts = opts
if (opts.method === 'POST') {
if (opts.endpoint) {
self._initPOST(opts)
} else if (opts.url) {
self._initPOSTURL(opts)
} else {
throw new Error('invalid request')
}
} else if (opts.method === 'GET') {
self._initGET(opts)
} else {
throw new Error('invalid request')
}
}
|
javascript
|
function Request (opts) {
var self = this
if (!(self instanceof Request)) return new Request(opts)
if (!opts) opts = {}
self.HTTPMethod = opts.method
self.HTTPHeaders = {}
self.opts = opts
if (opts.method === 'POST') {
if (opts.endpoint) {
self._initPOST(opts)
} else if (opts.url) {
self._initPOSTURL(opts)
} else {
throw new Error('invalid request')
}
} else if (opts.method === 'GET') {
self._initGET(opts)
} else {
throw new Error('invalid request')
}
}
|
[
"function",
"Request",
"(",
"opts",
")",
"{",
"var",
"self",
"=",
"this",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"Request",
")",
")",
"return",
"new",
"Request",
"(",
"opts",
")",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
"self",
".",
"HTTPMethod",
"=",
"opts",
".",
"method",
"self",
".",
"HTTPHeaders",
"=",
"{",
"}",
"self",
".",
"opts",
"=",
"opts",
"if",
"(",
"opts",
".",
"method",
"===",
"'POST'",
")",
"{",
"if",
"(",
"opts",
".",
"endpoint",
")",
"{",
"self",
".",
"_initPOST",
"(",
"opts",
")",
"}",
"else",
"if",
"(",
"opts",
".",
"url",
")",
"{",
"self",
".",
"_initPOSTURL",
"(",
"opts",
")",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'invalid request'",
")",
"}",
"}",
"else",
"if",
"(",
"opts",
".",
"method",
"===",
"'GET'",
")",
"{",
"self",
".",
"_initGET",
"(",
"opts",
")",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'invalid request'",
")",
"}",
"}"
] |
Snapchat wrapper for HTTP requests
@class
@param {Object} opts
|
[
"Snapchat",
"wrapper",
"for",
"HTTP",
"requests"
] |
14fcd09ec9d3f868c875250605abde9c3e62ed83
|
https://github.com/transitive-bullshit/snapchat/blob/14fcd09ec9d3f868c875250605abde9c3e62ed83/lib/request.js#L21-L43
|
19,675
|
pyrsmk/qwest
|
src/qwest.js
|
function(q) {
// Prepare
var promises = [],
loading = 0,
values = [];
// Create a new promise to handle all requests
return pinkyswear(function(pinky) {
// Basic request method
var method_index = -1,
createMethod = function(method) {
return function(url, data, options, before) {
var index = ++method_index;
++loading;
promises.push(qwest(method, pinky.base + url, data, options, before).then(function(xhr, response) {
values[index] = arguments;
if(!--loading) {
pinky(true, values.length == 1 ? values[0] : [values]);
}
}, function() {
pinky(false, arguments);
}));
return pinky;
};
};
// Define external API
pinky.get = createMethod('GET');
pinky.post = createMethod('POST');
pinky.put = createMethod('PUT');
pinky['delete'] = createMethod('DELETE');
pinky['catch'] = function(f) {
return pinky.then(null, f);
};
pinky.complete = function(f) {
var func = function() {
f(); // otherwise arguments will be passed to the callback
};
return pinky.then(func, func);
};
pinky.map = function(type, url, data, options, before) {
return createMethod(type.toUpperCase()).call(this, url, data, options, before);
};
// Populate methods from external object
for(var prop in q) {
if(!(prop in pinky)) {
pinky[prop] = q[prop];
}
}
// Set last methods
pinky.send = function() {
for(var i=0, j=promises.length; i<j; ++i) {
promises[i].send();
}
return pinky;
};
pinky.abort = function() {
for(var i=0, j=promises.length; i<j; ++i) {
promises[i].abort();
}
return pinky;
};
return pinky;
});
}
|
javascript
|
function(q) {
// Prepare
var promises = [],
loading = 0,
values = [];
// Create a new promise to handle all requests
return pinkyswear(function(pinky) {
// Basic request method
var method_index = -1,
createMethod = function(method) {
return function(url, data, options, before) {
var index = ++method_index;
++loading;
promises.push(qwest(method, pinky.base + url, data, options, before).then(function(xhr, response) {
values[index] = arguments;
if(!--loading) {
pinky(true, values.length == 1 ? values[0] : [values]);
}
}, function() {
pinky(false, arguments);
}));
return pinky;
};
};
// Define external API
pinky.get = createMethod('GET');
pinky.post = createMethod('POST');
pinky.put = createMethod('PUT');
pinky['delete'] = createMethod('DELETE');
pinky['catch'] = function(f) {
return pinky.then(null, f);
};
pinky.complete = function(f) {
var func = function() {
f(); // otherwise arguments will be passed to the callback
};
return pinky.then(func, func);
};
pinky.map = function(type, url, data, options, before) {
return createMethod(type.toUpperCase()).call(this, url, data, options, before);
};
// Populate methods from external object
for(var prop in q) {
if(!(prop in pinky)) {
pinky[prop] = q[prop];
}
}
// Set last methods
pinky.send = function() {
for(var i=0, j=promises.length; i<j; ++i) {
promises[i].send();
}
return pinky;
};
pinky.abort = function() {
for(var i=0, j=promises.length; i<j; ++i) {
promises[i].abort();
}
return pinky;
};
return pinky;
});
}
|
[
"function",
"(",
"q",
")",
"{",
"// Prepare",
"var",
"promises",
"=",
"[",
"]",
",",
"loading",
"=",
"0",
",",
"values",
"=",
"[",
"]",
";",
"// Create a new promise to handle all requests",
"return",
"pinkyswear",
"(",
"function",
"(",
"pinky",
")",
"{",
"// Basic request method",
"var",
"method_index",
"=",
"-",
"1",
",",
"createMethod",
"=",
"function",
"(",
"method",
")",
"{",
"return",
"function",
"(",
"url",
",",
"data",
",",
"options",
",",
"before",
")",
"{",
"var",
"index",
"=",
"++",
"method_index",
";",
"++",
"loading",
";",
"promises",
".",
"push",
"(",
"qwest",
"(",
"method",
",",
"pinky",
".",
"base",
"+",
"url",
",",
"data",
",",
"options",
",",
"before",
")",
".",
"then",
"(",
"function",
"(",
"xhr",
",",
"response",
")",
"{",
"values",
"[",
"index",
"]",
"=",
"arguments",
";",
"if",
"(",
"!",
"--",
"loading",
")",
"{",
"pinky",
"(",
"true",
",",
"values",
".",
"length",
"==",
"1",
"?",
"values",
"[",
"0",
"]",
":",
"[",
"values",
"]",
")",
";",
"}",
"}",
",",
"function",
"(",
")",
"{",
"pinky",
"(",
"false",
",",
"arguments",
")",
";",
"}",
")",
")",
";",
"return",
"pinky",
";",
"}",
";",
"}",
";",
"// Define external API",
"pinky",
".",
"get",
"=",
"createMethod",
"(",
"'GET'",
")",
";",
"pinky",
".",
"post",
"=",
"createMethod",
"(",
"'POST'",
")",
";",
"pinky",
".",
"put",
"=",
"createMethod",
"(",
"'PUT'",
")",
";",
"pinky",
"[",
"'delete'",
"]",
"=",
"createMethod",
"(",
"'DELETE'",
")",
";",
"pinky",
"[",
"'catch'",
"]",
"=",
"function",
"(",
"f",
")",
"{",
"return",
"pinky",
".",
"then",
"(",
"null",
",",
"f",
")",
";",
"}",
";",
"pinky",
".",
"complete",
"=",
"function",
"(",
"f",
")",
"{",
"var",
"func",
"=",
"function",
"(",
")",
"{",
"f",
"(",
")",
";",
"// otherwise arguments will be passed to the callback",
"}",
";",
"return",
"pinky",
".",
"then",
"(",
"func",
",",
"func",
")",
";",
"}",
";",
"pinky",
".",
"map",
"=",
"function",
"(",
"type",
",",
"url",
",",
"data",
",",
"options",
",",
"before",
")",
"{",
"return",
"createMethod",
"(",
"type",
".",
"toUpperCase",
"(",
")",
")",
".",
"call",
"(",
"this",
",",
"url",
",",
"data",
",",
"options",
",",
"before",
")",
";",
"}",
";",
"// Populate methods from external object",
"for",
"(",
"var",
"prop",
"in",
"q",
")",
"{",
"if",
"(",
"!",
"(",
"prop",
"in",
"pinky",
")",
")",
"{",
"pinky",
"[",
"prop",
"]",
"=",
"q",
"[",
"prop",
"]",
";",
"}",
"}",
"// Set last methods",
"pinky",
".",
"send",
"=",
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"promises",
".",
"length",
";",
"i",
"<",
"j",
";",
"++",
"i",
")",
"{",
"promises",
"[",
"i",
"]",
".",
"send",
"(",
")",
";",
"}",
"return",
"pinky",
";",
"}",
";",
"pinky",
".",
"abort",
"=",
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"promises",
".",
"length",
";",
"i",
"<",
"j",
";",
"++",
"i",
")",
"{",
"promises",
"[",
"i",
"]",
".",
"abort",
"(",
")",
";",
"}",
"return",
"pinky",
";",
"}",
";",
"return",
"pinky",
";",
"}",
")",
";",
"}"
] |
Define external qwest object
|
[
"Define",
"external",
"qwest",
"object"
] |
aaaa999c16fca8007bac0dc24079f720958ffa9a
|
https://github.com/pyrsmk/qwest/blob/aaaa999c16fca8007bac0dc24079f720958ffa9a/src/qwest.js#L398-L460
|
|
19,676
|
pyrsmk/qwest
|
src/qwest.js
|
function(method) {
return function(url, data, options, before) {
var index = ++method_index;
++loading;
promises.push(qwest(method, pinky.base + url, data, options, before).then(function(xhr, response) {
values[index] = arguments;
if(!--loading) {
pinky(true, values.length == 1 ? values[0] : [values]);
}
}, function() {
pinky(false, arguments);
}));
return pinky;
};
}
|
javascript
|
function(method) {
return function(url, data, options, before) {
var index = ++method_index;
++loading;
promises.push(qwest(method, pinky.base + url, data, options, before).then(function(xhr, response) {
values[index] = arguments;
if(!--loading) {
pinky(true, values.length == 1 ? values[0] : [values]);
}
}, function() {
pinky(false, arguments);
}));
return pinky;
};
}
|
[
"function",
"(",
"method",
")",
"{",
"return",
"function",
"(",
"url",
",",
"data",
",",
"options",
",",
"before",
")",
"{",
"var",
"index",
"=",
"++",
"method_index",
";",
"++",
"loading",
";",
"promises",
".",
"push",
"(",
"qwest",
"(",
"method",
",",
"pinky",
".",
"base",
"+",
"url",
",",
"data",
",",
"options",
",",
"before",
")",
".",
"then",
"(",
"function",
"(",
"xhr",
",",
"response",
")",
"{",
"values",
"[",
"index",
"]",
"=",
"arguments",
";",
"if",
"(",
"!",
"--",
"loading",
")",
"{",
"pinky",
"(",
"true",
",",
"values",
".",
"length",
"==",
"1",
"?",
"values",
"[",
"0",
"]",
":",
"[",
"values",
"]",
")",
";",
"}",
"}",
",",
"function",
"(",
")",
"{",
"pinky",
"(",
"false",
",",
"arguments",
")",
";",
"}",
")",
")",
";",
"return",
"pinky",
";",
"}",
";",
"}"
] |
Basic request method
|
[
"Basic",
"request",
"method"
] |
aaaa999c16fca8007bac0dc24079f720958ffa9a
|
https://github.com/pyrsmk/qwest/blob/aaaa999c16fca8007bac0dc24079f720958ffa9a/src/qwest.js#L407-L421
|
|
19,677
|
shakyShane/gulp-svg-sprites
|
index.js
|
getTemplates
|
function getTemplates(config) {
var templates = {};
Object.keys(templatePaths).forEach(function(key) {
if (config.templates && (config.templates[key] && config.templates[key] !== true)) {
templates[key] = config.templates[key];
} else {
templates[key] = fs.readFileSync(__dirname + templatePaths[key], "utf-8");
}
});
return templates;
}
|
javascript
|
function getTemplates(config) {
var templates = {};
Object.keys(templatePaths).forEach(function(key) {
if (config.templates && (config.templates[key] && config.templates[key] !== true)) {
templates[key] = config.templates[key];
} else {
templates[key] = fs.readFileSync(__dirname + templatePaths[key], "utf-8");
}
});
return templates;
}
|
[
"function",
"getTemplates",
"(",
"config",
")",
"{",
"var",
"templates",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"templatePaths",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"config",
".",
"templates",
"&&",
"(",
"config",
".",
"templates",
"[",
"key",
"]",
"&&",
"config",
".",
"templates",
"[",
"key",
"]",
"!==",
"true",
")",
")",
"{",
"templates",
"[",
"key",
"]",
"=",
"config",
".",
"templates",
"[",
"key",
"]",
";",
"}",
"else",
"{",
"templates",
"[",
"key",
"]",
"=",
"fs",
".",
"readFileSync",
"(",
"__dirname",
"+",
"templatePaths",
"[",
"key",
"]",
",",
"\"utf-8\"",
")",
";",
"}",
"}",
")",
";",
"return",
"templates",
";",
"}"
] |
Use user-provided templates first, defaults as fallback
@param {Object} config
@returns {Object}
|
[
"Use",
"user",
"-",
"provided",
"templates",
"first",
"defaults",
"as",
"fallback"
] |
1036e8defb3834f9662cbe20c93afe3e60684d7e
|
https://github.com/shakyShane/gulp-svg-sprites/blob/1036e8defb3834f9662cbe20c93afe3e60684d7e/index.js#L200-L213
|
19,678
|
shakyShane/gulp-svg-sprites
|
index.js
|
transformData
|
function transformData(data, config, done) {
data.baseSize = config.baseSize;
data.svgPath = config.svgPath.replace("%f", config.svg.sprite);
data.pngPath = config.pngPath.replace("%f", config.svg.sprite.replace(/\.svg$/, ".png"));
data.svg = data.svg.map(function(item) {
item.relHeight = item.height / config.baseSize;
item.relWidth = item.width / config.baseSize;
item.relPositionX = item.positionX / config.baseSize - config.padding / config.baseSize;
item.relPositionY = item.positionY / config.baseSize - config.padding / config.baseSize;
item.normal = true;
if (item.name.match(/~/g)) {
if (config.mode !== "sprite") {
return false;
} else {
var segs = item.name.split("~");
item.name = item.selector[0].expression + ":" + segs[1];
item.normal = false;
}
} else {
item.name = item.selector[0].expression;
}
return item;
});
data.svg = data.svg.filter(function(item) { return item; });
data.relWidth = data.swidth / config.baseSize;
data.relHeight = data.sheight / config.baseSize;
if (config.asyncTransforms) {
return done(data);
}
return data;
}
|
javascript
|
function transformData(data, config, done) {
data.baseSize = config.baseSize;
data.svgPath = config.svgPath.replace("%f", config.svg.sprite);
data.pngPath = config.pngPath.replace("%f", config.svg.sprite.replace(/\.svg$/, ".png"));
data.svg = data.svg.map(function(item) {
item.relHeight = item.height / config.baseSize;
item.relWidth = item.width / config.baseSize;
item.relPositionX = item.positionX / config.baseSize - config.padding / config.baseSize;
item.relPositionY = item.positionY / config.baseSize - config.padding / config.baseSize;
item.normal = true;
if (item.name.match(/~/g)) {
if (config.mode !== "sprite") {
return false;
} else {
var segs = item.name.split("~");
item.name = item.selector[0].expression + ":" + segs[1];
item.normal = false;
}
} else {
item.name = item.selector[0].expression;
}
return item;
});
data.svg = data.svg.filter(function(item) { return item; });
data.relWidth = data.swidth / config.baseSize;
data.relHeight = data.sheight / config.baseSize;
if (config.asyncTransforms) {
return done(data);
}
return data;
}
|
[
"function",
"transformData",
"(",
"data",
",",
"config",
",",
"done",
")",
"{",
"data",
".",
"baseSize",
"=",
"config",
".",
"baseSize",
";",
"data",
".",
"svgPath",
"=",
"config",
".",
"svgPath",
".",
"replace",
"(",
"\"%f\"",
",",
"config",
".",
"svg",
".",
"sprite",
")",
";",
"data",
".",
"pngPath",
"=",
"config",
".",
"pngPath",
".",
"replace",
"(",
"\"%f\"",
",",
"config",
".",
"svg",
".",
"sprite",
".",
"replace",
"(",
"/",
"\\.svg$",
"/",
",",
"\".png\"",
")",
")",
";",
"data",
".",
"svg",
"=",
"data",
".",
"svg",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"item",
".",
"relHeight",
"=",
"item",
".",
"height",
"/",
"config",
".",
"baseSize",
";",
"item",
".",
"relWidth",
"=",
"item",
".",
"width",
"/",
"config",
".",
"baseSize",
";",
"item",
".",
"relPositionX",
"=",
"item",
".",
"positionX",
"/",
"config",
".",
"baseSize",
"-",
"config",
".",
"padding",
"/",
"config",
".",
"baseSize",
";",
"item",
".",
"relPositionY",
"=",
"item",
".",
"positionY",
"/",
"config",
".",
"baseSize",
"-",
"config",
".",
"padding",
"/",
"config",
".",
"baseSize",
";",
"item",
".",
"normal",
"=",
"true",
";",
"if",
"(",
"item",
".",
"name",
".",
"match",
"(",
"/",
"~",
"/",
"g",
")",
")",
"{",
"if",
"(",
"config",
".",
"mode",
"!==",
"\"sprite\"",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"var",
"segs",
"=",
"item",
".",
"name",
".",
"split",
"(",
"\"~\"",
")",
";",
"item",
".",
"name",
"=",
"item",
".",
"selector",
"[",
"0",
"]",
".",
"expression",
"+",
"\":\"",
"+",
"segs",
"[",
"1",
"]",
";",
"item",
".",
"normal",
"=",
"false",
";",
"}",
"}",
"else",
"{",
"item",
".",
"name",
"=",
"item",
".",
"selector",
"[",
"0",
"]",
".",
"expression",
";",
"}",
"return",
"item",
";",
"}",
")",
";",
"data",
".",
"svg",
"=",
"data",
".",
"svg",
".",
"filter",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
";",
"}",
")",
";",
"data",
".",
"relWidth",
"=",
"data",
".",
"swidth",
"/",
"config",
".",
"baseSize",
";",
"data",
".",
"relHeight",
"=",
"data",
".",
"sheight",
"/",
"config",
".",
"baseSize",
";",
"if",
"(",
"config",
".",
"asyncTransforms",
")",
"{",
"return",
"done",
"(",
"data",
")",
";",
"}",
"return",
"data",
";",
"}"
] |
Any last-minute data transformations before handing off to templates,
can be overridden by supplying a 'transformData' option
@param data
@param config
@returns {*}
|
[
"Any",
"last",
"-",
"minute",
"data",
"transformations",
"before",
"handing",
"off",
"to",
"templates",
"can",
"be",
"overridden",
"by",
"supplying",
"a",
"transformData",
"option"
] |
1036e8defb3834f9662cbe20c93afe3e60684d7e
|
https://github.com/shakyShane/gulp-svg-sprites/blob/1036e8defb3834f9662cbe20c93afe3e60684d7e/index.js#L222-L262
|
19,679
|
danielstjules/mocha.parallel
|
spec/spec.js
|
run
|
function run() {
var bin = path.resolve(__dirname, '../node_modules/.bin/mocha');
var args = Array.prototype.slice.call(arguments);
var fn = args.pop();
var cmd = [bin].concat(args).join(' ') + ' --no-colors';
exec(cmd, fn);
}
|
javascript
|
function run() {
var bin = path.resolve(__dirname, '../node_modules/.bin/mocha');
var args = Array.prototype.slice.call(arguments);
var fn = args.pop();
var cmd = [bin].concat(args).join(' ') + ' --no-colors';
exec(cmd, fn);
}
|
[
"function",
"run",
"(",
")",
"{",
"var",
"bin",
"=",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../node_modules/.bin/mocha'",
")",
";",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"var",
"fn",
"=",
"args",
".",
"pop",
"(",
")",
";",
"var",
"cmd",
"=",
"[",
"bin",
"]",
".",
"concat",
"(",
"args",
")",
".",
"join",
"(",
"' '",
")",
"+",
"' --no-colors'",
";",
"exec",
"(",
"cmd",
",",
"fn",
")",
";",
"}"
] |
Runs mocha with the supplied argumentss, and passes the resulting stdout and
stderr to the callback.
@param {...string} args
@param {function} fn
|
[
"Runs",
"mocha",
"with",
"the",
"supplied",
"argumentss",
"and",
"passes",
"the",
"resulting",
"stdout",
"and",
"stderr",
"to",
"the",
"callback",
"."
] |
7d097eb5146472384227ce78e08f1a8954517196
|
https://github.com/danielstjules/mocha.parallel/blob/7d097eb5146472384227ce78e08f1a8954517196/spec/spec.js#L316-L322
|
19,680
|
danielstjules/mocha.parallel
|
spec/spec.js
|
assertSubstrings
|
function assertSubstrings(str, substrings) {
substrings.forEach(function(substring) {
assert(str.indexOf(substring) !== -1, str +
' - string does not contain: ' + substring);
});
}
|
javascript
|
function assertSubstrings(str, substrings) {
substrings.forEach(function(substring) {
assert(str.indexOf(substring) !== -1, str +
' - string does not contain: ' + substring);
});
}
|
[
"function",
"assertSubstrings",
"(",
"str",
",",
"substrings",
")",
"{",
"substrings",
".",
"forEach",
"(",
"function",
"(",
"substring",
")",
"{",
"assert",
"(",
"str",
".",
"indexOf",
"(",
"substring",
")",
"!==",
"-",
"1",
",",
"str",
"+",
"' - string does not contain: '",
"+",
"substring",
")",
";",
"}",
")",
";",
"}"
] |
Asserts that each substring is present in the supplied string.
@param {string} str
@param {string[]} substrings
|
[
"Asserts",
"that",
"each",
"substring",
"is",
"present",
"in",
"the",
"supplied",
"string",
"."
] |
7d097eb5146472384227ce78e08f1a8954517196
|
https://github.com/danielstjules/mocha.parallel/blob/7d097eb5146472384227ce78e08f1a8954517196/spec/spec.js#L341-L346
|
19,681
|
danielstjules/mocha.parallel
|
lib/parallel.js
|
patchHooks
|
function patchHooks(hooks) {
var original = {};
var restore;
hookTypes.map(function(key) {
original[key] = global[key];
global[key] = function(title, fn) {
// Hooks accept an optional title, though they're
// ignored here for simplicity
if (!fn) fn = title;
hooks[key] = createWrapper(fn);
};
});
restore = function() {
hookTypes.forEach(function(key) {
global[key] = original[key];
});
};
return restore;
}
|
javascript
|
function patchHooks(hooks) {
var original = {};
var restore;
hookTypes.map(function(key) {
original[key] = global[key];
global[key] = function(title, fn) {
// Hooks accept an optional title, though they're
// ignored here for simplicity
if (!fn) fn = title;
hooks[key] = createWrapper(fn);
};
});
restore = function() {
hookTypes.forEach(function(key) {
global[key] = original[key];
});
};
return restore;
}
|
[
"function",
"patchHooks",
"(",
"hooks",
")",
"{",
"var",
"original",
"=",
"{",
"}",
";",
"var",
"restore",
";",
"hookTypes",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"original",
"[",
"key",
"]",
"=",
"global",
"[",
"key",
"]",
";",
"global",
"[",
"key",
"]",
"=",
"function",
"(",
"title",
",",
"fn",
")",
"{",
"// Hooks accept an optional title, though they're",
"// ignored here for simplicity",
"if",
"(",
"!",
"fn",
")",
"fn",
"=",
"title",
";",
"hooks",
"[",
"key",
"]",
"=",
"createWrapper",
"(",
"fn",
")",
";",
"}",
";",
"}",
")",
";",
"restore",
"=",
"function",
"(",
")",
"{",
"hookTypes",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"global",
"[",
"key",
"]",
"=",
"original",
"[",
"key",
"]",
";",
"}",
")",
";",
"}",
";",
"return",
"restore",
";",
"}"
] |
Patches the global hook functions used by mocha, and returns a function
that restores the original behavior when invoked.
@param {object} hooks Object on which to add hooks
@returns {function} Function that restores the original it() behavior
|
[
"Patches",
"the",
"global",
"hook",
"functions",
"used",
"by",
"mocha",
"and",
"returns",
"a",
"function",
"that",
"restores",
"the",
"original",
"behavior",
"when",
"invoked",
"."
] |
7d097eb5146472384227ce78e08f1a8954517196
|
https://github.com/danielstjules/mocha.parallel/blob/7d097eb5146472384227ce78e08f1a8954517196/lib/parallel.js#L266-L288
|
19,682
|
danielstjules/mocha.parallel
|
lib/parallel.js
|
createWrapper
|
function createWrapper(fn, ctx) {
return function() {
return new Promise(function(resolve, reject) {
var start = Date.now();
var cb = function(err) {
if (err) return reject(err);
resolve(Date.now() - start);
};
// Wrap generator functions
if (fn && fn.constructor.name === 'GeneratorFunction') {
fn = Promise.coroutine(fn);
}
var res = fn.call(ctx || this, cb);
// Synchronous spec, or using promises rather than callbacks
if (!fn.length || (res && res.then)) {
Promise.resolve(res).then(function() {
resolve(Date.now() - start);
}, reject);
}
});
};
}
|
javascript
|
function createWrapper(fn, ctx) {
return function() {
return new Promise(function(resolve, reject) {
var start = Date.now();
var cb = function(err) {
if (err) return reject(err);
resolve(Date.now() - start);
};
// Wrap generator functions
if (fn && fn.constructor.name === 'GeneratorFunction') {
fn = Promise.coroutine(fn);
}
var res = fn.call(ctx || this, cb);
// Synchronous spec, or using promises rather than callbacks
if (!fn.length || (res && res.then)) {
Promise.resolve(res).then(function() {
resolve(Date.now() - start);
}, reject);
}
});
};
}
|
[
"function",
"createWrapper",
"(",
"fn",
",",
"ctx",
")",
"{",
"return",
"function",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"var",
"cb",
"=",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
";",
"resolve",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"start",
")",
";",
"}",
";",
"// Wrap generator functions",
"if",
"(",
"fn",
"&&",
"fn",
".",
"constructor",
".",
"name",
"===",
"'GeneratorFunction'",
")",
"{",
"fn",
"=",
"Promise",
".",
"coroutine",
"(",
"fn",
")",
";",
"}",
"var",
"res",
"=",
"fn",
".",
"call",
"(",
"ctx",
"||",
"this",
",",
"cb",
")",
";",
"// Synchronous spec, or using promises rather than callbacks",
"if",
"(",
"!",
"fn",
".",
"length",
"||",
"(",
"res",
"&&",
"res",
".",
"then",
")",
")",
"{",
"Promise",
".",
"resolve",
"(",
"res",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"resolve",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"start",
")",
";",
"}",
",",
"reject",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"}"
] |
Returns a wrapper for a given runnable's fn, including specs or hooks.
Optionally binds the function handler to the passed context. Resolves
with the duration of the fn.
@param {function} fn
@param {function} [ctx]
@returns {function}
|
[
"Returns",
"a",
"wrapper",
"for",
"a",
"given",
"runnable",
"s",
"fn",
"including",
"specs",
"or",
"hooks",
".",
"Optionally",
"binds",
"the",
"function",
"handler",
"to",
"the",
"passed",
"context",
".",
"Resolves",
"with",
"the",
"duration",
"of",
"the",
"fn",
"."
] |
7d097eb5146472384227ce78e08f1a8954517196
|
https://github.com/danielstjules/mocha.parallel/blob/7d097eb5146472384227ce78e08f1a8954517196/lib/parallel.js#L299-L324
|
19,683
|
danielstjules/mocha.parallel
|
lib/parallel.js
|
patchUncaught
|
function patchUncaught() {
var name = 'uncaughtException';
var originalListener = process.listeners(name).pop();
if (originalListener) {
process.removeListener(name, originalListener);
}
return function() {
if (!originalListener) return;
process.on(name, originalListener);
};
}
|
javascript
|
function patchUncaught() {
var name = 'uncaughtException';
var originalListener = process.listeners(name).pop();
if (originalListener) {
process.removeListener(name, originalListener);
}
return function() {
if (!originalListener) return;
process.on(name, originalListener);
};
}
|
[
"function",
"patchUncaught",
"(",
")",
"{",
"var",
"name",
"=",
"'uncaughtException'",
";",
"var",
"originalListener",
"=",
"process",
".",
"listeners",
"(",
"name",
")",
".",
"pop",
"(",
")",
";",
"if",
"(",
"originalListener",
")",
"{",
"process",
".",
"removeListener",
"(",
"name",
",",
"originalListener",
")",
";",
"}",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"originalListener",
")",
"return",
";",
"process",
".",
"on",
"(",
"name",
",",
"originalListener",
")",
";",
"}",
";",
"}"
] |
Removes mocha's uncaughtException handler, allowing exceptions to be handled
by domains during parallel spec execution, and all others to terminate the
process.
@returns {function} Function that restores mocha's uncaughtException listener
|
[
"Removes",
"mocha",
"s",
"uncaughtException",
"handler",
"allowing",
"exceptions",
"to",
"be",
"handled",
"by",
"domains",
"during",
"parallel",
"spec",
"execution",
"and",
"all",
"others",
"to",
"terminate",
"the",
"process",
"."
] |
7d097eb5146472384227ce78e08f1a8954517196
|
https://github.com/danielstjules/mocha.parallel/blob/7d097eb5146472384227ce78e08f1a8954517196/lib/parallel.js#L404-L416
|
19,684
|
craveprogramminginc/GeoJSON-Validation
|
index.js
|
_done
|
function _done (cb, message) {
var valid = false
if (typeof message === 'string') {
message = [message]
} else if (Object.prototype.toString.call(message) === '[object Array]') {
if (message.length === 0) {
valid = true
}
} else {
valid = true
}
if (isFunction(cb)) {
if (valid) {
cb(valid, [])
} else {
cb(valid, message)
}
}
return valid
}
|
javascript
|
function _done (cb, message) {
var valid = false
if (typeof message === 'string') {
message = [message]
} else if (Object.prototype.toString.call(message) === '[object Array]') {
if (message.length === 0) {
valid = true
}
} else {
valid = true
}
if (isFunction(cb)) {
if (valid) {
cb(valid, [])
} else {
cb(valid, message)
}
}
return valid
}
|
[
"function",
"_done",
"(",
"cb",
",",
"message",
")",
"{",
"var",
"valid",
"=",
"false",
"if",
"(",
"typeof",
"message",
"===",
"'string'",
")",
"{",
"message",
"=",
"[",
"message",
"]",
"}",
"else",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"message",
")",
"===",
"'[object Array]'",
")",
"{",
"if",
"(",
"message",
".",
"length",
"===",
"0",
")",
"{",
"valid",
"=",
"true",
"}",
"}",
"else",
"{",
"valid",
"=",
"true",
"}",
"if",
"(",
"isFunction",
"(",
"cb",
")",
")",
"{",
"if",
"(",
"valid",
")",
"{",
"cb",
"(",
"valid",
",",
"[",
"]",
")",
"}",
"else",
"{",
"cb",
"(",
"valid",
",",
"message",
")",
"}",
"}",
"return",
"valid",
"}"
] |
Formats error messages, calls the callback
@method done
@private
@param cb {Function} callback
@param [message] {Function} callback
@return {Boolean} is the object valid or not?
|
[
"Formats",
"error",
"messages",
"calls",
"the",
"callback"
] |
677b445715575d8e54cd3e6ac63afc67ed72c09a
|
https://github.com/craveprogramminginc/GeoJSON-Validation/blob/677b445715575d8e54cd3e6ac63afc67ed72c09a/index.js#L38-L60
|
19,685
|
craveprogramminginc/GeoJSON-Validation
|
index.js
|
_customDefinitions
|
function _customDefinitions (type, object) {
var errors
if (isFunction(definitions[type])) {
try {
errors = definitions[type](object)
} catch (e) {
errors = ['Problem with custom definition for '+type+': '+e]
}
if (typeof result === 'string') {
errors = [errors]
}
if (Object.prototype.toString.call(errors) === '[object Array]') {
return errors
}
}
return []
}
|
javascript
|
function _customDefinitions (type, object) {
var errors
if (isFunction(definitions[type])) {
try {
errors = definitions[type](object)
} catch (e) {
errors = ['Problem with custom definition for '+type+': '+e]
}
if (typeof result === 'string') {
errors = [errors]
}
if (Object.prototype.toString.call(errors) === '[object Array]') {
return errors
}
}
return []
}
|
[
"function",
"_customDefinitions",
"(",
"type",
",",
"object",
")",
"{",
"var",
"errors",
"if",
"(",
"isFunction",
"(",
"definitions",
"[",
"type",
"]",
")",
")",
"{",
"try",
"{",
"errors",
"=",
"definitions",
"[",
"type",
"]",
"(",
"object",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"errors",
"=",
"[",
"'Problem with custom definition for '",
"+",
"type",
"+",
"': '",
"+",
"e",
"]",
"}",
"if",
"(",
"typeof",
"result",
"===",
"'string'",
")",
"{",
"errors",
"=",
"[",
"errors",
"]",
"}",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"errors",
")",
"===",
"'[object Array]'",
")",
"{",
"return",
"errors",
"}",
"}",
"return",
"[",
"]",
"}"
] |
calls a custom definition if one is avalible for the given type
@method _customDefinitions
@private
@param type {'String'} a GeoJSON object type
@param object {Object} the Object being tested
@return {Array} an array of errors
|
[
"calls",
"a",
"custom",
"definition",
"if",
"one",
"is",
"avalible",
"for",
"the",
"given",
"type"
] |
677b445715575d8e54cd3e6ac63afc67ed72c09a
|
https://github.com/craveprogramminginc/GeoJSON-Validation/blob/677b445715575d8e54cd3e6ac63afc67ed72c09a/index.js#L70-L87
|
19,686
|
bigeasy/packet
|
explode.js
|
explode
|
function explode (field) {
switch (field.type) {
case 'structure':
field.fields = field.fields.map(explode)
break
case 'alternation':
field.select = explode(field.select)
field.choose.forEach(function (option) {
option.read.field = explode(option.read.field)
option.write.field = explode(option.write.field)
})
break
case 'lengthEncoded':
field.length = explode(field.length)
field.element = explode(field.element)
break
case 'integer':
var little = field.endianness === 'l'
if (field.bits == null && field.fields != null) {
field.bits = field.fields.reduce(function (sum, value) {
return sum + value.bits
}, 0)
}
var bytes = field.bits / 8
field = {
name: field.name || null,
length: field.length || null,
endianness: field.endianness,
type: 'integer',
little: little,
bite: little ? 0 : bytes - 1,
direction: little ? 1 : -1,
stop: little ? bytes : -1,
bits: field.bits,
bytes: bytes,
fields: packing(field.fields)
}
break
}
return field
}
|
javascript
|
function explode (field) {
switch (field.type) {
case 'structure':
field.fields = field.fields.map(explode)
break
case 'alternation':
field.select = explode(field.select)
field.choose.forEach(function (option) {
option.read.field = explode(option.read.field)
option.write.field = explode(option.write.field)
})
break
case 'lengthEncoded':
field.length = explode(field.length)
field.element = explode(field.element)
break
case 'integer':
var little = field.endianness === 'l'
if (field.bits == null && field.fields != null) {
field.bits = field.fields.reduce(function (sum, value) {
return sum + value.bits
}, 0)
}
var bytes = field.bits / 8
field = {
name: field.name || null,
length: field.length || null,
endianness: field.endianness,
type: 'integer',
little: little,
bite: little ? 0 : bytes - 1,
direction: little ? 1 : -1,
stop: little ? bytes : -1,
bits: field.bits,
bytes: bytes,
fields: packing(field.fields)
}
break
}
return field
}
|
[
"function",
"explode",
"(",
"field",
")",
"{",
"switch",
"(",
"field",
".",
"type",
")",
"{",
"case",
"'structure'",
":",
"field",
".",
"fields",
"=",
"field",
".",
"fields",
".",
"map",
"(",
"explode",
")",
"break",
"case",
"'alternation'",
":",
"field",
".",
"select",
"=",
"explode",
"(",
"field",
".",
"select",
")",
"field",
".",
"choose",
".",
"forEach",
"(",
"function",
"(",
"option",
")",
"{",
"option",
".",
"read",
".",
"field",
"=",
"explode",
"(",
"option",
".",
"read",
".",
"field",
")",
"option",
".",
"write",
".",
"field",
"=",
"explode",
"(",
"option",
".",
"write",
".",
"field",
")",
"}",
")",
"break",
"case",
"'lengthEncoded'",
":",
"field",
".",
"length",
"=",
"explode",
"(",
"field",
".",
"length",
")",
"field",
".",
"element",
"=",
"explode",
"(",
"field",
".",
"element",
")",
"break",
"case",
"'integer'",
":",
"var",
"little",
"=",
"field",
".",
"endianness",
"===",
"'l'",
"if",
"(",
"field",
".",
"bits",
"==",
"null",
"&&",
"field",
".",
"fields",
"!=",
"null",
")",
"{",
"field",
".",
"bits",
"=",
"field",
".",
"fields",
".",
"reduce",
"(",
"function",
"(",
"sum",
",",
"value",
")",
"{",
"return",
"sum",
"+",
"value",
".",
"bits",
"}",
",",
"0",
")",
"}",
"var",
"bytes",
"=",
"field",
".",
"bits",
"/",
"8",
"field",
"=",
"{",
"name",
":",
"field",
".",
"name",
"||",
"null",
",",
"length",
":",
"field",
".",
"length",
"||",
"null",
",",
"endianness",
":",
"field",
".",
"endianness",
",",
"type",
":",
"'integer'",
",",
"little",
":",
"little",
",",
"bite",
":",
"little",
"?",
"0",
":",
"bytes",
"-",
"1",
",",
"direction",
":",
"little",
"?",
"1",
":",
"-",
"1",
",",
"stop",
":",
"little",
"?",
"bytes",
":",
"-",
"1",
",",
"bits",
":",
"field",
".",
"bits",
",",
"bytes",
":",
"bytes",
",",
"fields",
":",
"packing",
"(",
"field",
".",
"fields",
")",
"}",
"break",
"}",
"return",
"field",
"}"
] |
Explode a field specified in the intermediate language, filling in all the properties needed by a generator. Saves the hastle and clutter of repeating these calculations as needed.
|
[
"Explode",
"a",
"field",
"specified",
"in",
"the",
"intermediate",
"language",
"filling",
"in",
"all",
"the",
"properties",
"needed",
"by",
"a",
"generator",
".",
"Saves",
"the",
"hastle",
"and",
"clutter",
"of",
"repeating",
"these",
"calculations",
"as",
"needed",
"."
] |
81aa4e2dcc57a7ed4020d28842fab809e1a55a8d
|
https://github.com/bigeasy/packet/blob/81aa4e2dcc57a7ed4020d28842fab809e1a55a8d/explode.js#L18-L58
|
19,687
|
froala/angular-froala
|
src/froala-sanitize.js
|
validStyles
|
function validStyles(styleAttr) {
var result = '';
var styleArray = styleAttr.split(';');
angular.forEach(styleArray, function (value) {
var v = value.split(':');
if (v.length === 2) {
var key = trim(v[0].toLowerCase());
value = trim(v[1].toLowerCase());
if (
(key === 'color' || key === 'background-color') && (
value.match(/^rgb\([0-9%,\. ]*\)$/i) ||
value.match(/^rgba\([0-9%,\. ]*\)$/i) ||
value.match(/^hsl\([0-9%,\. ]*\)$/i) ||
value.match(/^hsla\([0-9%,\. ]*\)$/i) ||
value.match(/^#[0-9a-f]{3,6}$/i) ||
value.match(/^[a-z]*$/i)
) ||
key === 'text-align' && (
value === 'left' ||
value === 'right' ||
value === 'center' ||
value === 'justify'
) ||
key === 'float' && (
value === 'left' ||
value === 'right' ||
value === 'none'
) ||
key === 'direction' && (
value === 'rtl' ||
value === 'ltr'
) ||
key === 'font-family' && (
value === 'arial,helvetica,sans-serif' ||
value === 'georgia,serif' ||
value === 'impact,charcoal,sans-serif' ||
value === 'tahoma,geneva,sans-serif' ||
value === "'times new roman',times,serif" ||
value === 'verdana,geneva,sans-serif'
) ||
(key === 'width' || key === 'height' || key === 'font-size' || key === 'margin-left') && (
value.match(/[0-9\.]*(px|em|rem|%)/)
)
) {
result += key + ': ' + value + ';';
}
}
});
return result;
}
|
javascript
|
function validStyles(styleAttr) {
var result = '';
var styleArray = styleAttr.split(';');
angular.forEach(styleArray, function (value) {
var v = value.split(':');
if (v.length === 2) {
var key = trim(v[0].toLowerCase());
value = trim(v[1].toLowerCase());
if (
(key === 'color' || key === 'background-color') && (
value.match(/^rgb\([0-9%,\. ]*\)$/i) ||
value.match(/^rgba\([0-9%,\. ]*\)$/i) ||
value.match(/^hsl\([0-9%,\. ]*\)$/i) ||
value.match(/^hsla\([0-9%,\. ]*\)$/i) ||
value.match(/^#[0-9a-f]{3,6}$/i) ||
value.match(/^[a-z]*$/i)
) ||
key === 'text-align' && (
value === 'left' ||
value === 'right' ||
value === 'center' ||
value === 'justify'
) ||
key === 'float' && (
value === 'left' ||
value === 'right' ||
value === 'none'
) ||
key === 'direction' && (
value === 'rtl' ||
value === 'ltr'
) ||
key === 'font-family' && (
value === 'arial,helvetica,sans-serif' ||
value === 'georgia,serif' ||
value === 'impact,charcoal,sans-serif' ||
value === 'tahoma,geneva,sans-serif' ||
value === "'times new roman',times,serif" ||
value === 'verdana,geneva,sans-serif'
) ||
(key === 'width' || key === 'height' || key === 'font-size' || key === 'margin-left') && (
value.match(/[0-9\.]*(px|em|rem|%)/)
)
) {
result += key + ': ' + value + ';';
}
}
});
return result;
}
|
[
"function",
"validStyles",
"(",
"styleAttr",
")",
"{",
"var",
"result",
"=",
"''",
";",
"var",
"styleArray",
"=",
"styleAttr",
".",
"split",
"(",
"';'",
")",
";",
"angular",
".",
"forEach",
"(",
"styleArray",
",",
"function",
"(",
"value",
")",
"{",
"var",
"v",
"=",
"value",
".",
"split",
"(",
"':'",
")",
";",
"if",
"(",
"v",
".",
"length",
"===",
"2",
")",
"{",
"var",
"key",
"=",
"trim",
"(",
"v",
"[",
"0",
"]",
".",
"toLowerCase",
"(",
")",
")",
";",
"value",
"=",
"trim",
"(",
"v",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
")",
";",
"if",
"(",
"(",
"key",
"===",
"'color'",
"||",
"key",
"===",
"'background-color'",
")",
"&&",
"(",
"value",
".",
"match",
"(",
"/",
"^rgb\\([0-9%,\\. ]*\\)$",
"/",
"i",
")",
"||",
"value",
".",
"match",
"(",
"/",
"^rgba\\([0-9%,\\. ]*\\)$",
"/",
"i",
")",
"||",
"value",
".",
"match",
"(",
"/",
"^hsl\\([0-9%,\\. ]*\\)$",
"/",
"i",
")",
"||",
"value",
".",
"match",
"(",
"/",
"^hsla\\([0-9%,\\. ]*\\)$",
"/",
"i",
")",
"||",
"value",
".",
"match",
"(",
"/",
"^#[0-9a-f]{3,6}$",
"/",
"i",
")",
"||",
"value",
".",
"match",
"(",
"/",
"^[a-z]*$",
"/",
"i",
")",
")",
"||",
"key",
"===",
"'text-align'",
"&&",
"(",
"value",
"===",
"'left'",
"||",
"value",
"===",
"'right'",
"||",
"value",
"===",
"'center'",
"||",
"value",
"===",
"'justify'",
")",
"||",
"key",
"===",
"'float'",
"&&",
"(",
"value",
"===",
"'left'",
"||",
"value",
"===",
"'right'",
"||",
"value",
"===",
"'none'",
")",
"||",
"key",
"===",
"'direction'",
"&&",
"(",
"value",
"===",
"'rtl'",
"||",
"value",
"===",
"'ltr'",
")",
"||",
"key",
"===",
"'font-family'",
"&&",
"(",
"value",
"===",
"'arial,helvetica,sans-serif'",
"||",
"value",
"===",
"'georgia,serif'",
"||",
"value",
"===",
"'impact,charcoal,sans-serif'",
"||",
"value",
"===",
"'tahoma,geneva,sans-serif'",
"||",
"value",
"===",
"\"'times new roman',times,serif\"",
"||",
"value",
"===",
"'verdana,geneva,sans-serif'",
")",
"||",
"(",
"key",
"===",
"'width'",
"||",
"key",
"===",
"'height'",
"||",
"key",
"===",
"'font-size'",
"||",
"key",
"===",
"'margin-left'",
")",
"&&",
"(",
"value",
".",
"match",
"(",
"/",
"[0-9\\.]*(px|em|rem|%)",
"/",
")",
")",
")",
"{",
"result",
"+=",
"key",
"+",
"': '",
"+",
"value",
"+",
"';'",
";",
"}",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Custom logic for accepting certain style options only - angularFroala Currently allows only the color, background-color, text-align, direction, font-family, font-size, float, width and height attributes all other attributes should be easily done through classes.
|
[
"Custom",
"logic",
"for",
"accepting",
"certain",
"style",
"options",
"only",
"-",
"angularFroala",
"Currently",
"allows",
"only",
"the",
"color",
"background",
"-",
"color",
"text",
"-",
"align",
"direction",
"font",
"-",
"family",
"font",
"-",
"size",
"float",
"width",
"and",
"height",
"attributes",
"all",
"other",
"attributes",
"should",
"be",
"easily",
"done",
"through",
"classes",
"."
] |
98666c5bc842a004d2aaca71526fcc71e60f5f32
|
https://github.com/froala/angular-froala/blob/98666c5bc842a004d2aaca71526fcc71e60f5f32/src/froala-sanitize.js#L593-L642
|
19,688
|
froala/angular-froala
|
src/froala-sanitize.js
|
validCustomTag
|
function validCustomTag(tag, attrs, lkey, value) {
// catch the div placeholder for the iframe replacement
if (tag === 'img' && attrs['ta-insert-video']) {
if (lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditble' && value === 'false')) {
return true;
}
}
return false;
}
|
javascript
|
function validCustomTag(tag, attrs, lkey, value) {
// catch the div placeholder for the iframe replacement
if (tag === 'img' && attrs['ta-insert-video']) {
if (lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditble' && value === 'false')) {
return true;
}
}
return false;
}
|
[
"function",
"validCustomTag",
"(",
"tag",
",",
"attrs",
",",
"lkey",
",",
"value",
")",
"{",
"// catch the div placeholder for the iframe replacement",
"if",
"(",
"tag",
"===",
"'img'",
"&&",
"attrs",
"[",
"'ta-insert-video'",
"]",
")",
"{",
"if",
"(",
"lkey",
"===",
"'ta-insert-video'",
"||",
"lkey",
"===",
"'allowfullscreen'",
"||",
"lkey",
"===",
"'frameborder'",
"||",
"(",
"lkey",
"===",
"'contenteditble'",
"&&",
"value",
"===",
"'false'",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
this function is used to manually allow specific attributes on specific tags with certain prerequisites
|
[
"this",
"function",
"is",
"used",
"to",
"manually",
"allow",
"specific",
"attributes",
"on",
"specific",
"tags",
"with",
"certain",
"prerequisites"
] |
98666c5bc842a004d2aaca71526fcc71e60f5f32
|
https://github.com/froala/angular-froala/blob/98666c5bc842a004d2aaca71526fcc71e60f5f32/src/froala-sanitize.js#L645-L653
|
19,689
|
tmcw/parse-gedcom
|
index.js
|
buildTree
|
function buildTree(memo, data) {
if (data.level === memo.level) {
memo.pointer.tree.push(data);
} else if (data.level > memo.level) {
var up = memo.pointer;
memo.pointer = memo.pointer.tree[
memo.pointer.tree.length - 1];
memo.pointer.tree.push(data);
memo.pointer.up = up;
memo.level = data.level;
} else if (data.level < memo.level) {
// the jump up in the stack may be by more than one, so ascend
// until we're at the right level.
while (data.level <= memo.pointer.level && memo.pointer.up) {
memo.pointer = memo.pointer.up;
}
memo.pointer.tree.push(data);
memo.level = data.level;
}
return memo;
}
|
javascript
|
function buildTree(memo, data) {
if (data.level === memo.level) {
memo.pointer.tree.push(data);
} else if (data.level > memo.level) {
var up = memo.pointer;
memo.pointer = memo.pointer.tree[
memo.pointer.tree.length - 1];
memo.pointer.tree.push(data);
memo.pointer.up = up;
memo.level = data.level;
} else if (data.level < memo.level) {
// the jump up in the stack may be by more than one, so ascend
// until we're at the right level.
while (data.level <= memo.pointer.level && memo.pointer.up) {
memo.pointer = memo.pointer.up;
}
memo.pointer.tree.push(data);
memo.level = data.level;
}
return memo;
}
|
[
"function",
"buildTree",
"(",
"memo",
",",
"data",
")",
"{",
"if",
"(",
"data",
".",
"level",
"===",
"memo",
".",
"level",
")",
"{",
"memo",
".",
"pointer",
".",
"tree",
".",
"push",
"(",
"data",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"level",
">",
"memo",
".",
"level",
")",
"{",
"var",
"up",
"=",
"memo",
".",
"pointer",
";",
"memo",
".",
"pointer",
"=",
"memo",
".",
"pointer",
".",
"tree",
"[",
"memo",
".",
"pointer",
".",
"tree",
".",
"length",
"-",
"1",
"]",
";",
"memo",
".",
"pointer",
".",
"tree",
".",
"push",
"(",
"data",
")",
";",
"memo",
".",
"pointer",
".",
"up",
"=",
"up",
";",
"memo",
".",
"level",
"=",
"data",
".",
"level",
";",
"}",
"else",
"if",
"(",
"data",
".",
"level",
"<",
"memo",
".",
"level",
")",
"{",
"// the jump up in the stack may be by more than one, so ascend",
"// until we're at the right level.",
"while",
"(",
"data",
".",
"level",
"<=",
"memo",
".",
"pointer",
".",
"level",
"&&",
"memo",
".",
"pointer",
".",
"up",
")",
"{",
"memo",
".",
"pointer",
"=",
"memo",
".",
"pointer",
".",
"up",
";",
"}",
"memo",
".",
"pointer",
".",
"tree",
".",
"push",
"(",
"data",
")",
";",
"memo",
".",
"level",
"=",
"data",
".",
"level",
";",
"}",
"return",
"memo",
";",
"}"
] |
the basic trick of this module is turning the suggested tree structure of a GEDCOM file into a tree in JSON. This reduction does that. The only real trick is the `.up` member of objects that points to a level up in the structure. This we have to censor before JSON.stringify since it creates circular references.
|
[
"the",
"basic",
"trick",
"of",
"this",
"module",
"is",
"turning",
"the",
"suggested",
"tree",
"structure",
"of",
"a",
"GEDCOM",
"file",
"into",
"a",
"tree",
"in",
"JSON",
".",
"This",
"reduction",
"does",
"that",
".",
"The",
"only",
"real",
"trick",
"is",
"the",
".",
"up",
"member",
"of",
"objects",
"that",
"points",
"to",
"a",
"level",
"up",
"in",
"the",
"structure",
".",
"This",
"we",
"have",
"to",
"censor",
"before",
"JSON",
".",
"stringify",
"since",
"it",
"creates",
"circular",
"references",
"."
] |
61915b8ac58f9a9902a98b85cd730f497ea3fa1f
|
https://github.com/tmcw/parse-gedcom/blob/61915b8ac58f9a9902a98b85cd730f497ea3fa1f/index.js#L30-L50
|
19,690
|
gpbl/denormalizr
|
src/index.js
|
resolveEntityOrId
|
function resolveEntityOrId(entityOrId, entities, schema) {
const key = schema.key;
let entity = entityOrId;
let id = entityOrId;
if (isObject(entityOrId)) {
const mutableEntity = isImmutable(entity) ? entity.toJS() : entity;
id = schema.getId(mutableEntity) || getIn(entity, ['id']);
} else {
entity = getIn(entities, [key, id]);
}
return { entity, id };
}
|
javascript
|
function resolveEntityOrId(entityOrId, entities, schema) {
const key = schema.key;
let entity = entityOrId;
let id = entityOrId;
if (isObject(entityOrId)) {
const mutableEntity = isImmutable(entity) ? entity.toJS() : entity;
id = schema.getId(mutableEntity) || getIn(entity, ['id']);
} else {
entity = getIn(entities, [key, id]);
}
return { entity, id };
}
|
[
"function",
"resolveEntityOrId",
"(",
"entityOrId",
",",
"entities",
",",
"schema",
")",
"{",
"const",
"key",
"=",
"schema",
".",
"key",
";",
"let",
"entity",
"=",
"entityOrId",
";",
"let",
"id",
"=",
"entityOrId",
";",
"if",
"(",
"isObject",
"(",
"entityOrId",
")",
")",
"{",
"const",
"mutableEntity",
"=",
"isImmutable",
"(",
"entity",
")",
"?",
"entity",
".",
"toJS",
"(",
")",
":",
"entity",
";",
"id",
"=",
"schema",
".",
"getId",
"(",
"mutableEntity",
")",
"||",
"getIn",
"(",
"entity",
",",
"[",
"'id'",
"]",
")",
";",
"}",
"else",
"{",
"entity",
"=",
"getIn",
"(",
"entities",
",",
"[",
"key",
",",
"id",
"]",
")",
";",
"}",
"return",
"{",
"entity",
",",
"id",
"}",
";",
"}"
] |
Take either an entity or id and derive the other.
@param {object|Immutable.Map|number|string} entityOrId
@param {object|Immutable.Map} entities
@param {schema.Entity} schema
@returns {object}
|
[
"Take",
"either",
"an",
"entity",
"or",
"id",
"and",
"derive",
"the",
"other",
"."
] |
11baeab9e9cb058f1096196d0d4c2e42e0ef8937
|
https://github.com/gpbl/denormalizr/blob/11baeab9e9cb058f1096196d0d4c2e42e0ef8937/src/index.js#L19-L33
|
19,691
|
gpbl/denormalizr
|
src/index.js
|
denormalizeIterable
|
function denormalizeIterable(items, entities, schema, bag) {
const isMappable = typeof items.map === 'function';
const itemSchema = Array.isArray(schema) ? schema[0] : schema.schema;
// Handle arrayOf iterables
if (isMappable) {
return items.map(o => denormalize(o, entities, itemSchema, bag));
}
// Handle valuesOf iterables
const denormalized = {};
Object.keys(items).forEach((key) => {
denormalized[key] = denormalize(items[key], entities, itemSchema, bag);
});
return denormalized;
}
|
javascript
|
function denormalizeIterable(items, entities, schema, bag) {
const isMappable = typeof items.map === 'function';
const itemSchema = Array.isArray(schema) ? schema[0] : schema.schema;
// Handle arrayOf iterables
if (isMappable) {
return items.map(o => denormalize(o, entities, itemSchema, bag));
}
// Handle valuesOf iterables
const denormalized = {};
Object.keys(items).forEach((key) => {
denormalized[key] = denormalize(items[key], entities, itemSchema, bag);
});
return denormalized;
}
|
[
"function",
"denormalizeIterable",
"(",
"items",
",",
"entities",
",",
"schema",
",",
"bag",
")",
"{",
"const",
"isMappable",
"=",
"typeof",
"items",
".",
"map",
"===",
"'function'",
";",
"const",
"itemSchema",
"=",
"Array",
".",
"isArray",
"(",
"schema",
")",
"?",
"schema",
"[",
"0",
"]",
":",
"schema",
".",
"schema",
";",
"// Handle arrayOf iterables",
"if",
"(",
"isMappable",
")",
"{",
"return",
"items",
".",
"map",
"(",
"o",
"=>",
"denormalize",
"(",
"o",
",",
"entities",
",",
"itemSchema",
",",
"bag",
")",
")",
";",
"}",
"// Handle valuesOf iterables",
"const",
"denormalized",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"items",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"denormalized",
"[",
"key",
"]",
"=",
"denormalize",
"(",
"items",
"[",
"key",
"]",
",",
"entities",
",",
"itemSchema",
",",
"bag",
")",
";",
"}",
")",
";",
"return",
"denormalized",
";",
"}"
] |
Denormalizes each entity in the given array.
@param {Array|Immutable.List} items
@param {object|Immutable.Map} entities
@param {schema.Entity} schema
@param {object} bag
@returns {Array|Immutable.List}
|
[
"Denormalizes",
"each",
"entity",
"in",
"the",
"given",
"array",
"."
] |
11baeab9e9cb058f1096196d0d4c2e42e0ef8937
|
https://github.com/gpbl/denormalizr/blob/11baeab9e9cb058f1096196d0d4c2e42e0ef8937/src/index.js#L44-L60
|
19,692
|
gpbl/denormalizr
|
src/index.js
|
denormalizeObject
|
function denormalizeObject(obj, entities, schema, bag) {
let denormalized = obj;
const schemaDefinition = typeof schema.inferSchema === 'function'
? schema.inferSchema(obj)
: (schema.schema || schema)
;
Object.keys(schemaDefinition)
// .filter(attribute => attribute.substring(0, 1) !== '_')
.filter(attribute => typeof getIn(obj, [attribute]) !== 'undefined')
.forEach((attribute) => {
const item = getIn(obj, [attribute]);
const itemSchema = getIn(schemaDefinition, [attribute]);
denormalized = setIn(denormalized, [attribute], denormalize(item, entities, itemSchema, bag));
});
return denormalized;
}
|
javascript
|
function denormalizeObject(obj, entities, schema, bag) {
let denormalized = obj;
const schemaDefinition = typeof schema.inferSchema === 'function'
? schema.inferSchema(obj)
: (schema.schema || schema)
;
Object.keys(schemaDefinition)
// .filter(attribute => attribute.substring(0, 1) !== '_')
.filter(attribute => typeof getIn(obj, [attribute]) !== 'undefined')
.forEach((attribute) => {
const item = getIn(obj, [attribute]);
const itemSchema = getIn(schemaDefinition, [attribute]);
denormalized = setIn(denormalized, [attribute], denormalize(item, entities, itemSchema, bag));
});
return denormalized;
}
|
[
"function",
"denormalizeObject",
"(",
"obj",
",",
"entities",
",",
"schema",
",",
"bag",
")",
"{",
"let",
"denormalized",
"=",
"obj",
";",
"const",
"schemaDefinition",
"=",
"typeof",
"schema",
".",
"inferSchema",
"===",
"'function'",
"?",
"schema",
".",
"inferSchema",
"(",
"obj",
")",
":",
"(",
"schema",
".",
"schema",
"||",
"schema",
")",
";",
"Object",
".",
"keys",
"(",
"schemaDefinition",
")",
"// .filter(attribute => attribute.substring(0, 1) !== '_')",
".",
"filter",
"(",
"attribute",
"=>",
"typeof",
"getIn",
"(",
"obj",
",",
"[",
"attribute",
"]",
")",
"!==",
"'undefined'",
")",
".",
"forEach",
"(",
"(",
"attribute",
")",
"=>",
"{",
"const",
"item",
"=",
"getIn",
"(",
"obj",
",",
"[",
"attribute",
"]",
")",
";",
"const",
"itemSchema",
"=",
"getIn",
"(",
"schemaDefinition",
",",
"[",
"attribute",
"]",
")",
";",
"denormalized",
"=",
"setIn",
"(",
"denormalized",
",",
"[",
"attribute",
"]",
",",
"denormalize",
"(",
"item",
",",
"entities",
",",
"itemSchema",
",",
"bag",
")",
")",
";",
"}",
")",
";",
"return",
"denormalized",
";",
"}"
] |
Takes an object and denormalizes it.
Note: For non-immutable objects, this will mutate the object. This is
necessary for handling circular dependencies. In order to not mutate the
original object, the caller should copy the object before passing it here.
@param {object|Immutable.Map} obj
@param {object|Immutable.Map} entities
@param {schema.Entity} schema
@param {object} bag
@returns {object|Immutable.Map}
|
[
"Takes",
"an",
"object",
"and",
"denormalizes",
"it",
"."
] |
11baeab9e9cb058f1096196d0d4c2e42e0ef8937
|
https://github.com/gpbl/denormalizr/blob/11baeab9e9cb058f1096196d0d4c2e42e0ef8937/src/index.js#L98-L117
|
19,693
|
gpbl/denormalizr
|
src/index.js
|
denormalizeEntity
|
function denormalizeEntity(entityOrId, entities, schema, bag) {
const key = schema.key;
const { entity, id } = resolveEntityOrId(entityOrId, entities, schema);
if (!bag.hasOwnProperty(key)) {
bag[key] = {};
}
if (!bag[key].hasOwnProperty(id)) {
// Ensure we don't mutate it non-immutable objects
const obj = isImmutable(entity) ? entity : merge({}, entity);
// Need to set this first so that if it is referenced within the call to
// denormalizeObject, it will already exist.
bag[key][id] = obj;
bag[key][id] = denormalizeObject(obj, entities, schema, bag);
}
return bag[key][id];
}
|
javascript
|
function denormalizeEntity(entityOrId, entities, schema, bag) {
const key = schema.key;
const { entity, id } = resolveEntityOrId(entityOrId, entities, schema);
if (!bag.hasOwnProperty(key)) {
bag[key] = {};
}
if (!bag[key].hasOwnProperty(id)) {
// Ensure we don't mutate it non-immutable objects
const obj = isImmutable(entity) ? entity : merge({}, entity);
// Need to set this first so that if it is referenced within the call to
// denormalizeObject, it will already exist.
bag[key][id] = obj;
bag[key][id] = denormalizeObject(obj, entities, schema, bag);
}
return bag[key][id];
}
|
[
"function",
"denormalizeEntity",
"(",
"entityOrId",
",",
"entities",
",",
"schema",
",",
"bag",
")",
"{",
"const",
"key",
"=",
"schema",
".",
"key",
";",
"const",
"{",
"entity",
",",
"id",
"}",
"=",
"resolveEntityOrId",
"(",
"entityOrId",
",",
"entities",
",",
"schema",
")",
";",
"if",
"(",
"!",
"bag",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"bag",
"[",
"key",
"]",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"bag",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"id",
")",
")",
"{",
"// Ensure we don't mutate it non-immutable objects",
"const",
"obj",
"=",
"isImmutable",
"(",
"entity",
")",
"?",
"entity",
":",
"merge",
"(",
"{",
"}",
",",
"entity",
")",
";",
"// Need to set this first so that if it is referenced within the call to",
"// denormalizeObject, it will already exist.",
"bag",
"[",
"key",
"]",
"[",
"id",
"]",
"=",
"obj",
";",
"bag",
"[",
"key",
"]",
"[",
"id",
"]",
"=",
"denormalizeObject",
"(",
"obj",
",",
"entities",
",",
"schema",
",",
"bag",
")",
";",
"}",
"return",
"bag",
"[",
"key",
"]",
"[",
"id",
"]",
";",
"}"
] |
Takes an entity, saves a reference to it in the 'bag' and then denormalizes
it. Saving the reference is necessary for circular dependencies.
@param {object|Immutable.Map|number|string} entityOrId
@param {object|Immutable.Map} entities
@param {schema.Entity} schema
@param {object} bag
@returns {object|Immutable.Map}
|
[
"Takes",
"an",
"entity",
"saves",
"a",
"reference",
"to",
"it",
"in",
"the",
"bag",
"and",
"then",
"denormalizes",
"it",
".",
"Saving",
"the",
"reference",
"is",
"necessary",
"for",
"circular",
"dependencies",
"."
] |
11baeab9e9cb058f1096196d0d4c2e42e0ef8937
|
https://github.com/gpbl/denormalizr/blob/11baeab9e9cb058f1096196d0d4c2e42e0ef8937/src/index.js#L129-L148
|
19,694
|
VividCortex/angular-recaptcha
|
release/angular-recaptcha.js
|
function (elm, conf) {
conf.sitekey = conf.key || config.key;
conf.theme = conf.theme || config.theme;
conf.stoken = conf.stoken || config.stoken;
conf.size = conf.size || config.size;
conf.type = conf.type || config.type;
conf.hl = conf.lang || config.lang;
conf.badge = conf.badge || config.badge;
if (!conf.sitekey) {
throwNoKeyException();
}
return getRecaptcha().then(function (recaptcha) {
var widgetId = recaptcha.render(elm, conf);
instances[widgetId] = elm;
return widgetId;
});
}
|
javascript
|
function (elm, conf) {
conf.sitekey = conf.key || config.key;
conf.theme = conf.theme || config.theme;
conf.stoken = conf.stoken || config.stoken;
conf.size = conf.size || config.size;
conf.type = conf.type || config.type;
conf.hl = conf.lang || config.lang;
conf.badge = conf.badge || config.badge;
if (!conf.sitekey) {
throwNoKeyException();
}
return getRecaptcha().then(function (recaptcha) {
var widgetId = recaptcha.render(elm, conf);
instances[widgetId] = elm;
return widgetId;
});
}
|
[
"function",
"(",
"elm",
",",
"conf",
")",
"{",
"conf",
".",
"sitekey",
"=",
"conf",
".",
"key",
"||",
"config",
".",
"key",
";",
"conf",
".",
"theme",
"=",
"conf",
".",
"theme",
"||",
"config",
".",
"theme",
";",
"conf",
".",
"stoken",
"=",
"conf",
".",
"stoken",
"||",
"config",
".",
"stoken",
";",
"conf",
".",
"size",
"=",
"conf",
".",
"size",
"||",
"config",
".",
"size",
";",
"conf",
".",
"type",
"=",
"conf",
".",
"type",
"||",
"config",
".",
"type",
";",
"conf",
".",
"hl",
"=",
"conf",
".",
"lang",
"||",
"config",
".",
"lang",
";",
"conf",
".",
"badge",
"=",
"conf",
".",
"badge",
"||",
"config",
".",
"badge",
";",
"if",
"(",
"!",
"conf",
".",
"sitekey",
")",
"{",
"throwNoKeyException",
"(",
")",
";",
"}",
"return",
"getRecaptcha",
"(",
")",
".",
"then",
"(",
"function",
"(",
"recaptcha",
")",
"{",
"var",
"widgetId",
"=",
"recaptcha",
".",
"render",
"(",
"elm",
",",
"conf",
")",
";",
"instances",
"[",
"widgetId",
"]",
"=",
"elm",
";",
"return",
"widgetId",
";",
"}",
")",
";",
"}"
] |
Creates a new reCaptcha object
@param elm the DOM element where to put the captcha
@param conf the captcha object configuration
@throws NoKeyException if no key is provided in the provider config or the directive instance (via attribute)
|
[
"Creates",
"a",
"new",
"reCaptcha",
"object"
] |
73d01e431d07f2fc9b84c5e62677e8ed5b41a377
|
https://github.com/VividCortex/angular-recaptcha/blob/73d01e431d07f2fc9b84c5e62677e8ed5b41a377/release/angular-recaptcha.js#L189-L207
|
|
19,695
|
jeka-kiselyov/dimeshift
|
public/scripts/app/views/dialogs/logout.js
|
function() {
App.currentUser.signOut();
App.viewStack.clear();
App.router.redirect('/');
$('#fill_profile_invitation').hide();
}
|
javascript
|
function() {
App.currentUser.signOut();
App.viewStack.clear();
App.router.redirect('/');
$('#fill_profile_invitation').hide();
}
|
[
"function",
"(",
")",
"{",
"App",
".",
"currentUser",
".",
"signOut",
"(",
")",
";",
"App",
".",
"viewStack",
".",
"clear",
"(",
")",
";",
"App",
".",
"router",
".",
"redirect",
"(",
"'/'",
")",
";",
"$",
"(",
"'#fill_profile_invitation'",
")",
".",
"hide",
"(",
")",
";",
"}"
] |
don't need template for this one, as we are not going to show it
|
[
"don",
"t",
"need",
"template",
"for",
"this",
"one",
"as",
"we",
"are",
"not",
"going",
"to",
"show",
"it"
] |
45063f370728d5cfa989d2c6b2a4e2c50bc9eec7
|
https://github.com/jeka-kiselyov/dimeshift/blob/45063f370728d5cfa989d2c6b2a4e2c50bc9eec7/public/scripts/app/views/dialogs/logout.js#L5-L10
|
|
19,696
|
jeka-kiselyov/dimeshift
|
Gruntfile.js
|
function(nodemon) {
nodemon.on('log', function(event) {
console.log(event.colour);
});
// opens browser on initial server start
nodemon.on('config:update', function() {
// Delay before server listens on port
setTimeout(function() {
require('open')('http://localhost:8080');
}, 1000);
});
// refreshes browser when server reboots
nodemon.on('restart', function() {
// Delay before server listens on port
setTimeout(function() {
require('fs').writeFileSync('.rebooted', 'rebooted');
}, 3000);
});
}
|
javascript
|
function(nodemon) {
nodemon.on('log', function(event) {
console.log(event.colour);
});
// opens browser on initial server start
nodemon.on('config:update', function() {
// Delay before server listens on port
setTimeout(function() {
require('open')('http://localhost:8080');
}, 1000);
});
// refreshes browser when server reboots
nodemon.on('restart', function() {
// Delay before server listens on port
setTimeout(function() {
require('fs').writeFileSync('.rebooted', 'rebooted');
}, 3000);
});
}
|
[
"function",
"(",
"nodemon",
")",
"{",
"nodemon",
".",
"on",
"(",
"'log'",
",",
"function",
"(",
"event",
")",
"{",
"console",
".",
"log",
"(",
"event",
".",
"colour",
")",
";",
"}",
")",
";",
"// opens browser on initial server start",
"nodemon",
".",
"on",
"(",
"'config:update'",
",",
"function",
"(",
")",
"{",
"// Delay before server listens on port",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"require",
"(",
"'open'",
")",
"(",
"'http://localhost:8080'",
")",
";",
"}",
",",
"1000",
")",
";",
"}",
")",
";",
"// refreshes browser when server reboots",
"nodemon",
".",
"on",
"(",
"'restart'",
",",
"function",
"(",
")",
"{",
"// Delay before server listens on port",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"require",
"(",
"'fs'",
")",
".",
"writeFileSync",
"(",
"'.rebooted'",
",",
"'rebooted'",
")",
";",
"}",
",",
"3000",
")",
";",
"}",
")",
";",
"}"
] |
omit this property if you aren't serving HTML files and don't want to open a browser tab on start
|
[
"omit",
"this",
"property",
"if",
"you",
"aren",
"t",
"serving",
"HTML",
"files",
"and",
"don",
"t",
"want",
"to",
"open",
"a",
"browser",
"tab",
"on",
"start"
] |
45063f370728d5cfa989d2c6b2a4e2c50bc9eec7
|
https://github.com/jeka-kiselyov/dimeshift/blob/45063f370728d5cfa989d2c6b2a4e2c50bc9eec7/Gruntfile.js#L24-L44
|
|
19,697
|
conveyal/transitive.js
|
lib/renderer/renderededge.js
|
constuctIdListString
|
function constuctIdListString (items) {
var idArr = []
forEach(items, item => {
idArr.push(item.getId())
})
idArr.sort()
return idArr.join(',')
}
|
javascript
|
function constuctIdListString (items) {
var idArr = []
forEach(items, item => {
idArr.push(item.getId())
})
idArr.sort()
return idArr.join(',')
}
|
[
"function",
"constuctIdListString",
"(",
"items",
")",
"{",
"var",
"idArr",
"=",
"[",
"]",
"forEach",
"(",
"items",
",",
"item",
"=>",
"{",
"idArr",
".",
"push",
"(",
"item",
".",
"getId",
"(",
")",
")",
"}",
")",
"idArr",
".",
"sort",
"(",
")",
"return",
"idArr",
".",
"join",
"(",
"','",
")",
"}"
] |
Helper method to construct a merged ID string from a list of items with
their own IDs
|
[
"Helper",
"method",
"to",
"construct",
"a",
"merged",
"ID",
"string",
"from",
"a",
"list",
"of",
"items",
"with",
"their",
"own",
"IDs"
] |
4ba541f40f2dcbfd77f11028da07bd3cec9f2b0b
|
https://github.com/conveyal/transitive.js/blob/4ba541f40f2dcbfd77f11028da07bd3cec9f2b0b/lib/renderer/renderededge.js#L262-L269
|
19,698
|
conveyal/transitive.js
|
lib/display/tile-layer.js
|
zoomed
|
function zoomed () {
// Get the height and width
height = el.clientHeight
width = el.clientWidth
// Set the map tile size
tile.size([width, height])
// Get the current display bounds
var bounds = display.llBounds()
// Project the bounds based on the current projection
var psw = projection(bounds[0])
var pne = projection(bounds[1])
// Based the new scale and translation vector off the current one
var scale = projection.scale() * 2 * Math.PI
var translate = projection.translate()
var dx = pne[0] - psw[0]
var dy = pne[1] - psw[1]
scale = scale * (1 / Math.max(dx / width, dy / height))
projection
.translate([width / 2, height / 2])
.scale(scale / 2 / Math.PI)
// Reproject the bounds based on the new scale and translation vector
psw = projection(bounds[0])
pne = projection(bounds[1])
var x = (psw[0] + pne[0]) / 2
var y = (psw[1] + pne[1]) / 2
translate = [width - x, height - y]
// Update the Geo tiles
tile
.scale(scale)
.translate(translate)
// Get the new set of tiles and render
renderTiles(tile())
}
|
javascript
|
function zoomed () {
// Get the height and width
height = el.clientHeight
width = el.clientWidth
// Set the map tile size
tile.size([width, height])
// Get the current display bounds
var bounds = display.llBounds()
// Project the bounds based on the current projection
var psw = projection(bounds[0])
var pne = projection(bounds[1])
// Based the new scale and translation vector off the current one
var scale = projection.scale() * 2 * Math.PI
var translate = projection.translate()
var dx = pne[0] - psw[0]
var dy = pne[1] - psw[1]
scale = scale * (1 / Math.max(dx / width, dy / height))
projection
.translate([width / 2, height / 2])
.scale(scale / 2 / Math.PI)
// Reproject the bounds based on the new scale and translation vector
psw = projection(bounds[0])
pne = projection(bounds[1])
var x = (psw[0] + pne[0]) / 2
var y = (psw[1] + pne[1]) / 2
translate = [width - x, height - y]
// Update the Geo tiles
tile
.scale(scale)
.translate(translate)
// Get the new set of tiles and render
renderTiles(tile())
}
|
[
"function",
"zoomed",
"(",
")",
"{",
"// Get the height and width",
"height",
"=",
"el",
".",
"clientHeight",
"width",
"=",
"el",
".",
"clientWidth",
"// Set the map tile size",
"tile",
".",
"size",
"(",
"[",
"width",
",",
"height",
"]",
")",
"// Get the current display bounds",
"var",
"bounds",
"=",
"display",
".",
"llBounds",
"(",
")",
"// Project the bounds based on the current projection",
"var",
"psw",
"=",
"projection",
"(",
"bounds",
"[",
"0",
"]",
")",
"var",
"pne",
"=",
"projection",
"(",
"bounds",
"[",
"1",
"]",
")",
"// Based the new scale and translation vector off the current one",
"var",
"scale",
"=",
"projection",
".",
"scale",
"(",
")",
"*",
"2",
"*",
"Math",
".",
"PI",
"var",
"translate",
"=",
"projection",
".",
"translate",
"(",
")",
"var",
"dx",
"=",
"pne",
"[",
"0",
"]",
"-",
"psw",
"[",
"0",
"]",
"var",
"dy",
"=",
"pne",
"[",
"1",
"]",
"-",
"psw",
"[",
"1",
"]",
"scale",
"=",
"scale",
"*",
"(",
"1",
"/",
"Math",
".",
"max",
"(",
"dx",
"/",
"width",
",",
"dy",
"/",
"height",
")",
")",
"projection",
".",
"translate",
"(",
"[",
"width",
"/",
"2",
",",
"height",
"/",
"2",
"]",
")",
".",
"scale",
"(",
"scale",
"/",
"2",
"/",
"Math",
".",
"PI",
")",
"// Reproject the bounds based on the new scale and translation vector",
"psw",
"=",
"projection",
"(",
"bounds",
"[",
"0",
"]",
")",
"pne",
"=",
"projection",
"(",
"bounds",
"[",
"1",
"]",
")",
"var",
"x",
"=",
"(",
"psw",
"[",
"0",
"]",
"+",
"pne",
"[",
"0",
"]",
")",
"/",
"2",
"var",
"y",
"=",
"(",
"psw",
"[",
"1",
"]",
"+",
"pne",
"[",
"1",
"]",
")",
"/",
"2",
"translate",
"=",
"[",
"width",
"-",
"x",
",",
"height",
"-",
"y",
"]",
"// Update the Geo tiles",
"tile",
".",
"scale",
"(",
"scale",
")",
".",
"translate",
"(",
"translate",
")",
"// Get the new set of tiles and render",
"renderTiles",
"(",
"tile",
"(",
")",
")",
"}"
] |
Reload tiles on pan and zoom
|
[
"Reload",
"tiles",
"on",
"pan",
"and",
"zoom"
] |
4ba541f40f2dcbfd77f11028da07bd3cec9f2b0b
|
https://github.com/conveyal/transitive.js/blob/4ba541f40f2dcbfd77f11028da07bd3cec9f2b0b/lib/display/tile-layer.js#L41-L82
|
19,699
|
conveyal/transitive.js
|
lib/display/tile-layer.js
|
matrix3d
|
function matrix3d (scale, translate) {
var k = scale / 256
var r = scale % 1 ? Number : Math.round
return 'matrix3d(' + [k, 0, 0, 0, 0, k, 0, 0, 0, 0, k, 0, r(translate[0] *
scale), r(translate[1] * scale), 0, 1] + ')'
}
|
javascript
|
function matrix3d (scale, translate) {
var k = scale / 256
var r = scale % 1 ? Number : Math.round
return 'matrix3d(' + [k, 0, 0, 0, 0, k, 0, 0, 0, 0, k, 0, r(translate[0] *
scale), r(translate[1] * scale), 0, 1] + ')'
}
|
[
"function",
"matrix3d",
"(",
"scale",
",",
"translate",
")",
"{",
"var",
"k",
"=",
"scale",
"/",
"256",
"var",
"r",
"=",
"scale",
"%",
"1",
"?",
"Number",
":",
"Math",
".",
"round",
"return",
"'matrix3d('",
"+",
"[",
"k",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"k",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"k",
",",
"0",
",",
"r",
"(",
"translate",
"[",
"0",
"]",
"*",
"scale",
")",
",",
"r",
"(",
"translate",
"[",
"1",
"]",
"*",
"scale",
")",
",",
"0",
",",
"1",
"]",
"+",
"')'",
"}"
] |
Get the 3D Transform Matrix
|
[
"Get",
"the",
"3D",
"Transform",
"Matrix"
] |
4ba541f40f2dcbfd77f11028da07bd3cec9f2b0b
|
https://github.com/conveyal/transitive.js/blob/4ba541f40f2dcbfd77f11028da07bd3cec9f2b0b/lib/display/tile-layer.js#L116-L121
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.