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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
13,300
|
socketstream/socketstream
|
lib/websocket/event_dispatcher.js
|
sendToMultiple
|
function sendToMultiple(send, msg, destinations, type) {
destinations = destinations instanceof Array && destinations || [destinations];
destinations.forEach(function(destination) {
var set, socketIds;
set = subscriptions[type];
if ((socketIds = set.members(destination))) {
return socketIds.slice(0).forEach(function(socketId) {
if (!send.socketId(socketId, msg, destination)) {
return set.removeFromAll(socketId);
}
});
}
});
return true;
}
|
javascript
|
function sendToMultiple(send, msg, destinations, type) {
destinations = destinations instanceof Array && destinations || [destinations];
destinations.forEach(function(destination) {
var set, socketIds;
set = subscriptions[type];
if ((socketIds = set.members(destination))) {
return socketIds.slice(0).forEach(function(socketId) {
if (!send.socketId(socketId, msg, destination)) {
return set.removeFromAll(socketId);
}
});
}
});
return true;
}
|
[
"function",
"sendToMultiple",
"(",
"send",
",",
"msg",
",",
"destinations",
",",
"type",
")",
"{",
"destinations",
"=",
"destinations",
"instanceof",
"Array",
"&&",
"destinations",
"||",
"[",
"destinations",
"]",
";",
"destinations",
".",
"forEach",
"(",
"function",
"(",
"destination",
")",
"{",
"var",
"set",
",",
"socketIds",
";",
"set",
"=",
"subscriptions",
"[",
"type",
"]",
";",
"if",
"(",
"(",
"socketIds",
"=",
"set",
".",
"members",
"(",
"destination",
")",
")",
")",
"{",
"return",
"socketIds",
".",
"slice",
"(",
"0",
")",
".",
"forEach",
"(",
"function",
"(",
"socketId",
")",
"{",
"if",
"(",
"!",
"send",
".",
"socketId",
"(",
"socketId",
",",
"msg",
",",
"destination",
")",
")",
"{",
"return",
"set",
".",
"removeFromAll",
"(",
"socketId",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"true",
";",
"}"
] |
Private Attempt to send the event to the socket. If socket no longer exists, remove it from set
|
[
"Private",
"Attempt",
"to",
"send",
"the",
"event",
"to",
"the",
"socket",
".",
"If",
"socket",
"no",
"longer",
"exists",
"remove",
"it",
"from",
"set"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/websocket/event_dispatcher.js#L42-L56
|
13,301
|
socketstream/socketstream
|
lib/tasks/index.js
|
function(all) {
var tasks = all? ['load-api']:['pack-prepare','load-api'];
ss.bundler.forEach(function(bundler){
if (all) {
tasks.push(bundler.client.name + ':pack');
} else if (bundler.packNeeded) {
tasks.push(bundler.client.name + ':pack-needed');
tasks.push(bundler.client.name + ':pack');
} else {
tasks.push(bundler.client.name + ':pack-unneeded');
}
});
return tasks;
}
|
javascript
|
function(all) {
var tasks = all? ['load-api']:['pack-prepare','load-api'];
ss.bundler.forEach(function(bundler){
if (all) {
tasks.push(bundler.client.name + ':pack');
} else if (bundler.packNeeded) {
tasks.push(bundler.client.name + ':pack-needed');
tasks.push(bundler.client.name + ':pack');
} else {
tasks.push(bundler.client.name + ':pack-unneeded');
}
});
return tasks;
}
|
[
"function",
"(",
"all",
")",
"{",
"var",
"tasks",
"=",
"all",
"?",
"[",
"'load-api'",
"]",
":",
"[",
"'pack-prepare'",
",",
"'load-api'",
"]",
";",
"ss",
".",
"bundler",
".",
"forEach",
"(",
"function",
"(",
"bundler",
")",
"{",
"if",
"(",
"all",
")",
"{",
"tasks",
".",
"push",
"(",
"bundler",
".",
"client",
".",
"name",
"+",
"':pack'",
")",
";",
"}",
"else",
"if",
"(",
"bundler",
".",
"packNeeded",
")",
"{",
"tasks",
".",
"push",
"(",
"bundler",
".",
"client",
".",
"name",
"+",
"':pack-needed'",
")",
";",
"tasks",
".",
"push",
"(",
"bundler",
".",
"client",
".",
"name",
"+",
"':pack'",
")",
";",
"}",
"else",
"{",
"tasks",
".",
"push",
"(",
"bundler",
".",
"client",
".",
"name",
"+",
"':pack-unneeded'",
")",
";",
"}",
"}",
")",
";",
"return",
"tasks",
";",
"}"
] |
this is mostly for testing
|
[
"this",
"is",
"mostly",
"for",
"testing"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/tasks/index.js#L52-L65
|
|
13,302
|
socketstream/socketstream
|
lib/client/template_engine.js
|
suggestedId
|
function suggestedId(pth, templatesPath) {
if (pth.indexOf(templatesPath) === 0) {
pth = pth.substring(templatesPath.length + 1);
}
var sp;
sp = pth.split('.');
if (pth.indexOf('.') > 0) {
sp.pop();
}
return sp.join('.').replace(/\//g, '-');
}
|
javascript
|
function suggestedId(pth, templatesPath) {
if (pth.indexOf(templatesPath) === 0) {
pth = pth.substring(templatesPath.length + 1);
}
var sp;
sp = pth.split('.');
if (pth.indexOf('.') > 0) {
sp.pop();
}
return sp.join('.').replace(/\//g, '-');
}
|
[
"function",
"suggestedId",
"(",
"pth",
",",
"templatesPath",
")",
"{",
"if",
"(",
"pth",
".",
"indexOf",
"(",
"templatesPath",
")",
"===",
"0",
")",
"{",
"pth",
"=",
"pth",
".",
"substring",
"(",
"templatesPath",
".",
"length",
"+",
"1",
")",
";",
"}",
"var",
"sp",
";",
"sp",
"=",
"pth",
".",
"split",
"(",
"'.'",
")",
";",
"if",
"(",
"pth",
".",
"indexOf",
"(",
"'.'",
")",
">",
"0",
")",
"{",
"sp",
".",
"pop",
"(",
")",
";",
"}",
"return",
"sp",
".",
"join",
"(",
"'.'",
")",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'-'",
")",
";",
"}"
] |
This should be on the bundler entries, so it can be tweaked by bundler before being used by the engine Suggest an ID for this template based upon its path 3rd party Template Engine modules are free to use their own naming conventions but we recommend using this where possible
|
[
"This",
"should",
"be",
"on",
"the",
"bundler",
"entries",
"so",
"it",
"can",
"be",
"tweaked",
"by",
"bundler",
"before",
"being",
"used",
"by",
"the",
"engine",
"Suggest",
"an",
"ID",
"for",
"this",
"template",
"based",
"upon",
"its",
"path",
"3rd",
"party",
"Template",
"Engine",
"modules",
"are",
"free",
"to",
"use",
"their",
"own",
"naming",
"conventions",
"but",
"we",
"recommend",
"using",
"this",
"where",
"possible"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/client/template_engine.js#L203-L213
|
13,303
|
socketstream/socketstream
|
lib/client/index.js
|
onChange
|
function onChange(changedPath, event) {
var _ref = path.extname(changedPath),
action = cssExtensions.indexOf(_ref) >= 0 ? 'updateCSS' : 'reload';
//first change is with delayTime delay , thereafter only once there has been no further changes for guardTime seconds
//validate the change
if (customOnChange.validate) {
if (!customOnChange.validate(changedPath, event,action)) { return ;} //ignore changes if the app says-so
}
//avoid multiple rapid changes
var delay=delayTime;
if (lastRun[action].guardTime) { clearTimeout(lastRun[action].guardTime); delay=guardTime;}
if (lastRun[action].delayTime) { clearTimeout(lastRun[action].delayTime); delay=delayTime;}
lastRun[action].delayTime = setTimeout(function(){
onChangeFiltered(changedPath, event, action);
lastRun[action].guardTime = setTimeout(function(){
lastRun[action].guardTime=null;
}, delay);
lastRun[action].delayTime=null;
}, delay);
return Date.now();
}
|
javascript
|
function onChange(changedPath, event) {
var _ref = path.extname(changedPath),
action = cssExtensions.indexOf(_ref) >= 0 ? 'updateCSS' : 'reload';
//first change is with delayTime delay , thereafter only once there has been no further changes for guardTime seconds
//validate the change
if (customOnChange.validate) {
if (!customOnChange.validate(changedPath, event,action)) { return ;} //ignore changes if the app says-so
}
//avoid multiple rapid changes
var delay=delayTime;
if (lastRun[action].guardTime) { clearTimeout(lastRun[action].guardTime); delay=guardTime;}
if (lastRun[action].delayTime) { clearTimeout(lastRun[action].delayTime); delay=delayTime;}
lastRun[action].delayTime = setTimeout(function(){
onChangeFiltered(changedPath, event, action);
lastRun[action].guardTime = setTimeout(function(){
lastRun[action].guardTime=null;
}, delay);
lastRun[action].delayTime=null;
}, delay);
return Date.now();
}
|
[
"function",
"onChange",
"(",
"changedPath",
",",
"event",
")",
"{",
"var",
"_ref",
"=",
"path",
".",
"extname",
"(",
"changedPath",
")",
",",
"action",
"=",
"cssExtensions",
".",
"indexOf",
"(",
"_ref",
")",
">=",
"0",
"?",
"'updateCSS'",
":",
"'reload'",
";",
"//first change is with delayTime delay , thereafter only once there has been no further changes for guardTime seconds",
"//validate the change",
"if",
"(",
"customOnChange",
".",
"validate",
")",
"{",
"if",
"(",
"!",
"customOnChange",
".",
"validate",
"(",
"changedPath",
",",
"event",
",",
"action",
")",
")",
"{",
"return",
";",
"}",
"//ignore changes if the app says-so",
"}",
"//avoid multiple rapid changes",
"var",
"delay",
"=",
"delayTime",
";",
"if",
"(",
"lastRun",
"[",
"action",
"]",
".",
"guardTime",
")",
"{",
"clearTimeout",
"(",
"lastRun",
"[",
"action",
"]",
".",
"guardTime",
")",
";",
"delay",
"=",
"guardTime",
";",
"}",
"if",
"(",
"lastRun",
"[",
"action",
"]",
".",
"delayTime",
")",
"{",
"clearTimeout",
"(",
"lastRun",
"[",
"action",
"]",
".",
"delayTime",
")",
";",
"delay",
"=",
"delayTime",
";",
"}",
"lastRun",
"[",
"action",
"]",
".",
"delayTime",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"onChangeFiltered",
"(",
"changedPath",
",",
"event",
",",
"action",
")",
";",
"lastRun",
"[",
"action",
"]",
".",
"guardTime",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"lastRun",
"[",
"action",
"]",
".",
"guardTime",
"=",
"null",
";",
"}",
",",
"delay",
")",
";",
"lastRun",
"[",
"action",
"]",
".",
"delayTime",
"=",
"null",
";",
"}",
",",
"delay",
")",
";",
"return",
"Date",
".",
"now",
"(",
")",
";",
"}"
] |
reload the browser
|
[
"reload",
"the",
"browser"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/client/index.js#L108-L131
|
13,304
|
socketstream/socketstream
|
lib/client/index.js
|
function(newOption) {
var k, v, y, _results;
if (typeof newOption !== 'object') {
throw new Error('ss.client.set() takes an object e.g. {liveReload: false}');
}
_results = [];
for (k in newOption) {
if (newOption.hasOwnProperty(k)) {
v = newOption[k];
if (v instanceof Object) {
//jshint -W083
_results.push((function() {
var _results1, x;
_results1 = [];
for (x in v) {
if (v.hasOwnProperty(x)) {
y = v[x];
if (!options[k]) {
options[k]= {};
}
_results1.push(options[k][x] = y);
}
}
return _results1;
})());
} else {
_results.push(options[k] = v);
}
}
}
return _results;
}
|
javascript
|
function(newOption) {
var k, v, y, _results;
if (typeof newOption !== 'object') {
throw new Error('ss.client.set() takes an object e.g. {liveReload: false}');
}
_results = [];
for (k in newOption) {
if (newOption.hasOwnProperty(k)) {
v = newOption[k];
if (v instanceof Object) {
//jshint -W083
_results.push((function() {
var _results1, x;
_results1 = [];
for (x in v) {
if (v.hasOwnProperty(x)) {
y = v[x];
if (!options[k]) {
options[k]= {};
}
_results1.push(options[k][x] = y);
}
}
return _results1;
})());
} else {
_results.push(options[k] = v);
}
}
}
return _results;
}
|
[
"function",
"(",
"newOption",
")",
"{",
"var",
"k",
",",
"v",
",",
"y",
",",
"_results",
";",
"if",
"(",
"typeof",
"newOption",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'ss.client.set() takes an object e.g. {liveReload: false}'",
")",
";",
"}",
"_results",
"=",
"[",
"]",
";",
"for",
"(",
"k",
"in",
"newOption",
")",
"{",
"if",
"(",
"newOption",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"{",
"v",
"=",
"newOption",
"[",
"k",
"]",
";",
"if",
"(",
"v",
"instanceof",
"Object",
")",
"{",
"//jshint -W083",
"_results",
".",
"push",
"(",
"(",
"function",
"(",
")",
"{",
"var",
"_results1",
",",
"x",
";",
"_results1",
"=",
"[",
"]",
";",
"for",
"(",
"x",
"in",
"v",
")",
"{",
"if",
"(",
"v",
".",
"hasOwnProperty",
"(",
"x",
")",
")",
"{",
"y",
"=",
"v",
"[",
"x",
"]",
";",
"if",
"(",
"!",
"options",
"[",
"k",
"]",
")",
"{",
"options",
"[",
"k",
"]",
"=",
"{",
"}",
";",
"}",
"_results1",
".",
"push",
"(",
"options",
"[",
"k",
"]",
"[",
"x",
"]",
"=",
"y",
")",
";",
"}",
"}",
"return",
"_results1",
";",
"}",
")",
"(",
")",
")",
";",
"}",
"else",
"{",
"_results",
".",
"push",
"(",
"options",
"[",
"k",
"]",
"=",
"v",
")",
";",
"}",
"}",
"}",
"return",
"_results",
";",
"}"
] |
Merge optional options
|
[
"Merge",
"optional",
"options"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/client/index.js#L206-L239
|
|
13,305
|
socketstream/socketstream
|
lib/client/index.js
|
function(opts) {
if (opts && typeof opts !== 'object') {
throw new Error('Options passed to ss.client.packAssets() must be an object');
}
options.packedAssets = opts || true;
options.servePacked = opts || true;
options.liveReload = false;
// As it's safe to assume we're running in production mode at this point, if your app is not catching uncaught
// errors with its own custom error handling code, step in and prevent any exceptions from taking the server down
if (options.packedAssets && process.listeners('uncaughtException').length === 0) {
return process.on('uncaughtException', function(err) {
log.error('Uncaught Exception!'.red);
return log.error(err.stack);
});
}
}
|
javascript
|
function(opts) {
if (opts && typeof opts !== 'object') {
throw new Error('Options passed to ss.client.packAssets() must be an object');
}
options.packedAssets = opts || true;
options.servePacked = opts || true;
options.liveReload = false;
// As it's safe to assume we're running in production mode at this point, if your app is not catching uncaught
// errors with its own custom error handling code, step in and prevent any exceptions from taking the server down
if (options.packedAssets && process.listeners('uncaughtException').length === 0) {
return process.on('uncaughtException', function(err) {
log.error('Uncaught Exception!'.red);
return log.error(err.stack);
});
}
}
|
[
"function",
"(",
"opts",
")",
"{",
"if",
"(",
"opts",
"&&",
"typeof",
"opts",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Options passed to ss.client.packAssets() must be an object'",
")",
";",
"}",
"options",
".",
"packedAssets",
"=",
"opts",
"||",
"true",
";",
"options",
".",
"servePacked",
"=",
"opts",
"||",
"true",
";",
"options",
".",
"liveReload",
"=",
"false",
";",
"// As it's safe to assume we're running in production mode at this point, if your app is not catching uncaught",
"// errors with its own custom error handling code, step in and prevent any exceptions from taking the server down",
"if",
"(",
"options",
".",
"packedAssets",
"&&",
"process",
".",
"listeners",
"(",
"'uncaughtException'",
")",
".",
"length",
"===",
"0",
")",
"{",
"return",
"process",
".",
"on",
"(",
"'uncaughtException'",
",",
"function",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"'Uncaught Exception!'",
".",
"red",
")",
";",
"return",
"log",
".",
"error",
"(",
"err",
".",
"stack",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Tell the asset manager to pack and minimise all assets
|
[
"Tell",
"the",
"asset",
"manager",
"to",
"pack",
"and",
"minimise",
"all",
"assets"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/client/index.js#L250-L266
|
|
13,306
|
socketstream/socketstream
|
lib/client/index.js
|
function() {
ss.http.cached.loadStatic();
ss.http.cached.loadAssets();
ss.bundler.updateCachedOndemandAssets();
ss.bundler.forEach(function(bundler) {
bundler.updateCachedDevAssets();
});
}
|
javascript
|
function() {
ss.http.cached.loadStatic();
ss.http.cached.loadAssets();
ss.bundler.updateCachedOndemandAssets();
ss.bundler.forEach(function(bundler) {
bundler.updateCachedDevAssets();
});
}
|
[
"function",
"(",
")",
"{",
"ss",
".",
"http",
".",
"cached",
".",
"loadStatic",
"(",
")",
";",
"ss",
".",
"http",
".",
"cached",
".",
"loadAssets",
"(",
")",
";",
"ss",
".",
"bundler",
".",
"updateCachedOndemandAssets",
"(",
")",
";",
"ss",
".",
"bundler",
".",
"forEach",
"(",
"function",
"(",
"bundler",
")",
"{",
"bundler",
".",
"updateCachedDevAssets",
"(",
")",
";",
"}",
")",
";",
"}"
] |
experimental interface to reload cache of contents for all clients
|
[
"experimental",
"interface",
"to",
"reload",
"cache",
"of",
"contents",
"for",
"all",
"clients"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/client/index.js#L333-L341
|
|
13,307
|
socketstream/socketstream
|
lib/client/index.js
|
function() {
if (options.servePacked) {
ss.bundler.forEach(function(bundler) {
bundler.useLatestsPackedId();
});
}
ss.bundler.load();
//TODO convert options.dirs to relative paths stripping the lead '/' if present
// Cache instances of code formatters and template engines here
// This may change in the future as I don't like hanging system objects
// on the 'ss' internal API object, but for now it solves a problem
// we were having when repl.start() would erase vars cached inside a module
ss.client.formatters = this.formatters.load();
ss.client.templateEngines = this.templateEngine.load();
}
|
javascript
|
function() {
if (options.servePacked) {
ss.bundler.forEach(function(bundler) {
bundler.useLatestsPackedId();
});
}
ss.bundler.load();
//TODO convert options.dirs to relative paths stripping the lead '/' if present
// Cache instances of code formatters and template engines here
// This may change in the future as I don't like hanging system objects
// on the 'ss' internal API object, but for now it solves a problem
// we were having when repl.start() would erase vars cached inside a module
ss.client.formatters = this.formatters.load();
ss.client.templateEngines = this.templateEngine.load();
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"options",
".",
"servePacked",
")",
"{",
"ss",
".",
"bundler",
".",
"forEach",
"(",
"function",
"(",
"bundler",
")",
"{",
"bundler",
".",
"useLatestsPackedId",
"(",
")",
";",
"}",
")",
";",
"}",
"ss",
".",
"bundler",
".",
"load",
"(",
")",
";",
"//TODO convert options.dirs to relative paths stripping the lead '/' if present",
"// Cache instances of code formatters and template engines here",
"// This may change in the future as I don't like hanging system objects",
"// on the 'ss' internal API object, but for now it solves a problem",
"// we were having when repl.start() would erase vars cached inside a module",
"ss",
".",
"client",
".",
"formatters",
"=",
"this",
".",
"formatters",
".",
"load",
"(",
")",
";",
"ss",
".",
"client",
".",
"templateEngines",
"=",
"this",
".",
"templateEngine",
".",
"load",
"(",
")",
";",
"}"
] |
Listen and serve incoming asset requests
|
[
"Listen",
"and",
"serve",
"incoming",
"asset",
"requests"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/client/index.js#L359-L374
|
|
13,308
|
socketstream/socketstream
|
lib/websocket/transports/engineio/index.js
|
function(msg) {
for (var id in openSocketsById) {
if (openSocketsById.hasOwnProperty(id)) {
openSocketsById[id].send('0|' + msg + '|null');
}
}
}
|
javascript
|
function(msg) {
for (var id in openSocketsById) {
if (openSocketsById.hasOwnProperty(id)) {
openSocketsById[id].send('0|' + msg + '|null');
}
}
}
|
[
"function",
"(",
"msg",
")",
"{",
"for",
"(",
"var",
"id",
"in",
"openSocketsById",
")",
"{",
"if",
"(",
"openSocketsById",
".",
"hasOwnProperty",
"(",
"id",
")",
")",
"{",
"openSocketsById",
"[",
"id",
"]",
".",
"send",
"(",
"'0|'",
"+",
"msg",
"+",
"'|null'",
")",
";",
"}",
"}",
"}"
] |
Send the same message to every open socket
|
[
"Send",
"the",
"same",
"message",
"to",
"every",
"open",
"socket"
] |
bc783da043de558ee3ff9032ea15b9b8113a8659
|
https://github.com/socketstream/socketstream/blob/bc783da043de558ee3ff9032ea15b9b8113a8659/lib/websocket/transports/engineio/index.js#L136-L142
|
|
13,309
|
kazupon/vue-validator
|
dist/vue-validator.common.js
|
pattern
|
function pattern (val, pat) {
if (typeof pat !== 'string') { return false }
var match = pat.match(new RegExp('^/(.*?)/([gimy]*)$'));
if (!match) { return false }
return new RegExp(match[1], match[2]).test(val)
}
|
javascript
|
function pattern (val, pat) {
if (typeof pat !== 'string') { return false }
var match = pat.match(new RegExp('^/(.*?)/([gimy]*)$'));
if (!match) { return false }
return new RegExp(match[1], match[2]).test(val)
}
|
[
"function",
"pattern",
"(",
"val",
",",
"pat",
")",
"{",
"if",
"(",
"typeof",
"pat",
"!==",
"'string'",
")",
"{",
"return",
"false",
"}",
"var",
"match",
"=",
"pat",
".",
"match",
"(",
"new",
"RegExp",
"(",
"'^/(.*?)/([gimy]*)$'",
")",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"false",
"}",
"return",
"new",
"RegExp",
"(",
"match",
"[",
"1",
"]",
",",
"match",
"[",
"2",
"]",
")",
".",
"test",
"(",
"val",
")",
"}"
] |
pattern
This function validate whether the value matches the regex pattern
|
[
"pattern",
"This",
"function",
"validate",
"whether",
"the",
"value",
"matches",
"the",
"regex",
"pattern"
] |
a88304a5c71cb3273341678ae48b030dc71c5956
|
https://github.com/kazupon/vue-validator/blob/a88304a5c71cb3273341678ae48b030dc71c5956/dist/vue-validator.common.js#L80-L87
|
13,310
|
kazupon/vue-validator
|
dist/vue-validator.common.js
|
minlength
|
function minlength (val, min) {
if (typeof val === 'string') {
return isInteger(min, 10) && val.length >= parseInt(min, 10)
} else if (Array.isArray(val)) {
return val.length >= parseInt(min, 10)
} else {
return false
}
}
|
javascript
|
function minlength (val, min) {
if (typeof val === 'string') {
return isInteger(min, 10) && val.length >= parseInt(min, 10)
} else if (Array.isArray(val)) {
return val.length >= parseInt(min, 10)
} else {
return false
}
}
|
[
"function",
"minlength",
"(",
"val",
",",
"min",
")",
"{",
"if",
"(",
"typeof",
"val",
"===",
"'string'",
")",
"{",
"return",
"isInteger",
"(",
"min",
",",
"10",
")",
"&&",
"val",
".",
"length",
">=",
"parseInt",
"(",
"min",
",",
"10",
")",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"return",
"val",
".",
"length",
">=",
"parseInt",
"(",
"min",
",",
"10",
")",
"}",
"else",
"{",
"return",
"false",
"}",
"}"
] |
minlength
This function validate whether the minimum length.
|
[
"minlength",
"This",
"function",
"validate",
"whether",
"the",
"minimum",
"length",
"."
] |
a88304a5c71cb3273341678ae48b030dc71c5956
|
https://github.com/kazupon/vue-validator/blob/a88304a5c71cb3273341678ae48b030dc71c5956/dist/vue-validator.common.js#L93-L101
|
13,311
|
kazupon/vue-validator
|
dist/vue-validator.common.js
|
maxlength
|
function maxlength (val, max) {
if (typeof val === 'string') {
return isInteger(max, 10) && val.length <= parseInt(max, 10)
} else if (Array.isArray(val)) {
return val.length <= parseInt(max, 10)
} else {
return false
}
}
|
javascript
|
function maxlength (val, max) {
if (typeof val === 'string') {
return isInteger(max, 10) && val.length <= parseInt(max, 10)
} else if (Array.isArray(val)) {
return val.length <= parseInt(max, 10)
} else {
return false
}
}
|
[
"function",
"maxlength",
"(",
"val",
",",
"max",
")",
"{",
"if",
"(",
"typeof",
"val",
"===",
"'string'",
")",
"{",
"return",
"isInteger",
"(",
"max",
",",
"10",
")",
"&&",
"val",
".",
"length",
"<=",
"parseInt",
"(",
"max",
",",
"10",
")",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"return",
"val",
".",
"length",
"<=",
"parseInt",
"(",
"max",
",",
"10",
")",
"}",
"else",
"{",
"return",
"false",
"}",
"}"
] |
maxlength
This function validate whether the maximum length.
|
[
"maxlength",
"This",
"function",
"validate",
"whether",
"the",
"maximum",
"length",
"."
] |
a88304a5c71cb3273341678ae48b030dc71c5956
|
https://github.com/kazupon/vue-validator/blob/a88304a5c71cb3273341678ae48b030dc71c5956/dist/vue-validator.common.js#L107-L115
|
13,312
|
kazupon/vue-validator
|
dist/vue-validator.common.js
|
validator
|
function validator (
id,
def
) {
if (def === undefined) {
return Vue.options['validators'][id]
} else {
Vue.options['validators'][id] = def;
if (def === null) {
delete Vue.options['validators']['id'];
}
}
}
|
javascript
|
function validator (
id,
def
) {
if (def === undefined) {
return Vue.options['validators'][id]
} else {
Vue.options['validators'][id] = def;
if (def === null) {
delete Vue.options['validators']['id'];
}
}
}
|
[
"function",
"validator",
"(",
"id",
",",
"def",
")",
"{",
"if",
"(",
"def",
"===",
"undefined",
")",
"{",
"return",
"Vue",
".",
"options",
"[",
"'validators'",
"]",
"[",
"id",
"]",
"}",
"else",
"{",
"Vue",
".",
"options",
"[",
"'validators'",
"]",
"[",
"id",
"]",
"=",
"def",
";",
"if",
"(",
"def",
"===",
"null",
")",
"{",
"delete",
"Vue",
".",
"options",
"[",
"'validators'",
"]",
"[",
"'id'",
"]",
";",
"}",
"}",
"}"
] |
Register or retrieve a global validator definition.
|
[
"Register",
"or",
"retrieve",
"a",
"global",
"validator",
"definition",
"."
] |
a88304a5c71cb3273341678ae48b030dc71c5956
|
https://github.com/kazupon/vue-validator/blob/a88304a5c71cb3273341678ae48b030dc71c5956/dist/vue-validator.common.js#L180-L192
|
13,313
|
RuntimeTools/appmetrics
|
probes/oracle-probe.js
|
addMonitoring
|
function addMonitoring(connection, probe) {
aspect.around(
connection,
'execute',
function(target, methodName, args, probeData) {
// Start the monitoring for the 'execute' method
probe.metricsProbeStart(probeData, methodName, args);
probe.requestProbeStart(probeData, methodName, args);
// Advise the callback for 'execute'. Will do nothing if no callback is registered
aspect.aroundCallback(args, probeData, function(target, callbackArgs, probeData) {
// 'execute' has completed and the callback has been called, so end the monitoring
// Call the transaction link with a name and the callback for strong trace
var callbackPosition = aspect.findCallbackArg(args);
if (typeof callbackPosition != 'undefined') {
aspect.strongTraceTransactionLink('oracle: ', methodName, args[callbackPosition]);
}
probe.metricsProbeEnd(probeData, methodName, args);
probe.requestProbeEnd(probeData, methodName, args);
});
},
function(target, methodName, args, probeData, rc) {
// If no callback used then end the monitoring after returning from the 'execute' method instead
if (aspect.findCallbackArg(args) == undefined) {
probe.metricsProbeEnd(probeData, methodName, args);
probe.requestProbeEnd(probeData, methodName, args);
}
return rc;
}
);
}
|
javascript
|
function addMonitoring(connection, probe) {
aspect.around(
connection,
'execute',
function(target, methodName, args, probeData) {
// Start the monitoring for the 'execute' method
probe.metricsProbeStart(probeData, methodName, args);
probe.requestProbeStart(probeData, methodName, args);
// Advise the callback for 'execute'. Will do nothing if no callback is registered
aspect.aroundCallback(args, probeData, function(target, callbackArgs, probeData) {
// 'execute' has completed and the callback has been called, so end the monitoring
// Call the transaction link with a name and the callback for strong trace
var callbackPosition = aspect.findCallbackArg(args);
if (typeof callbackPosition != 'undefined') {
aspect.strongTraceTransactionLink('oracle: ', methodName, args[callbackPosition]);
}
probe.metricsProbeEnd(probeData, methodName, args);
probe.requestProbeEnd(probeData, methodName, args);
});
},
function(target, methodName, args, probeData, rc) {
// If no callback used then end the monitoring after returning from the 'execute' method instead
if (aspect.findCallbackArg(args) == undefined) {
probe.metricsProbeEnd(probeData, methodName, args);
probe.requestProbeEnd(probeData, methodName, args);
}
return rc;
}
);
}
|
[
"function",
"addMonitoring",
"(",
"connection",
",",
"probe",
")",
"{",
"aspect",
".",
"around",
"(",
"connection",
",",
"'execute'",
",",
"function",
"(",
"target",
",",
"methodName",
",",
"args",
",",
"probeData",
")",
"{",
"// Start the monitoring for the 'execute' method",
"probe",
".",
"metricsProbeStart",
"(",
"probeData",
",",
"methodName",
",",
"args",
")",
";",
"probe",
".",
"requestProbeStart",
"(",
"probeData",
",",
"methodName",
",",
"args",
")",
";",
"// Advise the callback for 'execute'. Will do nothing if no callback is registered",
"aspect",
".",
"aroundCallback",
"(",
"args",
",",
"probeData",
",",
"function",
"(",
"target",
",",
"callbackArgs",
",",
"probeData",
")",
"{",
"// 'execute' has completed and the callback has been called, so end the monitoring",
"// Call the transaction link with a name and the callback for strong trace",
"var",
"callbackPosition",
"=",
"aspect",
".",
"findCallbackArg",
"(",
"args",
")",
";",
"if",
"(",
"typeof",
"callbackPosition",
"!=",
"'undefined'",
")",
"{",
"aspect",
".",
"strongTraceTransactionLink",
"(",
"'oracle: '",
",",
"methodName",
",",
"args",
"[",
"callbackPosition",
"]",
")",
";",
"}",
"probe",
".",
"metricsProbeEnd",
"(",
"probeData",
",",
"methodName",
",",
"args",
")",
";",
"probe",
".",
"requestProbeEnd",
"(",
"probeData",
",",
"methodName",
",",
"args",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"target",
",",
"methodName",
",",
"args",
",",
"probeData",
",",
"rc",
")",
"{",
"// If no callback used then end the monitoring after returning from the 'execute' method instead",
"if",
"(",
"aspect",
".",
"findCallbackArg",
"(",
"args",
")",
"==",
"undefined",
")",
"{",
"probe",
".",
"metricsProbeEnd",
"(",
"probeData",
",",
"methodName",
",",
"args",
")",
";",
"probe",
".",
"requestProbeEnd",
"(",
"probeData",
",",
"methodName",
",",
"args",
")",
";",
"}",
"return",
"rc",
";",
"}",
")",
";",
"}"
] |
Monitor the 'execute' method on a connection or prepared statement
|
[
"Monitor",
"the",
"execute",
"method",
"on",
"a",
"connection",
"or",
"prepared",
"statement"
] |
cdcb907b9d57f9531986cc87b454813d621f59f0
|
https://github.com/RuntimeTools/appmetrics/blob/cdcb907b9d57f9531986cc87b454813d621f59f0/probes/oracle-probe.js#L59-L90
|
13,314
|
RuntimeTools/appmetrics
|
probes/https-outbound-probe.js
|
function(target, methodName, methodArgs, probeData, rc) {
// If no callback has been used then end the metrics after returning from the method instead
if (aspect.findCallbackArg(methodArgs) === undefined) {
// Need to get request method and URL again
var ri = getRequestItems(methodArgs[0]);
// End metrics (no response available so pass empty object)
that.metricsProbeEnd(probeData, ri.requestMethod, ri.urlRequested, {}, ri.headers);
that.requestProbeEnd(probeData, ri.requestMethod, ri.urlRequested, {}, ri.headers);
}
return rc;
}
|
javascript
|
function(target, methodName, methodArgs, probeData, rc) {
// If no callback has been used then end the metrics after returning from the method instead
if (aspect.findCallbackArg(methodArgs) === undefined) {
// Need to get request method and URL again
var ri = getRequestItems(methodArgs[0]);
// End metrics (no response available so pass empty object)
that.metricsProbeEnd(probeData, ri.requestMethod, ri.urlRequested, {}, ri.headers);
that.requestProbeEnd(probeData, ri.requestMethod, ri.urlRequested, {}, ri.headers);
}
return rc;
}
|
[
"function",
"(",
"target",
",",
"methodName",
",",
"methodArgs",
",",
"probeData",
",",
"rc",
")",
"{",
"// If no callback has been used then end the metrics after returning from the method instead",
"if",
"(",
"aspect",
".",
"findCallbackArg",
"(",
"methodArgs",
")",
"===",
"undefined",
")",
"{",
"// Need to get request method and URL again",
"var",
"ri",
"=",
"getRequestItems",
"(",
"methodArgs",
"[",
"0",
"]",
")",
";",
"// End metrics (no response available so pass empty object)",
"that",
".",
"metricsProbeEnd",
"(",
"probeData",
",",
"ri",
".",
"requestMethod",
",",
"ri",
".",
"urlRequested",
",",
"{",
"}",
",",
"ri",
".",
"headers",
")",
";",
"that",
".",
"requestProbeEnd",
"(",
"probeData",
",",
"ri",
".",
"requestMethod",
",",
"ri",
".",
"urlRequested",
",",
"{",
"}",
",",
"ri",
".",
"headers",
")",
";",
"}",
"return",
"rc",
";",
"}"
] |
After 'https.request' function returns
|
[
"After",
"https",
".",
"request",
"function",
"returns"
] |
cdcb907b9d57f9531986cc87b454813d621f59f0
|
https://github.com/RuntimeTools/appmetrics/blob/cdcb907b9d57f9531986cc87b454813d621f59f0/probes/https-outbound-probe.js#L95-L105
|
|
13,315
|
RuntimeTools/appmetrics
|
probes/leveldown-probe.js
|
function() {
var lvldownObj = target.apply(null, arguments);
lvldownObj._ddProbeAttached_ = true;
aspectLvldownMethod(lvldownObj, methods, that);
return lvldownObj;
}
|
javascript
|
function() {
var lvldownObj = target.apply(null, arguments);
lvldownObj._ddProbeAttached_ = true;
aspectLvldownMethod(lvldownObj, methods, that);
return lvldownObj;
}
|
[
"function",
"(",
")",
"{",
"var",
"lvldownObj",
"=",
"target",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"lvldownObj",
".",
"_ddProbeAttached_",
"=",
"true",
";",
"aspectLvldownMethod",
"(",
"lvldownObj",
",",
"methods",
",",
"that",
")",
";",
"return",
"lvldownObj",
";",
"}"
] |
Wrapping the target in new function as leveldown returns constructor
|
[
"Wrapping",
"the",
"target",
"in",
"new",
"function",
"as",
"leveldown",
"returns",
"constructor"
] |
cdcb907b9d57f9531986cc87b454813d621f59f0
|
https://github.com/RuntimeTools/appmetrics/blob/cdcb907b9d57f9531986cc87b454813d621f59f0/probes/leveldown-probe.js#L56-L61
|
|
13,316
|
RuntimeTools/appmetrics
|
probes/http-outbound-probe.js
|
function(obj, methodName, methodArgs, probeData) {
// Start metrics
that.metricsProbeStart(probeData);
that.requestProbeStart(probeData);
// End metrics
aspect.aroundCallback(
methodArgs,
probeData,
function(target, args, probeData) {
// Get HTTP request method from options
var ri = getRequestItems(methodArgs[0]);
that.metricsProbeEnd(probeData, ri.requestMethod, ri.urlRequested, args[0], ri.headers);
that.requestProbeEnd(probeData, ri.requestMethod, ri.urlRequested, args[0], ri.headers);
},
function(target, args, probeData, ret) {
// Don't need to do anything after the callback
return ret;
}
);
}
|
javascript
|
function(obj, methodName, methodArgs, probeData) {
// Start metrics
that.metricsProbeStart(probeData);
that.requestProbeStart(probeData);
// End metrics
aspect.aroundCallback(
methodArgs,
probeData,
function(target, args, probeData) {
// Get HTTP request method from options
var ri = getRequestItems(methodArgs[0]);
that.metricsProbeEnd(probeData, ri.requestMethod, ri.urlRequested, args[0], ri.headers);
that.requestProbeEnd(probeData, ri.requestMethod, ri.urlRequested, args[0], ri.headers);
},
function(target, args, probeData, ret) {
// Don't need to do anything after the callback
return ret;
}
);
}
|
[
"function",
"(",
"obj",
",",
"methodName",
",",
"methodArgs",
",",
"probeData",
")",
"{",
"// Start metrics",
"that",
".",
"metricsProbeStart",
"(",
"probeData",
")",
";",
"that",
".",
"requestProbeStart",
"(",
"probeData",
")",
";",
"// End metrics",
"aspect",
".",
"aroundCallback",
"(",
"methodArgs",
",",
"probeData",
",",
"function",
"(",
"target",
",",
"args",
",",
"probeData",
")",
"{",
"// Get HTTP request method from options",
"var",
"ri",
"=",
"getRequestItems",
"(",
"methodArgs",
"[",
"0",
"]",
")",
";",
"that",
".",
"metricsProbeEnd",
"(",
"probeData",
",",
"ri",
".",
"requestMethod",
",",
"ri",
".",
"urlRequested",
",",
"args",
"[",
"0",
"]",
",",
"ri",
".",
"headers",
")",
";",
"that",
".",
"requestProbeEnd",
"(",
"probeData",
",",
"ri",
".",
"requestMethod",
",",
"ri",
".",
"urlRequested",
",",
"args",
"[",
"0",
"]",
",",
"ri",
".",
"headers",
")",
";",
"}",
",",
"function",
"(",
"target",
",",
"args",
",",
"probeData",
",",
"ret",
")",
"{",
"// Don't need to do anything after the callback",
"return",
"ret",
";",
"}",
")",
";",
"}"
] |
Before 'http.request' function
|
[
"Before",
"http",
".",
"request",
"function"
] |
cdcb907b9d57f9531986cc87b454813d621f59f0
|
https://github.com/RuntimeTools/appmetrics/blob/cdcb907b9d57f9531986cc87b454813d621f59f0/probes/http-outbound-probe.js#L69-L88
|
|
13,317
|
adamgruber/mochawesome
|
src/mochawesome.js
|
done
|
function done(output, options, config, failures, exit) {
return marge.create(output, options)
.then(([ htmlFile, jsonFile ]) => {
if (!htmlFile && !jsonFile) {
log('No files were generated', 'warn', config);
} else {
jsonFile && log(`Report JSON saved to ${jsonFile}`, null, config);
htmlFile && log(`Report HTML saved to ${htmlFile}`, null, config);
}
})
.catch(err => {
log(err, 'error', config);
})
.then(() => {
exit && exit(failures > 0 ? 1 : 0);
});
}
|
javascript
|
function done(output, options, config, failures, exit) {
return marge.create(output, options)
.then(([ htmlFile, jsonFile ]) => {
if (!htmlFile && !jsonFile) {
log('No files were generated', 'warn', config);
} else {
jsonFile && log(`Report JSON saved to ${jsonFile}`, null, config);
htmlFile && log(`Report HTML saved to ${htmlFile}`, null, config);
}
})
.catch(err => {
log(err, 'error', config);
})
.then(() => {
exit && exit(failures > 0 ? 1 : 0);
});
}
|
[
"function",
"done",
"(",
"output",
",",
"options",
",",
"config",
",",
"failures",
",",
"exit",
")",
"{",
"return",
"marge",
".",
"create",
"(",
"output",
",",
"options",
")",
".",
"then",
"(",
"(",
"[",
"htmlFile",
",",
"jsonFile",
"]",
")",
"=>",
"{",
"if",
"(",
"!",
"htmlFile",
"&&",
"!",
"jsonFile",
")",
"{",
"log",
"(",
"'No files were generated'",
",",
"'warn'",
",",
"config",
")",
";",
"}",
"else",
"{",
"jsonFile",
"&&",
"log",
"(",
"`",
"${",
"jsonFile",
"}",
"`",
",",
"null",
",",
"config",
")",
";",
"htmlFile",
"&&",
"log",
"(",
"`",
"${",
"htmlFile",
"}",
"`",
",",
"null",
",",
"config",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"log",
"(",
"err",
",",
"'error'",
",",
"config",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"exit",
"&&",
"exit",
"(",
"failures",
">",
"0",
"?",
"1",
":",
"0",
")",
";",
"}",
")",
";",
"}"
] |
Done function gets called before mocha exits
Creates and saves the report HTML and JSON files
@param {Object} output Final report object
@param {Object} options Options to pass to report generator
@param {Object} config Reporter config object
@param {Number} failures Number of reported failures
@param {Function} exit
@return {Promise} Resolves with successful report creation
|
[
"Done",
"function",
"gets",
"called",
"before",
"mocha",
"exits"
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/mochawesome.js#L31-L47
|
13,318
|
adamgruber/mochawesome
|
src/mochawesome.js
|
Mochawesome
|
function Mochawesome(runner, options) {
// Set the config options
this.config = conf(options);
// Reporter options
const reporterOptions = Object.assign(
{},
(options.reporterOptions || {}),
{
reportFilename: this.config.reportFilename,
saveHtml: this.config.saveHtml,
saveJson: this.config.saveJson
}
);
// Done function will be called before mocha exits
// This is where we will save JSON and generate the HTML report
this.done = (failures, exit) => done(
this.output,
reporterOptions,
this.config,
failures,
exit
);
// Reset total tests counter
totalTestsRegistered.total = 0;
// Call the Base mocha reporter
Base.call(this, runner);
// Show the Spec Reporter in the console
new Spec(runner); // eslint-disable-line
let endCalled = false;
// Add a unique identifier to each test/hook
runner.on('test', test => {
test.uuid = uuid.v4();
});
runner.on('hook', hook => {
hook.uuid = uuid.v4();
});
runner.on('pending', test => {
test.uuid = uuid.v4();
});
// Process the full suite
runner.on('end', () => {
try {
/* istanbul ignore else */
if (!endCalled) {
// end gets called more than once for some reason
// so we ensure the suite is processed only once
endCalled = true;
const allSuites = mapSuites(this.runner.suite, totalTestsRegistered, this.config);
const obj = {
stats: this.stats,
suites: allSuites,
copyrightYear: new Date().getFullYear()
};
obj.stats.testsRegistered = totalTestsRegistered.total;
const { passes, failures, pending, tests, testsRegistered } = obj.stats;
const passPercentage = Math.round((passes / (testsRegistered - pending)) * 1000) / 10;
const pendingPercentage = Math.round((pending / testsRegistered) * 1000) /10;
obj.stats.passPercent = passPercentage;
obj.stats.pendingPercent = pendingPercentage;
obj.stats.other = (passes + failures + pending) - tests;
obj.stats.hasOther = obj.stats.other > 0;
obj.stats.skipped = testsRegistered - tests;
obj.stats.hasSkipped = obj.stats.skipped > 0;
obj.stats.failures -= obj.stats.other;
obj.stats.passPercentClass = getPercentClass(passPercentage);
obj.stats.pendingPercentClass = getPercentClass(pendingPercentage);
// Save the final output to be used in the done function
this.output = obj;
}
} catch (e) {
// required because thrown errors are not handled directly in the
// event emitter pattern and mocha does not have an "on error"
/* istanbul ignore next */
log(`Problem with mochawesome: ${e.stack}`, 'error');
}
});
}
|
javascript
|
function Mochawesome(runner, options) {
// Set the config options
this.config = conf(options);
// Reporter options
const reporterOptions = Object.assign(
{},
(options.reporterOptions || {}),
{
reportFilename: this.config.reportFilename,
saveHtml: this.config.saveHtml,
saveJson: this.config.saveJson
}
);
// Done function will be called before mocha exits
// This is where we will save JSON and generate the HTML report
this.done = (failures, exit) => done(
this.output,
reporterOptions,
this.config,
failures,
exit
);
// Reset total tests counter
totalTestsRegistered.total = 0;
// Call the Base mocha reporter
Base.call(this, runner);
// Show the Spec Reporter in the console
new Spec(runner); // eslint-disable-line
let endCalled = false;
// Add a unique identifier to each test/hook
runner.on('test', test => {
test.uuid = uuid.v4();
});
runner.on('hook', hook => {
hook.uuid = uuid.v4();
});
runner.on('pending', test => {
test.uuid = uuid.v4();
});
// Process the full suite
runner.on('end', () => {
try {
/* istanbul ignore else */
if (!endCalled) {
// end gets called more than once for some reason
// so we ensure the suite is processed only once
endCalled = true;
const allSuites = mapSuites(this.runner.suite, totalTestsRegistered, this.config);
const obj = {
stats: this.stats,
suites: allSuites,
copyrightYear: new Date().getFullYear()
};
obj.stats.testsRegistered = totalTestsRegistered.total;
const { passes, failures, pending, tests, testsRegistered } = obj.stats;
const passPercentage = Math.round((passes / (testsRegistered - pending)) * 1000) / 10;
const pendingPercentage = Math.round((pending / testsRegistered) * 1000) /10;
obj.stats.passPercent = passPercentage;
obj.stats.pendingPercent = pendingPercentage;
obj.stats.other = (passes + failures + pending) - tests;
obj.stats.hasOther = obj.stats.other > 0;
obj.stats.skipped = testsRegistered - tests;
obj.stats.hasSkipped = obj.stats.skipped > 0;
obj.stats.failures -= obj.stats.other;
obj.stats.passPercentClass = getPercentClass(passPercentage);
obj.stats.pendingPercentClass = getPercentClass(pendingPercentage);
// Save the final output to be used in the done function
this.output = obj;
}
} catch (e) {
// required because thrown errors are not handled directly in the
// event emitter pattern and mocha does not have an "on error"
/* istanbul ignore next */
log(`Problem with mochawesome: ${e.stack}`, 'error');
}
});
}
|
[
"function",
"Mochawesome",
"(",
"runner",
",",
"options",
")",
"{",
"// Set the config options",
"this",
".",
"config",
"=",
"conf",
"(",
"options",
")",
";",
"// Reporter options",
"const",
"reporterOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"(",
"options",
".",
"reporterOptions",
"||",
"{",
"}",
")",
",",
"{",
"reportFilename",
":",
"this",
".",
"config",
".",
"reportFilename",
",",
"saveHtml",
":",
"this",
".",
"config",
".",
"saveHtml",
",",
"saveJson",
":",
"this",
".",
"config",
".",
"saveJson",
"}",
")",
";",
"// Done function will be called before mocha exits",
"// This is where we will save JSON and generate the HTML report",
"this",
".",
"done",
"=",
"(",
"failures",
",",
"exit",
")",
"=>",
"done",
"(",
"this",
".",
"output",
",",
"reporterOptions",
",",
"this",
".",
"config",
",",
"failures",
",",
"exit",
")",
";",
"// Reset total tests counter",
"totalTestsRegistered",
".",
"total",
"=",
"0",
";",
"// Call the Base mocha reporter",
"Base",
".",
"call",
"(",
"this",
",",
"runner",
")",
";",
"// Show the Spec Reporter in the console",
"new",
"Spec",
"(",
"runner",
")",
";",
"// eslint-disable-line",
"let",
"endCalled",
"=",
"false",
";",
"// Add a unique identifier to each test/hook",
"runner",
".",
"on",
"(",
"'test'",
",",
"test",
"=>",
"{",
"test",
".",
"uuid",
"=",
"uuid",
".",
"v4",
"(",
")",
";",
"}",
")",
";",
"runner",
".",
"on",
"(",
"'hook'",
",",
"hook",
"=>",
"{",
"hook",
".",
"uuid",
"=",
"uuid",
".",
"v4",
"(",
")",
";",
"}",
")",
";",
"runner",
".",
"on",
"(",
"'pending'",
",",
"test",
"=>",
"{",
"test",
".",
"uuid",
"=",
"uuid",
".",
"v4",
"(",
")",
";",
"}",
")",
";",
"// Process the full suite",
"runner",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"try",
"{",
"/* istanbul ignore else */",
"if",
"(",
"!",
"endCalled",
")",
"{",
"// end gets called more than once for some reason",
"// so we ensure the suite is processed only once",
"endCalled",
"=",
"true",
";",
"const",
"allSuites",
"=",
"mapSuites",
"(",
"this",
".",
"runner",
".",
"suite",
",",
"totalTestsRegistered",
",",
"this",
".",
"config",
")",
";",
"const",
"obj",
"=",
"{",
"stats",
":",
"this",
".",
"stats",
",",
"suites",
":",
"allSuites",
",",
"copyrightYear",
":",
"new",
"Date",
"(",
")",
".",
"getFullYear",
"(",
")",
"}",
";",
"obj",
".",
"stats",
".",
"testsRegistered",
"=",
"totalTestsRegistered",
".",
"total",
";",
"const",
"{",
"passes",
",",
"failures",
",",
"pending",
",",
"tests",
",",
"testsRegistered",
"}",
"=",
"obj",
".",
"stats",
";",
"const",
"passPercentage",
"=",
"Math",
".",
"round",
"(",
"(",
"passes",
"/",
"(",
"testsRegistered",
"-",
"pending",
")",
")",
"*",
"1000",
")",
"/",
"10",
";",
"const",
"pendingPercentage",
"=",
"Math",
".",
"round",
"(",
"(",
"pending",
"/",
"testsRegistered",
")",
"*",
"1000",
")",
"/",
"10",
";",
"obj",
".",
"stats",
".",
"passPercent",
"=",
"passPercentage",
";",
"obj",
".",
"stats",
".",
"pendingPercent",
"=",
"pendingPercentage",
";",
"obj",
".",
"stats",
".",
"other",
"=",
"(",
"passes",
"+",
"failures",
"+",
"pending",
")",
"-",
"tests",
";",
"obj",
".",
"stats",
".",
"hasOther",
"=",
"obj",
".",
"stats",
".",
"other",
">",
"0",
";",
"obj",
".",
"stats",
".",
"skipped",
"=",
"testsRegistered",
"-",
"tests",
";",
"obj",
".",
"stats",
".",
"hasSkipped",
"=",
"obj",
".",
"stats",
".",
"skipped",
">",
"0",
";",
"obj",
".",
"stats",
".",
"failures",
"-=",
"obj",
".",
"stats",
".",
"other",
";",
"obj",
".",
"stats",
".",
"passPercentClass",
"=",
"getPercentClass",
"(",
"passPercentage",
")",
";",
"obj",
".",
"stats",
".",
"pendingPercentClass",
"=",
"getPercentClass",
"(",
"pendingPercentage",
")",
";",
"// Save the final output to be used in the done function",
"this",
".",
"output",
"=",
"obj",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"// required because thrown errors are not handled directly in the",
"// event emitter pattern and mocha does not have an \"on error\"",
"/* istanbul ignore next */",
"log",
"(",
"`",
"${",
"e",
".",
"stack",
"}",
"`",
",",
"'error'",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Initialize a new reporter.
@param {Runner} runner
@api public
|
[
"Initialize",
"a",
"new",
"reporter",
"."
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/mochawesome.js#L55-L145
|
13,319
|
adamgruber/mochawesome
|
src/utils.js
|
log
|
function log(msg, level, config) {
// Don't log messages in quiet mode
if (config && config.quiet) return;
const logMethod = console[level] || console.log;
let out = msg;
if (typeof msg === 'object') {
out = stringify(msg, null, 2);
}
logMethod(`[${chalk.gray('mochawesome')}] ${out}\n`);
}
|
javascript
|
function log(msg, level, config) {
// Don't log messages in quiet mode
if (config && config.quiet) return;
const logMethod = console[level] || console.log;
let out = msg;
if (typeof msg === 'object') {
out = stringify(msg, null, 2);
}
logMethod(`[${chalk.gray('mochawesome')}] ${out}\n`);
}
|
[
"function",
"log",
"(",
"msg",
",",
"level",
",",
"config",
")",
"{",
"// Don't log messages in quiet mode",
"if",
"(",
"config",
"&&",
"config",
".",
"quiet",
")",
"return",
";",
"const",
"logMethod",
"=",
"console",
"[",
"level",
"]",
"||",
"console",
".",
"log",
";",
"let",
"out",
"=",
"msg",
";",
"if",
"(",
"typeof",
"msg",
"===",
"'object'",
")",
"{",
"out",
"=",
"stringify",
"(",
"msg",
",",
"null",
",",
"2",
")",
";",
"}",
"logMethod",
"(",
"`",
"${",
"chalk",
".",
"gray",
"(",
"'mochawesome'",
")",
"}",
"${",
"out",
"}",
"\\n",
"`",
")",
";",
"}"
] |
Return a classname based on percentage
@param {String} msg - message to log
@param {String} level - log level [log, info, warn, error]
@param {Object} config - configuration object
|
[
"Return",
"a",
"classname",
"based",
"on",
"percentage"
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L17-L26
|
13,320
|
adamgruber/mochawesome
|
src/utils.js
|
cleanCode
|
function cleanCode(str) {
str = str
.replace(/\r\n|[\r\n\u2028\u2029]/g, '\n') // unify linebreaks
.replace(/^\uFEFF/, ''); // replace zero-width no-break space
str = stripFnStart(str) // replace function declaration
.replace(/\)\s*\)\s*$/, ')') // replace closing paren
.replace(/\s*};?\s*$/, ''); // replace closing bracket
// Preserve indentation by finding leading tabs/spaces
// and removing that amount of space from each line
const spaces = str.match(/^\n?( *)/)[1].length;
const tabs = str.match(/^\n?(\t*)/)[1].length;
/* istanbul ignore next */
const indentRegex = new RegExp(`^\n?${tabs ? '\t' : ' '}{${tabs || spaces}}`, 'gm');
str = str.replace(indentRegex, '').trim();
return str;
}
|
javascript
|
function cleanCode(str) {
str = str
.replace(/\r\n|[\r\n\u2028\u2029]/g, '\n') // unify linebreaks
.replace(/^\uFEFF/, ''); // replace zero-width no-break space
str = stripFnStart(str) // replace function declaration
.replace(/\)\s*\)\s*$/, ')') // replace closing paren
.replace(/\s*};?\s*$/, ''); // replace closing bracket
// Preserve indentation by finding leading tabs/spaces
// and removing that amount of space from each line
const spaces = str.match(/^\n?( *)/)[1].length;
const tabs = str.match(/^\n?(\t*)/)[1].length;
/* istanbul ignore next */
const indentRegex = new RegExp(`^\n?${tabs ? '\t' : ' '}{${tabs || spaces}}`, 'gm');
str = str.replace(indentRegex, '').trim();
return str;
}
|
[
"function",
"cleanCode",
"(",
"str",
")",
"{",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"\\r\\n|[\\r\\n\\u2028\\u2029]",
"/",
"g",
",",
"'\\n'",
")",
"// unify linebreaks",
".",
"replace",
"(",
"/",
"^\\uFEFF",
"/",
",",
"''",
")",
";",
"// replace zero-width no-break space",
"str",
"=",
"stripFnStart",
"(",
"str",
")",
"// replace function declaration",
".",
"replace",
"(",
"/",
"\\)\\s*\\)\\s*$",
"/",
",",
"')'",
")",
"// replace closing paren",
".",
"replace",
"(",
"/",
"\\s*};?\\s*$",
"/",
",",
"''",
")",
";",
"// replace closing bracket",
"// Preserve indentation by finding leading tabs/spaces",
"// and removing that amount of space from each line",
"const",
"spaces",
"=",
"str",
".",
"match",
"(",
"/",
"^\\n?( *)",
"/",
")",
"[",
"1",
"]",
".",
"length",
";",
"const",
"tabs",
"=",
"str",
".",
"match",
"(",
"/",
"^\\n?(\\t*)",
"/",
")",
"[",
"1",
"]",
".",
"length",
";",
"/* istanbul ignore next */",
"const",
"indentRegex",
"=",
"new",
"RegExp",
"(",
"`",
"\\n",
"${",
"tabs",
"?",
"'\\t'",
":",
"' '",
"}",
"${",
"tabs",
"||",
"spaces",
"}",
"`",
",",
"'gm'",
")",
";",
"str",
"=",
"str",
".",
"replace",
"(",
"indentRegex",
",",
"''",
")",
".",
"trim",
"(",
")",
";",
"return",
"str",
";",
"}"
] |
Strip the function definition from `str`,
and re-indent for pre whitespace.
@param {String} str - code in
@return {String} cleaned code string
|
[
"Strip",
"the",
"function",
"definition",
"from",
"str",
"and",
"re",
"-",
"indent",
"for",
"pre",
"whitespace",
"."
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L53-L71
|
13,321
|
adamgruber/mochawesome
|
src/utils.js
|
createUnifiedDiff
|
function createUnifiedDiff({ actual, expected }) {
return diff.createPatch('string', actual, expected)
.split('\n')
.splice(4)
.map(line => {
if (line.match(/@@/)) {
return null;
}
if (line.match(/\\ No newline/)) {
return null;
}
return line.replace(/^(-|\+)/, '$1 ');
})
.filter(line => typeof line !== 'undefined' && line !== null)
.join('\n');
}
|
javascript
|
function createUnifiedDiff({ actual, expected }) {
return diff.createPatch('string', actual, expected)
.split('\n')
.splice(4)
.map(line => {
if (line.match(/@@/)) {
return null;
}
if (line.match(/\\ No newline/)) {
return null;
}
return line.replace(/^(-|\+)/, '$1 ');
})
.filter(line => typeof line !== 'undefined' && line !== null)
.join('\n');
}
|
[
"function",
"createUnifiedDiff",
"(",
"{",
"actual",
",",
"expected",
"}",
")",
"{",
"return",
"diff",
".",
"createPatch",
"(",
"'string'",
",",
"actual",
",",
"expected",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"splice",
"(",
"4",
")",
".",
"map",
"(",
"line",
"=>",
"{",
"if",
"(",
"line",
".",
"match",
"(",
"/",
"@@",
"/",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"line",
".",
"match",
"(",
"/",
"\\\\ No newline",
"/",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"line",
".",
"replace",
"(",
"/",
"^(-|\\+)",
"/",
",",
"'$1 '",
")",
";",
"}",
")",
".",
"filter",
"(",
"line",
"=>",
"typeof",
"line",
"!==",
"'undefined'",
"&&",
"line",
"!==",
"null",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] |
Create a unified diff between two strings
@param {Error} err Error object
@param {string} err.actual Actual result returned
@param {string} err.expected Result expected
@return {string} diff
|
[
"Create",
"a",
"unified",
"diff",
"between",
"two",
"strings"
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L82-L97
|
13,322
|
adamgruber/mochawesome
|
src/utils.js
|
normalizeErr
|
function normalizeErr(err, config) {
const { name, message, actual, expected, stack, showDiff } = err;
let errMessage;
let errDiff;
/**
* Check that a / b have the same type.
*/
function sameType(a, b) {
const objToString = Object.prototype.toString;
return objToString.call(a) === objToString.call(b);
}
// Format actual/expected for creating diff
if (showDiff !== false && sameType(actual, expected) && expected !== undefined) {
/* istanbul ignore if */
if (!(_.isString(actual) && _.isString(expected))) {
err.actual = mochaUtils.stringify(actual);
err.expected = mochaUtils.stringify(expected);
}
errDiff = config.useInlineDiffs ? createInlineDiff(err) : createUnifiedDiff(err);
}
// Assertion libraries do not output consitent error objects so in order to
// get a consistent message object we need to create it ourselves
if (name && message) {
errMessage = `${name}: ${stripAnsi(message)}`;
} else if (stack) {
errMessage = stack.replace(/\n.*/g, '');
}
return {
message: errMessage,
estack: stack && stripAnsi(stack),
diff: errDiff
};
}
|
javascript
|
function normalizeErr(err, config) {
const { name, message, actual, expected, stack, showDiff } = err;
let errMessage;
let errDiff;
/**
* Check that a / b have the same type.
*/
function sameType(a, b) {
const objToString = Object.prototype.toString;
return objToString.call(a) === objToString.call(b);
}
// Format actual/expected for creating diff
if (showDiff !== false && sameType(actual, expected) && expected !== undefined) {
/* istanbul ignore if */
if (!(_.isString(actual) && _.isString(expected))) {
err.actual = mochaUtils.stringify(actual);
err.expected = mochaUtils.stringify(expected);
}
errDiff = config.useInlineDiffs ? createInlineDiff(err) : createUnifiedDiff(err);
}
// Assertion libraries do not output consitent error objects so in order to
// get a consistent message object we need to create it ourselves
if (name && message) {
errMessage = `${name}: ${stripAnsi(message)}`;
} else if (stack) {
errMessage = stack.replace(/\n.*/g, '');
}
return {
message: errMessage,
estack: stack && stripAnsi(stack),
diff: errDiff
};
}
|
[
"function",
"normalizeErr",
"(",
"err",
",",
"config",
")",
"{",
"const",
"{",
"name",
",",
"message",
",",
"actual",
",",
"expected",
",",
"stack",
",",
"showDiff",
"}",
"=",
"err",
";",
"let",
"errMessage",
";",
"let",
"errDiff",
";",
"/**\n * Check that a / b have the same type.\n */",
"function",
"sameType",
"(",
"a",
",",
"b",
")",
"{",
"const",
"objToString",
"=",
"Object",
".",
"prototype",
".",
"toString",
";",
"return",
"objToString",
".",
"call",
"(",
"a",
")",
"===",
"objToString",
".",
"call",
"(",
"b",
")",
";",
"}",
"// Format actual/expected for creating diff",
"if",
"(",
"showDiff",
"!==",
"false",
"&&",
"sameType",
"(",
"actual",
",",
"expected",
")",
"&&",
"expected",
"!==",
"undefined",
")",
"{",
"/* istanbul ignore if */",
"if",
"(",
"!",
"(",
"_",
".",
"isString",
"(",
"actual",
")",
"&&",
"_",
".",
"isString",
"(",
"expected",
")",
")",
")",
"{",
"err",
".",
"actual",
"=",
"mochaUtils",
".",
"stringify",
"(",
"actual",
")",
";",
"err",
".",
"expected",
"=",
"mochaUtils",
".",
"stringify",
"(",
"expected",
")",
";",
"}",
"errDiff",
"=",
"config",
".",
"useInlineDiffs",
"?",
"createInlineDiff",
"(",
"err",
")",
":",
"createUnifiedDiff",
"(",
"err",
")",
";",
"}",
"// Assertion libraries do not output consitent error objects so in order to",
"// get a consistent message object we need to create it ourselves",
"if",
"(",
"name",
"&&",
"message",
")",
"{",
"errMessage",
"=",
"`",
"${",
"name",
"}",
"${",
"stripAnsi",
"(",
"message",
")",
"}",
"`",
";",
"}",
"else",
"if",
"(",
"stack",
")",
"{",
"errMessage",
"=",
"stack",
".",
"replace",
"(",
"/",
"\\n.*",
"/",
"g",
",",
"''",
")",
";",
"}",
"return",
"{",
"message",
":",
"errMessage",
",",
"estack",
":",
"stack",
"&&",
"stripAnsi",
"(",
"stack",
")",
",",
"diff",
":",
"errDiff",
"}",
";",
"}"
] |
Return a normalized error object
@param {Error} err Error object
@return {Object} normalized error
|
[
"Return",
"a",
"normalized",
"error",
"object"
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L119-L155
|
13,323
|
adamgruber/mochawesome
|
src/utils.js
|
cleanSuite
|
function cleanSuite(suite, totalTestsRegistered, config) {
let duration = 0;
const passingTests = [];
const failingTests = [];
const pendingTests = [];
const skippedTests = [];
const beforeHooks = _.map(
[].concat(suite._beforeAll, suite._beforeEach),
test => cleanTest(test, config)
);
const afterHooks = _.map(
[].concat(suite._afterAll, suite._afterEach),
test => cleanTest(test, config)
);
const tests = _.map(
suite.tests,
test => {
const cleanedTest = cleanTest(test, config);
duration += test.duration || 0;
if (cleanedTest.state === 'passed') passingTests.push(cleanedTest.uuid);
if (cleanedTest.state === 'failed') failingTests.push(cleanedTest.uuid);
if (cleanedTest.pending) pendingTests.push(cleanedTest.uuid);
if (cleanedTest.skipped) skippedTests.push(cleanedTest.uuid);
return cleanedTest;
}
);
totalTestsRegistered.total += tests.length;
const cleaned = {
uuid: uuid.v4(),
title: stripAnsi(suite.title),
fullFile: suite.file || '',
file: suite.file ? suite.file.replace(process.cwd(), '') : '',
beforeHooks,
afterHooks,
tests,
suites: suite.suites,
passes: passingTests,
failures: failingTests,
pending: pendingTests,
skipped: skippedTests,
duration,
root: suite.root,
rootEmpty: suite.root && tests.length === 0,
_timeout: suite._timeout
};
const isEmptySuite = _.isEmpty(cleaned.suites)
&& _.isEmpty(cleaned.tests)
&& _.isEmpty(cleaned.beforeHooks)
&& _.isEmpty(cleaned.afterHooks);
return !isEmptySuite && cleaned;
}
|
javascript
|
function cleanSuite(suite, totalTestsRegistered, config) {
let duration = 0;
const passingTests = [];
const failingTests = [];
const pendingTests = [];
const skippedTests = [];
const beforeHooks = _.map(
[].concat(suite._beforeAll, suite._beforeEach),
test => cleanTest(test, config)
);
const afterHooks = _.map(
[].concat(suite._afterAll, suite._afterEach),
test => cleanTest(test, config)
);
const tests = _.map(
suite.tests,
test => {
const cleanedTest = cleanTest(test, config);
duration += test.duration || 0;
if (cleanedTest.state === 'passed') passingTests.push(cleanedTest.uuid);
if (cleanedTest.state === 'failed') failingTests.push(cleanedTest.uuid);
if (cleanedTest.pending) pendingTests.push(cleanedTest.uuid);
if (cleanedTest.skipped) skippedTests.push(cleanedTest.uuid);
return cleanedTest;
}
);
totalTestsRegistered.total += tests.length;
const cleaned = {
uuid: uuid.v4(),
title: stripAnsi(suite.title),
fullFile: suite.file || '',
file: suite.file ? suite.file.replace(process.cwd(), '') : '',
beforeHooks,
afterHooks,
tests,
suites: suite.suites,
passes: passingTests,
failures: failingTests,
pending: pendingTests,
skipped: skippedTests,
duration,
root: suite.root,
rootEmpty: suite.root && tests.length === 0,
_timeout: suite._timeout
};
const isEmptySuite = _.isEmpty(cleaned.suites)
&& _.isEmpty(cleaned.tests)
&& _.isEmpty(cleaned.beforeHooks)
&& _.isEmpty(cleaned.afterHooks);
return !isEmptySuite && cleaned;
}
|
[
"function",
"cleanSuite",
"(",
"suite",
",",
"totalTestsRegistered",
",",
"config",
")",
"{",
"let",
"duration",
"=",
"0",
";",
"const",
"passingTests",
"=",
"[",
"]",
";",
"const",
"failingTests",
"=",
"[",
"]",
";",
"const",
"pendingTests",
"=",
"[",
"]",
";",
"const",
"skippedTests",
"=",
"[",
"]",
";",
"const",
"beforeHooks",
"=",
"_",
".",
"map",
"(",
"[",
"]",
".",
"concat",
"(",
"suite",
".",
"_beforeAll",
",",
"suite",
".",
"_beforeEach",
")",
",",
"test",
"=>",
"cleanTest",
"(",
"test",
",",
"config",
")",
")",
";",
"const",
"afterHooks",
"=",
"_",
".",
"map",
"(",
"[",
"]",
".",
"concat",
"(",
"suite",
".",
"_afterAll",
",",
"suite",
".",
"_afterEach",
")",
",",
"test",
"=>",
"cleanTest",
"(",
"test",
",",
"config",
")",
")",
";",
"const",
"tests",
"=",
"_",
".",
"map",
"(",
"suite",
".",
"tests",
",",
"test",
"=>",
"{",
"const",
"cleanedTest",
"=",
"cleanTest",
"(",
"test",
",",
"config",
")",
";",
"duration",
"+=",
"test",
".",
"duration",
"||",
"0",
";",
"if",
"(",
"cleanedTest",
".",
"state",
"===",
"'passed'",
")",
"passingTests",
".",
"push",
"(",
"cleanedTest",
".",
"uuid",
")",
";",
"if",
"(",
"cleanedTest",
".",
"state",
"===",
"'failed'",
")",
"failingTests",
".",
"push",
"(",
"cleanedTest",
".",
"uuid",
")",
";",
"if",
"(",
"cleanedTest",
".",
"pending",
")",
"pendingTests",
".",
"push",
"(",
"cleanedTest",
".",
"uuid",
")",
";",
"if",
"(",
"cleanedTest",
".",
"skipped",
")",
"skippedTests",
".",
"push",
"(",
"cleanedTest",
".",
"uuid",
")",
";",
"return",
"cleanedTest",
";",
"}",
")",
";",
"totalTestsRegistered",
".",
"total",
"+=",
"tests",
".",
"length",
";",
"const",
"cleaned",
"=",
"{",
"uuid",
":",
"uuid",
".",
"v4",
"(",
")",
",",
"title",
":",
"stripAnsi",
"(",
"suite",
".",
"title",
")",
",",
"fullFile",
":",
"suite",
".",
"file",
"||",
"''",
",",
"file",
":",
"suite",
".",
"file",
"?",
"suite",
".",
"file",
".",
"replace",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"''",
")",
":",
"''",
",",
"beforeHooks",
",",
"afterHooks",
",",
"tests",
",",
"suites",
":",
"suite",
".",
"suites",
",",
"passes",
":",
"passingTests",
",",
"failures",
":",
"failingTests",
",",
"pending",
":",
"pendingTests",
",",
"skipped",
":",
"skippedTests",
",",
"duration",
",",
"root",
":",
"suite",
".",
"root",
",",
"rootEmpty",
":",
"suite",
".",
"root",
"&&",
"tests",
".",
"length",
"===",
"0",
",",
"_timeout",
":",
"suite",
".",
"_timeout",
"}",
";",
"const",
"isEmptySuite",
"=",
"_",
".",
"isEmpty",
"(",
"cleaned",
".",
"suites",
")",
"&&",
"_",
".",
"isEmpty",
"(",
"cleaned",
".",
"tests",
")",
"&&",
"_",
".",
"isEmpty",
"(",
"cleaned",
".",
"beforeHooks",
")",
"&&",
"_",
".",
"isEmpty",
"(",
"cleaned",
".",
"afterHooks",
")",
";",
"return",
"!",
"isEmptySuite",
"&&",
"cleaned",
";",
"}"
] |
Return a plain-object representation of `suite` with additional properties for rendering.
@param {Object} suite
@param {Object} totalTestsRegistered
@param {Integer} totalTestsRegistered.total
@return {Object|boolean} cleaned suite or false if suite is empty
|
[
"Return",
"a",
"plain",
"-",
"object",
"representation",
"of",
"suite",
"with",
"additional",
"properties",
"for",
"rendering",
"."
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L207-L264
|
13,324
|
adamgruber/mochawesome
|
src/utils.js
|
mapSuites
|
function mapSuites(suite, totalTestsReg, config) {
const suites = _.compact(_.map(suite.suites, subSuite => (
mapSuites(subSuite, totalTestsReg, config)
)));
const toBeCleaned = Object.assign({}, suite, { suites });
return cleanSuite(toBeCleaned, totalTestsReg, config);
}
|
javascript
|
function mapSuites(suite, totalTestsReg, config) {
const suites = _.compact(_.map(suite.suites, subSuite => (
mapSuites(subSuite, totalTestsReg, config)
)));
const toBeCleaned = Object.assign({}, suite, { suites });
return cleanSuite(toBeCleaned, totalTestsReg, config);
}
|
[
"function",
"mapSuites",
"(",
"suite",
",",
"totalTestsReg",
",",
"config",
")",
"{",
"const",
"suites",
"=",
"_",
".",
"compact",
"(",
"_",
".",
"map",
"(",
"suite",
".",
"suites",
",",
"subSuite",
"=>",
"(",
"mapSuites",
"(",
"subSuite",
",",
"totalTestsReg",
",",
"config",
")",
")",
")",
")",
";",
"const",
"toBeCleaned",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"suite",
",",
"{",
"suites",
"}",
")",
";",
"return",
"cleanSuite",
"(",
"toBeCleaned",
",",
"totalTestsReg",
",",
"config",
")",
";",
"}"
] |
Map over a suite, returning a cleaned suite object
and recursively cleaning any nested suites.
@param {Object} suite Suite to map over
@param {Object} totalTestsReg Cumulative count of total tests registered
@param {Integer} totalTestsReg.total
@param {Object} config Reporter configuration
|
[
"Map",
"over",
"a",
"suite",
"returning",
"a",
"cleaned",
"suite",
"object",
"and",
"recursively",
"cleaning",
"any",
"nested",
"suites",
"."
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L275-L281
|
13,325
|
adamgruber/mochawesome
|
src/config.js
|
_getOption
|
function _getOption(optToGet, options, isBool, defaultValue) {
const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`;
if (options && typeof options[optToGet] !== 'undefined') {
return (isBool && typeof options[optToGet] === 'string')
? options[optToGet] === 'true'
: options[optToGet];
}
if (typeof process.env[envVar] !== 'undefined') {
return isBool
? process.env[envVar] === 'true'
: process.env[envVar];
}
return defaultValue;
}
|
javascript
|
function _getOption(optToGet, options, isBool, defaultValue) {
const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`;
if (options && typeof options[optToGet] !== 'undefined') {
return (isBool && typeof options[optToGet] === 'string')
? options[optToGet] === 'true'
: options[optToGet];
}
if (typeof process.env[envVar] !== 'undefined') {
return isBool
? process.env[envVar] === 'true'
: process.env[envVar];
}
return defaultValue;
}
|
[
"function",
"_getOption",
"(",
"optToGet",
",",
"options",
",",
"isBool",
",",
"defaultValue",
")",
"{",
"const",
"envVar",
"=",
"`",
"${",
"optToGet",
".",
"toUpperCase",
"(",
")",
"}",
"`",
";",
"if",
"(",
"options",
"&&",
"typeof",
"options",
"[",
"optToGet",
"]",
"!==",
"'undefined'",
")",
"{",
"return",
"(",
"isBool",
"&&",
"typeof",
"options",
"[",
"optToGet",
"]",
"===",
"'string'",
")",
"?",
"options",
"[",
"optToGet",
"]",
"===",
"'true'",
":",
"options",
"[",
"optToGet",
"]",
";",
"}",
"if",
"(",
"typeof",
"process",
".",
"env",
"[",
"envVar",
"]",
"!==",
"'undefined'",
")",
"{",
"return",
"isBool",
"?",
"process",
".",
"env",
"[",
"envVar",
"]",
"===",
"'true'",
":",
"process",
".",
"env",
"[",
"envVar",
"]",
";",
"}",
"return",
"defaultValue",
";",
"}"
] |
Retrieve the value of a user supplied option.
Falls back to `defaultValue`
Order of precedence
1. User-supplied option
2. Environment variable
3. Default value
@param {string} optToGet Option name
@param {object} options User supplied options object
@param {boolean} isBool Treat option as Boolean
@param {string|boolean} defaultValue Fallback value
@return {string|boolean} Option value
|
[
"Retrieve",
"the",
"value",
"of",
"a",
"user",
"supplied",
"option",
".",
"Falls",
"back",
"to",
"defaultValue",
"Order",
"of",
"precedence",
"1",
".",
"User",
"-",
"supplied",
"option",
"2",
".",
"Environment",
"variable",
"3",
".",
"Default",
"value"
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/config.js#L16-L29
|
13,326
|
adamgruber/mochawesome
|
src/addContext.js
|
function (...args) {
// Check args to see if we should bother continuing
if ((args.length !== 2) || !isObject(args[0])) {
log(ERRORS.INVALID_ARGS, 'error');
return;
}
const ctx = args[1];
// Ensure that context meets the requirements
if (!_isValidContext(ctx)) {
log(ERRORS.INVALID_CONTEXT(ctx), 'error');
return;
}
/* Context is valid, now get the test object
* If `addContext` is called from inside a `beforeEach` or `afterEach`
* the test object will be `.currentTest`, otherwise just `.test`
*/
const test = args[0].currentTest || args[0].test;
if (!test) {
log(ERRORS.INVALID_TEST, 'error');
return;
}
/* If context is an object, and value is `undefined`
* change it to 'undefined' so it can be displayed
* correctly in the report
*/
if (ctx.title && ctx.value === undefined) {
ctx.value = 'undefined';
}
// Test doesn't already have context -> set it
if (!test.context) {
test.context = ctx;
} else if (Array.isArray(test.context)) {
// Test has context and context is an array -> push new context
test.context.push(ctx);
} else {
// Test has context and it is not an array -> make it an array, then push new context
test.context = [ test.context ];
test.context.push(ctx);
}
}
|
javascript
|
function (...args) {
// Check args to see if we should bother continuing
if ((args.length !== 2) || !isObject(args[0])) {
log(ERRORS.INVALID_ARGS, 'error');
return;
}
const ctx = args[1];
// Ensure that context meets the requirements
if (!_isValidContext(ctx)) {
log(ERRORS.INVALID_CONTEXT(ctx), 'error');
return;
}
/* Context is valid, now get the test object
* If `addContext` is called from inside a `beforeEach` or `afterEach`
* the test object will be `.currentTest`, otherwise just `.test`
*/
const test = args[0].currentTest || args[0].test;
if (!test) {
log(ERRORS.INVALID_TEST, 'error');
return;
}
/* If context is an object, and value is `undefined`
* change it to 'undefined' so it can be displayed
* correctly in the report
*/
if (ctx.title && ctx.value === undefined) {
ctx.value = 'undefined';
}
// Test doesn't already have context -> set it
if (!test.context) {
test.context = ctx;
} else if (Array.isArray(test.context)) {
// Test has context and context is an array -> push new context
test.context.push(ctx);
} else {
// Test has context and it is not an array -> make it an array, then push new context
test.context = [ test.context ];
test.context.push(ctx);
}
}
|
[
"function",
"(",
"...",
"args",
")",
"{",
"// Check args to see if we should bother continuing",
"if",
"(",
"(",
"args",
".",
"length",
"!==",
"2",
")",
"||",
"!",
"isObject",
"(",
"args",
"[",
"0",
"]",
")",
")",
"{",
"log",
"(",
"ERRORS",
".",
"INVALID_ARGS",
",",
"'error'",
")",
";",
"return",
";",
"}",
"const",
"ctx",
"=",
"args",
"[",
"1",
"]",
";",
"// Ensure that context meets the requirements",
"if",
"(",
"!",
"_isValidContext",
"(",
"ctx",
")",
")",
"{",
"log",
"(",
"ERRORS",
".",
"INVALID_CONTEXT",
"(",
"ctx",
")",
",",
"'error'",
")",
";",
"return",
";",
"}",
"/* Context is valid, now get the test object\n * If `addContext` is called from inside a `beforeEach` or `afterEach`\n * the test object will be `.currentTest`, otherwise just `.test`\n */",
"const",
"test",
"=",
"args",
"[",
"0",
"]",
".",
"currentTest",
"||",
"args",
"[",
"0",
"]",
".",
"test",
";",
"if",
"(",
"!",
"test",
")",
"{",
"log",
"(",
"ERRORS",
".",
"INVALID_TEST",
",",
"'error'",
")",
";",
"return",
";",
"}",
"/* If context is an object, and value is `undefined`\n * change it to 'undefined' so it can be displayed\n * correctly in the report\n */",
"if",
"(",
"ctx",
".",
"title",
"&&",
"ctx",
".",
"value",
"===",
"undefined",
")",
"{",
"ctx",
".",
"value",
"=",
"'undefined'",
";",
"}",
"// Test doesn't already have context -> set it",
"if",
"(",
"!",
"test",
".",
"context",
")",
"{",
"test",
".",
"context",
"=",
"ctx",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"test",
".",
"context",
")",
")",
"{",
"// Test has context and context is an array -> push new context",
"test",
".",
"context",
".",
"push",
"(",
"ctx",
")",
";",
"}",
"else",
"{",
"// Test has context and it is not an array -> make it an array, then push new context",
"test",
".",
"context",
"=",
"[",
"test",
".",
"context",
"]",
";",
"test",
".",
"context",
".",
"push",
"(",
"ctx",
")",
";",
"}",
"}"
] |
Add context to the test object so it can
be displayed in the mochawesome report
@param {Object} test object
@param {String|Object} context to add
If context is an object, it must have the shape:
{
title: string that is used as context title in the report
value: the context that is to be added
}
Usage:
it('should test something', function () {
someFunctionThatTestsCode();
addContext(this, 'some context to add');
addContext(this, {
title: 'Expected number of something'
value: 42
});
assert('something');
});
|
[
"Add",
"context",
"to",
"the",
"test",
"object",
"so",
"it",
"can",
"be",
"displayed",
"in",
"the",
"mochawesome",
"report"
] |
ce0cafe0994f4226b1a63b7c14bad2c585193c70
|
https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/addContext.js#L70-L115
|
|
13,327
|
rethinkdb/horizon
|
client/src/index.js
|
sendRequest
|
function sendRequest(type, options) {
// Both remove and removeAll use the type 'remove' in the protocol
const normalizedType = type === 'removeAll' ? 'remove' : type
return socket
.hzRequest({ type: normalizedType, options }) // send the raw request
.takeWhile(resp => resp.state !== 'complete')
}
|
javascript
|
function sendRequest(type, options) {
// Both remove and removeAll use the type 'remove' in the protocol
const normalizedType = type === 'removeAll' ? 'remove' : type
return socket
.hzRequest({ type: normalizedType, options }) // send the raw request
.takeWhile(resp => resp.state !== 'complete')
}
|
[
"function",
"sendRequest",
"(",
"type",
",",
"options",
")",
"{",
"// Both remove and removeAll use the type 'remove' in the protocol",
"const",
"normalizedType",
"=",
"type",
"===",
"'removeAll'",
"?",
"'remove'",
":",
"type",
"return",
"socket",
".",
"hzRequest",
"(",
"{",
"type",
":",
"normalizedType",
",",
"options",
"}",
")",
"// send the raw request",
".",
"takeWhile",
"(",
"resp",
"=>",
"resp",
".",
"state",
"!==",
"'complete'",
")",
"}"
] |
Sends a horizon protocol request to the server, and pulls the data portion of the response out.
|
[
"Sends",
"a",
"horizon",
"protocol",
"request",
"to",
"the",
"server",
"and",
"pulls",
"the",
"data",
"portion",
"of",
"the",
"response",
"out",
"."
] |
6e16c613c8789e484bfc9309d9553a625a09608e
|
https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/client/src/index.js#L119-L125
|
13,328
|
rethinkdb/horizon
|
client/src/model.js
|
isPrimitive
|
function isPrimitive(value) {
if (value === null) {
return true
}
if (value === undefined) {
return false
}
if (typeof value === 'function') {
return false
}
if ([ 'boolean', 'number', 'string' ].indexOf(typeof value) !== -1) {
return true
}
if (value instanceof Date || value instanceof ArrayBuffer) {
return true
}
return false
}
|
javascript
|
function isPrimitive(value) {
if (value === null) {
return true
}
if (value === undefined) {
return false
}
if (typeof value === 'function') {
return false
}
if ([ 'boolean', 'number', 'string' ].indexOf(typeof value) !== -1) {
return true
}
if (value instanceof Date || value instanceof ArrayBuffer) {
return true
}
return false
}
|
[
"function",
"isPrimitive",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"===",
"null",
")",
"{",
"return",
"true",
"}",
"if",
"(",
"value",
"===",
"undefined",
")",
"{",
"return",
"false",
"}",
"if",
"(",
"typeof",
"value",
"===",
"'function'",
")",
"{",
"return",
"false",
"}",
"if",
"(",
"[",
"'boolean'",
",",
"'number'",
",",
"'string'",
"]",
".",
"indexOf",
"(",
"typeof",
"value",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"true",
"}",
"if",
"(",
"value",
"instanceof",
"Date",
"||",
"value",
"instanceof",
"ArrayBuffer",
")",
"{",
"return",
"true",
"}",
"return",
"false",
"}"
] |
Whether an object is primitive. We consider functions non-primitives, lump Dates and ArrayBuffers into primitives.
|
[
"Whether",
"an",
"object",
"is",
"primitive",
".",
"We",
"consider",
"functions",
"non",
"-",
"primitives",
"lump",
"Dates",
"and",
"ArrayBuffers",
"into",
"primitives",
"."
] |
6e16c613c8789e484bfc9309d9553a625a09608e
|
https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/client/src/model.js#L35-L52
|
13,329
|
rethinkdb/horizon
|
examples/cyclejs-chat-app/dist/app.js
|
model
|
function model(inputValue$, messages$) {
return Rx.Observable.combineLatest(
inputValue$.startWith(null),
messages$.startWith([]),
(inputValue, messages) => ({ messages, inputValue })
)
}
|
javascript
|
function model(inputValue$, messages$) {
return Rx.Observable.combineLatest(
inputValue$.startWith(null),
messages$.startWith([]),
(inputValue, messages) => ({ messages, inputValue })
)
}
|
[
"function",
"model",
"(",
"inputValue$",
",",
"messages$",
")",
"{",
"return",
"Rx",
".",
"Observable",
".",
"combineLatest",
"(",
"inputValue$",
".",
"startWith",
"(",
"null",
")",
",",
"messages$",
".",
"startWith",
"(",
"[",
"]",
")",
",",
"(",
"inputValue",
",",
"messages",
")",
"=>",
"(",
"{",
"messages",
",",
"inputValue",
"}",
")",
")",
"}"
] |
Model takes our action streams and turns them into the stream of app states
|
[
"Model",
"takes",
"our",
"action",
"streams",
"and",
"turns",
"them",
"into",
"the",
"stream",
"of",
"app",
"states"
] |
6e16c613c8789e484bfc9309d9553a625a09608e
|
https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/examples/cyclejs-chat-app/dist/app.js#L58-L64
|
13,330
|
rethinkdb/horizon
|
examples/cyclejs-chat-app/dist/app.js
|
view
|
function view(state$) {
// Displayed for each chat message.
function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
}
return state$.map(
state =>
div([
div('.row',
ul(state.messages.map(chatMessage))),
div('#input.row',
input('.u-full-width', { value: state.inputValue, autoFocus: true })),
])
)
}
|
javascript
|
function view(state$) {
// Displayed for each chat message.
function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
}
return state$.map(
state =>
div([
div('.row',
ul(state.messages.map(chatMessage))),
div('#input.row',
input('.u-full-width', { value: state.inputValue, autoFocus: true })),
])
)
}
|
[
"function",
"view",
"(",
"state$",
")",
"{",
"// Displayed for each chat message.",
"function",
"chatMessage",
"(",
"msg",
")",
"{",
"return",
"li",
"(",
"'.message'",
",",
"{",
"key",
":",
"msg",
".",
"id",
"}",
",",
"[",
"img",
"(",
"{",
"height",
":",
"'50'",
",",
"width",
":",
"'50'",
",",
"src",
":",
"`",
"${",
"msg",
".",
"authorId",
"}",
"`",
",",
"}",
")",
",",
"span",
"(",
"'.text'",
",",
"msg",
".",
"text",
")",
",",
"]",
")",
"}",
"return",
"state$",
".",
"map",
"(",
"state",
"=>",
"div",
"(",
"[",
"div",
"(",
"'.row'",
",",
"ul",
"(",
"state",
".",
"messages",
".",
"map",
"(",
"chatMessage",
")",
")",
")",
",",
"div",
"(",
"'#input.row'",
",",
"input",
"(",
"'.u-full-width'",
",",
"{",
"value",
":",
"state",
".",
"inputValue",
",",
"autoFocus",
":",
"true",
"}",
")",
")",
",",
"]",
")",
")",
"}"
] |
View takes the state and create a stream of virtual-dom trees for the app.
|
[
"View",
"takes",
"the",
"state",
"and",
"create",
"a",
"stream",
"of",
"virtual",
"-",
"dom",
"trees",
"for",
"the",
"app",
"."
] |
6e16c613c8789e484bfc9309d9553a625a09608e
|
https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/examples/cyclejs-chat-app/dist/app.js#L68-L89
|
13,331
|
rethinkdb/horizon
|
examples/cyclejs-chat-app/dist/app.js
|
chatMessage
|
function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
}
|
javascript
|
function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
}
|
[
"function",
"chatMessage",
"(",
"msg",
")",
"{",
"return",
"li",
"(",
"'.message'",
",",
"{",
"key",
":",
"msg",
".",
"id",
"}",
",",
"[",
"img",
"(",
"{",
"height",
":",
"'50'",
",",
"width",
":",
"'50'",
",",
"src",
":",
"`",
"${",
"msg",
".",
"authorId",
"}",
"`",
",",
"}",
")",
",",
"span",
"(",
"'.text'",
",",
"msg",
".",
"text",
")",
",",
"]",
")",
"}"
] |
Displayed for each chat message.
|
[
"Displayed",
"for",
"each",
"chat",
"message",
"."
] |
6e16c613c8789e484bfc9309d9553a625a09608e
|
https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/examples/cyclejs-chat-app/dist/app.js#L70-L78
|
13,332
|
rethinkdb/horizon
|
examples/cyclejs-chat-app/dist/app.js
|
main
|
function main(sources) {
const intents = intent(sources)
const state$ = model(intents.inputValue$, intents.messages$)
return {
// Send the virtual tree to the real DOM
DOM: view(state$),
// Send our messages to the horizon server
horizon: intents.writeOps$$,
}
}
|
javascript
|
function main(sources) {
const intents = intent(sources)
const state$ = model(intents.inputValue$, intents.messages$)
return {
// Send the virtual tree to the real DOM
DOM: view(state$),
// Send our messages to the horizon server
horizon: intents.writeOps$$,
}
}
|
[
"function",
"main",
"(",
"sources",
")",
"{",
"const",
"intents",
"=",
"intent",
"(",
"sources",
")",
"const",
"state$",
"=",
"model",
"(",
"intents",
".",
"inputValue$",
",",
"intents",
".",
"messages$",
")",
"return",
"{",
"// Send the virtual tree to the real DOM",
"DOM",
":",
"view",
"(",
"state$",
")",
",",
"// Send our messages to the horizon server",
"horizon",
":",
"intents",
".",
"writeOps$$",
",",
"}",
"}"
] |
In main we just wire everything together
|
[
"In",
"main",
"we",
"just",
"wire",
"everything",
"together"
] |
6e16c613c8789e484bfc9309d9553a625a09608e
|
https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/examples/cyclejs-chat-app/dist/app.js#L92-L101
|
13,333
|
rethinkdb/horizon
|
client/src/ast.js
|
makePresentable
|
function makePresentable(observable, query) {
// Whether the entire data structure is in each change
const pointQuery = Boolean(query.find)
if (pointQuery) {
let hasEmitted = false
const seedVal = null
// Simplest case: just pass through new_val
return observable
.filter(change => !hasEmitted || change.type !== 'state')
.scan((previous, change) => {
hasEmitted = true
if (change.new_val != null) {
delete change.new_val.$hz_v$
}
if (change.old_val != null) {
delete change.old_val.$hz_v$
}
if (change.state === 'synced') {
return previous
} else {
return change.new_val
}
}, seedVal)
} else {
const seedVal = { emitted: false, val: [] }
return observable
.scan((state, change) => {
if (change.new_val != null) {
delete change.new_val.$hz_v$
}
if (change.old_val != null) {
delete change.old_val.$hz_v$
}
if (change.state === 'synced') {
state.emitted = true
}
state.val = applyChange(state.val.slice(), change)
return state
}, seedVal)
.filter(state => state.emitted)
.map(x => x.val)
}
}
|
javascript
|
function makePresentable(observable, query) {
// Whether the entire data structure is in each change
const pointQuery = Boolean(query.find)
if (pointQuery) {
let hasEmitted = false
const seedVal = null
// Simplest case: just pass through new_val
return observable
.filter(change => !hasEmitted || change.type !== 'state')
.scan((previous, change) => {
hasEmitted = true
if (change.new_val != null) {
delete change.new_val.$hz_v$
}
if (change.old_val != null) {
delete change.old_val.$hz_v$
}
if (change.state === 'synced') {
return previous
} else {
return change.new_val
}
}, seedVal)
} else {
const seedVal = { emitted: false, val: [] }
return observable
.scan((state, change) => {
if (change.new_val != null) {
delete change.new_val.$hz_v$
}
if (change.old_val != null) {
delete change.old_val.$hz_v$
}
if (change.state === 'synced') {
state.emitted = true
}
state.val = applyChange(state.val.slice(), change)
return state
}, seedVal)
.filter(state => state.emitted)
.map(x => x.val)
}
}
|
[
"function",
"makePresentable",
"(",
"observable",
",",
"query",
")",
"{",
"// Whether the entire data structure is in each change",
"const",
"pointQuery",
"=",
"Boolean",
"(",
"query",
".",
"find",
")",
"if",
"(",
"pointQuery",
")",
"{",
"let",
"hasEmitted",
"=",
"false",
"const",
"seedVal",
"=",
"null",
"// Simplest case: just pass through new_val",
"return",
"observable",
".",
"filter",
"(",
"change",
"=>",
"!",
"hasEmitted",
"||",
"change",
".",
"type",
"!==",
"'state'",
")",
".",
"scan",
"(",
"(",
"previous",
",",
"change",
")",
"=>",
"{",
"hasEmitted",
"=",
"true",
"if",
"(",
"change",
".",
"new_val",
"!=",
"null",
")",
"{",
"delete",
"change",
".",
"new_val",
".",
"$hz_v$",
"}",
"if",
"(",
"change",
".",
"old_val",
"!=",
"null",
")",
"{",
"delete",
"change",
".",
"old_val",
".",
"$hz_v$",
"}",
"if",
"(",
"change",
".",
"state",
"===",
"'synced'",
")",
"{",
"return",
"previous",
"}",
"else",
"{",
"return",
"change",
".",
"new_val",
"}",
"}",
",",
"seedVal",
")",
"}",
"else",
"{",
"const",
"seedVal",
"=",
"{",
"emitted",
":",
"false",
",",
"val",
":",
"[",
"]",
"}",
"return",
"observable",
".",
"scan",
"(",
"(",
"state",
",",
"change",
")",
"=>",
"{",
"if",
"(",
"change",
".",
"new_val",
"!=",
"null",
")",
"{",
"delete",
"change",
".",
"new_val",
".",
"$hz_v$",
"}",
"if",
"(",
"change",
".",
"old_val",
"!=",
"null",
")",
"{",
"delete",
"change",
".",
"old_val",
".",
"$hz_v$",
"}",
"if",
"(",
"change",
".",
"state",
"===",
"'synced'",
")",
"{",
"state",
".",
"emitted",
"=",
"true",
"}",
"state",
".",
"val",
"=",
"applyChange",
"(",
"state",
".",
"val",
".",
"slice",
"(",
")",
",",
"change",
")",
"return",
"state",
"}",
",",
"seedVal",
")",
".",
"filter",
"(",
"state",
"=>",
"state",
".",
"emitted",
")",
".",
"map",
"(",
"x",
"=>",
"x",
".",
"val",
")",
"}",
"}"
] |
Turn a raw observable of server responses into user-presentable events `observable` is the base observable with full responses coming from the HorizonSocket `query` is the value of `options` in the request
|
[
"Turn",
"a",
"raw",
"observable",
"of",
"server",
"responses",
"into",
"user",
"-",
"presentable",
"events",
"observable",
"is",
"the",
"base",
"observable",
"with",
"full",
"responses",
"coming",
"from",
"the",
"HorizonSocket",
"query",
"is",
"the",
"value",
"of",
"options",
"in",
"the",
"request"
] |
6e16c613c8789e484bfc9309d9553a625a09608e
|
https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/client/src/ast.js#L140-L183
|
13,334
|
jabbany/CommentCoreLibrary
|
demo/scripting/sandbox.js
|
function(e){
if(e.keyCode === 9){
e.preventDefault();
var cursor = this.selectionStart;
var nv = this.value.substring(0,cursor),
bv = this.value.substring(cursor, this.value.length);;
this.value = nv + "\t" + bv;
this.setSelectionRange(cursor + 1, cursor + 1);
}
}
|
javascript
|
function(e){
if(e.keyCode === 9){
e.preventDefault();
var cursor = this.selectionStart;
var nv = this.value.substring(0,cursor),
bv = this.value.substring(cursor, this.value.length);;
this.value = nv + "\t" + bv;
this.setSelectionRange(cursor + 1, cursor + 1);
}
}
|
[
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"keyCode",
"===",
"9",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"cursor",
"=",
"this",
".",
"selectionStart",
";",
"var",
"nv",
"=",
"this",
".",
"value",
".",
"substring",
"(",
"0",
",",
"cursor",
")",
",",
"bv",
"=",
"this",
".",
"value",
".",
"substring",
"(",
"cursor",
",",
"this",
".",
"value",
".",
"length",
")",
";",
";",
"this",
".",
"value",
"=",
"nv",
"+",
"\"\\t\"",
"+",
"bv",
";",
"this",
".",
"setSelectionRange",
"(",
"cursor",
"+",
"1",
",",
"cursor",
"+",
"1",
")",
";",
"}",
"}"
] |
Hook tab keys
|
[
"Hook",
"tab",
"keys"
] |
5486e28e187cd4e490f129ec0cd9d07e6cf1b246
|
https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/demo/scripting/sandbox.js#L80-L89
|
|
13,335
|
jabbany/CommentCoreLibrary
|
dist/CommentCoreLibrary.js
|
_match
|
function _match (rule, cmtData) {
var path = rule.subject.split('.');
var extracted = cmtData;
while (path.length > 0) {
var item = path.shift();
if (item === '') {
continue;
}
if (extracted.hasOwnProperty(item)) {
extracted = extracted[item];
}
if (extracted === null || typeof extracted === 'undefined') {
extracted = null;
break;
}
}
if (extracted === null) {
// Null precondition implies anything
return true;
}
switch (rule.op) {
case '<':
return extracted < rule.value;
case '>':
return extracted > rule.value;
case '~':
case 'regexp':
return (new RegExp(rule.value)).test(extracted.toString());
case '=':
case 'eq':
return rule.value ===
((typeof extracted === 'number') ?
extracted : extracted.toString());
case '!':
case 'not':
return !_match(rule.value, extracted);
case '&&':
case 'and':
if (Array.isArray(rule.value)) {
return rule.value.every(function (r) {
return _match(r, extracted);
});
} else {
return false;
}
case '||':
case 'or':
if (Array.isArray(rule.value)) {
return rule.value.some(function (r) {
return _match(r, extracted);
});
} else {
return false;
}
default:
return false;
}
}
|
javascript
|
function _match (rule, cmtData) {
var path = rule.subject.split('.');
var extracted = cmtData;
while (path.length > 0) {
var item = path.shift();
if (item === '') {
continue;
}
if (extracted.hasOwnProperty(item)) {
extracted = extracted[item];
}
if (extracted === null || typeof extracted === 'undefined') {
extracted = null;
break;
}
}
if (extracted === null) {
// Null precondition implies anything
return true;
}
switch (rule.op) {
case '<':
return extracted < rule.value;
case '>':
return extracted > rule.value;
case '~':
case 'regexp':
return (new RegExp(rule.value)).test(extracted.toString());
case '=':
case 'eq':
return rule.value ===
((typeof extracted === 'number') ?
extracted : extracted.toString());
case '!':
case 'not':
return !_match(rule.value, extracted);
case '&&':
case 'and':
if (Array.isArray(rule.value)) {
return rule.value.every(function (r) {
return _match(r, extracted);
});
} else {
return false;
}
case '||':
case 'or':
if (Array.isArray(rule.value)) {
return rule.value.some(function (r) {
return _match(r, extracted);
});
} else {
return false;
}
default:
return false;
}
}
|
[
"function",
"_match",
"(",
"rule",
",",
"cmtData",
")",
"{",
"var",
"path",
"=",
"rule",
".",
"subject",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"extracted",
"=",
"cmtData",
";",
"while",
"(",
"path",
".",
"length",
">",
"0",
")",
"{",
"var",
"item",
"=",
"path",
".",
"shift",
"(",
")",
";",
"if",
"(",
"item",
"===",
"''",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"extracted",
".",
"hasOwnProperty",
"(",
"item",
")",
")",
"{",
"extracted",
"=",
"extracted",
"[",
"item",
"]",
";",
"}",
"if",
"(",
"extracted",
"===",
"null",
"||",
"typeof",
"extracted",
"===",
"'undefined'",
")",
"{",
"extracted",
"=",
"null",
";",
"break",
";",
"}",
"}",
"if",
"(",
"extracted",
"===",
"null",
")",
"{",
"// Null precondition implies anything",
"return",
"true",
";",
"}",
"switch",
"(",
"rule",
".",
"op",
")",
"{",
"case",
"'<'",
":",
"return",
"extracted",
"<",
"rule",
".",
"value",
";",
"case",
"'>'",
":",
"return",
"extracted",
">",
"rule",
".",
"value",
";",
"case",
"'~'",
":",
"case",
"'regexp'",
":",
"return",
"(",
"new",
"RegExp",
"(",
"rule",
".",
"value",
")",
")",
".",
"test",
"(",
"extracted",
".",
"toString",
"(",
")",
")",
";",
"case",
"'='",
":",
"case",
"'eq'",
":",
"return",
"rule",
".",
"value",
"===",
"(",
"(",
"typeof",
"extracted",
"===",
"'number'",
")",
"?",
"extracted",
":",
"extracted",
".",
"toString",
"(",
")",
")",
";",
"case",
"'!'",
":",
"case",
"'not'",
":",
"return",
"!",
"_match",
"(",
"rule",
".",
"value",
",",
"extracted",
")",
";",
"case",
"'&&'",
":",
"case",
"'and'",
":",
"if",
"(",
"Array",
".",
"isArray",
"(",
"rule",
".",
"value",
")",
")",
"{",
"return",
"rule",
".",
"value",
".",
"every",
"(",
"function",
"(",
"r",
")",
"{",
"return",
"_match",
"(",
"r",
",",
"extracted",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"case",
"'||'",
":",
"case",
"'or'",
":",
"if",
"(",
"Array",
".",
"isArray",
"(",
"rule",
".",
"value",
")",
")",
"{",
"return",
"rule",
".",
"value",
".",
"some",
"(",
"function",
"(",
"r",
")",
"{",
"return",
"_match",
"(",
"r",
",",
"extracted",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"default",
":",
"return",
"false",
";",
"}",
"}"
] |
Matches a rule against an input that could be the full or a subset of
the comment data.
@param rule - rule object to match
@param cmtData - full or portion of comment data
@return boolean indicator of match
|
[
"Matches",
"a",
"rule",
"against",
"an",
"input",
"that",
"could",
"be",
"the",
"full",
"or",
"a",
"subset",
"of",
"the",
"comment",
"data",
"."
] |
5486e28e187cd4e490f129ec0cd9d07e6cf1b246
|
https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/dist/CommentCoreLibrary.js#L1266-L1323
|
13,336
|
jabbany/CommentCoreLibrary
|
dist/CommentCoreLibrary.js
|
CommentFilter
|
function CommentFilter() {
this.rules = [];
this.modifiers = [];
this.allowUnknownTypes = true;
this.allowTypes = {
'1': true,
'2': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'17': true
};
}
|
javascript
|
function CommentFilter() {
this.rules = [];
this.modifiers = [];
this.allowUnknownTypes = true;
this.allowTypes = {
'1': true,
'2': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'17': true
};
}
|
[
"function",
"CommentFilter",
"(",
")",
"{",
"this",
".",
"rules",
"=",
"[",
"]",
";",
"this",
".",
"modifiers",
"=",
"[",
"]",
";",
"this",
".",
"allowUnknownTypes",
"=",
"true",
";",
"this",
".",
"allowTypes",
"=",
"{",
"'1'",
":",
"true",
",",
"'2'",
":",
"true",
",",
"'4'",
":",
"true",
",",
"'5'",
":",
"true",
",",
"'6'",
":",
"true",
",",
"'7'",
":",
"true",
",",
"'8'",
":",
"true",
",",
"'17'",
":",
"true",
"}",
";",
"}"
] |
Constructor for CommentFilter
@constructor
|
[
"Constructor",
"for",
"CommentFilter"
] |
5486e28e187cd4e490f129ec0cd9d07e6cf1b246
|
https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/dist/CommentCoreLibrary.js#L1329-L1343
|
13,337
|
jabbany/CommentCoreLibrary
|
dist/CommentCoreLibrary.js
|
function (text) {
if (text.charAt(0) === '[') {
switch (text.charAt(text.length - 1)) {
case ']':
return text;
case '"':
return text + ']';
case ',':
return text.substring(0, text.length - 1) + '"]';
default:
return _formatmode7(text.substring(0, text.length - 1));
}
} else {
return text;
}
}
|
javascript
|
function (text) {
if (text.charAt(0) === '[') {
switch (text.charAt(text.length - 1)) {
case ']':
return text;
case '"':
return text + ']';
case ',':
return text.substring(0, text.length - 1) + '"]';
default:
return _formatmode7(text.substring(0, text.length - 1));
}
} else {
return text;
}
}
|
[
"function",
"(",
"text",
")",
"{",
"if",
"(",
"text",
".",
"charAt",
"(",
"0",
")",
"===",
"'['",
")",
"{",
"switch",
"(",
"text",
".",
"charAt",
"(",
"text",
".",
"length",
"-",
"1",
")",
")",
"{",
"case",
"']'",
":",
"return",
"text",
";",
"case",
"'\"'",
":",
"return",
"text",
"+",
"']'",
";",
"case",
"','",
":",
"return",
"text",
".",
"substring",
"(",
"0",
",",
"text",
".",
"length",
"-",
"1",
")",
"+",
"'\"]'",
";",
"default",
":",
"return",
"_formatmode7",
"(",
"text",
".",
"substring",
"(",
"0",
",",
"text",
".",
"length",
"-",
"1",
")",
")",
";",
"}",
"}",
"else",
"{",
"return",
"text",
";",
"}",
"}"
] |
Fix Mode7 comments when they are bad
|
[
"Fix",
"Mode7",
"comments",
"when",
"they",
"are",
"bad"
] |
5486e28e187cd4e490f129ec0cd9d07e6cf1b246
|
https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/dist/CommentCoreLibrary.js#L1863-L1878
|
|
13,338
|
jabbany/CommentCoreLibrary
|
dist/CommentCoreLibrary.js
|
function (text) {
text = text.replace(new RegExp('</([^d])','g'), '</disabled $1');
text = text.replace(new RegExp('</(\S{2,})','g'), '</disabled $1');
text = text.replace(new RegExp('<([^d/]\W*?)','g'), '<disabled $1');
text = text.replace(new RegExp('<([^/ ]{2,}\W*?)','g'), '<disabled $1');
return text;
}
|
javascript
|
function (text) {
text = text.replace(new RegExp('</([^d])','g'), '</disabled $1');
text = text.replace(new RegExp('</(\S{2,})','g'), '</disabled $1');
text = text.replace(new RegExp('<([^d/]\W*?)','g'), '<disabled $1');
text = text.replace(new RegExp('<([^/ ]{2,}\W*?)','g'), '<disabled $1');
return text;
}
|
[
"function",
"(",
"text",
")",
"{",
"text",
"=",
"text",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'</([^d])'",
",",
"'g'",
")",
",",
"'</disabled $1'",
")",
";",
"text",
"=",
"text",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'</(\\S{2,})'",
",",
"'g'",
")",
",",
"'</disabled $1'",
")",
";",
"text",
"=",
"text",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'<([^d/]\\W*?)'",
",",
"'g'",
")",
",",
"'<disabled $1'",
")",
";",
"text",
"=",
"text",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'<([^/ ]{2,}\\W*?)'",
",",
"'g'",
")",
",",
"'<disabled $1'",
")",
";",
"return",
"text",
";",
"}"
] |
Try to escape unsafe HTML code. DO NOT trust that this handles all cases Please do not allow insecure DOM parsing unless you can trust your input source.
|
[
"Try",
"to",
"escape",
"unsafe",
"HTML",
"code",
".",
"DO",
"NOT",
"trust",
"that",
"this",
"handles",
"all",
"cases",
"Please",
"do",
"not",
"allow",
"insecure",
"DOM",
"parsing",
"unless",
"you",
"can",
"trust",
"your",
"input",
"source",
"."
] |
5486e28e187cd4e490f129ec0cd9d07e6cf1b246
|
https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/dist/CommentCoreLibrary.js#L1882-L1888
|
|
13,339
|
puleos/object-hash
|
index.js
|
isNativeFunction
|
function isNativeFunction(f) {
if ((typeof f) !== 'function') {
return false;
}
var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
return exp.exec(Function.prototype.toString.call(f)) != null;
}
|
javascript
|
function isNativeFunction(f) {
if ((typeof f) !== 'function') {
return false;
}
var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
return exp.exec(Function.prototype.toString.call(f)) != null;
}
|
[
"function",
"isNativeFunction",
"(",
"f",
")",
"{",
"if",
"(",
"(",
"typeof",
"f",
")",
"!==",
"'function'",
")",
"{",
"return",
"false",
";",
"}",
"var",
"exp",
"=",
"/",
"^function\\s+\\w*\\s*\\(\\s*\\)\\s*{\\s+\\[native code\\]\\s+}$",
"/",
"i",
";",
"return",
"exp",
".",
"exec",
"(",
"Function",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"f",
")",
")",
"!=",
"null",
";",
"}"
] |
Check if the given function is a native function
|
[
"Check",
"if",
"the",
"given",
"function",
"is",
"a",
"native",
"function"
] |
c70080cc88b4b54abffe723659bde530474f1d17
|
https://github.com/puleos/object-hash/blob/c70080cc88b4b54abffe723659bde530474f1d17/index.js#L105-L111
|
13,340
|
puleos/object-hash
|
index.js
|
PassThrough
|
function PassThrough() {
return {
buf: '',
write: function(b) {
this.buf += b;
},
end: function(b) {
this.buf += b;
},
read: function() {
return this.buf;
}
};
}
|
javascript
|
function PassThrough() {
return {
buf: '',
write: function(b) {
this.buf += b;
},
end: function(b) {
this.buf += b;
},
read: function() {
return this.buf;
}
};
}
|
[
"function",
"PassThrough",
"(",
")",
"{",
"return",
"{",
"buf",
":",
"''",
",",
"write",
":",
"function",
"(",
"b",
")",
"{",
"this",
".",
"buf",
"+=",
"b",
";",
"}",
",",
"end",
":",
"function",
"(",
"b",
")",
"{",
"this",
".",
"buf",
"+=",
"b",
";",
"}",
",",
"read",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"buf",
";",
"}",
"}",
";",
"}"
] |
Mini-implementation of stream.PassThrough We are far from having need for the full implementation, and we can make assumptions like "many writes, then only one final read" and we can ignore encoding specifics
|
[
"Mini",
"-",
"implementation",
"of",
"stream",
".",
"PassThrough",
"We",
"are",
"far",
"from",
"having",
"need",
"for",
"the",
"full",
"implementation",
"and",
"we",
"can",
"make",
"assumptions",
"like",
"many",
"writes",
"then",
"only",
"one",
"final",
"read",
"and",
"we",
"can",
"ignore",
"encoding",
"specifics"
] |
c70080cc88b4b54abffe723659bde530474f1d17
|
https://github.com/puleos/object-hash/blob/c70080cc88b4b54abffe723659bde530474f1d17/index.js#L425-L441
|
13,341
|
schteppe/poly-decomp.js
|
src/index.js
|
lineInt
|
function lineInt(l1,l2,precision){
precision = precision || 0;
var i = [0,0]; // point
var a1, b1, c1, a2, b2, c2, det; // scalars
a1 = l1[1][1] - l1[0][1];
b1 = l1[0][0] - l1[1][0];
c1 = a1 * l1[0][0] + b1 * l1[0][1];
a2 = l2[1][1] - l2[0][1];
b2 = l2[0][0] - l2[1][0];
c2 = a2 * l2[0][0] + b2 * l2[0][1];
det = a1 * b2 - a2*b1;
if (!scalar_eq(det, 0, precision)) { // lines are not parallel
i[0] = (b2 * c1 - b1 * c2) / det;
i[1] = (a1 * c2 - a2 * c1) / det;
}
return i;
}
|
javascript
|
function lineInt(l1,l2,precision){
precision = precision || 0;
var i = [0,0]; // point
var a1, b1, c1, a2, b2, c2, det; // scalars
a1 = l1[1][1] - l1[0][1];
b1 = l1[0][0] - l1[1][0];
c1 = a1 * l1[0][0] + b1 * l1[0][1];
a2 = l2[1][1] - l2[0][1];
b2 = l2[0][0] - l2[1][0];
c2 = a2 * l2[0][0] + b2 * l2[0][1];
det = a1 * b2 - a2*b1;
if (!scalar_eq(det, 0, precision)) { // lines are not parallel
i[0] = (b2 * c1 - b1 * c2) / det;
i[1] = (a1 * c2 - a2 * c1) / det;
}
return i;
}
|
[
"function",
"lineInt",
"(",
"l1",
",",
"l2",
",",
"precision",
")",
"{",
"precision",
"=",
"precision",
"||",
"0",
";",
"var",
"i",
"=",
"[",
"0",
",",
"0",
"]",
";",
"// point",
"var",
"a1",
",",
"b1",
",",
"c1",
",",
"a2",
",",
"b2",
",",
"c2",
",",
"det",
";",
"// scalars",
"a1",
"=",
"l1",
"[",
"1",
"]",
"[",
"1",
"]",
"-",
"l1",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"b1",
"=",
"l1",
"[",
"0",
"]",
"[",
"0",
"]",
"-",
"l1",
"[",
"1",
"]",
"[",
"0",
"]",
";",
"c1",
"=",
"a1",
"*",
"l1",
"[",
"0",
"]",
"[",
"0",
"]",
"+",
"b1",
"*",
"l1",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"a2",
"=",
"l2",
"[",
"1",
"]",
"[",
"1",
"]",
"-",
"l2",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"b2",
"=",
"l2",
"[",
"0",
"]",
"[",
"0",
"]",
"-",
"l2",
"[",
"1",
"]",
"[",
"0",
"]",
";",
"c2",
"=",
"a2",
"*",
"l2",
"[",
"0",
"]",
"[",
"0",
"]",
"+",
"b2",
"*",
"l2",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"det",
"=",
"a1",
"*",
"b2",
"-",
"a2",
"*",
"b1",
";",
"if",
"(",
"!",
"scalar_eq",
"(",
"det",
",",
"0",
",",
"precision",
")",
")",
"{",
"// lines are not parallel",
"i",
"[",
"0",
"]",
"=",
"(",
"b2",
"*",
"c1",
"-",
"b1",
"*",
"c2",
")",
"/",
"det",
";",
"i",
"[",
"1",
"]",
"=",
"(",
"a1",
"*",
"c2",
"-",
"a2",
"*",
"c1",
")",
"/",
"det",
";",
"}",
"return",
"i",
";",
"}"
] |
Compute the intersection between two lines.
@static
@method lineInt
@param {Array} l1 Line vector 1
@param {Array} l2 Line vector 2
@param {Number} precision Precision to use when checking if the lines are parallel
@return {Array} The intersection point.
|
[
"Compute",
"the",
"intersection",
"between",
"two",
"lines",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L19-L35
|
13,342
|
schteppe/poly-decomp.js
|
src/index.js
|
lineSegmentsIntersect
|
function lineSegmentsIntersect(p1, p2, q1, q2){
var dx = p2[0] - p1[0];
var dy = p2[1] - p1[1];
var da = q2[0] - q1[0];
var db = q2[1] - q1[1];
// segments are parallel
if((da*dy - db*dx) === 0){
return false;
}
var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx);
var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy);
return (s>=0 && s<=1 && t>=0 && t<=1);
}
|
javascript
|
function lineSegmentsIntersect(p1, p2, q1, q2){
var dx = p2[0] - p1[0];
var dy = p2[1] - p1[1];
var da = q2[0] - q1[0];
var db = q2[1] - q1[1];
// segments are parallel
if((da*dy - db*dx) === 0){
return false;
}
var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx);
var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy);
return (s>=0 && s<=1 && t>=0 && t<=1);
}
|
[
"function",
"lineSegmentsIntersect",
"(",
"p1",
",",
"p2",
",",
"q1",
",",
"q2",
")",
"{",
"var",
"dx",
"=",
"p2",
"[",
"0",
"]",
"-",
"p1",
"[",
"0",
"]",
";",
"var",
"dy",
"=",
"p2",
"[",
"1",
"]",
"-",
"p1",
"[",
"1",
"]",
";",
"var",
"da",
"=",
"q2",
"[",
"0",
"]",
"-",
"q1",
"[",
"0",
"]",
";",
"var",
"db",
"=",
"q2",
"[",
"1",
"]",
"-",
"q1",
"[",
"1",
"]",
";",
"// segments are parallel",
"if",
"(",
"(",
"da",
"*",
"dy",
"-",
"db",
"*",
"dx",
")",
"===",
"0",
")",
"{",
"return",
"false",
";",
"}",
"var",
"s",
"=",
"(",
"dx",
"*",
"(",
"q1",
"[",
"1",
"]",
"-",
"p1",
"[",
"1",
"]",
")",
"+",
"dy",
"*",
"(",
"p1",
"[",
"0",
"]",
"-",
"q1",
"[",
"0",
"]",
")",
")",
"/",
"(",
"da",
"*",
"dy",
"-",
"db",
"*",
"dx",
")",
";",
"var",
"t",
"=",
"(",
"da",
"*",
"(",
"p1",
"[",
"1",
"]",
"-",
"q1",
"[",
"1",
"]",
")",
"+",
"db",
"*",
"(",
"q1",
"[",
"0",
"]",
"-",
"p1",
"[",
"0",
"]",
")",
")",
"/",
"(",
"db",
"*",
"dx",
"-",
"da",
"*",
"dy",
")",
";",
"return",
"(",
"s",
">=",
"0",
"&&",
"s",
"<=",
"1",
"&&",
"t",
">=",
"0",
"&&",
"t",
"<=",
"1",
")",
";",
"}"
] |
Checks if two line segments intersects.
@method segmentsIntersect
@param {Array} p1 The start vertex of the first line segment.
@param {Array} p2 The end vertex of the first line segment.
@param {Array} q1 The start vertex of the second line segment.
@param {Array} q2 The end vertex of the second line segment.
@return {Boolean} True if the two line segments intersect
|
[
"Checks",
"if",
"two",
"line",
"segments",
"intersects",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L46-L61
|
13,343
|
schteppe/poly-decomp.js
|
src/index.js
|
triangleArea
|
function triangleArea(a,b,c){
return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])));
}
|
javascript
|
function triangleArea(a,b,c){
return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])));
}
|
[
"function",
"triangleArea",
"(",
"a",
",",
"b",
",",
"c",
")",
"{",
"return",
"(",
"(",
"(",
"b",
"[",
"0",
"]",
"-",
"a",
"[",
"0",
"]",
")",
"*",
"(",
"c",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
")",
")",
"-",
"(",
"(",
"c",
"[",
"0",
"]",
"-",
"a",
"[",
"0",
"]",
")",
"*",
"(",
"b",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
")",
")",
")",
";",
"}"
] |
Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order.
@static
@method area
@param {Array} a
@param {Array} b
@param {Array} c
@return {Number}
|
[
"Get",
"the",
"area",
"of",
"a",
"triangle",
"spanned",
"by",
"the",
"three",
"given",
"points",
".",
"Note",
"that",
"the",
"area",
"will",
"be",
"negative",
"if",
"the",
"points",
"are",
"not",
"given",
"in",
"counter",
"-",
"clockwise",
"order",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L72-L74
|
13,344
|
schteppe/poly-decomp.js
|
src/index.js
|
collinear
|
function collinear(a,b,c,thresholdAngle) {
if(!thresholdAngle){
return triangleArea(a, b, c) === 0;
} else {
var ab = tmpPoint1,
bc = tmpPoint2;
ab[0] = b[0]-a[0];
ab[1] = b[1]-a[1];
bc[0] = c[0]-b[0];
bc[1] = c[1]-b[1];
var dot = ab[0]*bc[0] + ab[1]*bc[1],
magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]),
magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]),
angle = Math.acos(dot/(magA*magB));
return angle < thresholdAngle;
}
}
|
javascript
|
function collinear(a,b,c,thresholdAngle) {
if(!thresholdAngle){
return triangleArea(a, b, c) === 0;
} else {
var ab = tmpPoint1,
bc = tmpPoint2;
ab[0] = b[0]-a[0];
ab[1] = b[1]-a[1];
bc[0] = c[0]-b[0];
bc[1] = c[1]-b[1];
var dot = ab[0]*bc[0] + ab[1]*bc[1],
magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]),
magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]),
angle = Math.acos(dot/(magA*magB));
return angle < thresholdAngle;
}
}
|
[
"function",
"collinear",
"(",
"a",
",",
"b",
",",
"c",
",",
"thresholdAngle",
")",
"{",
"if",
"(",
"!",
"thresholdAngle",
")",
"{",
"return",
"triangleArea",
"(",
"a",
",",
"b",
",",
"c",
")",
"===",
"0",
";",
"}",
"else",
"{",
"var",
"ab",
"=",
"tmpPoint1",
",",
"bc",
"=",
"tmpPoint2",
";",
"ab",
"[",
"0",
"]",
"=",
"b",
"[",
"0",
"]",
"-",
"a",
"[",
"0",
"]",
";",
"ab",
"[",
"1",
"]",
"=",
"b",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
";",
"bc",
"[",
"0",
"]",
"=",
"c",
"[",
"0",
"]",
"-",
"b",
"[",
"0",
"]",
";",
"bc",
"[",
"1",
"]",
"=",
"c",
"[",
"1",
"]",
"-",
"b",
"[",
"1",
"]",
";",
"var",
"dot",
"=",
"ab",
"[",
"0",
"]",
"*",
"bc",
"[",
"0",
"]",
"+",
"ab",
"[",
"1",
"]",
"*",
"bc",
"[",
"1",
"]",
",",
"magA",
"=",
"Math",
".",
"sqrt",
"(",
"ab",
"[",
"0",
"]",
"*",
"ab",
"[",
"0",
"]",
"+",
"ab",
"[",
"1",
"]",
"*",
"ab",
"[",
"1",
"]",
")",
",",
"magB",
"=",
"Math",
".",
"sqrt",
"(",
"bc",
"[",
"0",
"]",
"*",
"bc",
"[",
"0",
"]",
"+",
"bc",
"[",
"1",
"]",
"*",
"bc",
"[",
"1",
"]",
")",
",",
"angle",
"=",
"Math",
".",
"acos",
"(",
"dot",
"/",
"(",
"magA",
"*",
"magB",
")",
")",
";",
"return",
"angle",
"<",
"thresholdAngle",
";",
"}",
"}"
] |
Check if three points are collinear
@method collinear
@param {Array} a
@param {Array} b
@param {Array} c
@param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision.
@return {Boolean}
|
[
"Check",
"if",
"three",
"points",
"are",
"collinear"
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L104-L122
|
13,345
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonAt
|
function polygonAt(polygon, i){
var s = polygon.length;
return polygon[i < 0 ? i % s + s : i % s];
}
|
javascript
|
function polygonAt(polygon, i){
var s = polygon.length;
return polygon[i < 0 ? i % s + s : i % s];
}
|
[
"function",
"polygonAt",
"(",
"polygon",
",",
"i",
")",
"{",
"var",
"s",
"=",
"polygon",
".",
"length",
";",
"return",
"polygon",
"[",
"i",
"<",
"0",
"?",
"i",
"%",
"s",
"+",
"s",
":",
"i",
"%",
"s",
"]",
";",
"}"
] |
Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle.
@method at
@param {Number} i
@return {Array}
|
[
"Get",
"a",
"vertex",
"at",
"position",
"i",
".",
"It",
"does",
"not",
"matter",
"if",
"i",
"is",
"out",
"of",
"bounds",
"this",
"function",
"will",
"just",
"cycle",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L136-L139
|
13,346
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonAppend
|
function polygonAppend(polygon, poly, from, to){
for(var i=from; i<to; i++){
polygon.push(poly[i]);
}
}
|
javascript
|
function polygonAppend(polygon, poly, from, to){
for(var i=from; i<to; i++){
polygon.push(poly[i]);
}
}
|
[
"function",
"polygonAppend",
"(",
"polygon",
",",
"poly",
",",
"from",
",",
"to",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"from",
";",
"i",
"<",
"to",
";",
"i",
"++",
")",
"{",
"polygon",
".",
"push",
"(",
"poly",
"[",
"i",
"]",
")",
";",
"}",
"}"
] |
Append points "from" to "to"-1 from an other polygon "poly" onto this one.
@method append
@param {Polygon} poly The polygon to get points from.
@param {Number} from The vertex index in "poly".
@param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending.
@return {Array}
|
[
"Append",
"points",
"from",
"to",
"to",
"-",
"1",
"from",
"an",
"other",
"polygon",
"poly",
"onto",
"this",
"one",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L158-L162
|
13,347
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonMakeCCW
|
function polygonMakeCCW(polygon){
var br = 0,
v = polygon;
// find bottom right point
for (var i = 1; i < polygon.length; ++i) {
if (v[i][1] < v[br][1] || (v[i][1] === v[br][1] && v[i][0] > v[br][0])) {
br = i;
}
}
// reverse poly if clockwise
if (!isLeft(polygonAt(polygon, br - 1), polygonAt(polygon, br), polygonAt(polygon, br + 1))) {
polygonReverse(polygon);
return true;
} else {
return false;
}
}
|
javascript
|
function polygonMakeCCW(polygon){
var br = 0,
v = polygon;
// find bottom right point
for (var i = 1; i < polygon.length; ++i) {
if (v[i][1] < v[br][1] || (v[i][1] === v[br][1] && v[i][0] > v[br][0])) {
br = i;
}
}
// reverse poly if clockwise
if (!isLeft(polygonAt(polygon, br - 1), polygonAt(polygon, br), polygonAt(polygon, br + 1))) {
polygonReverse(polygon);
return true;
} else {
return false;
}
}
|
[
"function",
"polygonMakeCCW",
"(",
"polygon",
")",
"{",
"var",
"br",
"=",
"0",
",",
"v",
"=",
"polygon",
";",
"// find bottom right point",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"polygon",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"v",
"[",
"i",
"]",
"[",
"1",
"]",
"<",
"v",
"[",
"br",
"]",
"[",
"1",
"]",
"||",
"(",
"v",
"[",
"i",
"]",
"[",
"1",
"]",
"===",
"v",
"[",
"br",
"]",
"[",
"1",
"]",
"&&",
"v",
"[",
"i",
"]",
"[",
"0",
"]",
">",
"v",
"[",
"br",
"]",
"[",
"0",
"]",
")",
")",
"{",
"br",
"=",
"i",
";",
"}",
"}",
"// reverse poly if clockwise",
"if",
"(",
"!",
"isLeft",
"(",
"polygonAt",
"(",
"polygon",
",",
"br",
"-",
"1",
")",
",",
"polygonAt",
"(",
"polygon",
",",
"br",
")",
",",
"polygonAt",
"(",
"polygon",
",",
"br",
"+",
"1",
")",
")",
")",
"{",
"polygonReverse",
"(",
"polygon",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] |
Make sure that the polygon vertices are ordered counter-clockwise.
@method makeCCW
|
[
"Make",
"sure",
"that",
"the",
"polygon",
"vertices",
"are",
"ordered",
"counter",
"-",
"clockwise",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L168-L186
|
13,348
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonReverse
|
function polygonReverse(polygon){
var tmp = [];
var N = polygon.length;
for(var i=0; i!==N; i++){
tmp.push(polygon.pop());
}
for(var i=0; i!==N; i++){
polygon[i] = tmp[i];
}
}
|
javascript
|
function polygonReverse(polygon){
var tmp = [];
var N = polygon.length;
for(var i=0; i!==N; i++){
tmp.push(polygon.pop());
}
for(var i=0; i!==N; i++){
polygon[i] = tmp[i];
}
}
|
[
"function",
"polygonReverse",
"(",
"polygon",
")",
"{",
"var",
"tmp",
"=",
"[",
"]",
";",
"var",
"N",
"=",
"polygon",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"!==",
"N",
";",
"i",
"++",
")",
"{",
"tmp",
".",
"push",
"(",
"polygon",
".",
"pop",
"(",
")",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"!==",
"N",
";",
"i",
"++",
")",
"{",
"polygon",
"[",
"i",
"]",
"=",
"tmp",
"[",
"i",
"]",
";",
"}",
"}"
] |
Reverse the vertices in the polygon
@method reverse
|
[
"Reverse",
"the",
"vertices",
"in",
"the",
"polygon"
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L192-L201
|
13,349
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonIsReflex
|
function polygonIsReflex(polygon, i){
return isRight(polygonAt(polygon, i - 1), polygonAt(polygon, i), polygonAt(polygon, i + 1));
}
|
javascript
|
function polygonIsReflex(polygon, i){
return isRight(polygonAt(polygon, i - 1), polygonAt(polygon, i), polygonAt(polygon, i + 1));
}
|
[
"function",
"polygonIsReflex",
"(",
"polygon",
",",
"i",
")",
"{",
"return",
"isRight",
"(",
"polygonAt",
"(",
"polygon",
",",
"i",
"-",
"1",
")",
",",
"polygonAt",
"(",
"polygon",
",",
"i",
")",
",",
"polygonAt",
"(",
"polygon",
",",
"i",
"+",
"1",
")",
")",
";",
"}"
] |
Check if a point in the polygon is a reflex point
@method isReflex
@param {Number} i
@return {Boolean}
|
[
"Check",
"if",
"a",
"point",
"in",
"the",
"polygon",
"is",
"a",
"reflex",
"point"
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L209-L211
|
13,350
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonCopy
|
function polygonCopy(polygon, i,j,targetPoly){
var p = targetPoly || [];
polygonClear(p);
if (i < j) {
// Insert all vertices from i to j
for(var k=i; k<=j; k++){
p.push(polygon[k]);
}
} else {
// Insert vertices 0 to j
for(var k=0; k<=j; k++){
p.push(polygon[k]);
}
// Insert vertices i to end
for(var k=i; k<polygon.length; k++){
p.push(polygon[k]);
}
}
return p;
}
|
javascript
|
function polygonCopy(polygon, i,j,targetPoly){
var p = targetPoly || [];
polygonClear(p);
if (i < j) {
// Insert all vertices from i to j
for(var k=i; k<=j; k++){
p.push(polygon[k]);
}
} else {
// Insert vertices 0 to j
for(var k=0; k<=j; k++){
p.push(polygon[k]);
}
// Insert vertices i to end
for(var k=i; k<polygon.length; k++){
p.push(polygon[k]);
}
}
return p;
}
|
[
"function",
"polygonCopy",
"(",
"polygon",
",",
"i",
",",
"j",
",",
"targetPoly",
")",
"{",
"var",
"p",
"=",
"targetPoly",
"||",
"[",
"]",
";",
"polygonClear",
"(",
"p",
")",
";",
"if",
"(",
"i",
"<",
"j",
")",
"{",
"// Insert all vertices from i to j",
"for",
"(",
"var",
"k",
"=",
"i",
";",
"k",
"<=",
"j",
";",
"k",
"++",
")",
"{",
"p",
".",
"push",
"(",
"polygon",
"[",
"k",
"]",
")",
";",
"}",
"}",
"else",
"{",
"// Insert vertices 0 to j",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
"<=",
"j",
";",
"k",
"++",
")",
"{",
"p",
".",
"push",
"(",
"polygon",
"[",
"k",
"]",
")",
";",
"}",
"// Insert vertices i to end",
"for",
"(",
"var",
"k",
"=",
"i",
";",
"k",
"<",
"polygon",
".",
"length",
";",
"k",
"++",
")",
"{",
"p",
".",
"push",
"(",
"polygon",
"[",
"k",
"]",
")",
";",
"}",
"}",
"return",
"p",
";",
"}"
] |
Copy the polygon from vertex i to vertex j.
@method copy
@param {Number} i
@param {Number} j
@param {Polygon} [targetPoly] Optional target polygon to save in.
@return {Polygon} The resulting copy.
|
[
"Copy",
"the",
"polygon",
"from",
"vertex",
"i",
"to",
"vertex",
"j",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L278-L301
|
13,351
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonDecomp
|
function polygonDecomp(polygon){
var edges = polygonGetCutEdges(polygon);
if(edges.length > 0){
return polygonSlice(polygon, edges);
} else {
return [polygon];
}
}
|
javascript
|
function polygonDecomp(polygon){
var edges = polygonGetCutEdges(polygon);
if(edges.length > 0){
return polygonSlice(polygon, edges);
} else {
return [polygon];
}
}
|
[
"function",
"polygonDecomp",
"(",
"polygon",
")",
"{",
"var",
"edges",
"=",
"polygonGetCutEdges",
"(",
"polygon",
")",
";",
"if",
"(",
"edges",
".",
"length",
">",
"0",
")",
"{",
"return",
"polygonSlice",
"(",
"polygon",
",",
"edges",
")",
";",
"}",
"else",
"{",
"return",
"[",
"polygon",
"]",
";",
"}",
"}"
] |
Decomposes the polygon into one or more convex sub-Polygons.
@method decomp
@return {Array} An array or Polygon objects.
|
[
"Decomposes",
"the",
"polygon",
"into",
"one",
"or",
"more",
"convex",
"sub",
"-",
"Polygons",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L342-L349
|
13,352
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonIsSimple
|
function polygonIsSimple(polygon){
var path = polygon, i;
// Check
for(i=0; i<path.length-1; i++){
for(var j=0; j<i-1; j++){
if(lineSegmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
return false;
}
}
}
// Check the segment between the last and the first point to all others
for(i=1; i<path.length-2; i++){
if(lineSegmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){
return false;
}
}
return true;
}
|
javascript
|
function polygonIsSimple(polygon){
var path = polygon, i;
// Check
for(i=0; i<path.length-1; i++){
for(var j=0; j<i-1; j++){
if(lineSegmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
return false;
}
}
}
// Check the segment between the last and the first point to all others
for(i=1; i<path.length-2; i++){
if(lineSegmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){
return false;
}
}
return true;
}
|
[
"function",
"polygonIsSimple",
"(",
"polygon",
")",
"{",
"var",
"path",
"=",
"polygon",
",",
"i",
";",
"// Check",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"path",
".",
"length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"i",
"-",
"1",
";",
"j",
"++",
")",
"{",
"if",
"(",
"lineSegmentsIntersect",
"(",
"path",
"[",
"i",
"]",
",",
"path",
"[",
"i",
"+",
"1",
"]",
",",
"path",
"[",
"j",
"]",
",",
"path",
"[",
"j",
"+",
"1",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"// Check the segment between the last and the first point to all others",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<",
"path",
".",
"length",
"-",
"2",
";",
"i",
"++",
")",
"{",
"if",
"(",
"lineSegmentsIntersect",
"(",
"path",
"[",
"0",
"]",
",",
"path",
"[",
"path",
".",
"length",
"-",
"1",
"]",
",",
"path",
"[",
"i",
"]",
",",
"path",
"[",
"i",
"+",
"1",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Checks that the line segments of this polygon do not intersect each other.
@method isSimple
@param {Array} path An array of vertices e.g. [[0,0],[0,1],...]
@return {Boolean}
@todo Should it check all segments with all others?
|
[
"Checks",
"that",
"the",
"line",
"segments",
"of",
"this",
"polygon",
"do",
"not",
"intersect",
"each",
"other",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L404-L423
|
13,353
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonRemoveCollinearPoints
|
function polygonRemoveCollinearPoints(polygon, precision){
var num = 0;
for(var i=polygon.length-1; polygon.length>3 && i>=0; --i){
if(collinear(polygonAt(polygon, i-1),polygonAt(polygon, i),polygonAt(polygon, i+1),precision)){
// Remove the middle point
polygon.splice(i%polygon.length,1);
num++;
}
}
return num;
}
|
javascript
|
function polygonRemoveCollinearPoints(polygon, precision){
var num = 0;
for(var i=polygon.length-1; polygon.length>3 && i>=0; --i){
if(collinear(polygonAt(polygon, i-1),polygonAt(polygon, i),polygonAt(polygon, i+1),precision)){
// Remove the middle point
polygon.splice(i%polygon.length,1);
num++;
}
}
return num;
}
|
[
"function",
"polygonRemoveCollinearPoints",
"(",
"polygon",
",",
"precision",
")",
"{",
"var",
"num",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"polygon",
".",
"length",
"-",
"1",
";",
"polygon",
".",
"length",
">",
"3",
"&&",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"if",
"(",
"collinear",
"(",
"polygonAt",
"(",
"polygon",
",",
"i",
"-",
"1",
")",
",",
"polygonAt",
"(",
"polygon",
",",
"i",
")",
",",
"polygonAt",
"(",
"polygon",
",",
"i",
"+",
"1",
")",
",",
"precision",
")",
")",
"{",
"// Remove the middle point",
"polygon",
".",
"splice",
"(",
"i",
"%",
"polygon",
".",
"length",
",",
"1",
")",
";",
"num",
"++",
";",
"}",
"}",
"return",
"num",
";",
"}"
] |
Remove collinear points in the polygon.
@method removeCollinearPoints
@param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision.
@return {Number} The number of points removed
|
[
"Remove",
"collinear",
"points",
"in",
"the",
"polygon",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L603-L613
|
13,354
|
schteppe/poly-decomp.js
|
src/index.js
|
polygonRemoveDuplicatePoints
|
function polygonRemoveDuplicatePoints(polygon, precision){
for(var i=polygon.length-1; i>=1; --i){
var pi = polygon[i];
for(var j=i-1; j>=0; --j){
if(points_eq(pi, polygon[j], precision)){
polygon.splice(i,1);
continue;
}
}
}
}
|
javascript
|
function polygonRemoveDuplicatePoints(polygon, precision){
for(var i=polygon.length-1; i>=1; --i){
var pi = polygon[i];
for(var j=i-1; j>=0; --j){
if(points_eq(pi, polygon[j], precision)){
polygon.splice(i,1);
continue;
}
}
}
}
|
[
"function",
"polygonRemoveDuplicatePoints",
"(",
"polygon",
",",
"precision",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"polygon",
".",
"length",
"-",
"1",
";",
"i",
">=",
"1",
";",
"--",
"i",
")",
"{",
"var",
"pi",
"=",
"polygon",
"[",
"i",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"i",
"-",
"1",
";",
"j",
">=",
"0",
";",
"--",
"j",
")",
"{",
"if",
"(",
"points_eq",
"(",
"pi",
",",
"polygon",
"[",
"j",
"]",
",",
"precision",
")",
")",
"{",
"polygon",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"continue",
";",
"}",
"}",
"}",
"}"
] |
Remove duplicate points in the polygon.
@method removeDuplicatePoints
@param {Number} [precision] The threshold to use when determining whether two points are the same. Use zero for best precision.
|
[
"Remove",
"duplicate",
"points",
"in",
"the",
"polygon",
"."
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L620-L630
|
13,355
|
schteppe/poly-decomp.js
|
src/index.js
|
scalar_eq
|
function scalar_eq(a,b,precision){
precision = precision || 0;
return Math.abs(a-b) <= precision;
}
|
javascript
|
function scalar_eq(a,b,precision){
precision = precision || 0;
return Math.abs(a-b) <= precision;
}
|
[
"function",
"scalar_eq",
"(",
"a",
",",
"b",
",",
"precision",
")",
"{",
"precision",
"=",
"precision",
"||",
"0",
";",
"return",
"Math",
".",
"abs",
"(",
"a",
"-",
"b",
")",
"<=",
"precision",
";",
"}"
] |
Check if two scalars are equal
@static
@method eq
@param {Number} a
@param {Number} b
@param {Number} [precision]
@return {Boolean}
|
[
"Check",
"if",
"two",
"scalars",
"are",
"equal"
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L641-L644
|
13,356
|
schteppe/poly-decomp.js
|
src/index.js
|
points_eq
|
function points_eq(a,b,precision){
return scalar_eq(a[0],b[0],precision) && scalar_eq(a[1],b[1],precision);
}
|
javascript
|
function points_eq(a,b,precision){
return scalar_eq(a[0],b[0],precision) && scalar_eq(a[1],b[1],precision);
}
|
[
"function",
"points_eq",
"(",
"a",
",",
"b",
",",
"precision",
")",
"{",
"return",
"scalar_eq",
"(",
"a",
"[",
"0",
"]",
",",
"b",
"[",
"0",
"]",
",",
"precision",
")",
"&&",
"scalar_eq",
"(",
"a",
"[",
"1",
"]",
",",
"b",
"[",
"1",
"]",
",",
"precision",
")",
";",
"}"
] |
Check if two points are equal
@static
@method points_eq
@param {Array} a
@param {Array} b
@param {Number} [precision]
@return {Boolean}
|
[
"Check",
"if",
"two",
"points",
"are",
"equal"
] |
4eebc5b5780d8ffd8094615622b701e34a7835e8
|
https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L655-L657
|
13,357
|
Raynos/mercury
|
examples/unidirectional/backbone/observ-backbone.js
|
serialize
|
function serialize(model) {
var data = model.toJSON();
Object.keys(data).forEach(function serializeRecur(key) {
var value = data[key];
// if any value can be serialized toJSON() then do it
if (value && value.toJSON) {
data[key] = data[key].toJSON();
}
});
return data;
}
|
javascript
|
function serialize(model) {
var data = model.toJSON();
Object.keys(data).forEach(function serializeRecur(key) {
var value = data[key];
// if any value can be serialized toJSON() then do it
if (value && value.toJSON) {
data[key] = data[key].toJSON();
}
});
return data;
}
|
[
"function",
"serialize",
"(",
"model",
")",
"{",
"var",
"data",
"=",
"model",
".",
"toJSON",
"(",
")",
";",
"Object",
".",
"keys",
"(",
"data",
")",
".",
"forEach",
"(",
"function",
"serializeRecur",
"(",
"key",
")",
"{",
"var",
"value",
"=",
"data",
"[",
"key",
"]",
";",
"// if any value can be serialized toJSON() then do it",
"if",
"(",
"value",
"&&",
"value",
".",
"toJSON",
")",
"{",
"data",
"[",
"key",
"]",
"=",
"data",
"[",
"key",
"]",
".",
"toJSON",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
"data",
";",
"}"
] |
convert a Backbone model to JSON
|
[
"convert",
"a",
"Backbone",
"model",
"to",
"JSON"
] |
58fae95356efacb6b2a7f91b44ed5c0b46aab78c
|
https://github.com/Raynos/mercury/blob/58fae95356efacb6b2a7f91b44ed5c0b46aab78c/examples/unidirectional/backbone/observ-backbone.js#L30-L40
|
13,358
|
Raynos/mercury
|
examples/unidirectional/backbone/observ-backbone.js
|
listen
|
function listen(model, listener) {
model.on('change', listener);
model.values().forEach(function listenRecur(value) {
var isCollection = value && value._byId;
if (!isCollection) {
return;
}
// for each collection listen to it
// console.log('listenCollection')
listenCollection(value, listener);
});
}
|
javascript
|
function listen(model, listener) {
model.on('change', listener);
model.values().forEach(function listenRecur(value) {
var isCollection = value && value._byId;
if (!isCollection) {
return;
}
// for each collection listen to it
// console.log('listenCollection')
listenCollection(value, listener);
});
}
|
[
"function",
"listen",
"(",
"model",
",",
"listener",
")",
"{",
"model",
".",
"on",
"(",
"'change'",
",",
"listener",
")",
";",
"model",
".",
"values",
"(",
")",
".",
"forEach",
"(",
"function",
"listenRecur",
"(",
"value",
")",
"{",
"var",
"isCollection",
"=",
"value",
"&&",
"value",
".",
"_byId",
";",
"if",
"(",
"!",
"isCollection",
")",
"{",
"return",
";",
"}",
"// for each collection listen to it",
"// console.log('listenCollection')",
"listenCollection",
"(",
"value",
",",
"listener",
")",
";",
"}",
")",
";",
"}"
] |
listen to a Backbone model
|
[
"listen",
"to",
"a",
"Backbone",
"model"
] |
58fae95356efacb6b2a7f91b44ed5c0b46aab78c
|
https://github.com/Raynos/mercury/blob/58fae95356efacb6b2a7f91b44ed5c0b46aab78c/examples/unidirectional/backbone/observ-backbone.js#L43-L57
|
13,359
|
Raynos/mercury
|
examples/unidirectional/backbone/observ-backbone.js
|
listenCollection
|
function listenCollection(collection, listener) {
collection.forEach(function listenModel(model) {
listen(model, listener);
});
collection.on('add', function onAdd(model) {
listen(model, listener);
listener();
});
}
|
javascript
|
function listenCollection(collection, listener) {
collection.forEach(function listenModel(model) {
listen(model, listener);
});
collection.on('add', function onAdd(model) {
listen(model, listener);
listener();
});
}
|
[
"function",
"listenCollection",
"(",
"collection",
",",
"listener",
")",
"{",
"collection",
".",
"forEach",
"(",
"function",
"listenModel",
"(",
"model",
")",
"{",
"listen",
"(",
"model",
",",
"listener",
")",
";",
"}",
")",
";",
"collection",
".",
"on",
"(",
"'add'",
",",
"function",
"onAdd",
"(",
"model",
")",
"{",
"listen",
"(",
"model",
",",
"listener",
")",
";",
"listener",
"(",
")",
";",
"}",
")",
";",
"}"
] |
listen to a Backbone collection
|
[
"listen",
"to",
"a",
"Backbone",
"collection"
] |
58fae95356efacb6b2a7f91b44ed5c0b46aab78c
|
https://github.com/Raynos/mercury/blob/58fae95356efacb6b2a7f91b44ed5c0b46aab78c/examples/unidirectional/backbone/observ-backbone.js#L60-L69
|
13,360
|
reframejs/reframe
|
helpers/webpack-config-mod/index.js
|
parseBabelThing
|
function parseBabelThing(babelThing) {
assert_usage([String, Array].includes(babelThing.constructor));
let name;
let options;
if( babelThing.constructor === Array ) {
name = babelThing[0];
options = babelThing[1];
} else {
name = babelThing;
}
assert_usage(name.constructor===String, babelThing);
spec = [name];
if( options ) {
spec.push(options);
}
return {name, options, spec};
}
|
javascript
|
function parseBabelThing(babelThing) {
assert_usage([String, Array].includes(babelThing.constructor));
let name;
let options;
if( babelThing.constructor === Array ) {
name = babelThing[0];
options = babelThing[1];
} else {
name = babelThing;
}
assert_usage(name.constructor===String, babelThing);
spec = [name];
if( options ) {
spec.push(options);
}
return {name, options, spec};
}
|
[
"function",
"parseBabelThing",
"(",
"babelThing",
")",
"{",
"assert_usage",
"(",
"[",
"String",
",",
"Array",
"]",
".",
"includes",
"(",
"babelThing",
".",
"constructor",
")",
")",
";",
"let",
"name",
";",
"let",
"options",
";",
"if",
"(",
"babelThing",
".",
"constructor",
"===",
"Array",
")",
"{",
"name",
"=",
"babelThing",
"[",
"0",
"]",
";",
"options",
"=",
"babelThing",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"name",
"=",
"babelThing",
";",
"}",
"assert_usage",
"(",
"name",
".",
"constructor",
"===",
"String",
",",
"babelThing",
")",
";",
"spec",
"=",
"[",
"name",
"]",
";",
"if",
"(",
"options",
")",
"{",
"spec",
".",
"push",
"(",
"options",
")",
";",
"}",
"return",
"{",
"name",
",",
"options",
",",
"spec",
"}",
";",
"}"
] |
Works for babel presets as well as for babel plugins
|
[
"Works",
"for",
"babel",
"presets",
"as",
"well",
"as",
"for",
"babel",
"plugins"
] |
d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c
|
https://github.com/reframejs/reframe/blob/d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c/helpers/webpack-config-mod/index.js#L163-L179
|
13,361
|
reframejs/reframe
|
plugins/react/common.js
|
applyViewWrappers
|
function applyViewWrappers({reactElement, initialProps, viewWrappers=[]}) {
viewWrappers
.forEach(viewWrapper => {
reactElement = viewWrapper(reactElement, initialProps);
});
return reactElement;
}
|
javascript
|
function applyViewWrappers({reactElement, initialProps, viewWrappers=[]}) {
viewWrappers
.forEach(viewWrapper => {
reactElement = viewWrapper(reactElement, initialProps);
});
return reactElement;
}
|
[
"function",
"applyViewWrappers",
"(",
"{",
"reactElement",
",",
"initialProps",
",",
"viewWrappers",
"=",
"[",
"]",
"}",
")",
"{",
"viewWrappers",
".",
"forEach",
"(",
"viewWrapper",
"=>",
"{",
"reactElement",
"=",
"viewWrapper",
"(",
"reactElement",
",",
"initialProps",
")",
";",
"}",
")",
";",
"return",
"reactElement",
";",
"}"
] |
Apply view wrappers. E.g. the `@reframe/react-router` plugin adds a view wrapper to add the provider-components `<BrowserRouter>` and `<StaticRouter>`.
|
[
"Apply",
"view",
"wrappers",
".",
"E",
".",
"g",
".",
"the"
] |
d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c
|
https://github.com/reframejs/reframe/blob/d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c/plugins/react/common.js#L17-L23
|
13,362
|
reframejs/reframe
|
plugins/build/index.js
|
assemble_modifiers
|
function assemble_modifiers(modifier_name, configParts) {
const assert_usage = require('reassert/usage');
// `configParts` holds all globalConfig parts
// `config` holds a webpack config
let supra_modifier = ({config}) => config;
// We assemble all `configParts`'s config modifiers into one `supra_modifier`
configParts
.forEach(configPart => {
const modifier = configPart[modifier_name];
if( ! modifier ) {
return;
}
assert_usage(configPart[modifier_name] instanceof Function);
const previous_modifier = supra_modifier;
supra_modifier = (
args => {
const config = previous_modifier(args);
const config__new = modifier({...args, config});
assert_usage(
config__new,
(
configPart.$name ? (
"The `"+modifier_name+"` of `"+configPart.$name+"`"
) : (
"A `"+modifier_name+"`"
)
) + (
" is returning `"+config__new+"` but it should be returning a webpack config instead."
)
);
return config__new;
}
);
});
return supra_modifier;
}
|
javascript
|
function assemble_modifiers(modifier_name, configParts) {
const assert_usage = require('reassert/usage');
// `configParts` holds all globalConfig parts
// `config` holds a webpack config
let supra_modifier = ({config}) => config;
// We assemble all `configParts`'s config modifiers into one `supra_modifier`
configParts
.forEach(configPart => {
const modifier = configPart[modifier_name];
if( ! modifier ) {
return;
}
assert_usage(configPart[modifier_name] instanceof Function);
const previous_modifier = supra_modifier;
supra_modifier = (
args => {
const config = previous_modifier(args);
const config__new = modifier({...args, config});
assert_usage(
config__new,
(
configPart.$name ? (
"The `"+modifier_name+"` of `"+configPart.$name+"`"
) : (
"A `"+modifier_name+"`"
)
) + (
" is returning `"+config__new+"` but it should be returning a webpack config instead."
)
);
return config__new;
}
);
});
return supra_modifier;
}
|
[
"function",
"assemble_modifiers",
"(",
"modifier_name",
",",
"configParts",
")",
"{",
"const",
"assert_usage",
"=",
"require",
"(",
"'reassert/usage'",
")",
";",
"// `configParts` holds all globalConfig parts",
"// `config` holds a webpack config",
"let",
"supra_modifier",
"=",
"(",
"{",
"config",
"}",
")",
"=>",
"config",
";",
"// We assemble all `configParts`'s config modifiers into one `supra_modifier`",
"configParts",
".",
"forEach",
"(",
"configPart",
"=>",
"{",
"const",
"modifier",
"=",
"configPart",
"[",
"modifier_name",
"]",
";",
"if",
"(",
"!",
"modifier",
")",
"{",
"return",
";",
"}",
"assert_usage",
"(",
"configPart",
"[",
"modifier_name",
"]",
"instanceof",
"Function",
")",
";",
"const",
"previous_modifier",
"=",
"supra_modifier",
";",
"supra_modifier",
"=",
"(",
"args",
"=>",
"{",
"const",
"config",
"=",
"previous_modifier",
"(",
"args",
")",
";",
"const",
"config__new",
"=",
"modifier",
"(",
"{",
"...",
"args",
",",
"config",
"}",
")",
";",
"assert_usage",
"(",
"config__new",
",",
"(",
"configPart",
".",
"$name",
"?",
"(",
"\"The `\"",
"+",
"modifier_name",
"+",
"\"` of `\"",
"+",
"configPart",
".",
"$name",
"+",
"\"`\"",
")",
":",
"(",
"\"A `\"",
"+",
"modifier_name",
"+",
"\"`\"",
")",
")",
"+",
"(",
"\" is returning `\"",
"+",
"config__new",
"+",
"\"` but it should be returning a webpack config instead.\"",
")",
")",
";",
"return",
"config__new",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"supra_modifier",
";",
"}"
] |
We assemble several webpack config modifiers into one supra modifier
|
[
"We",
"assemble",
"several",
"webpack",
"config",
"modifiers",
"into",
"one",
"supra",
"modifier"
] |
d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c
|
https://github.com/reframejs/reframe/blob/d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c/plugins/build/index.js#L41-L79
|
13,363
|
adobe-photoshop/generator-core
|
lib/logging.js
|
StreamFormatter
|
function StreamFormatter(loggerManager, options) {
if (!(this instanceof StreamFormatter)) {
return new StreamFormatter(loggerManager, options);
}
stream.Readable.call(this, options);
this._buffer = [];
this._pushable = false;
this._ended = false;
loggerManager.on("message", this._handleMessage.bind(this));
loggerManager.on("end", function () { this._handleMessage("END"); }.bind(this));
}
|
javascript
|
function StreamFormatter(loggerManager, options) {
if (!(this instanceof StreamFormatter)) {
return new StreamFormatter(loggerManager, options);
}
stream.Readable.call(this, options);
this._buffer = [];
this._pushable = false;
this._ended = false;
loggerManager.on("message", this._handleMessage.bind(this));
loggerManager.on("end", function () { this._handleMessage("END"); }.bind(this));
}
|
[
"function",
"StreamFormatter",
"(",
"loggerManager",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"StreamFormatter",
")",
")",
"{",
"return",
"new",
"StreamFormatter",
"(",
"loggerManager",
",",
"options",
")",
";",
"}",
"stream",
".",
"Readable",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"_buffer",
"=",
"[",
"]",
";",
"this",
".",
"_pushable",
"=",
"false",
";",
"this",
".",
"_ended",
"=",
"false",
";",
"loggerManager",
".",
"on",
"(",
"\"message\"",
",",
"this",
".",
"_handleMessage",
".",
"bind",
"(",
"this",
")",
")",
";",
"loggerManager",
".",
"on",
"(",
"\"end\"",
",",
"function",
"(",
")",
"{",
"this",
".",
"_handleMessage",
"(",
"\"END\"",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] |
StreamFormatter objects are Readable streams. They output a string represntation
of the log events generated by the "logger" variable.
The "options" argument is passed directly to the stream.Readable constructor.
No configuration of the log format is supported at this time.
|
[
"StreamFormatter",
"objects",
"are",
"Readable",
"streams",
".",
"They",
"output",
"a",
"string",
"represntation",
"of",
"the",
"log",
"events",
"generated",
"by",
"the",
"logger",
"variable",
"."
] |
24a2c4e38aef79adb42869f200778ab52de4ef36
|
https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/logging.js#L316-L327
|
13,364
|
adobe-photoshop/generator-core
|
lib/stdlog.js
|
logReadableStream
|
function logReadableStream(stream) {
var encoding = "utf8";
stream.setEncoding(encoding);
stream.on("data", function (chunk) {
writeToLog(chunk, encoding);
});
}
|
javascript
|
function logReadableStream(stream) {
var encoding = "utf8";
stream.setEncoding(encoding);
stream.on("data", function (chunk) {
writeToLog(chunk, encoding);
});
}
|
[
"function",
"logReadableStream",
"(",
"stream",
")",
"{",
"var",
"encoding",
"=",
"\"utf8\"",
";",
"stream",
".",
"setEncoding",
"(",
"encoding",
")",
";",
"stream",
".",
"on",
"(",
"\"data\"",
",",
"function",
"(",
"chunk",
")",
"{",
"writeToLog",
"(",
"chunk",
",",
"encoding",
")",
";",
"}",
")",
";",
"}"
] |
Listen for data on a readable stream, write to the log file
@param {stream.Readable} stream
|
[
"Listen",
"for",
"data",
"on",
"a",
"readable",
"stream",
"write",
"to",
"the",
"log",
"file"
] |
24a2c4e38aef79adb42869f200778ab52de4ef36
|
https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/stdlog.js#L115-L123
|
13,365
|
adobe-photoshop/generator-core
|
lib/stdlog.js
|
logWriteableStream
|
function logWriteableStream(stream, colorFunction) {
var write = stream.write;
// The third parameter, callback, will be passed implicitely using arguments
stream.write = function (chunk, encoding) {
// Write to STDOUT right away
try {
write.apply(this, arguments);
} catch (streamWriteError) { }
writeToLog(chunk, encoding, colorFunction);
};
}
|
javascript
|
function logWriteableStream(stream, colorFunction) {
var write = stream.write;
// The third parameter, callback, will be passed implicitely using arguments
stream.write = function (chunk, encoding) {
// Write to STDOUT right away
try {
write.apply(this, arguments);
} catch (streamWriteError) { }
writeToLog(chunk, encoding, colorFunction);
};
}
|
[
"function",
"logWriteableStream",
"(",
"stream",
",",
"colorFunction",
")",
"{",
"var",
"write",
"=",
"stream",
".",
"write",
";",
"// The third parameter, callback, will be passed implicitely using arguments",
"stream",
".",
"write",
"=",
"function",
"(",
"chunk",
",",
"encoding",
")",
"{",
"// Write to STDOUT right away",
"try",
"{",
"write",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"catch",
"(",
"streamWriteError",
")",
"{",
"}",
"writeToLog",
"(",
"chunk",
",",
"encoding",
",",
"colorFunction",
")",
";",
"}",
";",
"}"
] |
Tap a writable stream and write the data to the log file
@param {stream.Writable} stream
@param {function=} colorFunction optional function to apply color to the log message
|
[
"Tap",
"a",
"writable",
"stream",
"and",
"write",
"the",
"data",
"to",
"the",
"log",
"file"
] |
24a2c4e38aef79adb42869f200778ab52de4ef36
|
https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/stdlog.js#L131-L143
|
13,366
|
adobe-photoshop/generator-core
|
lib/stdlog.js
|
getLogDirectoryElements
|
function getLogDirectoryElements(settings) {
var elements,
platform = process.platform;
if (settings.logRoot) {
elements = [settings.logRoot, settings.module];
} else if (platform === "darwin") {
elements = [process.env.HOME, "Library", "Logs", settings.vendor, settings.application, settings.module];
} else if (platform === "win32") {
elements = [process.env.APPDATA, settings.vendor, settings.application, settings.module, "logs"];
} else {
elements = [process.env.HOME, settings.vendor, settings.application, settings.module, "logs"];
}
return elements;
}
|
javascript
|
function getLogDirectoryElements(settings) {
var elements,
platform = process.platform;
if (settings.logRoot) {
elements = [settings.logRoot, settings.module];
} else if (platform === "darwin") {
elements = [process.env.HOME, "Library", "Logs", settings.vendor, settings.application, settings.module];
} else if (platform === "win32") {
elements = [process.env.APPDATA, settings.vendor, settings.application, settings.module, "logs"];
} else {
elements = [process.env.HOME, settings.vendor, settings.application, settings.module, "logs"];
}
return elements;
}
|
[
"function",
"getLogDirectoryElements",
"(",
"settings",
")",
"{",
"var",
"elements",
",",
"platform",
"=",
"process",
".",
"platform",
";",
"if",
"(",
"settings",
".",
"logRoot",
")",
"{",
"elements",
"=",
"[",
"settings",
".",
"logRoot",
",",
"settings",
".",
"module",
"]",
";",
"}",
"else",
"if",
"(",
"platform",
"===",
"\"darwin\"",
")",
"{",
"elements",
"=",
"[",
"process",
".",
"env",
".",
"HOME",
",",
"\"Library\"",
",",
"\"Logs\"",
",",
"settings",
".",
"vendor",
",",
"settings",
".",
"application",
",",
"settings",
".",
"module",
"]",
";",
"}",
"else",
"if",
"(",
"platform",
"===",
"\"win32\"",
")",
"{",
"elements",
"=",
"[",
"process",
".",
"env",
".",
"APPDATA",
",",
"settings",
".",
"vendor",
",",
"settings",
".",
"application",
",",
"settings",
".",
"module",
",",
"\"logs\"",
"]",
";",
"}",
"else",
"{",
"elements",
"=",
"[",
"process",
".",
"env",
".",
"HOME",
",",
"settings",
".",
"vendor",
",",
"settings",
".",
"application",
",",
"settings",
".",
"module",
",",
"\"logs\"",
"]",
";",
"}",
"return",
"elements",
";",
"}"
] |
Define the log directory as an array so we can easily create the individual subdirectories if necessary, without requiring an external library like mkdirp
|
[
"Define",
"the",
"log",
"directory",
"as",
"an",
"array",
"so",
"we",
"can",
"easily",
"create",
"the",
"individual",
"subdirectories",
"if",
"necessary",
"without",
"requiring",
"an",
"external",
"library",
"like",
"mkdirp"
] |
24a2c4e38aef79adb42869f200778ab52de4ef36
|
https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/stdlog.js#L147-L162
|
13,367
|
adobe-photoshop/generator-core
|
lib/style.js
|
extractStyleInfo
|
function extractStyleInfo(psd/*, opts*/) {
var SON = {};
var layers = psd.layers;
_classnames = [];
_psd = psd;
SON.layers = [];
layers.forEach(function (layer) {
var s = extractLayerStyleInfo(layer);
if (s !== undefined) {
SON.layers.push(s);
}
});
return SON;
}
|
javascript
|
function extractStyleInfo(psd/*, opts*/) {
var SON = {};
var layers = psd.layers;
_classnames = [];
_psd = psd;
SON.layers = [];
layers.forEach(function (layer) {
var s = extractLayerStyleInfo(layer);
if (s !== undefined) {
SON.layers.push(s);
}
});
return SON;
}
|
[
"function",
"extractStyleInfo",
"(",
"psd",
"/*, opts*/",
")",
"{",
"var",
"SON",
"=",
"{",
"}",
";",
"var",
"layers",
"=",
"psd",
".",
"layers",
";",
"_classnames",
"=",
"[",
"]",
";",
"_psd",
"=",
"psd",
";",
"SON",
".",
"layers",
"=",
"[",
"]",
";",
"layers",
".",
"forEach",
"(",
"function",
"(",
"layer",
")",
"{",
"var",
"s",
"=",
"extractLayerStyleInfo",
"(",
"layer",
")",
";",
"if",
"(",
"s",
"!==",
"undefined",
")",
"{",
"SON",
".",
"layers",
".",
"push",
"(",
"s",
")",
";",
"}",
"}",
")",
";",
"return",
"SON",
";",
"}"
] |
Return a SON document for the specified document info
@param {Object} psd document retrieved from Generator.getDocumentInfo()
@return {Object} The SON document for the specified Generator document
Note: This API should be considered private and may be changed/removed at any
time with only a bump to the "patch" version number of generator-core.
Use at your own risk.
|
[
"Return",
"a",
"SON",
"document",
"for",
"the",
"specified",
"document",
"info"
] |
24a2c4e38aef79adb42869f200778ab52de4ef36
|
https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/style.js#L550-L564
|
13,368
|
adobe-photoshop/generator-core
|
lib/generator.js
|
function (pixmapWidth, pixmapHeight) {
// Find out if the mask extends beyond the visible pixels
var paddingWanted;
["top", "left", "right", "bottom"].forEach(function (key) {
if (paddedInputBounds[key] !== visibleInputBounds[key]) {
paddingWanted = true;
return false;
}
});
// When Photoshop produces inaccurate results, the padding is adjusted to compensate
// When no padding is requested, this may be unwanted, so return a padding of 0px
if (!paddingWanted) {
return { left: 0, top: 0, right: 0, bottom: 0 };
}
var // How much padding is necessary in both dimensions
missingWidth = finalOutputWidth - pixmapWidth,
missingHeight = finalOutputHeight - pixmapHeight,
// How of the original padding was on which side (default 0)
leftRatio = paddingInputWidth === 0 ? 0 :
((visibleInputBounds.left - paddedInputBounds.left) / paddingInputWidth),
topRatio = paddingInputHeight === 0 ? 0 :
((visibleInputBounds.top - paddedInputBounds.top) / paddingInputHeight),
// Concrete padding size on one side so the other side can use the rest
leftPadding = Math.round(leftRatio * missingWidth),
topPadding = Math.round(topRatio * missingHeight);
// Padding: how many transparent pixels to add on which side
return {
left: Math.max(0, leftPadding),
top: Math.max(0, topPadding),
right: Math.max(0, missingWidth - leftPadding),
bottom: Math.max(0, missingHeight - topPadding)
};
}
|
javascript
|
function (pixmapWidth, pixmapHeight) {
// Find out if the mask extends beyond the visible pixels
var paddingWanted;
["top", "left", "right", "bottom"].forEach(function (key) {
if (paddedInputBounds[key] !== visibleInputBounds[key]) {
paddingWanted = true;
return false;
}
});
// When Photoshop produces inaccurate results, the padding is adjusted to compensate
// When no padding is requested, this may be unwanted, so return a padding of 0px
if (!paddingWanted) {
return { left: 0, top: 0, right: 0, bottom: 0 };
}
var // How much padding is necessary in both dimensions
missingWidth = finalOutputWidth - pixmapWidth,
missingHeight = finalOutputHeight - pixmapHeight,
// How of the original padding was on which side (default 0)
leftRatio = paddingInputWidth === 0 ? 0 :
((visibleInputBounds.left - paddedInputBounds.left) / paddingInputWidth),
topRatio = paddingInputHeight === 0 ? 0 :
((visibleInputBounds.top - paddedInputBounds.top) / paddingInputHeight),
// Concrete padding size on one side so the other side can use the rest
leftPadding = Math.round(leftRatio * missingWidth),
topPadding = Math.round(topRatio * missingHeight);
// Padding: how many transparent pixels to add on which side
return {
left: Math.max(0, leftPadding),
top: Math.max(0, topPadding),
right: Math.max(0, missingWidth - leftPadding),
bottom: Math.max(0, missingHeight - topPadding)
};
}
|
[
"function",
"(",
"pixmapWidth",
",",
"pixmapHeight",
")",
"{",
"// Find out if the mask extends beyond the visible pixels",
"var",
"paddingWanted",
";",
"[",
"\"top\"",
",",
"\"left\"",
",",
"\"right\"",
",",
"\"bottom\"",
"]",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"paddedInputBounds",
"[",
"key",
"]",
"!==",
"visibleInputBounds",
"[",
"key",
"]",
")",
"{",
"paddingWanted",
"=",
"true",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"// When Photoshop produces inaccurate results, the padding is adjusted to compensate",
"// When no padding is requested, this may be unwanted, so return a padding of 0px",
"if",
"(",
"!",
"paddingWanted",
")",
"{",
"return",
"{",
"left",
":",
"0",
",",
"top",
":",
"0",
",",
"right",
":",
"0",
",",
"bottom",
":",
"0",
"}",
";",
"}",
"var",
"// How much padding is necessary in both dimensions",
"missingWidth",
"=",
"finalOutputWidth",
"-",
"pixmapWidth",
",",
"missingHeight",
"=",
"finalOutputHeight",
"-",
"pixmapHeight",
",",
"// How of the original padding was on which side (default 0)",
"leftRatio",
"=",
"paddingInputWidth",
"===",
"0",
"?",
"0",
":",
"(",
"(",
"visibleInputBounds",
".",
"left",
"-",
"paddedInputBounds",
".",
"left",
")",
"/",
"paddingInputWidth",
")",
",",
"topRatio",
"=",
"paddingInputHeight",
"===",
"0",
"?",
"0",
":",
"(",
"(",
"visibleInputBounds",
".",
"top",
"-",
"paddedInputBounds",
".",
"top",
")",
"/",
"paddingInputHeight",
")",
",",
"// Concrete padding size on one side so the other side can use the rest",
"leftPadding",
"=",
"Math",
".",
"round",
"(",
"leftRatio",
"*",
"missingWidth",
")",
",",
"topPadding",
"=",
"Math",
".",
"round",
"(",
"topRatio",
"*",
"missingHeight",
")",
";",
"// Padding: how many transparent pixels to add on which side",
"return",
"{",
"left",
":",
"Math",
".",
"max",
"(",
"0",
",",
"leftPadding",
")",
",",
"top",
":",
"Math",
".",
"max",
"(",
"0",
",",
"topPadding",
")",
",",
"right",
":",
"Math",
".",
"max",
"(",
"0",
",",
"missingWidth",
"-",
"leftPadding",
")",
",",
"bottom",
":",
"Math",
".",
"max",
"(",
"0",
",",
"missingHeight",
"-",
"topPadding",
")",
"}",
";",
"}"
] |
The padding depends on the actual size of the returned image, therefore provide a function
|
[
"The",
"padding",
"depends",
"on",
"the",
"actual",
"size",
"of",
"the",
"returned",
"image",
"therefore",
"provide",
"a",
"function"
] |
24a2c4e38aef79adb42869f200778ab52de4ef36
|
https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/generator.js#L1504-L1539
|
|
13,369
|
3rd-Eden/memcached
|
lib/memcached.js
|
Client
|
function Client (args, options) {
// Ensure Client instantiated with 'new'
if (!(this instanceof Client)) {
return new Client(args, options);
}
var servers = []
, weights = {}
, regular = 'localhost:11211'
, key;
// Parse down the connection arguments
switch (Object.prototype.toString.call(args)) {
case '[object Object]':
weights = args;
servers = Object.keys(args);
break;
case '[object Array]':
servers = args.length ? args : [regular];
break;
default:
servers.push(args || regular);
break;
}
if (!servers.length) {
throw new Error('No servers where supplied in the arguments');
}
// merge with global and user config
Utils.merge(this, Client.config);
Utils.merge(this, options);
this.servers = servers;
var compatibility = this.compatibility || this.compatiblity;
this.HashRing = new HashRing(args, this.algorithm, {
'compatibility': compatibility,
'default port': compatibility === 'ketama' ? 11211 : null
});
this.connections = {};
this.issues = [];
}
|
javascript
|
function Client (args, options) {
// Ensure Client instantiated with 'new'
if (!(this instanceof Client)) {
return new Client(args, options);
}
var servers = []
, weights = {}
, regular = 'localhost:11211'
, key;
// Parse down the connection arguments
switch (Object.prototype.toString.call(args)) {
case '[object Object]':
weights = args;
servers = Object.keys(args);
break;
case '[object Array]':
servers = args.length ? args : [regular];
break;
default:
servers.push(args || regular);
break;
}
if (!servers.length) {
throw new Error('No servers where supplied in the arguments');
}
// merge with global and user config
Utils.merge(this, Client.config);
Utils.merge(this, options);
this.servers = servers;
var compatibility = this.compatibility || this.compatiblity;
this.HashRing = new HashRing(args, this.algorithm, {
'compatibility': compatibility,
'default port': compatibility === 'ketama' ? 11211 : null
});
this.connections = {};
this.issues = [];
}
|
[
"function",
"Client",
"(",
"args",
",",
"options",
")",
"{",
"// Ensure Client instantiated with 'new'",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Client",
")",
")",
"{",
"return",
"new",
"Client",
"(",
"args",
",",
"options",
")",
";",
"}",
"var",
"servers",
"=",
"[",
"]",
",",
"weights",
"=",
"{",
"}",
",",
"regular",
"=",
"'localhost:11211'",
",",
"key",
";",
"// Parse down the connection arguments",
"switch",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"args",
")",
")",
"{",
"case",
"'[object Object]'",
":",
"weights",
"=",
"args",
";",
"servers",
"=",
"Object",
".",
"keys",
"(",
"args",
")",
";",
"break",
";",
"case",
"'[object Array]'",
":",
"servers",
"=",
"args",
".",
"length",
"?",
"args",
":",
"[",
"regular",
"]",
";",
"break",
";",
"default",
":",
"servers",
".",
"push",
"(",
"args",
"||",
"regular",
")",
";",
"break",
";",
"}",
"if",
"(",
"!",
"servers",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No servers where supplied in the arguments'",
")",
";",
"}",
"// merge with global and user config",
"Utils",
".",
"merge",
"(",
"this",
",",
"Client",
".",
"config",
")",
";",
"Utils",
".",
"merge",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"servers",
"=",
"servers",
";",
"var",
"compatibility",
"=",
"this",
".",
"compatibility",
"||",
"this",
".",
"compatiblity",
";",
"this",
".",
"HashRing",
"=",
"new",
"HashRing",
"(",
"args",
",",
"this",
".",
"algorithm",
",",
"{",
"'compatibility'",
":",
"compatibility",
",",
"'default port'",
":",
"compatibility",
"===",
"'ketama'",
"?",
"11211",
":",
"null",
"}",
")",
";",
"this",
".",
"connections",
"=",
"{",
"}",
";",
"this",
".",
"issues",
"=",
"[",
"]",
";",
"}"
] |
Constructs a new memcached client
@constructor
@param {Mixed} args Array, string or object with servers
@param {Object} options options
@api public
|
[
"Constructs",
"a",
"new",
"memcached",
"client"
] |
5438a03ec44c703b5f60012c2208d9a0bc5bc733
|
https://github.com/3rd-Eden/memcached/blob/5438a03ec44c703b5f60012c2208d9a0bc5bc733/lib/memcached.js#L31-L74
|
13,370
|
3rd-Eden/memcached
|
lib/memcached.js
|
stats
|
function stats(resultSet) {
var response = {};
if (resultSetIsEmpty(resultSet)) return response;
// add references to the retrieved server
response.server = this.serverAddress;
// Fill the object
resultSet.forEach(function each(statSet) {
if (statSet) response[statSet[0]] = statSet[1];
});
return response;
}
|
javascript
|
function stats(resultSet) {
var response = {};
if (resultSetIsEmpty(resultSet)) return response;
// add references to the retrieved server
response.server = this.serverAddress;
// Fill the object
resultSet.forEach(function each(statSet) {
if (statSet) response[statSet[0]] = statSet[1];
});
return response;
}
|
[
"function",
"stats",
"(",
"resultSet",
")",
"{",
"var",
"response",
"=",
"{",
"}",
";",
"if",
"(",
"resultSetIsEmpty",
"(",
"resultSet",
")",
")",
"return",
"response",
";",
"// add references to the retrieved server",
"response",
".",
"server",
"=",
"this",
".",
"serverAddress",
";",
"// Fill the object",
"resultSet",
".",
"forEach",
"(",
"function",
"each",
"(",
"statSet",
")",
"{",
"if",
"(",
"statSet",
")",
"response",
"[",
"statSet",
"[",
"0",
"]",
"]",
"=",
"statSet",
"[",
"1",
"]",
";",
"}",
")",
";",
"return",
"response",
";",
"}"
] |
combines the stats array, in to an object
|
[
"combines",
"the",
"stats",
"array",
"in",
"to",
"an",
"object"
] |
5438a03ec44c703b5f60012c2208d9a0bc5bc733
|
https://github.com/3rd-Eden/memcached/blob/5438a03ec44c703b5f60012c2208d9a0bc5bc733/lib/memcached.js#L588-L601
|
13,371
|
3rd-Eden/memcached
|
lib/memcached.js
|
handle
|
function handle(err, results) {
if (err) {
errors.push(err);
}
// add all responses to the array
(Array.isArray(results) ? results : [results]).forEach(function each(value) {
if (value && memcached.namespace.length) {
var ns_key = Object.keys(value)[0]
, newvalue = {};
newvalue[ns_key.replace(memcached.namespace, '')] = value[ns_key];
Utils.merge(responses, newvalue);
} else {
Utils.merge(responses, value);
}
});
if (!--calls){
callback(errors.length ? errors : undefined, responses);
}
}
|
javascript
|
function handle(err, results) {
if (err) {
errors.push(err);
}
// add all responses to the array
(Array.isArray(results) ? results : [results]).forEach(function each(value) {
if (value && memcached.namespace.length) {
var ns_key = Object.keys(value)[0]
, newvalue = {};
newvalue[ns_key.replace(memcached.namespace, '')] = value[ns_key];
Utils.merge(responses, newvalue);
} else {
Utils.merge(responses, value);
}
});
if (!--calls){
callback(errors.length ? errors : undefined, responses);
}
}
|
[
"function",
"handle",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"{",
"errors",
".",
"push",
"(",
"err",
")",
";",
"}",
"// add all responses to the array",
"(",
"Array",
".",
"isArray",
"(",
"results",
")",
"?",
"results",
":",
"[",
"results",
"]",
")",
".",
"forEach",
"(",
"function",
"each",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"&&",
"memcached",
".",
"namespace",
".",
"length",
")",
"{",
"var",
"ns_key",
"=",
"Object",
".",
"keys",
"(",
"value",
")",
"[",
"0",
"]",
",",
"newvalue",
"=",
"{",
"}",
";",
"newvalue",
"[",
"ns_key",
".",
"replace",
"(",
"memcached",
".",
"namespace",
",",
"''",
")",
"]",
"=",
"value",
"[",
"ns_key",
"]",
";",
"Utils",
".",
"merge",
"(",
"responses",
",",
"newvalue",
")",
";",
"}",
"else",
"{",
"Utils",
".",
"merge",
"(",
"responses",
",",
"value",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"--",
"calls",
")",
"{",
"callback",
"(",
"errors",
".",
"length",
"?",
"errors",
":",
"undefined",
",",
"responses",
")",
";",
"}",
"}"
] |
handle multiple responses and cache them untill we receive all.
|
[
"handle",
"multiple",
"responses",
"and",
"cache",
"them",
"untill",
"we",
"receive",
"all",
"."
] |
5438a03ec44c703b5f60012c2208d9a0bc5bc733
|
https://github.com/3rd-Eden/memcached/blob/5438a03ec44c703b5f60012c2208d9a0bc5bc733/lib/memcached.js#L874-L895
|
13,372
|
3rd-Eden/memcached
|
lib/memcached.js
|
handle
|
function handle(err, results) {
if (err) {
errors = errors || [];
errors.push(err);
}
if (results) responses = responses.concat(results);
// multi calls should ALWAYS return an array!
if (!--calls) {
callback(errors && errors.length ? errors.pop() : undefined, responses);
}
}
|
javascript
|
function handle(err, results) {
if (err) {
errors = errors || [];
errors.push(err);
}
if (results) responses = responses.concat(results);
// multi calls should ALWAYS return an array!
if (!--calls) {
callback(errors && errors.length ? errors.pop() : undefined, responses);
}
}
|
[
"function",
"handle",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"{",
"errors",
"=",
"errors",
"||",
"[",
"]",
";",
"errors",
".",
"push",
"(",
"err",
")",
";",
"}",
"if",
"(",
"results",
")",
"responses",
"=",
"responses",
".",
"concat",
"(",
"results",
")",
";",
"// multi calls should ALWAYS return an array!",
"if",
"(",
"!",
"--",
"calls",
")",
"{",
"callback",
"(",
"errors",
"&&",
"errors",
".",
"length",
"?",
"errors",
".",
"pop",
"(",
")",
":",
"undefined",
",",
"responses",
")",
";",
"}",
"}"
] |
handle multiple servers
|
[
"handle",
"multiple",
"servers"
] |
5438a03ec44c703b5f60012c2208d9a0bc5bc733
|
https://github.com/3rd-Eden/memcached/blob/5438a03ec44c703b5f60012c2208d9a0bc5bc733/lib/memcached.js#L1093-L1104
|
13,373
|
prescottprue/generator-react-firebase
|
examples/redux-firestore/src/utils/firebaseMessaging.js
|
updateUserProfileWithToken
|
function updateUserProfileWithToken(messagingToken) {
const currentUserUid =
firebase.auth().currentUser && firebase.auth().currentUser.uid
if (!currentUserUid) {
return Promise.resolve();
}
return firebase
.firestore()
.collection('users')
.doc(currentUserUid)
.update({
messaging: {
mostRecentToken: messagingToken,
updatedAt: firebase.firestore.FieldValue.serverTimestamp()
}
})
}
|
javascript
|
function updateUserProfileWithToken(messagingToken) {
const currentUserUid =
firebase.auth().currentUser && firebase.auth().currentUser.uid
if (!currentUserUid) {
return Promise.resolve();
}
return firebase
.firestore()
.collection('users')
.doc(currentUserUid)
.update({
messaging: {
mostRecentToken: messagingToken,
updatedAt: firebase.firestore.FieldValue.serverTimestamp()
}
})
}
|
[
"function",
"updateUserProfileWithToken",
"(",
"messagingToken",
")",
"{",
"const",
"currentUserUid",
"=",
"firebase",
".",
"auth",
"(",
")",
".",
"currentUser",
"&&",
"firebase",
".",
"auth",
"(",
")",
".",
"currentUser",
".",
"uid",
"if",
"(",
"!",
"currentUserUid",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"return",
"firebase",
".",
"firestore",
"(",
")",
".",
"collection",
"(",
"'users'",
")",
".",
"doc",
"(",
"currentUserUid",
")",
".",
"update",
"(",
"{",
"messaging",
":",
"{",
"mostRecentToken",
":",
"messagingToken",
",",
"updatedAt",
":",
"firebase",
".",
"firestore",
".",
"FieldValue",
".",
"serverTimestamp",
"(",
")",
"}",
"}",
")",
"}"
] |
Write FCM messagingToken to user profile
@param {String} messagingToken - Token to be written to user profile
|
[
"Write",
"FCM",
"messagingToken",
"to",
"user",
"profile"
] |
8f044b05da7a034018a6384b081df9d380ac22dd
|
https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/redux-firestore/src/utils/firebaseMessaging.js#L11-L27
|
13,374
|
prescottprue/generator-react-firebase
|
examples/redux-firestore/src/utils/firebaseMessaging.js
|
getMessagingToken
|
function getMessagingToken() {
return firebase
.messaging()
.getToken()
.catch(err => {
console.error('Unable to retrieve refreshed token ', err) // eslint-disable-line no-console
return Promise.reject(err)
})
}
|
javascript
|
function getMessagingToken() {
return firebase
.messaging()
.getToken()
.catch(err => {
console.error('Unable to retrieve refreshed token ', err) // eslint-disable-line no-console
return Promise.reject(err)
})
}
|
[
"function",
"getMessagingToken",
"(",
")",
"{",
"return",
"firebase",
".",
"messaging",
"(",
")",
".",
"getToken",
"(",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"console",
".",
"error",
"(",
"'Unable to retrieve refreshed token '",
",",
"err",
")",
"// eslint-disable-line no-console",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
"}",
")",
"}"
] |
Get messaging token from Firebase messaging
|
[
"Get",
"messaging",
"token",
"from",
"Firebase",
"messaging"
] |
8f044b05da7a034018a6384b081df9d380ac22dd
|
https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/redux-firestore/src/utils/firebaseMessaging.js#L32-L40
|
13,375
|
prescottprue/generator-react-firebase
|
examples/react-firebase-redux/src/utils/errorHandler.js
|
initStackdriverErrorReporter
|
function initStackdriverErrorReporter() {
if (typeof window.StackdriverErrorReporter === 'function') {
window.addEventListener('DOMContentLoaded', () => {
const errorHandler = new window.StackdriverErrorReporter()
errorHandler.start({
key: firebase.apiKey,
projectId: firebase.projectId,
service: 'react-firebase-redux-site',
version
})
})
}
return errorHandler
}
|
javascript
|
function initStackdriverErrorReporter() {
if (typeof window.StackdriverErrorReporter === 'function') {
window.addEventListener('DOMContentLoaded', () => {
const errorHandler = new window.StackdriverErrorReporter()
errorHandler.start({
key: firebase.apiKey,
projectId: firebase.projectId,
service: 'react-firebase-redux-site',
version
})
})
}
return errorHandler
}
|
[
"function",
"initStackdriverErrorReporter",
"(",
")",
"{",
"if",
"(",
"typeof",
"window",
".",
"StackdriverErrorReporter",
"===",
"'function'",
")",
"{",
"window",
".",
"addEventListener",
"(",
"'DOMContentLoaded'",
",",
"(",
")",
"=>",
"{",
"const",
"errorHandler",
"=",
"new",
"window",
".",
"StackdriverErrorReporter",
"(",
")",
"errorHandler",
".",
"start",
"(",
"{",
"key",
":",
"firebase",
".",
"apiKey",
",",
"projectId",
":",
"firebase",
".",
"projectId",
",",
"service",
":",
"'react-firebase-redux-site'",
",",
"version",
"}",
")",
"}",
")",
"}",
"return",
"errorHandler",
"}"
] |
Initialize Stackdriver Error Reporter only if api key exists
|
[
"Initialize",
"Stackdriver",
"Error",
"Reporter",
"only",
"if",
"api",
"key",
"exists"
] |
8f044b05da7a034018a6384b081df9d380ac22dd
|
https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/react-firebase-redux/src/utils/errorHandler.js#L9-L22
|
13,376
|
prescottprue/generator-react-firebase
|
examples/redux-firestore/src/utils/analytics.js
|
initGA
|
function initGA() {
if (analyticsTrackingId) {
ReactGA.initialize(analyticsTrackingId)
ReactGA.set({
appName: environment || 'Production',
appVersion: version
})
}
}
|
javascript
|
function initGA() {
if (analyticsTrackingId) {
ReactGA.initialize(analyticsTrackingId)
ReactGA.set({
appName: environment || 'Production',
appVersion: version
})
}
}
|
[
"function",
"initGA",
"(",
")",
"{",
"if",
"(",
"analyticsTrackingId",
")",
"{",
"ReactGA",
".",
"initialize",
"(",
"analyticsTrackingId",
")",
"ReactGA",
".",
"set",
"(",
"{",
"appName",
":",
"environment",
"||",
"'Production'",
",",
"appVersion",
":",
"version",
"}",
")",
"}",
"}"
] |
Initialize Google Analytics if analytics id exists and environment is
production
|
[
"Initialize",
"Google",
"Analytics",
"if",
"analytics",
"id",
"exists",
"and",
"environment",
"is",
"production"
] |
8f044b05da7a034018a6384b081df9d380ac22dd
|
https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/redux-firestore/src/utils/analytics.js#L9-L17
|
13,377
|
prescottprue/generator-react-firebase
|
examples/redux-firestore/src/utils/analytics.js
|
setGAUser
|
function setGAUser(auth) {
if (auth && auth.uid) {
ReactGA.set({ userId: auth.uid })
}
}
|
javascript
|
function setGAUser(auth) {
if (auth && auth.uid) {
ReactGA.set({ userId: auth.uid })
}
}
|
[
"function",
"setGAUser",
"(",
"auth",
")",
"{",
"if",
"(",
"auth",
"&&",
"auth",
".",
"uid",
")",
"{",
"ReactGA",
".",
"set",
"(",
"{",
"userId",
":",
"auth",
".",
"uid",
"}",
")",
"}",
"}"
] |
Set user auth data within Google Analytics
@param {Object} auth - Authentication data
@param {String} auth.uid - User's id
|
[
"Set",
"user",
"auth",
"data",
"within",
"Google",
"Analytics"
] |
8f044b05da7a034018a6384b081df9d380ac22dd
|
https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/redux-firestore/src/utils/analytics.js#L36-L40
|
13,378
|
ai/audio-recorder-polyfill
|
index.js
|
MediaRecorder
|
function MediaRecorder (stream) {
/**
* The `MediaStream` passed into the constructor.
* @type {MediaStream}
*/
this.stream = stream
/**
* The current state of recording process.
* @type {"inactive"|"recording"|"paused"}
*/
this.state = 'inactive'
this.em = document.createDocumentFragment()
this.encoder = createWorker(MediaRecorder.encoder)
var recorder = this
this.encoder.addEventListener('message', function (e) {
var event = new Event('dataavailable')
event.data = new Blob([e.data], { type: recorder.mimeType })
recorder.em.dispatchEvent(event)
if (recorder.state === 'inactive') {
recorder.em.dispatchEvent(new Event('stop'))
}
})
}
|
javascript
|
function MediaRecorder (stream) {
/**
* The `MediaStream` passed into the constructor.
* @type {MediaStream}
*/
this.stream = stream
/**
* The current state of recording process.
* @type {"inactive"|"recording"|"paused"}
*/
this.state = 'inactive'
this.em = document.createDocumentFragment()
this.encoder = createWorker(MediaRecorder.encoder)
var recorder = this
this.encoder.addEventListener('message', function (e) {
var event = new Event('dataavailable')
event.data = new Blob([e.data], { type: recorder.mimeType })
recorder.em.dispatchEvent(event)
if (recorder.state === 'inactive') {
recorder.em.dispatchEvent(new Event('stop'))
}
})
}
|
[
"function",
"MediaRecorder",
"(",
"stream",
")",
"{",
"/**\n * The `MediaStream` passed into the constructor.\n * @type {MediaStream}\n */",
"this",
".",
"stream",
"=",
"stream",
"/**\n * The current state of recording process.\n * @type {\"inactive\"|\"recording\"|\"paused\"}\n */",
"this",
".",
"state",
"=",
"'inactive'",
"this",
".",
"em",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
"this",
".",
"encoder",
"=",
"createWorker",
"(",
"MediaRecorder",
".",
"encoder",
")",
"var",
"recorder",
"=",
"this",
"this",
".",
"encoder",
".",
"addEventListener",
"(",
"'message'",
",",
"function",
"(",
"e",
")",
"{",
"var",
"event",
"=",
"new",
"Event",
"(",
"'dataavailable'",
")",
"event",
".",
"data",
"=",
"new",
"Blob",
"(",
"[",
"e",
".",
"data",
"]",
",",
"{",
"type",
":",
"recorder",
".",
"mimeType",
"}",
")",
"recorder",
".",
"em",
".",
"dispatchEvent",
"(",
"event",
")",
"if",
"(",
"recorder",
".",
"state",
"===",
"'inactive'",
")",
"{",
"recorder",
".",
"em",
".",
"dispatchEvent",
"(",
"new",
"Event",
"(",
"'stop'",
")",
")",
"}",
"}",
")",
"}"
] |
Audio Recorder with MediaRecorder API.
@param {MediaStream} stream The audio stream to record.
@example
navigator.mediaDevices.getUserMedia({ audio: true }).then(function (stream) {
var recorder = new MediaRecorder(stream)
})
@class
|
[
"Audio",
"Recorder",
"with",
"MediaRecorder",
"API",
"."
] |
9025a1d0003b0ade09de42a7ea682bf20b5c0224
|
https://github.com/ai/audio-recorder-polyfill/blob/9025a1d0003b0ade09de42a7ea682bf20b5c0224/index.js#L32-L57
|
13,379
|
ai/audio-recorder-polyfill
|
index.js
|
start
|
function start (timeslice) {
if (this.state !== 'inactive') {
return this.em.dispatchEvent(error('start'))
}
this.state = 'recording'
if (!context) {
context = new AudioContext()
}
this.clone = this.stream.clone()
var input = context.createMediaStreamSource(this.clone)
if (!processor) {
processor = context.createScriptProcessor(2048, 1, 1)
}
var recorder = this
processor.onaudioprocess = function (e) {
if (recorder.state === 'recording') {
recorder.encoder.postMessage([
'encode', e.inputBuffer.getChannelData(0)
])
}
}
input.connect(processor)
processor.connect(context.destination)
this.em.dispatchEvent(new Event('start'))
if (timeslice) {
this.slicing = setInterval(function () {
if (recorder.state === 'recording') recorder.requestData()
}, timeslice)
}
return undefined
}
|
javascript
|
function start (timeslice) {
if (this.state !== 'inactive') {
return this.em.dispatchEvent(error('start'))
}
this.state = 'recording'
if (!context) {
context = new AudioContext()
}
this.clone = this.stream.clone()
var input = context.createMediaStreamSource(this.clone)
if (!processor) {
processor = context.createScriptProcessor(2048, 1, 1)
}
var recorder = this
processor.onaudioprocess = function (e) {
if (recorder.state === 'recording') {
recorder.encoder.postMessage([
'encode', e.inputBuffer.getChannelData(0)
])
}
}
input.connect(processor)
processor.connect(context.destination)
this.em.dispatchEvent(new Event('start'))
if (timeslice) {
this.slicing = setInterval(function () {
if (recorder.state === 'recording') recorder.requestData()
}, timeslice)
}
return undefined
}
|
[
"function",
"start",
"(",
"timeslice",
")",
"{",
"if",
"(",
"this",
".",
"state",
"!==",
"'inactive'",
")",
"{",
"return",
"this",
".",
"em",
".",
"dispatchEvent",
"(",
"error",
"(",
"'start'",
")",
")",
"}",
"this",
".",
"state",
"=",
"'recording'",
"if",
"(",
"!",
"context",
")",
"{",
"context",
"=",
"new",
"AudioContext",
"(",
")",
"}",
"this",
".",
"clone",
"=",
"this",
".",
"stream",
".",
"clone",
"(",
")",
"var",
"input",
"=",
"context",
".",
"createMediaStreamSource",
"(",
"this",
".",
"clone",
")",
"if",
"(",
"!",
"processor",
")",
"{",
"processor",
"=",
"context",
".",
"createScriptProcessor",
"(",
"2048",
",",
"1",
",",
"1",
")",
"}",
"var",
"recorder",
"=",
"this",
"processor",
".",
"onaudioprocess",
"=",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"recorder",
".",
"state",
"===",
"'recording'",
")",
"{",
"recorder",
".",
"encoder",
".",
"postMessage",
"(",
"[",
"'encode'",
",",
"e",
".",
"inputBuffer",
".",
"getChannelData",
"(",
"0",
")",
"]",
")",
"}",
"}",
"input",
".",
"connect",
"(",
"processor",
")",
"processor",
".",
"connect",
"(",
"context",
".",
"destination",
")",
"this",
".",
"em",
".",
"dispatchEvent",
"(",
"new",
"Event",
"(",
"'start'",
")",
")",
"if",
"(",
"timeslice",
")",
"{",
"this",
".",
"slicing",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"recorder",
".",
"state",
"===",
"'recording'",
")",
"recorder",
".",
"requestData",
"(",
")",
"}",
",",
"timeslice",
")",
"}",
"return",
"undefined",
"}"
] |
Begins recording media.
@param {number} [timeslice] The milliseconds to record into each `Blob`.
If this parameter isn’t included, single `Blob`
will be recorded.
@return {undefined}
@example
recordButton.addEventListener('click', function () {
recorder.start()
})
|
[
"Begins",
"recording",
"media",
"."
] |
9025a1d0003b0ade09de42a7ea682bf20b5c0224
|
https://github.com/ai/audio-recorder-polyfill/blob/9025a1d0003b0ade09de42a7ea682bf20b5c0224/index.js#L80-L118
|
13,380
|
ai/audio-recorder-polyfill
|
index.js
|
stop
|
function stop () {
if (this.state === 'inactive') {
return this.em.dispatchEvent(error('stop'))
}
this.requestData()
this.state = 'inactive'
this.clone.getTracks().forEach(function (track) {
track.stop()
})
return clearInterval(this.slicing)
}
|
javascript
|
function stop () {
if (this.state === 'inactive') {
return this.em.dispatchEvent(error('stop'))
}
this.requestData()
this.state = 'inactive'
this.clone.getTracks().forEach(function (track) {
track.stop()
})
return clearInterval(this.slicing)
}
|
[
"function",
"stop",
"(",
")",
"{",
"if",
"(",
"this",
".",
"state",
"===",
"'inactive'",
")",
"{",
"return",
"this",
".",
"em",
".",
"dispatchEvent",
"(",
"error",
"(",
"'stop'",
")",
")",
"}",
"this",
".",
"requestData",
"(",
")",
"this",
".",
"state",
"=",
"'inactive'",
"this",
".",
"clone",
".",
"getTracks",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"track",
")",
"{",
"track",
".",
"stop",
"(",
")",
"}",
")",
"return",
"clearInterval",
"(",
"this",
".",
"slicing",
")",
"}"
] |
Stop media capture and raise `dataavailable` event with recorded data.
@return {undefined}
@example
finishButton.addEventListener('click', function () {
recorder.stop()
})
|
[
"Stop",
"media",
"capture",
"and",
"raise",
"dataavailable",
"event",
"with",
"recorded",
"data",
"."
] |
9025a1d0003b0ade09de42a7ea682bf20b5c0224
|
https://github.com/ai/audio-recorder-polyfill/blob/9025a1d0003b0ade09de42a7ea682bf20b5c0224/index.js#L130-L141
|
13,381
|
jaggedsoft/node-binance-api
|
examples/balances-and-exchangeInfo.js
|
balance
|
function balance() {
binance.balance((error, balances) => {
if ( error ) console.error(error);
let btc = 0.00;
for ( let asset in balances ) {
let obj = balances[asset];
obj.available = parseFloat(obj.available);
//if ( !obj.available ) continue;
obj.onOrder = parseFloat(obj.onOrder);
obj.btcValue = 0;
obj.btcTotal = 0;
if ( asset == 'BTC' ) obj.btcValue = obj.available;
else if ( asset == 'USDT' ) obj.btcValue = obj.available / global.ticker.BTCUSDT;
else obj.btcValue = obj.available * global.ticker[asset+'BTC'];
if ( asset == 'BTC' ) obj.btcTotal = obj.available + obj.onOrder;
else if ( asset == 'USDT' ) obj.btcTotal = (obj.available + obj.onOrder) / global.ticker.BTCUSDT;
else obj.btcTotal = (obj.available + obj.onOrder) * global.ticker[asset+'BTC'];
if ( isNaN(obj.btcValue) ) obj.btcValue = 0;
if ( isNaN(obj.btcTotal) ) obj.btcTotal = 0;
btc+= obj.btcTotal;
global.balance[asset] = obj;
}
//fs.writeFile("json/balance.json", JSON.stringify(global.balance, null, 4), (err)=>{});
});
}
|
javascript
|
function balance() {
binance.balance((error, balances) => {
if ( error ) console.error(error);
let btc = 0.00;
for ( let asset in balances ) {
let obj = balances[asset];
obj.available = parseFloat(obj.available);
//if ( !obj.available ) continue;
obj.onOrder = parseFloat(obj.onOrder);
obj.btcValue = 0;
obj.btcTotal = 0;
if ( asset == 'BTC' ) obj.btcValue = obj.available;
else if ( asset == 'USDT' ) obj.btcValue = obj.available / global.ticker.BTCUSDT;
else obj.btcValue = obj.available * global.ticker[asset+'BTC'];
if ( asset == 'BTC' ) obj.btcTotal = obj.available + obj.onOrder;
else if ( asset == 'USDT' ) obj.btcTotal = (obj.available + obj.onOrder) / global.ticker.BTCUSDT;
else obj.btcTotal = (obj.available + obj.onOrder) * global.ticker[asset+'BTC'];
if ( isNaN(obj.btcValue) ) obj.btcValue = 0;
if ( isNaN(obj.btcTotal) ) obj.btcTotal = 0;
btc+= obj.btcTotal;
global.balance[asset] = obj;
}
//fs.writeFile("json/balance.json", JSON.stringify(global.balance, null, 4), (err)=>{});
});
}
|
[
"function",
"balance",
"(",
")",
"{",
"binance",
".",
"balance",
"(",
"(",
"error",
",",
"balances",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"console",
".",
"error",
"(",
"error",
")",
";",
"let",
"btc",
"=",
"0.00",
";",
"for",
"(",
"let",
"asset",
"in",
"balances",
")",
"{",
"let",
"obj",
"=",
"balances",
"[",
"asset",
"]",
";",
"obj",
".",
"available",
"=",
"parseFloat",
"(",
"obj",
".",
"available",
")",
";",
"//if ( !obj.available ) continue;",
"obj",
".",
"onOrder",
"=",
"parseFloat",
"(",
"obj",
".",
"onOrder",
")",
";",
"obj",
".",
"btcValue",
"=",
"0",
";",
"obj",
".",
"btcTotal",
"=",
"0",
";",
"if",
"(",
"asset",
"==",
"'BTC'",
")",
"obj",
".",
"btcValue",
"=",
"obj",
".",
"available",
";",
"else",
"if",
"(",
"asset",
"==",
"'USDT'",
")",
"obj",
".",
"btcValue",
"=",
"obj",
".",
"available",
"/",
"global",
".",
"ticker",
".",
"BTCUSDT",
";",
"else",
"obj",
".",
"btcValue",
"=",
"obj",
".",
"available",
"*",
"global",
".",
"ticker",
"[",
"asset",
"+",
"'BTC'",
"]",
";",
"if",
"(",
"asset",
"==",
"'BTC'",
")",
"obj",
".",
"btcTotal",
"=",
"obj",
".",
"available",
"+",
"obj",
".",
"onOrder",
";",
"else",
"if",
"(",
"asset",
"==",
"'USDT'",
")",
"obj",
".",
"btcTotal",
"=",
"(",
"obj",
".",
"available",
"+",
"obj",
".",
"onOrder",
")",
"/",
"global",
".",
"ticker",
".",
"BTCUSDT",
";",
"else",
"obj",
".",
"btcTotal",
"=",
"(",
"obj",
".",
"available",
"+",
"obj",
".",
"onOrder",
")",
"*",
"global",
".",
"ticker",
"[",
"asset",
"+",
"'BTC'",
"]",
";",
"if",
"(",
"isNaN",
"(",
"obj",
".",
"btcValue",
")",
")",
"obj",
".",
"btcValue",
"=",
"0",
";",
"if",
"(",
"isNaN",
"(",
"obj",
".",
"btcTotal",
")",
")",
"obj",
".",
"btcTotal",
"=",
"0",
";",
"btc",
"+=",
"obj",
".",
"btcTotal",
";",
"global",
".",
"balance",
"[",
"asset",
"]",
"=",
"obj",
";",
"}",
"//fs.writeFile(\"json/balance.json\", JSON.stringify(global.balance, null, 4), (err)=>{});",
"}",
")",
";",
"}"
] |
Get your balances
|
[
"Get",
"your",
"balances"
] |
1d6c9e4c19b7cab928e462c12a7dcdd0fbe8ff71
|
https://github.com/jaggedsoft/node-binance-api/blob/1d6c9e4c19b7cab928e462c12a7dcdd0fbe8ff71/examples/balances-and-exchangeInfo.js#L47-L71
|
13,382
|
microstates/microstates.js
|
src/reflection.js
|
getAllPropertyDescriptors
|
function getAllPropertyDescriptors(object) {
if (object === Object.prototype) {
return {};
} else {
let prototype = getPrototypeOf(object);
return assign(getAllPropertyDescriptors(prototype), getOwnPropertyDescriptors(object));
}
}
|
javascript
|
function getAllPropertyDescriptors(object) {
if (object === Object.prototype) {
return {};
} else {
let prototype = getPrototypeOf(object);
return assign(getAllPropertyDescriptors(prototype), getOwnPropertyDescriptors(object));
}
}
|
[
"function",
"getAllPropertyDescriptors",
"(",
"object",
")",
"{",
"if",
"(",
"object",
"===",
"Object",
".",
"prototype",
")",
"{",
"return",
"{",
"}",
";",
"}",
"else",
"{",
"let",
"prototype",
"=",
"getPrototypeOf",
"(",
"object",
")",
";",
"return",
"assign",
"(",
"getAllPropertyDescriptors",
"(",
"prototype",
")",
",",
"getOwnPropertyDescriptors",
"(",
"object",
")",
")",
";",
"}",
"}"
] |
As opposed to `getOwnPropertyDescriptors` which only gets the
descriptors on a single object, `getAllPropertydescriptors` walks
the entire prototype chain starting at `prototype` and gather all
descriptors that are accessible to this object.
|
[
"As",
"opposed",
"to",
"getOwnPropertyDescriptors",
"which",
"only",
"gets",
"the",
"descriptors",
"on",
"a",
"single",
"object",
"getAllPropertydescriptors",
"walks",
"the",
"entire",
"prototype",
"chain",
"starting",
"at",
"prototype",
"and",
"gather",
"all",
"descriptors",
"that",
"are",
"accessible",
"to",
"this",
"object",
"."
] |
cd4114be8d9c26f4e68b520adc1380d26c9ba38a
|
https://github.com/microstates/microstates.js/blob/cd4114be8d9c26f4e68b520adc1380d26c9ba38a/src/reflection.js#L17-L24
|
13,383
|
FormidableLabs/rapscallion
|
src/consumers/node-stream.js
|
toNodeStream
|
function toNodeStream (renderer) {
let sourceIsReady = true;
const read = () => {
// If source is not ready, defer any reads until the promise resolves.
if (!sourceIsReady) { return false; }
sourceIsReady = false;
const pull = pullBatch(renderer, stream);
return pull.then(result => {
sourceIsReady = true;
if (result === EXHAUSTED) {
return stream.push(null);
} else {
if (result !== INCOMPLETE) {
stream.push(result);
}
return read();
}
}).catch(err => {
return stream.emit("error", err);
});
};
const stream = new Readable({ read });
return stream;
}
|
javascript
|
function toNodeStream (renderer) {
let sourceIsReady = true;
const read = () => {
// If source is not ready, defer any reads until the promise resolves.
if (!sourceIsReady) { return false; }
sourceIsReady = false;
const pull = pullBatch(renderer, stream);
return pull.then(result => {
sourceIsReady = true;
if (result === EXHAUSTED) {
return stream.push(null);
} else {
if (result !== INCOMPLETE) {
stream.push(result);
}
return read();
}
}).catch(err => {
return stream.emit("error", err);
});
};
const stream = new Readable({ read });
return stream;
}
|
[
"function",
"toNodeStream",
"(",
"renderer",
")",
"{",
"let",
"sourceIsReady",
"=",
"true",
";",
"const",
"read",
"=",
"(",
")",
"=>",
"{",
"// If source is not ready, defer any reads until the promise resolves.",
"if",
"(",
"!",
"sourceIsReady",
")",
"{",
"return",
"false",
";",
"}",
"sourceIsReady",
"=",
"false",
";",
"const",
"pull",
"=",
"pullBatch",
"(",
"renderer",
",",
"stream",
")",
";",
"return",
"pull",
".",
"then",
"(",
"result",
"=>",
"{",
"sourceIsReady",
"=",
"true",
";",
"if",
"(",
"result",
"===",
"EXHAUSTED",
")",
"{",
"return",
"stream",
".",
"push",
"(",
"null",
")",
";",
"}",
"else",
"{",
"if",
"(",
"result",
"!==",
"INCOMPLETE",
")",
"{",
"stream",
".",
"push",
"(",
"result",
")",
";",
"}",
"return",
"read",
"(",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"return",
"stream",
".",
"emit",
"(",
"\"error\"",
",",
"err",
")",
";",
"}",
")",
";",
"}",
";",
"const",
"stream",
"=",
"new",
"Readable",
"(",
"{",
"read",
"}",
")",
";",
"return",
"stream",
";",
"}"
] |
Consumes the provided sequence and pushes onto a readable Node stream.
@param {Renderer} renderer The Renderer from which to pull next-vals.
@return {Readable} A readable Node stream.
|
[
"Consumes",
"the",
"provided",
"sequence",
"and",
"pushes",
"onto",
"a",
"readable",
"Node",
"stream",
"."
] |
20a8f67778dbc9d224588ee718cb962ddbd71f48
|
https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/consumers/node-stream.js#L14-L42
|
13,384
|
FormidableLabs/rapscallion
|
src/render/traverse.js
|
evalComponent
|
function evalComponent (seq, node, context) {
const Component = node.type;
const componentContext = getContext(Component, context);
const instance = constructComponent(Component, node.props, componentContext);
const renderedElement = renderComponentInstance(instance, node.props, componentContext);
const childContext = getChildContext(Component, instance, context);
traverse({
seq,
node: renderedElement,
context: childContext,
parent: node
});
}
|
javascript
|
function evalComponent (seq, node, context) {
const Component = node.type;
const componentContext = getContext(Component, context);
const instance = constructComponent(Component, node.props, componentContext);
const renderedElement = renderComponentInstance(instance, node.props, componentContext);
const childContext = getChildContext(Component, instance, context);
traverse({
seq,
node: renderedElement,
context: childContext,
parent: node
});
}
|
[
"function",
"evalComponent",
"(",
"seq",
",",
"node",
",",
"context",
")",
"{",
"const",
"Component",
"=",
"node",
".",
"type",
";",
"const",
"componentContext",
"=",
"getContext",
"(",
"Component",
",",
"context",
")",
";",
"const",
"instance",
"=",
"constructComponent",
"(",
"Component",
",",
"node",
".",
"props",
",",
"componentContext",
")",
";",
"const",
"renderedElement",
"=",
"renderComponentInstance",
"(",
"instance",
",",
"node",
".",
"props",
",",
"componentContext",
")",
";",
"const",
"childContext",
"=",
"getChildContext",
"(",
"Component",
",",
"instance",
",",
"context",
")",
";",
"traverse",
"(",
"{",
"seq",
",",
"node",
":",
"renderedElement",
",",
"context",
":",
"childContext",
",",
"parent",
":",
"node",
"}",
")",
";",
"}"
] |
Prior to being rendered, React components are represented in the same
way as true HTML DOM elements. This function evaluates the component
and traverses through its rendered elements.
@param {Sequence} seq Sequence that receives HTML segments.
@param {VDOM} node VOM node (of a component).
@param {Object} context React context.
@return {undefined} No return value.
|
[
"Prior",
"to",
"being",
"rendered",
"React",
"components",
"are",
"represented",
"in",
"the",
"same",
"way",
"as",
"true",
"HTML",
"DOM",
"elements",
".",
"This",
"function",
"evaluates",
"the",
"component",
"and",
"traverses",
"through",
"its",
"rendered",
"elements",
"."
] |
20a8f67778dbc9d224588ee718cb962ddbd71f48
|
https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/traverse.js#L121-L135
|
13,385
|
FormidableLabs/rapscallion
|
src/render/traverse.js
|
traverse
|
function traverse ({ seq, node, context, numChildren, parent }) {
if (node === undefined || node === true) {
return;
}
if (node === false) {
if (parent && isFunction(parent.type)) {
emitEmpty(seq);
return;
} else {
return;
}
}
if (node === null) {
emitEmpty(seq);
return;
}
switch (typeof node) {
case "string": {
// Text node.
emitText({
seq,
text: htmlStringEscape(node),
numChildren,
isNewlineEatingTag: Boolean(parent && newlineEatingTags[parent.type])
});
return;
}
case "number": {
emitText({
seq,
text: node.toString(),
numChildren
});
return;
}
case "object": {
if (node.__prerendered__) {
evalPreRendered(seq, node, context);
return;
} else if (typeof node.type === "string") {
// Plain-jane DOM element, not a React component.
seq.delegateCached(node, (_seq, _node) => renderNode(_seq, _node, context));
return;
} else if (node.$$typeof) {
// React component.
seq.delegateCached(node, (_seq, _node) => evalComponent(_seq, _node, context));
return;
}
}
}
throw new TypeError(`Unknown node of type: ${node.type}`);
}
|
javascript
|
function traverse ({ seq, node, context, numChildren, parent }) {
if (node === undefined || node === true) {
return;
}
if (node === false) {
if (parent && isFunction(parent.type)) {
emitEmpty(seq);
return;
} else {
return;
}
}
if (node === null) {
emitEmpty(seq);
return;
}
switch (typeof node) {
case "string": {
// Text node.
emitText({
seq,
text: htmlStringEscape(node),
numChildren,
isNewlineEatingTag: Boolean(parent && newlineEatingTags[parent.type])
});
return;
}
case "number": {
emitText({
seq,
text: node.toString(),
numChildren
});
return;
}
case "object": {
if (node.__prerendered__) {
evalPreRendered(seq, node, context);
return;
} else if (typeof node.type === "string") {
// Plain-jane DOM element, not a React component.
seq.delegateCached(node, (_seq, _node) => renderNode(_seq, _node, context));
return;
} else if (node.$$typeof) {
// React component.
seq.delegateCached(node, (_seq, _node) => evalComponent(_seq, _node, context));
return;
}
}
}
throw new TypeError(`Unknown node of type: ${node.type}`);
}
|
[
"function",
"traverse",
"(",
"{",
"seq",
",",
"node",
",",
"context",
",",
"numChildren",
",",
"parent",
"}",
")",
"{",
"if",
"(",
"node",
"===",
"undefined",
"||",
"node",
"===",
"true",
")",
"{",
"return",
";",
"}",
"if",
"(",
"node",
"===",
"false",
")",
"{",
"if",
"(",
"parent",
"&&",
"isFunction",
"(",
"parent",
".",
"type",
")",
")",
"{",
"emitEmpty",
"(",
"seq",
")",
";",
"return",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"if",
"(",
"node",
"===",
"null",
")",
"{",
"emitEmpty",
"(",
"seq",
")",
";",
"return",
";",
"}",
"switch",
"(",
"typeof",
"node",
")",
"{",
"case",
"\"string\"",
":",
"{",
"// Text node.",
"emitText",
"(",
"{",
"seq",
",",
"text",
":",
"htmlStringEscape",
"(",
"node",
")",
",",
"numChildren",
",",
"isNewlineEatingTag",
":",
"Boolean",
"(",
"parent",
"&&",
"newlineEatingTags",
"[",
"parent",
".",
"type",
"]",
")",
"}",
")",
";",
"return",
";",
"}",
"case",
"\"number\"",
":",
"{",
"emitText",
"(",
"{",
"seq",
",",
"text",
":",
"node",
".",
"toString",
"(",
")",
",",
"numChildren",
"}",
")",
";",
"return",
";",
"}",
"case",
"\"object\"",
":",
"{",
"if",
"(",
"node",
".",
"__prerendered__",
")",
"{",
"evalPreRendered",
"(",
"seq",
",",
"node",
",",
"context",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"typeof",
"node",
".",
"type",
"===",
"\"string\"",
")",
"{",
"// Plain-jane DOM element, not a React component.",
"seq",
".",
"delegateCached",
"(",
"node",
",",
"(",
"_seq",
",",
"_node",
")",
"=>",
"renderNode",
"(",
"_seq",
",",
"_node",
",",
"context",
")",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"node",
".",
"$$typeof",
")",
"{",
"// React component.",
"seq",
".",
"delegateCached",
"(",
"node",
",",
"(",
"_seq",
",",
"_node",
")",
"=>",
"evalComponent",
"(",
"_seq",
",",
"_node",
",",
"context",
")",
")",
";",
"return",
";",
"}",
"}",
"}",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"node",
".",
"type",
"}",
"`",
")",
";",
"}"
] |
This function will recursively traverse the VDOM tree, emitting HTML segments
to the provided sequence.
@param {Sequence} seq Sequence that receives HTML segments.
@param {VDOM} node Root VDOM node.
@param {Object} context React context.
@param {Number} numChildren number of children the parent node has
@return {undefined} No return value.
eslint-disable-next-line max-statements, complexity
|
[
"This",
"function",
"will",
"recursively",
"traverse",
"the",
"VDOM",
"tree",
"emitting",
"HTML",
"segments",
"to",
"the",
"provided",
"sequence",
"."
] |
20a8f67778dbc9d224588ee718cb962ddbd71f48
|
https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/traverse.js#L247-L304
|
13,386
|
FormidableLabs/rapscallion
|
src/render/state.js
|
syncSetState
|
function syncSetState (newState) {
// Mutation is faster and should be safe here.
this.state = assign(
this.state,
isFunction(newState) ?
newState(this.state, this.props) :
newState
);
}
|
javascript
|
function syncSetState (newState) {
// Mutation is faster and should be safe here.
this.state = assign(
this.state,
isFunction(newState) ?
newState(this.state, this.props) :
newState
);
}
|
[
"function",
"syncSetState",
"(",
"newState",
")",
"{",
"// Mutation is faster and should be safe here.",
"this",
".",
"state",
"=",
"assign",
"(",
"this",
".",
"state",
",",
"isFunction",
"(",
"newState",
")",
"?",
"newState",
"(",
"this",
".",
"state",
",",
"this",
".",
"props",
")",
":",
"newState",
")",
";",
"}"
] |
A synchronous replacement for React's `setState` method.
@param {Function|Object} newState An object containing new keys/values
or a function that will provide the same.
@returns {undefined} No return value.
|
[
"A",
"synchronous",
"replacement",
"for",
"React",
"s",
"setState",
"method",
"."
] |
20a8f67778dbc9d224588ee718cb962ddbd71f48
|
https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/state.js#L16-L24
|
13,387
|
FormidableLabs/rapscallion
|
src/consumers/promise.js
|
toPromise
|
function toPromise (renderer) {
// this.sequence, this.batchSize, this.dataReactAttrs
const buffer = {
value: [],
push (segment) { this.value.push(segment); }
};
return new Promise((resolve, reject) =>
setImmediate(
asyncBatch,
renderer,
buffer,
resolve,
reject
)
)
.then(() => Promise.all(buffer.value))
.then(chunks => {
let html = chunks
.filter(chunk => typeof chunk === "string")
.join("");
if (renderer.dataReactAttrs && !COMMENT_START.test(html)) {
const checksum = renderer.checksum();
html = html.replace(TAG_END, ` data-react-checksum="${checksum}"$&`);
}
return html;
});
}
|
javascript
|
function toPromise (renderer) {
// this.sequence, this.batchSize, this.dataReactAttrs
const buffer = {
value: [],
push (segment) { this.value.push(segment); }
};
return new Promise((resolve, reject) =>
setImmediate(
asyncBatch,
renderer,
buffer,
resolve,
reject
)
)
.then(() => Promise.all(buffer.value))
.then(chunks => {
let html = chunks
.filter(chunk => typeof chunk === "string")
.join("");
if (renderer.dataReactAttrs && !COMMENT_START.test(html)) {
const checksum = renderer.checksum();
html = html.replace(TAG_END, ` data-react-checksum="${checksum}"$&`);
}
return html;
});
}
|
[
"function",
"toPromise",
"(",
"renderer",
")",
"{",
"// this.sequence, this.batchSize, this.dataReactAttrs",
"const",
"buffer",
"=",
"{",
"value",
":",
"[",
"]",
",",
"push",
"(",
"segment",
")",
"{",
"this",
".",
"value",
".",
"push",
"(",
"segment",
")",
";",
"}",
"}",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"setImmediate",
"(",
"asyncBatch",
",",
"renderer",
",",
"buffer",
",",
"resolve",
",",
"reject",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"Promise",
".",
"all",
"(",
"buffer",
".",
"value",
")",
")",
".",
"then",
"(",
"chunks",
"=>",
"{",
"let",
"html",
"=",
"chunks",
".",
"filter",
"(",
"chunk",
"=>",
"typeof",
"chunk",
"===",
"\"string\"",
")",
".",
"join",
"(",
"\"\"",
")",
";",
"if",
"(",
"renderer",
".",
"dataReactAttrs",
"&&",
"!",
"COMMENT_START",
".",
"test",
"(",
"html",
")",
")",
"{",
"const",
"checksum",
"=",
"renderer",
".",
"checksum",
"(",
")",
";",
"html",
"=",
"html",
".",
"replace",
"(",
"TAG_END",
",",
"`",
"${",
"checksum",
"}",
"`",
")",
";",
"}",
"return",
"html",
";",
"}",
")",
";",
"}"
] |
Consumes the provided sequence and returns a promise with the concatenation of all
sequence segments.
@param {Renderer} renderer The Renderer from which to pull next-vals.
@return {Promise} A promise resolving to the HTML string.
|
[
"Consumes",
"the",
"provided",
"sequence",
"and",
"returns",
"a",
"promise",
"with",
"the",
"concatenation",
"of",
"all",
"sequence",
"segments",
"."
] |
20a8f67778dbc9d224588ee718cb962ddbd71f48
|
https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/consumers/promise.js#L46-L75
|
13,388
|
FormidableLabs/rapscallion
|
src/render/context.js
|
getChildContext
|
function getChildContext (componentPrototype, instance, context) {
if (componentPrototype.childContextTypes) {
return assign(Object.create(null), context, instance.getChildContext());
}
return context;
}
|
javascript
|
function getChildContext (componentPrototype, instance, context) {
if (componentPrototype.childContextTypes) {
return assign(Object.create(null), context, instance.getChildContext());
}
return context;
}
|
[
"function",
"getChildContext",
"(",
"componentPrototype",
",",
"instance",
",",
"context",
")",
"{",
"if",
"(",
"componentPrototype",
".",
"childContextTypes",
")",
"{",
"return",
"assign",
"(",
"Object",
".",
"create",
"(",
"null",
")",
",",
"context",
",",
"instance",
".",
"getChildContext",
"(",
")",
")",
";",
"}",
"return",
"context",
";",
"}"
] |
Using a component prototype's `childContextTypes`, generate an
object that will merged into the master traversal context for
that component's subtree.
@param {Component} componentPrototype The component prototype.
@param {component} instance Component instance.
@param {Object} context The master context propagating through
the traversal.
@return {Object} Child context merged into master context.
|
[
"Using",
"a",
"component",
"prototype",
"s",
"childContextTypes",
"generate",
"an",
"object",
"that",
"will",
"merged",
"into",
"the",
"master",
"traversal",
"context",
"for",
"that",
"component",
"s",
"subtree",
"."
] |
20a8f67778dbc9d224588ee718cb962ddbd71f48
|
https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/context.js#L22-L27
|
13,389
|
FormidableLabs/rapscallion
|
src/render/context.js
|
getContext
|
function getContext (componentPrototype, context) {
if (componentPrototype.contextTypes) {
const contextTypes = componentPrototype.contextTypes;
return keys(context).reduce(
(memo, contextKey) => {
if (contextKey in contextTypes) {
memo[contextKey] = context[contextKey];
}
return memo;
},
Object.create(null)
);
}
return EMPTY_CONTEXT;
}
|
javascript
|
function getContext (componentPrototype, context) {
if (componentPrototype.contextTypes) {
const contextTypes = componentPrototype.contextTypes;
return keys(context).reduce(
(memo, contextKey) => {
if (contextKey in contextTypes) {
memo[contextKey] = context[contextKey];
}
return memo;
},
Object.create(null)
);
}
return EMPTY_CONTEXT;
}
|
[
"function",
"getContext",
"(",
"componentPrototype",
",",
"context",
")",
"{",
"if",
"(",
"componentPrototype",
".",
"contextTypes",
")",
"{",
"const",
"contextTypes",
"=",
"componentPrototype",
".",
"contextTypes",
";",
"return",
"keys",
"(",
"context",
")",
".",
"reduce",
"(",
"(",
"memo",
",",
"contextKey",
")",
"=>",
"{",
"if",
"(",
"contextKey",
"in",
"contextTypes",
")",
"{",
"memo",
"[",
"contextKey",
"]",
"=",
"context",
"[",
"contextKey",
"]",
";",
"}",
"return",
"memo",
";",
"}",
",",
"Object",
".",
"create",
"(",
"null",
")",
")",
";",
"}",
"return",
"EMPTY_CONTEXT",
";",
"}"
] |
Using a component prototype's `contextTypes`, generate an object that
will be used as React context for a component instance.
@param {Component} componentPrototype The component prototype.
@param {Object} context The master context propagating through
traversal.
@return {Object} The generated context object.
|
[
"Using",
"a",
"component",
"prototype",
"s",
"contextTypes",
"generate",
"an",
"object",
"that",
"will",
"be",
"used",
"as",
"React",
"context",
"for",
"a",
"component",
"instance",
"."
] |
20a8f67778dbc9d224588ee718cb962ddbd71f48
|
https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/context.js#L39-L53
|
13,390
|
geowarin/friendly-errors-webpack-plugin
|
src/core/transformErrors.js
|
processErrors
|
function processErrors (errors, transformers) {
const transform = (error, transformer) => transformer(error);
const applyTransformations = (error) => transformers.reduce(transform, error);
return errors.map(extractError).map(applyTransformations);
}
|
javascript
|
function processErrors (errors, transformers) {
const transform = (error, transformer) => transformer(error);
const applyTransformations = (error) => transformers.reduce(transform, error);
return errors.map(extractError).map(applyTransformations);
}
|
[
"function",
"processErrors",
"(",
"errors",
",",
"transformers",
")",
"{",
"const",
"transform",
"=",
"(",
"error",
",",
"transformer",
")",
"=>",
"transformer",
"(",
"error",
")",
";",
"const",
"applyTransformations",
"=",
"(",
"error",
")",
"=>",
"transformers",
".",
"reduce",
"(",
"transform",
",",
"error",
")",
";",
"return",
"errors",
".",
"map",
"(",
"extractError",
")",
".",
"map",
"(",
"applyTransformations",
")",
";",
"}"
] |
Applies all transformers to all errors and returns "annotated"
errors.
Each transformer should have the following signature WebpackError => AnnotatedError
A WebpackError has the following fields:
- message
- file
- origin
- name
- severity
- webpackError (original error)
An AnnotatedError should be an extension (Object.assign) of the WebpackError
and add whatever information is convenient for formatting.
In particular, they should have a 'priority' field.
The plugin will only display errors having maximum priority at the same time.
If they don't have a 'type' field, the will be handled by the default formatter.
|
[
"Applies",
"all",
"transformers",
"to",
"all",
"errors",
"and",
"returns",
"annotated",
"errors",
"."
] |
e02907b855288bd91e369b21714bdc2b6417d82b
|
https://github.com/geowarin/friendly-errors-webpack-plugin/blob/e02907b855288bd91e369b21714bdc2b6417d82b/src/core/transformErrors.js#L27-L32
|
13,391
|
geowarin/friendly-errors-webpack-plugin
|
src/formatters/defaultError.js
|
format
|
function format(errors, type) {
return errors
.filter(isDefaultError)
.reduce((accum, error) => (
accum.concat(displayError(type, error))
), []);
}
|
javascript
|
function format(errors, type) {
return errors
.filter(isDefaultError)
.reduce((accum, error) => (
accum.concat(displayError(type, error))
), []);
}
|
[
"function",
"format",
"(",
"errors",
",",
"type",
")",
"{",
"return",
"errors",
".",
"filter",
"(",
"isDefaultError",
")",
".",
"reduce",
"(",
"(",
"accum",
",",
"error",
")",
"=>",
"(",
"accum",
".",
"concat",
"(",
"displayError",
"(",
"type",
",",
"error",
")",
")",
")",
",",
"[",
"]",
")",
";",
"}"
] |
Format errors without a type
|
[
"Format",
"errors",
"without",
"a",
"type"
] |
e02907b855288bd91e369b21714bdc2b6417d82b
|
https://github.com/geowarin/friendly-errors-webpack-plugin/blob/e02907b855288bd91e369b21714bdc2b6417d82b/src/formatters/defaultError.js#L35-L41
|
13,392
|
geowarin/friendly-errors-webpack-plugin
|
src/core/formatErrors.js
|
formatErrors
|
function formatErrors(errors, formatters, errorType) {
const format = (formatter) => formatter(errors, errorType) || [];
const flatten = (accum, curr) => accum.concat(curr);
return formatters.map(format).reduce(flatten, [])
}
|
javascript
|
function formatErrors(errors, formatters, errorType) {
const format = (formatter) => formatter(errors, errorType) || [];
const flatten = (accum, curr) => accum.concat(curr);
return formatters.map(format).reduce(flatten, [])
}
|
[
"function",
"formatErrors",
"(",
"errors",
",",
"formatters",
",",
"errorType",
")",
"{",
"const",
"format",
"=",
"(",
"formatter",
")",
"=>",
"formatter",
"(",
"errors",
",",
"errorType",
")",
"||",
"[",
"]",
";",
"const",
"flatten",
"=",
"(",
"accum",
",",
"curr",
")",
"=>",
"accum",
".",
"concat",
"(",
"curr",
")",
";",
"return",
"formatters",
".",
"map",
"(",
"format",
")",
".",
"reduce",
"(",
"flatten",
",",
"[",
"]",
")",
"}"
] |
Applies formatters to all AnnotatedErrors.
A formatter has the following signature: FormattedError => Array<String>.
It takes a formatted error produced by a transformer and returns a list
of log statements to print.
|
[
"Applies",
"formatters",
"to",
"all",
"AnnotatedErrors",
"."
] |
e02907b855288bd91e369b21714bdc2b6417d82b
|
https://github.com/geowarin/friendly-errors-webpack-plugin/blob/e02907b855288bd91e369b21714bdc2b6417d82b/src/core/formatErrors.js#L11-L16
|
13,393
|
creativelive/appear
|
lib/appearlazy.js
|
doReveal
|
function doReveal(el) {
var orig = el.getAttribute('src') || false;
el.addEventListener('error', function handler(e) {
// on error put back the original image if available (usually a placeholder)
console.log('error loading image', e);
if (orig) {
el.setAttribute('src', orig);
}
el.removeEventListener('error', handler); // hate this.
});
var src = el.getAttribute('data-src');
if (src) {
el.setAttribute('src', src);
addClass(el);
return;
}
src = el.getAttribute('data-bkg');
if (src) {
el.style.backgroundImage = 'url("' + src + '")';
addClass(el);
return;
}
}
|
javascript
|
function doReveal(el) {
var orig = el.getAttribute('src') || false;
el.addEventListener('error', function handler(e) {
// on error put back the original image if available (usually a placeholder)
console.log('error loading image', e);
if (orig) {
el.setAttribute('src', orig);
}
el.removeEventListener('error', handler); // hate this.
});
var src = el.getAttribute('data-src');
if (src) {
el.setAttribute('src', src);
addClass(el);
return;
}
src = el.getAttribute('data-bkg');
if (src) {
el.style.backgroundImage = 'url("' + src + '")';
addClass(el);
return;
}
}
|
[
"function",
"doReveal",
"(",
"el",
")",
"{",
"var",
"orig",
"=",
"el",
".",
"getAttribute",
"(",
"'src'",
")",
"||",
"false",
";",
"el",
".",
"addEventListener",
"(",
"'error'",
",",
"function",
"handler",
"(",
"e",
")",
"{",
"// on error put back the original image if available (usually a placeholder)",
"console",
".",
"log",
"(",
"'error loading image'",
",",
"e",
")",
";",
"if",
"(",
"orig",
")",
"{",
"el",
".",
"setAttribute",
"(",
"'src'",
",",
"orig",
")",
";",
"}",
"el",
".",
"removeEventListener",
"(",
"'error'",
",",
"handler",
")",
";",
"// hate this.",
"}",
")",
";",
"var",
"src",
"=",
"el",
".",
"getAttribute",
"(",
"'data-src'",
")",
";",
"if",
"(",
"src",
")",
"{",
"el",
".",
"setAttribute",
"(",
"'src'",
",",
"src",
")",
";",
"addClass",
"(",
"el",
")",
";",
"return",
";",
"}",
"src",
"=",
"el",
".",
"getAttribute",
"(",
"'data-bkg'",
")",
";",
"if",
"(",
"src",
")",
"{",
"el",
".",
"style",
".",
"backgroundImage",
"=",
"'url(\"'",
"+",
"src",
"+",
"'\")'",
";",
"addClass",
"(",
"el",
")",
";",
"return",
";",
"}",
"}"
] |
set the image src or background attribute
|
[
"set",
"the",
"image",
"src",
"or",
"background",
"attribute"
] |
4ae92e6f7ccbad0a00431ddec419b25ca3de2927
|
https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appearlazy.js#L16-L40
|
13,394
|
creativelive/appear
|
lib/appearlazy.js
|
reveal
|
function reveal(el) {
if (el.hasChildNodes()) {
// dealing with a container try and find children
var els = el.querySelectorAll('[data-src], [data-bkg]');
var elsl = els.length;
if (elsl === 0) {
// node has children, but none have the attributes, so reveal
// the node itself (use case: div with a background)
doReveal(el);
} else {
for (var j = 0; j < elsl; j++) {
doReveal(els[j]);
}
}
} else {
doReveal(el);
}
}
|
javascript
|
function reveal(el) {
if (el.hasChildNodes()) {
// dealing with a container try and find children
var els = el.querySelectorAll('[data-src], [data-bkg]');
var elsl = els.length;
if (elsl === 0) {
// node has children, but none have the attributes, so reveal
// the node itself (use case: div with a background)
doReveal(el);
} else {
for (var j = 0; j < elsl; j++) {
doReveal(els[j]);
}
}
} else {
doReveal(el);
}
}
|
[
"function",
"reveal",
"(",
"el",
")",
"{",
"if",
"(",
"el",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"// dealing with a container try and find children",
"var",
"els",
"=",
"el",
".",
"querySelectorAll",
"(",
"'[data-src], [data-bkg]'",
")",
";",
"var",
"elsl",
"=",
"els",
".",
"length",
";",
"if",
"(",
"elsl",
"===",
"0",
")",
"{",
"// node has children, but none have the attributes, so reveal",
"// the node itself (use case: div with a background)",
"doReveal",
"(",
"el",
")",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"elsl",
";",
"j",
"++",
")",
"{",
"doReveal",
"(",
"els",
"[",
"j",
"]",
")",
";",
"}",
"}",
"}",
"else",
"{",
"doReveal",
"(",
"el",
")",
";",
"}",
"}"
] |
find what element to work with, as we support containers of images
|
[
"find",
"what",
"element",
"to",
"work",
"with",
"as",
"we",
"support",
"containers",
"of",
"images"
] |
4ae92e6f7ccbad0a00431ddec419b25ca3de2927
|
https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appearlazy.js#L43-L60
|
13,395
|
creativelive/appear
|
lib/appearlazy.js
|
init
|
function init() {
// find all elements with the class "appear"
var els = document.getElementsByClassName('appear');
var elsl = els.length;
// put html elements into an array object to work with
for (var i = 0; i < elsl; i += 1) {
// some images are revealed on a simple timeout, instead of
// viewport appears. These delays appears must have
// the appear class on them directly
var delay = els[i].getAttribute('data-delay');
if (delay) {
delayAppear(els[i], delay);
} else {
nodes.push(els[i]);
}
}
}
|
javascript
|
function init() {
// find all elements with the class "appear"
var els = document.getElementsByClassName('appear');
var elsl = els.length;
// put html elements into an array object to work with
for (var i = 0; i < elsl; i += 1) {
// some images are revealed on a simple timeout, instead of
// viewport appears. These delays appears must have
// the appear class on them directly
var delay = els[i].getAttribute('data-delay');
if (delay) {
delayAppear(els[i], delay);
} else {
nodes.push(els[i]);
}
}
}
|
[
"function",
"init",
"(",
")",
"{",
"// find all elements with the class \"appear\"",
"var",
"els",
"=",
"document",
".",
"getElementsByClassName",
"(",
"'appear'",
")",
";",
"var",
"elsl",
"=",
"els",
".",
"length",
";",
"// put html elements into an array object to work with",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"elsl",
";",
"i",
"+=",
"1",
")",
"{",
"// some images are revealed on a simple timeout, instead of",
"// viewport appears. These delays appears must have",
"// the appear class on them directly",
"var",
"delay",
"=",
"els",
"[",
"i",
"]",
".",
"getAttribute",
"(",
"'data-delay'",
")",
";",
"if",
"(",
"delay",
")",
"{",
"delayAppear",
"(",
"els",
"[",
"i",
"]",
",",
"delay",
")",
";",
"}",
"else",
"{",
"nodes",
".",
"push",
"(",
"els",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}"
] |
function executed when dom is interactive
|
[
"function",
"executed",
"when",
"dom",
"is",
"interactive"
] |
4ae92e6f7ccbad0a00431ddec419b25ca3de2927
|
https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appearlazy.js#L71-L87
|
13,396
|
creativelive/appear
|
lib/appear.js
|
debounce
|
function debounce(fn, delay) {
return function () {
var self = this, args = arguments;
clearTimeout(timer);
console.log('debounce()');
timer = setTimeout(function () {
fn.apply(self, args);
}, delay);
};
}
|
javascript
|
function debounce(fn, delay) {
return function () {
var self = this, args = arguments;
clearTimeout(timer);
console.log('debounce()');
timer = setTimeout(function () {
fn.apply(self, args);
}, delay);
};
}
|
[
"function",
"debounce",
"(",
"fn",
",",
"delay",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
",",
"args",
"=",
"arguments",
";",
"clearTimeout",
"(",
"timer",
")",
";",
"console",
".",
"log",
"(",
"'debounce()'",
")",
";",
"timer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"fn",
".",
"apply",
"(",
"self",
",",
"args",
")",
";",
"}",
",",
"delay",
")",
";",
"}",
";",
"}"
] |
handle debouncing a function for better performance on scroll
|
[
"handle",
"debouncing",
"a",
"function",
"for",
"better",
"performance",
"on",
"scroll"
] |
4ae92e6f7ccbad0a00431ddec419b25ca3de2927
|
https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appear.js#L40-L49
|
13,397
|
creativelive/appear
|
lib/appear.js
|
checkAppear
|
function checkAppear() {
if(scroll.delta < opts.delta.speed) {
if(!deltaSet) {
deltaSet = true;
doCheckAppear();
setTimeout(function(){
deltaSet = false;
}, opts.delta.timeout);
}
}
(debounce(function() {
doCheckAppear();
}, opts.debounce)());
}
|
javascript
|
function checkAppear() {
if(scroll.delta < opts.delta.speed) {
if(!deltaSet) {
deltaSet = true;
doCheckAppear();
setTimeout(function(){
deltaSet = false;
}, opts.delta.timeout);
}
}
(debounce(function() {
doCheckAppear();
}, opts.debounce)());
}
|
[
"function",
"checkAppear",
"(",
")",
"{",
"if",
"(",
"scroll",
".",
"delta",
"<",
"opts",
".",
"delta",
".",
"speed",
")",
"{",
"if",
"(",
"!",
"deltaSet",
")",
"{",
"deltaSet",
"=",
"true",
";",
"doCheckAppear",
"(",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"deltaSet",
"=",
"false",
";",
"}",
",",
"opts",
".",
"delta",
".",
"timeout",
")",
";",
"}",
"}",
"(",
"debounce",
"(",
"function",
"(",
")",
"{",
"doCheckAppear",
"(",
")",
";",
"}",
",",
"opts",
".",
"debounce",
")",
"(",
")",
")",
";",
"}"
] |
called on scroll and resize event, so debounce the actual function that does the heavy work of determining if an item is viewable and then "appearing" it
|
[
"called",
"on",
"scroll",
"and",
"resize",
"event",
"so",
"debounce",
"the",
"actual",
"function",
"that",
"does",
"the",
"heavy",
"work",
"of",
"determining",
"if",
"an",
"item",
"is",
"viewable",
"and",
"then",
"appearing",
"it"
] |
4ae92e6f7ccbad0a00431ddec419b25ca3de2927
|
https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appear.js#L53-L66
|
13,398
|
jriecken/sat-js
|
examples/examples.js
|
poly2path
|
function poly2path(polygon) {
var pos = polygon.pos;
var points = polygon.calcPoints;
var result = 'M' + pos.x + ' ' + pos.y;
result += 'M' + (pos.x + points[0].x) + ' ' + (pos.y + points[0].y);
for (var i = 1; i < points.length; i++) {
var point = points[i];
result += 'L' + (pos.x + point.x) + ' ' + (pos.y + point.y);
}
result += 'Z';
return result;
}
|
javascript
|
function poly2path(polygon) {
var pos = polygon.pos;
var points = polygon.calcPoints;
var result = 'M' + pos.x + ' ' + pos.y;
result += 'M' + (pos.x + points[0].x) + ' ' + (pos.y + points[0].y);
for (var i = 1; i < points.length; i++) {
var point = points[i];
result += 'L' + (pos.x + point.x) + ' ' + (pos.y + point.y);
}
result += 'Z';
return result;
}
|
[
"function",
"poly2path",
"(",
"polygon",
")",
"{",
"var",
"pos",
"=",
"polygon",
".",
"pos",
";",
"var",
"points",
"=",
"polygon",
".",
"calcPoints",
";",
"var",
"result",
"=",
"'M'",
"+",
"pos",
".",
"x",
"+",
"' '",
"+",
"pos",
".",
"y",
";",
"result",
"+=",
"'M'",
"+",
"(",
"pos",
".",
"x",
"+",
"points",
"[",
"0",
"]",
".",
"x",
")",
"+",
"' '",
"+",
"(",
"pos",
".",
"y",
"+",
"points",
"[",
"0",
"]",
".",
"y",
")",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"points",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"point",
"=",
"points",
"[",
"i",
"]",
";",
"result",
"+=",
"'L'",
"+",
"(",
"pos",
".",
"x",
"+",
"point",
".",
"x",
")",
"+",
"' '",
"+",
"(",
"pos",
".",
"y",
"+",
"point",
".",
"y",
")",
";",
"}",
"result",
"+=",
"'Z'",
";",
"return",
"result",
";",
"}"
] |
Converts a SAT.Polygon into a SVG path string.
|
[
"Converts",
"a",
"SAT",
".",
"Polygon",
"into",
"a",
"SVG",
"path",
"string",
"."
] |
4e06e0a81ae38d6630469d94beb1a46d7b5f74bb
|
https://github.com/jriecken/sat-js/blob/4e06e0a81ae38d6630469d94beb1a46d7b5f74bb/examples/examples.js#L8-L19
|
13,399
|
jriecken/sat-js
|
examples/examples.js
|
moveDrag
|
function moveDrag(entity, world) {
return function (dx, dy) {
// This position updating is fairly naive - it lets objects tunnel through each other, but it suffices for these examples.
entity.data.pos.x = this.ox + dx;
entity.data.pos.y = this.oy + dy;
world.simulate();
};
}
|
javascript
|
function moveDrag(entity, world) {
return function (dx, dy) {
// This position updating is fairly naive - it lets objects tunnel through each other, but it suffices for these examples.
entity.data.pos.x = this.ox + dx;
entity.data.pos.y = this.oy + dy;
world.simulate();
};
}
|
[
"function",
"moveDrag",
"(",
"entity",
",",
"world",
")",
"{",
"return",
"function",
"(",
"dx",
",",
"dy",
")",
"{",
"// This position updating is fairly naive - it lets objects tunnel through each other, but it suffices for these examples.",
"entity",
".",
"data",
".",
"pos",
".",
"x",
"=",
"this",
".",
"ox",
"+",
"dx",
";",
"entity",
".",
"data",
".",
"pos",
".",
"y",
"=",
"this",
".",
"oy",
"+",
"dy",
";",
"world",
".",
"simulate",
"(",
")",
";",
"}",
";",
"}"
] |
Create a Raphael move drag handler for specified entity
|
[
"Create",
"a",
"Raphael",
"move",
"drag",
"handler",
"for",
"specified",
"entity"
] |
4e06e0a81ae38d6630469d94beb1a46d7b5f74bb
|
https://github.com/jriecken/sat-js/blob/4e06e0a81ae38d6630469d94beb1a46d7b5f74bb/examples/examples.js#L29-L36
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.