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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
53,800 | NumminorihSF/bramqp-wrapper | domain/tx.js | TX | function TX(client, channel){
EE.call(this);
this.client = client;
this.channel = channel;
this.id = channel.$getId();
return this;
} | javascript | function TX(client, channel){
EE.call(this);
this.client = client;
this.channel = channel;
this.id = channel.$getId();
return this;
} | [
"function",
"TX",
"(",
"client",
",",
"channel",
")",
"{",
"EE",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"client",
"=",
"client",
";",
"this",
".",
"channel",
"=",
"channel",
";",
"this",
".",
"id",
"=",
"channel",
".",
"$getId",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Work with transactions.
The Tx class allows publish and ack operations to be batched into atomic units of work.
The intention is that all publish and ack requests issued within a transaction will
complete successfully or none of them will.
Servers SHOULD implement atomic transactions at least where all publish or ack requests
affect a single queue. Transactions that cover multiple queues may be non-atomic,
given that queues can be created and destroyed asynchronously, and such events do not
form part of any transaction. Further, the behaviour of transactions with respect to the
immediate and mandatory flags on Basic.Publish methods is not defined.
@extends EventEmitter
@param {BRAMQPClient} client Client object that returns from bramqp#openAMQPCommunication() method.
@param {Channel} channel Channel object (should be opened).
@return {TX}
@constructor
@class Tx | [
"Work",
"with",
"transactions",
"."
] | 3e2bd769a2828f7592eba79556c9ef1491177781 | https://github.com/NumminorihSF/bramqp-wrapper/blob/3e2bd769a2828f7592eba79556c9ef1491177781/domain/tx.js#L23-L30 |
53,801 | fresheneesz/asyncFuture | asyncFuture.js | executeCallback | function executeCallback(cb, arg) {
var r = cb(arg)
if(r !== undefined && !isLikeAFuture(r) )
throw Error("Value returned from then or catch ("+r+") is *not* a Future. Callback: "+cb.toString())
return r
} | javascript | function executeCallback(cb, arg) {
var r = cb(arg)
if(r !== undefined && !isLikeAFuture(r) )
throw Error("Value returned from then or catch ("+r+") is *not* a Future. Callback: "+cb.toString())
return r
} | [
"function",
"executeCallback",
"(",
"cb",
",",
"arg",
")",
"{",
"var",
"r",
"=",
"cb",
"(",
"arg",
")",
"if",
"(",
"r",
"!==",
"undefined",
"&&",
"!",
"isLikeAFuture",
"(",
"r",
")",
")",
"throw",
"Error",
"(",
"\"Value returned from then or catch (\"",
"+",
"r",
"+",
"\") is *not* a Future. Callback: \"",
"+",
"cb",
".",
"toString",
"(",
")",
")",
"return",
"r",
"}"
] | executes a callback and ensures that it returns a future | [
"executes",
"a",
"callback",
"and",
"ensures",
"that",
"it",
"returns",
"a",
"future"
] | 312d8732db06b15455b844934b5b3ca5dd2debb5 | https://github.com/fresheneesz/asyncFuture/blob/312d8732db06b15455b844934b5b3ca5dd2debb5/asyncFuture.js#L352-L358 |
53,802 | fallanic/node-squad | lib/node-squad.js | batchLoop | function batchLoop(){
var promisesArray = createBatchJobs();
Q[qFunction](promisesArray).then(function(batchResult){
if(qFunction === "allSettled"){
batchResult = batchResult.filter(function(res){return res.state === "fulfilled"}).map(function(item){return item.value;})
}
results = results.concat(batchResult);
//these are upserted, let's check the next ones
if(!disableLogs) {
console.log("This squad is done, " + dataCopy.length + " items remaining");
}
if(dataCopy.length == 0){
if(!disableLogs){
console.log("Finished the batch loop");
}
deferred.resolve(results);
}else{
batchLoop();
}
}).catch(function(e){
if(!disableLogs) {
console.error(e);
}
deferred.reject(results);
});
} | javascript | function batchLoop(){
var promisesArray = createBatchJobs();
Q[qFunction](promisesArray).then(function(batchResult){
if(qFunction === "allSettled"){
batchResult = batchResult.filter(function(res){return res.state === "fulfilled"}).map(function(item){return item.value;})
}
results = results.concat(batchResult);
//these are upserted, let's check the next ones
if(!disableLogs) {
console.log("This squad is done, " + dataCopy.length + " items remaining");
}
if(dataCopy.length == 0){
if(!disableLogs){
console.log("Finished the batch loop");
}
deferred.resolve(results);
}else{
batchLoop();
}
}).catch(function(e){
if(!disableLogs) {
console.error(e);
}
deferred.reject(results);
});
} | [
"function",
"batchLoop",
"(",
")",
"{",
"var",
"promisesArray",
"=",
"createBatchJobs",
"(",
")",
";",
"Q",
"[",
"qFunction",
"]",
"(",
"promisesArray",
")",
".",
"then",
"(",
"function",
"(",
"batchResult",
")",
"{",
"if",
"(",
"qFunction",
"===",
"\"allSettled\"",
")",
"{",
"batchResult",
"=",
"batchResult",
".",
"filter",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"res",
".",
"state",
"===",
"\"fulfilled\"",
"}",
")",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
".",
"value",
";",
"}",
")",
"}",
"results",
"=",
"results",
".",
"concat",
"(",
"batchResult",
")",
";",
"//these are upserted, let's check the next ones",
"if",
"(",
"!",
"disableLogs",
")",
"{",
"console",
".",
"log",
"(",
"\"This squad is done, \"",
"+",
"dataCopy",
".",
"length",
"+",
"\" items remaining\"",
")",
";",
"}",
"if",
"(",
"dataCopy",
".",
"length",
"==",
"0",
")",
"{",
"if",
"(",
"!",
"disableLogs",
")",
"{",
"console",
".",
"log",
"(",
"\"Finished the batch loop\"",
")",
";",
"}",
"deferred",
".",
"resolve",
"(",
"results",
")",
";",
"}",
"else",
"{",
"batchLoop",
"(",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"disableLogs",
")",
"{",
"console",
".",
"error",
"(",
"e",
")",
";",
"}",
"deferred",
".",
"reject",
"(",
"results",
")",
";",
"}",
")",
";",
"}"
] | the main loop creating batches of jobs | [
"the",
"main",
"loop",
"creating",
"batches",
"of",
"jobs"
] | 142afe88a8859d273c421cd7598792250224e2be | https://github.com/fallanic/node-squad/blob/142afe88a8859d273c421cd7598792250224e2be/lib/node-squad.js#L54-L81 |
53,803 | fallanic/node-squad | lib/node-squad.js | createBatchJobs | function createBatchJobs(){
var promises = [];
for(var i=0;i<squadSize && dataCopy.length > 0;i++){
var item = dataCopy.shift();
promises.push(worker(item));
}
return promises;
} | javascript | function createBatchJobs(){
var promises = [];
for(var i=0;i<squadSize && dataCopy.length > 0;i++){
var item = dataCopy.shift();
promises.push(worker(item));
}
return promises;
} | [
"function",
"createBatchJobs",
"(",
")",
"{",
"var",
"promises",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"squadSize",
"&&",
"dataCopy",
".",
"length",
">",
"0",
";",
"i",
"++",
")",
"{",
"var",
"item",
"=",
"dataCopy",
".",
"shift",
"(",
")",
";",
"promises",
".",
"push",
"(",
"worker",
"(",
"item",
")",
")",
";",
"}",
"return",
"promises",
";",
"}"
] | this will create a batch of up to squadSize jobs | [
"this",
"will",
"create",
"a",
"batch",
"of",
"up",
"to",
"squadSize",
"jobs"
] | 142afe88a8859d273c421cd7598792250224e2be | https://github.com/fallanic/node-squad/blob/142afe88a8859d273c421cd7598792250224e2be/lib/node-squad.js#L84-L92 |
53,804 | AndiDittrich/Node.mysql-magic | lib/fetch-all.js | fetchAll | async function fetchAll(connection, query, params){
// execute query
const [result] = await _query(connection, query, params);
// entry found ?
return result || [];
} | javascript | async function fetchAll(connection, query, params){
// execute query
const [result] = await _query(connection, query, params);
// entry found ?
return result || [];
} | [
"async",
"function",
"fetchAll",
"(",
"connection",
",",
"query",
",",
"params",
")",
"{",
"// execute query",
"const",
"[",
"result",
"]",
"=",
"await",
"_query",
"(",
"connection",
",",
"query",
",",
"params",
")",
";",
"// entry found ?",
"return",
"result",
"||",
"[",
"]",
";",
"}"
] | fetch multiple rows in once | [
"fetch",
"multiple",
"rows",
"in",
"once"
] | f9783ac93f4a5744407781d7875ae68cad58cc48 | https://github.com/AndiDittrich/Node.mysql-magic/blob/f9783ac93f4a5744407781d7875ae68cad58cc48/lib/fetch-all.js#L4-L11 |
53,805 | jtheriault/code-copter | examples/analyzer-plugin/code-copter-analyzer-hell-no-world/index.js | analyze | function analyze (fileSourceData) {
var analysis = new Analysis();
for (let sample of fileSourceData) {
if (saysHelloWorld(sample.text)) {
analysis.addError({
line: sample.line,
message: 'At least try to look like you didn\'t copy the demo code!'
});
}
}
return analysis;
} | javascript | function analyze (fileSourceData) {
var analysis = new Analysis();
for (let sample of fileSourceData) {
if (saysHelloWorld(sample.text)) {
analysis.addError({
line: sample.line,
message: 'At least try to look like you didn\'t copy the demo code!'
});
}
}
return analysis;
} | [
"function",
"analyze",
"(",
"fileSourceData",
")",
"{",
"var",
"analysis",
"=",
"new",
"Analysis",
"(",
")",
";",
"for",
"(",
"let",
"sample",
"of",
"fileSourceData",
")",
"{",
"if",
"(",
"saysHelloWorld",
"(",
"sample",
".",
"text",
")",
")",
"{",
"analysis",
".",
"addError",
"(",
"{",
"line",
":",
"sample",
".",
"line",
",",
"message",
":",
"'At least try to look like you didn\\'t copy the demo code!'",
"}",
")",
";",
"}",
"}",
"return",
"analysis",
";",
"}"
] | Analyze file source data for the case-insensitive phrase "Hello world".
@param {FileSourceData} fileSourceData - The file source data to analyze.
@returns {Analysis} - The analysis of the file source data. | [
"Analyze",
"file",
"source",
"data",
"for",
"the",
"case",
"-",
"insensitive",
"phrase",
"Hello",
"world",
"."
] | e69f22e1c9de5d59d15958a09d732ce8d8b519fb | https://github.com/jtheriault/code-copter/blob/e69f22e1c9de5d59d15958a09d732ce8d8b519fb/examples/analyzer-plugin/code-copter-analyzer-hell-no-world/index.js#L18-L31 |
53,806 | Galiaf47/lib3d | src/controls.js | onMouseDown | function onMouseDown(event, env, isSideEffectsDisabled) {
mouse.down(event, env ? env.camera : null);
if (!env || isSideEffectsDisabled) {
return;
}
if (mouse.keys[1] && !mouse.keys[3]) {
let focusedObject = focusObject(env.library, env.camera, env.selector);
if (env.selector.selectFocused()) {
events.triggerSelect(focusedObject);
}
}
} | javascript | function onMouseDown(event, env, isSideEffectsDisabled) {
mouse.down(event, env ? env.camera : null);
if (!env || isSideEffectsDisabled) {
return;
}
if (mouse.keys[1] && !mouse.keys[3]) {
let focusedObject = focusObject(env.library, env.camera, env.selector);
if (env.selector.selectFocused()) {
events.triggerSelect(focusedObject);
}
}
} | [
"function",
"onMouseDown",
"(",
"event",
",",
"env",
",",
"isSideEffectsDisabled",
")",
"{",
"mouse",
".",
"down",
"(",
"event",
",",
"env",
"?",
"env",
".",
"camera",
":",
"null",
")",
";",
"if",
"(",
"!",
"env",
"||",
"isSideEffectsDisabled",
")",
"{",
"return",
";",
"}",
"if",
"(",
"mouse",
".",
"keys",
"[",
"1",
"]",
"&&",
"!",
"mouse",
".",
"keys",
"[",
"3",
"]",
")",
"{",
"let",
"focusedObject",
"=",
"focusObject",
"(",
"env",
".",
"library",
",",
"env",
".",
"camera",
",",
"env",
".",
"selector",
")",
";",
"if",
"(",
"env",
".",
"selector",
".",
"selectFocused",
"(",
")",
")",
"{",
"events",
".",
"triggerSelect",
"(",
"focusedObject",
")",
";",
"}",
"}",
"}"
] | Triggers object select
@alias module:lib3d.onMouseDown
@param {Object} event - mouse event
@param {Environment} env - affected environment
@param {Boolean} isSideEffectsDisabled - disable side effects like focusing, selecting, moving objects | [
"Triggers",
"object",
"select"
] | dccbb862fc23d8d7dd67a84761cc4012702a7d96 | https://github.com/Galiaf47/lib3d/blob/dccbb862fc23d8d7dd67a84761cc4012702a7d96/src/controls.js#L17-L31 |
53,807 | Galiaf47/lib3d | src/controls.js | onMouseUp | function onMouseUp(event, env, isSideEffectsDisabled) {
mouse.up(event);
if (!env || isSideEffectsDisabled) {
return;
}
if (objectMoved) {
if(env.selector.isSelectedEditable()) {
events.triggerObjectChange(env.selector.getSelectedObject());
}
objectMoved = false;
}
} | javascript | function onMouseUp(event, env, isSideEffectsDisabled) {
mouse.up(event);
if (!env || isSideEffectsDisabled) {
return;
}
if (objectMoved) {
if(env.selector.isSelectedEditable()) {
events.triggerObjectChange(env.selector.getSelectedObject());
}
objectMoved = false;
}
} | [
"function",
"onMouseUp",
"(",
"event",
",",
"env",
",",
"isSideEffectsDisabled",
")",
"{",
"mouse",
".",
"up",
"(",
"event",
")",
";",
"if",
"(",
"!",
"env",
"||",
"isSideEffectsDisabled",
")",
"{",
"return",
";",
"}",
"if",
"(",
"objectMoved",
")",
"{",
"if",
"(",
"env",
".",
"selector",
".",
"isSelectedEditable",
"(",
")",
")",
"{",
"events",
".",
"triggerObjectChange",
"(",
"env",
".",
"selector",
".",
"getSelectedObject",
"(",
")",
")",
";",
"}",
"objectMoved",
"=",
"false",
";",
"}",
"}"
] | Triggers object change
@alias module:lib3d.onMouseUp
@param {Object} event - mouse event
@param {Environment} env - affected environment
@param {Boolean} isSideEffectsDisabled - disable side effects like focusing, selecting, moving objects | [
"Triggers",
"object",
"change"
] | dccbb862fc23d8d7dd67a84761cc4012702a7d96 | https://github.com/Galiaf47/lib3d/blob/dccbb862fc23d8d7dd67a84761cc4012702a7d96/src/controls.js#L39-L53 |
53,808 | Galiaf47/lib3d | src/controls.js | onMouseMove | function onMouseMove(event, env, isSideEffectsDisabled) {
event.preventDefault();
mouse.move(event, env ? env.camera : null);
if (!env || isSideEffectsDisabled) {
return;
}
if(mouse.keys[1] && !mouse.keys[3]) {
moveObject(env.library, env.camera, env.selector);
} else {
focusObject(env.library, env.camera, env.selector);
}
} | javascript | function onMouseMove(event, env, isSideEffectsDisabled) {
event.preventDefault();
mouse.move(event, env ? env.camera : null);
if (!env || isSideEffectsDisabled) {
return;
}
if(mouse.keys[1] && !mouse.keys[3]) {
moveObject(env.library, env.camera, env.selector);
} else {
focusObject(env.library, env.camera, env.selector);
}
} | [
"function",
"onMouseMove",
"(",
"event",
",",
"env",
",",
"isSideEffectsDisabled",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"mouse",
".",
"move",
"(",
"event",
",",
"env",
"?",
"env",
".",
"camera",
":",
"null",
")",
";",
"if",
"(",
"!",
"env",
"||",
"isSideEffectsDisabled",
")",
"{",
"return",
";",
"}",
"if",
"(",
"mouse",
".",
"keys",
"[",
"1",
"]",
"&&",
"!",
"mouse",
".",
"keys",
"[",
"3",
"]",
")",
"{",
"moveObject",
"(",
"env",
".",
"library",
",",
"env",
".",
"camera",
",",
"env",
".",
"selector",
")",
";",
"}",
"else",
"{",
"focusObject",
"(",
"env",
".",
"library",
",",
"env",
".",
"camera",
",",
"env",
".",
"selector",
")",
";",
"}",
"}"
] | Triggers object focus
@alias module:lib3d.onMouseMove
@param {Object} event - mouse event
@param {Environment} env - affected environment
@param {Boolean} isSideEffectsDisabled - disable side effects like focusing, selecting, moving objects | [
"Triggers",
"object",
"focus"
] | dccbb862fc23d8d7dd67a84761cc4012702a7d96 | https://github.com/Galiaf47/lib3d/blob/dccbb862fc23d8d7dd67a84761cc4012702a7d96/src/controls.js#L61-L74 |
53,809 | Galiaf47/lib3d | src/controls.js | rotateObject | function rotateObject(obj, rotation, order) {
let originRotation = obj.rotation.clone();
obj.rotation.setFromVector3(originRotation.toVector3().add(rotation), order);
if (obj.isCollided()) {
obj.rotation.setFromVector3(originRotation.toVector3(), originRotation.order);
return false;
}
obj.updateBoundingBox();
events.triggerObjectChange(obj);
return true;
} | javascript | function rotateObject(obj, rotation, order) {
let originRotation = obj.rotation.clone();
obj.rotation.setFromVector3(originRotation.toVector3().add(rotation), order);
if (obj.isCollided()) {
obj.rotation.setFromVector3(originRotation.toVector3(), originRotation.order);
return false;
}
obj.updateBoundingBox();
events.triggerObjectChange(obj);
return true;
} | [
"function",
"rotateObject",
"(",
"obj",
",",
"rotation",
",",
"order",
")",
"{",
"let",
"originRotation",
"=",
"obj",
".",
"rotation",
".",
"clone",
"(",
")",
";",
"obj",
".",
"rotation",
".",
"setFromVector3",
"(",
"originRotation",
".",
"toVector3",
"(",
")",
".",
"add",
"(",
"rotation",
")",
",",
"order",
")",
";",
"if",
"(",
"obj",
".",
"isCollided",
"(",
")",
")",
"{",
"obj",
".",
"rotation",
".",
"setFromVector3",
"(",
"originRotation",
".",
"toVector3",
"(",
")",
",",
"originRotation",
".",
"order",
")",
";",
"return",
"false",
";",
"}",
"obj",
".",
"updateBoundingBox",
"(",
")",
";",
"events",
".",
"triggerObjectChange",
"(",
"obj",
")",
";",
"return",
"true",
";",
"}"
] | Rotate an object with avoiiding collisions and triggering objectChangeEvent
@alias module:lib3d.rotateObject
@param {BaseObject} obj - Object to rotate
@param {THREE.Vector3} rotation - A vector with rotation angles in radians
@param {String} order - Euler angles order (optional) | [
"Rotate",
"an",
"object",
"with",
"avoiiding",
"collisions",
"and",
"triggering",
"objectChangeEvent"
] | dccbb862fc23d8d7dd67a84761cc4012702a7d96 | https://github.com/Galiaf47/lib3d/blob/dccbb862fc23d8d7dd67a84761cc4012702a7d96/src/controls.js#L133-L146 |
53,810 | ApsisInternational/gulp-config-apsis | src/taskMaker.js | taskMaker | function taskMaker(gulp) {
if (!gulp) {
throw new Error('Task maker: No gulp instance provided.');
}
const maker = {
createTask,
};
return maker;
function createTask(task) {
gulp.task(
task.name,
task.desc || false,
task.fn,
task.help
);
return maker;
}
} | javascript | function taskMaker(gulp) {
if (!gulp) {
throw new Error('Task maker: No gulp instance provided.');
}
const maker = {
createTask,
};
return maker;
function createTask(task) {
gulp.task(
task.name,
task.desc || false,
task.fn,
task.help
);
return maker;
}
} | [
"function",
"taskMaker",
"(",
"gulp",
")",
"{",
"if",
"(",
"!",
"gulp",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Task maker: No gulp instance provided.'",
")",
";",
"}",
"const",
"maker",
"=",
"{",
"createTask",
",",
"}",
";",
"return",
"maker",
";",
"function",
"createTask",
"(",
"task",
")",
"{",
"gulp",
".",
"task",
"(",
"task",
".",
"name",
",",
"task",
".",
"desc",
"||",
"false",
",",
"task",
".",
"fn",
",",
"task",
".",
"help",
")",
";",
"return",
"maker",
";",
"}",
"}"
] | Create a gulp task
@param {object} task configuration for the task
@return {} | [
"Create",
"a",
"gulp",
"task"
] | 700ae59ca09e3a0e7787886531c7336bdf7491e8 | https://github.com/ApsisInternational/gulp-config-apsis/blob/700ae59ca09e3a0e7787886531c7336bdf7491e8/src/taskMaker.js#L6-L27 |
53,811 | ironboy/warp-core | html-to-render.js | getFiles | function getFiles(folder = srcFolder){
let all = [];
let f = fs.readdirSync(folder);
for(file of f){
all.push(path.join(folder,file))
if(fs.lstatSync(path.join(folder,file)).isDirectory()){
all = all.concat(getFiles(path.join(folder,file)));
}
}
return all;
} | javascript | function getFiles(folder = srcFolder){
let all = [];
let f = fs.readdirSync(folder);
for(file of f){
all.push(path.join(folder,file))
if(fs.lstatSync(path.join(folder,file)).isDirectory()){
all = all.concat(getFiles(path.join(folder,file)));
}
}
return all;
} | [
"function",
"getFiles",
"(",
"folder",
"=",
"srcFolder",
")",
"{",
"let",
"all",
"=",
"[",
"]",
";",
"let",
"f",
"=",
"fs",
".",
"readdirSync",
"(",
"folder",
")",
";",
"for",
"(",
"file",
"of",
"f",
")",
"{",
"all",
".",
"push",
"(",
"path",
".",
"join",
"(",
"folder",
",",
"file",
")",
")",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"path",
".",
"join",
"(",
"folder",
",",
"file",
")",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"all",
"=",
"all",
".",
"concat",
"(",
"getFiles",
"(",
"path",
".",
"join",
"(",
"folder",
",",
"file",
")",
")",
")",
";",
"}",
"}",
"return",
"all",
";",
"}"
] | get all file paths in a folder recursively | [
"get",
"all",
"file",
"paths",
"in",
"a",
"folder",
"recursively"
] | 0e3556e41e40cdfc0dafdfd4d9e02662010e9379 | https://github.com/ironboy/warp-core/blob/0e3556e41e40cdfc0dafdfd4d9e02662010e9379/html-to-render.js#L32-L42 |
53,812 | ariatemplates/noder-js | src/modules/resolver.js | function(map, terms) {
for (var i = 0, l = terms.length; i < l; i++) {
var curTerm = terms[i];
map = map[curTerm];
if (!map || curTerm === map) {
return false; // no change
} else if (isString(map)) {
applyChange(terms, map, i);
return true;
}
}
// if we reach this place, it is a directory
applyChange(terms, map['.'] || "index.js", terms.length);
return true;
} | javascript | function(map, terms) {
for (var i = 0, l = terms.length; i < l; i++) {
var curTerm = terms[i];
map = map[curTerm];
if (!map || curTerm === map) {
return false; // no change
} else if (isString(map)) {
applyChange(terms, map, i);
return true;
}
}
// if we reach this place, it is a directory
applyChange(terms, map['.'] || "index.js", terms.length);
return true;
} | [
"function",
"(",
"map",
",",
"terms",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"terms",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"var",
"curTerm",
"=",
"terms",
"[",
"i",
"]",
";",
"map",
"=",
"map",
"[",
"curTerm",
"]",
";",
"if",
"(",
"!",
"map",
"||",
"curTerm",
"===",
"map",
")",
"{",
"return",
"false",
";",
"// no change",
"}",
"else",
"if",
"(",
"isString",
"(",
"map",
")",
")",
"{",
"applyChange",
"(",
"terms",
",",
"map",
",",
"i",
")",
";",
"return",
"true",
";",
"}",
"}",
"// if we reach this place, it is a directory",
"applyChange",
"(",
"terms",
",",
"map",
"[",
"'.'",
"]",
"||",
"\"index.js\"",
",",
"terms",
".",
"length",
")",
";",
"return",
"true",
";",
"}"
] | Apply a module map iteration.
@param {Object} map
@param {Array} terms Note that this array is changed by this function.
@return {Boolean} | [
"Apply",
"a",
"module",
"map",
"iteration",
"."
] | c2db684299d907b2035fa427f030cf08da8ceb57 | https://github.com/ariatemplates/noder-js/blob/c2db684299d907b2035fa427f030cf08da8ceb57/src/modules/resolver.js#L65-L79 |
|
53,813 | molnarg/node-http2-protocol | example/server.js | onConnection | function onConnection(socket) {
var endpoint = new http2.Endpoint(log, 'SERVER', {});
endpoint.pipe(socket).pipe(endpoint);
endpoint.on('stream', function(stream) {
stream.on('headers', function(headers) {
var path = headers[':path'];
var filename = join(__dirname, path);
// Serving server.js from cache. Useful for microbenchmarks.
if (path == cachedUrl) {
stream.headers({ ':status': 200 });
stream.end(cachedFile);
}
// Reading file from disk if it exists and is safe.
else if ((filename.indexOf(__dirname) === 0) && exists(filename) && stat(filename).isFile()) {
stream.headers({ ':status': 200 });
// If they download the certificate, push the private key too, they might need it.
if (path === '/localhost.crt') {
var push = stream.promise({
':method': 'GET',
':scheme': headers[':scheme'],
':authority': headers[':authority'],
':path': '/localhost.key'
});
push.headers({ ':status': 200 });
read(join(__dirname, '/localhost.key')).pipe(push);
}
read(filename).pipe(stream);
}
// Otherwise responding with 404.
else {
stream.headers({ ':status': 404 });
stream.end();
}
});
});
} | javascript | function onConnection(socket) {
var endpoint = new http2.Endpoint(log, 'SERVER', {});
endpoint.pipe(socket).pipe(endpoint);
endpoint.on('stream', function(stream) {
stream.on('headers', function(headers) {
var path = headers[':path'];
var filename = join(__dirname, path);
// Serving server.js from cache. Useful for microbenchmarks.
if (path == cachedUrl) {
stream.headers({ ':status': 200 });
stream.end(cachedFile);
}
// Reading file from disk if it exists and is safe.
else if ((filename.indexOf(__dirname) === 0) && exists(filename) && stat(filename).isFile()) {
stream.headers({ ':status': 200 });
// If they download the certificate, push the private key too, they might need it.
if (path === '/localhost.crt') {
var push = stream.promise({
':method': 'GET',
':scheme': headers[':scheme'],
':authority': headers[':authority'],
':path': '/localhost.key'
});
push.headers({ ':status': 200 });
read(join(__dirname, '/localhost.key')).pipe(push);
}
read(filename).pipe(stream);
}
// Otherwise responding with 404.
else {
stream.headers({ ':status': 404 });
stream.end();
}
});
});
} | [
"function",
"onConnection",
"(",
"socket",
")",
"{",
"var",
"endpoint",
"=",
"new",
"http2",
".",
"Endpoint",
"(",
"log",
",",
"'SERVER'",
",",
"{",
"}",
")",
";",
"endpoint",
".",
"pipe",
"(",
"socket",
")",
".",
"pipe",
"(",
"endpoint",
")",
";",
"endpoint",
".",
"on",
"(",
"'stream'",
",",
"function",
"(",
"stream",
")",
"{",
"stream",
".",
"on",
"(",
"'headers'",
",",
"function",
"(",
"headers",
")",
"{",
"var",
"path",
"=",
"headers",
"[",
"':path'",
"]",
";",
"var",
"filename",
"=",
"join",
"(",
"__dirname",
",",
"path",
")",
";",
"// Serving server.js from cache. Useful for microbenchmarks.",
"if",
"(",
"path",
"==",
"cachedUrl",
")",
"{",
"stream",
".",
"headers",
"(",
"{",
"':status'",
":",
"200",
"}",
")",
";",
"stream",
".",
"end",
"(",
"cachedFile",
")",
";",
"}",
"// Reading file from disk if it exists and is safe.",
"else",
"if",
"(",
"(",
"filename",
".",
"indexOf",
"(",
"__dirname",
")",
"===",
"0",
")",
"&&",
"exists",
"(",
"filename",
")",
"&&",
"stat",
"(",
"filename",
")",
".",
"isFile",
"(",
")",
")",
"{",
"stream",
".",
"headers",
"(",
"{",
"':status'",
":",
"200",
"}",
")",
";",
"// If they download the certificate, push the private key too, they might need it.",
"if",
"(",
"path",
"===",
"'/localhost.crt'",
")",
"{",
"var",
"push",
"=",
"stream",
".",
"promise",
"(",
"{",
"':method'",
":",
"'GET'",
",",
"':scheme'",
":",
"headers",
"[",
"':scheme'",
"]",
",",
"':authority'",
":",
"headers",
"[",
"':authority'",
"]",
",",
"':path'",
":",
"'/localhost.key'",
"}",
")",
";",
"push",
".",
"headers",
"(",
"{",
"':status'",
":",
"200",
"}",
")",
";",
"read",
"(",
"join",
"(",
"__dirname",
",",
"'/localhost.key'",
")",
")",
".",
"pipe",
"(",
"push",
")",
";",
"}",
"read",
"(",
"filename",
")",
".",
"pipe",
"(",
"stream",
")",
";",
"}",
"// Otherwise responding with 404.",
"else",
"{",
"stream",
".",
"headers",
"(",
"{",
"':status'",
":",
"404",
"}",
")",
";",
"stream",
".",
"end",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Handling incoming connections | [
"Handling",
"incoming",
"connections"
] | a03dff630a33771d045ac0362023afb84b441aa4 | https://github.com/molnarg/node-http2-protocol/blob/a03dff630a33771d045ac0362023afb84b441aa4/example/server.js#L30-L71 |
53,814 | dpjanes/iotdb-upnp | upnp/upnp-service.js | function (device, desc) {
EventEmitter.call(this);
if (TRACE && DETAIL) {
logger.info({
method: "UpnpService",
device: device,
desc: desc,
}, "called");
}
this.device = device;
this.ok = true;
this.forgotten = false
try {
this.serviceType = desc.serviceType[0];
this.serviceId = desc.serviceId[0];
this.controlUrl = desc.controlURL[0];
this.eventSubUrl = desc.eventSubURL[0];
this.scpdUrl = desc.SCPDURL[0];
// actions that can be performed on this service
this.actions = {};
// variables that represent state on this service.
this.stateVariables = {};
var u = url.parse(device.location);
this.host = u.hostname;
this.port = u.port;
this.subscriptionTimeout = 30; // 60;
} catch (x) {
logger.error({
method: "UpnpService",
cause: "maybe a bad UPnP response - we'll ignore this device",
exception: x,
device: device,
desc: desc,
}, "unexpected exception");
this.ok = false;
return;
}
} | javascript | function (device, desc) {
EventEmitter.call(this);
if (TRACE && DETAIL) {
logger.info({
method: "UpnpService",
device: device,
desc: desc,
}, "called");
}
this.device = device;
this.ok = true;
this.forgotten = false
try {
this.serviceType = desc.serviceType[0];
this.serviceId = desc.serviceId[0];
this.controlUrl = desc.controlURL[0];
this.eventSubUrl = desc.eventSubURL[0];
this.scpdUrl = desc.SCPDURL[0];
// actions that can be performed on this service
this.actions = {};
// variables that represent state on this service.
this.stateVariables = {};
var u = url.parse(device.location);
this.host = u.hostname;
this.port = u.port;
this.subscriptionTimeout = 30; // 60;
} catch (x) {
logger.error({
method: "UpnpService",
cause: "maybe a bad UPnP response - we'll ignore this device",
exception: x,
device: device,
desc: desc,
}, "unexpected exception");
this.ok = false;
return;
}
} | [
"function",
"(",
"device",
",",
"desc",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"TRACE",
"&&",
"DETAIL",
")",
"{",
"logger",
".",
"info",
"(",
"{",
"method",
":",
"\"UpnpService\"",
",",
"device",
":",
"device",
",",
"desc",
":",
"desc",
",",
"}",
",",
"\"called\"",
")",
";",
"}",
"this",
".",
"device",
"=",
"device",
";",
"this",
".",
"ok",
"=",
"true",
";",
"this",
".",
"forgotten",
"=",
"false",
"try",
"{",
"this",
".",
"serviceType",
"=",
"desc",
".",
"serviceType",
"[",
"0",
"]",
";",
"this",
".",
"serviceId",
"=",
"desc",
".",
"serviceId",
"[",
"0",
"]",
";",
"this",
".",
"controlUrl",
"=",
"desc",
".",
"controlURL",
"[",
"0",
"]",
";",
"this",
".",
"eventSubUrl",
"=",
"desc",
".",
"eventSubURL",
"[",
"0",
"]",
";",
"this",
".",
"scpdUrl",
"=",
"desc",
".",
"SCPDURL",
"[",
"0",
"]",
";",
"// actions that can be performed on this service",
"this",
".",
"actions",
"=",
"{",
"}",
";",
"// variables that represent state on this service.",
"this",
".",
"stateVariables",
"=",
"{",
"}",
";",
"var",
"u",
"=",
"url",
".",
"parse",
"(",
"device",
".",
"location",
")",
";",
"this",
".",
"host",
"=",
"u",
".",
"hostname",
";",
"this",
".",
"port",
"=",
"u",
".",
"port",
";",
"this",
".",
"subscriptionTimeout",
"=",
"30",
";",
"// 60;",
"}",
"catch",
"(",
"x",
")",
"{",
"logger",
".",
"error",
"(",
"{",
"method",
":",
"\"UpnpService\"",
",",
"cause",
":",
"\"maybe a bad UPnP response - we'll ignore this device\"",
",",
"exception",
":",
"x",
",",
"device",
":",
"device",
",",
"desc",
":",
"desc",
",",
"}",
",",
"\"unexpected exception\"",
")",
";",
"this",
".",
"ok",
"=",
"false",
";",
"return",
";",
"}",
"}"
] | A UPnP service. | [
"A",
"UPnP",
"service",
"."
] | 514d6253eca4c6440105e48aa940a07778187e43 | https://github.com/dpjanes/iotdb-upnp/blob/514d6253eca4c6440105e48aa940a07778187e43/upnp/upnp-service.js#L28-L73 |
|
53,815 | marcelomf/graojs | modeling/assets/WebGL/matrix4x4.js | function () {
var tmp = this.elements[0*4+1];
this.elements[0*4+1] = this.elements[1*4+0];
this.elements[1*4+0] = tmp;
tmp = this.elements[0*4+2];
this.elements[0*4+2] = this.elements[2*4+0];
this.elements[2*4+0] = tmp;
tmp = this.elements[0*4+3];
this.elements[0*4+3] = this.elements[3*4+0];
this.elements[3*4+0] = tmp;
tmp = this.elements[1*4+2];
this.elements[1*4+2] = this.elements[2*4+1];
this.elements[2*4+1] = tmp;
tmp = this.elements[1*4+3];
this.elements[1*4+3] = this.elements[3*4+1];
this.elements[3*4+1] = tmp;
tmp = this.elements[2*4+3];
this.elements[2*4+3] = this.elements[3*4+2];
this.elements[3*4+2] = tmp;
return this;
} | javascript | function () {
var tmp = this.elements[0*4+1];
this.elements[0*4+1] = this.elements[1*4+0];
this.elements[1*4+0] = tmp;
tmp = this.elements[0*4+2];
this.elements[0*4+2] = this.elements[2*4+0];
this.elements[2*4+0] = tmp;
tmp = this.elements[0*4+3];
this.elements[0*4+3] = this.elements[3*4+0];
this.elements[3*4+0] = tmp;
tmp = this.elements[1*4+2];
this.elements[1*4+2] = this.elements[2*4+1];
this.elements[2*4+1] = tmp;
tmp = this.elements[1*4+3];
this.elements[1*4+3] = this.elements[3*4+1];
this.elements[3*4+1] = tmp;
tmp = this.elements[2*4+3];
this.elements[2*4+3] = this.elements[3*4+2];
this.elements[3*4+2] = tmp;
return this;
} | [
"function",
"(",
")",
"{",
"var",
"tmp",
"=",
"this",
".",
"elements",
"[",
"0",
"*",
"4",
"+",
"1",
"]",
";",
"this",
".",
"elements",
"[",
"0",
"*",
"4",
"+",
"1",
"]",
"=",
"this",
".",
"elements",
"[",
"1",
"*",
"4",
"+",
"0",
"]",
";",
"this",
".",
"elements",
"[",
"1",
"*",
"4",
"+",
"0",
"]",
"=",
"tmp",
";",
"tmp",
"=",
"this",
".",
"elements",
"[",
"0",
"*",
"4",
"+",
"2",
"]",
";",
"this",
".",
"elements",
"[",
"0",
"*",
"4",
"+",
"2",
"]",
"=",
"this",
".",
"elements",
"[",
"2",
"*",
"4",
"+",
"0",
"]",
";",
"this",
".",
"elements",
"[",
"2",
"*",
"4",
"+",
"0",
"]",
"=",
"tmp",
";",
"tmp",
"=",
"this",
".",
"elements",
"[",
"0",
"*",
"4",
"+",
"3",
"]",
";",
"this",
".",
"elements",
"[",
"0",
"*",
"4",
"+",
"3",
"]",
"=",
"this",
".",
"elements",
"[",
"3",
"*",
"4",
"+",
"0",
"]",
";",
"this",
".",
"elements",
"[",
"3",
"*",
"4",
"+",
"0",
"]",
"=",
"tmp",
";",
"tmp",
"=",
"this",
".",
"elements",
"[",
"1",
"*",
"4",
"+",
"2",
"]",
";",
"this",
".",
"elements",
"[",
"1",
"*",
"4",
"+",
"2",
"]",
"=",
"this",
".",
"elements",
"[",
"2",
"*",
"4",
"+",
"1",
"]",
";",
"this",
".",
"elements",
"[",
"2",
"*",
"4",
"+",
"1",
"]",
"=",
"tmp",
";",
"tmp",
"=",
"this",
".",
"elements",
"[",
"1",
"*",
"4",
"+",
"3",
"]",
";",
"this",
".",
"elements",
"[",
"1",
"*",
"4",
"+",
"3",
"]",
"=",
"this",
".",
"elements",
"[",
"3",
"*",
"4",
"+",
"1",
"]",
";",
"this",
".",
"elements",
"[",
"3",
"*",
"4",
"+",
"1",
"]",
"=",
"tmp",
";",
"tmp",
"=",
"this",
".",
"elements",
"[",
"2",
"*",
"4",
"+",
"3",
"]",
";",
"this",
".",
"elements",
"[",
"2",
"*",
"4",
"+",
"3",
"]",
"=",
"this",
".",
"elements",
"[",
"3",
"*",
"4",
"+",
"2",
"]",
";",
"this",
".",
"elements",
"[",
"3",
"*",
"4",
"+",
"2",
"]",
"=",
"tmp",
";",
"return",
"this",
";",
"}"
] | In-place transpose | [
"In",
"-",
"place",
"transpose"
] | f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f | https://github.com/marcelomf/graojs/blob/f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f/modeling/assets/WebGL/matrix4x4.js#L336-L362 |
|
53,816 | clubajax/on | dist/on.js | function (node, callback) {
return on.makeMultiHandle([
on(node, 'click', callback),
on(node, 'keyup:Enter', callback)
]);
} | javascript | function (node, callback) {
return on.makeMultiHandle([
on(node, 'click', callback),
on(node, 'keyup:Enter', callback)
]);
} | [
"function",
"(",
"node",
",",
"callback",
")",
"{",
"return",
"on",
".",
"makeMultiHandle",
"(",
"[",
"on",
"(",
"node",
",",
"'click'",
",",
"callback",
")",
",",
"on",
"(",
"node",
",",
"'keyup:Enter'",
",",
"callback",
")",
"]",
")",
";",
"}"
] | handle click and Enter | [
"handle",
"click",
"and",
"Enter"
] | a0472362dbab5928fcd70c12d420557db01f68fd | https://github.com/clubajax/on/blob/a0472362dbab5928fcd70c12d420557db01f68fd/dist/on.js#L84-L89 |
|
53,817 | clubajax/on | dist/on.js | function (node, callback) {
// important note!
// starts paused
//
var bHandle = on(node.ownerDocument.documentElement, 'click', function (e) {
var target = e.target;
if (target.nodeType !== 1) {
target = target.parentNode;
}
if (target && !node.contains(target)) {
callback(e);
}
});
var handle = {
state: 'resumed',
resume: function () {
setTimeout(function () {
bHandle.resume();
}, 100);
this.state = 'resumed';
},
pause: function () {
bHandle.pause();
this.state = 'paused';
},
remove: function () {
bHandle.remove();
this.state = 'removed';
}
};
handle.pause();
return handle;
} | javascript | function (node, callback) {
// important note!
// starts paused
//
var bHandle = on(node.ownerDocument.documentElement, 'click', function (e) {
var target = e.target;
if (target.nodeType !== 1) {
target = target.parentNode;
}
if (target && !node.contains(target)) {
callback(e);
}
});
var handle = {
state: 'resumed',
resume: function () {
setTimeout(function () {
bHandle.resume();
}, 100);
this.state = 'resumed';
},
pause: function () {
bHandle.pause();
this.state = 'paused';
},
remove: function () {
bHandle.remove();
this.state = 'removed';
}
};
handle.pause();
return handle;
} | [
"function",
"(",
"node",
",",
"callback",
")",
"{",
"// important note!",
"// starts paused",
"//",
"var",
"bHandle",
"=",
"on",
"(",
"node",
".",
"ownerDocument",
".",
"documentElement",
",",
"'click'",
",",
"function",
"(",
"e",
")",
"{",
"var",
"target",
"=",
"e",
".",
"target",
";",
"if",
"(",
"target",
".",
"nodeType",
"!==",
"1",
")",
"{",
"target",
"=",
"target",
".",
"parentNode",
";",
"}",
"if",
"(",
"target",
"&&",
"!",
"node",
".",
"contains",
"(",
"target",
")",
")",
"{",
"callback",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"var",
"handle",
"=",
"{",
"state",
":",
"'resumed'",
",",
"resume",
":",
"function",
"(",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"bHandle",
".",
"resume",
"(",
")",
";",
"}",
",",
"100",
")",
";",
"this",
".",
"state",
"=",
"'resumed'",
";",
"}",
",",
"pause",
":",
"function",
"(",
")",
"{",
"bHandle",
".",
"pause",
"(",
")",
";",
"this",
".",
"state",
"=",
"'paused'",
";",
"}",
",",
"remove",
":",
"function",
"(",
")",
"{",
"bHandle",
".",
"remove",
"(",
")",
";",
"this",
".",
"state",
"=",
"'removed'",
";",
"}",
"}",
";",
"handle",
".",
"pause",
"(",
")",
";",
"return",
"handle",
";",
"}"
] | custom - used for popups 'n stuff | [
"custom",
"-",
"used",
"for",
"popups",
"n",
"stuff"
] | a0472362dbab5928fcd70c12d420557db01f68fd | https://github.com/clubajax/on/blob/a0472362dbab5928fcd70c12d420557db01f68fd/dist/on.js#L92-L126 |
|
53,818 | clubajax/on | dist/on.js | onDomEvent | function onDomEvent (node, eventName, callback) {
node.addEventListener(eventName, callback, false);
return {
remove: function () {
node.removeEventListener(eventName, callback, false);
node = callback = null;
this.remove = this.pause = this.resume = function () {};
},
pause: function () {
node.removeEventListener(eventName, callback, false);
},
resume: function () {
node.addEventListener(eventName, callback, false);
}
};
} | javascript | function onDomEvent (node, eventName, callback) {
node.addEventListener(eventName, callback, false);
return {
remove: function () {
node.removeEventListener(eventName, callback, false);
node = callback = null;
this.remove = this.pause = this.resume = function () {};
},
pause: function () {
node.removeEventListener(eventName, callback, false);
},
resume: function () {
node.addEventListener(eventName, callback, false);
}
};
} | [
"function",
"onDomEvent",
"(",
"node",
",",
"eventName",
",",
"callback",
")",
"{",
"node",
".",
"addEventListener",
"(",
"eventName",
",",
"callback",
",",
"false",
")",
";",
"return",
"{",
"remove",
":",
"function",
"(",
")",
"{",
"node",
".",
"removeEventListener",
"(",
"eventName",
",",
"callback",
",",
"false",
")",
";",
"node",
"=",
"callback",
"=",
"null",
";",
"this",
".",
"remove",
"=",
"this",
".",
"pause",
"=",
"this",
".",
"resume",
"=",
"function",
"(",
")",
"{",
"}",
";",
"}",
",",
"pause",
":",
"function",
"(",
")",
"{",
"node",
".",
"removeEventListener",
"(",
"eventName",
",",
"callback",
",",
"false",
")",
";",
"}",
",",
"resume",
":",
"function",
"(",
")",
"{",
"node",
".",
"addEventListener",
"(",
"eventName",
",",
"callback",
",",
"false",
")",
";",
"}",
"}",
";",
"}"
] | internal event handlers | [
"internal",
"event",
"handlers"
] | a0472362dbab5928fcd70c12d420557db01f68fd | https://github.com/clubajax/on/blob/a0472362dbab5928fcd70c12d420557db01f68fd/dist/on.js#L131-L146 |
53,819 | opencolor-tools/opencolor-js | lib/entry.js | rename | function rename(newName) {
newName = newName.replace(/[\.\/]/g, '');
if (this.isRoot()) {
this._name = newName;
} else {
var newPath = [this.parent.path(), newName].filter(function (e) {
return e !== '';
}).join('.');
this.moveTo(newPath);
}
} | javascript | function rename(newName) {
newName = newName.replace(/[\.\/]/g, '');
if (this.isRoot()) {
this._name = newName;
} else {
var newPath = [this.parent.path(), newName].filter(function (e) {
return e !== '';
}).join('.');
this.moveTo(newPath);
}
} | [
"function",
"rename",
"(",
"newName",
")",
"{",
"newName",
"=",
"newName",
".",
"replace",
"(",
"/",
"[\\.\\/]",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"this",
".",
"isRoot",
"(",
")",
")",
"{",
"this",
".",
"_name",
"=",
"newName",
";",
"}",
"else",
"{",
"var",
"newPath",
"=",
"[",
"this",
".",
"parent",
".",
"path",
"(",
")",
",",
"newName",
"]",
".",
"filter",
"(",
"function",
"(",
"e",
")",
"{",
"return",
"e",
"!==",
"''",
";",
"}",
")",
".",
"join",
"(",
"'.'",
")",
";",
"this",
".",
"moveTo",
"(",
"newPath",
")",
";",
"}",
"}"
] | Rename an Entry. This can also mean to move the entry from one point to another in the tree
@param {string} newName the new name/path for the renamed entry | [
"Rename",
"an",
"Entry",
".",
"This",
"can",
"also",
"mean",
"to",
"move",
"the",
"entry",
"from",
"one",
"point",
"to",
"another",
"in",
"the",
"tree"
] | c0a5832bba60ce1d3ece24bc72ee8b4e169c69ac | https://github.com/opencolor-tools/opencolor-js/blob/c0a5832bba60ce1d3ece24bc72ee8b4e169c69ac/lib/entry.js#L67-L77 |
53,820 | KanoComputing/routy.js | lib/index.js | getHrefRec | function getHrefRec(element) {
var href = element.getAttribute('href');
if (href) {
return href.replace(location.origin, '');
}
if (element.parentElement && element.parentElement !== document.body) {
return getHrefRec(element.parentElement);
}
return null;
} | javascript | function getHrefRec(element) {
var href = element.getAttribute('href');
if (href) {
return href.replace(location.origin, '');
}
if (element.parentElement && element.parentElement !== document.body) {
return getHrefRec(element.parentElement);
}
return null;
} | [
"function",
"getHrefRec",
"(",
"element",
")",
"{",
"var",
"href",
"=",
"element",
".",
"getAttribute",
"(",
"'href'",
")",
";",
"if",
"(",
"href",
")",
"{",
"return",
"href",
".",
"replace",
"(",
"location",
".",
"origin",
",",
"''",
")",
";",
"}",
"if",
"(",
"element",
".",
"parentElement",
"&&",
"element",
".",
"parentElement",
"!==",
"document",
".",
"body",
")",
"{",
"return",
"getHrefRec",
"(",
"element",
".",
"parentElement",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Search recursively href attribute value between given element and parents | [
"Search",
"recursively",
"href",
"attribute",
"value",
"between",
"given",
"element",
"and",
"parents"
] | ff659d35d2ff882158e2c04d94a67d2307ed04f7 | https://github.com/KanoComputing/routy.js/blob/ff659d35d2ff882158e2c04d94a67d2307ed04f7/lib/index.js#L190-L202 |
53,821 | cliffano/cmdt | lib/reporters/console.js | _segment | function _segment(file) {
console.log();
process.stdout.write(util.format('%s ', file));
} | javascript | function _segment(file) {
console.log();
process.stdout.write(util.format('%s ', file));
} | [
"function",
"_segment",
"(",
"file",
")",
"{",
"console",
".",
"log",
"(",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"util",
".",
"format",
"(",
"'%s '",
",",
"file",
")",
")",
";",
"}"
] | Segment event handler, log a new line and test file name.
@param {String} file: test file name | [
"Segment",
"event",
"handler",
"log",
"a",
"new",
"line",
"and",
"test",
"file",
"name",
"."
] | 8b8de56a23994a02117069c9c6da5fa1a3176fe5 | https://github.com/cliffano/cmdt/blob/8b8de56a23994a02117069c9c6da5fa1a3176fe5/lib/reporters/console.js#L12-L15 |
53,822 | cliffano/cmdt | lib/reporters/console.js | _success | function _success(test, result) {
process.stdout.write('.'.green);
successes.push({ test: test, result: result });
} | javascript | function _success(test, result) {
process.stdout.write('.'.green);
successes.push({ test: test, result: result });
} | [
"function",
"_success",
"(",
"test",
",",
"result",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"'.'",
".",
"green",
")",
";",
"successes",
".",
"push",
"(",
"{",
"test",
":",
"test",
",",
"result",
":",
"result",
"}",
")",
";",
"}"
] | Success event handler, displays a green dot and register success.
@param {Object} test: test expectation (exitcode, output)
@param {Object} result: command execution result (exitcode, output) | [
"Success",
"event",
"handler",
"displays",
"a",
"green",
"dot",
"and",
"register",
"success",
"."
] | 8b8de56a23994a02117069c9c6da5fa1a3176fe5 | https://github.com/cliffano/cmdt/blob/8b8de56a23994a02117069c9c6da5fa1a3176fe5/lib/reporters/console.js#L23-L26 |
53,823 | cliffano/cmdt | lib/reporters/console.js | _failure | function _failure(errors, test, result) {
process.stdout.write('.'.red);
failures.push({ errors: errors, test: test, result: result });
} | javascript | function _failure(errors, test, result) {
process.stdout.write('.'.red);
failures.push({ errors: errors, test: test, result: result });
} | [
"function",
"_failure",
"(",
"errors",
",",
"test",
",",
"result",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"'.'",
".",
"red",
")",
";",
"failures",
".",
"push",
"(",
"{",
"errors",
":",
"errors",
",",
"test",
":",
"test",
",",
"result",
":",
"result",
"}",
")",
";",
"}"
] | Failure event handler, displays a red dot and register failure.
@param {Array} check errors
@param {Object} test: test expectation (exitcode, output)
@param {Object} result: command execution result (exitcode, output) | [
"Failure",
"event",
"handler",
"displays",
"a",
"red",
"dot",
"and",
"register",
"failure",
"."
] | 8b8de56a23994a02117069c9c6da5fa1a3176fe5 | https://github.com/cliffano/cmdt/blob/8b8de56a23994a02117069c9c6da5fa1a3176fe5/lib/reporters/console.js#L35-L38 |
53,824 | cliffano/cmdt | lib/reporters/console.js | _end | function _end(debug) {
const DEBUG_FIELDS = ['exitcode', 'output', 'stdout', 'stderr'];
var summary = util.format(
'%d test%s, %d success%s, %d failure%s',
successes.length + failures.length,
(successes.length + failures.length > 1) ? 's' : '',
successes.length,
(successes.length > 1) ? 'es' : '',
failures.length,
(failures.length > 1) ? 's' : ''
);
console.log('');
if (failures.length === 0) {
console.log(summary.green);
} else {
failures.forEach(function (failure) {
console.error(util.format('' +
'\n----------------' +
'\n%s%s' +
'\n%s',
failure.test.description ? failure.test.description + '\n' : '',
failure.test.file.cyan,
failure.test.command));
failure.errors.forEach(function (error) {
console.error(error.red);
});
if (debug) {
console.error('exec dir: %s\n'.grey, failure.test.dir);
DEBUG_FIELDS.forEach(function (field) {
if (failure.test[field]) {
console.error('%s: %s\n'.grey, field, failure.result[field]);
}
});
}
});
console.error(summary.red);
}
} | javascript | function _end(debug) {
const DEBUG_FIELDS = ['exitcode', 'output', 'stdout', 'stderr'];
var summary = util.format(
'%d test%s, %d success%s, %d failure%s',
successes.length + failures.length,
(successes.length + failures.length > 1) ? 's' : '',
successes.length,
(successes.length > 1) ? 'es' : '',
failures.length,
(failures.length > 1) ? 's' : ''
);
console.log('');
if (failures.length === 0) {
console.log(summary.green);
} else {
failures.forEach(function (failure) {
console.error(util.format('' +
'\n----------------' +
'\n%s%s' +
'\n%s',
failure.test.description ? failure.test.description + '\n' : '',
failure.test.file.cyan,
failure.test.command));
failure.errors.forEach(function (error) {
console.error(error.red);
});
if (debug) {
console.error('exec dir: %s\n'.grey, failure.test.dir);
DEBUG_FIELDS.forEach(function (field) {
if (failure.test[field]) {
console.error('%s: %s\n'.grey, field, failure.result[field]);
}
});
}
});
console.error(summary.red);
}
} | [
"function",
"_end",
"(",
"debug",
")",
"{",
"const",
"DEBUG_FIELDS",
"=",
"[",
"'exitcode'",
",",
"'output'",
",",
"'stdout'",
",",
"'stderr'",
"]",
";",
"var",
"summary",
"=",
"util",
".",
"format",
"(",
"'%d test%s, %d success%s, %d failure%s'",
",",
"successes",
".",
"length",
"+",
"failures",
".",
"length",
",",
"(",
"successes",
".",
"length",
"+",
"failures",
".",
"length",
">",
"1",
")",
"?",
"'s'",
":",
"''",
",",
"successes",
".",
"length",
",",
"(",
"successes",
".",
"length",
">",
"1",
")",
"?",
"'es'",
":",
"''",
",",
"failures",
".",
"length",
",",
"(",
"failures",
".",
"length",
">",
"1",
")",
"?",
"'s'",
":",
"''",
")",
";",
"console",
".",
"log",
"(",
"''",
")",
";",
"if",
"(",
"failures",
".",
"length",
"===",
"0",
")",
"{",
"console",
".",
"log",
"(",
"summary",
".",
"green",
")",
";",
"}",
"else",
"{",
"failures",
".",
"forEach",
"(",
"function",
"(",
"failure",
")",
"{",
"console",
".",
"error",
"(",
"util",
".",
"format",
"(",
"''",
"+",
"'\\n----------------'",
"+",
"'\\n%s%s'",
"+",
"'\\n%s'",
",",
"failure",
".",
"test",
".",
"description",
"?",
"failure",
".",
"test",
".",
"description",
"+",
"'\\n'",
":",
"''",
",",
"failure",
".",
"test",
".",
"file",
".",
"cyan",
",",
"failure",
".",
"test",
".",
"command",
")",
")",
";",
"failure",
".",
"errors",
".",
"forEach",
"(",
"function",
"(",
"error",
")",
"{",
"console",
".",
"error",
"(",
"error",
".",
"red",
")",
";",
"}",
")",
";",
"if",
"(",
"debug",
")",
"{",
"console",
".",
"error",
"(",
"'exec dir: %s\\n'",
".",
"grey",
",",
"failure",
".",
"test",
".",
"dir",
")",
";",
"DEBUG_FIELDS",
".",
"forEach",
"(",
"function",
"(",
"field",
")",
"{",
"if",
"(",
"failure",
".",
"test",
"[",
"field",
"]",
")",
"{",
"console",
".",
"error",
"(",
"'%s: %s\\n'",
".",
"grey",
",",
"field",
",",
"failure",
".",
"result",
"[",
"field",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"console",
".",
"error",
"(",
"summary",
".",
"red",
")",
";",
"}",
"}"
] | End event handler, displays test summary and optional debug message.
@param {Boolean} debug: if true, displays result output and exit code | [
"End",
"event",
"handler",
"displays",
"test",
"summary",
"and",
"optional",
"debug",
"message",
"."
] | 8b8de56a23994a02117069c9c6da5fa1a3176fe5 | https://github.com/cliffano/cmdt/blob/8b8de56a23994a02117069c9c6da5fa1a3176fe5/lib/reporters/console.js#L45-L93 |
53,825 | Adam4lexander/aframe-event-decorators | event-binder.js | BindToEventDecorator | function BindToEventDecorator(_event, _target, _listenIn, _removeIn) {
return function(propertyName, func) {
const scope = this;
const event = _event || propertyName;
const target = !_target ? this.el : document.querySelector(_target);
if (!target) {
console.warn("Couldn't subscribe "+this.name+"."+propertyName+" to "+event+" on "+_target
+" because querySelector returned undefined.");
return;
}
const listenIn = _listenIn || "init";
const removeIn = _removeIn || "remove";
const listenFunc = this[listenIn];
const removeFunc = this[removeIn];
const boundFunc = func.bind(this);
this[listenIn] = function() {
if (listenFunc !== undefined) {
listenFunc.apply(scope, arguments);
}
target.addEventListener(event, boundFunc);
}
this[removeIn] = function() {
if (removeFunc !== undefined) {
removeFunc.apply(scope, arguments);
}
target.removeEventListener(event, boundFunc);
}
return func;
}
} | javascript | function BindToEventDecorator(_event, _target, _listenIn, _removeIn) {
return function(propertyName, func) {
const scope = this;
const event = _event || propertyName;
const target = !_target ? this.el : document.querySelector(_target);
if (!target) {
console.warn("Couldn't subscribe "+this.name+"."+propertyName+" to "+event+" on "+_target
+" because querySelector returned undefined.");
return;
}
const listenIn = _listenIn || "init";
const removeIn = _removeIn || "remove";
const listenFunc = this[listenIn];
const removeFunc = this[removeIn];
const boundFunc = func.bind(this);
this[listenIn] = function() {
if (listenFunc !== undefined) {
listenFunc.apply(scope, arguments);
}
target.addEventListener(event, boundFunc);
}
this[removeIn] = function() {
if (removeFunc !== undefined) {
removeFunc.apply(scope, arguments);
}
target.removeEventListener(event, boundFunc);
}
return func;
}
} | [
"function",
"BindToEventDecorator",
"(",
"_event",
",",
"_target",
",",
"_listenIn",
",",
"_removeIn",
")",
"{",
"return",
"function",
"(",
"propertyName",
",",
"func",
")",
"{",
"const",
"scope",
"=",
"this",
";",
"const",
"event",
"=",
"_event",
"||",
"propertyName",
";",
"const",
"target",
"=",
"!",
"_target",
"?",
"this",
".",
"el",
":",
"document",
".",
"querySelector",
"(",
"_target",
")",
";",
"if",
"(",
"!",
"target",
")",
"{",
"console",
".",
"warn",
"(",
"\"Couldn't subscribe \"",
"+",
"this",
".",
"name",
"+",
"\".\"",
"+",
"propertyName",
"+",
"\" to \"",
"+",
"event",
"+",
"\" on \"",
"+",
"_target",
"+",
"\" because querySelector returned undefined.\"",
")",
";",
"return",
";",
"}",
"const",
"listenIn",
"=",
"_listenIn",
"||",
"\"init\"",
";",
"const",
"removeIn",
"=",
"_removeIn",
"||",
"\"remove\"",
";",
"const",
"listenFunc",
"=",
"this",
"[",
"listenIn",
"]",
";",
"const",
"removeFunc",
"=",
"this",
"[",
"removeIn",
"]",
";",
"const",
"boundFunc",
"=",
"func",
".",
"bind",
"(",
"this",
")",
";",
"this",
"[",
"listenIn",
"]",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"listenFunc",
"!==",
"undefined",
")",
"{",
"listenFunc",
".",
"apply",
"(",
"scope",
",",
"arguments",
")",
";",
"}",
"target",
".",
"addEventListener",
"(",
"event",
",",
"boundFunc",
")",
";",
"}",
"this",
"[",
"removeIn",
"]",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"removeFunc",
"!==",
"undefined",
")",
"{",
"removeFunc",
".",
"apply",
"(",
"scope",
",",
"arguments",
")",
";",
"}",
"target",
".",
"removeEventListener",
"(",
"event",
",",
"boundFunc",
")",
";",
"}",
"return",
"func",
";",
"}",
"}"
] | Implements the automatic binding and unbinding of the chosen function. Wraps its listenIn and removeIn functions to add and remove the event listener at the correct times. | [
"Implements",
"the",
"automatic",
"binding",
"and",
"unbinding",
"of",
"the",
"chosen",
"function",
".",
"Wraps",
"its",
"listenIn",
"and",
"removeIn",
"functions",
"to",
"add",
"and",
"remove",
"the",
"event",
"listener",
"at",
"the",
"correct",
"times",
"."
] | ddd2a11041ab6e5551fa21c861b8a6c4af5a26ab | https://github.com/Adam4lexander/aframe-event-decorators/blob/ddd2a11041ab6e5551fa21c861b8a6c4af5a26ab/event-binder.js#L41-L74 |
53,826 | spacemaus/postvox | vox-common/authentication.js | checkStanza | function checkStanza(hubClient, stanza, fields, author, opt_sigValue) {
var sig = opt_sigValue === undefined ? stanza.sig : opt_sigValue;
if (!sig) {
throw new errors.AuthenticationError('No `sig` field in stanza');
}
if (!stanza.updatedAt || typeof(stanza.updatedAt) != 'number') {
throw new errors.AuthenticationError('Invalid `updatedAt` field in stanza');
}
return hubClient.getUserProfile(author, stanza.updatedAt)
.then(function(userProfile) {
var verifier = ursa.createVerifier('sha1');
updateWithFields(verifier, stanza, fields);
var pubkeyStr = userProfile.pubkey;
var pubkey = ursa.createPublicKey(pubkeyStr);
var ok = verifier.verify(pubkey, stanza.sig, 'base64');
if (ok) {
return true;
}
debug('First verification failed', author);
// The signatures do not match. Refetch the author's profile directly
// from the hub, then try again.
if (Date.now() - userProfile.syncedAt < MIN_ENTITY_RESYNC_MS) {
debug('Not refetching user profile', author);
return false;
}
return hubClient.getUserProfileFromHub(author, stanza.updatedAt)
.then(function(userProfile) {
// The pubkeys are still the same, so don't bother re-checking.
if (userProfile.pubkey == pubkeyStr) {
debug('Pubkeys identical, not reverifying', author);
return false;
}
// The pubkeys are different, so perhaps that's why the first check
// failed.
var pubkey = ursa.createPublicKey(userProfile.pubkey);
return verifier.verify(userProfile.pubkey, sig, 'base64');
})
})
.catch(errors.NotFoundError, function(err) {
throw new errors.AuthenticationError(
'No such user registered with the Hub: ' + author);
})
.then(function(ok) {
if (!ok) {
throw new errors.AuthenticationError('Stanza signatures do not match for user ' + author);
}
return ok;
});
} | javascript | function checkStanza(hubClient, stanza, fields, author, opt_sigValue) {
var sig = opt_sigValue === undefined ? stanza.sig : opt_sigValue;
if (!sig) {
throw new errors.AuthenticationError('No `sig` field in stanza');
}
if (!stanza.updatedAt || typeof(stanza.updatedAt) != 'number') {
throw new errors.AuthenticationError('Invalid `updatedAt` field in stanza');
}
return hubClient.getUserProfile(author, stanza.updatedAt)
.then(function(userProfile) {
var verifier = ursa.createVerifier('sha1');
updateWithFields(verifier, stanza, fields);
var pubkeyStr = userProfile.pubkey;
var pubkey = ursa.createPublicKey(pubkeyStr);
var ok = verifier.verify(pubkey, stanza.sig, 'base64');
if (ok) {
return true;
}
debug('First verification failed', author);
// The signatures do not match. Refetch the author's profile directly
// from the hub, then try again.
if (Date.now() - userProfile.syncedAt < MIN_ENTITY_RESYNC_MS) {
debug('Not refetching user profile', author);
return false;
}
return hubClient.getUserProfileFromHub(author, stanza.updatedAt)
.then(function(userProfile) {
// The pubkeys are still the same, so don't bother re-checking.
if (userProfile.pubkey == pubkeyStr) {
debug('Pubkeys identical, not reverifying', author);
return false;
}
// The pubkeys are different, so perhaps that's why the first check
// failed.
var pubkey = ursa.createPublicKey(userProfile.pubkey);
return verifier.verify(userProfile.pubkey, sig, 'base64');
})
})
.catch(errors.NotFoundError, function(err) {
throw new errors.AuthenticationError(
'No such user registered with the Hub: ' + author);
})
.then(function(ok) {
if (!ok) {
throw new errors.AuthenticationError('Stanza signatures do not match for user ' + author);
}
return ok;
});
} | [
"function",
"checkStanza",
"(",
"hubClient",
",",
"stanza",
",",
"fields",
",",
"author",
",",
"opt_sigValue",
")",
"{",
"var",
"sig",
"=",
"opt_sigValue",
"===",
"undefined",
"?",
"stanza",
".",
"sig",
":",
"opt_sigValue",
";",
"if",
"(",
"!",
"sig",
")",
"{",
"throw",
"new",
"errors",
".",
"AuthenticationError",
"(",
"'No `sig` field in stanza'",
")",
";",
"}",
"if",
"(",
"!",
"stanza",
".",
"updatedAt",
"||",
"typeof",
"(",
"stanza",
".",
"updatedAt",
")",
"!=",
"'number'",
")",
"{",
"throw",
"new",
"errors",
".",
"AuthenticationError",
"(",
"'Invalid `updatedAt` field in stanza'",
")",
";",
"}",
"return",
"hubClient",
".",
"getUserProfile",
"(",
"author",
",",
"stanza",
".",
"updatedAt",
")",
".",
"then",
"(",
"function",
"(",
"userProfile",
")",
"{",
"var",
"verifier",
"=",
"ursa",
".",
"createVerifier",
"(",
"'sha1'",
")",
";",
"updateWithFields",
"(",
"verifier",
",",
"stanza",
",",
"fields",
")",
";",
"var",
"pubkeyStr",
"=",
"userProfile",
".",
"pubkey",
";",
"var",
"pubkey",
"=",
"ursa",
".",
"createPublicKey",
"(",
"pubkeyStr",
")",
";",
"var",
"ok",
"=",
"verifier",
".",
"verify",
"(",
"pubkey",
",",
"stanza",
".",
"sig",
",",
"'base64'",
")",
";",
"if",
"(",
"ok",
")",
"{",
"return",
"true",
";",
"}",
"debug",
"(",
"'First verification failed'",
",",
"author",
")",
";",
"// The signatures do not match. Refetch the author's profile directly",
"// from the hub, then try again.",
"if",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"userProfile",
".",
"syncedAt",
"<",
"MIN_ENTITY_RESYNC_MS",
")",
"{",
"debug",
"(",
"'Not refetching user profile'",
",",
"author",
")",
";",
"return",
"false",
";",
"}",
"return",
"hubClient",
".",
"getUserProfileFromHub",
"(",
"author",
",",
"stanza",
".",
"updatedAt",
")",
".",
"then",
"(",
"function",
"(",
"userProfile",
")",
"{",
"// The pubkeys are still the same, so don't bother re-checking.",
"if",
"(",
"userProfile",
".",
"pubkey",
"==",
"pubkeyStr",
")",
"{",
"debug",
"(",
"'Pubkeys identical, not reverifying'",
",",
"author",
")",
";",
"return",
"false",
";",
"}",
"// The pubkeys are different, so perhaps that's why the first check",
"// failed.",
"var",
"pubkey",
"=",
"ursa",
".",
"createPublicKey",
"(",
"userProfile",
".",
"pubkey",
")",
";",
"return",
"verifier",
".",
"verify",
"(",
"userProfile",
".",
"pubkey",
",",
"sig",
",",
"'base64'",
")",
";",
"}",
")",
"}",
")",
".",
"catch",
"(",
"errors",
".",
"NotFoundError",
",",
"function",
"(",
"err",
")",
"{",
"throw",
"new",
"errors",
".",
"AuthenticationError",
"(",
"'No such user registered with the Hub: '",
"+",
"author",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"ok",
")",
"{",
"if",
"(",
"!",
"ok",
")",
"{",
"throw",
"new",
"errors",
".",
"AuthenticationError",
"(",
"'Stanza signatures do not match for user '",
"+",
"author",
")",
";",
"}",
"return",
"ok",
";",
"}",
")",
";",
"}"
] | Verifies that the stanza's signature matches the author's public key on file
at the Hub.
May fetch updated user profile information from the Hub.
@param {HubClient} hubClient A HubClient instance used to fetch user profile
information.
@param {Object} stanza The stanza to check
@param {String} stanza.sig The stanza's signature field.
@param {Array<String>} fields The names of the stanza fields to check.
@param {String} author The name of the purported author of the stanza.
@param {String?} opt_sigValue The sig value to check. If unset, defaults to
`stanza.sig`.
@return {Promise<true>} Iff the signature is valid
@throws {errors.AuthenticationError} If the signature is invalid or the user
cannot be found. | [
"Verifies",
"that",
"the",
"stanza",
"s",
"signature",
"matches",
"the",
"author",
"s",
"public",
"key",
"on",
"file",
"at",
"the",
"Hub",
"."
] | de98e5ed37edaee1b1edadf93e15eb8f8d21f457 | https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-common/authentication.js#L181-L229 |
53,827 | spacemaus/postvox | vox-common/authentication.js | signStanza | function signStanza(stanza, fields, privkey) {
stanza.sig = generateStanzaSig(stanza, fields, privkey);
return stanza;
} | javascript | function signStanza(stanza, fields, privkey) {
stanza.sig = generateStanzaSig(stanza, fields, privkey);
return stanza;
} | [
"function",
"signStanza",
"(",
"stanza",
",",
"fields",
",",
"privkey",
")",
"{",
"stanza",
".",
"sig",
"=",
"generateStanzaSig",
"(",
"stanza",
",",
"fields",
",",
"privkey",
")",
";",
"return",
"stanza",
";",
"}"
] | Signs a stanza with the given private key.
@param {Object} stanza The object to sign.
@param {Array<String>} fields The name of the fields to include in the
signature.
@param {String} privkey The private key to use to sign, in PEM format.
@returns {Object} The given stanza, with `sig` set to the signature. | [
"Signs",
"a",
"stanza",
"with",
"the",
"given",
"private",
"key",
"."
] | de98e5ed37edaee1b1edadf93e15eb8f8d21f457 | https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-common/authentication.js#L241-L244 |
53,828 | vphantom/docblox2md | docblox2md.js | srcToMarkdown | function srcToMarkdown(src, level, threshold) {
var blocks = srcToBlocks(src);
return blocksToMarkdown(blocks, level, threshold);
} | javascript | function srcToMarkdown(src, level, threshold) {
var blocks = srcToBlocks(src);
return blocksToMarkdown(blocks, level, threshold);
} | [
"function",
"srcToMarkdown",
"(",
"src",
",",
"level",
",",
"threshold",
")",
"{",
"var",
"blocks",
"=",
"srcToBlocks",
"(",
"src",
")",
";",
"return",
"blocksToMarkdown",
"(",
"blocks",
",",
"level",
",",
"threshold",
")",
";",
"}"
] | Generate Markdown from doc-commented source
Visibility threshold can be:
0: public only
1: public and protected
2: public, protected and private
@param {String} src Source code
@param {Number} level Header starting level (1-6)
@param {Number} threshold Visibility threshold
@return {String} Markdown text | [
"Generate",
"Markdown",
"from",
"doc",
"-",
"commented",
"source"
] | a3524e7188546dc93f93c3e5b9b822f73cec8267 | https://github.com/vphantom/docblox2md/blob/a3524e7188546dc93f93c3e5b9b822f73cec8267/docblox2md.js#L369-L373 |
53,829 | vphantom/docblox2md | docblox2md.js | loadFile | function loadFile(filename, level, threshold) {
var out = [];
var file;
out.push('<!-- BEGIN DOC-COMMENT H' + level + ' ' + filename + ' -->\n');
try {
file = fs.readFileSync(filename, {encoding: 'utf-8'});
out.push(srcToMarkdown(file, level, threshold));
} catch (e) {
// I don't see how we can relay this error safely
}
out.push('<!-- END DOC-COMMENT -->');
return out.join('');
} | javascript | function loadFile(filename, level, threshold) {
var out = [];
var file;
out.push('<!-- BEGIN DOC-COMMENT H' + level + ' ' + filename + ' -->\n');
try {
file = fs.readFileSync(filename, {encoding: 'utf-8'});
out.push(srcToMarkdown(file, level, threshold));
} catch (e) {
// I don't see how we can relay this error safely
}
out.push('<!-- END DOC-COMMENT -->');
return out.join('');
} | [
"function",
"loadFile",
"(",
"filename",
",",
"level",
",",
"threshold",
")",
"{",
"var",
"out",
"=",
"[",
"]",
";",
"var",
"file",
";",
"out",
".",
"push",
"(",
"'<!-- BEGIN DOC-COMMENT H'",
"+",
"level",
"+",
"' '",
"+",
"filename",
"+",
"' -->\\n'",
")",
";",
"try",
"{",
"file",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
",",
"{",
"encoding",
":",
"'utf-8'",
"}",
")",
";",
"out",
".",
"push",
"(",
"srcToMarkdown",
"(",
"file",
",",
"level",
",",
"threshold",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// I don't see how we can relay this error safely",
"}",
"out",
".",
"push",
"(",
"'<!-- END DOC-COMMENT -->'",
")",
";",
"return",
"out",
".",
"join",
"(",
"''",
")",
";",
"}"
] | Load file from disk and process to Markdown
Visibility threshold can be:
0: public only
1: public and protected
2: public, protected and private
@param {String} filename File name
@param {Number} level Header starting level (1-6)
@param {Number} threshold Visibility threshold
@return {String} Markdown text with placeholder envelope | [
"Load",
"file",
"from",
"disk",
"and",
"process",
"to",
"Markdown"
] | a3524e7188546dc93f93c3e5b9b822f73cec8267 | https://github.com/vphantom/docblox2md/blob/a3524e7188546dc93f93c3e5b9b822f73cec8267/docblox2md.js#L390-L406 |
53,830 | vphantom/docblox2md | docblox2md.js | filterDocument | function filterDocument(doc, threshold) {
var sections = doc.split(re.mdSplit);
var out = [];
var i = 0;
for (i = 0; i < sections.length; i++) {
// 1. Raw input to preserve
out.push(sections[i]);
// Iterate
i++;
if (i >= sections.length) {
break;
}
// 2. Header level
let level = sections[i];
if (level === undefined) {
level = 1;
}
// Iterate
i++;
if (i >= sections.length) {
break;
}
// 3. File name
out.push(loadFile(sections[i], level, threshold));
}
return out.join('');
} | javascript | function filterDocument(doc, threshold) {
var sections = doc.split(re.mdSplit);
var out = [];
var i = 0;
for (i = 0; i < sections.length; i++) {
// 1. Raw input to preserve
out.push(sections[i]);
// Iterate
i++;
if (i >= sections.length) {
break;
}
// 2. Header level
let level = sections[i];
if (level === undefined) {
level = 1;
}
// Iterate
i++;
if (i >= sections.length) {
break;
}
// 3. File name
out.push(loadFile(sections[i], level, threshold));
}
return out.join('');
} | [
"function",
"filterDocument",
"(",
"doc",
",",
"threshold",
")",
"{",
"var",
"sections",
"=",
"doc",
".",
"split",
"(",
"re",
".",
"mdSplit",
")",
";",
"var",
"out",
"=",
"[",
"]",
";",
"var",
"i",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"sections",
".",
"length",
";",
"i",
"++",
")",
"{",
"// 1. Raw input to preserve",
"out",
".",
"push",
"(",
"sections",
"[",
"i",
"]",
")",
";",
"// Iterate",
"i",
"++",
";",
"if",
"(",
"i",
">=",
"sections",
".",
"length",
")",
"{",
"break",
";",
"}",
"// 2. Header level",
"let",
"level",
"=",
"sections",
"[",
"i",
"]",
";",
"if",
"(",
"level",
"===",
"undefined",
")",
"{",
"level",
"=",
"1",
";",
"}",
"// Iterate",
"i",
"++",
";",
"if",
"(",
"i",
">=",
"sections",
".",
"length",
")",
"{",
"break",
";",
"}",
"// 3. File name",
"out",
".",
"push",
"(",
"loadFile",
"(",
"sections",
"[",
"i",
"]",
",",
"level",
",",
"threshold",
")",
")",
";",
"}",
"return",
"out",
".",
"join",
"(",
"''",
")",
";",
"}"
] | Filter Markdown document for our placeholders
Visibility threshold can be:
0: public only
1: public and protected
2: public, protected and private
@param {String} doc Input document
@param {Number} threshold Visibility threshold
@return {String} Updated document | [
"Filter",
"Markdown",
"document",
"for",
"our",
"placeholders"
] | a3524e7188546dc93f93c3e5b9b822f73cec8267 | https://github.com/vphantom/docblox2md/blob/a3524e7188546dc93f93c3e5b9b822f73cec8267/docblox2md.js#L422-L455 |
53,831 | xiaoyann/smart-ui | src/index.js | install | function install(Vue) {
for (const name in components) {
const component = components[name].component || components[name]
Vue.component(name, component)
}
Vue.prototype.$actionSheet = $actionSheet
Vue.prototype.$loading = $loading
Vue.prototype.$toast = $toast
Vue.prototype.$dialog = $dialog
} | javascript | function install(Vue) {
for (const name in components) {
const component = components[name].component || components[name]
Vue.component(name, component)
}
Vue.prototype.$actionSheet = $actionSheet
Vue.prototype.$loading = $loading
Vue.prototype.$toast = $toast
Vue.prototype.$dialog = $dialog
} | [
"function",
"install",
"(",
"Vue",
")",
"{",
"for",
"(",
"const",
"name",
"in",
"components",
")",
"{",
"const",
"component",
"=",
"components",
"[",
"name",
"]",
".",
"component",
"||",
"components",
"[",
"name",
"]",
"Vue",
".",
"component",
"(",
"name",
",",
"component",
")",
"}",
"Vue",
".",
"prototype",
".",
"$actionSheet",
"=",
"$actionSheet",
"Vue",
".",
"prototype",
".",
"$loading",
"=",
"$loading",
"Vue",
".",
"prototype",
".",
"$toast",
"=",
"$toast",
"Vue",
".",
"prototype",
".",
"$dialog",
"=",
"$dialog",
"}"
] | register globally all components | [
"register",
"globally",
"all",
"components"
] | f5e1d70717eec062434d4cfe2998329880d2ecc4 | https://github.com/xiaoyann/smart-ui/blob/f5e1d70717eec062434d4cfe2998329880d2ecc4/src/index.js#L45-L54 |
53,832 | xiaoyann/smart-ui | src/index.js | config | function config(name) {
const args = [].slice.call(arguments, 1)
const modules = {
ActionSheet: $actionSheet,
Loading: $loading,
Toast: $toast,
Dialog: $dialog
}
const module = components[name] || modules[name]
if (typeof module.config === 'function') {
module.config.apply(null, args)
}
else {
console.warn(`${name}.config is not a function`)
}
} | javascript | function config(name) {
const args = [].slice.call(arguments, 1)
const modules = {
ActionSheet: $actionSheet,
Loading: $loading,
Toast: $toast,
Dialog: $dialog
}
const module = components[name] || modules[name]
if (typeof module.config === 'function') {
module.config.apply(null, args)
}
else {
console.warn(`${name}.config is not a function`)
}
} | [
"function",
"config",
"(",
"name",
")",
"{",
"const",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
"const",
"modules",
"=",
"{",
"ActionSheet",
":",
"$actionSheet",
",",
"Loading",
":",
"$loading",
",",
"Toast",
":",
"$toast",
",",
"Dialog",
":",
"$dialog",
"}",
"const",
"module",
"=",
"components",
"[",
"name",
"]",
"||",
"modules",
"[",
"name",
"]",
"if",
"(",
"typeof",
"module",
".",
"config",
"===",
"'function'",
")",
"{",
"module",
".",
"config",
".",
"apply",
"(",
"null",
",",
"args",
")",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"`",
"${",
"name",
"}",
"`",
")",
"}",
"}"
] | Components can export a function named config to customize some options for user | [
"Components",
"can",
"export",
"a",
"function",
"named",
"config",
"to",
"customize",
"some",
"options",
"for",
"user"
] | f5e1d70717eec062434d4cfe2998329880d2ecc4 | https://github.com/xiaoyann/smart-ui/blob/f5e1d70717eec062434d4cfe2998329880d2ecc4/src/index.js#L58-L73 |
53,833 | AndiDittrich/Node.mysql-magic | lib/fetch-row.js | fetchRow | async function fetchRow(connection, query, params){
// execute query
const [result] = await _query(connection, query, params);
// entry found ?
if (result.length >= 1){
// extract data
return result[0];
}else{
return null;
}
} | javascript | async function fetchRow(connection, query, params){
// execute query
const [result] = await _query(connection, query, params);
// entry found ?
if (result.length >= 1){
// extract data
return result[0];
}else{
return null;
}
} | [
"async",
"function",
"fetchRow",
"(",
"connection",
",",
"query",
",",
"params",
")",
"{",
"// execute query",
"const",
"[",
"result",
"]",
"=",
"await",
"_query",
"(",
"connection",
",",
"query",
",",
"params",
")",
";",
"// entry found ?",
"if",
"(",
"result",
".",
"length",
">=",
"1",
")",
"{",
"// extract data",
"return",
"result",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | fetch a single row and handle errors | [
"fetch",
"a",
"single",
"row",
"and",
"handle",
"errors"
] | f9783ac93f4a5744407781d7875ae68cad58cc48 | https://github.com/AndiDittrich/Node.mysql-magic/blob/f9783ac93f4a5744407781d7875ae68cad58cc48/lib/fetch-row.js#L4-L16 |
53,834 | thlorenz/node-traceur | src/semantics/symbols/Project.js | getStandardModule | function getStandardModule(url) {
if (!(url in standardModuleCache)) {
var symbol = new ModuleSymbol(null, null, null, url);
var moduleInstance = traceur.runtime.modules[url];
Object.keys(moduleInstance).forEach((name) => {
symbol.addExport(name, new ExportSymbol(null, name, null));
});
standardModuleCache[url] = symbol;
}
return standardModuleCache[url];
} | javascript | function getStandardModule(url) {
if (!(url in standardModuleCache)) {
var symbol = new ModuleSymbol(null, null, null, url);
var moduleInstance = traceur.runtime.modules[url];
Object.keys(moduleInstance).forEach((name) => {
symbol.addExport(name, new ExportSymbol(null, name, null));
});
standardModuleCache[url] = symbol;
}
return standardModuleCache[url];
} | [
"function",
"getStandardModule",
"(",
"url",
")",
"{",
"if",
"(",
"!",
"(",
"url",
"in",
"standardModuleCache",
")",
")",
"{",
"var",
"symbol",
"=",
"new",
"ModuleSymbol",
"(",
"null",
",",
"null",
",",
"null",
",",
"url",
")",
";",
"var",
"moduleInstance",
"=",
"traceur",
".",
"runtime",
".",
"modules",
"[",
"url",
"]",
";",
"Object",
".",
"keys",
"(",
"moduleInstance",
")",
".",
"forEach",
"(",
"(",
"name",
")",
"=>",
"{",
"symbol",
".",
"addExport",
"(",
"name",
",",
"new",
"ExportSymbol",
"(",
"null",
",",
"name",
",",
"null",
")",
")",
";",
"}",
")",
";",
"standardModuleCache",
"[",
"url",
"]",
"=",
"symbol",
";",
"}",
"return",
"standardModuleCache",
"[",
"url",
"]",
";",
"}"
] | Gets a ModuleSymbol for a standard module. We cache the Symbol so that
future accesses to this returns the same symbol.
@param {string} url
@return {ModuleSymbol} | [
"Gets",
"a",
"ModuleSymbol",
"for",
"a",
"standard",
"module",
".",
"We",
"cache",
"the",
"Symbol",
"so",
"that",
"future",
"accesses",
"to",
"this",
"returns",
"the",
"same",
"symbol",
"."
] | 79a21ad03831ba36df504988b05022404ad8f9c3 | https://github.com/thlorenz/node-traceur/blob/79a21ad03831ba36df504988b05022404ad8f9c3/src/semantics/symbols/Project.js#L43-L53 |
53,835 | kaelzhang/node-semver-stable | index.js | desc | function desc (array) {
// Simply clone
array = [].concat(array);
// Ordered by version DESC
array.sort(semver.rcompare);
return array;
} | javascript | function desc (array) {
// Simply clone
array = [].concat(array);
// Ordered by version DESC
array.sort(semver.rcompare);
return array;
} | [
"function",
"desc",
"(",
"array",
")",
"{",
"// Simply clone",
"array",
"=",
"[",
"]",
".",
"concat",
"(",
"array",
")",
";",
"// Ordered by version DESC ",
"array",
".",
"sort",
"(",
"semver",
".",
"rcompare",
")",
";",
"return",
"array",
";",
"}"
] | Sort by DESC | [
"Sort",
"by",
"DESC"
] | 34dd29842409295d49889d45871bec55a992b7f6 | https://github.com/kaelzhang/node-semver-stable/blob/34dd29842409295d49889d45871bec55a992b7f6/index.js#L38-L44 |
53,836 | spacemaus/postvox | vox-common/level-index.js | scan | function scan(leveldb, options) {
return new P(function(resolve, reject) {
var datas = [];
var resolved = false;
function fin() {
if (resolved) {
return;
}
resolve(P.all(datas));
resolved = true;
}
leveldb.createReadStream(options)
.on('data', function(data) {
datas.push(data);
})
.on('close', fin)
.on('end', fin)
.on('error', function(err) {
reject(err);
})
});
} | javascript | function scan(leveldb, options) {
return new P(function(resolve, reject) {
var datas = [];
var resolved = false;
function fin() {
if (resolved) {
return;
}
resolve(P.all(datas));
resolved = true;
}
leveldb.createReadStream(options)
.on('data', function(data) {
datas.push(data);
})
.on('close', fin)
.on('end', fin)
.on('error', function(err) {
reject(err);
})
});
} | [
"function",
"scan",
"(",
"leveldb",
",",
"options",
")",
"{",
"return",
"new",
"P",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"datas",
"=",
"[",
"]",
";",
"var",
"resolved",
"=",
"false",
";",
"function",
"fin",
"(",
")",
"{",
"if",
"(",
"resolved",
")",
"{",
"return",
";",
"}",
"resolve",
"(",
"P",
".",
"all",
"(",
"datas",
")",
")",
";",
"resolved",
"=",
"true",
";",
"}",
"leveldb",
".",
"createReadStream",
"(",
"options",
")",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"datas",
".",
"push",
"(",
"data",
")",
";",
"}",
")",
".",
"on",
"(",
"'close'",
",",
"fin",
")",
".",
"on",
"(",
"'end'",
",",
"fin",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
"}",
")",
";",
"}"
] | Starts a LevelDB scan and returns a Promise for the list of results.
@param {LevelDB} leveldb The DB to scan.
@param {Object} options An options object passed verbatim to
leveldb.createReadStream().
@return {Promise<Object[]>} The scan results. | [
"Starts",
"a",
"LevelDB",
"scan",
"and",
"returns",
"a",
"Promise",
"for",
"the",
"list",
"of",
"results",
"."
] | de98e5ed37edaee1b1edadf93e15eb8f8d21f457 | https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-common/level-index.js#L177-L198 |
53,837 | spacemaus/postvox | vox-common/level-index.js | scanIndex | function scanIndex(leveldb, options) {
return new P(function(resolve, reject) {
var datas = [];
var resolved = false;
function fin() {
if (resolved) {
return;
}
resolve(P.all(datas));
resolved = true;
}
leveldb.createKeyStream(options)
.on('data', function(key) {
var i = key.lastIndexOf('\x00');
var key = key.substr(i + 1);
datas.push(leveldb.getAsync(key));
})
.on('close', fin)
.on('end', fin)
.on('error', function(err) {
reject(err);
})
});
} | javascript | function scanIndex(leveldb, options) {
return new P(function(resolve, reject) {
var datas = [];
var resolved = false;
function fin() {
if (resolved) {
return;
}
resolve(P.all(datas));
resolved = true;
}
leveldb.createKeyStream(options)
.on('data', function(key) {
var i = key.lastIndexOf('\x00');
var key = key.substr(i + 1);
datas.push(leveldb.getAsync(key));
})
.on('close', fin)
.on('end', fin)
.on('error', function(err) {
reject(err);
})
});
} | [
"function",
"scanIndex",
"(",
"leveldb",
",",
"options",
")",
"{",
"return",
"new",
"P",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"datas",
"=",
"[",
"]",
";",
"var",
"resolved",
"=",
"false",
";",
"function",
"fin",
"(",
")",
"{",
"if",
"(",
"resolved",
")",
"{",
"return",
";",
"}",
"resolve",
"(",
"P",
".",
"all",
"(",
"datas",
")",
")",
";",
"resolved",
"=",
"true",
";",
"}",
"leveldb",
".",
"createKeyStream",
"(",
"options",
")",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"key",
")",
"{",
"var",
"i",
"=",
"key",
".",
"lastIndexOf",
"(",
"'\\x00'",
")",
";",
"var",
"key",
"=",
"key",
".",
"substr",
"(",
"i",
"+",
"1",
")",
";",
"datas",
".",
"push",
"(",
"leveldb",
".",
"getAsync",
"(",
"key",
")",
")",
";",
"}",
")",
".",
"on",
"(",
"'close'",
",",
"fin",
")",
".",
"on",
"(",
"'end'",
",",
"fin",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
"}",
")",
";",
"}"
] | Starts a LevelDB index scan and returns a Promise for the list of results.
@param {LevelDB} leveldb The DB to scan.
@param {Object} options An options object passed verbatim to
leveldb.createKeyStream().
@return {Promise<Object[]>} The scan results. | [
"Starts",
"a",
"LevelDB",
"index",
"scan",
"and",
"returns",
"a",
"Promise",
"for",
"the",
"list",
"of",
"results",
"."
] | de98e5ed37edaee1b1edadf93e15eb8f8d21f457 | https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-common/level-index.js#L209-L232 |
53,838 | SilentCicero/wafr | src/index.js | wafr | function wafr(options, callback) {
const contractsPath = options.path;
const optimizeCompiler = options.optimize;
const sourcesExclude = options.exclude;
const sourcesInclude = options.include;
const focusContract = options.focus;
const reportLogs = {
contracts: {},
status: 'success',
failure: 0,
success: 0,
logs: {},
};
// get allinput sources
getInputSources(contractsPath, sourcesExclude, sourcesInclude, focusContract, (inputError, sources) => {
if (inputError) {
throwError(`while getting input sources: ${inputError}`);
}
// build contract sources input for compiler
const compilerInput = {
sources: Object.assign({ 'wafr/Test.sol': testContract }, sources),
};
// compiling contracts
log(`compiling contracts from ${Object.keys(sources).length} sources...`);
// compile solc output (sync method)
const output = solc.compile(compilerInput, optimizeCompiler);
// output compiler warnings
filterErrorErrors(output.errors).forEach((outputError) => {
log(`while compiling contracts in path warning.. ${contractsPath}: ${outputError}`);
});
// handle all compiling errors
if (filterErrorWarnings(output.errors).length > 0) {
output.errors.forEach((outputError) => {
throwError(`while compiling contracts in path ${contractsPath}: ${outputError}`);
});
} else {
// compiling contracts
log('contracts compiled!');
const outputContracts = contractNameProcessing(options.onlyContractName, output.contracts);
// add output to report
reportLogs.contracts = outputContracts;
// find and build test contracts array
const testContracts = buildTestContractsArray(outputContracts);
const startIndex = 0;
// done function
const contractComplete = (contractReport) => {
// if contract failed, then all tests fail
if (contractReport !== false) {
if (contractReport.status === 'failure') {
reportLogs.status = 'failure';
reportLogs.failure += contractReport.failure;
} else {
reportLogs.success += contractReport.success;
}
}
// if contract report is false, there is no more contracts to test
if (contractReport === false) {
// report done in log
report(`
${reportLogs.failure && chalk.red(`${reportLogs.failure} not passing`) || ''}
${reportLogs.success && chalk.green(`${reportLogs.success} passing`) || ''}
`);
// report logs
callback(null, reportLogs);
} else {
reportLogs.logs[contractReport.name] = contractReport;
}
};
// if no test contracts, end testing
if (testContracts.length === 0) {
contractComplete(false);
} else {
// test each contract sequentially
testContractsSeq(startIndex, testContracts, contractComplete);
}
}
});
} | javascript | function wafr(options, callback) {
const contractsPath = options.path;
const optimizeCompiler = options.optimize;
const sourcesExclude = options.exclude;
const sourcesInclude = options.include;
const focusContract = options.focus;
const reportLogs = {
contracts: {},
status: 'success',
failure: 0,
success: 0,
logs: {},
};
// get allinput sources
getInputSources(contractsPath, sourcesExclude, sourcesInclude, focusContract, (inputError, sources) => {
if (inputError) {
throwError(`while getting input sources: ${inputError}`);
}
// build contract sources input for compiler
const compilerInput = {
sources: Object.assign({ 'wafr/Test.sol': testContract }, sources),
};
// compiling contracts
log(`compiling contracts from ${Object.keys(sources).length} sources...`);
// compile solc output (sync method)
const output = solc.compile(compilerInput, optimizeCompiler);
// output compiler warnings
filterErrorErrors(output.errors).forEach((outputError) => {
log(`while compiling contracts in path warning.. ${contractsPath}: ${outputError}`);
});
// handle all compiling errors
if (filterErrorWarnings(output.errors).length > 0) {
output.errors.forEach((outputError) => {
throwError(`while compiling contracts in path ${contractsPath}: ${outputError}`);
});
} else {
// compiling contracts
log('contracts compiled!');
const outputContracts = contractNameProcessing(options.onlyContractName, output.contracts);
// add output to report
reportLogs.contracts = outputContracts;
// find and build test contracts array
const testContracts = buildTestContractsArray(outputContracts);
const startIndex = 0;
// done function
const contractComplete = (contractReport) => {
// if contract failed, then all tests fail
if (contractReport !== false) {
if (contractReport.status === 'failure') {
reportLogs.status = 'failure';
reportLogs.failure += contractReport.failure;
} else {
reportLogs.success += contractReport.success;
}
}
// if contract report is false, there is no more contracts to test
if (contractReport === false) {
// report done in log
report(`
${reportLogs.failure && chalk.red(`${reportLogs.failure} not passing`) || ''}
${reportLogs.success && chalk.green(`${reportLogs.success} passing`) || ''}
`);
// report logs
callback(null, reportLogs);
} else {
reportLogs.logs[contractReport.name] = contractReport;
}
};
// if no test contracts, end testing
if (testContracts.length === 0) {
contractComplete(false);
} else {
// test each contract sequentially
testContractsSeq(startIndex, testContracts, contractComplete);
}
}
});
} | [
"function",
"wafr",
"(",
"options",
",",
"callback",
")",
"{",
"const",
"contractsPath",
"=",
"options",
".",
"path",
";",
"const",
"optimizeCompiler",
"=",
"options",
".",
"optimize",
";",
"const",
"sourcesExclude",
"=",
"options",
".",
"exclude",
";",
"const",
"sourcesInclude",
"=",
"options",
".",
"include",
";",
"const",
"focusContract",
"=",
"options",
".",
"focus",
";",
"const",
"reportLogs",
"=",
"{",
"contracts",
":",
"{",
"}",
",",
"status",
":",
"'success'",
",",
"failure",
":",
"0",
",",
"success",
":",
"0",
",",
"logs",
":",
"{",
"}",
",",
"}",
";",
"// get allinput sources",
"getInputSources",
"(",
"contractsPath",
",",
"sourcesExclude",
",",
"sourcesInclude",
",",
"focusContract",
",",
"(",
"inputError",
",",
"sources",
")",
"=>",
"{",
"if",
"(",
"inputError",
")",
"{",
"throwError",
"(",
"`",
"${",
"inputError",
"}",
"`",
")",
";",
"}",
"// build contract sources input for compiler",
"const",
"compilerInput",
"=",
"{",
"sources",
":",
"Object",
".",
"assign",
"(",
"{",
"'wafr/Test.sol'",
":",
"testContract",
"}",
",",
"sources",
")",
",",
"}",
";",
"// compiling contracts",
"log",
"(",
"`",
"${",
"Object",
".",
"keys",
"(",
"sources",
")",
".",
"length",
"}",
"`",
")",
";",
"// compile solc output (sync method)",
"const",
"output",
"=",
"solc",
".",
"compile",
"(",
"compilerInput",
",",
"optimizeCompiler",
")",
";",
"// output compiler warnings",
"filterErrorErrors",
"(",
"output",
".",
"errors",
")",
".",
"forEach",
"(",
"(",
"outputError",
")",
"=>",
"{",
"log",
"(",
"`",
"${",
"contractsPath",
"}",
"${",
"outputError",
"}",
"`",
")",
";",
"}",
")",
";",
"// handle all compiling errors",
"if",
"(",
"filterErrorWarnings",
"(",
"output",
".",
"errors",
")",
".",
"length",
">",
"0",
")",
"{",
"output",
".",
"errors",
".",
"forEach",
"(",
"(",
"outputError",
")",
"=>",
"{",
"throwError",
"(",
"`",
"${",
"contractsPath",
"}",
"${",
"outputError",
"}",
"`",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// compiling contracts",
"log",
"(",
"'contracts compiled!'",
")",
";",
"const",
"outputContracts",
"=",
"contractNameProcessing",
"(",
"options",
".",
"onlyContractName",
",",
"output",
".",
"contracts",
")",
";",
"// add output to report",
"reportLogs",
".",
"contracts",
"=",
"outputContracts",
";",
"// find and build test contracts array",
"const",
"testContracts",
"=",
"buildTestContractsArray",
"(",
"outputContracts",
")",
";",
"const",
"startIndex",
"=",
"0",
";",
"// done function",
"const",
"contractComplete",
"=",
"(",
"contractReport",
")",
"=>",
"{",
"// if contract failed, then all tests fail",
"if",
"(",
"contractReport",
"!==",
"false",
")",
"{",
"if",
"(",
"contractReport",
".",
"status",
"===",
"'failure'",
")",
"{",
"reportLogs",
".",
"status",
"=",
"'failure'",
";",
"reportLogs",
".",
"failure",
"+=",
"contractReport",
".",
"failure",
";",
"}",
"else",
"{",
"reportLogs",
".",
"success",
"+=",
"contractReport",
".",
"success",
";",
"}",
"}",
"// if contract report is false, there is no more contracts to test",
"if",
"(",
"contractReport",
"===",
"false",
")",
"{",
"// report done in log",
"report",
"(",
"`",
"${",
"reportLogs",
".",
"failure",
"&&",
"chalk",
".",
"red",
"(",
"`",
"${",
"reportLogs",
".",
"failure",
"}",
"`",
")",
"||",
"''",
"}",
"${",
"reportLogs",
".",
"success",
"&&",
"chalk",
".",
"green",
"(",
"`",
"${",
"reportLogs",
".",
"success",
"}",
"`",
")",
"||",
"''",
"}",
"`",
")",
";",
"// report logs",
"callback",
"(",
"null",
",",
"reportLogs",
")",
";",
"}",
"else",
"{",
"reportLogs",
".",
"logs",
"[",
"contractReport",
".",
"name",
"]",
"=",
"contractReport",
";",
"}",
"}",
";",
"// if no test contracts, end testing",
"if",
"(",
"testContracts",
".",
"length",
"===",
"0",
")",
"{",
"contractComplete",
"(",
"false",
")",
";",
"}",
"else",
"{",
"// test each contract sequentially",
"testContractsSeq",
"(",
"startIndex",
",",
"testContracts",
",",
"contractComplete",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | run the main solTest export | [
"run",
"the",
"main",
"solTest",
"export"
] | 2c7483feec5df346d8903cab5badc17143c3876d | https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/src/index.js#L530-L621 |
53,839 | Wiredcraft/handle-http-error | lib/parseError.js | parseError | function parseError(res, body) {
// Res is optional.
if (body == null) {
body = res;
}
// Status code is required.
const status = parseError.findErrorCode(sliced(arguments));
if (!status) {
return false;
}
// Body can have an error-like object, in which case the attributes will be used.
const obj = findErrorObj(body);
if (obj) {
body = Object.assign(body, obj);
}
return [status, body];
} | javascript | function parseError(res, body) {
// Res is optional.
if (body == null) {
body = res;
}
// Status code is required.
const status = parseError.findErrorCode(sliced(arguments));
if (!status) {
return false;
}
// Body can have an error-like object, in which case the attributes will be used.
const obj = findErrorObj(body);
if (obj) {
body = Object.assign(body, obj);
}
return [status, body];
} | [
"function",
"parseError",
"(",
"res",
",",
"body",
")",
"{",
"// Res is optional.",
"if",
"(",
"body",
"==",
"null",
")",
"{",
"body",
"=",
"res",
";",
"}",
"// Status code is required.",
"const",
"status",
"=",
"parseError",
".",
"findErrorCode",
"(",
"sliced",
"(",
"arguments",
")",
")",
";",
"if",
"(",
"!",
"status",
")",
"{",
"return",
"false",
";",
"}",
"// Body can have an error-like object, in which case the attributes will be used.",
"const",
"obj",
"=",
"findErrorObj",
"(",
"body",
")",
";",
"if",
"(",
"obj",
")",
"{",
"body",
"=",
"Object",
".",
"assign",
"(",
"body",
",",
"obj",
")",
";",
"}",
"return",
"[",
"status",
",",
"body",
"]",
";",
"}"
] | See if the response has a status error code, and if the error message has an error-like object. | [
"See",
"if",
"the",
"response",
"has",
"a",
"status",
"error",
"code",
"and",
"if",
"the",
"error",
"message",
"has",
"an",
"error",
"-",
"like",
"object",
"."
] | 2054c1ade9f5e4b11fd64c432317c815cb97063a | https://github.com/Wiredcraft/handle-http-error/blob/2054c1ade9f5e4b11fd64c432317c815cb97063a/lib/parseError.js#L18-L34 |
53,840 | teabyii/qa | lib/tty.js | function (len) {
_.isNumber(len) || (len = 1)
while (len--) {
readline.moveCursor(this.rl.output, -cliWidth(), 0)
readline.clearLine(this.rl.output, 0)
if (len) {
readline.moveCursor(this.rl.output, 0, -1)
}
}
return this
} | javascript | function (len) {
_.isNumber(len) || (len = 1)
while (len--) {
readline.moveCursor(this.rl.output, -cliWidth(), 0)
readline.clearLine(this.rl.output, 0)
if (len) {
readline.moveCursor(this.rl.output, 0, -1)
}
}
return this
} | [
"function",
"(",
"len",
")",
"{",
"_",
".",
"isNumber",
"(",
"len",
")",
"||",
"(",
"len",
"=",
"1",
")",
"while",
"(",
"len",
"--",
")",
"{",
"readline",
".",
"moveCursor",
"(",
"this",
".",
"rl",
".",
"output",
",",
"-",
"cliWidth",
"(",
")",
",",
"0",
")",
"readline",
".",
"clearLine",
"(",
"this",
".",
"rl",
".",
"output",
",",
"0",
")",
"if",
"(",
"len",
")",
"{",
"readline",
".",
"moveCursor",
"(",
"this",
".",
"rl",
".",
"output",
",",
"0",
",",
"-",
"1",
")",
"}",
"}",
"return",
"this",
"}"
] | Remove the line.
@params {number} len Lines to remove.
@returns {Object} Self. | [
"Remove",
"the",
"line",
"."
] | 9224180dcb9e6b57c021f83b259316e84ebc573e | https://github.com/teabyii/qa/blob/9224180dcb9e6b57c021f83b259316e84ebc573e/lib/tty.js#L17-L28 |
|
53,841 | teabyii/qa | lib/tty.js | function (x) {
_.isNumber(x) || (x = 1)
readline.moveCursor(this.rl.output, 0, -x)
return this
} | javascript | function (x) {
_.isNumber(x) || (x = 1)
readline.moveCursor(this.rl.output, 0, -x)
return this
} | [
"function",
"(",
"x",
")",
"{",
"_",
".",
"isNumber",
"(",
"x",
")",
"||",
"(",
"x",
"=",
"1",
")",
"readline",
".",
"moveCursor",
"(",
"this",
".",
"rl",
".",
"output",
",",
"0",
",",
"-",
"x",
")",
"return",
"this",
"}"
] | Move cursor up.
@param {number} x How far to go up (default to 1).
@return {Object} Self. | [
"Move",
"cursor",
"up",
"."
] | 9224180dcb9e6b57c021f83b259316e84ebc573e | https://github.com/teabyii/qa/blob/9224180dcb9e6b57c021f83b259316e84ebc573e/lib/tty.js#L64-L68 |
|
53,842 | teabyii/qa | lib/tty.js | function () {
if (!this.cursorPos) {
return this
}
var line = this.rl._prompt + this.rl.line
readline.moveCursor(this.rl.output, -line.length, 0)
readline.moveCursor(this.rl.output, this.cursorPos.cols, 0)
this.cursorPos = null
return this
} | javascript | function () {
if (!this.cursorPos) {
return this
}
var line = this.rl._prompt + this.rl.line
readline.moveCursor(this.rl.output, -line.length, 0)
readline.moveCursor(this.rl.output, this.cursorPos.cols, 0)
this.cursorPos = null
return this
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"cursorPos",
")",
"{",
"return",
"this",
"}",
"var",
"line",
"=",
"this",
".",
"rl",
".",
"_prompt",
"+",
"this",
".",
"rl",
".",
"line",
"readline",
".",
"moveCursor",
"(",
"this",
".",
"rl",
".",
"output",
",",
"-",
"line",
".",
"length",
",",
"0",
")",
"readline",
".",
"moveCursor",
"(",
"this",
".",
"rl",
".",
"output",
",",
"this",
".",
"cursorPos",
".",
"cols",
",",
"0",
")",
"this",
".",
"cursorPos",
"=",
"null",
"return",
"this",
"}"
] | Restore the cursor position to where it has been previously stored.
@return {Object} Self. | [
"Restore",
"the",
"cursor",
"position",
"to",
"where",
"it",
"has",
"been",
"previously",
"stored",
"."
] | 9224180dcb9e6b57c021f83b259316e84ebc573e | https://github.com/teabyii/qa/blob/9224180dcb9e6b57c021f83b259316e84ebc573e/lib/tty.js#L142-L151 |
|
53,843 | cahilfoley/snowfall | lib/utils.js | random | function random(min, max) {
var randomNumber = Math.random() * (max - min + 1) + min;
if (!Number.isInteger(min) || !Number.isInteger(max)) {
return randomNumber;
} else {
return Math.floor(randomNumber);
}
} | javascript | function random(min, max) {
var randomNumber = Math.random() * (max - min + 1) + min;
if (!Number.isInteger(min) || !Number.isInteger(max)) {
return randomNumber;
} else {
return Math.floor(randomNumber);
}
} | [
"function",
"random",
"(",
"min",
",",
"max",
")",
"{",
"var",
"randomNumber",
"=",
"Math",
".",
"random",
"(",
")",
"*",
"(",
"max",
"-",
"min",
"+",
"1",
")",
"+",
"min",
";",
"if",
"(",
"!",
"Number",
".",
"isInteger",
"(",
"min",
")",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"max",
")",
")",
"{",
"return",
"randomNumber",
";",
"}",
"else",
"{",
"return",
"Math",
".",
"floor",
"(",
"randomNumber",
")",
";",
"}",
"}"
] | Enhanced random function, selects a random value between a minimum and maximum. If the values provided are both
integers then the number returned will be an integer, otherwise the return number will be a decimal.
@param min The minimum value
@param max The maximum value | [
"Enhanced",
"random",
"function",
"selects",
"a",
"random",
"value",
"between",
"a",
"minimum",
"and",
"maximum",
".",
"If",
"the",
"values",
"provided",
"are",
"both",
"integers",
"then",
"the",
"number",
"returned",
"will",
"be",
"an",
"integer",
"otherwise",
"the",
"return",
"number",
"will",
"be",
"a",
"decimal",
"."
] | d16b7e913ffb9999521fbfc4054e7b6154712711 | https://github.com/cahilfoley/snowfall/blob/d16b7e913ffb9999521fbfc4054e7b6154712711/lib/utils.js#L15-L23 |
53,844 | mjhasbach/MS-Task | lib/ms-task.js | pidOf | function pidOf( procName, callback ){
if ( isString( procName )){
var pids = [];
procStat( procName, function( err, processes ){
processes.object.forEach( function( proc ){
pids.push( proc.pid )
});
callback( err, pids )
})
} else callback( new Error( 'A non-string process name was supplied' ), null, null )
} | javascript | function pidOf( procName, callback ){
if ( isString( procName )){
var pids = [];
procStat( procName, function( err, processes ){
processes.object.forEach( function( proc ){
pids.push( proc.pid )
});
callback( err, pids )
})
} else callback( new Error( 'A non-string process name was supplied' ), null, null )
} | [
"function",
"pidOf",
"(",
"procName",
",",
"callback",
")",
"{",
"if",
"(",
"isString",
"(",
"procName",
")",
")",
"{",
"var",
"pids",
"=",
"[",
"]",
";",
"procStat",
"(",
"procName",
",",
"function",
"(",
"err",
",",
"processes",
")",
"{",
"processes",
".",
"object",
".",
"forEach",
"(",
"function",
"(",
"proc",
")",
"{",
"pids",
".",
"push",
"(",
"proc",
".",
"pid",
")",
"}",
")",
";",
"callback",
"(",
"err",
",",
"pids",
")",
"}",
")",
"}",
"else",
"callback",
"(",
"new",
"Error",
"(",
"'A non-string process name was supplied'",
")",
",",
"null",
",",
"null",
")",
"}"
] | Search for one or more PIDs that match a give process name | [
"Search",
"for",
"one",
"or",
"more",
"PIDs",
"that",
"match",
"a",
"give",
"process",
"name"
] | f91fe301024a31d02a4c56f3886cc783fc5eda30 | https://github.com/mjhasbach/MS-Task/blob/f91fe301024a31d02a4c56f3886cc783fc5eda30/lib/ms-task.js#L17-L29 |
53,845 | mjhasbach/MS-Task | lib/ms-task.js | nameOf | function nameOf( pid, callback ){
if( isNumber( pid )){
procStat( pid, function( err, proc ){
callback( err, proc.object[ 0 ].name );
})
} else callback( new Error( 'A non-numeric PID was supplied' ), null )
} | javascript | function nameOf( pid, callback ){
if( isNumber( pid )){
procStat( pid, function( err, proc ){
callback( err, proc.object[ 0 ].name );
})
} else callback( new Error( 'A non-numeric PID was supplied' ), null )
} | [
"function",
"nameOf",
"(",
"pid",
",",
"callback",
")",
"{",
"if",
"(",
"isNumber",
"(",
"pid",
")",
")",
"{",
"procStat",
"(",
"pid",
",",
"function",
"(",
"err",
",",
"proc",
")",
"{",
"callback",
"(",
"err",
",",
"proc",
".",
"object",
"[",
"0",
"]",
".",
"name",
")",
";",
"}",
")",
"}",
"else",
"callback",
"(",
"new",
"Error",
"(",
"'A non-numeric PID was supplied'",
")",
",",
"null",
")",
"}"
] | Search for the process name that corresponds with the supplied PID | [
"Search",
"for",
"the",
"process",
"name",
"that",
"corresponds",
"with",
"the",
"supplied",
"PID"
] | f91fe301024a31d02a4c56f3886cc783fc5eda30 | https://github.com/mjhasbach/MS-Task/blob/f91fe301024a31d02a4c56f3886cc783fc5eda30/lib/ms-task.js#L32-L38 |
53,846 | mjhasbach/MS-Task | lib/ms-task.js | procStat | function procStat( proc, callback ){
var type = isNumber( proc ) ? 'PID' : 'IMAGENAME',
arg = '/fi \"' + type + ' eq ' + proc + '\" /fo CSV',
row = null,
processes = {
array: [],
object: []
};
taskList( arg, function( err, stdout ){
csv.parse( stdout, function( err, rows ){
if ( rows.length > 0 ){
for ( var i = 1; i < rows.length; i++ ){
row = rows[ i ];
processes.array.push( row );
processes.object.push({
name: row[ 0 ],
pid: row[ 1 ],
sessionName: row[ 2 ],
sessionNumber: row[ 3 ],
memUsage: row[ 4 ]
})
}
} else {
var noun = isNumber( proc ) ? 'PIDs' : 'process names';
err = new Error( 'There were no ' + noun + ' found when searching for \"' + proc + '\"' )
}
callback( err, processes )
})
})
} | javascript | function procStat( proc, callback ){
var type = isNumber( proc ) ? 'PID' : 'IMAGENAME',
arg = '/fi \"' + type + ' eq ' + proc + '\" /fo CSV',
row = null,
processes = {
array: [],
object: []
};
taskList( arg, function( err, stdout ){
csv.parse( stdout, function( err, rows ){
if ( rows.length > 0 ){
for ( var i = 1; i < rows.length; i++ ){
row = rows[ i ];
processes.array.push( row );
processes.object.push({
name: row[ 0 ],
pid: row[ 1 ],
sessionName: row[ 2 ],
sessionNumber: row[ 3 ],
memUsage: row[ 4 ]
})
}
} else {
var noun = isNumber( proc ) ? 'PIDs' : 'process names';
err = new Error( 'There were no ' + noun + ' found when searching for \"' + proc + '\"' )
}
callback( err, processes )
})
})
} | [
"function",
"procStat",
"(",
"proc",
",",
"callback",
")",
"{",
"var",
"type",
"=",
"isNumber",
"(",
"proc",
")",
"?",
"'PID'",
":",
"'IMAGENAME'",
",",
"arg",
"=",
"'/fi \\\"'",
"+",
"type",
"+",
"' eq '",
"+",
"proc",
"+",
"'\\\" /fo CSV'",
",",
"row",
"=",
"null",
",",
"processes",
"=",
"{",
"array",
":",
"[",
"]",
",",
"object",
":",
"[",
"]",
"}",
";",
"taskList",
"(",
"arg",
",",
"function",
"(",
"err",
",",
"stdout",
")",
"{",
"csv",
".",
"parse",
"(",
"stdout",
",",
"function",
"(",
"err",
",",
"rows",
")",
"{",
"if",
"(",
"rows",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"rows",
".",
"length",
";",
"i",
"++",
")",
"{",
"row",
"=",
"rows",
"[",
"i",
"]",
";",
"processes",
".",
"array",
".",
"push",
"(",
"row",
")",
";",
"processes",
".",
"object",
".",
"push",
"(",
"{",
"name",
":",
"row",
"[",
"0",
"]",
",",
"pid",
":",
"row",
"[",
"1",
"]",
",",
"sessionName",
":",
"row",
"[",
"2",
"]",
",",
"sessionNumber",
":",
"row",
"[",
"3",
"]",
",",
"memUsage",
":",
"row",
"[",
"4",
"]",
"}",
")",
"}",
"}",
"else",
"{",
"var",
"noun",
"=",
"isNumber",
"(",
"proc",
")",
"?",
"'PIDs'",
":",
"'process names'",
";",
"err",
"=",
"new",
"Error",
"(",
"'There were no '",
"+",
"noun",
"+",
"' found when searching for \\\"'",
"+",
"proc",
"+",
"'\\\"'",
")",
"}",
"callback",
"(",
"err",
",",
"processes",
")",
"}",
")",
"}",
")",
"}"
] | Search for a given process name or PID | [
"Search",
"for",
"a",
"given",
"process",
"name",
"or",
"PID"
] | f91fe301024a31d02a4c56f3886cc783fc5eda30 | https://github.com/mjhasbach/MS-Task/blob/f91fe301024a31d02a4c56f3886cc783fc5eda30/lib/ms-task.js#L41-L73 |
53,847 | mjhasbach/MS-Task | lib/ms-task.js | kill | function kill( proc, callback ){
var arg = isNumber( proc ) ? '/F /PID ' + proc : '/F /IM ' + proc;
if ( isNumber( proc ) || isString( proc )){
exec( taskKillPath + arg, function( err ){
if( callback ) callback( err )
})
} else {
callback( new Error( 'The first kill() argument provided is neither a string nor an integer (not a valid process).' ))
}
} | javascript | function kill( proc, callback ){
var arg = isNumber( proc ) ? '/F /PID ' + proc : '/F /IM ' + proc;
if ( isNumber( proc ) || isString( proc )){
exec( taskKillPath + arg, function( err ){
if( callback ) callback( err )
})
} else {
callback( new Error( 'The first kill() argument provided is neither a string nor an integer (not a valid process).' ))
}
} | [
"function",
"kill",
"(",
"proc",
",",
"callback",
")",
"{",
"var",
"arg",
"=",
"isNumber",
"(",
"proc",
")",
"?",
"'/F /PID '",
"+",
"proc",
":",
"'/F /IM '",
"+",
"proc",
";",
"if",
"(",
"isNumber",
"(",
"proc",
")",
"||",
"isString",
"(",
"proc",
")",
")",
"{",
"exec",
"(",
"taskKillPath",
"+",
"arg",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"err",
")",
"}",
")",
"}",
"else",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'The first kill() argument provided is neither a string nor an integer (not a valid process).'",
")",
")",
"}",
"}"
] | Kill a given process name or PID | [
"Kill",
"a",
"given",
"process",
"name",
"or",
"PID"
] | f91fe301024a31d02a4c56f3886cc783fc5eda30 | https://github.com/mjhasbach/MS-Task/blob/f91fe301024a31d02a4c56f3886cc783fc5eda30/lib/ms-task.js#L76-L86 |
53,848 | Everyplay/sear | lib/stringutils.js | escapeStringForJavascript | function escapeStringForJavascript(content) {
return content.replace(/(['\\])/g, '\\$1')
.replace(/[\f]/g, "\\f")
.replace(/[\b]/g, "\\b")
.replace(/[\n]/g, "\\n")
.replace(/[\t]/g, "\\t")
.replace(/[\r]/g, "\\r")
.replace(/[\u2028]/g, "\\u2028")
.replace(/[\u2029]/g, "\\u2029");
} | javascript | function escapeStringForJavascript(content) {
return content.replace(/(['\\])/g, '\\$1')
.replace(/[\f]/g, "\\f")
.replace(/[\b]/g, "\\b")
.replace(/[\n]/g, "\\n")
.replace(/[\t]/g, "\\t")
.replace(/[\r]/g, "\\r")
.replace(/[\u2028]/g, "\\u2028")
.replace(/[\u2029]/g, "\\u2029");
} | [
"function",
"escapeStringForJavascript",
"(",
"content",
")",
"{",
"return",
"content",
".",
"replace",
"(",
"/",
"(['\\\\])",
"/",
"g",
",",
"'\\\\$1'",
")",
".",
"replace",
"(",
"/",
"[\\f]",
"/",
"g",
",",
"\"\\\\f\"",
")",
".",
"replace",
"(",
"/",
"[\\b]",
"/",
"g",
",",
"\"\\\\b\"",
")",
".",
"replace",
"(",
"/",
"[\\n]",
"/",
"g",
",",
"\"\\\\n\"",
")",
".",
"replace",
"(",
"/",
"[\\t]",
"/",
"g",
",",
"\"\\\\t\"",
")",
".",
"replace",
"(",
"/",
"[\\r]",
"/",
"g",
",",
"\"\\\\r\"",
")",
".",
"replace",
"(",
"/",
"[\\u2028]",
"/",
"g",
",",
"\"\\\\u2028\"",
")",
".",
"replace",
"(",
"/",
"[\\u2029]",
"/",
"g",
",",
"\"\\\\u2029\"",
")",
";",
"}"
] | Escape string so it can be inlined in javascript
@param content {String} input to be escaped
@return {String} escaped string | [
"Escape",
"string",
"so",
"it",
"can",
"be",
"inlined",
"in",
"javascript"
] | b3ab97e8452b4df7caa72252559144812fbfef1c | https://github.com/Everyplay/sear/blob/b3ab97e8452b4df7caa72252559144812fbfef1c/lib/stringutils.js#L7-L16 |
53,849 | windmaomao/ng-admin-restify | src/provider.js | function(nga, options) {
// create an admin application
var app = ngAdmin.create(nga, options);
// app.dashboard(nga.dashboard().template('<dashboard-page></dashboard-page>'));
// create custom header
if (options.auth) {
app.header('<header-partial></header-partial>');
}
// attach the admin application to the DOM and run it
ngAdmin.attach(app);
return app;
} | javascript | function(nga, options) {
// create an admin application
var app = ngAdmin.create(nga, options);
// app.dashboard(nga.dashboard().template('<dashboard-page></dashboard-page>'));
// create custom header
if (options.auth) {
app.header('<header-partial></header-partial>');
}
// attach the admin application to the DOM and run it
ngAdmin.attach(app);
return app;
} | [
"function",
"(",
"nga",
",",
"options",
")",
"{",
"// create an admin application\r",
"var",
"app",
"=",
"ngAdmin",
".",
"create",
"(",
"nga",
",",
"options",
")",
";",
"// app.dashboard(nga.dashboard().template('<dashboard-page></dashboard-page>'));\r",
"// create custom header\r",
"if",
"(",
"options",
".",
"auth",
")",
"{",
"app",
".",
"header",
"(",
"'<header-partial></header-partial>'",
")",
";",
"}",
"// attach the admin application to the DOM and run it\r",
"ngAdmin",
".",
"attach",
"(",
"app",
")",
";",
"return",
"app",
";",
"}"
] | Given ng-admin provider and options Return an application instance | [
"Given",
"ng",
"-",
"admin",
"provider",
"and",
"options",
"Return",
"an",
"application",
"instance"
] | d86d8c12eb07e1b23def2f5de0832aa357c2a731 | https://github.com/windmaomao/ng-admin-restify/blob/d86d8c12eb07e1b23def2f5de0832aa357c2a731/src/provider.js#L18-L30 |
|
53,850 | NumminorihSF/bramqp-wrapper | domain/channel.js | Channel | function Channel(client, id){
EE.call(this);
this.client = client;
this.id = id;
this.opened = false;
this.confirmMode = false;
var work = (id, method, err) => {
this.opened = false;
var error = new RabbitClientError(err);
this.emit('close', error, this.id);
if (error) {
this.emit('error', error);
this.client.channel['close-ok'](this.id, (err) => {
if (err) this.emit('error', err);
});
}
};
var returning = (id, method, err) => {
var error = new RabbitRouteError(err);
this.emit('return', error, this.id);
if (error) {
this.emit('error', error);
}
};
this.client.once(this.id+':channel.close', work);
this.once('close', ()=>{
this.client.removeListener(this.id+':channel.close', work);
this.client.removeListener(this.id+':basic.return', returning);
});
this.client.on(this.id+':basic.return', returning);
} | javascript | function Channel(client, id){
EE.call(this);
this.client = client;
this.id = id;
this.opened = false;
this.confirmMode = false;
var work = (id, method, err) => {
this.opened = false;
var error = new RabbitClientError(err);
this.emit('close', error, this.id);
if (error) {
this.emit('error', error);
this.client.channel['close-ok'](this.id, (err) => {
if (err) this.emit('error', err);
});
}
};
var returning = (id, method, err) => {
var error = new RabbitRouteError(err);
this.emit('return', error, this.id);
if (error) {
this.emit('error', error);
}
};
this.client.once(this.id+':channel.close', work);
this.once('close', ()=>{
this.client.removeListener(this.id+':channel.close', work);
this.client.removeListener(this.id+':basic.return', returning);
});
this.client.on(this.id+':basic.return', returning);
} | [
"function",
"Channel",
"(",
"client",
",",
"id",
")",
"{",
"EE",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"client",
"=",
"client",
";",
"this",
".",
"id",
"=",
"id",
";",
"this",
".",
"opened",
"=",
"false",
";",
"this",
".",
"confirmMode",
"=",
"false",
";",
"var",
"work",
"=",
"(",
"id",
",",
"method",
",",
"err",
")",
"=>",
"{",
"this",
".",
"opened",
"=",
"false",
";",
"var",
"error",
"=",
"new",
"RabbitClientError",
"(",
"err",
")",
";",
"this",
".",
"emit",
"(",
"'close'",
",",
"error",
",",
"this",
".",
"id",
")",
";",
"if",
"(",
"error",
")",
"{",
"this",
".",
"emit",
"(",
"'error'",
",",
"error",
")",
";",
"this",
".",
"client",
".",
"channel",
"[",
"'close-ok'",
"]",
"(",
"this",
".",
"id",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"this",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"var",
"returning",
"=",
"(",
"id",
",",
"method",
",",
"err",
")",
"=>",
"{",
"var",
"error",
"=",
"new",
"RabbitRouteError",
"(",
"err",
")",
";",
"this",
".",
"emit",
"(",
"'return'",
",",
"error",
",",
"this",
".",
"id",
")",
";",
"if",
"(",
"error",
")",
"{",
"this",
".",
"emit",
"(",
"'error'",
",",
"error",
")",
";",
"}",
"}",
";",
"this",
".",
"client",
".",
"once",
"(",
"this",
".",
"id",
"+",
"':channel.close'",
",",
"work",
")",
";",
"this",
".",
"once",
"(",
"'close'",
",",
"(",
")",
"=>",
"{",
"this",
".",
"client",
".",
"removeListener",
"(",
"this",
".",
"id",
"+",
"':channel.close'",
",",
"work",
")",
";",
"this",
".",
"client",
".",
"removeListener",
"(",
"this",
".",
"id",
"+",
"':basic.return'",
",",
"returning",
")",
";",
"}",
")",
";",
"this",
".",
"client",
".",
"on",
"(",
"this",
".",
"id",
"+",
"':basic.return'",
",",
"returning",
")",
";",
"}"
] | Work with channels.
The channel class provides methods for a client to establish a channel to a server
and for both peers to operate the channel thereafter.
@class Channel
@extends EventEmitter
@param {BRAMQPClient} client Client object that returns from bramqp#openAMQPCommunication() method.
@param {Number} id Channel id.
@return {Channel}
@constructor | [
"Work",
"with",
"channels",
"."
] | 3e2bd769a2828f7592eba79556c9ef1491177781 | https://github.com/NumminorihSF/bramqp-wrapper/blob/3e2bd769a2828f7592eba79556c9ef1491177781/domain/channel.js#L18-L48 |
53,851 | linyngfly/omelo | lib/common/service/channelService.js | function(uid, sid, group) {
if(!uid || !sid || !group) {
return false;
}
for(let i=0, l=group.length; i<l; i++) {
if(group[i] === uid) {
group.splice(i, 1);
return true;
}
}
return false;
} | javascript | function(uid, sid, group) {
if(!uid || !sid || !group) {
return false;
}
for(let i=0, l=group.length; i<l; i++) {
if(group[i] === uid) {
group.splice(i, 1);
return true;
}
}
return false;
} | [
"function",
"(",
"uid",
",",
"sid",
",",
"group",
")",
"{",
"if",
"(",
"!",
"uid",
"||",
"!",
"sid",
"||",
"!",
"group",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"group",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"group",
"[",
"i",
"]",
"===",
"uid",
")",
"{",
"group",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | delete element from array | [
"delete",
"element",
"from",
"array"
] | fb5f79fa31c69de36bd1c370bad5edfa753ca601 | https://github.com/linyngfly/omelo/blob/fb5f79fa31c69de36bd1c370bad5edfa753ca601/lib/common/service/channelService.js#L359-L372 |
|
53,852 | linyngfly/omelo | lib/common/service/channelService.js | function(channelService, route, msg, groups, opts, cb) {
let app = channelService.app;
let namespace = 'sys';
let service = 'channelRemote';
let method = 'pushMessage';
let count = utils.size(groups);
let successFlag = false;
let failIds = [];
logger.debug('[%s] channelService sendMessageByGroup route: %s, msg: %j, groups: %j, opts: %j', app.serverId, route, msg, groups, opts);
if(count === 0) {
// group is empty
utils.invokeCallback(cb);
return;
}
let latch = countDownLatch.createCountDownLatch(count, function() {
if(!successFlag) {
utils.invokeCallback(cb, new Error('all uids push message fail'));
return;
}
utils.invokeCallback(cb, null, failIds);
});
let rpcCB = function(serverId) {
return function(err, fails) {
if(err) {
logger.error('[pushMessage] fail to dispatch msg to serverId: ' + serverId + ', err:' + err.stack);
latch.done();
return;
}
if(fails) {
failIds = failIds.concat(fails);
}
successFlag = true;
latch.done();
};
};
opts = {type: 'push', userOptions: opts || {}};
// for compatiblity
opts.isPush = true;
let sendMessage = function(sid) {
return (function() {
if(sid === app.serverId) {
channelService.channelRemote[method](route, msg, groups[sid], opts, rpcCB(sid));
} else {
app.rpcInvoke(sid, {namespace: namespace, service: service,
method: method, args: [route, msg, groups[sid], opts]}, rpcCB(sid));
}
})();
};
let group;
for(let sid in groups) {
group = groups[sid];
if(group && group.length > 0) {
sendMessage(sid);
} else {
// empty group
process.nextTick(rpcCB(sid));
}
}
} | javascript | function(channelService, route, msg, groups, opts, cb) {
let app = channelService.app;
let namespace = 'sys';
let service = 'channelRemote';
let method = 'pushMessage';
let count = utils.size(groups);
let successFlag = false;
let failIds = [];
logger.debug('[%s] channelService sendMessageByGroup route: %s, msg: %j, groups: %j, opts: %j', app.serverId, route, msg, groups, opts);
if(count === 0) {
// group is empty
utils.invokeCallback(cb);
return;
}
let latch = countDownLatch.createCountDownLatch(count, function() {
if(!successFlag) {
utils.invokeCallback(cb, new Error('all uids push message fail'));
return;
}
utils.invokeCallback(cb, null, failIds);
});
let rpcCB = function(serverId) {
return function(err, fails) {
if(err) {
logger.error('[pushMessage] fail to dispatch msg to serverId: ' + serverId + ', err:' + err.stack);
latch.done();
return;
}
if(fails) {
failIds = failIds.concat(fails);
}
successFlag = true;
latch.done();
};
};
opts = {type: 'push', userOptions: opts || {}};
// for compatiblity
opts.isPush = true;
let sendMessage = function(sid) {
return (function() {
if(sid === app.serverId) {
channelService.channelRemote[method](route, msg, groups[sid], opts, rpcCB(sid));
} else {
app.rpcInvoke(sid, {namespace: namespace, service: service,
method: method, args: [route, msg, groups[sid], opts]}, rpcCB(sid));
}
})();
};
let group;
for(let sid in groups) {
group = groups[sid];
if(group && group.length > 0) {
sendMessage(sid);
} else {
// empty group
process.nextTick(rpcCB(sid));
}
}
} | [
"function",
"(",
"channelService",
",",
"route",
",",
"msg",
",",
"groups",
",",
"opts",
",",
"cb",
")",
"{",
"let",
"app",
"=",
"channelService",
".",
"app",
";",
"let",
"namespace",
"=",
"'sys'",
";",
"let",
"service",
"=",
"'channelRemote'",
";",
"let",
"method",
"=",
"'pushMessage'",
";",
"let",
"count",
"=",
"utils",
".",
"size",
"(",
"groups",
")",
";",
"let",
"successFlag",
"=",
"false",
";",
"let",
"failIds",
"=",
"[",
"]",
";",
"logger",
".",
"debug",
"(",
"'[%s] channelService sendMessageByGroup route: %s, msg: %j, groups: %j, opts: %j'",
",",
"app",
".",
"serverId",
",",
"route",
",",
"msg",
",",
"groups",
",",
"opts",
")",
";",
"if",
"(",
"count",
"===",
"0",
")",
"{",
"// group is empty",
"utils",
".",
"invokeCallback",
"(",
"cb",
")",
";",
"return",
";",
"}",
"let",
"latch",
"=",
"countDownLatch",
".",
"createCountDownLatch",
"(",
"count",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"successFlag",
")",
"{",
"utils",
".",
"invokeCallback",
"(",
"cb",
",",
"new",
"Error",
"(",
"'all uids push message fail'",
")",
")",
";",
"return",
";",
"}",
"utils",
".",
"invokeCallback",
"(",
"cb",
",",
"null",
",",
"failIds",
")",
";",
"}",
")",
";",
"let",
"rpcCB",
"=",
"function",
"(",
"serverId",
")",
"{",
"return",
"function",
"(",
"err",
",",
"fails",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"'[pushMessage] fail to dispatch msg to serverId: '",
"+",
"serverId",
"+",
"', err:'",
"+",
"err",
".",
"stack",
")",
";",
"latch",
".",
"done",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"fails",
")",
"{",
"failIds",
"=",
"failIds",
".",
"concat",
"(",
"fails",
")",
";",
"}",
"successFlag",
"=",
"true",
";",
"latch",
".",
"done",
"(",
")",
";",
"}",
";",
"}",
";",
"opts",
"=",
"{",
"type",
":",
"'push'",
",",
"userOptions",
":",
"opts",
"||",
"{",
"}",
"}",
";",
"// for compatiblity",
"opts",
".",
"isPush",
"=",
"true",
";",
"let",
"sendMessage",
"=",
"function",
"(",
"sid",
")",
"{",
"return",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"sid",
"===",
"app",
".",
"serverId",
")",
"{",
"channelService",
".",
"channelRemote",
"[",
"method",
"]",
"(",
"route",
",",
"msg",
",",
"groups",
"[",
"sid",
"]",
",",
"opts",
",",
"rpcCB",
"(",
"sid",
")",
")",
";",
"}",
"else",
"{",
"app",
".",
"rpcInvoke",
"(",
"sid",
",",
"{",
"namespace",
":",
"namespace",
",",
"service",
":",
"service",
",",
"method",
":",
"method",
",",
"args",
":",
"[",
"route",
",",
"msg",
",",
"groups",
"[",
"sid",
"]",
",",
"opts",
"]",
"}",
",",
"rpcCB",
"(",
"sid",
")",
")",
";",
"}",
"}",
")",
"(",
")",
";",
"}",
";",
"let",
"group",
";",
"for",
"(",
"let",
"sid",
"in",
"groups",
")",
"{",
"group",
"=",
"groups",
"[",
"sid",
"]",
";",
"if",
"(",
"group",
"&&",
"group",
".",
"length",
">",
"0",
")",
"{",
"sendMessage",
"(",
"sid",
")",
";",
"}",
"else",
"{",
"// empty group",
"process",
".",
"nextTick",
"(",
"rpcCB",
"(",
"sid",
")",
")",
";",
"}",
"}",
"}"
] | push message by group
@param route {String} route route message
@param msg {Object} message that would be sent to client
@param groups {Object} grouped uids, , key: sid, value: [uid]
@param opts {Object} push options
@param cb {Function} cb(err)
@api private | [
"push",
"message",
"by",
"group"
] | fb5f79fa31c69de36bd1c370bad5edfa753ca601 | https://github.com/linyngfly/omelo/blob/fb5f79fa31c69de36bd1c370bad5edfa753ca601/lib/common/service/channelService.js#L385-L449 |
|
53,853 | yeptlabs/wns | src/core/base/wnConsole.js | function () {
process.stdin.resume();
process.stdin.setEncoding('utf8');
_execCtx = [self];
process.stdin.on('data', function (chunk) {
var ctx = _execCtx[0],
cmd = chunk.substr(0,chunk.length-1);
if (cmd.substr(0,2) == '..')
{
cmd = 'if (_execCtx.length>1) _execCtx.shift(); undefined;'
} else if (cmd.substr(0,1) == ':')
{
cmd = 'var newCtx = '+cmd.substr(1)+'; _execCtx.unshift(newCtx); undefined;';
} else if (cmd.substr(0,1) == '/')
{
cmd = '';
_execCtx = [self];
}
self.exec(cmd,ctx?ctx:undefined);
return false;
});
} | javascript | function () {
process.stdin.resume();
process.stdin.setEncoding('utf8');
_execCtx = [self];
process.stdin.on('data', function (chunk) {
var ctx = _execCtx[0],
cmd = chunk.substr(0,chunk.length-1);
if (cmd.substr(0,2) == '..')
{
cmd = 'if (_execCtx.length>1) _execCtx.shift(); undefined;'
} else if (cmd.substr(0,1) == ':')
{
cmd = 'var newCtx = '+cmd.substr(1)+'; _execCtx.unshift(newCtx); undefined;';
} else if (cmd.substr(0,1) == '/')
{
cmd = '';
_execCtx = [self];
}
self.exec(cmd,ctx?ctx:undefined);
return false;
});
} | [
"function",
"(",
")",
"{",
"process",
".",
"stdin",
".",
"resume",
"(",
")",
";",
"process",
".",
"stdin",
".",
"setEncoding",
"(",
"'utf8'",
")",
";",
"_execCtx",
"=",
"[",
"self",
"]",
";",
"process",
".",
"stdin",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"var",
"ctx",
"=",
"_execCtx",
"[",
"0",
"]",
",",
"cmd",
"=",
"chunk",
".",
"substr",
"(",
"0",
",",
"chunk",
".",
"length",
"-",
"1",
")",
";",
"if",
"(",
"cmd",
".",
"substr",
"(",
"0",
",",
"2",
")",
"==",
"'..'",
")",
"{",
"cmd",
"=",
"'if (_execCtx.length>1) _execCtx.shift(); undefined;'",
"}",
"else",
"if",
"(",
"cmd",
".",
"substr",
"(",
"0",
",",
"1",
")",
"==",
"':'",
")",
"{",
"cmd",
"=",
"'var newCtx = '",
"+",
"cmd",
".",
"substr",
"(",
"1",
")",
"+",
"'; _execCtx.unshift(newCtx); undefined;'",
";",
"}",
"else",
"if",
"(",
"cmd",
".",
"substr",
"(",
"0",
",",
"1",
")",
"==",
"'/'",
")",
"{",
"cmd",
"=",
"''",
";",
"_execCtx",
"=",
"[",
"self",
"]",
";",
"}",
"self",
".",
"exec",
"(",
"cmd",
",",
"ctx",
"?",
"ctx",
":",
"undefined",
")",
";",
"return",
"false",
";",
"}",
")",
";",
"}"
] | Listen to the console input | [
"Listen",
"to",
"the",
"console",
"input"
] | c42602b062dcf6bbffc22e4365bba2cbf363fe2f | https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnConsole.js#L77-L100 |
|
53,854 | yeptlabs/wns | src/core/base/wnConsole.js | function (serverPath)
{
if (!_.isString(serverPath))
return false;
var _sourcePath = cwd+sourcePath,
relativeSourcePath = path.relative(serverPath,_sourcePath)+'/',
relativeServerPath = path.relative(cwd,serverPath);
self.e.log("[*] Building new wnServer on `"+serverPath+"`");
if (!fs.existsSync(serverPath))
fs.mkdirSync(serverPath);
self.e.log("[*] - Creating new `package.js` file.");
var defaultPackage = fs.readFileSync(_sourcePath+'/default-package.json').toString('utf8');
defaultPackage = (defaultPackage+'').replace(/\{moduleName\}/g, 'server-'+serverPath.substr(0,serverPath.length-1).split('/').pop().replace(/\s/g,'-'));
fs.writeFileSync(serverPath+'/package.json',defaultPackage);
self.e.log("[*] - Creating new `config.json` file.");
fs.writeFileSync(serverPath+'/config.json',
fs.readFileSync(_sourcePath+'/default-config.json')
);
self.e.log("[*] - Creating new `index.js` file.");
var defaultIndex = fs.readFileSync(_sourcePath+'/default-index.js').toString('utf8');
defaultIndex = defaultIndex.replace(/\{sourcePath\}/g,'./'+relativeSourcePath.replace(/\\/g,'/'));
defaultIndex = defaultIndex.replace(/\{serverPath\}/g,'./'+relativeServerPath.replace(/\\/g,'/'));
fs.writeFileSync(serverPath+'/index.js',defaultIndex);
self.e.log('[*] New wnServer created.');
return true;
} | javascript | function (serverPath)
{
if (!_.isString(serverPath))
return false;
var _sourcePath = cwd+sourcePath,
relativeSourcePath = path.relative(serverPath,_sourcePath)+'/',
relativeServerPath = path.relative(cwd,serverPath);
self.e.log("[*] Building new wnServer on `"+serverPath+"`");
if (!fs.existsSync(serverPath))
fs.mkdirSync(serverPath);
self.e.log("[*] - Creating new `package.js` file.");
var defaultPackage = fs.readFileSync(_sourcePath+'/default-package.json').toString('utf8');
defaultPackage = (defaultPackage+'').replace(/\{moduleName\}/g, 'server-'+serverPath.substr(0,serverPath.length-1).split('/').pop().replace(/\s/g,'-'));
fs.writeFileSync(serverPath+'/package.json',defaultPackage);
self.e.log("[*] - Creating new `config.json` file.");
fs.writeFileSync(serverPath+'/config.json',
fs.readFileSync(_sourcePath+'/default-config.json')
);
self.e.log("[*] - Creating new `index.js` file.");
var defaultIndex = fs.readFileSync(_sourcePath+'/default-index.js').toString('utf8');
defaultIndex = defaultIndex.replace(/\{sourcePath\}/g,'./'+relativeSourcePath.replace(/\\/g,'/'));
defaultIndex = defaultIndex.replace(/\{serverPath\}/g,'./'+relativeServerPath.replace(/\\/g,'/'));
fs.writeFileSync(serverPath+'/index.js',defaultIndex);
self.e.log('[*] New wnServer created.');
return true;
} | [
"function",
"(",
"serverPath",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"serverPath",
")",
")",
"return",
"false",
";",
"var",
"_sourcePath",
"=",
"cwd",
"+",
"sourcePath",
",",
"relativeSourcePath",
"=",
"path",
".",
"relative",
"(",
"serverPath",
",",
"_sourcePath",
")",
"+",
"'/'",
",",
"relativeServerPath",
"=",
"path",
".",
"relative",
"(",
"cwd",
",",
"serverPath",
")",
";",
"self",
".",
"e",
".",
"log",
"(",
"\"[*] Building new wnServer on `\"",
"+",
"serverPath",
"+",
"\"`\"",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"serverPath",
")",
")",
"fs",
".",
"mkdirSync",
"(",
"serverPath",
")",
";",
"self",
".",
"e",
".",
"log",
"(",
"\"[*] - Creating new `package.js` file.\"",
")",
";",
"var",
"defaultPackage",
"=",
"fs",
".",
"readFileSync",
"(",
"_sourcePath",
"+",
"'/default-package.json'",
")",
".",
"toString",
"(",
"'utf8'",
")",
";",
"defaultPackage",
"=",
"(",
"defaultPackage",
"+",
"''",
")",
".",
"replace",
"(",
"/",
"\\{moduleName\\}",
"/",
"g",
",",
"'server-'",
"+",
"serverPath",
".",
"substr",
"(",
"0",
",",
"serverPath",
".",
"length",
"-",
"1",
")",
".",
"split",
"(",
"'/'",
")",
".",
"pop",
"(",
")",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"'-'",
")",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"serverPath",
"+",
"'/package.json'",
",",
"defaultPackage",
")",
";",
"self",
".",
"e",
".",
"log",
"(",
"\"[*] - Creating new `config.json` file.\"",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"serverPath",
"+",
"'/config.json'",
",",
"fs",
".",
"readFileSync",
"(",
"_sourcePath",
"+",
"'/default-config.json'",
")",
")",
";",
"self",
".",
"e",
".",
"log",
"(",
"\"[*] - Creating new `index.js` file.\"",
")",
";",
"var",
"defaultIndex",
"=",
"fs",
".",
"readFileSync",
"(",
"_sourcePath",
"+",
"'/default-index.js'",
")",
".",
"toString",
"(",
"'utf8'",
")",
";",
"defaultIndex",
"=",
"defaultIndex",
".",
"replace",
"(",
"/",
"\\{sourcePath\\}",
"/",
"g",
",",
"'./'",
"+",
"relativeSourcePath",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
")",
";",
"defaultIndex",
"=",
"defaultIndex",
".",
"replace",
"(",
"/",
"\\{serverPath\\}",
"/",
"g",
",",
"'./'",
"+",
"relativeServerPath",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"serverPath",
"+",
"'/index.js'",
",",
"defaultIndex",
")",
";",
"self",
".",
"e",
".",
"log",
"(",
"'[*] New wnServer created.'",
")",
";",
"return",
"true",
";",
"}"
] | Build a new server structure on the given directory
@param string $serverPath directory of the new server
@return boolean successfully builded? | [
"Build",
"a",
"new",
"server",
"structure",
"on",
"the",
"given",
"directory"
] | c42602b062dcf6bbffc22e4365bba2cbf363fe2f | https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnConsole.js#L107-L140 |
|
53,855 | yeptlabs/wns | src/core/base/wnConsole.js | function (servers)
{
if (!_.isObject(servers))
return false;
var modules = {};
for (s in servers)
{
var ref=servers[s],
s = 'server-'+s;
modules[s]=ref;
modules[s].modulePath=(modules[s].serverPath || modules[s].modulePath);
modules[s].class='wnServer';
modules[s].autoInit = false;
}
this.setModules(modules);
} | javascript | function (servers)
{
if (!_.isObject(servers))
return false;
var modules = {};
for (s in servers)
{
var ref=servers[s],
s = 'server-'+s;
modules[s]=ref;
modules[s].modulePath=(modules[s].serverPath || modules[s].modulePath);
modules[s].class='wnServer';
modules[s].autoInit = false;
}
this.setModules(modules);
} | [
"function",
"(",
"servers",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"servers",
")",
")",
"return",
"false",
";",
"var",
"modules",
"=",
"{",
"}",
";",
"for",
"(",
"s",
"in",
"servers",
")",
"{",
"var",
"ref",
"=",
"servers",
"[",
"s",
"]",
",",
"s",
"=",
"'server-'",
"+",
"s",
";",
"modules",
"[",
"s",
"]",
"=",
"ref",
";",
"modules",
"[",
"s",
"]",
".",
"modulePath",
"=",
"(",
"modules",
"[",
"s",
"]",
".",
"serverPath",
"||",
"modules",
"[",
"s",
"]",
".",
"modulePath",
")",
";",
"modules",
"[",
"s",
"]",
".",
"class",
"=",
"'wnServer'",
";",
"modules",
"[",
"s",
"]",
".",
"autoInit",
"=",
"false",
";",
"}",
"this",
".",
"setModules",
"(",
"modules",
")",
";",
"}"
] | Set new properties to the respective servers
@param object $servers servers configurations | [
"Set",
"new",
"properties",
"to",
"the",
"respective",
"servers"
] | c42602b062dcf6bbffc22e4365bba2cbf363fe2f | https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnConsole.js#L146-L162 |
|
53,856 | yeptlabs/wns | src/core/base/wnConsole.js | function (id)
{
var m = this.getModule('server-'+id, function (server) {
self.e.loadServer(server);
});
_serverModules.push(m);
return m;
} | javascript | function (id)
{
var m = this.getModule('server-'+id, function (server) {
self.e.loadServer(server);
});
_serverModules.push(m);
return m;
} | [
"function",
"(",
"id",
")",
"{",
"var",
"m",
"=",
"this",
".",
"getModule",
"(",
"'server-'",
"+",
"id",
",",
"function",
"(",
"server",
")",
"{",
"self",
".",
"e",
".",
"loadServer",
"(",
"server",
")",
";",
"}",
")",
";",
"_serverModules",
".",
"push",
"(",
"m",
")",
";",
"return",
"m",
";",
"}"
] | Create a new instance of server.
@param STRING $id server ID
@return wnModule the module instance, false if the module is disabled or does not exist. | [
"Create",
"a",
"new",
"instance",
"of",
"server",
"."
] | c42602b062dcf6bbffc22e4365bba2cbf363fe2f | https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnConsole.js#L199-L206 |
|
53,857 | yeptlabs/wns | src/core/base/wnConsole.js | function (serverPath,relativeMainPath)
{
if (relativeMainPath)
serverPath = path.relative(cwd,path.resolve(mainPath,serverPath));
var serverConfig = {},
consoleID = this.getServerModules().length+1;
serverConfig[consoleID] = { 'modulePath': serverPath, 'serverID': consoleID };
this.e.log('[*] Building wnServer from `'+serverPath+'`');
if (!fs.existsSync(this.modulePath+serverPath))
{
this.e.log('[*] Failed to load wnServer from path.');
return false;
}
this.setServers(serverConfig);
var server = this.createServer(consoleID);
this.selectServer(consoleID);
return server;
} | javascript | function (serverPath,relativeMainPath)
{
if (relativeMainPath)
serverPath = path.relative(cwd,path.resolve(mainPath,serverPath));
var serverConfig = {},
consoleID = this.getServerModules().length+1;
serverConfig[consoleID] = { 'modulePath': serverPath, 'serverID': consoleID };
this.e.log('[*] Building wnServer from `'+serverPath+'`');
if (!fs.existsSync(this.modulePath+serverPath))
{
this.e.log('[*] Failed to load wnServer from path.');
return false;
}
this.setServers(serverConfig);
var server = this.createServer(consoleID);
this.selectServer(consoleID);
return server;
} | [
"function",
"(",
"serverPath",
",",
"relativeMainPath",
")",
"{",
"if",
"(",
"relativeMainPath",
")",
"serverPath",
"=",
"path",
".",
"relative",
"(",
"cwd",
",",
"path",
".",
"resolve",
"(",
"mainPath",
",",
"serverPath",
")",
")",
";",
"var",
"serverConfig",
"=",
"{",
"}",
",",
"consoleID",
"=",
"this",
".",
"getServerModules",
"(",
")",
".",
"length",
"+",
"1",
";",
"serverConfig",
"[",
"consoleID",
"]",
"=",
"{",
"'modulePath'",
":",
"serverPath",
",",
"'serverID'",
":",
"consoleID",
"}",
";",
"this",
".",
"e",
".",
"log",
"(",
"'[*] Building wnServer from `'",
"+",
"serverPath",
"+",
"'`'",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"this",
".",
"modulePath",
"+",
"serverPath",
")",
")",
"{",
"this",
".",
"e",
".",
"log",
"(",
"'[*] Failed to load wnServer from path.'",
")",
";",
"return",
"false",
";",
"}",
"this",
".",
"setServers",
"(",
"serverConfig",
")",
";",
"var",
"server",
"=",
"this",
".",
"createServer",
"(",
"consoleID",
")",
";",
"this",
".",
"selectServer",
"(",
"consoleID",
")",
";",
"return",
"server",
";",
"}"
] | Create a new wnServer and puts under the management of this console
@param $serverPath server module path
@param $relativeMainPath boolean relative to mainPath | [
"Create",
"a",
"new",
"wnServer",
"and",
"puts",
"under",
"the",
"management",
"of",
"this",
"console"
] | c42602b062dcf6bbffc22e4365bba2cbf363fe2f | https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnConsole.js#L239-L262 |
|
53,858 | yeptlabs/wns | src/core/base/wnConsole.js | function (id)
{
if (this.hasServer(id))
{
this.e.log('[*] Console active in SERVER#' + id);
this.activeServer = id;
} else {
this.e.log('[*] Console active in NONE');
this.activeServer = -1;
}
} | javascript | function (id)
{
if (this.hasServer(id))
{
this.e.log('[*] Console active in SERVER#' + id);
this.activeServer = id;
} else {
this.e.log('[*] Console active in NONE');
this.activeServer = -1;
}
} | [
"function",
"(",
"id",
")",
"{",
"if",
"(",
"this",
".",
"hasServer",
"(",
"id",
")",
")",
"{",
"this",
".",
"e",
".",
"log",
"(",
"'[*] Console active in SERVER#'",
"+",
"id",
")",
";",
"this",
".",
"activeServer",
"=",
"id",
";",
"}",
"else",
"{",
"this",
".",
"e",
".",
"log",
"(",
"'[*] Console active in NONE'",
")",
";",
"this",
".",
"activeServer",
"=",
"-",
"1",
";",
"}",
"}"
] | Define the server as the active on the console.
@param $server wnServer instance | [
"Define",
"the",
"server",
"as",
"the",
"active",
"on",
"the",
"console",
"."
] | c42602b062dcf6bbffc22e4365bba2cbf363fe2f | https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnConsole.js#L268-L278 |
|
53,859 | linyngfly/omelo | lib/components/session.js | function(app, opts) {
opts = opts || {};
this.app = app;
this.service = new SessionService(opts);
let getFun = function(m) {
return (function() {
return function() {
return self.service[m].apply(self.service, arguments);
};
})();
};
// proxy the service methods except the lifecycle interfaces of component
let method, self = this;
for(let m in this.service) {
if(m !== 'start' && m !== 'stop') {
method = this.service[m];
if(typeof method === 'function') {
this[m] = getFun(m);
}
}
}
} | javascript | function(app, opts) {
opts = opts || {};
this.app = app;
this.service = new SessionService(opts);
let getFun = function(m) {
return (function() {
return function() {
return self.service[m].apply(self.service, arguments);
};
})();
};
// proxy the service methods except the lifecycle interfaces of component
let method, self = this;
for(let m in this.service) {
if(m !== 'start' && m !== 'stop') {
method = this.service[m];
if(typeof method === 'function') {
this[m] = getFun(m);
}
}
}
} | [
"function",
"(",
"app",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"app",
"=",
"app",
";",
"this",
".",
"service",
"=",
"new",
"SessionService",
"(",
"opts",
")",
";",
"let",
"getFun",
"=",
"function",
"(",
"m",
")",
"{",
"return",
"(",
"function",
"(",
")",
"{",
"return",
"function",
"(",
")",
"{",
"return",
"self",
".",
"service",
"[",
"m",
"]",
".",
"apply",
"(",
"self",
".",
"service",
",",
"arguments",
")",
";",
"}",
";",
"}",
")",
"(",
")",
";",
"}",
";",
"// proxy the service methods except the lifecycle interfaces of component",
"let",
"method",
",",
"self",
"=",
"this",
";",
"for",
"(",
"let",
"m",
"in",
"this",
".",
"service",
")",
"{",
"if",
"(",
"m",
"!==",
"'start'",
"&&",
"m",
"!==",
"'stop'",
")",
"{",
"method",
"=",
"this",
".",
"service",
"[",
"m",
"]",
";",
"if",
"(",
"typeof",
"method",
"===",
"'function'",
")",
"{",
"this",
"[",
"m",
"]",
"=",
"getFun",
"(",
"m",
")",
";",
"}",
"}",
"}",
"}"
] | Session component. Manage sessions.
@param {Object} app current application context
@param {Object} opts attach parameters | [
"Session",
"component",
".",
"Manage",
"sessions",
"."
] | fb5f79fa31c69de36bd1c370bad5edfa753ca601 | https://github.com/linyngfly/omelo/blob/fb5f79fa31c69de36bd1c370bad5edfa753ca601/lib/components/session.js#L15-L37 |
|
53,860 | iolo/express-toybox | logger.js | logger | function logger(options) {
DEBUG && debug('configure http logger middleware', options);
var format;
if (typeof options === 'string') {
format = options;
options = {};
} else {
format = options.format || 'combined';
delete options.format;
}
if (options.debug) {
try {
return require('morgan-debug')(options.debug, format, options);
} catch (e) {
console.error('**fatal** failed to configure logger with debug', e);
return process.exit(2);
}
}
if (options.file) {
try {
var file = path.resolve(process.cwd(), options.file);
// replace stream options with stream object
delete options.file;
options.stream = require('fs').createWriteStream(file, {flags: 'a'});
} catch (e) {
console.error('**fatal** failed to configure logger with file stream', e);
return process.exit(2);
}
}
console.warn('**fallback** use default logger middleware');
return require('morgan')(format, options);
} | javascript | function logger(options) {
DEBUG && debug('configure http logger middleware', options);
var format;
if (typeof options === 'string') {
format = options;
options = {};
} else {
format = options.format || 'combined';
delete options.format;
}
if (options.debug) {
try {
return require('morgan-debug')(options.debug, format, options);
} catch (e) {
console.error('**fatal** failed to configure logger with debug', e);
return process.exit(2);
}
}
if (options.file) {
try {
var file = path.resolve(process.cwd(), options.file);
// replace stream options with stream object
delete options.file;
options.stream = require('fs').createWriteStream(file, {flags: 'a'});
} catch (e) {
console.error('**fatal** failed to configure logger with file stream', e);
return process.exit(2);
}
}
console.warn('**fallback** use default logger middleware');
return require('morgan')(format, options);
} | [
"function",
"logger",
"(",
"options",
")",
"{",
"DEBUG",
"&&",
"debug",
"(",
"'configure http logger middleware'",
",",
"options",
")",
";",
"var",
"format",
";",
"if",
"(",
"typeof",
"options",
"===",
"'string'",
")",
"{",
"format",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"format",
"=",
"options",
".",
"format",
"||",
"'combined'",
";",
"delete",
"options",
".",
"format",
";",
"}",
"if",
"(",
"options",
".",
"debug",
")",
"{",
"try",
"{",
"return",
"require",
"(",
"'morgan-debug'",
")",
"(",
"options",
".",
"debug",
",",
"format",
",",
"options",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"'**fatal** failed to configure logger with debug'",
",",
"e",
")",
";",
"return",
"process",
".",
"exit",
"(",
"2",
")",
";",
"}",
"}",
"if",
"(",
"options",
".",
"file",
")",
"{",
"try",
"{",
"var",
"file",
"=",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"options",
".",
"file",
")",
";",
"// replace stream options with stream object",
"delete",
"options",
".",
"file",
";",
"options",
".",
"stream",
"=",
"require",
"(",
"'fs'",
")",
".",
"createWriteStream",
"(",
"file",
",",
"{",
"flags",
":",
"'a'",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"'**fatal** failed to configure logger with file stream'",
",",
"e",
")",
";",
"return",
"process",
".",
"exit",
"(",
"2",
")",
";",
"}",
"}",
"console",
".",
"warn",
"(",
"'**fallback** use default logger middleware'",
")",
";",
"return",
"require",
"(",
"'morgan'",
")",
"(",
"format",
",",
"options",
")",
";",
"}"
] | logger middleware using "morgan" or "debug".
@param {*|String} options or log format.
@param {Number|Boolean} [options.buffer]
@param {Boolean} [options.immediate]
@param {Function} [options.skip]
@param {*} [options.stream]
@param {String} [options.format='combined'] log format. "combined", "common", "dev", "short", "tiny" or "default".
@param {String} [options.file] file to emit log.
@param {String} [options.debug] namespace for tj's debug namespace to emit log.
@returns {Function} connect/express middleware function | [
"logger",
"middleware",
"using",
"morgan",
"or",
"debug",
"."
] | c375a1388cfc167017e8dcd2325e71ca86ccb994 | https://github.com/iolo/express-toybox/blob/c375a1388cfc167017e8dcd2325e71ca86ccb994/logger.js#L24-L55 |
53,861 | gretro/robs-fetch | samples/simple-example/src/store/reducer.js | handlePeopleRetrieved | function handlePeopleRetrieved(state, action) {
if (action.error) {
return {
...state,
people: null,
error: getErrorDescription(action.payload)
};
}
return {
...state,
people: action.payload,
error: null
};
} | javascript | function handlePeopleRetrieved(state, action) {
if (action.error) {
return {
...state,
people: null,
error: getErrorDescription(action.payload)
};
}
return {
...state,
people: action.payload,
error: null
};
} | [
"function",
"handlePeopleRetrieved",
"(",
"state",
",",
"action",
")",
"{",
"if",
"(",
"action",
".",
"error",
")",
"{",
"return",
"{",
"...",
"state",
",",
"people",
":",
"null",
",",
"error",
":",
"getErrorDescription",
"(",
"action",
".",
"payload",
")",
"}",
";",
"}",
"return",
"{",
"...",
"state",
",",
"people",
":",
"action",
".",
"payload",
",",
"error",
":",
"null",
"}",
";",
"}"
] | Handling the response of the REST Action. | [
"Handling",
"the",
"response",
"of",
"the",
"REST",
"Action",
"."
] | 65178913bbfeea2c9bdd064c6afed6704c50f79a | https://github.com/gretro/robs-fetch/blob/65178913bbfeea2c9bdd064c6afed6704c50f79a/samples/simple-example/src/store/reducer.js#L18-L32 |
53,862 | francejs/karma-effroi | lib/effroi.js | function(element, options) {
var event;
options = options || {};
options.canBubble = ('false' === options.canBubble ? false : true);
options.cancelable = ('false' === options.cancelable ? false : true);
options.view = options.view || window;
try {
event = new Event(options.type, {
bubbles: options.canBubble,
cancelable: options.cancelable,
view: options.view,
relatedTarget: options.relatedTarget
});
return element.dispatchEvent(event);
} catch(e) {
try {
event = document.createEvent("Event");
event.initEvent(options.type,
options.canBubble, options.cancelable);
this.setEventProperty(event, 'relatedTarget', options.relatedTarget);
return element.dispatchEvent(event);
} catch(e) {
// old IE fallback
event = document.createEventObject();
event.eventType = options.type;
event.relatedTarget = options.relatedTarget;
return element.fireEvent('on'+options.type, event)
}
}
} | javascript | function(element, options) {
var event;
options = options || {};
options.canBubble = ('false' === options.canBubble ? false : true);
options.cancelable = ('false' === options.cancelable ? false : true);
options.view = options.view || window;
try {
event = new Event(options.type, {
bubbles: options.canBubble,
cancelable: options.cancelable,
view: options.view,
relatedTarget: options.relatedTarget
});
return element.dispatchEvent(event);
} catch(e) {
try {
event = document.createEvent("Event");
event.initEvent(options.type,
options.canBubble, options.cancelable);
this.setEventProperty(event, 'relatedTarget', options.relatedTarget);
return element.dispatchEvent(event);
} catch(e) {
// old IE fallback
event = document.createEventObject();
event.eventType = options.type;
event.relatedTarget = options.relatedTarget;
return element.fireEvent('on'+options.type, event)
}
}
} | [
"function",
"(",
"element",
",",
"options",
")",
"{",
"var",
"event",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"canBubble",
"=",
"(",
"'false'",
"===",
"options",
".",
"canBubble",
"?",
"false",
":",
"true",
")",
";",
"options",
".",
"cancelable",
"=",
"(",
"'false'",
"===",
"options",
".",
"cancelable",
"?",
"false",
":",
"true",
")",
";",
"options",
".",
"view",
"=",
"options",
".",
"view",
"||",
"window",
";",
"try",
"{",
"event",
"=",
"new",
"Event",
"(",
"options",
".",
"type",
",",
"{",
"bubbles",
":",
"options",
".",
"canBubble",
",",
"cancelable",
":",
"options",
".",
"cancelable",
",",
"view",
":",
"options",
".",
"view",
",",
"relatedTarget",
":",
"options",
".",
"relatedTarget",
"}",
")",
";",
"return",
"element",
".",
"dispatchEvent",
"(",
"event",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"try",
"{",
"event",
"=",
"document",
".",
"createEvent",
"(",
"\"Event\"",
")",
";",
"event",
".",
"initEvent",
"(",
"options",
".",
"type",
",",
"options",
".",
"canBubble",
",",
"options",
".",
"cancelable",
")",
";",
"this",
".",
"setEventProperty",
"(",
"event",
",",
"'relatedTarget'",
",",
"options",
".",
"relatedTarget",
")",
";",
"return",
"element",
".",
"dispatchEvent",
"(",
"event",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// old IE fallback",
"event",
"=",
"document",
".",
"createEventObject",
"(",
")",
";",
"event",
".",
"eventType",
"=",
"options",
".",
"type",
";",
"event",
".",
"relatedTarget",
"=",
"options",
".",
"relatedTarget",
";",
"return",
"element",
".",
"fireEvent",
"(",
"'on'",
"+",
"options",
".",
"type",
",",
"event",
")",
"}",
"}",
"}"
] | dispatch a simple event | [
"dispatch",
"a",
"simple",
"event"
] | 7a624211bfd51927618e12e56439924da741d3b1 | https://github.com/francejs/karma-effroi/blob/7a624211bfd51927618e12e56439924da741d3b1/lib/effroi.js#L1560-L1589 |
|
53,863 | magicdawn/impress-router-table | index.js | bind | function bind(method, path, controller, action) {
let handler = controllerRegistry[controller] && controllerRegistry[controller][action]
if (!handler) {
console.warn(`can't bind route ${ path } to unknown action ${ controller }.${ action }`)
return
}
const policyName = LocalUtil.getPolicyName(policy, controller, action)
let currentPolicy
if (policyName) currentPolicy = policyRegistry[policyName]
if (currentPolicy) {
router[method](path, currentPolicy, handler)
} else {
router[method](path, handler)
}
} | javascript | function bind(method, path, controller, action) {
let handler = controllerRegistry[controller] && controllerRegistry[controller][action]
if (!handler) {
console.warn(`can't bind route ${ path } to unknown action ${ controller }.${ action }`)
return
}
const policyName = LocalUtil.getPolicyName(policy, controller, action)
let currentPolicy
if (policyName) currentPolicy = policyRegistry[policyName]
if (currentPolicy) {
router[method](path, currentPolicy, handler)
} else {
router[method](path, handler)
}
} | [
"function",
"bind",
"(",
"method",
",",
"path",
",",
"controller",
",",
"action",
")",
"{",
"let",
"handler",
"=",
"controllerRegistry",
"[",
"controller",
"]",
"&&",
"controllerRegistry",
"[",
"controller",
"]",
"[",
"action",
"]",
"if",
"(",
"!",
"handler",
")",
"{",
"console",
".",
"warn",
"(",
"`",
"${",
"path",
"}",
"${",
"controller",
"}",
"${",
"action",
"}",
"`",
")",
"return",
"}",
"const",
"policyName",
"=",
"LocalUtil",
".",
"getPolicyName",
"(",
"policy",
",",
"controller",
",",
"action",
")",
"let",
"currentPolicy",
"if",
"(",
"policyName",
")",
"currentPolicy",
"=",
"policyRegistry",
"[",
"policyName",
"]",
"if",
"(",
"currentPolicy",
")",
"{",
"router",
"[",
"method",
"]",
"(",
"path",
",",
"currentPolicy",
",",
"handler",
")",
"}",
"else",
"{",
"router",
"[",
"method",
"]",
"(",
"path",
",",
"handler",
")",
"}",
"}"
] | bind path to controller & action | [
"bind",
"path",
"to",
"controller",
"&",
"action"
] | 03a6925fba1be5982d67b1a41f3095f3d2da8a46 | https://github.com/magicdawn/impress-router-table/blob/03a6925fba1be5982d67b1a41f3095f3d2da8a46/index.js#L114-L130 |
53,864 | tunnckoCore/online-branch-exist | index.js | verify | function verify(pattern, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
if (typeof callback !== 'function') {
errs.type('expect `callback` to be function');
}
if (typeof pattern !== 'string') {
errs.type('expect `pattern` to be string');
}
if (!regex.test(pattern)) {
errs.error('expect `pattern` to be `user/repo#branch`');
}
if (!isObject(opts)) {
errs.type('expect `opts` to be object');
}
opts = typeof opts.token === 'string' ? {
headers: {
Authorization: 'token ' + opts.token
}
} : undefined;
memo(regex.exec(pattern));
if (!cache.branch) {
errs.error('should give a branch or tag in `pattern`');
}
return {
opts: opts,
callback: callback
}
} | javascript | function verify(pattern, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
if (typeof callback !== 'function') {
errs.type('expect `callback` to be function');
}
if (typeof pattern !== 'string') {
errs.type('expect `pattern` to be string');
}
if (!regex.test(pattern)) {
errs.error('expect `pattern` to be `user/repo#branch`');
}
if (!isObject(opts)) {
errs.type('expect `opts` to be object');
}
opts = typeof opts.token === 'string' ? {
headers: {
Authorization: 'token ' + opts.token
}
} : undefined;
memo(regex.exec(pattern));
if (!cache.branch) {
errs.error('should give a branch or tag in `pattern`');
}
return {
opts: opts,
callback: callback
}
} | [
"function",
"verify",
"(",
"pattern",
",",
"opts",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"opts",
"===",
"'function'",
")",
"{",
"callback",
"=",
"opts",
";",
"opts",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"errs",
".",
"type",
"(",
"'expect `callback` to be function'",
")",
";",
"}",
"if",
"(",
"typeof",
"pattern",
"!==",
"'string'",
")",
"{",
"errs",
".",
"type",
"(",
"'expect `pattern` to be string'",
")",
";",
"}",
"if",
"(",
"!",
"regex",
".",
"test",
"(",
"pattern",
")",
")",
"{",
"errs",
".",
"error",
"(",
"'expect `pattern` to be `user/repo#branch`'",
")",
";",
"}",
"if",
"(",
"!",
"isObject",
"(",
"opts",
")",
")",
"{",
"errs",
".",
"type",
"(",
"'expect `opts` to be object'",
")",
";",
"}",
"opts",
"=",
"typeof",
"opts",
".",
"token",
"===",
"'string'",
"?",
"{",
"headers",
":",
"{",
"Authorization",
":",
"'token '",
"+",
"opts",
".",
"token",
"}",
"}",
":",
"undefined",
";",
"memo",
"(",
"regex",
".",
"exec",
"(",
"pattern",
")",
")",
";",
"if",
"(",
"!",
"cache",
".",
"branch",
")",
"{",
"errs",
".",
"error",
"(",
"'should give a branch or tag in `pattern`'",
")",
";",
"}",
"return",
"{",
"opts",
":",
"opts",
",",
"callback",
":",
"callback",
"}",
"}"
] | Verify the given arguments.
@param {String} `pattern`
@param {Object} `opts`
@param {Function} `callback`
@return {Object}
@api private | [
"Verify",
"the",
"given",
"arguments",
"."
] | 5913351870ee22c44083a2f47b6d3196aa5a9df4 | https://github.com/tunnckoCore/online-branch-exist/blob/5913351870ee22c44083a2f47b6d3196aa5a9df4/index.js#L85-L119 |
53,865 | rafrex/current-input | src/index.js | updateCurrentInput | function updateCurrentInput(input) {
if (input !== currentInput) {
body.classList.remove(`current-input-${currentInput}`);
body.classList.add(`current-input-${input}`);
currentInput = input;
}
} | javascript | function updateCurrentInput(input) {
if (input !== currentInput) {
body.classList.remove(`current-input-${currentInput}`);
body.classList.add(`current-input-${input}`);
currentInput = input;
}
} | [
"function",
"updateCurrentInput",
"(",
"input",
")",
"{",
"if",
"(",
"input",
"!==",
"currentInput",
")",
"{",
"body",
".",
"classList",
".",
"remove",
"(",
"`",
"${",
"currentInput",
"}",
"`",
")",
";",
"body",
".",
"classList",
".",
"add",
"(",
"`",
"${",
"input",
"}",
"`",
")",
";",
"currentInput",
"=",
"input",
";",
"}",
"}"
] | set current input class on body | [
"set",
"current",
"input",
"class",
"on",
"body"
] | d8b1764a235d1c0113083f8dde0f85c4f97f6376 | https://github.com/rafrex/current-input/blob/d8b1764a235d1c0113083f8dde0f85c4f97f6376/src/index.js#L9-L15 |
53,866 | Gozala/method | core.js | ArrayindexOf | function ArrayindexOf(thing) {
var index = 0;
var count = this.length;
while (index < count) {
if (this[index] === thing) return index
index = index + 1
}
return -1
} | javascript | function ArrayindexOf(thing) {
var index = 0;
var count = this.length;
while (index < count) {
if (this[index] === thing) return index
index = index + 1
}
return -1
} | [
"function",
"ArrayindexOf",
"(",
"thing",
")",
"{",
"var",
"index",
"=",
"0",
";",
"var",
"count",
"=",
"this",
".",
"length",
";",
"while",
"(",
"index",
"<",
"count",
")",
"{",
"if",
"(",
"this",
"[",
"index",
"]",
"===",
"thing",
")",
"return",
"index",
"index",
"=",
"index",
"+",
"1",
"}",
"return",
"-",
"1",
"}"
] | IE does not really has indexOf on arrays so we shim if that's what we're dealing with. | [
"IE",
"does",
"not",
"really",
"has",
"indexOf",
"on",
"arrays",
"so",
"we",
"shim",
"if",
"that",
"s",
"what",
"we",
"re",
"dealing",
"with",
"."
] | 4c1d83ef7b9524af2a7b35e6fed3b42316af2820 | https://github.com/Gozala/method/blob/4c1d83ef7b9524af2a7b35e6fed3b42316af2820/core.js#L10-L18 |
53,867 | godaddy/joi-of-cql | index.js | int64 | function int64(name) {
return joi.alternatives().meta({ cql: true, type: name }).try(
// a string that represents a number that is larger than JavaScript can handle
joi.string().regex(/^\-?\d{1,19}$/m),
// any integer that can be represented in JavaScript
joi.number().integer()
);
} | javascript | function int64(name) {
return joi.alternatives().meta({ cql: true, type: name }).try(
// a string that represents a number that is larger than JavaScript can handle
joi.string().regex(/^\-?\d{1,19}$/m),
// any integer that can be represented in JavaScript
joi.number().integer()
);
} | [
"function",
"int64",
"(",
"name",
")",
"{",
"return",
"joi",
".",
"alternatives",
"(",
")",
".",
"meta",
"(",
"{",
"cql",
":",
"true",
",",
"type",
":",
"name",
"}",
")",
".",
"try",
"(",
"// a string that represents a number that is larger than JavaScript can handle",
"joi",
".",
"string",
"(",
")",
".",
"regex",
"(",
"/",
"^\\-?\\d{1,19}$",
"/",
"m",
")",
",",
"// any integer that can be represented in JavaScript",
"joi",
".",
"number",
"(",
")",
".",
"integer",
"(",
")",
")",
";",
"}"
] | Used for creating Int64 with string and number alternative formats
@param {String} name - the type of int64 value
@returns {Joi} - the validator | [
"Used",
"for",
"creating",
"Int64",
"with",
"string",
"and",
"number",
"alternative",
"formats"
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L123-L130 |
53,868 | godaddy/joi-of-cql | index.js | decimal | function decimal(name) {
return joi.alternatives().meta({ cql: true, type: name }).try(
// a string that represents a number that is larger than JavaScript can handle
joi.string().regex(/^\-?\d+(\.\d+)?$/m),
// any number that can be represented in JavaScript
joi.number()
);
} | javascript | function decimal(name) {
return joi.alternatives().meta({ cql: true, type: name }).try(
// a string that represents a number that is larger than JavaScript can handle
joi.string().regex(/^\-?\d+(\.\d+)?$/m),
// any number that can be represented in JavaScript
joi.number()
);
} | [
"function",
"decimal",
"(",
"name",
")",
"{",
"return",
"joi",
".",
"alternatives",
"(",
")",
".",
"meta",
"(",
"{",
"cql",
":",
"true",
",",
"type",
":",
"name",
"}",
")",
".",
"try",
"(",
"// a string that represents a number that is larger than JavaScript can handle",
"joi",
".",
"string",
"(",
")",
".",
"regex",
"(",
"/",
"^\\-?\\d+(\\.\\d+)?$",
"/",
"m",
")",
",",
"// any number that can be represented in JavaScript",
"joi",
".",
"number",
"(",
")",
")",
";",
"}"
] | Used for creating decimal with string and number alternative formats
@param {String} name - the type of decimal value
@returns {Joi} - the validator | [
"Used",
"for",
"creating",
"decimal",
"with",
"string",
"and",
"number",
"alternative",
"formats"
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L138-L145 |
53,869 | godaddy/joi-of-cql | index.js | function (keyType, valueType) {
var meta = findMeta(valueType);
return joi.object().meta({
cql: true,
type: 'map',
mapType: ['text', meta.type],
serialize: convertMap(meta.serialize),
deserialize: convertMap(meta.deserialize)
}).pattern(/[\-\w]+/, valueType);
} | javascript | function (keyType, valueType) {
var meta = findMeta(valueType);
return joi.object().meta({
cql: true,
type: 'map',
mapType: ['text', meta.type],
serialize: convertMap(meta.serialize),
deserialize: convertMap(meta.deserialize)
}).pattern(/[\-\w]+/, valueType);
} | [
"function",
"(",
"keyType",
",",
"valueType",
")",
"{",
"var",
"meta",
"=",
"findMeta",
"(",
"valueType",
")",
";",
"return",
"joi",
".",
"object",
"(",
")",
".",
"meta",
"(",
"{",
"cql",
":",
"true",
",",
"type",
":",
"'map'",
",",
"mapType",
":",
"[",
"'text'",
",",
"meta",
".",
"type",
"]",
",",
"serialize",
":",
"convertMap",
"(",
"meta",
".",
"serialize",
")",
",",
"deserialize",
":",
"convertMap",
"(",
"meta",
".",
"deserialize",
")",
"}",
")",
".",
"pattern",
"(",
"/",
"[\\-\\w]+",
"/",
",",
"valueType",
")",
";",
"}"
] | Create a joi object that can validate a `map` for Cassandra.
@param {(String|Joi)} keyType - used for validating the fields of the object, ignored currently
@param {Joi} valueType - used for validating the values of the fields in the object
@returns {Joi} - the validator | [
"Create",
"a",
"joi",
"object",
"that",
"can",
"validate",
"a",
"map",
"for",
"Cassandra",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L298-L307 |
|
53,870 | godaddy/joi-of-cql | index.js | function (type) {
var meta = findMeta(type);
var set = joi.array().sparse(false).unique().items(type);
return joi.alternatives().meta({
cql: true,
type: 'set',
setType: meta.type,
serialize: convertArray(meta.serialize),
deserialize: convertArray(meta.deserialize)
}).try(set, joi.object().keys({
add: set,
remove: set
}).or('add', 'remove').unknown(false));
} | javascript | function (type) {
var meta = findMeta(type);
var set = joi.array().sparse(false).unique().items(type);
return joi.alternatives().meta({
cql: true,
type: 'set',
setType: meta.type,
serialize: convertArray(meta.serialize),
deserialize: convertArray(meta.deserialize)
}).try(set, joi.object().keys({
add: set,
remove: set
}).or('add', 'remove').unknown(false));
} | [
"function",
"(",
"type",
")",
"{",
"var",
"meta",
"=",
"findMeta",
"(",
"type",
")",
";",
"var",
"set",
"=",
"joi",
".",
"array",
"(",
")",
".",
"sparse",
"(",
"false",
")",
".",
"unique",
"(",
")",
".",
"items",
"(",
"type",
")",
";",
"return",
"joi",
".",
"alternatives",
"(",
")",
".",
"meta",
"(",
"{",
"cql",
":",
"true",
",",
"type",
":",
"'set'",
",",
"setType",
":",
"meta",
".",
"type",
",",
"serialize",
":",
"convertArray",
"(",
"meta",
".",
"serialize",
")",
",",
"deserialize",
":",
"convertArray",
"(",
"meta",
".",
"deserialize",
")",
"}",
")",
".",
"try",
"(",
"set",
",",
"joi",
".",
"object",
"(",
")",
".",
"keys",
"(",
"{",
"add",
":",
"set",
",",
"remove",
":",
"set",
"}",
")",
".",
"or",
"(",
"'add'",
",",
"'remove'",
")",
".",
"unknown",
"(",
"false",
")",
")",
";",
"}"
] | Create a joi object that can validate a `set` for Cassandra.
@param {Joi} type - used for validating the values of the set
@returns {Joi} - the validator | [
"Create",
"a",
"joi",
"object",
"that",
"can",
"validate",
"a",
"set",
"for",
"Cassandra",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L314-L327 |
|
53,871 | godaddy/joi-of-cql | index.js | function (type) {
var meta = findMeta(type);
var list = joi.array().sparse(false).items(type);
return joi.alternatives().meta({
cql: true,
type: 'list',
listType: meta.type,
serialize: convertArray(meta.serialize),
deserialize: convertArray(meta.deserialize)
}).try(list, joi.object().keys({
prepend: list,
append: list,
remove: list,
index: joi.object().pattern(/^\d+$/, type)
}).or('prepend', 'append', 'remove', 'index').unknown(false));
} | javascript | function (type) {
var meta = findMeta(type);
var list = joi.array().sparse(false).items(type);
return joi.alternatives().meta({
cql: true,
type: 'list',
listType: meta.type,
serialize: convertArray(meta.serialize),
deserialize: convertArray(meta.deserialize)
}).try(list, joi.object().keys({
prepend: list,
append: list,
remove: list,
index: joi.object().pattern(/^\d+$/, type)
}).or('prepend', 'append', 'remove', 'index').unknown(false));
} | [
"function",
"(",
"type",
")",
"{",
"var",
"meta",
"=",
"findMeta",
"(",
"type",
")",
";",
"var",
"list",
"=",
"joi",
".",
"array",
"(",
")",
".",
"sparse",
"(",
"false",
")",
".",
"items",
"(",
"type",
")",
";",
"return",
"joi",
".",
"alternatives",
"(",
")",
".",
"meta",
"(",
"{",
"cql",
":",
"true",
",",
"type",
":",
"'list'",
",",
"listType",
":",
"meta",
".",
"type",
",",
"serialize",
":",
"convertArray",
"(",
"meta",
".",
"serialize",
")",
",",
"deserialize",
":",
"convertArray",
"(",
"meta",
".",
"deserialize",
")",
"}",
")",
".",
"try",
"(",
"list",
",",
"joi",
".",
"object",
"(",
")",
".",
"keys",
"(",
"{",
"prepend",
":",
"list",
",",
"append",
":",
"list",
",",
"remove",
":",
"list",
",",
"index",
":",
"joi",
".",
"object",
"(",
")",
".",
"pattern",
"(",
"/",
"^\\d+$",
"/",
",",
"type",
")",
"}",
")",
".",
"or",
"(",
"'prepend'",
",",
"'append'",
",",
"'remove'",
",",
"'index'",
")",
".",
"unknown",
"(",
"false",
")",
")",
";",
"}"
] | Create a joi object that can validate a `list` for Cassandra.
@param {Joi} type - used for validating the values in the list
@returns {Joi} - the validator | [
"Create",
"a",
"joi",
"object",
"that",
"can",
"validate",
"a",
"list",
"for",
"Cassandra",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L334-L349 |
|
53,872 | godaddy/joi-of-cql | index.js | function (validator, options) {
var when = options.default;
var fn = function (context, config) {
if ((when === config.context.operation) ||
(when === 'update' && ['create', 'update'].indexOf(config.context.operation) > -1)
) {
return new Date().toISOString();
}
return undef;
};
fn.isJoi = true;
return validator.default(fn);
} | javascript | function (validator, options) {
var when = options.default;
var fn = function (context, config) {
if ((when === config.context.operation) ||
(when === 'update' && ['create', 'update'].indexOf(config.context.operation) > -1)
) {
return new Date().toISOString();
}
return undef;
};
fn.isJoi = true;
return validator.default(fn);
} | [
"function",
"(",
"validator",
",",
"options",
")",
"{",
"var",
"when",
"=",
"options",
".",
"default",
";",
"var",
"fn",
"=",
"function",
"(",
"context",
",",
"config",
")",
"{",
"if",
"(",
"(",
"when",
"===",
"config",
".",
"context",
".",
"operation",
")",
"||",
"(",
"when",
"===",
"'update'",
"&&",
"[",
"'create'",
",",
"'update'",
"]",
".",
"indexOf",
"(",
"config",
".",
"context",
".",
"operation",
")",
">",
"-",
"1",
")",
")",
"{",
"return",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
";",
"}",
"return",
"undef",
";",
"}",
";",
"fn",
".",
"isJoi",
"=",
"true",
";",
"return",
"validator",
".",
"default",
"(",
"fn",
")",
";",
"}"
] | Set a default date based on the contextual operation in which the joi object is being validated.
If 'update' is the specified default, default the value on both 'update' && 'create' operations
otherwise only default if the operation matches the specified default.
@param {Joi} validator - the object that is having a default set
@param {DefaultSpecifierOptions} options - the options for setting the default
@param {String} options.default - [create, update]
@returns {Joi} - the new validator | [
"Set",
"a",
"default",
"date",
"based",
"on",
"the",
"contextual",
"operation",
"in",
"which",
"the",
"joi",
"object",
"is",
"being",
"validated",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L394-L406 |
|
53,873 | godaddy/joi-of-cql | index.js | function (validator, options) {
var fn = function (context, config) {
if (config.context.operation === 'create')
return options.default === 'empty' ? '00000000-0000-0000-0000-000000000000' : uuid[options.default]();
return undef;
};
fn.isJoi = true;
return validator.default(fn);
} | javascript | function (validator, options) {
var fn = function (context, config) {
if (config.context.operation === 'create')
return options.default === 'empty' ? '00000000-0000-0000-0000-000000000000' : uuid[options.default]();
return undef;
};
fn.isJoi = true;
return validator.default(fn);
} | [
"function",
"(",
"validator",
",",
"options",
")",
"{",
"var",
"fn",
"=",
"function",
"(",
"context",
",",
"config",
")",
"{",
"if",
"(",
"config",
".",
"context",
".",
"operation",
"===",
"'create'",
")",
"return",
"options",
".",
"default",
"===",
"'empty'",
"?",
"'00000000-0000-0000-0000-000000000000'",
":",
"uuid",
"[",
"options",
".",
"default",
"]",
"(",
")",
";",
"return",
"undef",
";",
"}",
";",
"fn",
".",
"isJoi",
"=",
"true",
";",
"return",
"validator",
".",
"default",
"(",
"fn",
")",
";",
"}"
] | Set a default uuid when the the contextual operation is 'create'.
@param {Joi} validator - the object that is having a default set
@param {DefaultSpecifierOptions} options - the options for setting the default
@param {String} options.default - [empty, v1, v4]
@returns {Joi} - the new validator | [
"Set",
"a",
"default",
"uuid",
"when",
"the",
"the",
"contextual",
"operation",
"is",
"create",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L416-L424 |
|
53,874 | godaddy/joi-of-cql | index.js | defaultify | function defaultify(type, validator, options) {
return options && options.default ? defaults[type](validator, options) : validator;
} | javascript | function defaultify(type, validator, options) {
return options && options.default ? defaults[type](validator, options) : validator;
} | [
"function",
"defaultify",
"(",
"type",
",",
"validator",
",",
"options",
")",
"{",
"return",
"options",
"&&",
"options",
".",
"default",
"?",
"defaults",
"[",
"type",
"]",
"(",
"validator",
",",
"options",
")",
":",
"validator",
";",
"}"
] | Create a default based on a string identifier if one is provided.
@param {String} type - types of defaults [date, uuid]
@param {Joi} validator - the object being defaulted
@param {DefaultSpecifierOptions} options - the options for creating the default
@returns {Joi} - the new validator, possibly with a default | [
"Create",
"a",
"default",
"based",
"on",
"a",
"string",
"identifier",
"if",
"one",
"is",
"provided",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L435-L437 |
53,875 | godaddy/joi-of-cql | index.js | findMeta | function findMeta(any, key) {
key = key || 'cql';
var meta = (any.describe().meta || []).filter(function (m) {
return key in m;
});
return meta[meta.length - 1];
} | javascript | function findMeta(any, key) {
key = key || 'cql';
var meta = (any.describe().meta || []).filter(function (m) {
return key in m;
});
return meta[meta.length - 1];
} | [
"function",
"findMeta",
"(",
"any",
",",
"key",
")",
"{",
"key",
"=",
"key",
"||",
"'cql'",
";",
"var",
"meta",
"=",
"(",
"any",
".",
"describe",
"(",
")",
".",
"meta",
"||",
"[",
"]",
")",
".",
"filter",
"(",
"function",
"(",
"m",
")",
"{",
"return",
"key",
"in",
"m",
";",
"}",
")",
";",
"return",
"meta",
"[",
"meta",
".",
"length",
"-",
"1",
"]",
";",
"}"
] | Find the meta object that has the key given.
@param {Joi} any - the validator to be inspected
@param {String} key - the name of the field in the meta object that we are looking for
@returns {JoiMetaDefinition} - the result | [
"Find",
"the",
"meta",
"object",
"that",
"has",
"the",
"key",
"given",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L446-L452 |
53,876 | godaddy/joi-of-cql | index.js | convertToJsonOnValidate | function convertToJsonOnValidate(any) {
var validate = any._validate;
any._validate = function () {
var result = validate.apply(this, arguments);
if (!result.error && result.value) {
result.value = JSON.stringify(result.value);
}
return result;
};
return any;
} | javascript | function convertToJsonOnValidate(any) {
var validate = any._validate;
any._validate = function () {
var result = validate.apply(this, arguments);
if (!result.error && result.value) {
result.value = JSON.stringify(result.value);
}
return result;
};
return any;
} | [
"function",
"convertToJsonOnValidate",
"(",
"any",
")",
"{",
"var",
"validate",
"=",
"any",
".",
"_validate",
";",
"any",
".",
"_validate",
"=",
"function",
"(",
")",
"{",
"var",
"result",
"=",
"validate",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"if",
"(",
"!",
"result",
".",
"error",
"&&",
"result",
".",
"value",
")",
"{",
"result",
".",
"value",
"=",
"JSON",
".",
"stringify",
"(",
"result",
".",
"value",
")",
";",
"}",
"return",
"result",
";",
"}",
";",
"return",
"any",
";",
"}"
] | Convert the resulting object back to JSON after validation.
* Warning: This relies on the internal structure of a joi object
@param {Joi} any - the object that will be extended to convert the given value
@returns {Joi} - the extended validator | [
"Convert",
"the",
"resulting",
"object",
"back",
"to",
"JSON",
"after",
"validation",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L473-L483 |
53,877 | godaddy/joi-of-cql | index.js | defaultUuid | function defaultUuid(options, version) {
if (options && options.default) {
if ([version, 'empty'].indexOf(options.default) > -1) {
return options.default;
}
return version;
}
return undef;
} | javascript | function defaultUuid(options, version) {
if (options && options.default) {
if ([version, 'empty'].indexOf(options.default) > -1) {
return options.default;
}
return version;
}
return undef;
} | [
"function",
"defaultUuid",
"(",
"options",
",",
"version",
")",
"{",
"if",
"(",
"options",
"&&",
"options",
".",
"default",
")",
"{",
"if",
"(",
"[",
"version",
",",
"'empty'",
"]",
".",
"indexOf",
"(",
"options",
".",
"default",
")",
">",
"-",
"1",
")",
"{",
"return",
"options",
".",
"default",
";",
"}",
"return",
"version",
";",
"}",
"return",
"undef",
";",
"}"
] | Ensure that `uuid` type joi objects have a default specified.
@param {DefaultSpecifierOptions} [options] - possible default options
@property {String} options.default - [empty, v1, v4]
@param {String} version - the uuid version that should be used as a default if no other default is specified
@returns {(Undefined|String)} - the value that will identify the appropriate default to the default handler on the validator | [
"Ensure",
"that",
"uuid",
"type",
"joi",
"objects",
"have",
"a",
"default",
"specified",
"."
] | e9498171eaf4b068aab4b76b8ba762c8ed657f23 | https://github.com/godaddy/joi-of-cql/blob/e9498171eaf4b068aab4b76b8ba762c8ed657f23/index.js#L493-L501 |
53,878 | pagespace/pagespace | static/inpage/inpage-edit.js | handleAdminEvents | function handleAdminEvents() {
//listen for clicks that bubble in up in the admin bar
document.body.addEventListener('click', function (ev) {
if(ev.target.hasAttribute('data-edit-include')) {
launchPluginEditor(ev.target);
} else if(ev.target.hasAttribute('data-add-include')) {
launchAddInclude(ev.target);
}
});
//intercept link clicks so the parent frame changes
window.pagespace.interceptLinks = function(ev) {
if(ev.target.tagName.toUpperCase() === 'A' && ev.target.getAttribute('href').indexOf('/') === 0) {
var href = ev.target.getAttribute('href');
window.parent.location.assign('/_dashboard#/view-page/preview' + href);
ev.preventDefault();
}
};
document.body.addEventListener('click', window.pagespace.interceptLinks);
} | javascript | function handleAdminEvents() {
//listen for clicks that bubble in up in the admin bar
document.body.addEventListener('click', function (ev) {
if(ev.target.hasAttribute('data-edit-include')) {
launchPluginEditor(ev.target);
} else if(ev.target.hasAttribute('data-add-include')) {
launchAddInclude(ev.target);
}
});
//intercept link clicks so the parent frame changes
window.pagespace.interceptLinks = function(ev) {
if(ev.target.tagName.toUpperCase() === 'A' && ev.target.getAttribute('href').indexOf('/') === 0) {
var href = ev.target.getAttribute('href');
window.parent.location.assign('/_dashboard#/view-page/preview' + href);
ev.preventDefault();
}
};
document.body.addEventListener('click', window.pagespace.interceptLinks);
} | [
"function",
"handleAdminEvents",
"(",
")",
"{",
"//listen for clicks that bubble in up in the admin bar",
"document",
".",
"body",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
"ev",
")",
"{",
"if",
"(",
"ev",
".",
"target",
".",
"hasAttribute",
"(",
"'data-edit-include'",
")",
")",
"{",
"launchPluginEditor",
"(",
"ev",
".",
"target",
")",
";",
"}",
"else",
"if",
"(",
"ev",
".",
"target",
".",
"hasAttribute",
"(",
"'data-add-include'",
")",
")",
"{",
"launchAddInclude",
"(",
"ev",
".",
"target",
")",
";",
"}",
"}",
")",
";",
"//intercept link clicks so the parent frame changes",
"window",
".",
"pagespace",
".",
"interceptLinks",
"=",
"function",
"(",
"ev",
")",
"{",
"if",
"(",
"ev",
".",
"target",
".",
"tagName",
".",
"toUpperCase",
"(",
")",
"===",
"'A'",
"&&",
"ev",
".",
"target",
".",
"getAttribute",
"(",
"'href'",
")",
".",
"indexOf",
"(",
"'/'",
")",
"===",
"0",
")",
"{",
"var",
"href",
"=",
"ev",
".",
"target",
".",
"getAttribute",
"(",
"'href'",
")",
";",
"window",
".",
"parent",
".",
"location",
".",
"assign",
"(",
"'/_dashboard#/view-page/preview'",
"+",
"href",
")",
";",
"ev",
".",
"preventDefault",
"(",
")",
";",
"}",
"}",
";",
"document",
".",
"body",
".",
"addEventListener",
"(",
"'click'",
",",
"window",
".",
"pagespace",
".",
"interceptLinks",
")",
";",
"}"
] | Handle Admin Events | [
"Handle",
"Admin",
"Events"
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/inpage/inpage-edit.js#L15-L36 |
53,879 | pagespace/pagespace | static/inpage/inpage-edit.js | getIncludeDragData | function getIncludeDragData(ev) {
var data = ev.dataTransfer.getData('include-info');
return data ? JSON.parse(data) : null;
} | javascript | function getIncludeDragData(ev) {
var data = ev.dataTransfer.getData('include-info');
return data ? JSON.parse(data) : null;
} | [
"function",
"getIncludeDragData",
"(",
"ev",
")",
"{",
"var",
"data",
"=",
"ev",
".",
"dataTransfer",
".",
"getData",
"(",
"'include-info'",
")",
";",
"return",
"data",
"?",
"JSON",
".",
"parse",
"(",
"data",
")",
":",
"null",
";",
"}"
] | utils for drag+drop | [
"utils",
"for",
"drag",
"+",
"drop"
] | 943c45ddd9aaa4f3136e1ba4c2593aa0289daf43 | https://github.com/pagespace/pagespace/blob/943c45ddd9aaa4f3136e1ba4c2593aa0289daf43/static/inpage/inpage-edit.js#L257-L260 |
53,880 | envone/ember-runner | index.js | function(callback) {
helpers.walk(buildInfo.srcApps, function(err, results) {
if (err) return callback("Error walking files.");
callback(null, results);
});
} | javascript | function(callback) {
helpers.walk(buildInfo.srcApps, function(err, results) {
if (err) return callback("Error walking files.");
callback(null, results);
});
} | [
"function",
"(",
"callback",
")",
"{",
"helpers",
".",
"walk",
"(",
"buildInfo",
".",
"srcApps",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"\"Error walking files.\"",
")",
";",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
")",
";",
"}"
] | Load apps files | [
"Load",
"apps",
"files"
] | 2bd8c0a86cc251f4ea7b00885b804646f0a2190c | https://github.com/envone/ember-runner/blob/2bd8c0a86cc251f4ea7b00885b804646f0a2190c/index.js#L280-L285 |
|
53,881 | envone/ember-runner | index.js | function(callback) {
helpers.walk(buildInfo.srcVendors, function(err, results) {
if (err) return callback("Error walking files.");
callback(null, results);
});
} | javascript | function(callback) {
helpers.walk(buildInfo.srcVendors, function(err, results) {
if (err) return callback("Error walking files.");
callback(null, results);
});
} | [
"function",
"(",
"callback",
")",
"{",
"helpers",
".",
"walk",
"(",
"buildInfo",
".",
"srcVendors",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"\"Error walking files.\"",
")",
";",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
")",
";",
"}"
] | Load vendors files | [
"Load",
"vendors",
"files"
] | 2bd8c0a86cc251f4ea7b00885b804646f0a2190c | https://github.com/envone/ember-runner/blob/2bd8c0a86cc251f4ea7b00885b804646f0a2190c/index.js#L287-L292 |
|
53,882 | IonicaBizau/cb-buffer | example/index.js | getUniqueRandomNumberAsync | function getUniqueRandomNumberAsync(callback) {
if (cb.check(callback)) { return; }
setTimeout(() => {
debugger
cb.done(Math.random());
}, 1000);
} | javascript | function getUniqueRandomNumberAsync(callback) {
if (cb.check(callback)) { return; }
setTimeout(() => {
debugger
cb.done(Math.random());
}, 1000);
} | [
"function",
"getUniqueRandomNumberAsync",
"(",
"callback",
")",
"{",
"if",
"(",
"cb",
".",
"check",
"(",
"callback",
")",
")",
"{",
"return",
";",
"}",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"debugger",
"cb",
".",
"done",
"(",
"Math",
".",
"random",
"(",
")",
")",
";",
"}",
",",
"1000",
")",
";",
"}"
] | Callbacks a random unique number after 1 sec | [
"Callbacks",
"a",
"random",
"unique",
"number",
"after",
"1",
"sec"
] | cf4d6b6c4b77500bb5f68fa569745cdfb9f54f42 | https://github.com/IonicaBizau/cb-buffer/blob/cf4d6b6c4b77500bb5f68fa569745cdfb9f54f42/example/index.js#L8-L14 |
53,883 | feedhenry/fh-service-auth | lib/models/service.js | initServiceModel | function initServiceModel(connectionUrl) {
log.logger.debug("initServiceModel ", {connectionUrl: connectionUrl});
if (!connectionUrl) {
log.logger.error("No Connection Url Specified");
return null;
}
//If the connection has not already been created, create it and initialise the Service Schema For That Domain
if (!domainMongooseConnections[connectionUrl]) {
log.logger.debug("No Connection Exists for " + connectionUrl + ", creating a new one");
domainMongooseConnections[connectionUrl] = mongoose.createConnection(connectionUrl);
domainMongooseConnections[connectionUrl].model(SERVICE_MODEL, ServiceSchema);
//Setting Up Event Listeners
domainMongooseConnections[connectionUrl].on('connecting', function(msg){
log.logger.debug("Mongoose Connecting", {msg: msg, connectionUrl: connectionUrl});
});
domainMongooseConnections[connectionUrl].on('error', function(msg){
log.logger.error("Mongoose Connection Error", {msg: msg, connectionUrl: connectionUrl});
});
domainMongooseConnections[connectionUrl].on('connected', function(msg){
log.logger.debug("Mongoose Connected", {msg: msg, connectionUrl: connectionUrl});
});
} else {
log.logger.debug("Connection Already Exists.");
}
return domainMongooseConnections[connectionUrl];
} | javascript | function initServiceModel(connectionUrl) {
log.logger.debug("initServiceModel ", {connectionUrl: connectionUrl});
if (!connectionUrl) {
log.logger.error("No Connection Url Specified");
return null;
}
//If the connection has not already been created, create it and initialise the Service Schema For That Domain
if (!domainMongooseConnections[connectionUrl]) {
log.logger.debug("No Connection Exists for " + connectionUrl + ", creating a new one");
domainMongooseConnections[connectionUrl] = mongoose.createConnection(connectionUrl);
domainMongooseConnections[connectionUrl].model(SERVICE_MODEL, ServiceSchema);
//Setting Up Event Listeners
domainMongooseConnections[connectionUrl].on('connecting', function(msg){
log.logger.debug("Mongoose Connecting", {msg: msg, connectionUrl: connectionUrl});
});
domainMongooseConnections[connectionUrl].on('error', function(msg){
log.logger.error("Mongoose Connection Error", {msg: msg, connectionUrl: connectionUrl});
});
domainMongooseConnections[connectionUrl].on('connected', function(msg){
log.logger.debug("Mongoose Connected", {msg: msg, connectionUrl: connectionUrl});
});
} else {
log.logger.debug("Connection Already Exists.");
}
return domainMongooseConnections[connectionUrl];
} | [
"function",
"initServiceModel",
"(",
"connectionUrl",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"\"initServiceModel \"",
",",
"{",
"connectionUrl",
":",
"connectionUrl",
"}",
")",
";",
"if",
"(",
"!",
"connectionUrl",
")",
"{",
"log",
".",
"logger",
".",
"error",
"(",
"\"No Connection Url Specified\"",
")",
";",
"return",
"null",
";",
"}",
"//If the connection has not already been created, create it and initialise the Service Schema For That Domain",
"if",
"(",
"!",
"domainMongooseConnections",
"[",
"connectionUrl",
"]",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"\"No Connection Exists for \"",
"+",
"connectionUrl",
"+",
"\", creating a new one\"",
")",
";",
"domainMongooseConnections",
"[",
"connectionUrl",
"]",
"=",
"mongoose",
".",
"createConnection",
"(",
"connectionUrl",
")",
";",
"domainMongooseConnections",
"[",
"connectionUrl",
"]",
".",
"model",
"(",
"SERVICE_MODEL",
",",
"ServiceSchema",
")",
";",
"//Setting Up Event Listeners",
"domainMongooseConnections",
"[",
"connectionUrl",
"]",
".",
"on",
"(",
"'connecting'",
",",
"function",
"(",
"msg",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"\"Mongoose Connecting\"",
",",
"{",
"msg",
":",
"msg",
",",
"connectionUrl",
":",
"connectionUrl",
"}",
")",
";",
"}",
")",
";",
"domainMongooseConnections",
"[",
"connectionUrl",
"]",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"msg",
")",
"{",
"log",
".",
"logger",
".",
"error",
"(",
"\"Mongoose Connection Error\"",
",",
"{",
"msg",
":",
"msg",
",",
"connectionUrl",
":",
"connectionUrl",
"}",
")",
";",
"}",
")",
";",
"domainMongooseConnections",
"[",
"connectionUrl",
"]",
".",
"on",
"(",
"'connected'",
",",
"function",
"(",
"msg",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"\"Mongoose Connected\"",
",",
"{",
"msg",
":",
"msg",
",",
"connectionUrl",
":",
"connectionUrl",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"\"Connection Already Exists.\"",
")",
";",
"}",
"return",
"domainMongooseConnections",
"[",
"connectionUrl",
"]",
";",
"}"
] | Creating A connection To The Domain Database If It Does Not Already Exist
@param connectionUrl - Full Mongo Connection String For A Domain Database
@returns {null} | [
"Creating",
"A",
"connection",
"To",
"The",
"Domain",
"Database",
"If",
"It",
"Does",
"Not",
"Already",
"Exist"
] | ba3b8d736fb495c00d03c38ec2dc456f516b28c8 | https://github.com/feedhenry/fh-service-auth/blob/ba3b8d736fb495c00d03c38ec2dc456f516b28c8/lib/models/service.js#L173-L203 |
53,884 | kgryte/eval-serialize-typed-array | examples/index.js | create | function create( arr ) {
var f = '';
f += 'return function fill( len ) {';
f += 'var arr = new Array( len );';
f += 'for ( var i = 0; i < len; i++ ) {';
f += 'arr[ i ] = ' + serialize( arr ) + ';';
f += '}';
f += 'return arr;';
f += '}';
return ( new Function( f ) )();
} | javascript | function create( arr ) {
var f = '';
f += 'return function fill( len ) {';
f += 'var arr = new Array( len );';
f += 'for ( var i = 0; i < len; i++ ) {';
f += 'arr[ i ] = ' + serialize( arr ) + ';';
f += '}';
f += 'return arr;';
f += '}';
return ( new Function( f ) )();
} | [
"function",
"create",
"(",
"arr",
")",
"{",
"var",
"f",
"=",
"''",
";",
"f",
"+=",
"'return function fill( len ) {'",
";",
"f",
"+=",
"'var arr = new Array( len );'",
";",
"f",
"+=",
"'for ( var i = 0; i < len; i++ ) {'",
";",
"f",
"+=",
"'arr[ i ] = '",
"+",
"serialize",
"(",
"arr",
")",
"+",
"';'",
";",
"f",
"+=",
"'}'",
";",
"f",
"+=",
"'return arr;'",
";",
"f",
"+=",
"'}'",
";",
"return",
"(",
"new",
"Function",
"(",
"f",
")",
")",
"(",
")",
";",
"}"
] | Returns a function to create a filled array. | [
"Returns",
"a",
"function",
"to",
"create",
"a",
"filled",
"array",
"."
] | 65cb14bd7b5417b555b1003d46f0ee7e94adebf8 | https://github.com/kgryte/eval-serialize-typed-array/blob/65cb14bd7b5417b555b1003d46f0ee7e94adebf8/examples/index.js#L9-L19 |
53,885 | patrickfatrick/harsh | dist/harsh.js | hash | function hash() {
var ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [Math.floor(Math.random() * 100)];
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36;
if (!ids.splice) {
throw new TypeError('The ids argument should be an array of numbers');
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('The number of salts should be a positive integer');
}
if (typeof base !== 'number' || base < 16 || base > 36) {
throw new TypeError('The base should be a number between 16 and 36');
}
// Create the salts. This will be the same for all hashes
var salts = _createSalts(n, base);
// Combine the salts and the actual
var hashes = ids.map(function (id) {
if (typeof id !== 'number') {
throw new TypeError('The ids you\'re hashing should only be numbers');
}
return _createHash(id, salts, base);
});
return {
ids: ids,
hashes: hashes,
salts: salts,
base: base
};
} | javascript | function hash() {
var ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [Math.floor(Math.random() * 100)];
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36;
if (!ids.splice) {
throw new TypeError('The ids argument should be an array of numbers');
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('The number of salts should be a positive integer');
}
if (typeof base !== 'number' || base < 16 || base > 36) {
throw new TypeError('The base should be a number between 16 and 36');
}
// Create the salts. This will be the same for all hashes
var salts = _createSalts(n, base);
// Combine the salts and the actual
var hashes = ids.map(function (id) {
if (typeof id !== 'number') {
throw new TypeError('The ids you\'re hashing should only be numbers');
}
return _createHash(id, salts, base);
});
return {
ids: ids,
hashes: hashes,
salts: salts,
base: base
};
} | [
"function",
"hash",
"(",
")",
"{",
"var",
"ids",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"[",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"100",
")",
"]",
";",
"var",
"n",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"2",
";",
"var",
"base",
"=",
"arguments",
".",
"length",
">",
"2",
"&&",
"arguments",
"[",
"2",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"2",
"]",
":",
"36",
";",
"if",
"(",
"!",
"ids",
".",
"splice",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The ids argument should be an array of numbers'",
")",
";",
"}",
"if",
"(",
"typeof",
"n",
"!==",
"'number'",
"||",
"n",
"<",
"0",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The number of salts should be a positive integer'",
")",
";",
"}",
"if",
"(",
"typeof",
"base",
"!==",
"'number'",
"||",
"base",
"<",
"16",
"||",
"base",
">",
"36",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The base should be a number between 16 and 36'",
")",
";",
"}",
"// Create the salts. This will be the same for all hashes",
"var",
"salts",
"=",
"_createSalts",
"(",
"n",
",",
"base",
")",
";",
"// Combine the salts and the actual",
"var",
"hashes",
"=",
"ids",
".",
"map",
"(",
"function",
"(",
"id",
")",
"{",
"if",
"(",
"typeof",
"id",
"!==",
"'number'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The ids you\\'re hashing should only be numbers'",
")",
";",
"}",
"return",
"_createHash",
"(",
"id",
",",
"salts",
",",
"base",
")",
";",
"}",
")",
";",
"return",
"{",
"ids",
":",
"ids",
",",
"hashes",
":",
"hashes",
",",
"salts",
":",
"salts",
",",
"base",
":",
"base",
"}",
";",
"}"
] | Takes a number and a radix base, outputs a salted hash
@param {Array} ids list of ids to hash
@param {Number} n number of salts to add to the hash
@param {Number} base radix base, 16 through 36 allowed
@return {Object} a hash object containing the hashes as well as info needed to reverse them | [
"Takes",
"a",
"number",
"and",
"a",
"radix",
"base",
"outputs",
"a",
"salted",
"hash"
] | 5a99a5b0e8c30889a99cd68aabe52635724e2c8d | https://github.com/patrickfatrick/harsh/blob/5a99a5b0e8c30889a99cd68aabe52635724e2c8d/dist/harsh.js#L38-L70 |
53,886 | patrickfatrick/harsh | dist/harsh.js | bunch | function bunch() {
var num = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36;
if (typeof num !== 'number') {
throw new TypeError('The num should be a number');
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('The number of salts should be a positive integer');
}
if (typeof base !== 'number' || base < 16 || base > 36) {
throw new TypeError('The base should be a number between 16 and 36');
}
// Create the ids
var ids = [];
for (var i = 0; i < num; i++) {
ids.push(Math.floor(Math.random() * Math.pow(10, num.toString(10).length + 2)));
}
// Create the salts. This will be the same for all hashes
var salts = _createSalts(n, base);
// Combine the salts and the actual
var hashes = ids.map(function (id) {
return _createHash(id, salts, base);
});
return {
ids: ids,
hashes: hashes,
salts: salts,
base: base
};
} | javascript | function bunch() {
var num = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36;
if (typeof num !== 'number') {
throw new TypeError('The num should be a number');
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('The number of salts should be a positive integer');
}
if (typeof base !== 'number' || base < 16 || base > 36) {
throw new TypeError('The base should be a number between 16 and 36');
}
// Create the ids
var ids = [];
for (var i = 0; i < num; i++) {
ids.push(Math.floor(Math.random() * Math.pow(10, num.toString(10).length + 2)));
}
// Create the salts. This will be the same for all hashes
var salts = _createSalts(n, base);
// Combine the salts and the actual
var hashes = ids.map(function (id) {
return _createHash(id, salts, base);
});
return {
ids: ids,
hashes: hashes,
salts: salts,
base: base
};
} | [
"function",
"bunch",
"(",
")",
"{",
"var",
"num",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"1",
";",
"var",
"n",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"2",
";",
"var",
"base",
"=",
"arguments",
".",
"length",
">",
"2",
"&&",
"arguments",
"[",
"2",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"2",
"]",
":",
"36",
";",
"if",
"(",
"typeof",
"num",
"!==",
"'number'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The num should be a number'",
")",
";",
"}",
"if",
"(",
"typeof",
"n",
"!==",
"'number'",
"||",
"n",
"<",
"0",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The number of salts should be a positive integer'",
")",
";",
"}",
"if",
"(",
"typeof",
"base",
"!==",
"'number'",
"||",
"base",
"<",
"16",
"||",
"base",
">",
"36",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The base should be a number between 16 and 36'",
")",
";",
"}",
"// Create the ids",
"var",
"ids",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
")",
"{",
"ids",
".",
"push",
"(",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"Math",
".",
"pow",
"(",
"10",
",",
"num",
".",
"toString",
"(",
"10",
")",
".",
"length",
"+",
"2",
")",
")",
")",
";",
"}",
"// Create the salts. This will be the same for all hashes",
"var",
"salts",
"=",
"_createSalts",
"(",
"n",
",",
"base",
")",
";",
"// Combine the salts and the actual",
"var",
"hashes",
"=",
"ids",
".",
"map",
"(",
"function",
"(",
"id",
")",
"{",
"return",
"_createHash",
"(",
"id",
",",
"salts",
",",
"base",
")",
";",
"}",
")",
";",
"return",
"{",
"ids",
":",
"ids",
",",
"hashes",
":",
"hashes",
",",
"salts",
":",
"salts",
",",
"base",
":",
"base",
"}",
";",
"}"
] | Creates a specified number of random tokens
@param {Number} num number of tokens to create
@param {Number} n number of salts to add to each hash
@param {Number} base radix base, 16 through 36 allowed
@return {Object} a hash object containing the hashes as well as info needed to reverse them | [
"Creates",
"a",
"specified",
"number",
"of",
"random",
"tokens"
] | 5a99a5b0e8c30889a99cd68aabe52635724e2c8d | https://github.com/patrickfatrick/harsh/blob/5a99a5b0e8c30889a99cd68aabe52635724e2c8d/dist/harsh.js#L91-L126 |
53,887 | ashpool/telldus-live-promise | lib/api.js | request | function request(path, json) {
return new Promise(function (resolve, reject) {
oauth._performSecureRequest(config.telldusToken,
config.telldusTokenSecret,
'GET',
'https://api.telldus.com/json' + path,
null,
json,
!!json ? 'application/json' : null, function (err, body, response) {
_parseResponse(err, body, response, resolve, reject);
});
});
} | javascript | function request(path, json) {
return new Promise(function (resolve, reject) {
oauth._performSecureRequest(config.telldusToken,
config.telldusTokenSecret,
'GET',
'https://api.telldus.com/json' + path,
null,
json,
!!json ? 'application/json' : null, function (err, body, response) {
_parseResponse(err, body, response, resolve, reject);
});
});
} | [
"function",
"request",
"(",
"path",
",",
"json",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"oauth",
".",
"_performSecureRequest",
"(",
"config",
".",
"telldusToken",
",",
"config",
".",
"telldusTokenSecret",
",",
"'GET'",
",",
"'https://api.telldus.com/json'",
"+",
"path",
",",
"null",
",",
"json",
",",
"!",
"!",
"json",
"?",
"'application/json'",
":",
"null",
",",
"function",
"(",
"err",
",",
"body",
",",
"response",
")",
"{",
"_parseResponse",
"(",
"err",
",",
"body",
",",
"response",
",",
"resolve",
",",
"reject",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Performs a secure oauth request to Telldus API.
@param path
@param json optional
@returns {Promise} | [
"Performs",
"a",
"secure",
"oauth",
"request",
"to",
"Telldus",
"API",
"."
] | ee13365136da640d78907f468b19580bdd8545d8 | https://github.com/ashpool/telldus-live-promise/blob/ee13365136da640d78907f468b19580bdd8545d8/lib/api.js#L27-L39 |
53,888 | segmentio/clear-ajax | lib/index.js | clearAjax | function clearAjax() {
each(function(request) {
try {
request.onload = noop;
request.onerror = noop;
request.onabort = noop;
request.onreadystatechange = noop;
each(function(added) {
request[added[0]].apply(request, added[1]);
}, request._queue || []);
request.abort();
} catch (e) {
// Ignore error
}
}, requests);
requests.length = [];
} | javascript | function clearAjax() {
each(function(request) {
try {
request.onload = noop;
request.onerror = noop;
request.onabort = noop;
request.onreadystatechange = noop;
each(function(added) {
request[added[0]].apply(request, added[1]);
}, request._queue || []);
request.abort();
} catch (e) {
// Ignore error
}
}, requests);
requests.length = [];
} | [
"function",
"clearAjax",
"(",
")",
"{",
"each",
"(",
"function",
"(",
"request",
")",
"{",
"try",
"{",
"request",
".",
"onload",
"=",
"noop",
";",
"request",
".",
"onerror",
"=",
"noop",
";",
"request",
".",
"onabort",
"=",
"noop",
";",
"request",
".",
"onreadystatechange",
"=",
"noop",
";",
"each",
"(",
"function",
"(",
"added",
")",
"{",
"request",
"[",
"added",
"[",
"0",
"]",
"]",
".",
"apply",
"(",
"request",
",",
"added",
"[",
"1",
"]",
")",
";",
"}",
",",
"request",
".",
"_queue",
"||",
"[",
"]",
")",
";",
"request",
".",
"abort",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Ignore error",
"}",
"}",
",",
"requests",
")",
";",
"requests",
".",
"length",
"=",
"[",
"]",
";",
"}"
] | Clear all active AJAX requests.
@api public | [
"Clear",
"all",
"active",
"AJAX",
"requests",
"."
] | 930f38b0ffb7fef082ce7227168ad3d28ab9ea71 | https://github.com/segmentio/clear-ajax/blob/930f38b0ffb7fef082ce7227168ad3d28ab9ea71/lib/index.js#L45-L61 |
53,889 | ffan-fe/fancyui | lib/datetimepicker/index.js | getMoment | function getMoment(modelValue) {
return moment(modelValue, angular.isString(modelValue) ? configuration.parseFormat : undefined)
} | javascript | function getMoment(modelValue) {
return moment(modelValue, angular.isString(modelValue) ? configuration.parseFormat : undefined)
} | [
"function",
"getMoment",
"(",
"modelValue",
")",
"{",
"return",
"moment",
"(",
"modelValue",
",",
"angular",
".",
"isString",
"(",
"modelValue",
")",
"?",
"configuration",
".",
"parseFormat",
":",
"undefined",
")",
"}"
] | Converts a time value into a moment.
This function is now necessary because moment logs a warning when parsing a string without a format.
@param modelValue
a time value in any of the supported formats (Date, moment, milliseconds, and string)
@returns {moment}
representing the specified time value. | [
"Converts",
"a",
"time",
"value",
"into",
"a",
"moment",
"."
] | e6077985d0e939976da435d7eeaa28886359e6e7 | https://github.com/ffan-fe/fancyui/blob/e6077985d0e939976da435d7eeaa28886359e6e7/lib/datetimepicker/index.js#L358-L360 |
53,890 | ChrisAckerman/politic | src/main/util/debounce.js | debounce | function debounce(callback) {
let timeout = null;
return () => {
if (timeout !== null) {
return;
}
timeout = setTimeout(() => {
timeout = null;
callback();
}, 0);
}
} | javascript | function debounce(callback) {
let timeout = null;
return () => {
if (timeout !== null) {
return;
}
timeout = setTimeout(() => {
timeout = null;
callback();
}, 0);
}
} | [
"function",
"debounce",
"(",
"callback",
")",
"{",
"let",
"timeout",
"=",
"null",
";",
"return",
"(",
")",
"=>",
"{",
"if",
"(",
"timeout",
"!==",
"null",
")",
"{",
"return",
";",
"}",
"timeout",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"timeout",
"=",
"null",
";",
"callback",
"(",
")",
";",
"}",
",",
"0",
")",
";",
"}",
"}"
] | Wrap a function so that multiple calls result in a single invocation on the next event loop tick. This function
cannot accept arguments or return a value.
@param {function()} callback - Function to be wrapped.
@returns {function()} Wrapped function. | [
"Wrap",
"a",
"function",
"so",
"that",
"multiple",
"calls",
"result",
"in",
"a",
"single",
"invocation",
"on",
"the",
"next",
"event",
"loop",
"tick",
".",
"This",
"function",
"cannot",
"accept",
"arguments",
"or",
"return",
"a",
"value",
"."
] | dd90696c933b4afe5ef1f88fafea2cd0adb8cd3b | https://github.com/ChrisAckerman/politic/blob/dd90696c933b4afe5ef1f88fafea2cd0adb8cd3b/src/main/util/debounce.js#L8-L21 |
53,891 | aledbf/deis-api | lib/keys.js | add | function add(keyId, sshKey, callback) {
try {
sshKeyparser(sshKey);
}catch (e) {
return callback(e);
}
commons.post(format('/%s/keys/', deis.version), {
id: keyId || deis.username,
'public': sshKey
},callback);
} | javascript | function add(keyId, sshKey, callback) {
try {
sshKeyparser(sshKey);
}catch (e) {
return callback(e);
}
commons.post(format('/%s/keys/', deis.version), {
id: keyId || deis.username,
'public': sshKey
},callback);
} | [
"function",
"add",
"(",
"keyId",
",",
"sshKey",
",",
"callback",
")",
"{",
"try",
"{",
"sshKeyparser",
"(",
"sshKey",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"callback",
"(",
"e",
")",
";",
"}",
"commons",
".",
"post",
"(",
"format",
"(",
"'/%s/keys/'",
",",
"deis",
".",
"version",
")",
",",
"{",
"id",
":",
"keyId",
"||",
"deis",
".",
"username",
",",
"'public'",
":",
"sshKey",
"}",
",",
"callback",
")",
";",
"}"
] | add an SSH key | [
"add",
"an",
"SSH",
"key"
] | f0833789998032b11221a3a617bb566ade1fcc13 | https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/keys.js#L18-L29 |
53,892 | aledbf/deis-api | lib/keys.js | remove | function remove(keyId, callback) {
commons.del(format('/%s/keys/%s', deis.version, keyId), callback);
} | javascript | function remove(keyId, callback) {
commons.del(format('/%s/keys/%s', deis.version, keyId), callback);
} | [
"function",
"remove",
"(",
"keyId",
",",
"callback",
")",
"{",
"commons",
".",
"del",
"(",
"format",
"(",
"'/%s/keys/%s'",
",",
"deis",
".",
"version",
",",
"keyId",
")",
",",
"callback",
")",
";",
"}"
] | remove an SSH key | [
"remove",
"an",
"SSH",
"key"
] | f0833789998032b11221a3a617bb566ade1fcc13 | https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/keys.js#L34-L36 |
53,893 | AndiDittrich/Node.Logging-Facility | logging-facility.js | exposeAPI | function exposeAPI(log){
return {
emerg: log(_loglevel.EMERGENCY),
emergency: log(_loglevel.EMERGENCY),
alert: log(_loglevel.ALERT),
crit: log(_loglevel.CRITICAL),
critical: log(_loglevel.CRITICAL),
error: log(_loglevel.ERROR),
err: log(_loglevel.ERROR),
warning: log(_loglevel.WARNING),
warn: log(_loglevel.WARNING),
notice: log(_loglevel.NOTICE),
log: log(_loglevel.INFO),
info: log(_loglevel.INFO),
debug: log(_loglevel.DEBUG)
};
} | javascript | function exposeAPI(log){
return {
emerg: log(_loglevel.EMERGENCY),
emergency: log(_loglevel.EMERGENCY),
alert: log(_loglevel.ALERT),
crit: log(_loglevel.CRITICAL),
critical: log(_loglevel.CRITICAL),
error: log(_loglevel.ERROR),
err: log(_loglevel.ERROR),
warning: log(_loglevel.WARNING),
warn: log(_loglevel.WARNING),
notice: log(_loglevel.NOTICE),
log: log(_loglevel.INFO),
info: log(_loglevel.INFO),
debug: log(_loglevel.DEBUG)
};
} | [
"function",
"exposeAPI",
"(",
"log",
")",
"{",
"return",
"{",
"emerg",
":",
"log",
"(",
"_loglevel",
".",
"EMERGENCY",
")",
",",
"emergency",
":",
"log",
"(",
"_loglevel",
".",
"EMERGENCY",
")",
",",
"alert",
":",
"log",
"(",
"_loglevel",
".",
"ALERT",
")",
",",
"crit",
":",
"log",
"(",
"_loglevel",
".",
"CRITICAL",
")",
",",
"critical",
":",
"log",
"(",
"_loglevel",
".",
"CRITICAL",
")",
",",
"error",
":",
"log",
"(",
"_loglevel",
".",
"ERROR",
")",
",",
"err",
":",
"log",
"(",
"_loglevel",
".",
"ERROR",
")",
",",
"warning",
":",
"log",
"(",
"_loglevel",
".",
"WARNING",
")",
",",
"warn",
":",
"log",
"(",
"_loglevel",
".",
"WARNING",
")",
",",
"notice",
":",
"log",
"(",
"_loglevel",
".",
"NOTICE",
")",
",",
"log",
":",
"log",
"(",
"_loglevel",
".",
"INFO",
")",
",",
"info",
":",
"log",
"(",
"_loglevel",
".",
"INFO",
")",
",",
"debug",
":",
"log",
"(",
"_loglevel",
".",
"DEBUG",
")",
"}",
";",
"}"
] | utility function to expose logging api | [
"utility",
"function",
"to",
"expose",
"logging",
"api"
] | 015ec21aca6b257a4fbbf3170474c2b96752958a | https://github.com/AndiDittrich/Node.Logging-Facility/blob/015ec21aca6b257a4fbbf3170474c2b96752958a/logging-facility.js#L13-L36 |
53,894 | AndiDittrich/Node.Logging-Facility | logging-facility.js | createLogger | function createLogger(instance){
// generator
function log(level){
return function(...args){
// logging backend available ?
if (_loggingBackends.length > 0){
// trigger backends
_loggingBackends.forEach(function(backend){
backend.apply(backend, [instance, level, args]);
});
// use default backend
}else{
_defaultBackend.apply(_defaultBackend, [instance, level, args]);
}
}
}
return exposeAPI(log);
} | javascript | function createLogger(instance){
// generator
function log(level){
return function(...args){
// logging backend available ?
if (_loggingBackends.length > 0){
// trigger backends
_loggingBackends.forEach(function(backend){
backend.apply(backend, [instance, level, args]);
});
// use default backend
}else{
_defaultBackend.apply(_defaultBackend, [instance, level, args]);
}
}
}
return exposeAPI(log);
} | [
"function",
"createLogger",
"(",
"instance",
")",
"{",
"// generator",
"function",
"log",
"(",
"level",
")",
"{",
"return",
"function",
"(",
"...",
"args",
")",
"{",
"// logging backend available ?",
"if",
"(",
"_loggingBackends",
".",
"length",
">",
"0",
")",
"{",
"// trigger backends",
"_loggingBackends",
".",
"forEach",
"(",
"function",
"(",
"backend",
")",
"{",
"backend",
".",
"apply",
"(",
"backend",
",",
"[",
"instance",
",",
"level",
",",
"args",
"]",
")",
";",
"}",
")",
";",
"// use default backend",
"}",
"else",
"{",
"_defaultBackend",
".",
"apply",
"(",
"_defaultBackend",
",",
"[",
"instance",
",",
"level",
",",
"args",
"]",
")",
";",
"}",
"}",
"}",
"return",
"exposeAPI",
"(",
"log",
")",
";",
"}"
] | generator to create the logging instance | [
"generator",
"to",
"create",
"the",
"logging",
"instance"
] | 015ec21aca6b257a4fbbf3170474c2b96752958a | https://github.com/AndiDittrich/Node.Logging-Facility/blob/015ec21aca6b257a4fbbf3170474c2b96752958a/logging-facility.js#L39-L61 |
53,895 | AndiDittrich/Node.Logging-Facility | logging-facility.js | getLogger | function getLogger(instance){
// create new instance if not available
if (!_loggerInstances[instance]){
_loggerInstances[instance] = createLogger(instance);
}
return _loggerInstances[instance];
} | javascript | function getLogger(instance){
// create new instance if not available
if (!_loggerInstances[instance]){
_loggerInstances[instance] = createLogger(instance);
}
return _loggerInstances[instance];
} | [
"function",
"getLogger",
"(",
"instance",
")",
"{",
"// create new instance if not available",
"if",
"(",
"!",
"_loggerInstances",
"[",
"instance",
"]",
")",
"{",
"_loggerInstances",
"[",
"instance",
"]",
"=",
"createLogger",
"(",
"instance",
")",
";",
"}",
"return",
"_loggerInstances",
"[",
"instance",
"]",
";",
"}"
] | utility function to fetch or create loggers by namespace | [
"utility",
"function",
"to",
"fetch",
"or",
"create",
"loggers",
"by",
"namespace"
] | 015ec21aca6b257a4fbbf3170474c2b96752958a | https://github.com/AndiDittrich/Node.Logging-Facility/blob/015ec21aca6b257a4fbbf3170474c2b96752958a/logging-facility.js#L64-L71 |
53,896 | AndiDittrich/Node.Logging-Facility | logging-facility.js | addLoggingBackend | function addLoggingBackend(backend, minLoglevel=99){
// function or string input supported
if (typeof backend === 'function'){
_loggingBackends.push(backend);
// lookup
}else{
if (backend === 'fancy-cli'){
_loggingBackends.push(_fancyCliLogger(minLoglevel));
}else if (backend === 'cli'){
_loggingBackends.push(_simpleCliLogger(minLoglevel));
}else{
throw new Error('Unknown backend <' + backend + '>');
}
}
} | javascript | function addLoggingBackend(backend, minLoglevel=99){
// function or string input supported
if (typeof backend === 'function'){
_loggingBackends.push(backend);
// lookup
}else{
if (backend === 'fancy-cli'){
_loggingBackends.push(_fancyCliLogger(minLoglevel));
}else if (backend === 'cli'){
_loggingBackends.push(_simpleCliLogger(minLoglevel));
}else{
throw new Error('Unknown backend <' + backend + '>');
}
}
} | [
"function",
"addLoggingBackend",
"(",
"backend",
",",
"minLoglevel",
"=",
"99",
")",
"{",
"// function or string input supported",
"if",
"(",
"typeof",
"backend",
"===",
"'function'",
")",
"{",
"_loggingBackends",
".",
"push",
"(",
"backend",
")",
";",
"// lookup",
"}",
"else",
"{",
"if",
"(",
"backend",
"===",
"'fancy-cli'",
")",
"{",
"_loggingBackends",
".",
"push",
"(",
"_fancyCliLogger",
"(",
"minLoglevel",
")",
")",
";",
"}",
"else",
"if",
"(",
"backend",
"===",
"'cli'",
")",
"{",
"_loggingBackends",
".",
"push",
"(",
"_simpleCliLogger",
"(",
"minLoglevel",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown backend <'",
"+",
"backend",
"+",
"'>'",
")",
";",
"}",
"}",
"}"
] | add multiple upstream backends | [
"add",
"multiple",
"upstream",
"backends"
] | 015ec21aca6b257a4fbbf3170474c2b96752958a | https://github.com/AndiDittrich/Node.Logging-Facility/blob/015ec21aca6b257a4fbbf3170474c2b96752958a/logging-facility.js#L74-L89 |
53,897 | spacemaus/postvox | vox-client/stanza-fetcher.js | StanzaFetcher | function StanzaFetcher(db, getInterchangeSession) {
var self = this;
self.db = db;
self._closed = false;
self.getInterchangeSession = getInterchangeSession;
self._highWaterMarks = new Chain(self._fetchMostRecentStanzaSeq.bind(self));
events.EventEmitter.call(this);
} | javascript | function StanzaFetcher(db, getInterchangeSession) {
var self = this;
self.db = db;
self._closed = false;
self.getInterchangeSession = getInterchangeSession;
self._highWaterMarks = new Chain(self._fetchMostRecentStanzaSeq.bind(self));
events.EventEmitter.call(this);
} | [
"function",
"StanzaFetcher",
"(",
"db",
",",
"getInterchangeSession",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"db",
"=",
"db",
";",
"self",
".",
"_closed",
"=",
"false",
";",
"self",
".",
"getInterchangeSession",
"=",
"getInterchangeSession",
";",
"self",
".",
"_highWaterMarks",
"=",
"new",
"Chain",
"(",
"self",
".",
"_fetchMostRecentStanzaSeq",
".",
"bind",
"(",
"self",
")",
")",
";",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"}"
] | Fetches stanzas from interchange servers. Also listens for interchange push
messages. | [
"Fetches",
"stanzas",
"from",
"interchange",
"servers",
".",
"Also",
"listens",
"for",
"interchange",
"push",
"messages",
"."
] | de98e5ed37edaee1b1edadf93e15eb8f8d21f457 | https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-client/stanza-fetcher.js#L15-L22 |
53,898 | pqml/dom | lib/render.js | render | function render (vnode, parent, context) {
// render
var i = 0
var rendered = rawRender(vnode)
// mount
if (typeof parent === 'function') {
var nodes = rendered.nodes.length < 2 ? rendered.nodes[0] : rendered.nodes
parent(nodes)
} else if (parent) {
for (i = 0; i < rendered.nodes.length; i++) {
parent.appendChild(rendered.nodes[i])
}
}
// dispatch callback refs and didmounts
var mockComponent = { _collector: rendered } // for dispatch convenience
dispatchRefs(mockComponent)
dispatch(mockComponent, function (c) {
c.mounted = true
c.componentDidMount && c.componentDidMount(c.props)
})
// Add items to context
if (context && context._collector) {
var c = context._collector
for (i = 0; i < rendered.components.length; i++) {
rendered.components[i]._parent = context
}
if (c.refs) c.refs = c.refs.concat(rendered.refs)
if (c.components) c.components = c.components.concat(rendered.components)
}
mockComponent = undefined
return rendered
} | javascript | function render (vnode, parent, context) {
// render
var i = 0
var rendered = rawRender(vnode)
// mount
if (typeof parent === 'function') {
var nodes = rendered.nodes.length < 2 ? rendered.nodes[0] : rendered.nodes
parent(nodes)
} else if (parent) {
for (i = 0; i < rendered.nodes.length; i++) {
parent.appendChild(rendered.nodes[i])
}
}
// dispatch callback refs and didmounts
var mockComponent = { _collector: rendered } // for dispatch convenience
dispatchRefs(mockComponent)
dispatch(mockComponent, function (c) {
c.mounted = true
c.componentDidMount && c.componentDidMount(c.props)
})
// Add items to context
if (context && context._collector) {
var c = context._collector
for (i = 0; i < rendered.components.length; i++) {
rendered.components[i]._parent = context
}
if (c.refs) c.refs = c.refs.concat(rendered.refs)
if (c.components) c.components = c.components.concat(rendered.components)
}
mockComponent = undefined
return rendered
} | [
"function",
"render",
"(",
"vnode",
",",
"parent",
",",
"context",
")",
"{",
"// render",
"var",
"i",
"=",
"0",
"var",
"rendered",
"=",
"rawRender",
"(",
"vnode",
")",
"// mount",
"if",
"(",
"typeof",
"parent",
"===",
"'function'",
")",
"{",
"var",
"nodes",
"=",
"rendered",
".",
"nodes",
".",
"length",
"<",
"2",
"?",
"rendered",
".",
"nodes",
"[",
"0",
"]",
":",
"rendered",
".",
"nodes",
"parent",
"(",
"nodes",
")",
"}",
"else",
"if",
"(",
"parent",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"rendered",
".",
"nodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"parent",
".",
"appendChild",
"(",
"rendered",
".",
"nodes",
"[",
"i",
"]",
")",
"}",
"}",
"// dispatch callback refs and didmounts",
"var",
"mockComponent",
"=",
"{",
"_collector",
":",
"rendered",
"}",
"// for dispatch convenience",
"dispatchRefs",
"(",
"mockComponent",
")",
"dispatch",
"(",
"mockComponent",
",",
"function",
"(",
"c",
")",
"{",
"c",
".",
"mounted",
"=",
"true",
"c",
".",
"componentDidMount",
"&&",
"c",
".",
"componentDidMount",
"(",
"c",
".",
"props",
")",
"}",
")",
"// Add items to context",
"if",
"(",
"context",
"&&",
"context",
".",
"_collector",
")",
"{",
"var",
"c",
"=",
"context",
".",
"_collector",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"rendered",
".",
"components",
".",
"length",
";",
"i",
"++",
")",
"{",
"rendered",
".",
"components",
"[",
"i",
"]",
".",
"_parent",
"=",
"context",
"}",
"if",
"(",
"c",
".",
"refs",
")",
"c",
".",
"refs",
"=",
"c",
".",
"refs",
".",
"concat",
"(",
"rendered",
".",
"refs",
")",
"if",
"(",
"c",
".",
"components",
")",
"c",
".",
"components",
"=",
"c",
".",
"components",
".",
"concat",
"(",
"rendered",
".",
"components",
")",
"}",
"mockComponent",
"=",
"undefined",
"return",
"rendered",
"}"
] | > Renders a virtual node and mount-it into a `parent` Element
> :warning: `render` always dispatch lifecycle events. Even if you don't pass a parent as 2nd argument, all componentDidMount methods and callback refs will be called. Be carreful!
> :warning: If you render a virtual node inside an already mounted component,
use its [component.render method](#Component+render) instead.
Otherwise, the rendered subcomponents and callback refs will not be register as "childs" of the parent component.
This can lead to bad lifecycle dispatching if you destroy the parent for instance.
@param {object} vnode A (JSX) VNode to render
@param {(HTMLElement|function)} [parent] DOM Element to render into. **You can also use a callback function:** the function will be called with DOM Elements to mount as first argument
@param {Component} [parentComponent] The parent component instance where the vnode will be mounted. You can directly use `parentComponent.render(vnode, parent)`
@return {object} Return an object containing:
- `result.nodes` : Array of rendered DOM nodes
- `result.components` : First-level components instances
- `result.refs` : First-level callback refs
@example
import { h, render } from '@internet/dom'
import App from 'components/App'
// Instanciate an App component and append it to document.body
render(<App />, document.body)
// Insert a new div into document.body, before the first child of document.body
render(<div>Some text</div>, div => {
document.body.insertBefore(div, document.body.firstChild)
}) | [
">",
"Renders",
"a",
"virtual",
"node",
"and",
"mount",
"-",
"it",
"into",
"a",
"parent",
"Element"
] | c9dfc7c8237f7662361fc635af4b1e1302260f44 | https://github.com/pqml/dom/blob/c9dfc7c8237f7662361fc635af4b1e1302260f44/lib/render.js#L37-L72 |
53,899 | iolo/express-toybox | errors.js | HttpError | function HttpError(message, status, cause) {
this.status = status || StatusCode.UNKNOWN;
HttpError.super_.call(this, errors.ErrorCode.HTTP + this.status, message || StatusLine[this.status] || StatusLine[StatusCode.UNKNOWN], cause);
} | javascript | function HttpError(message, status, cause) {
this.status = status || StatusCode.UNKNOWN;
HttpError.super_.call(this, errors.ErrorCode.HTTP + this.status, message || StatusLine[this.status] || StatusLine[StatusCode.UNKNOWN], cause);
} | [
"function",
"HttpError",
"(",
"message",
",",
"status",
",",
"cause",
")",
"{",
"this",
".",
"status",
"=",
"status",
"||",
"StatusCode",
".",
"UNKNOWN",
";",
"HttpError",
".",
"super_",
".",
"call",
"(",
"this",
",",
"errors",
".",
"ErrorCode",
".",
"HTTP",
"+",
"this",
".",
"status",
",",
"message",
"||",
"StatusLine",
"[",
"this",
".",
"status",
"]",
"||",
"StatusLine",
"[",
"StatusCode",
".",
"UNKNOWN",
"]",
",",
"cause",
")",
";",
"}"
] | abstract superclass for HTTP specific error.
@param {String} [message]
@param {Number} [status=599]
@param {*} [cause]
@constructor
@abstract
@memberOf errors | [
"abstract",
"superclass",
"for",
"HTTP",
"specific",
"error",
"."
] | c375a1388cfc167017e8dcd2325e71ca86ccb994 | https://github.com/iolo/express-toybox/blob/c375a1388cfc167017e8dcd2325e71ca86ccb994/errors.js#L59-L62 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.