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
|
---|---|---|---|---|---|---|---|---|---|---|---|
52,900 | GregBee2/xassist-csv | src/csv.js | checkCRLF | function checkCRLF() {
/*function check if the current character is NEWLINE or RETURN
if RETURN it checks if the next is NEWLINE (CRLF)
afterwards it sets the charIndex after the NEWLINE, RETURN OR CRLF and currentCharacter to the character at index charIndex*/
//check if current character at charIndex is NEWLINE (set eol)
//adds 1 to charIndex
if ((currentCharacter = text.charCodeAt(charIndex++)) === NEWLINE)
eol = true;
//checks if equal to RETURN
else if (currentCharacter === RETURN) {
eol = true;
//checks next character equal to NEWLINE and adds 1 to charindex (total =2)
if (text.charCodeAt(charIndex) === NEWLINE)
++charIndex;
}
return eol;
} | javascript | function checkCRLF() {
/*function check if the current character is NEWLINE or RETURN
if RETURN it checks if the next is NEWLINE (CRLF)
afterwards it sets the charIndex after the NEWLINE, RETURN OR CRLF and currentCharacter to the character at index charIndex*/
//check if current character at charIndex is NEWLINE (set eol)
//adds 1 to charIndex
if ((currentCharacter = text.charCodeAt(charIndex++)) === NEWLINE)
eol = true;
//checks if equal to RETURN
else if (currentCharacter === RETURN) {
eol = true;
//checks next character equal to NEWLINE and adds 1 to charindex (total =2)
if (text.charCodeAt(charIndex) === NEWLINE)
++charIndex;
}
return eol;
} | [
"function",
"checkCRLF",
"(",
")",
"{",
"/*function check if the current character is NEWLINE or RETURN\n\t\t\t\tif RETURN it checks if the next is NEWLINE (CRLF)\n\t\t\t\tafterwards it sets the charIndex after the NEWLINE, RETURN OR CRLF and currentCharacter to the character at index charIndex*/",
"//check if current character at charIndex is NEWLINE (set eol)",
"//adds 1 to charIndex",
"if",
"(",
"(",
"currentCharacter",
"=",
"text",
".",
"charCodeAt",
"(",
"charIndex",
"++",
")",
")",
"===",
"NEWLINE",
")",
"eol",
"=",
"true",
";",
"//checks if equal to RETURN",
"else",
"if",
"(",
"currentCharacter",
"===",
"RETURN",
")",
"{",
"eol",
"=",
"true",
";",
"//checks next character equal to NEWLINE and adds 1 to charindex (total =2)",
"if",
"(",
"text",
".",
"charCodeAt",
"(",
"charIndex",
")",
"===",
"NEWLINE",
")",
"++",
"charIndex",
";",
"}",
"return",
"eol",
";",
"}"
] | Unescape quotes. | [
"Unescape",
"quotes",
"."
] | a80619da9d0bff5af1cd503ad0b9697667548b5e | https://github.com/GregBee2/xassist-csv/blob/a80619da9d0bff5af1cd503ad0b9697667548b5e/src/csv.js#L270-L286 |
52,901 | redisjs/jsr-server | lib/command/database/key/rename.js | validate | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var source = '' + args[0]
, destination = '' + args[1];
if(!info.db.getKey(args[0], info)) {
throw NoSuchKey;
}else if(source === destination) {
throw SourceDestination;
}
args[0] = source;
args[1] = destination;
} | javascript | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var source = '' + args[0]
, destination = '' + args[1];
if(!info.db.getKey(args[0], info)) {
throw NoSuchKey;
}else if(source === destination) {
throw SourceDestination;
}
args[0] = source;
args[1] = destination;
} | [
"function",
"validate",
"(",
"cmd",
",",
"args",
",",
"info",
")",
"{",
"AbstractCommand",
".",
"prototype",
".",
"validate",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"var",
"source",
"=",
"''",
"+",
"args",
"[",
"0",
"]",
",",
"destination",
"=",
"''",
"+",
"args",
"[",
"1",
"]",
";",
"if",
"(",
"!",
"info",
".",
"db",
".",
"getKey",
"(",
"args",
"[",
"0",
"]",
",",
"info",
")",
")",
"{",
"throw",
"NoSuchKey",
";",
"}",
"else",
"if",
"(",
"source",
"===",
"destination",
")",
"{",
"throw",
"SourceDestination",
";",
"}",
"args",
"[",
"0",
"]",
"=",
"source",
";",
"args",
"[",
"1",
"]",
"=",
"destination",
";",
"}"
] | Validate the RENAME command. | [
"Validate",
"the",
"RENAME",
"command",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/database/key/rename.js#L20-L33 |
52,902 | andrewscwei/requiem | src/utils/getIntersectRect.js | getIntersectRect | function getIntersectRect() {
let n = arguments.length;
if (!assert(n > 0, 'This method requires at least 1 argument specified.')) return null;
let rect = {};
let currRect, nextRect;
for (let i = 0; i < n; i++) {
if (!currRect) currRect = getRect(arguments[i]);
if (!assert(currRect, 'Invalid computed rect.')) return null;
if (i === 0 && ((i + 1) === n)) {
nextRect = getRect(window);
}
else if ((i + 1) < n) {
nextRect = getRect(arguments[i + 1]);
}
else {
break;
}
if (!assert(nextRect, 'Invalid computed rect.')) return null;
rect.width = Math.max(0.0, Math.min(currRect.right, nextRect.right) - Math.max(currRect.left, nextRect.left));
rect.height = Math.max(0.0, Math.min(currRect.bottom, nextRect.bottom) - Math.max(currRect.top, nextRect.top));
rect.top = Math.max(currRect.top, nextRect.top);
rect.left = Math.max(currRect.left, nextRect.left);
rect.bottom = rect.top + rect.height;
rect.right = rect.left + rect.width;
if (rect.width * rect.height === 0) {
rect.width = 0;
rect.height = 0;
rect.top = 0;
rect.left = 0;
rect.bottom = 0;
rect.right = 0;
}
currRect = rect;
}
return rect;
} | javascript | function getIntersectRect() {
let n = arguments.length;
if (!assert(n > 0, 'This method requires at least 1 argument specified.')) return null;
let rect = {};
let currRect, nextRect;
for (let i = 0; i < n; i++) {
if (!currRect) currRect = getRect(arguments[i]);
if (!assert(currRect, 'Invalid computed rect.')) return null;
if (i === 0 && ((i + 1) === n)) {
nextRect = getRect(window);
}
else if ((i + 1) < n) {
nextRect = getRect(arguments[i + 1]);
}
else {
break;
}
if (!assert(nextRect, 'Invalid computed rect.')) return null;
rect.width = Math.max(0.0, Math.min(currRect.right, nextRect.right) - Math.max(currRect.left, nextRect.left));
rect.height = Math.max(0.0, Math.min(currRect.bottom, nextRect.bottom) - Math.max(currRect.top, nextRect.top));
rect.top = Math.max(currRect.top, nextRect.top);
rect.left = Math.max(currRect.left, nextRect.left);
rect.bottom = rect.top + rect.height;
rect.right = rect.left + rect.width;
if (rect.width * rect.height === 0) {
rect.width = 0;
rect.height = 0;
rect.top = 0;
rect.left = 0;
rect.bottom = 0;
rect.right = 0;
}
currRect = rect;
}
return rect;
} | [
"function",
"getIntersectRect",
"(",
")",
"{",
"let",
"n",
"=",
"arguments",
".",
"length",
";",
"if",
"(",
"!",
"assert",
"(",
"n",
">",
"0",
",",
"'This method requires at least 1 argument specified.'",
")",
")",
"return",
"null",
";",
"let",
"rect",
"=",
"{",
"}",
";",
"let",
"currRect",
",",
"nextRect",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"currRect",
")",
"currRect",
"=",
"getRect",
"(",
"arguments",
"[",
"i",
"]",
")",
";",
"if",
"(",
"!",
"assert",
"(",
"currRect",
",",
"'Invalid computed rect.'",
")",
")",
"return",
"null",
";",
"if",
"(",
"i",
"===",
"0",
"&&",
"(",
"(",
"i",
"+",
"1",
")",
"===",
"n",
")",
")",
"{",
"nextRect",
"=",
"getRect",
"(",
"window",
")",
";",
"}",
"else",
"if",
"(",
"(",
"i",
"+",
"1",
")",
"<",
"n",
")",
"{",
"nextRect",
"=",
"getRect",
"(",
"arguments",
"[",
"i",
"+",
"1",
"]",
")",
";",
"}",
"else",
"{",
"break",
";",
"}",
"if",
"(",
"!",
"assert",
"(",
"nextRect",
",",
"'Invalid computed rect.'",
")",
")",
"return",
"null",
";",
"rect",
".",
"width",
"=",
"Math",
".",
"max",
"(",
"0.0",
",",
"Math",
".",
"min",
"(",
"currRect",
".",
"right",
",",
"nextRect",
".",
"right",
")",
"-",
"Math",
".",
"max",
"(",
"currRect",
".",
"left",
",",
"nextRect",
".",
"left",
")",
")",
";",
"rect",
".",
"height",
"=",
"Math",
".",
"max",
"(",
"0.0",
",",
"Math",
".",
"min",
"(",
"currRect",
".",
"bottom",
",",
"nextRect",
".",
"bottom",
")",
"-",
"Math",
".",
"max",
"(",
"currRect",
".",
"top",
",",
"nextRect",
".",
"top",
")",
")",
";",
"rect",
".",
"top",
"=",
"Math",
".",
"max",
"(",
"currRect",
".",
"top",
",",
"nextRect",
".",
"top",
")",
";",
"rect",
".",
"left",
"=",
"Math",
".",
"max",
"(",
"currRect",
".",
"left",
",",
"nextRect",
".",
"left",
")",
";",
"rect",
".",
"bottom",
"=",
"rect",
".",
"top",
"+",
"rect",
".",
"height",
";",
"rect",
".",
"right",
"=",
"rect",
".",
"left",
"+",
"rect",
".",
"width",
";",
"if",
"(",
"rect",
".",
"width",
"*",
"rect",
".",
"height",
"===",
"0",
")",
"{",
"rect",
".",
"width",
"=",
"0",
";",
"rect",
".",
"height",
"=",
"0",
";",
"rect",
".",
"top",
"=",
"0",
";",
"rect",
".",
"left",
"=",
"0",
";",
"rect",
".",
"bottom",
"=",
"0",
";",
"rect",
".",
"right",
"=",
"0",
";",
"}",
"currRect",
"=",
"rect",
";",
"}",
"return",
"rect",
";",
"}"
] | Computes the intersecting rect of 2 given elements. If only 1 element is
specified, the other element will default to the current viewport.
@param {...Node}
@return {Object} Object containing width, height.
@alias module:requiem~utils.getIntersectRect | [
"Computes",
"the",
"intersecting",
"rect",
"of",
"2",
"given",
"elements",
".",
"If",
"only",
"1",
"element",
"is",
"specified",
"the",
"other",
"element",
"will",
"default",
"to",
"the",
"current",
"viewport",
"."
] | c4182bfffc9841c6de5718f689ad3c2060511777 | https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/utils/getIntersectRect.js#L18-L63 |
52,903 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | executeInitiateBatchTask | function executeInitiateBatchTask(batch, cancellable, context) {
/**
* Defines the initiate batch task (and its sub-tasks) to be used to track the state of the initiating phase.
* @returns {InitiateBatchTaskDef} a new initiate batch task definition (with its sub-task definitions)
*/
function defineInitiateBatchTask() {
const taskDef = TaskDef.defineTask(initiateBatch.name, initiateBatch, batchAndCancellableSettings);
taskDef.defineSubTask(extractAndSequenceMessages.name, extractAndSequenceMessages, batchSettings);
taskDef.defineSubTask(loadBatchState.name, loadBatchState, batchSettings);
taskDef.defineSubTask(reviveTasks.name, reviveTasks, batchSettings);
taskDef.defineSubTask(preProcessBatch.name, preProcessBatch, batchSettings);
return taskDef;
}
/**
* Creates a new initiate batch task to be used to initiate the batch and to track the state of the initiating
* (pre-processing) phase.
* @param {Batch} batch - the batch to be initiated
* @param {StreamConsumerContext} context - the context to use
* @returns {InitiateBatchTask} a new initiate batch task (with sub-tasks)
*/
function createInitiateBatchTask(batch, context) {
// Define a new initiate batch task definition for the batch & update the batch with it
batch.taskDefs.initiateTaskDef = defineInitiateBatchTask();
// Create a new initiate batch task (and all of its sub-tasks) from the task definition
const task = context.taskFactory.createTask(batch.taskDefs.initiateTaskDef, initiateTaskOpts);
// Cache it on the batch
const initiatingTasks = batch.getOrSetInitiatingTasks();
initiatingTasks[task.name] = task;
return task;
}
// Create a new initiate batch task to handle and track the state of the initiating phase
const initiateBatchTask = createInitiateBatchTask(batch, context);
// Initiate the batch
const p = initiateBatchTask.execute(batch, cancellable, context);
// Terminate the initiate batch task with its first Failure outcome (if any); otherwise return its successful values
return whenDone(initiateBatchTask, p, cancellable, context);
// const donePromise = whenDone(initiateBatchTask, p, cancellable, context);
// handleUnhandledRejections([p, donePromise], context);
// return donePromise;
} | javascript | function executeInitiateBatchTask(batch, cancellable, context) {
/**
* Defines the initiate batch task (and its sub-tasks) to be used to track the state of the initiating phase.
* @returns {InitiateBatchTaskDef} a new initiate batch task definition (with its sub-task definitions)
*/
function defineInitiateBatchTask() {
const taskDef = TaskDef.defineTask(initiateBatch.name, initiateBatch, batchAndCancellableSettings);
taskDef.defineSubTask(extractAndSequenceMessages.name, extractAndSequenceMessages, batchSettings);
taskDef.defineSubTask(loadBatchState.name, loadBatchState, batchSettings);
taskDef.defineSubTask(reviveTasks.name, reviveTasks, batchSettings);
taskDef.defineSubTask(preProcessBatch.name, preProcessBatch, batchSettings);
return taskDef;
}
/**
* Creates a new initiate batch task to be used to initiate the batch and to track the state of the initiating
* (pre-processing) phase.
* @param {Batch} batch - the batch to be initiated
* @param {StreamConsumerContext} context - the context to use
* @returns {InitiateBatchTask} a new initiate batch task (with sub-tasks)
*/
function createInitiateBatchTask(batch, context) {
// Define a new initiate batch task definition for the batch & update the batch with it
batch.taskDefs.initiateTaskDef = defineInitiateBatchTask();
// Create a new initiate batch task (and all of its sub-tasks) from the task definition
const task = context.taskFactory.createTask(batch.taskDefs.initiateTaskDef, initiateTaskOpts);
// Cache it on the batch
const initiatingTasks = batch.getOrSetInitiatingTasks();
initiatingTasks[task.name] = task;
return task;
}
// Create a new initiate batch task to handle and track the state of the initiating phase
const initiateBatchTask = createInitiateBatchTask(batch, context);
// Initiate the batch
const p = initiateBatchTask.execute(batch, cancellable, context);
// Terminate the initiate batch task with its first Failure outcome (if any); otherwise return its successful values
return whenDone(initiateBatchTask, p, cancellable, context);
// const donePromise = whenDone(initiateBatchTask, p, cancellable, context);
// handleUnhandledRejections([p, donePromise], context);
// return donePromise;
} | [
"function",
"executeInitiateBatchTask",
"(",
"batch",
",",
"cancellable",
",",
"context",
")",
"{",
"/**\n * Defines the initiate batch task (and its sub-tasks) to be used to track the state of the initiating phase.\n * @returns {InitiateBatchTaskDef} a new initiate batch task definition (with its sub-task definitions)\n */",
"function",
"defineInitiateBatchTask",
"(",
")",
"{",
"const",
"taskDef",
"=",
"TaskDef",
".",
"defineTask",
"(",
"initiateBatch",
".",
"name",
",",
"initiateBatch",
",",
"batchAndCancellableSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"extractAndSequenceMessages",
".",
"name",
",",
"extractAndSequenceMessages",
",",
"batchSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"loadBatchState",
".",
"name",
",",
"loadBatchState",
",",
"batchSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"reviveTasks",
".",
"name",
",",
"reviveTasks",
",",
"batchSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"preProcessBatch",
".",
"name",
",",
"preProcessBatch",
",",
"batchSettings",
")",
";",
"return",
"taskDef",
";",
"}",
"/**\n * Creates a new initiate batch task to be used to initiate the batch and to track the state of the initiating\n * (pre-processing) phase.\n * @param {Batch} batch - the batch to be initiated\n * @param {StreamConsumerContext} context - the context to use\n * @returns {InitiateBatchTask} a new initiate batch task (with sub-tasks)\n */",
"function",
"createInitiateBatchTask",
"(",
"batch",
",",
"context",
")",
"{",
"// Define a new initiate batch task definition for the batch & update the batch with it",
"batch",
".",
"taskDefs",
".",
"initiateTaskDef",
"=",
"defineInitiateBatchTask",
"(",
")",
";",
"// Create a new initiate batch task (and all of its sub-tasks) from the task definition",
"const",
"task",
"=",
"context",
".",
"taskFactory",
".",
"createTask",
"(",
"batch",
".",
"taskDefs",
".",
"initiateTaskDef",
",",
"initiateTaskOpts",
")",
";",
"// Cache it on the batch",
"const",
"initiatingTasks",
"=",
"batch",
".",
"getOrSetInitiatingTasks",
"(",
")",
";",
"initiatingTasks",
"[",
"task",
".",
"name",
"]",
"=",
"task",
";",
"return",
"task",
";",
"}",
"// Create a new initiate batch task to handle and track the state of the initiating phase",
"const",
"initiateBatchTask",
"=",
"createInitiateBatchTask",
"(",
"batch",
",",
"context",
")",
";",
"// Initiate the batch",
"const",
"p",
"=",
"initiateBatchTask",
".",
"execute",
"(",
"batch",
",",
"cancellable",
",",
"context",
")",
";",
"// Terminate the initiate batch task with its first Failure outcome (if any); otherwise return its successful values",
"return",
"whenDone",
"(",
"initiateBatchTask",
",",
"p",
",",
"cancellable",
",",
"context",
")",
";",
"// const donePromise = whenDone(initiateBatchTask, p, cancellable, context);",
"// handleUnhandledRejections([p, donePromise], context);",
"// return donePromise;",
"}"
] | Creates and executes a new initiate batch task on the given batch.
@param {Batch} batch - the batch to be initiated
@param {Cancellable|Object|undefined} [cancellable] - a cancellable object onto which to install cancel functionality
@param {StreamConsumerContext} context - the context to use
@returns {Promise.<Batch>} a promise that will resolve with the updated batch when the initiate batch task's execution completes | [
"Creates",
"and",
"executes",
"a",
"new",
"initiate",
"batch",
"task",
"on",
"the",
"given",
"batch",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L191-L237 |
52,904 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | executeProcessBatchTask | function executeProcessBatchTask(batch, cancellable, context) {
/**
* Defines the process batch task (and its sub-tasks) to be used to track the state of the processing phase.
* @returns {ProcessBatchTaskDef} a new process batch task definition (with its sub-task definitions)
*/
function defineProcessBatchTask() {
const taskDef = TaskDef.defineTask(processBatch.name, processBatch, batchAndCancellableSettings);
taskDef.defineSubTask(executeAllProcessOneTasks.name, executeAllProcessOneTasks, batchAndCancellableSettings);
taskDef.defineSubTask(executeAllProcessAllTasks.name, executeAllProcessAllTasks, batchAndCancellableSettings);
taskDef.defineSubTask(discardUnusableRecords.name, discardUnusableRecords, batchAndUnusableRecordsSettings);
taskDef.defineSubTask(preFinaliseBatch.name, preFinaliseBatch, batchSettings);
return taskDef;
}
/**
* Creates a new process batch task to be used to process the batch and to strack the state of the processing phase.
* @param {Batch} batch - the batch to be processed
* @param {StreamConsumerContext} context - the context to use
* @returns {ProcessBatchTask} a new process batch task (with sub-tasks)
*/
function createProcessBatchTask(batch, context) {
// Define a new process task definition for the batch & updates the batch with it
batch.taskDefs.processTaskDef = defineProcessBatchTask();
const task = context.taskFactory.createTask(batch.taskDefs.processTaskDef, processTaskOpts);
// Cache it on the batch
const processingTasks = batch.getOrSetProcessingTasks();
processingTasks[task.name] = task;
return task;
}
// Create a new process batch task to handle and track the state of the processing phase
const processBatchTask = createProcessBatchTask(batch, context);
// Process the batch
const p = processBatchTask.execute(batch, cancellable, context);
return whenDone(processBatchTask, p, cancellable, context);
// const donePromise = whenDone(processBatchTask, p, cancellable, context);
// handleUnhandledRejections([p, donePromise], context);
// return donePromise;
} | javascript | function executeProcessBatchTask(batch, cancellable, context) {
/**
* Defines the process batch task (and its sub-tasks) to be used to track the state of the processing phase.
* @returns {ProcessBatchTaskDef} a new process batch task definition (with its sub-task definitions)
*/
function defineProcessBatchTask() {
const taskDef = TaskDef.defineTask(processBatch.name, processBatch, batchAndCancellableSettings);
taskDef.defineSubTask(executeAllProcessOneTasks.name, executeAllProcessOneTasks, batchAndCancellableSettings);
taskDef.defineSubTask(executeAllProcessAllTasks.name, executeAllProcessAllTasks, batchAndCancellableSettings);
taskDef.defineSubTask(discardUnusableRecords.name, discardUnusableRecords, batchAndUnusableRecordsSettings);
taskDef.defineSubTask(preFinaliseBatch.name, preFinaliseBatch, batchSettings);
return taskDef;
}
/**
* Creates a new process batch task to be used to process the batch and to strack the state of the processing phase.
* @param {Batch} batch - the batch to be processed
* @param {StreamConsumerContext} context - the context to use
* @returns {ProcessBatchTask} a new process batch task (with sub-tasks)
*/
function createProcessBatchTask(batch, context) {
// Define a new process task definition for the batch & updates the batch with it
batch.taskDefs.processTaskDef = defineProcessBatchTask();
const task = context.taskFactory.createTask(batch.taskDefs.processTaskDef, processTaskOpts);
// Cache it on the batch
const processingTasks = batch.getOrSetProcessingTasks();
processingTasks[task.name] = task;
return task;
}
// Create a new process batch task to handle and track the state of the processing phase
const processBatchTask = createProcessBatchTask(batch, context);
// Process the batch
const p = processBatchTask.execute(batch, cancellable, context);
return whenDone(processBatchTask, p, cancellable, context);
// const donePromise = whenDone(processBatchTask, p, cancellable, context);
// handleUnhandledRejections([p, donePromise], context);
// return donePromise;
} | [
"function",
"executeProcessBatchTask",
"(",
"batch",
",",
"cancellable",
",",
"context",
")",
"{",
"/**\n * Defines the process batch task (and its sub-tasks) to be used to track the state of the processing phase.\n * @returns {ProcessBatchTaskDef} a new process batch task definition (with its sub-task definitions)\n */",
"function",
"defineProcessBatchTask",
"(",
")",
"{",
"const",
"taskDef",
"=",
"TaskDef",
".",
"defineTask",
"(",
"processBatch",
".",
"name",
",",
"processBatch",
",",
"batchAndCancellableSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"executeAllProcessOneTasks",
".",
"name",
",",
"executeAllProcessOneTasks",
",",
"batchAndCancellableSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"executeAllProcessAllTasks",
".",
"name",
",",
"executeAllProcessAllTasks",
",",
"batchAndCancellableSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"discardUnusableRecords",
".",
"name",
",",
"discardUnusableRecords",
",",
"batchAndUnusableRecordsSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"preFinaliseBatch",
".",
"name",
",",
"preFinaliseBatch",
",",
"batchSettings",
")",
";",
"return",
"taskDef",
";",
"}",
"/**\n * Creates a new process batch task to be used to process the batch and to strack the state of the processing phase.\n * @param {Batch} batch - the batch to be processed\n * @param {StreamConsumerContext} context - the context to use\n * @returns {ProcessBatchTask} a new process batch task (with sub-tasks)\n */",
"function",
"createProcessBatchTask",
"(",
"batch",
",",
"context",
")",
"{",
"// Define a new process task definition for the batch & updates the batch with it",
"batch",
".",
"taskDefs",
".",
"processTaskDef",
"=",
"defineProcessBatchTask",
"(",
")",
";",
"const",
"task",
"=",
"context",
".",
"taskFactory",
".",
"createTask",
"(",
"batch",
".",
"taskDefs",
".",
"processTaskDef",
",",
"processTaskOpts",
")",
";",
"// Cache it on the batch",
"const",
"processingTasks",
"=",
"batch",
".",
"getOrSetProcessingTasks",
"(",
")",
";",
"processingTasks",
"[",
"task",
".",
"name",
"]",
"=",
"task",
";",
"return",
"task",
";",
"}",
"// Create a new process batch task to handle and track the state of the processing phase",
"const",
"processBatchTask",
"=",
"createProcessBatchTask",
"(",
"batch",
",",
"context",
")",
";",
"// Process the batch",
"const",
"p",
"=",
"processBatchTask",
".",
"execute",
"(",
"batch",
",",
"cancellable",
",",
"context",
")",
";",
"return",
"whenDone",
"(",
"processBatchTask",
",",
"p",
",",
"cancellable",
",",
"context",
")",
";",
"// const donePromise = whenDone(processBatchTask, p, cancellable, context);",
"// handleUnhandledRejections([p, donePromise], context);",
"// return donePromise;",
"}"
] | Creates and executes a new process batch task on the given batch.
@param {Batch} batch - the batch to be processed
@param {Cancellable|Object|undefined} [cancellable] - a cancellable object onto which to install cancel functionality
@param {StreamConsumerContext} context - the context to use
@returns {Promise.<Outcomes>} a promise that will resolve with the outcomes of the process batch task's execution | [
"Creates",
"and",
"executes",
"a",
"new",
"process",
"batch",
"task",
"on",
"the",
"given",
"batch",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L246-L288 |
52,905 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | createProcessBatchTask | function createProcessBatchTask(batch, context) {
// Define a new process task definition for the batch & updates the batch with it
batch.taskDefs.processTaskDef = defineProcessBatchTask();
const task = context.taskFactory.createTask(batch.taskDefs.processTaskDef, processTaskOpts);
// Cache it on the batch
const processingTasks = batch.getOrSetProcessingTasks();
processingTasks[task.name] = task;
return task;
} | javascript | function createProcessBatchTask(batch, context) {
// Define a new process task definition for the batch & updates the batch with it
batch.taskDefs.processTaskDef = defineProcessBatchTask();
const task = context.taskFactory.createTask(batch.taskDefs.processTaskDef, processTaskOpts);
// Cache it on the batch
const processingTasks = batch.getOrSetProcessingTasks();
processingTasks[task.name] = task;
return task;
} | [
"function",
"createProcessBatchTask",
"(",
"batch",
",",
"context",
")",
"{",
"// Define a new process task definition for the batch & updates the batch with it",
"batch",
".",
"taskDefs",
".",
"processTaskDef",
"=",
"defineProcessBatchTask",
"(",
")",
";",
"const",
"task",
"=",
"context",
".",
"taskFactory",
".",
"createTask",
"(",
"batch",
".",
"taskDefs",
".",
"processTaskDef",
",",
"processTaskOpts",
")",
";",
"// Cache it on the batch",
"const",
"processingTasks",
"=",
"batch",
".",
"getOrSetProcessingTasks",
"(",
")",
";",
"processingTasks",
"[",
"task",
".",
"name",
"]",
"=",
"task",
";",
"return",
"task",
";",
"}"
] | Creates a new process batch task to be used to process the batch and to strack the state of the processing phase.
@param {Batch} batch - the batch to be processed
@param {StreamConsumerContext} context - the context to use
@returns {ProcessBatchTask} a new process batch task (with sub-tasks) | [
"Creates",
"a",
"new",
"process",
"batch",
"task",
"to",
"be",
"used",
"to",
"process",
"the",
"batch",
"and",
"to",
"strack",
"the",
"state",
"of",
"the",
"processing",
"phase",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L266-L277 |
52,906 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | executeFinaliseBatchTask | function executeFinaliseBatchTask(batch, processOutcomes, cancellable, context) {
/**
* Defines the finalise batch task (and its sub-tasks) to be used to track the state of the finalising phase.
* @returns {FinaliseBatchTaskDef} a new finalise batch task definition (with its sub-task definitions)
*/
function defineFinaliseBatchTask() {
const taskDef = TaskDef.defineTask(finaliseBatch.name, finaliseBatch, batchAndProcessOutcomesSettings);
taskDef.defineSubTask(discardAnyRejectedMessages.name, discardAnyRejectedMessages, batchAndCancellableSettings);
taskDef.defineSubTask(saveBatchState.name, saveBatchState, batchSettings);
taskDef.defineSubTask(postFinaliseBatch.name, postFinaliseBatch, batchSettings);
return taskDef;
}
/**
* Creates a new finalise batch task to be used to finalise the batch and to track the state of the finalising phase.
* @param {Batch} batch - the batch to be processed
* @param {StreamConsumerContext} context - the context to use
* @returns {FinaliseBatchTask} a new finalise batch task (with sub-tasks)
*/
function createFinaliseBatchTask(batch, context) {
// Define a new finalise task definition for the batch & updates the batch with it
batch.taskDefs.finaliseTaskDef = defineFinaliseBatchTask();
const task = context.taskFactory.createTask(batch.taskDefs.finaliseTaskDef, finaliseTaskOpts);
// Cache it on the batch
const finalisingTasks = batch.getOrSetFinalisingTasks();
finalisingTasks[task.name] = task;
return task;
}
// Create a new finalise batch task to handle and track the state of the finalising phase
const finaliseBatchTask = createFinaliseBatchTask(batch, context);
// Regardless of whether processing completes or times out, finalise the batch as best as possible
const p = finaliseBatchTask.execute(batch, processOutcomes, cancellable, context);
return whenDone(finaliseBatchTask, p, cancellable, context).then(() => batch);
} | javascript | function executeFinaliseBatchTask(batch, processOutcomes, cancellable, context) {
/**
* Defines the finalise batch task (and its sub-tasks) to be used to track the state of the finalising phase.
* @returns {FinaliseBatchTaskDef} a new finalise batch task definition (with its sub-task definitions)
*/
function defineFinaliseBatchTask() {
const taskDef = TaskDef.defineTask(finaliseBatch.name, finaliseBatch, batchAndProcessOutcomesSettings);
taskDef.defineSubTask(discardAnyRejectedMessages.name, discardAnyRejectedMessages, batchAndCancellableSettings);
taskDef.defineSubTask(saveBatchState.name, saveBatchState, batchSettings);
taskDef.defineSubTask(postFinaliseBatch.name, postFinaliseBatch, batchSettings);
return taskDef;
}
/**
* Creates a new finalise batch task to be used to finalise the batch and to track the state of the finalising phase.
* @param {Batch} batch - the batch to be processed
* @param {StreamConsumerContext} context - the context to use
* @returns {FinaliseBatchTask} a new finalise batch task (with sub-tasks)
*/
function createFinaliseBatchTask(batch, context) {
// Define a new finalise task definition for the batch & updates the batch with it
batch.taskDefs.finaliseTaskDef = defineFinaliseBatchTask();
const task = context.taskFactory.createTask(batch.taskDefs.finaliseTaskDef, finaliseTaskOpts);
// Cache it on the batch
const finalisingTasks = batch.getOrSetFinalisingTasks();
finalisingTasks[task.name] = task;
return task;
}
// Create a new finalise batch task to handle and track the state of the finalising phase
const finaliseBatchTask = createFinaliseBatchTask(batch, context);
// Regardless of whether processing completes or times out, finalise the batch as best as possible
const p = finaliseBatchTask.execute(batch, processOutcomes, cancellable, context);
return whenDone(finaliseBatchTask, p, cancellable, context).then(() => batch);
} | [
"function",
"executeFinaliseBatchTask",
"(",
"batch",
",",
"processOutcomes",
",",
"cancellable",
",",
"context",
")",
"{",
"/**\n * Defines the finalise batch task (and its sub-tasks) to be used to track the state of the finalising phase.\n * @returns {FinaliseBatchTaskDef} a new finalise batch task definition (with its sub-task definitions)\n */",
"function",
"defineFinaliseBatchTask",
"(",
")",
"{",
"const",
"taskDef",
"=",
"TaskDef",
".",
"defineTask",
"(",
"finaliseBatch",
".",
"name",
",",
"finaliseBatch",
",",
"batchAndProcessOutcomesSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"discardAnyRejectedMessages",
".",
"name",
",",
"discardAnyRejectedMessages",
",",
"batchAndCancellableSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"saveBatchState",
".",
"name",
",",
"saveBatchState",
",",
"batchSettings",
")",
";",
"taskDef",
".",
"defineSubTask",
"(",
"postFinaliseBatch",
".",
"name",
",",
"postFinaliseBatch",
",",
"batchSettings",
")",
";",
"return",
"taskDef",
";",
"}",
"/**\n * Creates a new finalise batch task to be used to finalise the batch and to track the state of the finalising phase.\n * @param {Batch} batch - the batch to be processed\n * @param {StreamConsumerContext} context - the context to use\n * @returns {FinaliseBatchTask} a new finalise batch task (with sub-tasks)\n */",
"function",
"createFinaliseBatchTask",
"(",
"batch",
",",
"context",
")",
"{",
"// Define a new finalise task definition for the batch & updates the batch with it",
"batch",
".",
"taskDefs",
".",
"finaliseTaskDef",
"=",
"defineFinaliseBatchTask",
"(",
")",
";",
"const",
"task",
"=",
"context",
".",
"taskFactory",
".",
"createTask",
"(",
"batch",
".",
"taskDefs",
".",
"finaliseTaskDef",
",",
"finaliseTaskOpts",
")",
";",
"// Cache it on the batch",
"const",
"finalisingTasks",
"=",
"batch",
".",
"getOrSetFinalisingTasks",
"(",
")",
";",
"finalisingTasks",
"[",
"task",
".",
"name",
"]",
"=",
"task",
";",
"return",
"task",
";",
"}",
"// Create a new finalise batch task to handle and track the state of the finalising phase",
"const",
"finaliseBatchTask",
"=",
"createFinaliseBatchTask",
"(",
"batch",
",",
"context",
")",
";",
"// Regardless of whether processing completes or times out, finalise the batch as best as possible",
"const",
"p",
"=",
"finaliseBatchTask",
".",
"execute",
"(",
"batch",
",",
"processOutcomes",
",",
"cancellable",
",",
"context",
")",
";",
"return",
"whenDone",
"(",
"finaliseBatchTask",
",",
"p",
",",
"cancellable",
",",
"context",
")",
".",
"then",
"(",
"(",
")",
"=>",
"batch",
")",
";",
"}"
] | Creates and executes a new finalise batch task on the given batch.
@param {Batch} batch - the batch to be finalised
@param {Outcomes} processOutcomes - all of the outcomes of the preceding process stage
@param {Cancellable|Object|undefined} [cancellable] - a cancellable object onto which to install cancel functionality
@param {StreamConsumerContext} context - the context to use
@returns {Promise.<Batch>} a promise that will resolve with the batch when the finalise batch task's execution completes | [
"Creates",
"and",
"executes",
"a",
"new",
"finalise",
"batch",
"task",
"on",
"the",
"given",
"batch",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L298-L337 |
52,907 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | createFinaliseBatchTask | function createFinaliseBatchTask(batch, context) {
// Define a new finalise task definition for the batch & updates the batch with it
batch.taskDefs.finaliseTaskDef = defineFinaliseBatchTask();
const task = context.taskFactory.createTask(batch.taskDefs.finaliseTaskDef, finaliseTaskOpts);
// Cache it on the batch
const finalisingTasks = batch.getOrSetFinalisingTasks();
finalisingTasks[task.name] = task;
return task;
} | javascript | function createFinaliseBatchTask(batch, context) {
// Define a new finalise task definition for the batch & updates the batch with it
batch.taskDefs.finaliseTaskDef = defineFinaliseBatchTask();
const task = context.taskFactory.createTask(batch.taskDefs.finaliseTaskDef, finaliseTaskOpts);
// Cache it on the batch
const finalisingTasks = batch.getOrSetFinalisingTasks();
finalisingTasks[task.name] = task;
return task;
} | [
"function",
"createFinaliseBatchTask",
"(",
"batch",
",",
"context",
")",
"{",
"// Define a new finalise task definition for the batch & updates the batch with it",
"batch",
".",
"taskDefs",
".",
"finaliseTaskDef",
"=",
"defineFinaliseBatchTask",
"(",
")",
";",
"const",
"task",
"=",
"context",
".",
"taskFactory",
".",
"createTask",
"(",
"batch",
".",
"taskDefs",
".",
"finaliseTaskDef",
",",
"finaliseTaskOpts",
")",
";",
"// Cache it on the batch",
"const",
"finalisingTasks",
"=",
"batch",
".",
"getOrSetFinalisingTasks",
"(",
")",
";",
"finalisingTasks",
"[",
"task",
".",
"name",
"]",
"=",
"task",
";",
"return",
"task",
";",
"}"
] | Creates a new finalise batch task to be used to finalise the batch and to track the state of the finalising phase.
@param {Batch} batch - the batch to be processed
@param {StreamConsumerContext} context - the context to use
@returns {FinaliseBatchTask} a new finalise batch task (with sub-tasks) | [
"Creates",
"a",
"new",
"finalise",
"batch",
"task",
"to",
"be",
"used",
"to",
"finalise",
"the",
"batch",
"and",
"to",
"track",
"the",
"state",
"of",
"the",
"finalising",
"phase",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L317-L328 |
52,908 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | preProcessBatch | function preProcessBatch(batch, context) {
const task = this;
// const initiatingTask = task.parent;
// Look up the actual function to be used to do the load of the previous tracked state (if any) of the current batch
const preProcessBatchFn = Settings.getPreProcessBatchFunction(context);
if (!preProcessBatchFn) {
if (context.traceEnabled) context.trace(`Skipping pre-process of ${batch.describe(true)}, since no preProcessBatch function configured`);
return Promise.resolve([]);
}
// Create a task to be used to execute and track the configured preProcessBatch function
const fnName = isNotBlank(preProcessBatchFn.name) ? preProcessBatchFn.name : 'preProcessBatch';
const preProcessBatchTask = task.createSubTask(fnName, preProcessBatchFn, batchSettings, initiateTaskOpts);
// Preprocess the batch
const p = preProcessBatchTask.execute(batch, context);
return whenDone(preProcessBatchTask, p, undefined, context).then(
() => {
if (context.traceEnabled) context.trace(`Pre-processed ${batch.describe(true)}`);
return batch;
},
err => {
context.error(`Failed to pre-process ${batch.describe(true)}`, err);
throw err;
}
);
} | javascript | function preProcessBatch(batch, context) {
const task = this;
// const initiatingTask = task.parent;
// Look up the actual function to be used to do the load of the previous tracked state (if any) of the current batch
const preProcessBatchFn = Settings.getPreProcessBatchFunction(context);
if (!preProcessBatchFn) {
if (context.traceEnabled) context.trace(`Skipping pre-process of ${batch.describe(true)}, since no preProcessBatch function configured`);
return Promise.resolve([]);
}
// Create a task to be used to execute and track the configured preProcessBatch function
const fnName = isNotBlank(preProcessBatchFn.name) ? preProcessBatchFn.name : 'preProcessBatch';
const preProcessBatchTask = task.createSubTask(fnName, preProcessBatchFn, batchSettings, initiateTaskOpts);
// Preprocess the batch
const p = preProcessBatchTask.execute(batch, context);
return whenDone(preProcessBatchTask, p, undefined, context).then(
() => {
if (context.traceEnabled) context.trace(`Pre-processed ${batch.describe(true)}`);
return batch;
},
err => {
context.error(`Failed to pre-process ${batch.describe(true)}`, err);
throw err;
}
);
} | [
"function",
"preProcessBatch",
"(",
"batch",
",",
"context",
")",
"{",
"const",
"task",
"=",
"this",
";",
"// const initiatingTask = task.parent;",
"// Look up the actual function to be used to do the load of the previous tracked state (if any) of the current batch",
"const",
"preProcessBatchFn",
"=",
"Settings",
".",
"getPreProcessBatchFunction",
"(",
"context",
")",
";",
"if",
"(",
"!",
"preProcessBatchFn",
")",
"{",
"if",
"(",
"context",
".",
"traceEnabled",
")",
"context",
".",
"trace",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"`",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"[",
"]",
")",
";",
"}",
"// Create a task to be used to execute and track the configured preProcessBatch function",
"const",
"fnName",
"=",
"isNotBlank",
"(",
"preProcessBatchFn",
".",
"name",
")",
"?",
"preProcessBatchFn",
".",
"name",
":",
"'preProcessBatch'",
";",
"const",
"preProcessBatchTask",
"=",
"task",
".",
"createSubTask",
"(",
"fnName",
",",
"preProcessBatchFn",
",",
"batchSettings",
",",
"initiateTaskOpts",
")",
";",
"// Preprocess the batch",
"const",
"p",
"=",
"preProcessBatchTask",
".",
"execute",
"(",
"batch",
",",
"context",
")",
";",
"return",
"whenDone",
"(",
"preProcessBatchTask",
",",
"p",
",",
"undefined",
",",
"context",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"context",
".",
"traceEnabled",
")",
"context",
".",
"trace",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"`",
")",
";",
"return",
"batch",
";",
"}",
",",
"err",
"=>",
"{",
"context",
".",
"error",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Provides a hook for an optional pre-process batch function to be invoked after the batch has been successfully
initiated and before the batch is processed.
@param {Batch} batch
@param {StreamConsumerContext} context
@param {PreFinaliseBatch} [context.preProcessBatch] - an optional pre-process batch function to execute
@returns {Promise.<Batch|undefined>} | [
"Provides",
"a",
"hook",
"for",
"an",
"optional",
"pre",
"-",
"process",
"batch",
"function",
"to",
"be",
"invoked",
"after",
"the",
"batch",
"has",
"been",
"successfully",
"initiated",
"and",
"before",
"the",
"batch",
"is",
"processed",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L749-L777 |
52,909 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | executeAllProcessAllTasks | function executeAllProcessAllTasks(batch, cancellable, context) {
const messages = batch.messages;
const m = messages.length;
const ms = toCountString(m, 'message');
const t = batch.taskDefs.processAllTaskDefs.length;
const ts = toCountString(t, 'process all task');
if (m <= 0) {
if (context.debugEnabled) context.debug(`Skipping execution of ${ts} for ${batch.describe(true)}, since ${ms}`);
return Promise.resolve([]);
}
if (t <= 0) {
context.warn(`Skipping execution of ${ts} for ${batch.describe(true)}), since ${ts}`);
return Promise.resolve([]);
}
// First get all of the batch's process all tasks
const tasksByName = batch.getProcessAllTasks();
const tasks = taskUtils.getTasks(tasksByName);
const incompleteTasks = tasks.filter(task => !task.isFullyFinalised());
const i = incompleteTasks.length;
if (i <= 0) {
const is = toCountString(i, 'incomplete task');
if (context.debugEnabled) context.debug(`Skipping execution of ${ts} on ${batch.describe(true)}, since ${is}`);
return Promise.resolve([]);
} else {
if (context.traceEnabled) context.trace(`About to execute ${i} incomplete of ${ts} on ${batch.describe(true)}`);
}
// Execute all of the incomplete processAll tasks on the batch and collect their promises
const promises = incompleteTasks.map(task => {
// Collect all of the incomplete messages from the batch that are not fully finalised yet for the given task
const incompleteMessages = messages.filter(msg => {
const msgTask = batch.getProcessAllTask(msg, task.name);
return !msgTask || !msgTask.isFullyFinalised();
});
const p = task.execute(batch, incompleteMessages, context);
return whenDone(task, p, cancellable, context);
});
return Promises.every(promises, cancellable, context);
} | javascript | function executeAllProcessAllTasks(batch, cancellable, context) {
const messages = batch.messages;
const m = messages.length;
const ms = toCountString(m, 'message');
const t = batch.taskDefs.processAllTaskDefs.length;
const ts = toCountString(t, 'process all task');
if (m <= 0) {
if (context.debugEnabled) context.debug(`Skipping execution of ${ts} for ${batch.describe(true)}, since ${ms}`);
return Promise.resolve([]);
}
if (t <= 0) {
context.warn(`Skipping execution of ${ts} for ${batch.describe(true)}), since ${ts}`);
return Promise.resolve([]);
}
// First get all of the batch's process all tasks
const tasksByName = batch.getProcessAllTasks();
const tasks = taskUtils.getTasks(tasksByName);
const incompleteTasks = tasks.filter(task => !task.isFullyFinalised());
const i = incompleteTasks.length;
if (i <= 0) {
const is = toCountString(i, 'incomplete task');
if (context.debugEnabled) context.debug(`Skipping execution of ${ts} on ${batch.describe(true)}, since ${is}`);
return Promise.resolve([]);
} else {
if (context.traceEnabled) context.trace(`About to execute ${i} incomplete of ${ts} on ${batch.describe(true)}`);
}
// Execute all of the incomplete processAll tasks on the batch and collect their promises
const promises = incompleteTasks.map(task => {
// Collect all of the incomplete messages from the batch that are not fully finalised yet for the given task
const incompleteMessages = messages.filter(msg => {
const msgTask = batch.getProcessAllTask(msg, task.name);
return !msgTask || !msgTask.isFullyFinalised();
});
const p = task.execute(batch, incompleteMessages, context);
return whenDone(task, p, cancellable, context);
});
return Promises.every(promises, cancellable, context);
} | [
"function",
"executeAllProcessAllTasks",
"(",
"batch",
",",
"cancellable",
",",
"context",
")",
"{",
"const",
"messages",
"=",
"batch",
".",
"messages",
";",
"const",
"m",
"=",
"messages",
".",
"length",
";",
"const",
"ms",
"=",
"toCountString",
"(",
"m",
",",
"'message'",
")",
";",
"const",
"t",
"=",
"batch",
".",
"taskDefs",
".",
"processAllTaskDefs",
".",
"length",
";",
"const",
"ts",
"=",
"toCountString",
"(",
"t",
",",
"'process all task'",
")",
";",
"if",
"(",
"m",
"<=",
"0",
")",
"{",
"if",
"(",
"context",
".",
"debugEnabled",
")",
"context",
".",
"debug",
"(",
"`",
"${",
"ts",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"${",
"ms",
"}",
"`",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"[",
"]",
")",
";",
"}",
"if",
"(",
"t",
"<=",
"0",
")",
"{",
"context",
".",
"warn",
"(",
"`",
"${",
"ts",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"${",
"ts",
"}",
"`",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"[",
"]",
")",
";",
"}",
"// First get all of the batch's process all tasks",
"const",
"tasksByName",
"=",
"batch",
".",
"getProcessAllTasks",
"(",
")",
";",
"const",
"tasks",
"=",
"taskUtils",
".",
"getTasks",
"(",
"tasksByName",
")",
";",
"const",
"incompleteTasks",
"=",
"tasks",
".",
"filter",
"(",
"task",
"=>",
"!",
"task",
".",
"isFullyFinalised",
"(",
")",
")",
";",
"const",
"i",
"=",
"incompleteTasks",
".",
"length",
";",
"if",
"(",
"i",
"<=",
"0",
")",
"{",
"const",
"is",
"=",
"toCountString",
"(",
"i",
",",
"'incomplete task'",
")",
";",
"if",
"(",
"context",
".",
"debugEnabled",
")",
"context",
".",
"debug",
"(",
"`",
"${",
"ts",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"${",
"is",
"}",
"`",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"[",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"context",
".",
"traceEnabled",
")",
"context",
".",
"trace",
"(",
"`",
"${",
"i",
"}",
"${",
"ts",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"`",
")",
";",
"}",
"// Execute all of the incomplete processAll tasks on the batch and collect their promises",
"const",
"promises",
"=",
"incompleteTasks",
".",
"map",
"(",
"task",
"=>",
"{",
"// Collect all of the incomplete messages from the batch that are not fully finalised yet for the given task",
"const",
"incompleteMessages",
"=",
"messages",
".",
"filter",
"(",
"msg",
"=>",
"{",
"const",
"msgTask",
"=",
"batch",
".",
"getProcessAllTask",
"(",
"msg",
",",
"task",
".",
"name",
")",
";",
"return",
"!",
"msgTask",
"||",
"!",
"msgTask",
".",
"isFullyFinalised",
"(",
")",
";",
"}",
")",
";",
"const",
"p",
"=",
"task",
".",
"execute",
"(",
"batch",
",",
"incompleteMessages",
",",
"context",
")",
";",
"return",
"whenDone",
"(",
"task",
",",
"p",
",",
"cancellable",
",",
"context",
")",
";",
"}",
")",
";",
"return",
"Promises",
".",
"every",
"(",
"promises",
",",
"cancellable",
",",
"context",
")",
";",
"}"
] | Executes all of the incomplete "process all" tasks on the batch and returns a promise of an array with a Success or
Failure execution outcome for each task.
For each "process all" task to be executed, also resolves and passes all of its incomplete messages, which are all
of the batch's messages that are not yet fully finalised for the particular task. The incomplete messages are passed
as the 2nd argument to the task's `execute` function.
Any and all errors encountered along the way are logged, but no errors are allowed to escape from this function.
@param {Batch} batch - the batch on which to execute each of the "process all" tasks (passed as the 1st argument)
@param {Cancellable|Object|undefined} [cancellable] - a cancellable object onto which to install cancel functionality
@param {StreamConsumerContext} context - the context to use (passed as the 3rd argument)
@return {Promise.<Outcomes>} a promise to return all of the "process all" tasks' outcomes | [
"Executes",
"all",
"of",
"the",
"incomplete",
"process",
"all",
"tasks",
"on",
"the",
"batch",
"and",
"returns",
"a",
"promise",
"of",
"an",
"array",
"with",
"a",
"Success",
"or",
"Failure",
"execution",
"outcome",
"for",
"each",
"task",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L939-L985 |
52,910 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | calculateTimeoutMs | function calculateTimeoutMs(timeoutAtPercentageOfRemainingTime, context) {
const remainingTimeInMillis = context.awsContext.getRemainingTimeInMillis();
return Math.round(remainingTimeInMillis * timeoutAtPercentageOfRemainingTime);
} | javascript | function calculateTimeoutMs(timeoutAtPercentageOfRemainingTime, context) {
const remainingTimeInMillis = context.awsContext.getRemainingTimeInMillis();
return Math.round(remainingTimeInMillis * timeoutAtPercentageOfRemainingTime);
} | [
"function",
"calculateTimeoutMs",
"(",
"timeoutAtPercentageOfRemainingTime",
",",
"context",
")",
"{",
"const",
"remainingTimeInMillis",
"=",
"context",
".",
"awsContext",
".",
"getRemainingTimeInMillis",
"(",
")",
";",
"return",
"Math",
".",
"round",
"(",
"remainingTimeInMillis",
"*",
"timeoutAtPercentageOfRemainingTime",
")",
";",
"}"
] | Calculates the number of milliseconds to wait before timing out using the given timeoutAtPercentageOfRemainingTime
and the Lambda's remaining time to execute.
@param {number} timeoutAtPercentageOfRemainingTime - the percentage of the remaining time at which to timeout
the given task (expressed as a number between 0.0 and 1.0, e.g. 0.9 would mean timeout at 90% of the remaining time)
@param {StreamConsumerContext} context - the context to use
@returns {number} the number of milliseconds to wait | [
"Calculates",
"the",
"number",
"of",
"milliseconds",
"to",
"wait",
"before",
"timing",
"out",
"using",
"the",
"given",
"timeoutAtPercentageOfRemainingTime",
"and",
"the",
"Lambda",
"s",
"remaining",
"time",
"to",
"execute",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L995-L998 |
52,911 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | createCompletedPromise | function createCompletedPromise(task, completingPromise, batch, timeoutCancellable, context) {
const mustResolve = false;
return completingPromise.then(
outcomes => {
// The completing promise has completed
// 1. Try to cancel the timeout with which the completing promise was racing
const timedOut = timeoutCancellable.cancelTimeout(mustResolve);
if (timedOut) {
context.warn(`Timed out before ${task.name} completed for ${batch.describe(true)}`);
} else {
// 2. Mark the completing task as failed if any of its outcomes (or any of its sub-tasks' outcomes) is a Failure
const failure = Try.findFailure(outcomes);
if (failure) {
task.fail(failure.error, false);
} else {
task.complete(outcomes, dontOverrideTimedOut, false);
}
context.debug(`Completed ${task.name} for ${batch.describe(true)} - final state (${task.state})`);
}
return outcomes;
},
err => {
if (isInstanceOf(err, CancelledError)) {
// The completing promise was cancelled, which means the timeout must have triggered and cancelled it
context.warn(`Cancelling ${task.name} for ${batch.describe(true)}`, err);
const timeoutOpts = {overrideCompleted: false, overrideUnstarted: false, reverseAttempt: true};
const timeoutError = new TimeoutError(`Ran out of time to complete ${task.name}`);
if (!task.timedOut) {
task.timeout(timeoutError, timeoutOpts, true);
}
// timeoutError.cancelledError = err;
// throw timeoutError;
throw err;
} else {
// The completing promise rejected with a non-cancelled error, so attempt to cancel the timeout promise
const timedOut = timeoutCancellable.cancelTimeout(mustResolve);
if (timedOut) {
context.warn(`Timed out before failed ${task.name} for ${batch.describe(true)}`, err);
} else {
context.info(`Failed ${task.name} for ${batch.describe(true)}`, err);
task.fail(err, false);
}
throw err;
}
}
);
} | javascript | function createCompletedPromise(task, completingPromise, batch, timeoutCancellable, context) {
const mustResolve = false;
return completingPromise.then(
outcomes => {
// The completing promise has completed
// 1. Try to cancel the timeout with which the completing promise was racing
const timedOut = timeoutCancellable.cancelTimeout(mustResolve);
if (timedOut) {
context.warn(`Timed out before ${task.name} completed for ${batch.describe(true)}`);
} else {
// 2. Mark the completing task as failed if any of its outcomes (or any of its sub-tasks' outcomes) is a Failure
const failure = Try.findFailure(outcomes);
if (failure) {
task.fail(failure.error, false);
} else {
task.complete(outcomes, dontOverrideTimedOut, false);
}
context.debug(`Completed ${task.name} for ${batch.describe(true)} - final state (${task.state})`);
}
return outcomes;
},
err => {
if (isInstanceOf(err, CancelledError)) {
// The completing promise was cancelled, which means the timeout must have triggered and cancelled it
context.warn(`Cancelling ${task.name} for ${batch.describe(true)}`, err);
const timeoutOpts = {overrideCompleted: false, overrideUnstarted: false, reverseAttempt: true};
const timeoutError = new TimeoutError(`Ran out of time to complete ${task.name}`);
if (!task.timedOut) {
task.timeout(timeoutError, timeoutOpts, true);
}
// timeoutError.cancelledError = err;
// throw timeoutError;
throw err;
} else {
// The completing promise rejected with a non-cancelled error, so attempt to cancel the timeout promise
const timedOut = timeoutCancellable.cancelTimeout(mustResolve);
if (timedOut) {
context.warn(`Timed out before failed ${task.name} for ${batch.describe(true)}`, err);
} else {
context.info(`Failed ${task.name} for ${batch.describe(true)}`, err);
task.fail(err, false);
}
throw err;
}
}
);
} | [
"function",
"createCompletedPromise",
"(",
"task",
",",
"completingPromise",
",",
"batch",
",",
"timeoutCancellable",
",",
"context",
")",
"{",
"const",
"mustResolve",
"=",
"false",
";",
"return",
"completingPromise",
".",
"then",
"(",
"outcomes",
"=>",
"{",
"// The completing promise has completed",
"// 1. Try to cancel the timeout with which the completing promise was racing",
"const",
"timedOut",
"=",
"timeoutCancellable",
".",
"cancelTimeout",
"(",
"mustResolve",
")",
";",
"if",
"(",
"timedOut",
")",
"{",
"context",
".",
"warn",
"(",
"`",
"${",
"task",
".",
"name",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"`",
")",
";",
"}",
"else",
"{",
"// 2. Mark the completing task as failed if any of its outcomes (or any of its sub-tasks' outcomes) is a Failure",
"const",
"failure",
"=",
"Try",
".",
"findFailure",
"(",
"outcomes",
")",
";",
"if",
"(",
"failure",
")",
"{",
"task",
".",
"fail",
"(",
"failure",
".",
"error",
",",
"false",
")",
";",
"}",
"else",
"{",
"task",
".",
"complete",
"(",
"outcomes",
",",
"dontOverrideTimedOut",
",",
"false",
")",
";",
"}",
"context",
".",
"debug",
"(",
"`",
"${",
"task",
".",
"name",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"${",
"task",
".",
"state",
"}",
"`",
")",
";",
"}",
"return",
"outcomes",
";",
"}",
",",
"err",
"=>",
"{",
"if",
"(",
"isInstanceOf",
"(",
"err",
",",
"CancelledError",
")",
")",
"{",
"// The completing promise was cancelled, which means the timeout must have triggered and cancelled it",
"context",
".",
"warn",
"(",
"`",
"${",
"task",
".",
"name",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"`",
",",
"err",
")",
";",
"const",
"timeoutOpts",
"=",
"{",
"overrideCompleted",
":",
"false",
",",
"overrideUnstarted",
":",
"false",
",",
"reverseAttempt",
":",
"true",
"}",
";",
"const",
"timeoutError",
"=",
"new",
"TimeoutError",
"(",
"`",
"${",
"task",
".",
"name",
"}",
"`",
")",
";",
"if",
"(",
"!",
"task",
".",
"timedOut",
")",
"{",
"task",
".",
"timeout",
"(",
"timeoutError",
",",
"timeoutOpts",
",",
"true",
")",
";",
"}",
"// timeoutError.cancelledError = err;",
"// throw timeoutError;",
"throw",
"err",
";",
"}",
"else",
"{",
"// The completing promise rejected with a non-cancelled error, so attempt to cancel the timeout promise",
"const",
"timedOut",
"=",
"timeoutCancellable",
".",
"cancelTimeout",
"(",
"mustResolve",
")",
";",
"if",
"(",
"timedOut",
")",
"{",
"context",
".",
"warn",
"(",
"`",
"${",
"task",
".",
"name",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"`",
",",
"err",
")",
";",
"}",
"else",
"{",
"context",
".",
"info",
"(",
"`",
"${",
"task",
".",
"name",
"}",
"${",
"batch",
".",
"describe",
"(",
"true",
")",
"}",
"`",
",",
"err",
")",
";",
"task",
".",
"fail",
"(",
"err",
",",
"false",
")",
";",
"}",
"throw",
"err",
";",
"}",
"}",
")",
";",
"}"
] | Build a completed promise that will only complete when the given completingPromise has completed.
@param {Task} task - a task to be completed or failed depending on the outcome of the promise and if the timeout has not triggered yet
@param {Promise} completingPromise - the promise that will complete when all processing has been completed for the current phase
@param {Batch} batch - the batch being processed
@param {Object} timeoutCancellable - a cancellable object that enables cancellation of the timeout promise on completion
@param {StreamConsumerContext} context - the context to use
@returns {Promise.<Outcomes>} a promise to return the outcomes of the completing promise when the completingPromise resolves | [
"Build",
"a",
"completed",
"promise",
"that",
"will",
"only",
"complete",
"when",
"the",
"given",
"completingPromise",
"has",
"completed",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L1053-L1101 |
52,912 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | preFinaliseBatch | function preFinaliseBatch(batch, context) {
const task = this;
// Look up the actual function to be used to do the pre-finalise batch logic (if any)
const preFinaliseBatchFn = Settings.getPreFinaliseBatchFunction(context);
if (!preFinaliseBatchFn) {
if (context.traceEnabled) context.trace(`Skipping pre-finalise of ${batch.describe(false)}, since no preFinaliseBatch function configured`);
return Promise.resolve(undefined);
}
// Create a task to be used to execute and track the configured preFinaliseBatch function
const fnName = isNotBlank(preFinaliseBatchFn.name) ? preFinaliseBatchFn.name : 'preFinaliseBatch';
const preFinaliseBatchTask = task.createSubTask(fnName, preFinaliseBatchFn, batchSettings, processTaskOpts);
// Pre-finalise the batch
const p = preFinaliseBatchTask.execute(batch, context);
return whenDone(preFinaliseBatchTask, p, undefined, context).then(
() => {
if (context.traceEnabled) context.trace(`Pre-finalised ${batch.describe(false)}`);
return batch;
},
err => {
context.error(`Failed to pre-finalise ${batch.describe(false)}`, err);
throw err;
}
);
} | javascript | function preFinaliseBatch(batch, context) {
const task = this;
// Look up the actual function to be used to do the pre-finalise batch logic (if any)
const preFinaliseBatchFn = Settings.getPreFinaliseBatchFunction(context);
if (!preFinaliseBatchFn) {
if (context.traceEnabled) context.trace(`Skipping pre-finalise of ${batch.describe(false)}, since no preFinaliseBatch function configured`);
return Promise.resolve(undefined);
}
// Create a task to be used to execute and track the configured preFinaliseBatch function
const fnName = isNotBlank(preFinaliseBatchFn.name) ? preFinaliseBatchFn.name : 'preFinaliseBatch';
const preFinaliseBatchTask = task.createSubTask(fnName, preFinaliseBatchFn, batchSettings, processTaskOpts);
// Pre-finalise the batch
const p = preFinaliseBatchTask.execute(batch, context);
return whenDone(preFinaliseBatchTask, p, undefined, context).then(
() => {
if (context.traceEnabled) context.trace(`Pre-finalised ${batch.describe(false)}`);
return batch;
},
err => {
context.error(`Failed to pre-finalise ${batch.describe(false)}`, err);
throw err;
}
);
} | [
"function",
"preFinaliseBatch",
"(",
"batch",
",",
"context",
")",
"{",
"const",
"task",
"=",
"this",
";",
"// Look up the actual function to be used to do the pre-finalise batch logic (if any)",
"const",
"preFinaliseBatchFn",
"=",
"Settings",
".",
"getPreFinaliseBatchFunction",
"(",
"context",
")",
";",
"if",
"(",
"!",
"preFinaliseBatchFn",
")",
"{",
"if",
"(",
"context",
".",
"traceEnabled",
")",
"context",
".",
"trace",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
"false",
")",
"}",
"`",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"undefined",
")",
";",
"}",
"// Create a task to be used to execute and track the configured preFinaliseBatch function",
"const",
"fnName",
"=",
"isNotBlank",
"(",
"preFinaliseBatchFn",
".",
"name",
")",
"?",
"preFinaliseBatchFn",
".",
"name",
":",
"'preFinaliseBatch'",
";",
"const",
"preFinaliseBatchTask",
"=",
"task",
".",
"createSubTask",
"(",
"fnName",
",",
"preFinaliseBatchFn",
",",
"batchSettings",
",",
"processTaskOpts",
")",
";",
"// Pre-finalise the batch",
"const",
"p",
"=",
"preFinaliseBatchTask",
".",
"execute",
"(",
"batch",
",",
"context",
")",
";",
"return",
"whenDone",
"(",
"preFinaliseBatchTask",
",",
"p",
",",
"undefined",
",",
"context",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"context",
".",
"traceEnabled",
")",
"context",
".",
"trace",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
"false",
")",
"}",
"`",
")",
";",
"return",
"batch",
";",
"}",
",",
"err",
"=>",
"{",
"context",
".",
"error",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
"false",
")",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Provides a hook for an optional pre-finalise batch function to be invoked after the batch has been successfully
processed and before the batch is finalised.
@param {Batch} batch
@param {StreamConsumerContext} context
@param {PreFinaliseBatch} [context.preFinaliseBatch] - an optional pre-finalise batch function to execute
@returns {Promise.<Batch|undefined>} | [
"Provides",
"a",
"hook",
"for",
"an",
"optional",
"pre",
"-",
"finalise",
"batch",
"function",
"to",
"be",
"invoked",
"after",
"the",
"batch",
"has",
"been",
"successfully",
"processed",
"and",
"before",
"the",
"batch",
"is",
"finalised",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L1123-L1150 |
52,913 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | postFinaliseBatch | function postFinaliseBatch(batch, context) {
const task = this;
// const finalisingTask = task.parent;
// Look up the actual function to be used to do the post-finalise batch logic (if any)
const postFinaliseBatchFn = Settings.getPostFinaliseBatchFunction(context);
if (!postFinaliseBatchFn) {
if (context.traceEnabled) context.trace(`Skipping post-finalise of ${batch.describe()}, since no postFinaliseBatch function configured`);
return Promise.resolve(undefined);
}
// Create a task to be used to execute and track the configured postFinaliseBatch function
const fnName = isNotBlank(postFinaliseBatchFn.name) ? postFinaliseBatchFn.name : 'postFinaliseBatch';
const postFinaliseBatchTask = task.createSubTask(fnName, postFinaliseBatchFn, batchSettings, finaliseTaskOpts);
// Pre-finalise the batch
const p = postFinaliseBatchTask.execute(batch, context);
return whenDone(postFinaliseBatchTask, p, undefined, context).then(
// return Promises.try(() => preFinaliseBatchTask.execute(batch, context)).then(
() => {
context.debug(`Post-finalised ${batch.describe()}`);
return batch;
},
err => {
context.error(`Failed to post-finalise ${batch.describe()}`, err);
throw err;
}
);
} | javascript | function postFinaliseBatch(batch, context) {
const task = this;
// const finalisingTask = task.parent;
// Look up the actual function to be used to do the post-finalise batch logic (if any)
const postFinaliseBatchFn = Settings.getPostFinaliseBatchFunction(context);
if (!postFinaliseBatchFn) {
if (context.traceEnabled) context.trace(`Skipping post-finalise of ${batch.describe()}, since no postFinaliseBatch function configured`);
return Promise.resolve(undefined);
}
// Create a task to be used to execute and track the configured postFinaliseBatch function
const fnName = isNotBlank(postFinaliseBatchFn.name) ? postFinaliseBatchFn.name : 'postFinaliseBatch';
const postFinaliseBatchTask = task.createSubTask(fnName, postFinaliseBatchFn, batchSettings, finaliseTaskOpts);
// Pre-finalise the batch
const p = postFinaliseBatchTask.execute(batch, context);
return whenDone(postFinaliseBatchTask, p, undefined, context).then(
// return Promises.try(() => preFinaliseBatchTask.execute(batch, context)).then(
() => {
context.debug(`Post-finalised ${batch.describe()}`);
return batch;
},
err => {
context.error(`Failed to post-finalise ${batch.describe()}`, err);
throw err;
}
);
} | [
"function",
"postFinaliseBatch",
"(",
"batch",
",",
"context",
")",
"{",
"const",
"task",
"=",
"this",
";",
"// const finalisingTask = task.parent;",
"// Look up the actual function to be used to do the post-finalise batch logic (if any)",
"const",
"postFinaliseBatchFn",
"=",
"Settings",
".",
"getPostFinaliseBatchFunction",
"(",
"context",
")",
";",
"if",
"(",
"!",
"postFinaliseBatchFn",
")",
"{",
"if",
"(",
"context",
".",
"traceEnabled",
")",
"context",
".",
"trace",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
")",
"}",
"`",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"undefined",
")",
";",
"}",
"// Create a task to be used to execute and track the configured postFinaliseBatch function",
"const",
"fnName",
"=",
"isNotBlank",
"(",
"postFinaliseBatchFn",
".",
"name",
")",
"?",
"postFinaliseBatchFn",
".",
"name",
":",
"'postFinaliseBatch'",
";",
"const",
"postFinaliseBatchTask",
"=",
"task",
".",
"createSubTask",
"(",
"fnName",
",",
"postFinaliseBatchFn",
",",
"batchSettings",
",",
"finaliseTaskOpts",
")",
";",
"// Pre-finalise the batch",
"const",
"p",
"=",
"postFinaliseBatchTask",
".",
"execute",
"(",
"batch",
",",
"context",
")",
";",
"return",
"whenDone",
"(",
"postFinaliseBatchTask",
",",
"p",
",",
"undefined",
",",
"context",
")",
".",
"then",
"(",
"// return Promises.try(() => preFinaliseBatchTask.execute(batch, context)).then(",
"(",
")",
"=>",
"{",
"context",
".",
"debug",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
")",
"}",
"`",
")",
";",
"return",
"batch",
";",
"}",
",",
"err",
"=>",
"{",
"context",
".",
"error",
"(",
"`",
"${",
"batch",
".",
"describe",
"(",
")",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Provides a hook for an optional post-finalise batch function to be invoked after the batch has been successfully
finalised.
@param {Batch} batch
@param {StreamConsumerContext} context
@param {PostFinaliseBatch} [context.postFinaliseBatch] - an optional post-finalise batch function to execute
@returns {Promise.<Batch|undefined>} | [
"Provides",
"a",
"hook",
"for",
"an",
"optional",
"post",
"-",
"finalise",
"batch",
"function",
"to",
"be",
"invoked",
"after",
"the",
"batch",
"has",
"been",
"successfully",
"finalised",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L1340-L1369 |
52,914 | byron-dupreez/aws-stream-consumer-core | stream-consumer.js | logFinalResults | function logFinalResults(batch, finalError, context) {
const summary = batch ? batch.summarizeFinalResults(finalError) : undefined;
context.info(`Summarized final batch results: ${JSON.stringify(summary)}`);
} | javascript | function logFinalResults(batch, finalError, context) {
const summary = batch ? batch.summarizeFinalResults(finalError) : undefined;
context.info(`Summarized final batch results: ${JSON.stringify(summary)}`);
} | [
"function",
"logFinalResults",
"(",
"batch",
",",
"finalError",
",",
"context",
")",
"{",
"const",
"summary",
"=",
"batch",
"?",
"batch",
".",
"summarizeFinalResults",
"(",
"finalError",
")",
":",
"undefined",
";",
"context",
".",
"info",
"(",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"summary",
")",
"}",
"`",
")",
";",
"}"
] | Summarizes and logs the final results of the given batch - converting lists of messages and records into counts.
@param {Batch} batch - the batch that was processed
@param {Error|undefined} [finalError] - the final error with which the batch was terminated (if unsuccessful)
@param {StreamConsumerContext} context - the context to use | [
"Summarizes",
"and",
"logs",
"the",
"final",
"results",
"of",
"the",
"given",
"batch",
"-",
"converting",
"lists",
"of",
"messages",
"and",
"records",
"into",
"counts",
"."
] | 9b256084297f80d373bcf483aaf68a9da176b3d7 | https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-consumer.js#L1423-L1426 |
52,915 | origin1tech/chek | dist/modules/from.js | fromEpoch | function fromEpoch(val, def) {
if (!is_1.isValue(val) || !is_1.isNumber(val))
return to_1.toDefault(null, def);
return new Date(val);
} | javascript | function fromEpoch(val, def) {
if (!is_1.isValue(val) || !is_1.isNumber(val))
return to_1.toDefault(null, def);
return new Date(val);
} | [
"function",
"fromEpoch",
"(",
"val",
",",
"def",
")",
"{",
"if",
"(",
"!",
"is_1",
".",
"isValue",
"(",
"val",
")",
"||",
"!",
"is_1",
".",
"isNumber",
"(",
"val",
")",
")",
"return",
"to_1",
".",
"toDefault",
"(",
"null",
",",
"def",
")",
";",
"return",
"new",
"Date",
"(",
"val",
")",
";",
"}"
] | From Epoch
Converts to a Date from an epoch.
@param val the epoch value to convert to date. | [
"From",
"Epoch",
"Converts",
"to",
"a",
"Date",
"from",
"an",
"epoch",
"."
] | 6bc3ab0ac36126cc7918a244a606009749897b2e | https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/from.js#L12-L16 |
52,916 | feedhenry/fh-mbaas-middleware | lib/middleware/events.js | listEvents | function listEvents(req, res, next){
var logger = log.logger;
var EventModel = models.getModels().Event;
var listReq = RequestTranslator.parseListEventsRequest(req);
if(! listReq.uid || ! listReq.env || ! listReq.domain){
return next({"error":"invalid params missing uid env or domain","code":400});
}
EventModel.queryEvents(listReq.uid, listReq.env, listReq.domain, function(err, events){
if(err) {
logger.error(loggerPrefix + 'Events Query Error: ', err);
return next(err);
} else {
req.resultData = ResponseTranslator.mapEventsToResponse(events);
next();
}
});
} | javascript | function listEvents(req, res, next){
var logger = log.logger;
var EventModel = models.getModels().Event;
var listReq = RequestTranslator.parseListEventsRequest(req);
if(! listReq.uid || ! listReq.env || ! listReq.domain){
return next({"error":"invalid params missing uid env or domain","code":400});
}
EventModel.queryEvents(listReq.uid, listReq.env, listReq.domain, function(err, events){
if(err) {
logger.error(loggerPrefix + 'Events Query Error: ', err);
return next(err);
} else {
req.resultData = ResponseTranslator.mapEventsToResponse(events);
next();
}
});
} | [
"function",
"listEvents",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"logger",
"=",
"log",
".",
"logger",
";",
"var",
"EventModel",
"=",
"models",
".",
"getModels",
"(",
")",
".",
"Event",
";",
"var",
"listReq",
"=",
"RequestTranslator",
".",
"parseListEventsRequest",
"(",
"req",
")",
";",
"if",
"(",
"!",
"listReq",
".",
"uid",
"||",
"!",
"listReq",
".",
"env",
"||",
"!",
"listReq",
".",
"domain",
")",
"{",
"return",
"next",
"(",
"{",
"\"error\"",
":",
"\"invalid params missing uid env or domain\"",
",",
"\"code\"",
":",
"400",
"}",
")",
";",
"}",
"EventModel",
".",
"queryEvents",
"(",
"listReq",
".",
"uid",
",",
"listReq",
".",
"env",
",",
"listReq",
".",
"domain",
",",
"function",
"(",
"err",
",",
"events",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"loggerPrefix",
"+",
"'Events Query Error: '",
",",
"err",
")",
";",
"return",
"next",
"(",
"err",
")",
";",
"}",
"else",
"{",
"req",
".",
"resultData",
"=",
"ResponseTranslator",
".",
"mapEventsToResponse",
"(",
"events",
")",
";",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Return list of Events for domain, env and app id
@param req
@param res
@param next | [
"Return",
"list",
"of",
"Events",
"for",
"domain",
"env",
"and",
"app",
"id"
] | f906e98efbb4b0963bf5137b34b5e0589ba24e69 | https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/middleware/events.js#L17-L33 |
52,917 | mmacmillan/aws-sns-q | sns-q.js | function(arn, attributes) {
var params = {
PlatformApplicationArn: arn,
Attributes: attributes
};
return this.svc.setPlatformApplicationAttributes(params);
} | javascript | function(arn, attributes) {
var params = {
PlatformApplicationArn: arn,
Attributes: attributes
};
return this.svc.setPlatformApplicationAttributes(params);
} | [
"function",
"(",
"arn",
",",
"attributes",
")",
"{",
"var",
"params",
"=",
"{",
"PlatformApplicationArn",
":",
"arn",
",",
"Attributes",
":",
"attributes",
"}",
";",
"return",
"this",
".",
"svc",
".",
"setPlatformApplicationAttributes",
"(",
"params",
")",
";",
"}"
] | updates the attributes for the specified platformApplicationArn
@param {String} arn the PlatformApplicationArn of the target platform application
@param {Object} attributes the Attributes map; a collection of fields to update | [
"updates",
"the",
"attributes",
"for",
"the",
"specified",
"platformApplicationArn"
] | b1c7a03d5687864a6130a7d5b4891d80aec16cdf | https://github.com/mmacmillan/aws-sns-q/blob/b1c7a03d5687864a6130a7d5b4891d80aec16cdf/sns-q.js#L61-L68 |
|
52,918 | mmacmillan/aws-sns-q | sns-q.js | function(arn, token) {
var params = {
PlatformApplicationArn: arn,
NextToken: token
};
return this.svc.listEndpointsByPlatformApplication(params);
} | javascript | function(arn, token) {
var params = {
PlatformApplicationArn: arn,
NextToken: token
};
return this.svc.listEndpointsByPlatformApplication(params);
} | [
"function",
"(",
"arn",
",",
"token",
")",
"{",
"var",
"params",
"=",
"{",
"PlatformApplicationArn",
":",
"arn",
",",
"NextToken",
":",
"token",
"}",
";",
"return",
"this",
".",
"svc",
".",
"listEndpointsByPlatformApplication",
"(",
"params",
")",
";",
"}"
] | returns a list of all endpoints for the specified platform application
@param {String} arn the PlatformApplicationArn of the application to list endpoints for
@param {String} token the token returned from the previous call, to access the next set of objects | [
"returns",
"a",
"list",
"of",
"all",
"endpoints",
"for",
"the",
"specified",
"platform",
"application"
] | b1c7a03d5687864a6130a7d5b4891d80aec16cdf | https://github.com/mmacmillan/aws-sns-q/blob/b1c7a03d5687864a6130a7d5b4891d80aec16cdf/sns-q.js#L85-L92 |
|
52,919 | mmacmillan/aws-sns-q | sns-q.js | function(arn, token, data, attributes) {
var params = {
PlatformApplicationArn: arn,
Token: token,
CustomUserData: data,
Attributes: attributes
};
return this.svc.createPlatformEndpoint(params);
} | javascript | function(arn, token, data, attributes) {
var params = {
PlatformApplicationArn: arn,
Token: token,
CustomUserData: data,
Attributes: attributes
};
return this.svc.createPlatformEndpoint(params);
} | [
"function",
"(",
"arn",
",",
"token",
",",
"data",
",",
"attributes",
")",
"{",
"var",
"params",
"=",
"{",
"PlatformApplicationArn",
":",
"arn",
",",
"Token",
":",
"token",
",",
"CustomUserData",
":",
"data",
",",
"Attributes",
":",
"attributes",
"}",
";",
"return",
"this",
".",
"svc",
".",
"createPlatformEndpoint",
"(",
"params",
")",
";",
"}"
] | creates an endpoint for a device, within the specified application
@param {String} name name of the platformApplication object
@param {String} platform the platform this application object targets (APNS, GCM, ADM)
@param {Object} attributes additional attributes provided
for more information regarding the additional attributes, see:
http://docs.aws.amazon.com/sns/latest/api/API_SetEndpointAttributes.html | [
"creates",
"an",
"endpoint",
"for",
"a",
"device",
"within",
"the",
"specified",
"application"
] | b1c7a03d5687864a6130a7d5b4891d80aec16cdf | https://github.com/mmacmillan/aws-sns-q/blob/b1c7a03d5687864a6130a7d5b4891d80aec16cdf/sns-q.js#L118-L127 |
|
52,920 | mmacmillan/aws-sns-q | sns-q.js | function(arn, attributes) {
var params = {
EndpointArn: arn,
Attributes: attributes
};
return this.svc.setEndpointAttributes(params);
} | javascript | function(arn, attributes) {
var params = {
EndpointArn: arn,
Attributes: attributes
};
return this.svc.setEndpointAttributes(params);
} | [
"function",
"(",
"arn",
",",
"attributes",
")",
"{",
"var",
"params",
"=",
"{",
"EndpointArn",
":",
"arn",
",",
"Attributes",
":",
"attributes",
"}",
";",
"return",
"this",
".",
"svc",
".",
"setEndpointAttributes",
"(",
"params",
")",
";",
"}"
] | updates the attributes for the specified endpoint
@param {String} arn the EndpointArn of the target platform endpoint
@param {Object} attributes the Attributes map; a collection of fields to update | [
"updates",
"the",
"attributes",
"for",
"the",
"specified",
"endpoint"
] | b1c7a03d5687864a6130a7d5b4891d80aec16cdf | https://github.com/mmacmillan/aws-sns-q/blob/b1c7a03d5687864a6130a7d5b4891d80aec16cdf/sns-q.js#L146-L153 |
|
52,921 | mmacmillan/aws-sns-q | sns-q.js | function(topicArn, endpointArn) {
var params = {
TopicArn: topicArn,
Protocol: 'application',
Endpoint: endpointArn
};
return this.svc.subscribe(params);
} | javascript | function(topicArn, endpointArn) {
var params = {
TopicArn: topicArn,
Protocol: 'application',
Endpoint: endpointArn
};
return this.svc.subscribe(params);
} | [
"function",
"(",
"topicArn",
",",
"endpointArn",
")",
"{",
"var",
"params",
"=",
"{",
"TopicArn",
":",
"topicArn",
",",
"Protocol",
":",
"'application'",
",",
"Endpoint",
":",
"endpointArn",
"}",
";",
"return",
"this",
".",
"svc",
".",
"subscribe",
"(",
"params",
")",
";",
"}"
] | shorthand for device specific registrations, assumes the endpoint is an arn, and presets the protocol
to 'application', which is used for mobile devices | [
"shorthand",
"for",
"device",
"specific",
"registrations",
"assumes",
"the",
"endpoint",
"is",
"an",
"arn",
"and",
"presets",
"the",
"protocol",
"to",
"application",
"which",
"is",
"used",
"for",
"mobile",
"devices"
] | b1c7a03d5687864a6130a7d5b4891d80aec16cdf | https://github.com/mmacmillan/aws-sns-q/blob/b1c7a03d5687864a6130a7d5b4891d80aec16cdf/sns-q.js#L276-L284 |
|
52,922 | mmacmillan/aws-sns-q | sns-q.js | messageBuilder | function messageBuilder(msg, args) {
var message = msg,
supported = [],
badge = 0,
builders = {};
//** currently only APNS is supported
builders[platforms.APNS] = builders[platforms.APNSSandbox] = function() {
return {
aps: {
//** adds the custom arguments onto the "alert" object
alert: _.extend({}, { body: msg }, args||{}),
badge: badge
}
};
}
//** sets the supported platforms
this.platforms = function(list) {
if(!Array.isArray(list)) return;
supported = list;
return this;
}
//** shows/clears badges for the app icon
this.showBadge = function(count) {
badge = count;
return this;
}
this.clearBadge = function() {
badge = 0;
return this;
}
this.toJSON = function() {
//** create the composite message object based on the supported platforms
return _.reduce(supported, function(m, platform) {
if(!!builders[platform])
m[platform] = JSON.stringify(builders[platform]());
return m;
},
//** support the default message inherently; this is required for publishing to topics
{ default: msg });
}
this.stringify = function() { return JSON.stringify(this.toJSON()); }
return this;
} | javascript | function messageBuilder(msg, args) {
var message = msg,
supported = [],
badge = 0,
builders = {};
//** currently only APNS is supported
builders[platforms.APNS] = builders[platforms.APNSSandbox] = function() {
return {
aps: {
//** adds the custom arguments onto the "alert" object
alert: _.extend({}, { body: msg }, args||{}),
badge: badge
}
};
}
//** sets the supported platforms
this.platforms = function(list) {
if(!Array.isArray(list)) return;
supported = list;
return this;
}
//** shows/clears badges for the app icon
this.showBadge = function(count) {
badge = count;
return this;
}
this.clearBadge = function() {
badge = 0;
return this;
}
this.toJSON = function() {
//** create the composite message object based on the supported platforms
return _.reduce(supported, function(m, platform) {
if(!!builders[platform])
m[platform] = JSON.stringify(builders[platform]());
return m;
},
//** support the default message inherently; this is required for publishing to topics
{ default: msg });
}
this.stringify = function() { return JSON.stringify(this.toJSON()); }
return this;
} | [
"function",
"messageBuilder",
"(",
"msg",
",",
"args",
")",
"{",
"var",
"message",
"=",
"msg",
",",
"supported",
"=",
"[",
"]",
",",
"badge",
"=",
"0",
",",
"builders",
"=",
"{",
"}",
";",
"//** currently only APNS is supported",
"builders",
"[",
"platforms",
".",
"APNS",
"]",
"=",
"builders",
"[",
"platforms",
".",
"APNSSandbox",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"{",
"aps",
":",
"{",
"//** adds the custom arguments onto the \"alert\" object",
"alert",
":",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"{",
"body",
":",
"msg",
"}",
",",
"args",
"||",
"{",
"}",
")",
",",
"badge",
":",
"badge",
"}",
"}",
";",
"}",
"//** sets the supported platforms",
"this",
".",
"platforms",
"=",
"function",
"(",
"list",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"list",
")",
")",
"return",
";",
"supported",
"=",
"list",
";",
"return",
"this",
";",
"}",
"//** shows/clears badges for the app icon",
"this",
".",
"showBadge",
"=",
"function",
"(",
"count",
")",
"{",
"badge",
"=",
"count",
";",
"return",
"this",
";",
"}",
"this",
".",
"clearBadge",
"=",
"function",
"(",
")",
"{",
"badge",
"=",
"0",
";",
"return",
"this",
";",
"}",
"this",
".",
"toJSON",
"=",
"function",
"(",
")",
"{",
"//** create the composite message object based on the supported platforms",
"return",
"_",
".",
"reduce",
"(",
"supported",
",",
"function",
"(",
"m",
",",
"platform",
")",
"{",
"if",
"(",
"!",
"!",
"builders",
"[",
"platform",
"]",
")",
"m",
"[",
"platform",
"]",
"=",
"JSON",
".",
"stringify",
"(",
"builders",
"[",
"platform",
"]",
"(",
")",
")",
";",
"return",
"m",
";",
"}",
",",
"//** support the default message inherently; this is required for publishing to topics",
"{",
"default",
":",
"msg",
"}",
")",
";",
"}",
"this",
".",
"stringify",
"=",
"function",
"(",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"this",
".",
"toJSON",
"(",
")",
")",
";",
"}",
"return",
"this",
";",
"}"
] | a message builder to abstract the individual format for each platform; supports a message, badges, and custom payloads
@param {String} msg the message we are building platform specific representations of
@param {Object} args individual platform specific payload arguments (optional) | [
"a",
"message",
"builder",
"to",
"abstract",
"the",
"individual",
"format",
"for",
"each",
"platform",
";",
"supports",
"a",
"message",
"badges",
"and",
"custom",
"payloads"
] | b1c7a03d5687864a6130a7d5b4891d80aec16cdf | https://github.com/mmacmillan/aws-sns-q/blob/b1c7a03d5687864a6130a7d5b4891d80aec16cdf/sns-q.js#L310-L360 |
52,923 | blond/rangem | lib/subtract.js | getBorders | function getBorders(ranges) {
var borders = [];
ranges.forEach(function(range) {
var leftBorder = { value: range.from, type: 'from' };
var rightBorder = { value: range.to, type: 'to' };
borders.push(leftBorder, rightBorder);
});
return borders;
} | javascript | function getBorders(ranges) {
var borders = [];
ranges.forEach(function(range) {
var leftBorder = { value: range.from, type: 'from' };
var rightBorder = { value: range.to, type: 'to' };
borders.push(leftBorder, rightBorder);
});
return borders;
} | [
"function",
"getBorders",
"(",
"ranges",
")",
"{",
"var",
"borders",
"=",
"[",
"]",
";",
"ranges",
".",
"forEach",
"(",
"function",
"(",
"range",
")",
"{",
"var",
"leftBorder",
"=",
"{",
"value",
":",
"range",
".",
"from",
",",
"type",
":",
"'from'",
"}",
";",
"var",
"rightBorder",
"=",
"{",
"value",
":",
"range",
".",
"to",
",",
"type",
":",
"'to'",
"}",
";",
"borders",
".",
"push",
"(",
"leftBorder",
",",
"rightBorder",
")",
";",
"}",
")",
";",
"return",
"borders",
";",
"}"
] | Returns borders of ranges.
@param {{from: number, to: number}} ranges — the source ranges.
@returns {{value: number, type: string}} | [
"Returns",
"borders",
"of",
"ranges",
"."
] | bd61375cbb3f2bfb5740cc9c59ea01aec208c90b | https://github.com/blond/rangem/blob/bd61375cbb3f2bfb5740cc9c59ea01aec208c90b/lib/subtract.js#L12-L23 |
52,924 | blond/rangem | lib/subtract.js | isEqualRange | function isEqualRange(range1, range2) {
return range1.from === range2.from && range1.to === range2.to;
} | javascript | function isEqualRange(range1, range2) {
return range1.from === range2.from && range1.to === range2.to;
} | [
"function",
"isEqualRange",
"(",
"range1",
",",
"range2",
")",
"{",
"return",
"range1",
".",
"from",
"===",
"range2",
".",
"from",
"&&",
"range1",
".",
"to",
"===",
"range2",
".",
"to",
";",
"}"
] | Returns `true` if ranges are equal.
@param {{from: number, to: number}} range1 — the range to check.
@param {{from: number, to: number}} range2 — the range to check.
@returns {Boolean} | [
"Returns",
"true",
"if",
"ranges",
"are",
"equal",
"."
] | bd61375cbb3f2bfb5740cc9c59ea01aec208c90b | https://github.com/blond/rangem/blob/bd61375cbb3f2bfb5740cc9c59ea01aec208c90b/lib/subtract.js#L33-L35 |
52,925 | vkiding/jud-vue-render | src/shared/console.js | generateLevelMap | function generateLevelMap () {
LEVELS.forEach(level => {
const levelIndex = LEVELS.indexOf(level)
levelMap[level] = {}
LEVELS.forEach(type => {
const typeIndex = LEVELS.indexOf(type)
if (typeIndex <= levelIndex) {
levelMap[level][type] = true
}
})
})
} | javascript | function generateLevelMap () {
LEVELS.forEach(level => {
const levelIndex = LEVELS.indexOf(level)
levelMap[level] = {}
LEVELS.forEach(type => {
const typeIndex = LEVELS.indexOf(type)
if (typeIndex <= levelIndex) {
levelMap[level][type] = true
}
})
})
} | [
"function",
"generateLevelMap",
"(",
")",
"{",
"LEVELS",
".",
"forEach",
"(",
"level",
"=>",
"{",
"const",
"levelIndex",
"=",
"LEVELS",
".",
"indexOf",
"(",
"level",
")",
"levelMap",
"[",
"level",
"]",
"=",
"{",
"}",
"LEVELS",
".",
"forEach",
"(",
"type",
"=>",
"{",
"const",
"typeIndex",
"=",
"LEVELS",
".",
"indexOf",
"(",
"type",
")",
"if",
"(",
"typeIndex",
"<=",
"levelIndex",
")",
"{",
"levelMap",
"[",
"level",
"]",
"[",
"type",
"]",
"=",
"true",
"}",
"}",
")",
"}",
")",
"}"
] | Generate map for which types of message will be sent in a certain message level
as the order of LEVELS. | [
"Generate",
"map",
"for",
"which",
"types",
"of",
"message",
"will",
"be",
"sent",
"in",
"a",
"certain",
"message",
"level",
"as",
"the",
"order",
"of",
"LEVELS",
"."
] | 07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47 | https://github.com/vkiding/jud-vue-render/blob/07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47/src/shared/console.js#L78-L89 |
52,926 | vkiding/jud-vue-render | src/shared/console.js | checkLevel | function checkLevel (type) {
const logLevel = (global.JUDEnvironment && global.JUDEnvironment.logLevel) || 'log'
return levelMap[logLevel] && levelMap[logLevel][type]
} | javascript | function checkLevel (type) {
const logLevel = (global.JUDEnvironment && global.JUDEnvironment.logLevel) || 'log'
return levelMap[logLevel] && levelMap[logLevel][type]
} | [
"function",
"checkLevel",
"(",
"type",
")",
"{",
"const",
"logLevel",
"=",
"(",
"global",
".",
"JUDEnvironment",
"&&",
"global",
".",
"JUDEnvironment",
".",
"logLevel",
")",
"||",
"'log'",
"return",
"levelMap",
"[",
"logLevel",
"]",
"&&",
"levelMap",
"[",
"logLevel",
"]",
"[",
"type",
"]",
"}"
] | Check if a certain type of message will be sent in current log level of env.
@param {string} type
@return {boolean} | [
"Check",
"if",
"a",
"certain",
"type",
"of",
"message",
"will",
"be",
"sent",
"in",
"current",
"log",
"level",
"of",
"env",
"."
] | 07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47 | https://github.com/vkiding/jud-vue-render/blob/07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47/src/shared/console.js#L96-L99 |
52,927 | vkiding/jud-vue-render | src/shared/console.js | format | function format (args) {
return args.map((v) => {
const type = Object.prototype.toString.call(v)
if (type.toLowerCase() === '[object object]') {
v = JSON.stringify(v)
}
else {
v = String(v)
}
return v
})
} | javascript | function format (args) {
return args.map((v) => {
const type = Object.prototype.toString.call(v)
if (type.toLowerCase() === '[object object]') {
v = JSON.stringify(v)
}
else {
v = String(v)
}
return v
})
} | [
"function",
"format",
"(",
"args",
")",
"{",
"return",
"args",
".",
"map",
"(",
"(",
"v",
")",
"=>",
"{",
"const",
"type",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"v",
")",
"if",
"(",
"type",
".",
"toLowerCase",
"(",
")",
"===",
"'[object object]'",
")",
"{",
"v",
"=",
"JSON",
".",
"stringify",
"(",
"v",
")",
"}",
"else",
"{",
"v",
"=",
"String",
"(",
"v",
")",
"}",
"return",
"v",
"}",
")",
"}"
] | Convert all log arguments into primitive values.
@param {array} args
@return {array}
/* istanbul ignore next | [
"Convert",
"all",
"log",
"arguments",
"into",
"primitive",
"values",
"."
] | 07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47 | https://github.com/vkiding/jud-vue-render/blob/07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47/src/shared/console.js#L107-L118 |
52,928 | NYPL-discovery/sierra-wrapper | index.js | function (url, requestItemsCb) {
// use the bearer auth token
request.get(url, {
'auth': {
'bearer': exports.authorizedToken
}
},
(error, response, body) => {
if (error) console.error(error)
if (response.statusCode && response.statusCode === 200) {
if (requestItemsCb) requestItemsCb(null, JSON.parse(body))
} else {
if (requestItemsCb) requestItemsCb(null, false)
}
})
} | javascript | function (url, requestItemsCb) {
// use the bearer auth token
request.get(url, {
'auth': {
'bearer': exports.authorizedToken
}
},
(error, response, body) => {
if (error) console.error(error)
if (response.statusCode && response.statusCode === 200) {
if (requestItemsCb) requestItemsCb(null, JSON.parse(body))
} else {
if (requestItemsCb) requestItemsCb(null, false)
}
})
} | [
"function",
"(",
"url",
",",
"requestItemsCb",
")",
"{",
"// use the bearer auth token",
"request",
".",
"get",
"(",
"url",
",",
"{",
"'auth'",
":",
"{",
"'bearer'",
":",
"exports",
".",
"authorizedToken",
"}",
"}",
",",
"(",
"error",
",",
"response",
",",
"body",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"console",
".",
"error",
"(",
"error",
")",
"if",
"(",
"response",
".",
"statusCode",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"if",
"(",
"requestItemsCb",
")",
"requestItemsCb",
"(",
"null",
",",
"JSON",
".",
"parse",
"(",
"body",
")",
")",
"}",
"else",
"{",
"if",
"(",
"requestItemsCb",
")",
"requestItemsCb",
"(",
"null",
",",
"false",
")",
"}",
"}",
")",
"}"
] | this is the request function we will curry below | [
"this",
"is",
"the",
"request",
"function",
"we",
"will",
"curry",
"below"
] | 9fb0f82da0ccab129c6a349d39b355c1e176f658 | https://github.com/NYPL-discovery/sierra-wrapper/blob/9fb0f82da0ccab129c6a349d39b355c1e176f658/index.js#L257-L272 |
|
52,929 | freestyle21/grunt-2x2x | tasks/_2x2x.js | function() {
var _2x2x = this;
var guard_file = 0;
var guard_2x = 0;
grunt.file.recurse(this.imgsrcdir, function(file) {
guard_file += 1;
var srcextname = path.extname(file),
srcdirname = path.dirname(file);
if (!grunt.file.isDir(_2x2x.imgdesdir)) {
grunt.file.mkdir(_2x2x.imgdesdir);
}
var has2x = (function() {
return file.indexOf('@2x') > -1;
})();
if(!has2x) {
return false;
}
guard_2x += 1;
_2x2x.series.push(function(callback) {
gm(file).size(function(err, features) {
// find the @2x image and get it's normal name
var outfile = replace2x(file);
var dstPath = _2x2x.imgdesdir + "/" + outfile;
var final_width = features.width;
var final_height = features.height;
// fix the decimals width & height
if((features.height % 2)) {
final_height += 1;
}
if((features.width % 2)) {
final_width += 1;
}
if(!_2x2x.overwrite) {
// not overwrite
if(grunt.file.exists(dstPath)) {
grunt.log.error((dstPath + "is existed already!"));
return false;
}
}
gm(file).autoOrient().
resize(final_width / 2, final_height / 2, "!").
write(dstPath, function(err) {
grunt.log.writelns((dstPath + " has been created !").green);
});
// gm(file).thumb(final_width / 2, final_height / 2, dstPath, _2x2x.quality, function() {
// grunt.log.writelns((dstPath + " has been created !").green);
// });
});
}(file));
});
if((guard_file != 0) && (guard_2x == 0)) {
grunt.log.error('no @2x image in the srcdir! ').red;
}
if(guard_file == 0) {
grunt.log.error('no image in the srcdir! ');
}
async.series(_2x2x.series, that.async());
} | javascript | function() {
var _2x2x = this;
var guard_file = 0;
var guard_2x = 0;
grunt.file.recurse(this.imgsrcdir, function(file) {
guard_file += 1;
var srcextname = path.extname(file),
srcdirname = path.dirname(file);
if (!grunt.file.isDir(_2x2x.imgdesdir)) {
grunt.file.mkdir(_2x2x.imgdesdir);
}
var has2x = (function() {
return file.indexOf('@2x') > -1;
})();
if(!has2x) {
return false;
}
guard_2x += 1;
_2x2x.series.push(function(callback) {
gm(file).size(function(err, features) {
// find the @2x image and get it's normal name
var outfile = replace2x(file);
var dstPath = _2x2x.imgdesdir + "/" + outfile;
var final_width = features.width;
var final_height = features.height;
// fix the decimals width & height
if((features.height % 2)) {
final_height += 1;
}
if((features.width % 2)) {
final_width += 1;
}
if(!_2x2x.overwrite) {
// not overwrite
if(grunt.file.exists(dstPath)) {
grunt.log.error((dstPath + "is existed already!"));
return false;
}
}
gm(file).autoOrient().
resize(final_width / 2, final_height / 2, "!").
write(dstPath, function(err) {
grunt.log.writelns((dstPath + " has been created !").green);
});
// gm(file).thumb(final_width / 2, final_height / 2, dstPath, _2x2x.quality, function() {
// grunt.log.writelns((dstPath + " has been created !").green);
// });
});
}(file));
});
if((guard_file != 0) && (guard_2x == 0)) {
grunt.log.error('no @2x image in the srcdir! ').red;
}
if(guard_file == 0) {
grunt.log.error('no image in the srcdir! ');
}
async.series(_2x2x.series, that.async());
} | [
"function",
"(",
")",
"{",
"var",
"_2x2x",
"=",
"this",
";",
"var",
"guard_file",
"=",
"0",
";",
"var",
"guard_2x",
"=",
"0",
";",
"grunt",
".",
"file",
".",
"recurse",
"(",
"this",
".",
"imgsrcdir",
",",
"function",
"(",
"file",
")",
"{",
"guard_file",
"+=",
"1",
";",
"var",
"srcextname",
"=",
"path",
".",
"extname",
"(",
"file",
")",
",",
"srcdirname",
"=",
"path",
".",
"dirname",
"(",
"file",
")",
";",
"if",
"(",
"!",
"grunt",
".",
"file",
".",
"isDir",
"(",
"_2x2x",
".",
"imgdesdir",
")",
")",
"{",
"grunt",
".",
"file",
".",
"mkdir",
"(",
"_2x2x",
".",
"imgdesdir",
")",
";",
"}",
"var",
"has2x",
"=",
"(",
"function",
"(",
")",
"{",
"return",
"file",
".",
"indexOf",
"(",
"'@2x'",
")",
">",
"-",
"1",
";",
"}",
")",
"(",
")",
";",
"if",
"(",
"!",
"has2x",
")",
"{",
"return",
"false",
";",
"}",
"guard_2x",
"+=",
"1",
";",
"_2x2x",
".",
"series",
".",
"push",
"(",
"function",
"(",
"callback",
")",
"{",
"gm",
"(",
"file",
")",
".",
"size",
"(",
"function",
"(",
"err",
",",
"features",
")",
"{",
"// find the @2x image and get it's normal name",
"var",
"outfile",
"=",
"replace2x",
"(",
"file",
")",
";",
"var",
"dstPath",
"=",
"_2x2x",
".",
"imgdesdir",
"+",
"\"/\"",
"+",
"outfile",
";",
"var",
"final_width",
"=",
"features",
".",
"width",
";",
"var",
"final_height",
"=",
"features",
".",
"height",
";",
"// fix the decimals width & height",
"if",
"(",
"(",
"features",
".",
"height",
"%",
"2",
")",
")",
"{",
"final_height",
"+=",
"1",
";",
"}",
"if",
"(",
"(",
"features",
".",
"width",
"%",
"2",
")",
")",
"{",
"final_width",
"+=",
"1",
";",
"}",
"if",
"(",
"!",
"_2x2x",
".",
"overwrite",
")",
"{",
"// not overwrite",
"if",
"(",
"grunt",
".",
"file",
".",
"exists",
"(",
"dstPath",
")",
")",
"{",
"grunt",
".",
"log",
".",
"error",
"(",
"(",
"dstPath",
"+",
"\"is existed already!\"",
")",
")",
";",
"return",
"false",
";",
"}",
"}",
"gm",
"(",
"file",
")",
".",
"autoOrient",
"(",
")",
".",
"resize",
"(",
"final_width",
"/",
"2",
",",
"final_height",
"/",
"2",
",",
"\"!\"",
")",
".",
"write",
"(",
"dstPath",
",",
"function",
"(",
"err",
")",
"{",
"grunt",
".",
"log",
".",
"writelns",
"(",
"(",
"dstPath",
"+",
"\" has been created !\"",
")",
".",
"green",
")",
";",
"}",
")",
";",
"// gm(file).thumb(final_width / 2, final_height / 2, dstPath, _2x2x.quality, function() {",
"// grunt.log.writelns((dstPath + \" has been created !\").green);",
"// });",
"}",
")",
";",
"}",
"(",
"file",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"(",
"guard_file",
"!=",
"0",
")",
"&&",
"(",
"guard_2x",
"==",
"0",
")",
")",
"{",
"grunt",
".",
"log",
".",
"error",
"(",
"'no @2x image in the srcdir! '",
")",
".",
"red",
";",
"}",
"if",
"(",
"guard_file",
"==",
"0",
")",
"{",
"grunt",
".",
"log",
".",
"error",
"(",
"'no image in the srcdir! '",
")",
";",
"}",
"async",
".",
"series",
"(",
"_2x2x",
".",
"series",
",",
"that",
".",
"async",
"(",
")",
")",
";",
"}"
] | ergodic the img in imgsrcdir | [
"ergodic",
"the",
"img",
"in",
"imgsrcdir"
] | 8466a623dfa03ce2067cbaf540fc00196925a67c | https://github.com/freestyle21/grunt-2x2x/blob/8466a623dfa03ce2067cbaf540fc00196925a67c/tasks/_2x2x.js#L42-L110 |
|
52,930 | mattmccray/blam.js | blam.js | function(){
var args= slice.call(arguments), block= args.pop();
return blam.compile(block, ctx).apply(tagset, args);
} | javascript | function(){
var args= slice.call(arguments), block= args.pop();
return blam.compile(block, ctx).apply(tagset, args);
} | [
"function",
"(",
")",
"{",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"block",
"=",
"args",
".",
"pop",
"(",
")",
";",
"return",
"blam",
".",
"compile",
"(",
"block",
",",
"ctx",
")",
".",
"apply",
"(",
"tagset",
",",
"args",
")",
";",
"}"
] | Did throw exception... | [
"Did",
"throw",
"exception",
"..."
] | a535b6fe9679b687897ac0dc18b26585a5c3a114 | https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/blam.js#L58-L61 |
|
52,931 | eliOcs/node-envy | envy.js | deepCopy | function deepCopy(destination, source) {
Object.keys(source).forEach(function (property) {
if (destination[property] && isObject(destination[property])) {
deepCopy(destination[property], source[property]);
} else {
destination[property] = source[property];
}
});
} | javascript | function deepCopy(destination, source) {
Object.keys(source).forEach(function (property) {
if (destination[property] && isObject(destination[property])) {
deepCopy(destination[property], source[property]);
} else {
destination[property] = source[property];
}
});
} | [
"function",
"deepCopy",
"(",
"destination",
",",
"source",
")",
"{",
"Object",
".",
"keys",
"(",
"source",
")",
".",
"forEach",
"(",
"function",
"(",
"property",
")",
"{",
"if",
"(",
"destination",
"[",
"property",
"]",
"&&",
"isObject",
"(",
"destination",
"[",
"property",
"]",
")",
")",
"{",
"deepCopy",
"(",
"destination",
"[",
"property",
"]",
",",
"source",
"[",
"property",
"]",
")",
";",
"}",
"else",
"{",
"destination",
"[",
"property",
"]",
"=",
"source",
"[",
"property",
"]",
";",
"}",
"}",
")",
";",
"}"
] | Deep copies the properties of the source object into the destination
object. | [
"Deep",
"copies",
"the",
"properties",
"of",
"the",
"source",
"object",
"into",
"the",
"destination",
"object",
"."
] | ec1b59cc1ac4901ef5bca6acd8a7abb1f0de0e81 | https://github.com/eliOcs/node-envy/blob/ec1b59cc1ac4901ef5bca6acd8a7abb1f0de0e81/envy.js#L24-L32 |
52,932 | jgnewman/brightsocket.io | bin/poolapi.js | runExtensions | function runExtensions(settings) {
var extensions = settings.extensions,
channels = settings.channels,
connection = settings.connection,
userPackage = settings.userPackage,
server = settings.server;
// For every extension the user listed...
extensions.forEach(function (extension) {
// Find the callbacks associated with that extension.
var callbacks = channels[extension];
// If there aren't any, we're trying to extend something that hasn't
// been defined yet.
if (!callbacks) {
throw new Error('Can not extend channel ' + extension + ' because it does not exist.');
// Otherwise, we can call each one.
} else {
callbacks.forEach(function (callback) {
return callback(connection, userPackage, server);
});
}
});
} | javascript | function runExtensions(settings) {
var extensions = settings.extensions,
channels = settings.channels,
connection = settings.connection,
userPackage = settings.userPackage,
server = settings.server;
// For every extension the user listed...
extensions.forEach(function (extension) {
// Find the callbacks associated with that extension.
var callbacks = channels[extension];
// If there aren't any, we're trying to extend something that hasn't
// been defined yet.
if (!callbacks) {
throw new Error('Can not extend channel ' + extension + ' because it does not exist.');
// Otherwise, we can call each one.
} else {
callbacks.forEach(function (callback) {
return callback(connection, userPackage, server);
});
}
});
} | [
"function",
"runExtensions",
"(",
"settings",
")",
"{",
"var",
"extensions",
"=",
"settings",
".",
"extensions",
",",
"channels",
"=",
"settings",
".",
"channels",
",",
"connection",
"=",
"settings",
".",
"connection",
",",
"userPackage",
"=",
"settings",
".",
"userPackage",
",",
"server",
"=",
"settings",
".",
"server",
";",
"// For every extension the user listed...",
"extensions",
".",
"forEach",
"(",
"function",
"(",
"extension",
")",
"{",
"// Find the callbacks associated with that extension.",
"var",
"callbacks",
"=",
"channels",
"[",
"extension",
"]",
";",
"// If there aren't any, we're trying to extend something that hasn't",
"// been defined yet.",
"if",
"(",
"!",
"callbacks",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Can not extend channel '",
"+",
"extension",
"+",
"' because it does not exist.'",
")",
";",
"// Otherwise, we can call each one.",
"}",
"else",
"{",
"callbacks",
".",
"forEach",
"(",
"function",
"(",
"callback",
")",
"{",
"return",
"callback",
"(",
"connection",
",",
"userPackage",
",",
"server",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Runs a series of callbacks for a new connection.
@param {Object} settings - All the values we'll need to run the callbacks.
@return {undefined} | [
"Runs",
"a",
"series",
"of",
"callbacks",
"for",
"a",
"new",
"connection",
"."
] | 19ec67d69946ab09ca389143ebbdcb0a7f22f950 | https://github.com/jgnewman/brightsocket.io/blob/19ec67d69946ab09ca389143ebbdcb0a7f22f950/bin/poolapi.js#L44-L70 |
52,933 | jgnewman/brightsocket.io | bin/poolapi.js | cleanIdentity | function cleanIdentity(identity) {
var userPackage = {};
Object.keys(identity).forEach(function (key) {
if (key.indexOf('BRIGHTSOCKET:') !== 0) {
userPackage[key] = identity[key];
}
});
return userPackage;
} | javascript | function cleanIdentity(identity) {
var userPackage = {};
Object.keys(identity).forEach(function (key) {
if (key.indexOf('BRIGHTSOCKET:') !== 0) {
userPackage[key] = identity[key];
}
});
return userPackage;
} | [
"function",
"cleanIdentity",
"(",
"identity",
")",
"{",
"var",
"userPackage",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"identity",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"key",
".",
"indexOf",
"(",
"'BRIGHTSOCKET:'",
")",
"!==",
"0",
")",
"{",
"userPackage",
"[",
"key",
"]",
"=",
"identity",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"return",
"userPackage",
";",
"}"
] | Takes an incoming identity package and strips out keys
that were inserted by Brightsocket.
@param {Object} identity - Came in from the IDENTIFY action.
@return {Object} The clean object. | [
"Takes",
"an",
"incoming",
"identity",
"package",
"and",
"strips",
"out",
"keys",
"that",
"were",
"inserted",
"by",
"Brightsocket",
"."
] | 19ec67d69946ab09ca389143ebbdcb0a7f22f950 | https://github.com/jgnewman/brightsocket.io/blob/19ec67d69946ab09ca389143ebbdcb0a7f22f950/bin/poolapi.js#L80-L88 |
52,934 | jgnewman/brightsocket.io | bin/poolapi.js | PoolAPI | function PoolAPI(server) {
_classCallCheck(this, PoolAPI);
this.pool = (0, _socketpool2.default)(server);
this.server = server;
this.channels = {};
} | javascript | function PoolAPI(server) {
_classCallCheck(this, PoolAPI);
this.pool = (0, _socketpool2.default)(server);
this.server = server;
this.channels = {};
} | [
"function",
"PoolAPI",
"(",
"server",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"PoolAPI",
")",
";",
"this",
".",
"pool",
"=",
"(",
"0",
",",
"_socketpool2",
".",
"default",
")",
"(",
"server",
")",
";",
"this",
".",
"server",
"=",
"server",
";",
"this",
".",
"channels",
"=",
"{",
"}",
";",
"}"
] | Builds the class. | [
"Builds",
"the",
"class",
"."
] | 19ec67d69946ab09ca389143ebbdcb0a7f22f950 | https://github.com/jgnewman/brightsocket.io/blob/19ec67d69946ab09ca389143ebbdcb0a7f22f950/bin/poolapi.js#L95-L101 |
52,935 | PeerioTechnologies/peerio-updater | fetch.js | get | function get(address, contentType, redirs = 0, tries = 0) {
return new Promise((fulfill, reject) => {
const { host, path } = url.parse(address);
const options = {
headers: { 'User-Agent': 'peerio-updater/1.0' },
timeout: REQUEST_TIMEOUT,
host,
path
};
const req = https.get(options, res => {
if (res.statusCode === 404) {
reject(new Error(`Not found: ${address}`));
return;
}
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers['location']) {
res.resume();
if (redirs >= MAX_REDIRECTS) {
reject(new Error('Too many redirects'));
return;
}
let location = res.headers['location']; // always string according to Node docs
if (!/^https?:/.test(location)) {
location = url.resolve(address, location);
}
if (!location.startsWith('https:')) {
reject(new Error(`Unsafe redirect to ${location}`));
return;
}
fulfill(get(location, contentType, redirs + 1, tries));
return;
}
if (res.statusCode !== 200) {
res.resume();
if (tries < MAX_RETRIES) {
fulfill(waitBeforeRetry(tries).then(() =>
get(address, contentType, 0, tries + 1))
);
} else {
reject(new Error(`Request failed with status ${res.statusCode}`));
}
return;
}
if (contentType) {
let got = res.headers['content-type'] || '';
// Strip anything after ';' (e.g. application/json; charset=utf8)
const semicolon = got.indexOf(';')
if (semicolon >= 0) got = got.substring(0, semicolon);
if (contentType !== got) {
res.resume();
reject(new Error(`Unexpected content type: ${got}`));
return;
}
}
fulfill(res);
});
const handleError = err => {
if (tries < MAX_RETRIES) {
fulfill(waitBeforeRetry(tries).then(() =>
get(address, contentType, 0, tries + 1))
);
} else {
reject(new Error(`Request failed: ${err.message}`));
}
};
req.on('error', handleError);
req.on('timeout', () => {
req.abort();
handleError(new Error('Request timed out'));
});
});
} | javascript | function get(address, contentType, redirs = 0, tries = 0) {
return new Promise((fulfill, reject) => {
const { host, path } = url.parse(address);
const options = {
headers: { 'User-Agent': 'peerio-updater/1.0' },
timeout: REQUEST_TIMEOUT,
host,
path
};
const req = https.get(options, res => {
if (res.statusCode === 404) {
reject(new Error(`Not found: ${address}`));
return;
}
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers['location']) {
res.resume();
if (redirs >= MAX_REDIRECTS) {
reject(new Error('Too many redirects'));
return;
}
let location = res.headers['location']; // always string according to Node docs
if (!/^https?:/.test(location)) {
location = url.resolve(address, location);
}
if (!location.startsWith('https:')) {
reject(new Error(`Unsafe redirect to ${location}`));
return;
}
fulfill(get(location, contentType, redirs + 1, tries));
return;
}
if (res.statusCode !== 200) {
res.resume();
if (tries < MAX_RETRIES) {
fulfill(waitBeforeRetry(tries).then(() =>
get(address, contentType, 0, tries + 1))
);
} else {
reject(new Error(`Request failed with status ${res.statusCode}`));
}
return;
}
if (contentType) {
let got = res.headers['content-type'] || '';
// Strip anything after ';' (e.g. application/json; charset=utf8)
const semicolon = got.indexOf(';')
if (semicolon >= 0) got = got.substring(0, semicolon);
if (contentType !== got) {
res.resume();
reject(new Error(`Unexpected content type: ${got}`));
return;
}
}
fulfill(res);
});
const handleError = err => {
if (tries < MAX_RETRIES) {
fulfill(waitBeforeRetry(tries).then(() =>
get(address, contentType, 0, tries + 1))
);
} else {
reject(new Error(`Request failed: ${err.message}`));
}
};
req.on('error', handleError);
req.on('timeout', () => {
req.abort();
handleError(new Error('Request timed out'));
});
});
} | [
"function",
"get",
"(",
"address",
",",
"contentType",
",",
"redirs",
"=",
"0",
",",
"tries",
"=",
"0",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"fulfill",
",",
"reject",
")",
"=>",
"{",
"const",
"{",
"host",
",",
"path",
"}",
"=",
"url",
".",
"parse",
"(",
"address",
")",
";",
"const",
"options",
"=",
"{",
"headers",
":",
"{",
"'User-Agent'",
":",
"'peerio-updater/1.0'",
"}",
",",
"timeout",
":",
"REQUEST_TIMEOUT",
",",
"host",
",",
"path",
"}",
";",
"const",
"req",
"=",
"https",
".",
"get",
"(",
"options",
",",
"res",
"=>",
"{",
"if",
"(",
"res",
".",
"statusCode",
"===",
"404",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"address",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"res",
".",
"statusCode",
">=",
"300",
"&&",
"res",
".",
"statusCode",
"<",
"400",
"&&",
"res",
".",
"headers",
"[",
"'location'",
"]",
")",
"{",
"res",
".",
"resume",
"(",
")",
";",
"if",
"(",
"redirs",
">=",
"MAX_REDIRECTS",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Too many redirects'",
")",
")",
";",
"return",
";",
"}",
"let",
"location",
"=",
"res",
".",
"headers",
"[",
"'location'",
"]",
";",
"// always string according to Node docs",
"if",
"(",
"!",
"/",
"^https?:",
"/",
".",
"test",
"(",
"location",
")",
")",
"{",
"location",
"=",
"url",
".",
"resolve",
"(",
"address",
",",
"location",
")",
";",
"}",
"if",
"(",
"!",
"location",
".",
"startsWith",
"(",
"'https:'",
")",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"location",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"fulfill",
"(",
"get",
"(",
"location",
",",
"contentType",
",",
"redirs",
"+",
"1",
",",
"tries",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"res",
".",
"statusCode",
"!==",
"200",
")",
"{",
"res",
".",
"resume",
"(",
")",
";",
"if",
"(",
"tries",
"<",
"MAX_RETRIES",
")",
"{",
"fulfill",
"(",
"waitBeforeRetry",
"(",
"tries",
")",
".",
"then",
"(",
"(",
")",
"=>",
"get",
"(",
"address",
",",
"contentType",
",",
"0",
",",
"tries",
"+",
"1",
")",
")",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"res",
".",
"statusCode",
"}",
"`",
")",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"contentType",
")",
"{",
"let",
"got",
"=",
"res",
".",
"headers",
"[",
"'content-type'",
"]",
"||",
"''",
";",
"// Strip anything after ';' (e.g. application/json; charset=utf8)",
"const",
"semicolon",
"=",
"got",
".",
"indexOf",
"(",
"';'",
")",
"if",
"(",
"semicolon",
">=",
"0",
")",
"got",
"=",
"got",
".",
"substring",
"(",
"0",
",",
"semicolon",
")",
";",
"if",
"(",
"contentType",
"!==",
"got",
")",
"{",
"res",
".",
"resume",
"(",
")",
";",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"got",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"}",
"fulfill",
"(",
"res",
")",
";",
"}",
")",
";",
"const",
"handleError",
"=",
"err",
"=>",
"{",
"if",
"(",
"tries",
"<",
"MAX_RETRIES",
")",
"{",
"fulfill",
"(",
"waitBeforeRetry",
"(",
"tries",
")",
".",
"then",
"(",
"(",
")",
"=>",
"get",
"(",
"address",
",",
"contentType",
",",
"0",
",",
"tries",
"+",
"1",
")",
")",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
")",
";",
"}",
"}",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"handleError",
")",
";",
"req",
".",
"on",
"(",
"'timeout'",
",",
"(",
")",
"=>",
"{",
"req",
".",
"abort",
"(",
")",
";",
"handleError",
"(",
"new",
"Error",
"(",
"'Request timed out'",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Initiates get request and returns a promise resolving to response object.
Handles redirects up to MAX_REDIRECTS.
Repeats on errors (except for 404) up to MAX_RETRIES times.
On success, the response must be fully consumed by the caller to avoid
leaking memory.
@param {string} address - requested URL (must start with `https://`)
@param {string?} [contentType] - expected content-type or undefined/null to not check it
@returns {Promise<https.IncomingMessage>} | [
"Initiates",
"get",
"request",
"and",
"returns",
"a",
"promise",
"resolving",
"to",
"response",
"object",
"."
] | 9d6fedeec727f16a31653e4bbd4efe164e0957cb | https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/fetch.js#L41-L113 |
52,936 | PeerioTechnologies/peerio-updater | fetch.js | streamToText | function streamToText(stream) {
return new Promise((fulfill, reject) => {
let chunks = [];
let length = 0;
stream.setEncoding('utf8');
stream.on('data', chunk => {
length += chunk.length;
if (length > MAX_TEXT_LENGTH) {
reject(new Error('Response is too big'));
return;
}
chunks.push(chunk);
});
stream.on('end', () => {
fulfill(chunks.join(''));
});
stream.on('error', err => {
reject(err);
});
});
} | javascript | function streamToText(stream) {
return new Promise((fulfill, reject) => {
let chunks = [];
let length = 0;
stream.setEncoding('utf8');
stream.on('data', chunk => {
length += chunk.length;
if (length > MAX_TEXT_LENGTH) {
reject(new Error('Response is too big'));
return;
}
chunks.push(chunk);
});
stream.on('end', () => {
fulfill(chunks.join(''));
});
stream.on('error', err => {
reject(err);
});
});
} | [
"function",
"streamToText",
"(",
"stream",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"fulfill",
",",
"reject",
")",
"=>",
"{",
"let",
"chunks",
"=",
"[",
"]",
";",
"let",
"length",
"=",
"0",
";",
"stream",
".",
"setEncoding",
"(",
"'utf8'",
")",
";",
"stream",
".",
"on",
"(",
"'data'",
",",
"chunk",
"=>",
"{",
"length",
"+=",
"chunk",
".",
"length",
";",
"if",
"(",
"length",
">",
"MAX_TEXT_LENGTH",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Response is too big'",
")",
")",
";",
"return",
";",
"}",
"chunks",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"fulfill",
"(",
"chunks",
".",
"join",
"(",
"''",
")",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Reads the given stream and returns it as string.
Rejects if data is larger than MAX_TEXT_LENGTH.
@param {stream.Readable} stream
@returns {Promise<string>} received text | [
"Reads",
"the",
"given",
"stream",
"and",
"returns",
"it",
"as",
"string",
".",
"Rejects",
"if",
"data",
"is",
"larger",
"than",
"MAX_TEXT_LENGTH",
"."
] | 9d6fedeec727f16a31653e4bbd4efe164e0957cb | https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/fetch.js#L122-L142 |
52,937 | PeerioTechnologies/peerio-updater | fetch.js | fetchText | function fetchText(address, contentType) {
return get(address, contentType)
.then(streamToText)
.catch(err => {
console.error(`Fetch error: ${err.message}`);
throw err; // re-throw
});
} | javascript | function fetchText(address, contentType) {
return get(address, contentType)
.then(streamToText)
.catch(err => {
console.error(`Fetch error: ${err.message}`);
throw err; // re-throw
});
} | [
"function",
"fetchText",
"(",
"address",
",",
"contentType",
")",
"{",
"return",
"get",
"(",
"address",
",",
"contentType",
")",
".",
"then",
"(",
"streamToText",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
";",
"throw",
"err",
";",
"// re-throw",
"}",
")",
";",
"}"
] | Fetches text from the given address.
Rejects if received text is larger than MAX_TEXT_LENGTH.
@param {string} address source URL
@param {string?} [contentType] expected content type or undefined if any
@returns {Promise<string>} resulting text | [
"Fetches",
"text",
"from",
"the",
"given",
"address",
".",
"Rejects",
"if",
"received",
"text",
"is",
"larger",
"than",
"MAX_TEXT_LENGTH",
"."
] | 9d6fedeec727f16a31653e4bbd4efe164e0957cb | https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/fetch.js#L152-L159 |
52,938 | PeerioTechnologies/peerio-updater | fetch.js | fetchFile | function fetchFile(address, filepath) {
return get(address)
.then(res => new Promise((fulfill, reject) => {
const file = fs.createWriteStream(filepath);
res.on('error', err => {
// reading error
file.close();
fs.unlink(filepath, err => { // best effort
if (err) console.error(err);
});
reject(err);
});
file.on('error', err => {
// writing error
fs.unlink(filepath, err => { // best effort
if (err) console.error(err);
});
reject(err);
});
file.on('finish', () => {
fulfill(filepath);
});
res.pipe(file);
}));
} | javascript | function fetchFile(address, filepath) {
return get(address)
.then(res => new Promise((fulfill, reject) => {
const file = fs.createWriteStream(filepath);
res.on('error', err => {
// reading error
file.close();
fs.unlink(filepath, err => { // best effort
if (err) console.error(err);
});
reject(err);
});
file.on('error', err => {
// writing error
fs.unlink(filepath, err => { // best effort
if (err) console.error(err);
});
reject(err);
});
file.on('finish', () => {
fulfill(filepath);
});
res.pipe(file);
}));
} | [
"function",
"fetchFile",
"(",
"address",
",",
"filepath",
")",
"{",
"return",
"get",
"(",
"address",
")",
".",
"then",
"(",
"res",
"=>",
"new",
"Promise",
"(",
"(",
"fulfill",
",",
"reject",
")",
"=>",
"{",
"const",
"file",
"=",
"fs",
".",
"createWriteStream",
"(",
"filepath",
")",
";",
"res",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"// reading error",
"file",
".",
"close",
"(",
")",
";",
"fs",
".",
"unlink",
"(",
"filepath",
",",
"err",
"=>",
"{",
"// best effort",
"if",
"(",
"err",
")",
"console",
".",
"error",
"(",
"err",
")",
";",
"}",
")",
";",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"file",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"// writing error",
"fs",
".",
"unlink",
"(",
"filepath",
",",
"err",
"=>",
"{",
"// best effort",
"if",
"(",
"err",
")",
"console",
".",
"error",
"(",
"err",
")",
";",
"}",
")",
";",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"file",
".",
"on",
"(",
"'finish'",
",",
"(",
")",
"=>",
"{",
"fulfill",
"(",
"filepath",
")",
";",
"}",
")",
";",
"res",
".",
"pipe",
"(",
"file",
")",
";",
"}",
")",
")",
";",
"}"
] | Fetches file from the given address, creating a file
into the given file path.
@param {string} address source URL
@param {string} filepath destination file path
@returns {Promise<string>} promise resolving to the destination file path | [
"Fetches",
"file",
"from",
"the",
"given",
"address",
"creating",
"a",
"file",
"into",
"the",
"given",
"file",
"path",
"."
] | 9d6fedeec727f16a31653e4bbd4efe164e0957cb | https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/fetch.js#L210-L234 |
52,939 | HenriJ/careless | vendor/fbtransform/visitors.js | getVisitorsBySet | function getVisitorsBySet(sets) {
var visitorsToInclude = sets.reduce(function(visitors, set) {
if (!transformSets.hasOwnProperty(set)) {
throw new Error('Unknown visitor set: ' + set);
}
transformSets[set].forEach(function(visitor) {
visitors[visitor] = true;
});
return visitors;
}, {});
var visitorList = [];
for (var i = 0; i < transformRunOrder.length; i++) {
if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) {
visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]);
}
}
return visitorList;
} | javascript | function getVisitorsBySet(sets) {
var visitorsToInclude = sets.reduce(function(visitors, set) {
if (!transformSets.hasOwnProperty(set)) {
throw new Error('Unknown visitor set: ' + set);
}
transformSets[set].forEach(function(visitor) {
visitors[visitor] = true;
});
return visitors;
}, {});
var visitorList = [];
for (var i = 0; i < transformRunOrder.length; i++) {
if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) {
visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]);
}
}
return visitorList;
} | [
"function",
"getVisitorsBySet",
"(",
"sets",
")",
"{",
"var",
"visitorsToInclude",
"=",
"sets",
".",
"reduce",
"(",
"function",
"(",
"visitors",
",",
"set",
")",
"{",
"if",
"(",
"!",
"transformSets",
".",
"hasOwnProperty",
"(",
"set",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown visitor set: '",
"+",
"set",
")",
";",
"}",
"transformSets",
"[",
"set",
"]",
".",
"forEach",
"(",
"function",
"(",
"visitor",
")",
"{",
"visitors",
"[",
"visitor",
"]",
"=",
"true",
";",
"}",
")",
";",
"return",
"visitors",
";",
"}",
",",
"{",
"}",
")",
";",
"var",
"visitorList",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"transformRunOrder",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"visitorsToInclude",
".",
"hasOwnProperty",
"(",
"transformRunOrder",
"[",
"i",
"]",
")",
")",
"{",
"visitorList",
"=",
"visitorList",
".",
"concat",
"(",
"transformVisitors",
"[",
"transformRunOrder",
"[",
"i",
"]",
"]",
")",
";",
"}",
"}",
"return",
"visitorList",
";",
"}"
] | Given a list of visitor set names, return the ordered list of visitors to be
passed to jstransform.
@param {array}
@return {array} | [
"Given",
"a",
"list",
"of",
"visitor",
"set",
"names",
"return",
"the",
"ordered",
"list",
"of",
"visitors",
"to",
"be",
"passed",
"to",
"jstransform",
"."
] | 7dea2384b412bf2a03e111dae22055dd9bdf95fe | https://github.com/HenriJ/careless/blob/7dea2384b412bf2a03e111dae22055dd9bdf95fe/vendor/fbtransform/visitors.js#L83-L102 |
52,940 | StudioLE/sqwk | lib/index.js | function(user_opts) {
// Set options
this.options = _.defaults(user_opts, this.options)
// Set title
// this.options.title = chalk.bold(this.options.title)
// Without this, we would only get streams once enter is pressed
process.stdin.setRawMode(true)
// Resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
process.stdin.resume()
} | javascript | function(user_opts) {
// Set options
this.options = _.defaults(user_opts, this.options)
// Set title
// this.options.title = chalk.bold(this.options.title)
// Without this, we would only get streams once enter is pressed
process.stdin.setRawMode(true)
// Resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
process.stdin.resume()
} | [
"function",
"(",
"user_opts",
")",
"{",
"// Set options",
"this",
".",
"options",
"=",
"_",
".",
"defaults",
"(",
"user_opts",
",",
"this",
".",
"options",
")",
"// Set title",
"// this.options.title = chalk.bold(this.options.title)",
"// Without this, we would only get streams once enter is pressed",
"process",
".",
"stdin",
".",
"setRawMode",
"(",
"true",
")",
"// Resume stdin in the parent process (node app won't quit all by itself",
"// unless an error or process.exit() happens)",
"process",
".",
"stdin",
".",
"resume",
"(",
")",
"}"
] | Set options and capture user input
@method init
@param {Object} options Options | [
"Set",
"options",
"and",
"capture",
"user",
"input"
] | 8eabaf71a84e07f9870b80526ca5194197df454f | https://github.com/StudioLE/sqwk/blob/8eabaf71a84e07f9870b80526ca5194197df454f/lib/index.js#L27-L40 |
|
52,941 | StudioLE/sqwk | lib/index.js | function(message, options, callback) {
// If no callback given create one
if( ! callback) callback = function() {}
// If a previous terminal has been opened then close it
if(terminal) terminal.close()
terminal = t_menu(this.options.menu)
// Reset the terminal, clearing all contents
if(this.options.reset) terminal.reset()
if(this.options.title) terminal.write(this.options.formatTitle() + '\n\n')
// Write message or messages to the console
if(_.isString(message)) message = [message]
_.each(message, function(message) {
terminal.write(chalk.bold(message + '\n'))
})
terminal.write('\n')
// If options were given write them to the console
if(options) {
_.each(options, function(option) {
terminal.add(option)
})
terminal.write('\n')
terminal.add('Cancel')
}
// Pipe the terminal menu to the console
process.stdin.pipe(terminal.createStream()).pipe(process.stdout)
// Run callback when a terminal item is selected
terminal.on('select', function(item, index) {
if(item == 'Cancel') return callback(Error('Cancelled by user'))
callback(null, item, index)
})
terminal.on('error', function(err) {
callback(err)
})
process.stdin.on('error', function(err) {
callback(err)
})
return terminal
} | javascript | function(message, options, callback) {
// If no callback given create one
if( ! callback) callback = function() {}
// If a previous terminal has been opened then close it
if(terminal) terminal.close()
terminal = t_menu(this.options.menu)
// Reset the terminal, clearing all contents
if(this.options.reset) terminal.reset()
if(this.options.title) terminal.write(this.options.formatTitle() + '\n\n')
// Write message or messages to the console
if(_.isString(message)) message = [message]
_.each(message, function(message) {
terminal.write(chalk.bold(message + '\n'))
})
terminal.write('\n')
// If options were given write them to the console
if(options) {
_.each(options, function(option) {
terminal.add(option)
})
terminal.write('\n')
terminal.add('Cancel')
}
// Pipe the terminal menu to the console
process.stdin.pipe(terminal.createStream()).pipe(process.stdout)
// Run callback when a terminal item is selected
terminal.on('select', function(item, index) {
if(item == 'Cancel') return callback(Error('Cancelled by user'))
callback(null, item, index)
})
terminal.on('error', function(err) {
callback(err)
})
process.stdin.on('error', function(err) {
callback(err)
})
return terminal
} | [
"function",
"(",
"message",
",",
"options",
",",
"callback",
")",
"{",
"// If no callback given create one",
"if",
"(",
"!",
"callback",
")",
"callback",
"=",
"function",
"(",
")",
"{",
"}",
"// If a previous terminal has been opened then close it",
"if",
"(",
"terminal",
")",
"terminal",
".",
"close",
"(",
")",
"terminal",
"=",
"t_menu",
"(",
"this",
".",
"options",
".",
"menu",
")",
"// Reset the terminal, clearing all contents",
"if",
"(",
"this",
".",
"options",
".",
"reset",
")",
"terminal",
".",
"reset",
"(",
")",
"if",
"(",
"this",
".",
"options",
".",
"title",
")",
"terminal",
".",
"write",
"(",
"this",
".",
"options",
".",
"formatTitle",
"(",
")",
"+",
"'\\n\\n'",
")",
"// Write message or messages to the console",
"if",
"(",
"_",
".",
"isString",
"(",
"message",
")",
")",
"message",
"=",
"[",
"message",
"]",
"_",
".",
"each",
"(",
"message",
",",
"function",
"(",
"message",
")",
"{",
"terminal",
".",
"write",
"(",
"chalk",
".",
"bold",
"(",
"message",
"+",
"'\\n'",
")",
")",
"}",
")",
"terminal",
".",
"write",
"(",
"'\\n'",
")",
"// If options were given write them to the console",
"if",
"(",
"options",
")",
"{",
"_",
".",
"each",
"(",
"options",
",",
"function",
"(",
"option",
")",
"{",
"terminal",
".",
"add",
"(",
"option",
")",
"}",
")",
"terminal",
".",
"write",
"(",
"'\\n'",
")",
"terminal",
".",
"add",
"(",
"'Cancel'",
")",
"}",
"// Pipe the terminal menu to the console",
"process",
".",
"stdin",
".",
"pipe",
"(",
"terminal",
".",
"createStream",
"(",
")",
")",
".",
"pipe",
"(",
"process",
".",
"stdout",
")",
"// Run callback when a terminal item is selected",
"terminal",
".",
"on",
"(",
"'select'",
",",
"function",
"(",
"item",
",",
"index",
")",
"{",
"if",
"(",
"item",
"==",
"'Cancel'",
")",
"return",
"callback",
"(",
"Error",
"(",
"'Cancelled by user'",
")",
")",
"callback",
"(",
"null",
",",
"item",
",",
"index",
")",
"}",
")",
"terminal",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
"}",
")",
"process",
".",
"stdin",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
"}",
")",
"return",
"terminal",
"}"
] | Write a message or menu to the terminal
@method write
@param {String|Array} message Message or messages
@param {Array} options Selectable menu options
@param {Function} callback
@return {Object} Terminal object | [
"Write",
"a",
"message",
"or",
"menu",
"to",
"the",
"terminal"
] | 8eabaf71a84e07f9870b80526ca5194197df454f | https://github.com/StudioLE/sqwk/blob/8eabaf71a84e07f9870b80526ca5194197df454f/lib/index.js#L51-L101 |
|
52,942 | StudioLE/sqwk | lib/index.js | function(err, exit) {
// Close the terminal
if(terminal) terminal.close()
// If there was an error throw it before exit
if(err) throw err
// process.stdin.resume() prevents node from exiting.
// process.exit() overrides in more cases than stdin.pause() or stdin.end()
// it also means we don't need to call process.stdin.setRawMode(false)
if(exit === undefined || exit) {
process.exit()
}
else {
process.stdin.setRawMode(false)
process.stdin.end()
}
} | javascript | function(err, exit) {
// Close the terminal
if(terminal) terminal.close()
// If there was an error throw it before exit
if(err) throw err
// process.stdin.resume() prevents node from exiting.
// process.exit() overrides in more cases than stdin.pause() or stdin.end()
// it also means we don't need to call process.stdin.setRawMode(false)
if(exit === undefined || exit) {
process.exit()
}
else {
process.stdin.setRawMode(false)
process.stdin.end()
}
} | [
"function",
"(",
"err",
",",
"exit",
")",
"{",
"// Close the terminal",
"if",
"(",
"terminal",
")",
"terminal",
".",
"close",
"(",
")",
"// If there was an error throw it before exit",
"if",
"(",
"err",
")",
"throw",
"err",
"// process.stdin.resume() prevents node from exiting.",
"// process.exit() overrides in more cases than stdin.pause() or stdin.end()",
"// it also means we don't need to call process.stdin.setRawMode(false)",
"if",
"(",
"exit",
"===",
"undefined",
"||",
"exit",
")",
"{",
"process",
".",
"exit",
"(",
")",
"}",
"else",
"{",
"process",
".",
"stdin",
".",
"setRawMode",
"(",
"false",
")",
"process",
".",
"stdin",
".",
"end",
"(",
")",
"}",
"}"
] | Close terminal and exit process
@method end
@param {Object} err Error
@param {Boolean} exit Exit process? | [
"Close",
"terminal",
"and",
"exit",
"process"
] | 8eabaf71a84e07f9870b80526ca5194197df454f | https://github.com/StudioLE/sqwk/blob/8eabaf71a84e07f9870b80526ca5194197df454f/lib/index.js#L110-L127 |
|
52,943 | creationix/culvert | channel.js | put | function put(item) {
if (monitor) monitor("put", item);
if (readQueue.length) {
if (monitor) monitor("take", item);
readQueue.shift()(null, item);
}
else {
dataQueue.push(item);
}
return dataQueue.length <= bufferSize;
} | javascript | function put(item) {
if (monitor) monitor("put", item);
if (readQueue.length) {
if (monitor) monitor("take", item);
readQueue.shift()(null, item);
}
else {
dataQueue.push(item);
}
return dataQueue.length <= bufferSize;
} | [
"function",
"put",
"(",
"item",
")",
"{",
"if",
"(",
"monitor",
")",
"monitor",
"(",
"\"put\"",
",",
"item",
")",
";",
"if",
"(",
"readQueue",
".",
"length",
")",
"{",
"if",
"(",
"monitor",
")",
"monitor",
"(",
"\"take\"",
",",
"item",
")",
";",
"readQueue",
".",
"shift",
"(",
")",
"(",
"null",
",",
"item",
")",
";",
"}",
"else",
"{",
"dataQueue",
".",
"push",
"(",
"item",
")",
";",
"}",
"return",
"dataQueue",
".",
"length",
"<=",
"bufferSize",
";",
"}"
] | Returns true when it's safe to continue without draining | [
"Returns",
"true",
"when",
"it",
"s",
"safe",
"to",
"continue",
"without",
"draining"
] | 42b83894041cd7f8ee3993af0df65c1afe17b2c5 | https://github.com/creationix/culvert/blob/42b83894041cd7f8ee3993af0df65c1afe17b2c5/channel.js#L30-L40 |
52,944 | PanthR/panthrMath | panthrMath/distributions/lognormal.js | dlnorm | function dlnorm(meanlog, sdlog, logp) {
logp = logp === true;
if (utils.hasNaN(meanlog, sdlog) || sdlog < 0) {
return function() { return NaN; };
}
return function(x) {
var z;
if (utils.hasNaN(x)) { return NaN; }
if (sdlog === 0) {
return Math.log(x) === meanlog ? Infinity
: logp ? -Infinity
: 0;
}
if (x <= 0) { return logp ? -Infinity : 0; }
z = (Math.log(x) - meanlog) / sdlog;
return logp ? -(logRoot2pi + 0.5 * z * z + Math.log(x * sdlog))
: recipRoot2pi * Math.exp(-0.5 * z * z) / (x * sdlog);
};
} | javascript | function dlnorm(meanlog, sdlog, logp) {
logp = logp === true;
if (utils.hasNaN(meanlog, sdlog) || sdlog < 0) {
return function() { return NaN; };
}
return function(x) {
var z;
if (utils.hasNaN(x)) { return NaN; }
if (sdlog === 0) {
return Math.log(x) === meanlog ? Infinity
: logp ? -Infinity
: 0;
}
if (x <= 0) { return logp ? -Infinity : 0; }
z = (Math.log(x) - meanlog) / sdlog;
return logp ? -(logRoot2pi + 0.5 * z * z + Math.log(x * sdlog))
: recipRoot2pi * Math.exp(-0.5 * z * z) / (x * sdlog);
};
} | [
"function",
"dlnorm",
"(",
"meanlog",
",",
"sdlog",
",",
"logp",
")",
"{",
"logp",
"=",
"logp",
"===",
"true",
";",
"if",
"(",
"utils",
".",
"hasNaN",
"(",
"meanlog",
",",
"sdlog",
")",
"||",
"sdlog",
"<",
"0",
")",
"{",
"return",
"function",
"(",
")",
"{",
"return",
"NaN",
";",
"}",
";",
"}",
"return",
"function",
"(",
"x",
")",
"{",
"var",
"z",
";",
"if",
"(",
"utils",
".",
"hasNaN",
"(",
"x",
")",
")",
"{",
"return",
"NaN",
";",
"}",
"if",
"(",
"sdlog",
"===",
"0",
")",
"{",
"return",
"Math",
".",
"log",
"(",
"x",
")",
"===",
"meanlog",
"?",
"Infinity",
":",
"logp",
"?",
"-",
"Infinity",
":",
"0",
";",
"}",
"if",
"(",
"x",
"<=",
"0",
")",
"{",
"return",
"logp",
"?",
"-",
"Infinity",
":",
"0",
";",
"}",
"z",
"=",
"(",
"Math",
".",
"log",
"(",
"x",
")",
"-",
"meanlog",
")",
"/",
"sdlog",
";",
"return",
"logp",
"?",
"-",
"(",
"logRoot2pi",
"+",
"0.5",
"*",
"z",
"*",
"z",
"+",
"Math",
".",
"log",
"(",
"x",
"*",
"sdlog",
")",
")",
":",
"recipRoot2pi",
"*",
"Math",
".",
"exp",
"(",
"-",
"0.5",
"*",
"z",
"*",
"z",
")",
"/",
"(",
"x",
"*",
"sdlog",
")",
";",
"}",
";",
"}"
] | Evaluates the lognormal distribution's density function at `x`.
Expects $x > 0$ and $\textrm{sdlog} > 0$.
@fullName dlnorm(meanlog, sdlog, logp)(x)
@memberof lognormal | [
"Evaluates",
"the",
"lognormal",
"distribution",
"s",
"density",
"function",
"at",
"x",
"."
] | 54d249ca9903a9535f963da711bd3a87fb229c0b | https://github.com/PanthR/panthrMath/blob/54d249ca9903a9535f963da711bd3a87fb229c0b/panthrMath/distributions/lognormal.js#L41-L63 |
52,945 | PanthR/panthrMath | panthrMath/distributions/lognormal.js | rlnorm | function rlnorm(meanlog, sdlog) {
var rnorm;
rnorm = normal.rnorm(meanlog, sdlog);
return function() {
return Math.exp(rnorm());
};
} | javascript | function rlnorm(meanlog, sdlog) {
var rnorm;
rnorm = normal.rnorm(meanlog, sdlog);
return function() {
return Math.exp(rnorm());
};
} | [
"function",
"rlnorm",
"(",
"meanlog",
",",
"sdlog",
")",
"{",
"var",
"rnorm",
";",
"rnorm",
"=",
"normal",
".",
"rnorm",
"(",
"meanlog",
",",
"sdlog",
")",
";",
"return",
"function",
"(",
")",
"{",
"return",
"Math",
".",
"exp",
"(",
"rnorm",
"(",
")",
")",
";",
"}",
";",
"}"
] | Returns a random variate from the lognormal distribution.
Expects $\textrm{sdlog} > 0$.
Uses a rejection polar method.
@fullName rlnorm(meanlog, sdlog)()
@memberof lognormal | [
"Returns",
"a",
"random",
"variate",
"from",
"the",
"lognormal",
"distribution",
"."
] | 54d249ca9903a9535f963da711bd3a87fb229c0b | https://github.com/PanthR/panthrMath/blob/54d249ca9903a9535f963da711bd3a87fb229c0b/panthrMath/distributions/lognormal.js#L144-L152 |
52,946 | PanthR/panthrMath | panthrMath/distributions/t.js | ptlog | function ptlog(df, lowerTail) {
return function(x) {
var val;
if (utils.hasNaN(x, df) || df <= 0) { return NaN; }
val = df > x * x ?
bratio(0.5, df / 2, x * x / (df + x * x), false, true)
: bratio(df / 2, 0.5, 1 / (1 + x / df * x), true, true);
if (x <= 0) { lowerTail = !lowerTail; }
return lowerTail ? log1p(-0.5 * Math.exp(val))
: val - Math.log(2);
};
} | javascript | function ptlog(df, lowerTail) {
return function(x) {
var val;
if (utils.hasNaN(x, df) || df <= 0) { return NaN; }
val = df > x * x ?
bratio(0.5, df / 2, x * x / (df + x * x), false, true)
: bratio(df / 2, 0.5, 1 / (1 + x / df * x), true, true);
if (x <= 0) { lowerTail = !lowerTail; }
return lowerTail ? log1p(-0.5 * Math.exp(val))
: val - Math.log(2);
};
} | [
"function",
"ptlog",
"(",
"df",
",",
"lowerTail",
")",
"{",
"return",
"function",
"(",
"x",
")",
"{",
"var",
"val",
";",
"if",
"(",
"utils",
".",
"hasNaN",
"(",
"x",
",",
"df",
")",
"||",
"df",
"<=",
"0",
")",
"{",
"return",
"NaN",
";",
"}",
"val",
"=",
"df",
">",
"x",
"*",
"x",
"?",
"bratio",
"(",
"0.5",
",",
"df",
"/",
"2",
",",
"x",
"*",
"x",
"/",
"(",
"df",
"+",
"x",
"*",
"x",
")",
",",
"false",
",",
"true",
")",
":",
"bratio",
"(",
"df",
"/",
"2",
",",
"0.5",
",",
"1",
"/",
"(",
"1",
"+",
"x",
"/",
"df",
"*",
"x",
")",
",",
"true",
",",
"true",
")",
";",
"if",
"(",
"x",
"<=",
"0",
")",
"{",
"lowerTail",
"=",
"!",
"lowerTail",
";",
"}",
"return",
"lowerTail",
"?",
"log1p",
"(",
"-",
"0.5",
"*",
"Math",
".",
"exp",
"(",
"val",
")",
")",
":",
"val",
"-",
"Math",
".",
"log",
"(",
"2",
")",
";",
"}",
";",
"}"
] | cumulative distribution function, log version based on pt.c from R implementation | [
"cumulative",
"distribution",
"function",
"log",
"version",
"based",
"on",
"pt",
".",
"c",
"from",
"R",
"implementation"
] | 54d249ca9903a9535f963da711bd3a87fb229c0b | https://github.com/PanthR/panthrMath/blob/54d249ca9903a9535f963da711bd3a87fb229c0b/panthrMath/distributions/t.js#L85-L99 |
52,947 | jonschlinkert/verbalize | index.js | Verbalize | function Verbalize(options) {
if (!(this instanceof Verbalize)) {
return new Verbalize(options);
}
Logger.call(this);
this.options = options || {};
this.define('cache', {});
use(this);
this.initDefaults();
this.initPlugins();
} | javascript | function Verbalize(options) {
if (!(this instanceof Verbalize)) {
return new Verbalize(options);
}
Logger.call(this);
this.options = options || {};
this.define('cache', {});
use(this);
this.initDefaults();
this.initPlugins();
} | [
"function",
"Verbalize",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Verbalize",
")",
")",
"{",
"return",
"new",
"Verbalize",
"(",
"options",
")",
";",
"}",
"Logger",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"define",
"(",
"'cache'",
",",
"{",
"}",
")",
";",
"use",
"(",
"this",
")",
";",
"this",
".",
"initDefaults",
"(",
")",
";",
"this",
".",
"initPlugins",
"(",
")",
";",
"}"
] | Create an instance of `Verbalize` with the given `options`.
```js
var logger = new Verbalize({verbose: true});
```
@param {Object} `options`
@api public | [
"Create",
"an",
"instance",
"of",
"Verbalize",
"with",
"the",
"given",
"options",
"."
] | 3d590602fde6a13682d0eebc180c731ea386b64f | https://github.com/jonschlinkert/verbalize/blob/3d590602fde6a13682d0eebc180c731ea386b64f/index.js#L30-L40 |
52,948 | el2iot2/grunt-hogan | Gruntfile.js | log | function log(err, stdout, stderr, cb) {
//And handle errors (if any)
if (err) {
grunt.log.errorlns(err);
}
else if (stderr) {
grunt.log.errorlns(stderr);
}
else {
//Otherwise load a lodash template
var template = grunt.file.read(
__dirname +
'/view/binders.lodash');
//process it with the hulk result
var result = grunt.template.process(template, {data: {stdout: stdout}});
//And write out our bootstrap module
grunt.file.write(
__dirname +
'/tasks/binders.js',
result
);
grunt.log.ok('hulk: generated binders.js');
cb();
}
} | javascript | function log(err, stdout, stderr, cb) {
//And handle errors (if any)
if (err) {
grunt.log.errorlns(err);
}
else if (stderr) {
grunt.log.errorlns(stderr);
}
else {
//Otherwise load a lodash template
var template = grunt.file.read(
__dirname +
'/view/binders.lodash');
//process it with the hulk result
var result = grunt.template.process(template, {data: {stdout: stdout}});
//And write out our bootstrap module
grunt.file.write(
__dirname +
'/tasks/binders.js',
result
);
grunt.log.ok('hulk: generated binders.js');
cb();
}
} | [
"function",
"log",
"(",
"err",
",",
"stdout",
",",
"stderr",
",",
"cb",
")",
"{",
"//And handle errors (if any)",
"if",
"(",
"err",
")",
"{",
"grunt",
".",
"log",
".",
"errorlns",
"(",
"err",
")",
";",
"}",
"else",
"if",
"(",
"stderr",
")",
"{",
"grunt",
".",
"log",
".",
"errorlns",
"(",
"stderr",
")",
";",
"}",
"else",
"{",
"//Otherwise load a lodash template",
"var",
"template",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"__dirname",
"+",
"'/view/binders.lodash'",
")",
";",
"//process it with the hulk result",
"var",
"result",
"=",
"grunt",
".",
"template",
".",
"process",
"(",
"template",
",",
"{",
"data",
":",
"{",
"stdout",
":",
"stdout",
"}",
"}",
")",
";",
"//And write out our bootstrap module",
"grunt",
".",
"file",
".",
"write",
"(",
"__dirname",
"+",
"'/tasks/binders.js'",
",",
"result",
")",
";",
"grunt",
".",
"log",
".",
"ok",
"(",
"'hulk: generated binders.js'",
")",
";",
"cb",
"(",
")",
";",
"}",
"}"
] | But catch the output | [
"But",
"catch",
"the",
"output"
] | 47962b7f63593c61fa0e2b0158f10bc6f8d51ca8 | https://github.com/el2iot2/grunt-hogan/blob/47962b7f63593c61fa0e2b0158f10bc6f8d51ca8/Gruntfile.js#L30-L56 |
52,949 | AndreasMadsen/blow | blow.js | generateIndex | function generateIndex(base, files) {
var document = base.copy();
var head = document.find().only().elem('head').toValue();
// set title
head.find()
.only().elem('title').toValue()
.setContent('Mocha Tests - all');
// bind testcases
Object.keys(files).forEach(function (relative) {
head.append('<script src="/test' + relative + '"></script>');
});
return document.content;
} | javascript | function generateIndex(base, files) {
var document = base.copy();
var head = document.find().only().elem('head').toValue();
// set title
head.find()
.only().elem('title').toValue()
.setContent('Mocha Tests - all');
// bind testcases
Object.keys(files).forEach(function (relative) {
head.append('<script src="/test' + relative + '"></script>');
});
return document.content;
} | [
"function",
"generateIndex",
"(",
"base",
",",
"files",
")",
"{",
"var",
"document",
"=",
"base",
".",
"copy",
"(",
")",
";",
"var",
"head",
"=",
"document",
".",
"find",
"(",
")",
".",
"only",
"(",
")",
".",
"elem",
"(",
"'head'",
")",
".",
"toValue",
"(",
")",
";",
"// set title",
"head",
".",
"find",
"(",
")",
".",
"only",
"(",
")",
".",
"elem",
"(",
"'title'",
")",
".",
"toValue",
"(",
")",
".",
"setContent",
"(",
"'Mocha Tests - all'",
")",
";",
"// bind testcases",
"Object",
".",
"keys",
"(",
"files",
")",
".",
"forEach",
"(",
"function",
"(",
"relative",
")",
"{",
"head",
".",
"append",
"(",
"'<script src=\"/test'",
"+",
"relative",
"+",
"'\"></script>'",
")",
";",
"}",
")",
";",
"return",
"document",
".",
"content",
";",
"}"
] | generate the master testsuite | [
"generate",
"the",
"master",
"testsuite"
] | 51f0e664228ce6bcfdda8a82665d783a7caabf1c | https://github.com/AndreasMadsen/blow/blob/51f0e664228ce6bcfdda8a82665d783a7caabf1c/blow.js#L163-L178 |
52,950 | derdesign/protos | lib/driver.js | function(o, callback) {
var self = this;
// Model::insert > Get ID > Create Model
this.insert(o, function(err, id) {
if (err) {
callback.call(self, err, null);
} else {
self.get(id, function(err, model) {
if (err) {
callback.call(self, err, null);
} else {
callback.call(self, null, model);
}
});
}
});
} | javascript | function(o, callback) {
var self = this;
// Model::insert > Get ID > Create Model
this.insert(o, function(err, id) {
if (err) {
callback.call(self, err, null);
} else {
self.get(id, function(err, model) {
if (err) {
callback.call(self, err, null);
} else {
callback.call(self, null, model);
}
});
}
});
} | [
"function",
"(",
"o",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// Model::insert > Get ID > Create Model",
"this",
".",
"insert",
"(",
"o",
",",
"function",
"(",
"err",
",",
"id",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
".",
"call",
"(",
"self",
",",
"err",
",",
"null",
")",
";",
"}",
"else",
"{",
"self",
".",
"get",
"(",
"id",
",",
"function",
"(",
"err",
",",
"model",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
".",
"call",
"(",
"self",
",",
"err",
",",
"null",
")",
";",
"}",
"else",
"{",
"callback",
".",
"call",
"(",
"self",
",",
"null",
",",
"model",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Creates a new model object. Saves into the
database, then creates the model with the provided data.
Validation should be performed against the values in `o`,
throwing an Error if not satisfied.
Provides: [err, model]
@param {object} o
@param {function} callback | [
"Creates",
"a",
"new",
"model",
"object",
".",
"Saves",
"into",
"the",
"database",
"then",
"creates",
"the",
"model",
"with",
"the",
"provided",
"data",
"."
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/driver.js#L358-L376 |
|
52,951 | tolokoban/ToloFrameWork | ker/mod/tfw.view.cropped-image.js | cropHorizontally | function cropHorizontally( img ) {
var zoom = this.height / img.height;
var x = 0;
if( this.cropping == 'body' ) {
x = 0.5 * (this.width - img.width * zoom);
}
else if( this.cropping == 'tail' ) {
x = this.width - img.width * zoom;
}
draw.call( this, img, x, 0, zoom );
} | javascript | function cropHorizontally( img ) {
var zoom = this.height / img.height;
var x = 0;
if( this.cropping == 'body' ) {
x = 0.5 * (this.width - img.width * zoom);
}
else if( this.cropping == 'tail' ) {
x = this.width - img.width * zoom;
}
draw.call( this, img, x, 0, zoom );
} | [
"function",
"cropHorizontally",
"(",
"img",
")",
"{",
"var",
"zoom",
"=",
"this",
".",
"height",
"/",
"img",
".",
"height",
";",
"var",
"x",
"=",
"0",
";",
"if",
"(",
"this",
".",
"cropping",
"==",
"'body'",
")",
"{",
"x",
"=",
"0.5",
"*",
"(",
"this",
".",
"width",
"-",
"img",
".",
"width",
"*",
"zoom",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"cropping",
"==",
"'tail'",
")",
"{",
"x",
"=",
"this",
".",
"width",
"-",
"img",
".",
"width",
"*",
"zoom",
";",
"}",
"draw",
".",
"call",
"(",
"this",
",",
"img",
",",
"x",
",",
"0",
",",
"zoom",
")",
";",
"}"
] | If img is set to have the same height as the view, it will overflow horizontally. | [
"If",
"img",
"is",
"set",
"to",
"have",
"the",
"same",
"height",
"as",
"the",
"view",
"it",
"will",
"overflow",
"horizontally",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.cropped-image.js#L57-L67 |
52,952 | tolokoban/ToloFrameWork | ker/mod/tfw.view.cropped-image.js | cropVertically | function cropVertically( img ) {
var zoom = this.width / img.width;
var y = 0;
if( this.cropping == 'body' ) {
y = 0.5 * (this.height - img.height * zoom);
}
else if( this.cropping == 'tail' ) {
y = this.height - img.height * zoom;
}
draw.call( this, img, 0, y, zoom );
} | javascript | function cropVertically( img ) {
var zoom = this.width / img.width;
var y = 0;
if( this.cropping == 'body' ) {
y = 0.5 * (this.height - img.height * zoom);
}
else if( this.cropping == 'tail' ) {
y = this.height - img.height * zoom;
}
draw.call( this, img, 0, y, zoom );
} | [
"function",
"cropVertically",
"(",
"img",
")",
"{",
"var",
"zoom",
"=",
"this",
".",
"width",
"/",
"img",
".",
"width",
";",
"var",
"y",
"=",
"0",
";",
"if",
"(",
"this",
".",
"cropping",
"==",
"'body'",
")",
"{",
"y",
"=",
"0.5",
"*",
"(",
"this",
".",
"height",
"-",
"img",
".",
"height",
"*",
"zoom",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"cropping",
"==",
"'tail'",
")",
"{",
"y",
"=",
"this",
".",
"height",
"-",
"img",
".",
"height",
"*",
"zoom",
";",
"}",
"draw",
".",
"call",
"(",
"this",
",",
"img",
",",
"0",
",",
"y",
",",
"zoom",
")",
";",
"}"
] | If img is set to have the same width as the view, it will overflow vertically. | [
"If",
"img",
"is",
"set",
"to",
"have",
"the",
"same",
"width",
"as",
"the",
"view",
"it",
"will",
"overflow",
"vertically",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.cropped-image.js#L73-L83 |
52,953 | linyngfly/omelo-admin | lib/master/masterAgent.js | function(socket, reqId, moduleId, msg) {
doSend(socket, 'monitor', protocol.composeRequest(reqId, moduleId, msg));
} | javascript | function(socket, reqId, moduleId, msg) {
doSend(socket, 'monitor', protocol.composeRequest(reqId, moduleId, msg));
} | [
"function",
"(",
"socket",
",",
"reqId",
",",
"moduleId",
",",
"msg",
")",
"{",
"doSend",
"(",
"socket",
",",
"'monitor'",
",",
"protocol",
".",
"composeRequest",
"(",
"reqId",
",",
"moduleId",
",",
"msg",
")",
")",
";",
"}"
] | send msg to monitor
@param {Object} socket socket-io object
@param {Number} reqId request id
@param {String} moduleId module id/name
@param {Object} msg message
@api private | [
"send",
"msg",
"to",
"monitor"
] | 1cd692c16ab63b9c0d4009535f300f2ca584b691 | https://github.com/linyngfly/omelo-admin/blob/1cd692c16ab63b9c0d4009535f300f2ca584b691/lib/master/masterAgent.js#L479-L481 |
|
52,954 | bloody-ux/menreiki | lib/core/dva-loading.js | createLoading | function createLoading(opts = {}) {
const namespace = opts.namespace || NAMESPACE;
const {
only = [], except = []
} = opts;
if (only.length > 0 && except.length > 0) {
throw Error('It is ambiguous to configurate `only` and `except` items at the same time.');
}
const initialState = {
global: false,
models: {},
effects: {},
};
const extraReducers = {
[namespace](state = initialState, {
type,
payload
}) {
const {
namespace,
actionType
} = payload || {};
let ret;
switch (type) {
case SHOW:
ret = {
...state,
global: true,
models: { ...state.models,
[namespace]: true
},
effects: { ...state.effects,
[actionType]: true
},
};
break;
case HIDE: // eslint-disable-line
const effects = { ...state.effects,
[actionType]: false
};
const models = {
...state.models,
[namespace]: Object.keys(effects).some((actionType) => {
const _namespace = actionType.split('/')[0];
if (_namespace !== namespace) return false;
return effects[actionType];
}),
};
const global = Object
.keys(models)
.some(namespace => models[namespace]);
ret = {
...state,
global,
models,
effects,
};
break;
default:
ret = state;
break;
}
return ret;
},
};
function onEffect(effect, {
put
}, model, actionType) {
const {
namespace
} = model;
if (
(only.length === 0 && except.length === 0) ||
(only.length > 0 && only.indexOf(actionType) !== -1) ||
(except.length > 0 && except.indexOf(actionType) === -1)
) {
return function* (...args) {
yield put({
type: SHOW,
payload: {
namespace,
actionType
}
});
yield effect(...args);
yield put({
type: HIDE,
payload: {
namespace,
actionType
}
});
};
}
return effect;
}
return {
extraReducers,
onEffect,
};
} | javascript | function createLoading(opts = {}) {
const namespace = opts.namespace || NAMESPACE;
const {
only = [], except = []
} = opts;
if (only.length > 0 && except.length > 0) {
throw Error('It is ambiguous to configurate `only` and `except` items at the same time.');
}
const initialState = {
global: false,
models: {},
effects: {},
};
const extraReducers = {
[namespace](state = initialState, {
type,
payload
}) {
const {
namespace,
actionType
} = payload || {};
let ret;
switch (type) {
case SHOW:
ret = {
...state,
global: true,
models: { ...state.models,
[namespace]: true
},
effects: { ...state.effects,
[actionType]: true
},
};
break;
case HIDE: // eslint-disable-line
const effects = { ...state.effects,
[actionType]: false
};
const models = {
...state.models,
[namespace]: Object.keys(effects).some((actionType) => {
const _namespace = actionType.split('/')[0];
if (_namespace !== namespace) return false;
return effects[actionType];
}),
};
const global = Object
.keys(models)
.some(namespace => models[namespace]);
ret = {
...state,
global,
models,
effects,
};
break;
default:
ret = state;
break;
}
return ret;
},
};
function onEffect(effect, {
put
}, model, actionType) {
const {
namespace
} = model;
if (
(only.length === 0 && except.length === 0) ||
(only.length > 0 && only.indexOf(actionType) !== -1) ||
(except.length > 0 && except.indexOf(actionType) === -1)
) {
return function* (...args) {
yield put({
type: SHOW,
payload: {
namespace,
actionType
}
});
yield effect(...args);
yield put({
type: HIDE,
payload: {
namespace,
actionType
}
});
};
}
return effect;
}
return {
extraReducers,
onEffect,
};
} | [
"function",
"createLoading",
"(",
"opts",
"=",
"{",
"}",
")",
"{",
"const",
"namespace",
"=",
"opts",
".",
"namespace",
"||",
"NAMESPACE",
";",
"const",
"{",
"only",
"=",
"[",
"]",
",",
"except",
"=",
"[",
"]",
"}",
"=",
"opts",
";",
"if",
"(",
"only",
".",
"length",
">",
"0",
"&&",
"except",
".",
"length",
">",
"0",
")",
"{",
"throw",
"Error",
"(",
"'It is ambiguous to configurate `only` and `except` items at the same time.'",
")",
";",
"}",
"const",
"initialState",
"=",
"{",
"global",
":",
"false",
",",
"models",
":",
"{",
"}",
",",
"effects",
":",
"{",
"}",
",",
"}",
";",
"const",
"extraReducers",
"=",
"{",
"[",
"namespace",
"]",
"(",
"state",
"=",
"initialState",
",",
"{",
"type",
",",
"payload",
"}",
")",
"{",
"const",
"{",
"namespace",
",",
"actionType",
"}",
"=",
"payload",
"||",
"{",
"}",
";",
"let",
"ret",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"SHOW",
":",
"ret",
"=",
"{",
"...",
"state",
",",
"global",
":",
"true",
",",
"models",
":",
"{",
"...",
"state",
".",
"models",
",",
"[",
"namespace",
"]",
":",
"true",
"}",
",",
"effects",
":",
"{",
"...",
"state",
".",
"effects",
",",
"[",
"actionType",
"]",
":",
"true",
"}",
",",
"}",
";",
"break",
";",
"case",
"HIDE",
":",
"// eslint-disable-line",
"const",
"effects",
"=",
"{",
"...",
"state",
".",
"effects",
",",
"[",
"actionType",
"]",
":",
"false",
"}",
";",
"const",
"models",
"=",
"{",
"...",
"state",
".",
"models",
",",
"[",
"namespace",
"]",
":",
"Object",
".",
"keys",
"(",
"effects",
")",
".",
"some",
"(",
"(",
"actionType",
")",
"=>",
"{",
"const",
"_namespace",
"=",
"actionType",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"_namespace",
"!==",
"namespace",
")",
"return",
"false",
";",
"return",
"effects",
"[",
"actionType",
"]",
";",
"}",
")",
",",
"}",
";",
"const",
"global",
"=",
"Object",
".",
"keys",
"(",
"models",
")",
".",
"some",
"(",
"namespace",
"=>",
"models",
"[",
"namespace",
"]",
")",
";",
"ret",
"=",
"{",
"...",
"state",
",",
"global",
",",
"models",
",",
"effects",
",",
"}",
";",
"break",
";",
"default",
":",
"ret",
"=",
"state",
";",
"break",
";",
"}",
"return",
"ret",
";",
"}",
",",
"}",
";",
"function",
"onEffect",
"(",
"effect",
",",
"{",
"put",
"}",
",",
"model",
",",
"actionType",
")",
"{",
"const",
"{",
"namespace",
"}",
"=",
"model",
";",
"if",
"(",
"(",
"only",
".",
"length",
"===",
"0",
"&&",
"except",
".",
"length",
"===",
"0",
")",
"||",
"(",
"only",
".",
"length",
">",
"0",
"&&",
"only",
".",
"indexOf",
"(",
"actionType",
")",
"!==",
"-",
"1",
")",
"||",
"(",
"except",
".",
"length",
">",
"0",
"&&",
"except",
".",
"indexOf",
"(",
"actionType",
")",
"===",
"-",
"1",
")",
")",
"{",
"return",
"function",
"*",
"(",
"...",
"args",
")",
"{",
"yield",
"put",
"(",
"{",
"type",
":",
"SHOW",
",",
"payload",
":",
"{",
"namespace",
",",
"actionType",
"}",
"}",
")",
";",
"yield",
"effect",
"(",
"...",
"args",
")",
";",
"yield",
"put",
"(",
"{",
"type",
":",
"HIDE",
",",
"payload",
":",
"{",
"namespace",
",",
"actionType",
"}",
"}",
")",
";",
"}",
";",
"}",
"return",
"effect",
";",
"}",
"return",
"{",
"extraReducers",
",",
"onEffect",
",",
"}",
";",
"}"
] | added loading state when distaching an action
@param {{ namespace?: string, only?: Array, except?: Array }} opts plugin options | [
"added",
"loading",
"state",
"when",
"distaching",
"an",
"action"
] | 66079c13a37ce96d261dfd6ab9e926856f107ba8 | https://github.com/bloody-ux/menreiki/blob/66079c13a37ce96d261dfd6ab9e926856f107ba8/lib/core/dva-loading.js#L10-L116 |
52,955 | epeios-q37/xdhelcq | js/mktree/mktree.js | addEvent | function addEvent(o,e,f){
if (o.addEventListener){ o.addEventListener(e,f,false); return true; }
else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
else { return false; }
} | javascript | function addEvent(o,e,f){
if (o.addEventListener){ o.addEventListener(e,f,false); return true; }
else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
else { return false; }
} | [
"function",
"addEvent",
"(",
"o",
",",
"e",
",",
"f",
")",
"{",
"if",
"(",
"o",
".",
"addEventListener",
")",
"{",
"o",
".",
"addEventListener",
"(",
"e",
",",
"f",
",",
"false",
")",
";",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"o",
".",
"attachEvent",
")",
"{",
"return",
"o",
".",
"attachEvent",
"(",
"\"on\"",
"+",
"e",
",",
"f",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Utility function to add an event listener | [
"Utility",
"function",
"to",
"add",
"an",
"event",
"listener"
] | 8cffac0650297c313779c9fba545096be24e52a5 | https://github.com/epeios-q37/xdhelcq/blob/8cffac0650297c313779c9fba545096be24e52a5/js/mktree/mktree.js#L26-L30 |
52,956 | epeios-q37/xdhelcq | js/mktree/mktree.js | setDefault | function setDefault(name,val) {
if (typeof(window[name])=="undefined" || window[name]==null) {
window[name]=val;
}
} | javascript | function setDefault(name,val) {
if (typeof(window[name])=="undefined" || window[name]==null) {
window[name]=val;
}
} | [
"function",
"setDefault",
"(",
"name",
",",
"val",
")",
"{",
"if",
"(",
"typeof",
"(",
"window",
"[",
"name",
"]",
")",
"==",
"\"undefined\"",
"||",
"window",
"[",
"name",
"]",
"==",
"null",
")",
"{",
"window",
"[",
"name",
"]",
"=",
"val",
";",
"}",
"}"
] | utility function to set a global variable if it is not already set | [
"utility",
"function",
"to",
"set",
"a",
"global",
"variable",
"if",
"it",
"is",
"not",
"already",
"set"
] | 8cffac0650297c313779c9fba545096be24e52a5 | https://github.com/epeios-q37/xdhelcq/blob/8cffac0650297c313779c9fba545096be24e52a5/js/mktree/mktree.js#L33-L37 |
52,957 | epeios-q37/xdhelcq | js/mktree/mktree.js | expandTree | function expandTree(treeId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
expandCollapseList(ul,nodeOpenClass);
} | javascript | function expandTree(treeId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
expandCollapseList(ul,nodeOpenClass);
} | [
"function",
"expandTree",
"(",
"treeId",
")",
"{",
"var",
"ul",
"=",
"document",
".",
"getElementById",
"(",
"treeId",
")",
";",
"if",
"(",
"ul",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"expandCollapseList",
"(",
"ul",
",",
"nodeOpenClass",
")",
";",
"}"
] | Full expands a tree with a given ID | [
"Full",
"expands",
"a",
"tree",
"with",
"a",
"given",
"ID"
] | 8cffac0650297c313779c9fba545096be24e52a5 | https://github.com/epeios-q37/xdhelcq/blob/8cffac0650297c313779c9fba545096be24e52a5/js/mktree/mktree.js#L40-L44 |
52,958 | epeios-q37/xdhelcq | js/mktree/mktree.js | collapseTree | function collapseTree(treeId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
expandCollapseList(ul,nodeClosedClass);
} | javascript | function collapseTree(treeId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
expandCollapseList(ul,nodeClosedClass);
} | [
"function",
"collapseTree",
"(",
"treeId",
")",
"{",
"var",
"ul",
"=",
"document",
".",
"getElementById",
"(",
"treeId",
")",
";",
"if",
"(",
"ul",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"expandCollapseList",
"(",
"ul",
",",
"nodeClosedClass",
")",
";",
"}"
] | Fully collapses a tree with a given ID | [
"Fully",
"collapses",
"a",
"tree",
"with",
"a",
"given",
"ID"
] | 8cffac0650297c313779c9fba545096be24e52a5 | https://github.com/epeios-q37/xdhelcq/blob/8cffac0650297c313779c9fba545096be24e52a5/js/mktree/mktree.js#L47-L51 |
52,959 | epeios-q37/xdhelcq | js/mktree/mktree.js | expandToItem | function expandToItem(treeId,itemId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
var ret = expandCollapseList(ul,nodeOpenClass,itemId);
if (ret) {
var o = document.getElementById(itemId);
if (o.scrollIntoView) {
o.scrollIntoView(false);
}
}
} | javascript | function expandToItem(treeId,itemId) {
var ul = document.getElementById(treeId);
if (ul == null) { return false; }
var ret = expandCollapseList(ul,nodeOpenClass,itemId);
if (ret) {
var o = document.getElementById(itemId);
if (o.scrollIntoView) {
o.scrollIntoView(false);
}
}
} | [
"function",
"expandToItem",
"(",
"treeId",
",",
"itemId",
")",
"{",
"var",
"ul",
"=",
"document",
".",
"getElementById",
"(",
"treeId",
")",
";",
"if",
"(",
"ul",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"var",
"ret",
"=",
"expandCollapseList",
"(",
"ul",
",",
"nodeOpenClass",
",",
"itemId",
")",
";",
"if",
"(",
"ret",
")",
"{",
"var",
"o",
"=",
"document",
".",
"getElementById",
"(",
"itemId",
")",
";",
"if",
"(",
"o",
".",
"scrollIntoView",
")",
"{",
"o",
".",
"scrollIntoView",
"(",
"false",
")",
";",
"}",
"}",
"}"
] | Expands enough nodes to expose an LI with a given ID | [
"Expands",
"enough",
"nodes",
"to",
"expose",
"an",
"LI",
"with",
"a",
"given",
"ID"
] | 8cffac0650297c313779c9fba545096be24e52a5 | https://github.com/epeios-q37/xdhelcq/blob/8cffac0650297c313779c9fba545096be24e52a5/js/mktree/mktree.js#L54-L64 |
52,960 | epeios-q37/xdhelcq | js/mktree/mktree.js | convertTrees | function convertTrees() {
setDefault("treeClass","mktree");
setDefault("nodeClosedClass","liClosed");
setDefault("nodeOpenClass","liOpen");
setDefault("nodeBulletClass","liBullet");
setDefault("nodeLinkClass","bullet");
setDefault("preProcessTrees",true);
if (preProcessTrees) {
if (!document.createElement) { return; } // Without createElement, we can't do anything
var uls = document.getElementsByTagName("ul");
if (uls==null) { return; }
var uls_length = uls.length;
for (var uli=0;uli<uls_length;uli++) {
var ul=uls[uli];
if (ul.nodeName=="UL" && ul.className==treeClass) {
processList(ul);
ul.setAttribute( "data-xdh-mktree", "handled" );
}
}
}
} | javascript | function convertTrees() {
setDefault("treeClass","mktree");
setDefault("nodeClosedClass","liClosed");
setDefault("nodeOpenClass","liOpen");
setDefault("nodeBulletClass","liBullet");
setDefault("nodeLinkClass","bullet");
setDefault("preProcessTrees",true);
if (preProcessTrees) {
if (!document.createElement) { return; } // Without createElement, we can't do anything
var uls = document.getElementsByTagName("ul");
if (uls==null) { return; }
var uls_length = uls.length;
for (var uli=0;uli<uls_length;uli++) {
var ul=uls[uli];
if (ul.nodeName=="UL" && ul.className==treeClass) {
processList(ul);
ul.setAttribute( "data-xdh-mktree", "handled" );
}
}
}
} | [
"function",
"convertTrees",
"(",
")",
"{",
"setDefault",
"(",
"\"treeClass\"",
",",
"\"mktree\"",
")",
";",
"setDefault",
"(",
"\"nodeClosedClass\"",
",",
"\"liClosed\"",
")",
";",
"setDefault",
"(",
"\"nodeOpenClass\"",
",",
"\"liOpen\"",
")",
";",
"setDefault",
"(",
"\"nodeBulletClass\"",
",",
"\"liBullet\"",
")",
";",
"setDefault",
"(",
"\"nodeLinkClass\"",
",",
"\"bullet\"",
")",
";",
"setDefault",
"(",
"\"preProcessTrees\"",
",",
"true",
")",
";",
"if",
"(",
"preProcessTrees",
")",
"{",
"if",
"(",
"!",
"document",
".",
"createElement",
")",
"{",
"return",
";",
"}",
"// Without createElement, we can't do anything",
"var",
"uls",
"=",
"document",
".",
"getElementsByTagName",
"(",
"\"ul\"",
")",
";",
"if",
"(",
"uls",
"==",
"null",
")",
"{",
"return",
";",
"}",
"var",
"uls_length",
"=",
"uls",
".",
"length",
";",
"for",
"(",
"var",
"uli",
"=",
"0",
";",
"uli",
"<",
"uls_length",
";",
"uli",
"++",
")",
"{",
"var",
"ul",
"=",
"uls",
"[",
"uli",
"]",
";",
"if",
"(",
"ul",
".",
"nodeName",
"==",
"\"UL\"",
"&&",
"ul",
".",
"className",
"==",
"treeClass",
")",
"{",
"processList",
"(",
"ul",
")",
";",
"ul",
".",
"setAttribute",
"(",
"\"data-xdh-mktree\"",
",",
"\"handled\"",
")",
";",
"}",
"}",
"}",
"}"
] | Search the document for UL elements with the correct CLASS name, then process them | [
"Search",
"the",
"document",
"for",
"UL",
"elements",
"with",
"the",
"correct",
"CLASS",
"name",
"then",
"process",
"them"
] | 8cffac0650297c313779c9fba545096be24e52a5 | https://github.com/epeios-q37/xdhelcq/blob/8cffac0650297c313779c9fba545096be24e52a5/js/mktree/mktree.js#L98-L118 |
52,961 | epeios-q37/xdhelcq | js/mktree/mktree.js | processList | function processList(ul) {
if ( ul.getAttribute( "data-xdh-mktree" ) == "handled" )
return;
if (!ul.childNodes || ul.childNodes.length==0) { return; }
// Iterate LIs
var childNodesLength = ul.childNodes.length;
for (var itemi=0;itemi<childNodesLength;itemi++) {
var item = ul.childNodes[itemi];
if (item.nodeName == "LI") {
// Iterate things in this LI
var subLists = false;
var itemChildNodesLength = item.childNodes.length;
for (var sitemi=0;sitemi<itemChildNodesLength;sitemi++) {
var sitem = item.childNodes[sitemi];
if (sitem.nodeName=="UL") {
subLists = true;
processList(sitem);
}
}
var s= document.createElement("SPAN");
var t= '\u00A0'; //
s.className = nodeLinkClass;
if (subLists) {
// This LI has UL's in it, so it's a +/- node
if (item.className==null || item.className=="") {
item.className = nodeClosedClass;
}
// If it's just text, make the text work as the link also
if (item.firstChild.nodeName=="#text") {
t = t+item.firstChild.nodeValue;
item.removeChild(item.firstChild);
}
s.onclick = treeNodeOnclick;
}
else {
// No sublists, so it's just a bullet node
item.className = nodeBulletClass;
s.onclick = retFalse;
}
s.appendChild(document.createTextNode(t));
item.insertBefore(s,item.firstChild);
}
}
} | javascript | function processList(ul) {
if ( ul.getAttribute( "data-xdh-mktree" ) == "handled" )
return;
if (!ul.childNodes || ul.childNodes.length==0) { return; }
// Iterate LIs
var childNodesLength = ul.childNodes.length;
for (var itemi=0;itemi<childNodesLength;itemi++) {
var item = ul.childNodes[itemi];
if (item.nodeName == "LI") {
// Iterate things in this LI
var subLists = false;
var itemChildNodesLength = item.childNodes.length;
for (var sitemi=0;sitemi<itemChildNodesLength;sitemi++) {
var sitem = item.childNodes[sitemi];
if (sitem.nodeName=="UL") {
subLists = true;
processList(sitem);
}
}
var s= document.createElement("SPAN");
var t= '\u00A0'; //
s.className = nodeLinkClass;
if (subLists) {
// This LI has UL's in it, so it's a +/- node
if (item.className==null || item.className=="") {
item.className = nodeClosedClass;
}
// If it's just text, make the text work as the link also
if (item.firstChild.nodeName=="#text") {
t = t+item.firstChild.nodeValue;
item.removeChild(item.firstChild);
}
s.onclick = treeNodeOnclick;
}
else {
// No sublists, so it's just a bullet node
item.className = nodeBulletClass;
s.onclick = retFalse;
}
s.appendChild(document.createTextNode(t));
item.insertBefore(s,item.firstChild);
}
}
} | [
"function",
"processList",
"(",
"ul",
")",
"{",
"if",
"(",
"ul",
".",
"getAttribute",
"(",
"\"data-xdh-mktree\"",
")",
"==",
"\"handled\"",
")",
"return",
";",
"if",
"(",
"!",
"ul",
".",
"childNodes",
"||",
"ul",
".",
"childNodes",
".",
"length",
"==",
"0",
")",
"{",
"return",
";",
"}",
"// Iterate LIs",
"var",
"childNodesLength",
"=",
"ul",
".",
"childNodes",
".",
"length",
";",
"for",
"(",
"var",
"itemi",
"=",
"0",
";",
"itemi",
"<",
"childNodesLength",
";",
"itemi",
"++",
")",
"{",
"var",
"item",
"=",
"ul",
".",
"childNodes",
"[",
"itemi",
"]",
";",
"if",
"(",
"item",
".",
"nodeName",
"==",
"\"LI\"",
")",
"{",
"// Iterate things in this LI",
"var",
"subLists",
"=",
"false",
";",
"var",
"itemChildNodesLength",
"=",
"item",
".",
"childNodes",
".",
"length",
";",
"for",
"(",
"var",
"sitemi",
"=",
"0",
";",
"sitemi",
"<",
"itemChildNodesLength",
";",
"sitemi",
"++",
")",
"{",
"var",
"sitem",
"=",
"item",
".",
"childNodes",
"[",
"sitemi",
"]",
";",
"if",
"(",
"sitem",
".",
"nodeName",
"==",
"\"UL\"",
")",
"{",
"subLists",
"=",
"true",
";",
"processList",
"(",
"sitem",
")",
";",
"}",
"}",
"var",
"s",
"=",
"document",
".",
"createElement",
"(",
"\"SPAN\"",
")",
";",
"var",
"t",
"=",
"'\\u00A0'",
";",
"// ",
"s",
".",
"className",
"=",
"nodeLinkClass",
";",
"if",
"(",
"subLists",
")",
"{",
"// This LI has UL's in it, so it's a +/- node",
"if",
"(",
"item",
".",
"className",
"==",
"null",
"||",
"item",
".",
"className",
"==",
"\"\"",
")",
"{",
"item",
".",
"className",
"=",
"nodeClosedClass",
";",
"}",
"// If it's just text, make the text work as the link also",
"if",
"(",
"item",
".",
"firstChild",
".",
"nodeName",
"==",
"\"#text\"",
")",
"{",
"t",
"=",
"t",
"+",
"item",
".",
"firstChild",
".",
"nodeValue",
";",
"item",
".",
"removeChild",
"(",
"item",
".",
"firstChild",
")",
";",
"}",
"s",
".",
"onclick",
"=",
"treeNodeOnclick",
";",
"}",
"else",
"{",
"// No sublists, so it's just a bullet node",
"item",
".",
"className",
"=",
"nodeBulletClass",
";",
"s",
".",
"onclick",
"=",
"retFalse",
";",
"}",
"s",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"t",
")",
")",
";",
"item",
".",
"insertBefore",
"(",
"s",
",",
"item",
".",
"firstChild",
")",
";",
"}",
"}",
"}"
] | Process a UL tag and all its children, to convert to a tree | [
"Process",
"a",
"UL",
"tag",
"and",
"all",
"its",
"children",
"to",
"convert",
"to",
"a",
"tree"
] | 8cffac0650297c313779c9fba545096be24e52a5 | https://github.com/epeios-q37/xdhelcq/blob/8cffac0650297c313779c9fba545096be24e52a5/js/mktree/mktree.js#L128-L172 |
52,962 | Digznav/bilberry | git-date-of.js | gitDateOf | function gitDateOf(val) {
let date = null;
try {
date = exec(`git log -1 --format=%cI ${val}`).toString();
} catch (err) {
return new Error(err);
}
return date.substring(0, date.indexOf('T'));
} | javascript | function gitDateOf(val) {
let date = null;
try {
date = exec(`git log -1 --format=%cI ${val}`).toString();
} catch (err) {
return new Error(err);
}
return date.substring(0, date.indexOf('T'));
} | [
"function",
"gitDateOf",
"(",
"val",
")",
"{",
"let",
"date",
"=",
"null",
";",
"try",
"{",
"date",
"=",
"exec",
"(",
"`",
"${",
"val",
"}",
"`",
")",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"new",
"Error",
"(",
"err",
")",
";",
"}",
"return",
"date",
".",
"substring",
"(",
"0",
",",
"date",
".",
"indexOf",
"(",
"'T'",
")",
")",
";",
"}"
] | Date of a git value
@param {string} val Value.
@return {string} Date. | [
"Date",
"of",
"a",
"git",
"value"
] | ef6db49de6c8b0d2f4f9d3e10e8a8153e39ffcc4 | https://github.com/Digznav/bilberry/blob/ef6db49de6c8b0d2f4f9d3e10e8a8153e39ffcc4/git-date-of.js#L8-L18 |
52,963 | lujintan/sherrie-cmd-scaffold | main.js | function(text){
var deferred = Q.defer();
r.question(text, function(answer) {
deferred.resolve(answer);
});
return deferred.promise;
} | javascript | function(text){
var deferred = Q.defer();
r.question(text, function(answer) {
deferred.resolve(answer);
});
return deferred.promise;
} | [
"function",
"(",
"text",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"r",
".",
"question",
"(",
"text",
",",
"function",
"(",
"answer",
")",
"{",
"deferred",
".",
"resolve",
"(",
"answer",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] | transfer the question funtion to a promised function | [
"transfer",
"the",
"question",
"funtion",
"to",
"a",
"promised",
"function"
] | af077b4bc3d73155765ad8f8601414d4d0858fea | https://github.com/lujintan/sherrie-cmd-scaffold/blob/af077b4bc3d73155765ad8f8601414d4d0858fea/main.js#L17-L23 |
|
52,964 | origin1tech/chek | dist/modules/type.js | castType | function castType(val, type, def) {
function cast() {
if (!is_1.isValue(val))
return to_1.toDefault(null, def);
// If no type specified try to get automatically.
type = type || getType(val);
if (is_1.isArray(type)) {
return to_1.toArray(val)
.map(function (v, i) { return castType(v, type[i] || type[i - 1] || type[0]); });
}
else if (is_1.isFunction(type)) {
val = to_1.toArray(val);
return type.apply(void 0, val);
}
else if (is_1.isString(type)) {
type = type.toLowerCase();
var func = toMap[type];
if (func)
return func(val);
return to_1.toDefault(null, def);
}
else {
return val;
}
}
return function_1.tryWrap(cast)(def);
} | javascript | function castType(val, type, def) {
function cast() {
if (!is_1.isValue(val))
return to_1.toDefault(null, def);
// If no type specified try to get automatically.
type = type || getType(val);
if (is_1.isArray(type)) {
return to_1.toArray(val)
.map(function (v, i) { return castType(v, type[i] || type[i - 1] || type[0]); });
}
else if (is_1.isFunction(type)) {
val = to_1.toArray(val);
return type.apply(void 0, val);
}
else if (is_1.isString(type)) {
type = type.toLowerCase();
var func = toMap[type];
if (func)
return func(val);
return to_1.toDefault(null, def);
}
else {
return val;
}
}
return function_1.tryWrap(cast)(def);
} | [
"function",
"castType",
"(",
"val",
",",
"type",
",",
"def",
")",
"{",
"function",
"cast",
"(",
")",
"{",
"if",
"(",
"!",
"is_1",
".",
"isValue",
"(",
"val",
")",
")",
"return",
"to_1",
".",
"toDefault",
"(",
"null",
",",
"def",
")",
";",
"// If no type specified try to get automatically.",
"type",
"=",
"type",
"||",
"getType",
"(",
"val",
")",
";",
"if",
"(",
"is_1",
".",
"isArray",
"(",
"type",
")",
")",
"{",
"return",
"to_1",
".",
"toArray",
"(",
"val",
")",
".",
"map",
"(",
"function",
"(",
"v",
",",
"i",
")",
"{",
"return",
"castType",
"(",
"v",
",",
"type",
"[",
"i",
"]",
"||",
"type",
"[",
"i",
"-",
"1",
"]",
"||",
"type",
"[",
"0",
"]",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isFunction",
"(",
"type",
")",
")",
"{",
"val",
"=",
"to_1",
".",
"toArray",
"(",
"val",
")",
";",
"return",
"type",
".",
"apply",
"(",
"void",
"0",
",",
"val",
")",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isString",
"(",
"type",
")",
")",
"{",
"type",
"=",
"type",
".",
"toLowerCase",
"(",
")",
";",
"var",
"func",
"=",
"toMap",
"[",
"type",
"]",
";",
"if",
"(",
"func",
")",
"return",
"func",
"(",
"val",
")",
";",
"return",
"to_1",
".",
"toDefault",
"(",
"null",
",",
"def",
")",
";",
"}",
"else",
"{",
"return",
"val",
";",
"}",
"}",
"return",
"function_1",
".",
"tryWrap",
"(",
"cast",
")",
"(",
"def",
")",
";",
"}"
] | Cast Type
Attempts to cast to specified type.
@param val the value to be cast.
@param type the type to cast to.
@param def optional default value to return on null. | [
"Cast",
"Type",
"Attempts",
"to",
"cast",
"to",
"specified",
"type",
"."
] | 6bc3ab0ac36126cc7918a244a606009749897b2e | https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/type.js#L25-L51 |
52,965 | origin1tech/chek | dist/modules/type.js | getType | function getType(val, strict, def) {
if (is_1.isString(strict)) {
def = strict;
strict = undefined;
}
var type = typeof val;
var parse = !is_1.isValue(strict) ? true : false;
function isKnown() {
return (type === 'undefined' ||
(type !== 'object' &&
type !== 'number' &&
type !== 'string'));
}
// If not 'object', 'number' or 'string' just
// return the type, numbers, objects and strings
// should fall through for more specific type.
if (isKnown())
return type;
if (is_1.isNull(val)) {
return 'null';
}
else if (is_1.isDate(val)) {
return 'date';
}
else if (is_1.isNumber(val)) {
if (strict)
return 'number';
if (is_1.isFloat(val))
return 'float';
if (is_1.isInteger(val))
return 'integer';
/* istanbul ignore next */
return 'number';
}
else if (is_1.isPlainObject(val)) {
if (strict)
return type;
return 'literal';
}
else if (is_1.isError(val)) {
return 'error';
}
else if (is_1.isRegExp(val)) {
return 'regexp';
}
else if (is_1.isArray(val)) {
return 'array';
}
else if (is_1.isString(val)) {
return 'string';
}
else if (val.constructor && val.constructor.name) {
if (strict)
return type;
return val.constructor.name;
}
/* istanbul ignore next */
return def || 'any';
} | javascript | function getType(val, strict, def) {
if (is_1.isString(strict)) {
def = strict;
strict = undefined;
}
var type = typeof val;
var parse = !is_1.isValue(strict) ? true : false;
function isKnown() {
return (type === 'undefined' ||
(type !== 'object' &&
type !== 'number' &&
type !== 'string'));
}
// If not 'object', 'number' or 'string' just
// return the type, numbers, objects and strings
// should fall through for more specific type.
if (isKnown())
return type;
if (is_1.isNull(val)) {
return 'null';
}
else if (is_1.isDate(val)) {
return 'date';
}
else if (is_1.isNumber(val)) {
if (strict)
return 'number';
if (is_1.isFloat(val))
return 'float';
if (is_1.isInteger(val))
return 'integer';
/* istanbul ignore next */
return 'number';
}
else if (is_1.isPlainObject(val)) {
if (strict)
return type;
return 'literal';
}
else if (is_1.isError(val)) {
return 'error';
}
else if (is_1.isRegExp(val)) {
return 'regexp';
}
else if (is_1.isArray(val)) {
return 'array';
}
else if (is_1.isString(val)) {
return 'string';
}
else if (val.constructor && val.constructor.name) {
if (strict)
return type;
return val.constructor.name;
}
/* istanbul ignore next */
return def || 'any';
} | [
"function",
"getType",
"(",
"val",
",",
"strict",
",",
"def",
")",
"{",
"if",
"(",
"is_1",
".",
"isString",
"(",
"strict",
")",
")",
"{",
"def",
"=",
"strict",
";",
"strict",
"=",
"undefined",
";",
"}",
"var",
"type",
"=",
"typeof",
"val",
";",
"var",
"parse",
"=",
"!",
"is_1",
".",
"isValue",
"(",
"strict",
")",
"?",
"true",
":",
"false",
";",
"function",
"isKnown",
"(",
")",
"{",
"return",
"(",
"type",
"===",
"'undefined'",
"||",
"(",
"type",
"!==",
"'object'",
"&&",
"type",
"!==",
"'number'",
"&&",
"type",
"!==",
"'string'",
")",
")",
";",
"}",
"// If not 'object', 'number' or 'string' just",
"// return the type, numbers, objects and strings",
"// should fall through for more specific type.",
"if",
"(",
"isKnown",
"(",
")",
")",
"return",
"type",
";",
"if",
"(",
"is_1",
".",
"isNull",
"(",
"val",
")",
")",
"{",
"return",
"'null'",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isDate",
"(",
"val",
")",
")",
"{",
"return",
"'date'",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isNumber",
"(",
"val",
")",
")",
"{",
"if",
"(",
"strict",
")",
"return",
"'number'",
";",
"if",
"(",
"is_1",
".",
"isFloat",
"(",
"val",
")",
")",
"return",
"'float'",
";",
"if",
"(",
"is_1",
".",
"isInteger",
"(",
"val",
")",
")",
"return",
"'integer'",
";",
"/* istanbul ignore next */",
"return",
"'number'",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isPlainObject",
"(",
"val",
")",
")",
"{",
"if",
"(",
"strict",
")",
"return",
"type",
";",
"return",
"'literal'",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isError",
"(",
"val",
")",
")",
"{",
"return",
"'error'",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isRegExp",
"(",
"val",
")",
")",
"{",
"return",
"'regexp'",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"return",
"'array'",
";",
"}",
"else",
"if",
"(",
"is_1",
".",
"isString",
"(",
"val",
")",
")",
"{",
"return",
"'string'",
";",
"}",
"else",
"if",
"(",
"val",
".",
"constructor",
"&&",
"val",
".",
"constructor",
".",
"name",
")",
"{",
"if",
"(",
"strict",
")",
"return",
"type",
";",
"return",
"val",
".",
"constructor",
".",
"name",
";",
"}",
"/* istanbul ignore next */",
"return",
"def",
"||",
"'any'",
";",
"}"
] | Get Type
Gets the type of the provided value.
Value Type Strict
-------------------------------------------------
{} literal object
true boolean boolean
'true' boolean string
25 integer number
25.5 float number
new Date() date date
'01/01/2017' date string
RegExp regexp regexp
'/^test/g' regexp string
null null null
function() {} function function
[] array array
'some string' string string
@param val the object to get type from.
@param strict when true returns the strict type see examples.
@param def the optional string name for unknown types. | [
"Get",
"Type",
"Gets",
"the",
"type",
"of",
"the",
"provided",
"value",
"."
] | 6bc3ab0ac36126cc7918a244a606009749897b2e | https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/type.js#L77-L135 |
52,966 | vkiding/jud-vue-loader | lib/loader.js | ensureLoader | function ensureLoader (lang) {
return lang.split('!').map(function (loader) {
return loader.replace(/^([\w-]+)(\?.*)?/, function (_, name, query) {
return (/-loader$/.test(name) ? name : (name + '-loader')) + (query || '')
})
}).join('!')
} | javascript | function ensureLoader (lang) {
return lang.split('!').map(function (loader) {
return loader.replace(/^([\w-]+)(\?.*)?/, function (_, name, query) {
return (/-loader$/.test(name) ? name : (name + '-loader')) + (query || '')
})
}).join('!')
} | [
"function",
"ensureLoader",
"(",
"lang",
")",
"{",
"return",
"lang",
".",
"split",
"(",
"'!'",
")",
".",
"map",
"(",
"function",
"(",
"loader",
")",
"{",
"return",
"loader",
".",
"replace",
"(",
"/",
"^([\\w-]+)(\\?.*)?",
"/",
",",
"function",
"(",
"_",
",",
"name",
",",
"query",
")",
"{",
"return",
"(",
"/",
"-loader$",
"/",
".",
"test",
"(",
"name",
")",
"?",
"name",
":",
"(",
"name",
"+",
"'-loader'",
")",
")",
"+",
"(",
"query",
"||",
"''",
")",
"}",
")",
"}",
")",
".",
"join",
"(",
"'!'",
")",
"}"
] | sass => sass-loader sass-loader => sass-loader sass?indentedsyntax!css => sass-loader?indentedSyntax!css-loader | [
"sass",
"=",
">",
"sass",
"-",
"loader",
"sass",
"-",
"loader",
"=",
">",
"sass",
"-",
"loader",
"sass?indentedsyntax!css",
"=",
">",
"sass",
"-",
"loader?indentedSyntax!css",
"-",
"loader"
] | e629aa1dc49d24a0ebe2f26b324966b9db17b256 | https://github.com/vkiding/jud-vue-loader/blob/e629aa1dc49d24a0ebe2f26b324966b9db17b256/lib/loader.js#L189-L195 |
52,967 | jmjuanes/logty | index.js | function (opt) {
if (typeof opt !== "object" || opt === null) {
opt = {};
}
if (typeof opt.tag !== "string") {
opt.tag = null;
}
if (typeof opt.encoding !== "string") {
opt.encoding = "utf8";
}
//Extends the readable stream
stream.Readable.call(this, {encoding: opt.encoding});
this._tag = (typeof opt.tag === "string") ? opt.tag.trim() : null;
this._level = labels.length;
this._disabled = false;
//Default message format
this._format = function (tag, label, text) {
let list = [];
if (tag) {
//Add the tag if it is provided
list.push("[" + tag + "]");
}
list.push("[" + timestamp("YYYY-MM-DD hh:mm:ss") + "]");
list.push("[" + label.toUpperCase() + "]");
list.push(text.trim());
return list.join(" ");
};
return this;
} | javascript | function (opt) {
if (typeof opt !== "object" || opt === null) {
opt = {};
}
if (typeof opt.tag !== "string") {
opt.tag = null;
}
if (typeof opt.encoding !== "string") {
opt.encoding = "utf8";
}
//Extends the readable stream
stream.Readable.call(this, {encoding: opt.encoding});
this._tag = (typeof opt.tag === "string") ? opt.tag.trim() : null;
this._level = labels.length;
this._disabled = false;
//Default message format
this._format = function (tag, label, text) {
let list = [];
if (tag) {
//Add the tag if it is provided
list.push("[" + tag + "]");
}
list.push("[" + timestamp("YYYY-MM-DD hh:mm:ss") + "]");
list.push("[" + label.toUpperCase() + "]");
list.push(text.trim());
return list.join(" ");
};
return this;
} | [
"function",
"(",
"opt",
")",
"{",
"if",
"(",
"typeof",
"opt",
"!==",
"\"object\"",
"||",
"opt",
"===",
"null",
")",
"{",
"opt",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"opt",
".",
"tag",
"!==",
"\"string\"",
")",
"{",
"opt",
".",
"tag",
"=",
"null",
";",
"}",
"if",
"(",
"typeof",
"opt",
".",
"encoding",
"!==",
"\"string\"",
")",
"{",
"opt",
".",
"encoding",
"=",
"\"utf8\"",
";",
"}",
"//Extends the readable stream",
"stream",
".",
"Readable",
".",
"call",
"(",
"this",
",",
"{",
"encoding",
":",
"opt",
".",
"encoding",
"}",
")",
";",
"this",
".",
"_tag",
"=",
"(",
"typeof",
"opt",
".",
"tag",
"===",
"\"string\"",
")",
"?",
"opt",
".",
"tag",
".",
"trim",
"(",
")",
":",
"null",
";",
"this",
".",
"_level",
"=",
"labels",
".",
"length",
";",
"this",
".",
"_disabled",
"=",
"false",
";",
"//Default message format",
"this",
".",
"_format",
"=",
"function",
"(",
"tag",
",",
"label",
",",
"text",
")",
"{",
"let",
"list",
"=",
"[",
"]",
";",
"if",
"(",
"tag",
")",
"{",
"//Add the tag if it is provided",
"list",
".",
"push",
"(",
"\"[\"",
"+",
"tag",
"+",
"\"]\"",
")",
";",
"}",
"list",
".",
"push",
"(",
"\"[\"",
"+",
"timestamp",
"(",
"\"YYYY-MM-DD hh:mm:ss\"",
")",
"+",
"\"]\"",
")",
";",
"list",
".",
"push",
"(",
"\"[\"",
"+",
"label",
".",
"toUpperCase",
"(",
")",
"+",
"\"]\"",
")",
";",
"list",
".",
"push",
"(",
"text",
".",
"trim",
"(",
")",
")",
";",
"return",
"list",
".",
"join",
"(",
"\" \"",
")",
";",
"}",
";",
"return",
"this",
";",
"}"
] | Logty readable stream | [
"Logty",
"readable",
"stream"
] | 47c4f9ea65f9443f54bd2ccb6a7277fb7c12201b | https://github.com/jmjuanes/logty/blob/47c4f9ea65f9443f54bd2ccb6a7277fb7c12201b/index.js#L10-L42 |
|
52,968 | hydrojs/chai | dist/hydro-chai.js | is | function is(type, input) {
if (type === 'Object') return Object(input) === input;
return toString.call(input) === '[object ' + type + ']';
} | javascript | function is(type, input) {
if (type === 'Object') return Object(input) === input;
return toString.call(input) === '[object ' + type + ']';
} | [
"function",
"is",
"(",
"type",
",",
"input",
")",
"{",
"if",
"(",
"type",
"===",
"'Object'",
")",
"return",
"Object",
"(",
"input",
")",
"===",
"input",
";",
"return",
"toString",
".",
"call",
"(",
"input",
")",
"===",
"'[object '",
"+",
"type",
"+",
"']'",
";",
"}"
] | Check if `input` is String, Function or Object.
@param {String} type
@param {Mixed} input
@returns {Boolean}
@api private | [
"Check",
"if",
"input",
"is",
"String",
"Function",
"or",
"Object",
"."
] | d8aa18e3a19f0f49d9cd57bac9ab633b1eb439de | https://github.com/hydrojs/chai/blob/d8aa18e3a19f0f49d9cd57bac9ab633b1eb439de/dist/hydro-chai.js#L225-L228 |
52,969 | hydrojs/chai | dist/hydro-chai.js | str | function str(input) {
if (!is('String', input)) return;
return root[input] || (root.require || require)(input);
} | javascript | function str(input) {
if (!is('String', input)) return;
return root[input] || (root.require || require)(input);
} | [
"function",
"str",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"is",
"(",
"'String'",
",",
"input",
")",
")",
"return",
";",
"return",
"root",
"[",
"input",
"]",
"||",
"(",
"root",
".",
"require",
"||",
"require",
")",
"(",
"input",
")",
";",
"}"
] | Check if `input` is a string and if so, either
refer to the global scope or `require` it. Then
call `loa` again in case the exported object
is a function.
@param {Mixed} input
@api private | [
"Check",
"if",
"input",
"is",
"a",
"string",
"and",
"if",
"so",
"either",
"refer",
"to",
"the",
"global",
"scope",
"or",
"require",
"it",
".",
"Then",
"call",
"loa",
"again",
"in",
"case",
"the",
"exported",
"object",
"is",
"a",
"function",
"."
] | d8aa18e3a19f0f49d9cd57bac9ab633b1eb439de | https://github.com/hydrojs/chai/blob/d8aa18e3a19f0f49d9cd57bac9ab633b1eb439de/dist/hydro-chai.js#L240-L243 |
52,970 | emiljohansson/captn | captn.dom.removeclass/index.js | removeClass | function removeClass(element, className) {
if (!hasClassNameProperty(element)) {
return;
}
element.className = element.className
.replace(className, '')
.replace(/^\s+|\s+$/g, '')
.replace(/\s\s/g, ' ');
} | javascript | function removeClass(element, className) {
if (!hasClassNameProperty(element)) {
return;
}
element.className = element.className
.replace(className, '')
.replace(/^\s+|\s+$/g, '')
.replace(/\s\s/g, ' ');
} | [
"function",
"removeClass",
"(",
"element",
",",
"className",
")",
"{",
"if",
"(",
"!",
"hasClassNameProperty",
"(",
"element",
")",
")",
"{",
"return",
";",
"}",
"element",
".",
"className",
"=",
"element",
".",
"className",
".",
"replace",
"(",
"className",
",",
"''",
")",
".",
"replace",
"(",
"/",
"^\\s+|\\s+$",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\s\\s",
"/",
"g",
",",
"' '",
")",
";",
"}"
] | Removes a class name from the element's list of class names.
@static
@param {DOMElement} element The DOM element to modify.
@param {string} className The name to remove.
@example
addClass(el, 'container');
hasClass(el, 'container');
// => true
removeClass(el, 'container');
hasClass(el, 'container');
// => false | [
"Removes",
"a",
"class",
"name",
"from",
"the",
"element",
"s",
"list",
"of",
"class",
"names",
"."
] | dae7520116dc2148b4de06af7e1d7a47a3a3ac37 | https://github.com/emiljohansson/captn/blob/dae7520116dc2148b4de06af7e1d7a47a3a3ac37/captn.dom.removeclass/index.js#L23-L31 |
52,971 | jonschlinkert/normalize-config | index.js | normalizeOptions | function normalizeOptions(obj) {
for (var key in obj) {
if (utils.optsKeys.indexOf(key) > -1) {
obj.options = obj.options || {};
obj.options[key] = obj[key];
delete obj[key];
}
}
return obj;
} | javascript | function normalizeOptions(obj) {
for (var key in obj) {
if (utils.optsKeys.indexOf(key) > -1) {
obj.options = obj.options || {};
obj.options[key] = obj[key];
delete obj[key];
}
}
return obj;
} | [
"function",
"normalizeOptions",
"(",
"obj",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"utils",
".",
"optsKeys",
".",
"indexOf",
"(",
"key",
")",
">",
"-",
"1",
")",
"{",
"obj",
".",
"options",
"=",
"obj",
".",
"options",
"||",
"{",
"}",
";",
"obj",
".",
"options",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"delete",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] | Move reserved options properties from `obj` to `obj.options` | [
"Move",
"reserved",
"options",
"properties",
"from",
"obj",
"to",
"obj",
".",
"options"
] | dc05e6ace37c5ae87e8b053d5817656d2a13d69c | https://github.com/jonschlinkert/normalize-config/blob/dc05e6ace37c5ae87e8b053d5817656d2a13d69c/index.js#L42-L51 |
52,972 | jonschlinkert/normalize-config | index.js | toObject | function toObject(src, dest, options) {
if (!utils.isObject(options)) {
options = {};
}
var config = {};
if (utils.isObject(dest)) {
options = extend({}, options, dest);
dest = null;
}
if (utils.isObject(src)) {
config = src;
}
if (isValidSrc(src)) {
config.src = src;
} else if (Array.isArray(src)) {
config = normalize(src);
}
if (typeof dest === 'string') {
config.dest = dest;
}
if (options.hasOwnProperty('options')) {
options = extend({}, options, options.options);
delete options.options;
}
config.options = extend({}, config.options, options);
return config;
} | javascript | function toObject(src, dest, options) {
if (!utils.isObject(options)) {
options = {};
}
var config = {};
if (utils.isObject(dest)) {
options = extend({}, options, dest);
dest = null;
}
if (utils.isObject(src)) {
config = src;
}
if (isValidSrc(src)) {
config.src = src;
} else if (Array.isArray(src)) {
config = normalize(src);
}
if (typeof dest === 'string') {
config.dest = dest;
}
if (options.hasOwnProperty('options')) {
options = extend({}, options, options.options);
delete options.options;
}
config.options = extend({}, config.options, options);
return config;
} | [
"function",
"toObject",
"(",
"src",
",",
"dest",
",",
"options",
")",
"{",
"if",
"(",
"!",
"utils",
".",
"isObject",
"(",
"options",
")",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"var",
"config",
"=",
"{",
"}",
";",
"if",
"(",
"utils",
".",
"isObject",
"(",
"dest",
")",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
",",
"dest",
")",
";",
"dest",
"=",
"null",
";",
"}",
"if",
"(",
"utils",
".",
"isObject",
"(",
"src",
")",
")",
"{",
"config",
"=",
"src",
";",
"}",
"if",
"(",
"isValidSrc",
"(",
"src",
")",
")",
"{",
"config",
".",
"src",
"=",
"src",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"src",
")",
")",
"{",
"config",
"=",
"normalize",
"(",
"src",
")",
";",
"}",
"if",
"(",
"typeof",
"dest",
"===",
"'string'",
")",
"{",
"config",
".",
"dest",
"=",
"dest",
";",
"}",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'options'",
")",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
",",
"options",
".",
"options",
")",
";",
"delete",
"options",
".",
"options",
";",
"}",
"config",
".",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"config",
".",
"options",
",",
"options",
")",
";",
"return",
"config",
";",
"}"
] | Convert args list to a config object. | [
"Convert",
"args",
"list",
"to",
"a",
"config",
"object",
"."
] | dc05e6ace37c5ae87e8b053d5817656d2a13d69c | https://github.com/jonschlinkert/normalize-config/blob/dc05e6ace37c5ae87e8b053d5817656d2a13d69c/index.js#L67-L99 |
52,973 | jonschlinkert/normalize-config | index.js | normalizeSrc | function normalizeSrc(val) {
if (!val.src) return val;
val.src = utils.arrayify(val.src);
return val;
} | javascript | function normalizeSrc(val) {
if (!val.src) return val;
val.src = utils.arrayify(val.src);
return val;
} | [
"function",
"normalizeSrc",
"(",
"val",
")",
"{",
"if",
"(",
"!",
"val",
".",
"src",
")",
"return",
"val",
";",
"val",
".",
"src",
"=",
"utils",
".",
"arrayify",
"(",
"val",
".",
"src",
")",
";",
"return",
"val",
";",
"}"
] | Ensure that `src` on the given val is an array
@param {Object} `val` Object with a `src` property
@return {Object} | [
"Ensure",
"that",
"src",
"on",
"the",
"given",
"val",
"is",
"an",
"array"
] | dc05e6ace37c5ae87e8b053d5817656d2a13d69c | https://github.com/jonschlinkert/normalize-config/blob/dc05e6ace37c5ae87e8b053d5817656d2a13d69c/index.js#L151-L155 |
52,974 | jonschlinkert/normalize-config | index.js | reduceFiles | function reduceFiles(files, orig) {
var config = {files: []};
var len = files.length;
var idx = -1;
while (++idx < len) {
var val = normalize(files[idx]);
config.files = config.files.concat(val.files);
}
return copyNonfiles(config, orig);
} | javascript | function reduceFiles(files, orig) {
var config = {files: []};
var len = files.length;
var idx = -1;
while (++idx < len) {
var val = normalize(files[idx]);
config.files = config.files.concat(val.files);
}
return copyNonfiles(config, orig);
} | [
"function",
"reduceFiles",
"(",
"files",
",",
"orig",
")",
"{",
"var",
"config",
"=",
"{",
"files",
":",
"[",
"]",
"}",
";",
"var",
"len",
"=",
"files",
".",
"length",
";",
"var",
"idx",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"idx",
"<",
"len",
")",
"{",
"var",
"val",
"=",
"normalize",
"(",
"files",
"[",
"idx",
"]",
")",
";",
"config",
".",
"files",
"=",
"config",
".",
"files",
".",
"concat",
"(",
"val",
".",
"files",
")",
";",
"}",
"return",
"copyNonfiles",
"(",
"config",
",",
"orig",
")",
";",
"}"
] | Normalize all objects in a `files` array.
@param {Array} `files`
@return {Array} | [
"Normalize",
"all",
"objects",
"in",
"a",
"files",
"array",
"."
] | dc05e6ace37c5ae87e8b053d5817656d2a13d69c | https://github.com/jonschlinkert/normalize-config/blob/dc05e6ace37c5ae87e8b053d5817656d2a13d69c/index.js#L192-L203 |
52,975 | jonschlinkert/normalize-config | index.js | copyNonfiles | function copyNonfiles(config, provider) {
if (!provider) return config;
for (var key in provider) {
if (!isFilesKey(key)) {
config[key] = provider[key];
}
}
return config;
} | javascript | function copyNonfiles(config, provider) {
if (!provider) return config;
for (var key in provider) {
if (!isFilesKey(key)) {
config[key] = provider[key];
}
}
return config;
} | [
"function",
"copyNonfiles",
"(",
"config",
",",
"provider",
")",
"{",
"if",
"(",
"!",
"provider",
")",
"return",
"config",
";",
"for",
"(",
"var",
"key",
"in",
"provider",
")",
"{",
"if",
"(",
"!",
"isFilesKey",
"(",
"key",
")",
")",
"{",
"config",
"[",
"key",
"]",
"=",
"provider",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"config",
";",
"}"
] | Create a `files` array from a src-dest object.
```js
// converts from:
{ src: '*.js', dest: 'foo/' }
// to:
{ files: [{ src: ['*.js'], dest: 'foo/' }] }
``` | [
"Create",
"a",
"files",
"array",
"from",
"a",
"src",
"-",
"dest",
"object",
"."
] | dc05e6ace37c5ae87e8b053d5817656d2a13d69c | https://github.com/jonschlinkert/normalize-config/blob/dc05e6ace37c5ae87e8b053d5817656d2a13d69c/index.js#L217-L225 |
52,976 | jonschlinkert/normalize-config | index.js | filesObjects | function filesObjects(val) {
var res = {};
if (val.options) res.options = val.options;
res.files = [];
for (var key in val) {
if (key !== 'options') {
var file = {};
if (val.options) file.options = val.options;
file.src = utils.arrayify(val[key]);
file.dest = key;
res.files.push(file);
}
}
return res;
} | javascript | function filesObjects(val) {
var res = {};
if (val.options) res.options = val.options;
res.files = [];
for (var key in val) {
if (key !== 'options') {
var file = {};
if (val.options) file.options = val.options;
file.src = utils.arrayify(val[key]);
file.dest = key;
res.files.push(file);
}
}
return res;
} | [
"function",
"filesObjects",
"(",
"val",
")",
"{",
"var",
"res",
"=",
"{",
"}",
";",
"if",
"(",
"val",
".",
"options",
")",
"res",
".",
"options",
"=",
"val",
".",
"options",
";",
"res",
".",
"files",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"val",
")",
"{",
"if",
"(",
"key",
"!==",
"'options'",
")",
"{",
"var",
"file",
"=",
"{",
"}",
";",
"if",
"(",
"val",
".",
"options",
")",
"file",
".",
"options",
"=",
"val",
".",
"options",
";",
"file",
".",
"src",
"=",
"utils",
".",
"arrayify",
"(",
"val",
"[",
"key",
"]",
")",
";",
"file",
".",
"dest",
"=",
"key",
";",
"res",
".",
"files",
".",
"push",
"(",
"file",
")",
";",
"}",
"}",
"return",
"res",
";",
"}"
] | When `src`, `dest` and `files` are absent from the
object, we check to see if file objects were defined.
```js
// converts from:
{ 'foo/': '*.js' }
// to
{ files: [{ src: ['*.js'], dest: 'foo/' }] }
``` | [
"When",
"src",
"dest",
"and",
"files",
"are",
"absent",
"from",
"the",
"object",
"we",
"check",
"to",
"see",
"if",
"file",
"objects",
"were",
"defined",
"."
] | dc05e6ace37c5ae87e8b053d5817656d2a13d69c | https://github.com/jonschlinkert/normalize-config/blob/dc05e6ace37c5ae87e8b053d5817656d2a13d69c/index.js#L257-L272 |
52,977 | jonschlinkert/normalize-config | index.js | formatObject | function formatObject(val) {
if (val.options && val.options.format === false) {
return val;
}
var res = { options: val.options };
res.files = val.files;
for (var key in val) {
if (key === 'files' || key === 'options') {
continue;
}
res[key] = val[key];
}
var len = res.files.length;
var idx = -1;
while (++idx < len) {
var ele = res.files[idx];
var obj = {};
obj.options = {};
obj.src = ele.src || [];
obj.dest = ele.dest || '';
copyNonfiles(obj, ele);
if (!ele.options) {
obj.options = res.options;
}
res.files[idx] = obj;
}
return res;
} | javascript | function formatObject(val) {
if (val.options && val.options.format === false) {
return val;
}
var res = { options: val.options };
res.files = val.files;
for (var key in val) {
if (key === 'files' || key === 'options') {
continue;
}
res[key] = val[key];
}
var len = res.files.length;
var idx = -1;
while (++idx < len) {
var ele = res.files[idx];
var obj = {};
obj.options = {};
obj.src = ele.src || [];
obj.dest = ele.dest || '';
copyNonfiles(obj, ele);
if (!ele.options) {
obj.options = res.options;
}
res.files[idx] = obj;
}
return res;
} | [
"function",
"formatObject",
"(",
"val",
")",
"{",
"if",
"(",
"val",
".",
"options",
"&&",
"val",
".",
"options",
".",
"format",
"===",
"false",
")",
"{",
"return",
"val",
";",
"}",
"var",
"res",
"=",
"{",
"options",
":",
"val",
".",
"options",
"}",
";",
"res",
".",
"files",
"=",
"val",
".",
"files",
";",
"for",
"(",
"var",
"key",
"in",
"val",
")",
"{",
"if",
"(",
"key",
"===",
"'files'",
"||",
"key",
"===",
"'options'",
")",
"{",
"continue",
";",
"}",
"res",
"[",
"key",
"]",
"=",
"val",
"[",
"key",
"]",
";",
"}",
"var",
"len",
"=",
"res",
".",
"files",
".",
"length",
";",
"var",
"idx",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"idx",
"<",
"len",
")",
"{",
"var",
"ele",
"=",
"res",
".",
"files",
"[",
"idx",
"]",
";",
"var",
"obj",
"=",
"{",
"}",
";",
"obj",
".",
"options",
"=",
"{",
"}",
";",
"obj",
".",
"src",
"=",
"ele",
".",
"src",
"||",
"[",
"]",
";",
"obj",
".",
"dest",
"=",
"ele",
".",
"dest",
"||",
"''",
";",
"copyNonfiles",
"(",
"obj",
",",
"ele",
")",
";",
"if",
"(",
"!",
"ele",
".",
"options",
")",
"{",
"obj",
".",
"options",
"=",
"res",
".",
"options",
";",
"}",
"res",
".",
"files",
"[",
"idx",
"]",
"=",
"obj",
";",
"}",
"return",
"res",
";",
"}"
] | Optionally sort the keys in all of the files objects.
Helps with debugging.
@param {Object} `val` Pass `{sort: true}` on `val.options` to enable sorting.
@return {Object} | [
"Optionally",
"sort",
"the",
"keys",
"in",
"all",
"of",
"the",
"files",
"objects",
".",
"Helps",
"with",
"debugging",
"."
] | dc05e6ace37c5ae87e8b053d5817656d2a13d69c | https://github.com/jonschlinkert/normalize-config/blob/dc05e6ace37c5ae87e8b053d5817656d2a13d69c/index.js#L282-L315 |
52,978 | chrisenytc/livi18n | lib/livi18n.js | function (app) {
//Provide angularLivi18nService
app.get('/livi18n/ngLivi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'ngLivi18n.js');
res.sendfile(filepath);
});
//Check if socket is enabled
if (config.socket) {
//Provide SocketManager
app.get('/livi18n/livi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'livi18nSocket.js');
res.sendfile(filepath);
});
//Provide angularSocketService
app.get('/livi18n/ngSocket.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'ngSocket.js');
res.sendfile(filepath);
});
} else {
//Provide js library
app.get('/livi18n/livi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'livi18n.js');
res.sendfile(filepath);
});
//Provide i18n API
app.get('/livi18n/:filename', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.json(readLanguage(config.currentLanguage, req.params.filename + '.json'));
});
}
} | javascript | function (app) {
//Provide angularLivi18nService
app.get('/livi18n/ngLivi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'ngLivi18n.js');
res.sendfile(filepath);
});
//Check if socket is enabled
if (config.socket) {
//Provide SocketManager
app.get('/livi18n/livi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'livi18nSocket.js');
res.sendfile(filepath);
});
//Provide angularSocketService
app.get('/livi18n/ngSocket.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'ngSocket.js');
res.sendfile(filepath);
});
} else {
//Provide js library
app.get('/livi18n/livi18n.js', function (req, res) {
var filepath = path.join(__dirname, 'client', 'livi18n.js');
res.sendfile(filepath);
});
//Provide i18n API
app.get('/livi18n/:filename', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.json(readLanguage(config.currentLanguage, req.params.filename + '.json'));
});
}
} | [
"function",
"(",
"app",
")",
"{",
"//Provide angularLivi18nService",
"app",
".",
"get",
"(",
"'/livi18n/ngLivi18n.js'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"filepath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'client'",
",",
"'ngLivi18n.js'",
")",
";",
"res",
".",
"sendfile",
"(",
"filepath",
")",
";",
"}",
")",
";",
"//Check if socket is enabled",
"if",
"(",
"config",
".",
"socket",
")",
"{",
"//Provide SocketManager",
"app",
".",
"get",
"(",
"'/livi18n/livi18n.js'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"filepath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'client'",
",",
"'livi18nSocket.js'",
")",
";",
"res",
".",
"sendfile",
"(",
"filepath",
")",
";",
"}",
")",
";",
"//Provide angularSocketService",
"app",
".",
"get",
"(",
"'/livi18n/ngSocket.js'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"filepath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'client'",
",",
"'ngSocket.js'",
")",
";",
"res",
".",
"sendfile",
"(",
"filepath",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"//Provide js library",
"app",
".",
"get",
"(",
"'/livi18n/livi18n.js'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"filepath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'client'",
",",
"'livi18n.js'",
")",
";",
"res",
".",
"sendfile",
"(",
"filepath",
")",
";",
"}",
")",
";",
"//Provide i18n API",
"app",
".",
"get",
"(",
"'/livi18n/:filename'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"header",
"(",
"\"Access-Control-Allow-Origin\"",
",",
"\"*\"",
")",
";",
"res",
".",
"header",
"(",
"\"Access-Control-Allow-Headers\"",
",",
"\"X-Requested-With\"",
")",
";",
"res",
".",
"json",
"(",
"readLanguage",
"(",
"config",
".",
"currentLanguage",
",",
"req",
".",
"params",
".",
"filename",
"+",
"'.json'",
")",
")",
";",
"}",
")",
";",
"}",
"}"
] | Provide ClientSide API | [
"Provide",
"ClientSide",
"API"
] | cff846d533f2db9162013dd572d18ffd8fa38340 | https://github.com/chrisenytc/livi18n/blob/cff846d533f2db9162013dd572d18ffd8fa38340/lib/livi18n.js#L63-L94 |
|
52,979 | chrisenytc/livi18n | lib/livi18n.js | function (language) {
for (var i in config.languages) {
if (config.languages[i] === language) {return true;}
}
//
return false;
} | javascript | function (language) {
for (var i in config.languages) {
if (config.languages[i] === language) {return true;}
}
//
return false;
} | [
"function",
"(",
"language",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"config",
".",
"languages",
")",
"{",
"if",
"(",
"config",
".",
"languages",
"[",
"i",
"]",
"===",
"language",
")",
"{",
"return",
"true",
";",
"}",
"}",
"//",
"return",
"false",
";",
"}"
] | Check if this language exists | [
"Check",
"if",
"this",
"language",
"exists"
] | cff846d533f2db9162013dd572d18ffd8fa38340 | https://github.com/chrisenytc/livi18n/blob/cff846d533f2db9162013dd572d18ffd8fa38340/lib/livi18n.js#L111-L117 |
|
52,980 | jmjuanes/minsql | lib/query/insert.js | GetValues | function GetValues(mydata, keys, index)
{
//Output
var values = [];
//Loop
for(var j = 0; j < keys.length; j++)
{
//Save data value
var value = mydata[keys[j]];
//Check if value exists
if(!value)
{
//Show warning
console.log('WARNING: value "' + keys[j] + '" is not defined on element "' + index + '" of your array.');
//Set it to empty string
value = '';
}
//Check the data type
if(typeof value === 'string' || value instanceof String)
{
//Add the quotes
value = '"' + value + '"';
}
//Push
values.push(value);
}
//Return
return values.join(',');
} | javascript | function GetValues(mydata, keys, index)
{
//Output
var values = [];
//Loop
for(var j = 0; j < keys.length; j++)
{
//Save data value
var value = mydata[keys[j]];
//Check if value exists
if(!value)
{
//Show warning
console.log('WARNING: value "' + keys[j] + '" is not defined on element "' + index + '" of your array.');
//Set it to empty string
value = '';
}
//Check the data type
if(typeof value === 'string' || value instanceof String)
{
//Add the quotes
value = '"' + value + '"';
}
//Push
values.push(value);
}
//Return
return values.join(',');
} | [
"function",
"GetValues",
"(",
"mydata",
",",
"keys",
",",
"index",
")",
"{",
"//Output\r",
"var",
"values",
"=",
"[",
"]",
";",
"//Loop\r",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"keys",
".",
"length",
";",
"j",
"++",
")",
"{",
"//Save data value\r",
"var",
"value",
"=",
"mydata",
"[",
"keys",
"[",
"j",
"]",
"]",
";",
"//Check if value exists\r",
"if",
"(",
"!",
"value",
")",
"{",
"//Show warning\r",
"console",
".",
"log",
"(",
"'WARNING: value \"'",
"+",
"keys",
"[",
"j",
"]",
"+",
"'\" is not defined on element \"'",
"+",
"index",
"+",
"'\" of your array.'",
")",
";",
"//Set it to empty string\r",
"value",
"=",
"''",
";",
"}",
"//Check the data type\r",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
"||",
"value",
"instanceof",
"String",
")",
"{",
"//Add the quotes\r",
"value",
"=",
"'\"'",
"+",
"value",
"+",
"'\"'",
";",
"}",
"//Push\r",
"values",
".",
"push",
"(",
"value",
")",
";",
"}",
"//Return\r",
"return",
"values",
".",
"join",
"(",
"','",
")",
";",
"}"
] | Get all the values | [
"Get",
"all",
"the",
"values"
] | 80eddd97e858545997b30e3c9bc067d5fc2df5a0 | https://github.com/jmjuanes/minsql/blob/80eddd97e858545997b30e3c9bc067d5fc2df5a0/lib/query/insert.js#L59-L93 |
52,981 | redisjs/jsr-store | lib/command/zset.js | zadd | function zadd(key /* score-1, member-1, score-N, member-N, req */) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, val = this.getKey(key, req);
if(val === undefined) {
val = new SortedSet();
this.setKey(key, val, undefined, undefined, undefined, req);
}
return val.zadd(args);
} | javascript | function zadd(key /* score-1, member-1, score-N, member-N, req */) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, val = this.getKey(key, req);
if(val === undefined) {
val = new SortedSet();
this.setKey(key, val, undefined, undefined, undefined, req);
}
return val.zadd(args);
} | [
"function",
"zadd",
"(",
"key",
"/* score-1, member-1, score-N, member-N, req */",
")",
"{",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
",",
"req",
"=",
"typeof",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
"===",
"'object'",
"?",
"args",
".",
"pop",
"(",
")",
":",
"null",
",",
"val",
"=",
"this",
".",
"getKey",
"(",
"key",
",",
"req",
")",
";",
"if",
"(",
"val",
"===",
"undefined",
")",
"{",
"val",
"=",
"new",
"SortedSet",
"(",
")",
";",
"this",
".",
"setKey",
"(",
"key",
",",
"val",
",",
"undefined",
",",
"undefined",
",",
"undefined",
",",
"req",
")",
";",
"}",
"return",
"val",
".",
"zadd",
"(",
"args",
")",
";",
"}"
] | Adds all the specified members with the specified scores
to the sorted set stored at key. | [
"Adds",
"all",
"the",
"specified",
"members",
"with",
"the",
"specified",
"scores",
"to",
"the",
"sorted",
"set",
"stored",
"at",
"key",
"."
] | b2b5c5b0347819f8a388b5d67e121ee8d73f328c | https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/command/zset.js#L8-L19 |
52,982 | redisjs/jsr-store | lib/command/zset.js | zrank | function zrank(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zrank(member);
} | javascript | function zrank(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zrank(member);
} | [
"function",
"zrank",
"(",
"key",
",",
"member",
",",
"req",
")",
"{",
"var",
"zset",
"=",
"this",
".",
"getKey",
"(",
"key",
",",
"req",
")",
";",
"if",
"(",
"zset",
"===",
"undefined",
")",
"return",
"null",
";",
"return",
"zset",
".",
"zrank",
"(",
"member",
")",
";",
"}"
] | Returns the rank of member in the sorted set stored at key,
with the scores ordered from low to high. | [
"Returns",
"the",
"rank",
"of",
"member",
"in",
"the",
"sorted",
"set",
"stored",
"at",
"key",
"with",
"the",
"scores",
"ordered",
"from",
"low",
"to",
"high",
"."
] | b2b5c5b0347819f8a388b5d67e121ee8d73f328c | https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/command/zset.js#L35-L39 |
52,983 | redisjs/jsr-store | lib/command/zset.js | zrevrank | function zrevrank(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zrevrank(member);
} | javascript | function zrevrank(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zrevrank(member);
} | [
"function",
"zrevrank",
"(",
"key",
",",
"member",
",",
"req",
")",
"{",
"var",
"zset",
"=",
"this",
".",
"getKey",
"(",
"key",
",",
"req",
")",
";",
"if",
"(",
"zset",
"===",
"undefined",
")",
"return",
"null",
";",
"return",
"zset",
".",
"zrevrank",
"(",
"member",
")",
";",
"}"
] | Returns the rank of member in the sorted set stored at key,
with the scores ordered from high to low. | [
"Returns",
"the",
"rank",
"of",
"member",
"in",
"the",
"sorted",
"set",
"stored",
"at",
"key",
"with",
"the",
"scores",
"ordered",
"from",
"high",
"to",
"low",
"."
] | b2b5c5b0347819f8a388b5d67e121ee8d73f328c | https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/command/zset.js#L45-L49 |
52,984 | redisjs/jsr-store | lib/command/zset.js | zscore | function zscore(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zscore(member);
} | javascript | function zscore(key, member, req) {
var zset = this.getKey(key, req);
if(zset === undefined) return null;
return zset.zscore(member);
} | [
"function",
"zscore",
"(",
"key",
",",
"member",
",",
"req",
")",
"{",
"var",
"zset",
"=",
"this",
".",
"getKey",
"(",
"key",
",",
"req",
")",
";",
"if",
"(",
"zset",
"===",
"undefined",
")",
"return",
"null",
";",
"return",
"zset",
".",
"zscore",
"(",
"member",
")",
";",
"}"
] | Returns the score of member in the sorted set at key. | [
"Returns",
"the",
"score",
"of",
"member",
"in",
"the",
"sorted",
"set",
"at",
"key",
"."
] | b2b5c5b0347819f8a388b5d67e121ee8d73f328c | https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/command/zset.js#L54-L58 |
52,985 | redisjs/jsr-store | lib/command/zset.js | zrem | function zrem(key /* member-1, member-N, req */) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, val = this.getKey(key, req);
if(val === undefined) return 0;
var deleted = val.zrem(args);
if(val.zcard() === 0) {
this.delKey(key, req);
}
return deleted;
} | javascript | function zrem(key /* member-1, member-N, req */) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, val = this.getKey(key, req);
if(val === undefined) return 0;
var deleted = val.zrem(args);
if(val.zcard() === 0) {
this.delKey(key, req);
}
return deleted;
} | [
"function",
"zrem",
"(",
"key",
"/* member-1, member-N, req */",
")",
"{",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
",",
"req",
"=",
"typeof",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
"===",
"'object'",
"?",
"args",
".",
"pop",
"(",
")",
":",
"null",
",",
"val",
"=",
"this",
".",
"getKey",
"(",
"key",
",",
"req",
")",
";",
"if",
"(",
"val",
"===",
"undefined",
")",
"return",
"0",
";",
"var",
"deleted",
"=",
"val",
".",
"zrem",
"(",
"args",
")",
";",
"if",
"(",
"val",
".",
"zcard",
"(",
")",
"===",
"0",
")",
"{",
"this",
".",
"delKey",
"(",
"key",
",",
"req",
")",
";",
"}",
"return",
"deleted",
";",
"}"
] | Removes the specified members from the sorted set stored at key. | [
"Removes",
"the",
"specified",
"members",
"from",
"the",
"sorted",
"set",
"stored",
"at",
"key",
"."
] | b2b5c5b0347819f8a388b5d67e121ee8d73f328c | https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/command/zset.js#L63-L73 |
52,986 | redisjs/jsr-store | lib/command/zset.js | zincrby | function zincrby(key, increment, member, req) {
var val = this.getKey(key, req);
if(val === undefined) {
val = new SortedSet();
this.setKey(key, val, undefined, undefined, undefined, req);
}
return val.zincrby(increment, member);
} | javascript | function zincrby(key, increment, member, req) {
var val = this.getKey(key, req);
if(val === undefined) {
val = new SortedSet();
this.setKey(key, val, undefined, undefined, undefined, req);
}
return val.zincrby(increment, member);
} | [
"function",
"zincrby",
"(",
"key",
",",
"increment",
",",
"member",
",",
"req",
")",
"{",
"var",
"val",
"=",
"this",
".",
"getKey",
"(",
"key",
",",
"req",
")",
";",
"if",
"(",
"val",
"===",
"undefined",
")",
"{",
"val",
"=",
"new",
"SortedSet",
"(",
")",
";",
"this",
".",
"setKey",
"(",
"key",
",",
"val",
",",
"undefined",
",",
"undefined",
",",
"undefined",
",",
"req",
")",
";",
"}",
"return",
"val",
".",
"zincrby",
"(",
"increment",
",",
"member",
")",
";",
"}"
] | Increments the score of member in the sorted set stored
at key by increment. | [
"Increments",
"the",
"score",
"of",
"member",
"in",
"the",
"sorted",
"set",
"stored",
"at",
"key",
"by",
"increment",
"."
] | b2b5c5b0347819f8a388b5d67e121ee8d73f328c | https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/command/zset.js#L79-L86 |
52,987 | eliascodes/modload | lib/utils.js | function (arr, val) {
if (!arr || arr.length === 0) return {}
let o = {}
let v = val || null
if (arr.length > 1)
v = this.fromArray(arr.slice(1), v)
o[arr[0]] = v
return o
} | javascript | function (arr, val) {
if (!arr || arr.length === 0) return {}
let o = {}
let v = val || null
if (arr.length > 1)
v = this.fromArray(arr.slice(1), v)
o[arr[0]] = v
return o
} | [
"function",
"(",
"arr",
",",
"val",
")",
"{",
"if",
"(",
"!",
"arr",
"||",
"arr",
".",
"length",
"===",
"0",
")",
"return",
"{",
"}",
"let",
"o",
"=",
"{",
"}",
"let",
"v",
"=",
"val",
"||",
"null",
"if",
"(",
"arr",
".",
"length",
">",
"1",
")",
"v",
"=",
"this",
".",
"fromArray",
"(",
"arr",
".",
"slice",
"(",
"1",
")",
",",
"v",
")",
"o",
"[",
"arr",
"[",
"0",
"]",
"]",
"=",
"v",
"return",
"o",
"}"
] | Constructs nested object reflecting array
@returns {object} The nested object
@param {array} arr - array from which to construct object
@param {any} val - value to assign to the deepest level object key | [
"Constructs",
"nested",
"object",
"reflecting",
"array"
] | bc3bad88c8b677970bb9154764db7bbf72401d3a | https://github.com/eliascodes/modload/blob/bc3bad88c8b677970bb9154764db7bbf72401d3a/lib/utils.js#L38-L49 |
|
52,988 | eliascodes/modload | lib/utils.js | function (str, sep, val) {
if (!str || str.length === 0) return {}
const parts = str.split(sep).filter((s) => s)
return this.fromArray(parts, val)
} | javascript | function (str, sep, val) {
if (!str || str.length === 0) return {}
const parts = str.split(sep).filter((s) => s)
return this.fromArray(parts, val)
} | [
"function",
"(",
"str",
",",
"sep",
",",
"val",
")",
"{",
"if",
"(",
"!",
"str",
"||",
"str",
".",
"length",
"===",
"0",
")",
"return",
"{",
"}",
"const",
"parts",
"=",
"str",
".",
"split",
"(",
"sep",
")",
".",
"filter",
"(",
"(",
"s",
")",
"=>",
"s",
")",
"return",
"this",
".",
"fromArray",
"(",
"parts",
",",
"val",
")",
"}"
] | Constructs nested object reflecting string
@returns {object} The nested object
@param {string} str - string from which to construct object
@param {string} sep - separator with which to split the string
@param {any} val - value to assign to the deepest level object key | [
"Constructs",
"nested",
"object",
"reflecting",
"string"
] | bc3bad88c8b677970bb9154764db7bbf72401d3a | https://github.com/eliascodes/modload/blob/bc3bad88c8b677970bb9154764db7bbf72401d3a/lib/utils.js#L58-L62 |
|
52,989 | eliascodes/modload | lib/utils.js | mergeObjects | function mergeObjects (o1, o2) {
let m = Object.assign({}, o1)
for (let attr in o2) {
let v = o2[attr]
if (attr in m && isPlainObject(v) && isPlainObject(m[attr]))
m[attr] = mergeObjects(m[attr], v)
else
m[attr] = v
}
return m
} | javascript | function mergeObjects (o1, o2) {
let m = Object.assign({}, o1)
for (let attr in o2) {
let v = o2[attr]
if (attr in m && isPlainObject(v) && isPlainObject(m[attr]))
m[attr] = mergeObjects(m[attr], v)
else
m[attr] = v
}
return m
} | [
"function",
"mergeObjects",
"(",
"o1",
",",
"o2",
")",
"{",
"let",
"m",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"o1",
")",
"for",
"(",
"let",
"attr",
"in",
"o2",
")",
"{",
"let",
"v",
"=",
"o2",
"[",
"attr",
"]",
"if",
"(",
"attr",
"in",
"m",
"&&",
"isPlainObject",
"(",
"v",
")",
"&&",
"isPlainObject",
"(",
"m",
"[",
"attr",
"]",
")",
")",
"m",
"[",
"attr",
"]",
"=",
"mergeObjects",
"(",
"m",
"[",
"attr",
"]",
",",
"v",
")",
"else",
"m",
"[",
"attr",
"]",
"=",
"v",
"}",
"return",
"m",
"}"
] | Merges objects recursively. Conflicts are resolved by privileging the second argument.
@returns {object} Recursively merged object
@param {object} o1 - First object to merge: taken as the base
@param {object} o2 - Second object to merge: overwrites the base | [
"Merges",
"objects",
"recursively",
".",
"Conflicts",
"are",
"resolved",
"by",
"privileging",
"the",
"second",
"argument",
"."
] | bc3bad88c8b677970bb9154764db7bbf72401d3a | https://github.com/eliascodes/modload/blob/bc3bad88c8b677970bb9154764db7bbf72401d3a/lib/utils.js#L71-L82 |
52,990 | eliascodes/modload | lib/utils.js | parser | function parser (defaults, validators, mappers) {
return function (opts) {
const merged = mergeObjects(defaults, opts)
Object.keys(merged).forEach((key) => {
if (validators[key] && ! validators[key](merged[key]))
throw new Error('Failed to validate ' + key)
if (mappers && mappers[key])
merged[key] = mappers[key](merged[key])
})
return merged
}
} | javascript | function parser (defaults, validators, mappers) {
return function (opts) {
const merged = mergeObjects(defaults, opts)
Object.keys(merged).forEach((key) => {
if (validators[key] && ! validators[key](merged[key]))
throw new Error('Failed to validate ' + key)
if (mappers && mappers[key])
merged[key] = mappers[key](merged[key])
})
return merged
}
} | [
"function",
"parser",
"(",
"defaults",
",",
"validators",
",",
"mappers",
")",
"{",
"return",
"function",
"(",
"opts",
")",
"{",
"const",
"merged",
"=",
"mergeObjects",
"(",
"defaults",
",",
"opts",
")",
"Object",
".",
"keys",
"(",
"merged",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"if",
"(",
"validators",
"[",
"key",
"]",
"&&",
"!",
"validators",
"[",
"key",
"]",
"(",
"merged",
"[",
"key",
"]",
")",
")",
"throw",
"new",
"Error",
"(",
"'Failed to validate '",
"+",
"key",
")",
"if",
"(",
"mappers",
"&&",
"mappers",
"[",
"key",
"]",
")",
"merged",
"[",
"key",
"]",
"=",
"mappers",
"[",
"key",
"]",
"(",
"merged",
"[",
"key",
"]",
")",
"}",
")",
"return",
"merged",
"}",
"}"
] | Creates function to validate and transform objects.
Useful for parsing of options objects
@returns {object} Parsed, validated and transformed object
@param {object} defaults - of default values used if absent from object being parsed
@param {object} validators - of methods used to validate values of object being parsed
@param {object} mappers - of methods used to transform values after successful validation | [
"Creates",
"function",
"to",
"validate",
"and",
"transform",
"objects",
".",
"Useful",
"for",
"parsing",
"of",
"options",
"objects"
] | bc3bad88c8b677970bb9154764db7bbf72401d3a | https://github.com/eliascodes/modload/blob/bc3bad88c8b677970bb9154764db7bbf72401d3a/lib/utils.js#L92-L106 |
52,991 | eliascodes/modload | lib/utils.js | combine | function combine () {
const c = Array.prototype.concat.apply([], arguments)
.map((expression) => '(' + expression.source + ')')
.join('|')
return new RegExp(c)
} | javascript | function combine () {
const c = Array.prototype.concat.apply([], arguments)
.map((expression) => '(' + expression.source + ')')
.join('|')
return new RegExp(c)
} | [
"function",
"combine",
"(",
")",
"{",
"const",
"c",
"=",
"Array",
".",
"prototype",
".",
"concat",
".",
"apply",
"(",
"[",
"]",
",",
"arguments",
")",
".",
"map",
"(",
"(",
"expression",
")",
"=>",
"'('",
"+",
"expression",
".",
"source",
"+",
"')'",
")",
".",
"join",
"(",
"'|'",
")",
"return",
"new",
"RegExp",
"(",
"c",
")",
"}"
] | Combines array of RegExp objects into a single RegExp with OR
Takes an arbitrary number of RegExp objects
@returns {RegExp} Combined RegExp | [
"Combines",
"array",
"of",
"RegExp",
"objects",
"into",
"a",
"single",
"RegExp",
"with",
"OR",
"Takes",
"an",
"arbitrary",
"number",
"of",
"RegExp",
"objects"
] | bc3bad88c8b677970bb9154764db7bbf72401d3a | https://github.com/eliascodes/modload/blob/bc3bad88c8b677970bb9154764db7bbf72401d3a/lib/utils.js#L113-L118 |
52,992 | Psychopoulet/node-promfs | bin/extractFromArgs.js | _executeCommands | function _executeCommands (showDetails, cmds) {
if (cmds.length) {
const cmd = cmds.shift();
execute(showDetails, cmd.cmd, cmd.options).then((...data) => {
if (data.length && undefined !== data[0]) {
if (1 === data.length && "boolean" === typeof data[0]) {
if (showDetails) {
(0, console).log(getFormatedTime(), "=>", data[0]);
}
else {
(0, console).log(data[0] ? "1" : "0");
}
}
else if (showDetails) {
(0, console).log(getFormatedTime(), "=>", ...data);
}
else {
(0, console).log(...data);
}
}
_executeCommands(showDetails, cmds);
}).catch((err) => {
(0, console).error(err);
(0, process).exitCode = 1;
});
}
} | javascript | function _executeCommands (showDetails, cmds) {
if (cmds.length) {
const cmd = cmds.shift();
execute(showDetails, cmd.cmd, cmd.options).then((...data) => {
if (data.length && undefined !== data[0]) {
if (1 === data.length && "boolean" === typeof data[0]) {
if (showDetails) {
(0, console).log(getFormatedTime(), "=>", data[0]);
}
else {
(0, console).log(data[0] ? "1" : "0");
}
}
else if (showDetails) {
(0, console).log(getFormatedTime(), "=>", ...data);
}
else {
(0, console).log(...data);
}
}
_executeCommands(showDetails, cmds);
}).catch((err) => {
(0, console).error(err);
(0, process).exitCode = 1;
});
}
} | [
"function",
"_executeCommands",
"(",
"showDetails",
",",
"cmds",
")",
"{",
"if",
"(",
"cmds",
".",
"length",
")",
"{",
"const",
"cmd",
"=",
"cmds",
".",
"shift",
"(",
")",
";",
"execute",
"(",
"showDetails",
",",
"cmd",
".",
"cmd",
",",
"cmd",
".",
"options",
")",
".",
"then",
"(",
"(",
"...",
"data",
")",
"=>",
"{",
"if",
"(",
"data",
".",
"length",
"&&",
"undefined",
"!==",
"data",
"[",
"0",
"]",
")",
"{",
"if",
"(",
"1",
"===",
"data",
".",
"length",
"&&",
"\"boolean\"",
"===",
"typeof",
"data",
"[",
"0",
"]",
")",
"{",
"if",
"(",
"showDetails",
")",
"{",
"(",
"0",
",",
"console",
")",
".",
"log",
"(",
"getFormatedTime",
"(",
")",
",",
"\"=>\"",
",",
"data",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"(",
"0",
",",
"console",
")",
".",
"log",
"(",
"data",
"[",
"0",
"]",
"?",
"\"1\"",
":",
"\"0\"",
")",
";",
"}",
"}",
"else",
"if",
"(",
"showDetails",
")",
"{",
"(",
"0",
",",
"console",
")",
".",
"log",
"(",
"getFormatedTime",
"(",
")",
",",
"\"=>\"",
",",
"...",
"data",
")",
";",
"}",
"else",
"{",
"(",
"0",
",",
"console",
")",
".",
"log",
"(",
"...",
"data",
")",
";",
"}",
"}",
"_executeCommands",
"(",
"showDetails",
",",
"cmds",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"(",
"0",
",",
"console",
")",
".",
"error",
"(",
"err",
")",
";",
"(",
"0",
",",
"process",
")",
".",
"exitCode",
"=",
"1",
";",
"}",
")",
";",
"}",
"}"
] | methods
Synchronously execute commands
@param {boolean} showDetails : show execution's details in console
@param {Array} cmds : all commands to execute
@returns {void} | [
"methods",
"Synchronously",
"execute",
"commands"
] | 016e272fc58c6ef6eae5ea551a0e8873f0ac20cc | https://github.com/Psychopoulet/node-promfs/blob/016e272fc58c6ef6eae5ea551a0e8873f0ac20cc/bin/extractFromArgs.js#L59-L97 |
52,993 | thebapi/connect-mongoose-session-store | lib/index.js | _getDefaultSessionSchema | function _getDefaultSessionSchema() {
return new MongooseSchema({
sid: {type : String, index: true },
session: {
type: MongooseSchema.Types.Mixed
},
dateLoggedIn : {
type : Date,
default : new Date()
},
lastAccessTime: {
type : Date,
default : new Date()
},
expires : {
type : Date,
index : true
}
});
} | javascript | function _getDefaultSessionSchema() {
return new MongooseSchema({
sid: {type : String, index: true },
session: {
type: MongooseSchema.Types.Mixed
},
dateLoggedIn : {
type : Date,
default : new Date()
},
lastAccessTime: {
type : Date,
default : new Date()
},
expires : {
type : Date,
index : true
}
});
} | [
"function",
"_getDefaultSessionSchema",
"(",
")",
"{",
"return",
"new",
"MongooseSchema",
"(",
"{",
"sid",
":",
"{",
"type",
":",
"String",
",",
"index",
":",
"true",
"}",
",",
"session",
":",
"{",
"type",
":",
"MongooseSchema",
".",
"Types",
".",
"Mixed",
"}",
",",
"dateLoggedIn",
":",
"{",
"type",
":",
"Date",
",",
"default",
":",
"new",
"Date",
"(",
")",
"}",
",",
"lastAccessTime",
":",
"{",
"type",
":",
"Date",
",",
"default",
":",
"new",
"Date",
"(",
")",
"}",
",",
"expires",
":",
"{",
"type",
":",
"Date",
",",
"index",
":",
"true",
"}",
"}",
")",
";",
"}"
] | Create a default mongoose schema
@returns {MongooseSchema}
@private | [
"Create",
"a",
"default",
"mongoose",
"schema"
] | a919f37582fb1fc619f375486e56046c0cae1813 | https://github.com/thebapi/connect-mongoose-session-store/blob/a919f37582fb1fc619f375486e56046c0cae1813/lib/index.js#L24-L45 |
52,994 | thebapi/connect-mongoose-session-store | lib/index.js | _pasreCookies | function _pasreCookies(sessionToStore) {
if (sessionToStore && sessionToStore.cookie && (typeof sessionToStore.cookie.toJSON === "function")) {
sessionToStore.cookie = sessionToStore.cookie.toJSON();
}
return sessionToStore;
} | javascript | function _pasreCookies(sessionToStore) {
if (sessionToStore && sessionToStore.cookie && (typeof sessionToStore.cookie.toJSON === "function")) {
sessionToStore.cookie = sessionToStore.cookie.toJSON();
}
return sessionToStore;
} | [
"function",
"_pasreCookies",
"(",
"sessionToStore",
")",
"{",
"if",
"(",
"sessionToStore",
"&&",
"sessionToStore",
".",
"cookie",
"&&",
"(",
"typeof",
"sessionToStore",
".",
"cookie",
".",
"toJSON",
"===",
"\"function\"",
")",
")",
"{",
"sessionToStore",
".",
"cookie",
"=",
"sessionToStore",
".",
"cookie",
".",
"toJSON",
"(",
")",
";",
"}",
"return",
"sessionToStore",
";",
"}"
] | parse and format cookie object | [
"parse",
"and",
"format",
"cookie",
"object"
] | a919f37582fb1fc619f375486e56046c0cae1813 | https://github.com/thebapi/connect-mongoose-session-store/blob/a919f37582fb1fc619f375486e56046c0cae1813/lib/index.js#L147-L152 |
52,995 | panjiesw/frest | internal/docs/themes/hugo-theme-learn/static/js/search.js | initLunr | function initLunr() {
if (!endsWith(baseurl,"/")){
baseurl = baseurl+'/'
};
// First retrieve the index file
$.getJSON(baseurl +"index.json")
.done(function(index) {
pagesIndex = index;
// Set up lunrjs by declaring the fields we use
// Also provide their boost level for the ranking
lunrIndex = new lunr.Index
lunrIndex.ref("uri");
lunrIndex.field('title', {
boost: 15
});
lunrIndex.field('tags', {
boost: 10
});
lunrIndex.field("content", {
boost: 5
});
// Feed lunr with each file and let lunr actually index them
pagesIndex.forEach(function(page) {
lunrIndex.add(page);
});
lunrIndex.pipeline.remove(lunrIndex.stemmer)
})
.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.error("Error getting Hugo index flie:", err);
});
} | javascript | function initLunr() {
if (!endsWith(baseurl,"/")){
baseurl = baseurl+'/'
};
// First retrieve the index file
$.getJSON(baseurl +"index.json")
.done(function(index) {
pagesIndex = index;
// Set up lunrjs by declaring the fields we use
// Also provide their boost level for the ranking
lunrIndex = new lunr.Index
lunrIndex.ref("uri");
lunrIndex.field('title', {
boost: 15
});
lunrIndex.field('tags', {
boost: 10
});
lunrIndex.field("content", {
boost: 5
});
// Feed lunr with each file and let lunr actually index them
pagesIndex.forEach(function(page) {
lunrIndex.add(page);
});
lunrIndex.pipeline.remove(lunrIndex.stemmer)
})
.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.error("Error getting Hugo index flie:", err);
});
} | [
"function",
"initLunr",
"(",
")",
"{",
"if",
"(",
"!",
"endsWith",
"(",
"baseurl",
",",
"\"/\"",
")",
")",
"{",
"baseurl",
"=",
"baseurl",
"+",
"'/'",
"}",
";",
"// First retrieve the index file",
"$",
".",
"getJSON",
"(",
"baseurl",
"+",
"\"index.json\"",
")",
".",
"done",
"(",
"function",
"(",
"index",
")",
"{",
"pagesIndex",
"=",
"index",
";",
"// Set up lunrjs by declaring the fields we use",
"// Also provide their boost level for the ranking",
"lunrIndex",
"=",
"new",
"lunr",
".",
"Index",
"lunrIndex",
".",
"ref",
"(",
"\"uri\"",
")",
";",
"lunrIndex",
".",
"field",
"(",
"'title'",
",",
"{",
"boost",
":",
"15",
"}",
")",
";",
"lunrIndex",
".",
"field",
"(",
"'tags'",
",",
"{",
"boost",
":",
"10",
"}",
")",
";",
"lunrIndex",
".",
"field",
"(",
"\"content\"",
",",
"{",
"boost",
":",
"5",
"}",
")",
";",
"// Feed lunr with each file and let lunr actually index them",
"pagesIndex",
".",
"forEach",
"(",
"function",
"(",
"page",
")",
"{",
"lunrIndex",
".",
"add",
"(",
"page",
")",
";",
"}",
")",
";",
"lunrIndex",
".",
"pipeline",
".",
"remove",
"(",
"lunrIndex",
".",
"stemmer",
")",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"jqxhr",
",",
"textStatus",
",",
"error",
")",
"{",
"var",
"err",
"=",
"textStatus",
"+",
"\", \"",
"+",
"error",
";",
"console",
".",
"error",
"(",
"\"Error getting Hugo index flie:\"",
",",
"err",
")",
";",
"}",
")",
";",
"}"
] | Initialize lunrjs using our generated index file | [
"Initialize",
"lunrjs",
"using",
"our",
"generated",
"index",
"file"
] | 975a16ae24bd214b608d0b0001d3d86e5cd65f9e | https://github.com/panjiesw/frest/blob/975a16ae24bd214b608d0b0001d3d86e5cd65f9e/internal/docs/themes/hugo-theme-learn/static/js/search.js#L8-L41 |
52,996 | panjiesw/frest | internal/docs/themes/hugo-theme-learn/static/js/search.js | search | function search(query) {
// Find the item in our index corresponding to the lunr one to have more info
return lunrIndex.search(query).map(function(result) {
return pagesIndex.filter(function(page) {
return page.uri === result.ref;
})[0];
});
} | javascript | function search(query) {
// Find the item in our index corresponding to the lunr one to have more info
return lunrIndex.search(query).map(function(result) {
return pagesIndex.filter(function(page) {
return page.uri === result.ref;
})[0];
});
} | [
"function",
"search",
"(",
"query",
")",
"{",
"// Find the item in our index corresponding to the lunr one to have more info",
"return",
"lunrIndex",
".",
"search",
"(",
"query",
")",
".",
"map",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"pagesIndex",
".",
"filter",
"(",
"function",
"(",
"page",
")",
"{",
"return",
"page",
".",
"uri",
"===",
"result",
".",
"ref",
";",
"}",
")",
"[",
"0",
"]",
";",
"}",
")",
";",
"}"
] | Trigger a search in lunr and transform the result
@param {String} query
@return {Array} results | [
"Trigger",
"a",
"search",
"in",
"lunr",
"and",
"transform",
"the",
"result"
] | 975a16ae24bd214b608d0b0001d3d86e5cd65f9e | https://github.com/panjiesw/frest/blob/975a16ae24bd214b608d0b0001d3d86e5cd65f9e/internal/docs/themes/hugo-theme-learn/static/js/search.js#L49-L56 |
52,997 | gethuman/pancakes-recipe | middleware/mw.tasks.js | init | function init(ctx) {
_.each(resources, function (resource) {
_.each(resource.tasks, function (taskInfo, taskName) {
taskInfo.name = taskName;
taskInfo.service = pancakes.getService(resource.name);
taskHandlers[taskName] = taskInfo;
});
});
return new Q(ctx);
} | javascript | function init(ctx) {
_.each(resources, function (resource) {
_.each(resource.tasks, function (taskInfo, taskName) {
taskInfo.name = taskName;
taskInfo.service = pancakes.getService(resource.name);
taskHandlers[taskName] = taskInfo;
});
});
return new Q(ctx);
} | [
"function",
"init",
"(",
"ctx",
")",
"{",
"_",
".",
"each",
"(",
"resources",
",",
"function",
"(",
"resource",
")",
"{",
"_",
".",
"each",
"(",
"resource",
".",
"tasks",
",",
"function",
"(",
"taskInfo",
",",
"taskName",
")",
"{",
"taskInfo",
".",
"name",
"=",
"taskName",
";",
"taskInfo",
".",
"service",
"=",
"pancakes",
".",
"getService",
"(",
"resource",
".",
"name",
")",
";",
"taskHandlers",
"[",
"taskName",
"]",
"=",
"taskInfo",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"new",
"Q",
"(",
"ctx",
")",
";",
"}"
] | Initialize a local variable that holds the config values for the task
handlers
@param ctx | [
"Initialize",
"a",
"local",
"variable",
"that",
"holds",
"the",
"config",
"values",
"for",
"the",
"task",
"handlers"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.tasks.js#L15-L25 |
52,998 | gethuman/pancakes-recipe | middleware/mw.tasks.js | isTaskHandled | function isTaskHandled(request, reply) {
var taskName = request.query.task;
// if no task or task handler, don't do anything
if (!taskName && !taskHandlers[taskName]) { return false; }
// if task info doesn't have service or method, don't do anything
var taskInfo = taskHandlers[taskName];
if (!taskInfo || !taskInfo.service || !taskInfo.method || !taskInfo.service[taskInfo.method]) {
return false;
}
// if user is not logged in redirect to login then back to here
if (!request.caller || !request.caller.user) {
var currentUrl = request.url.pathname;
var loginUrl = currentUrl + '?modal=auth&submodal=login&redirect=' + currentUrl;
reply().redirect(loginUrl);
return true;
}
// start collecting the service request
var serviceReq = { caller: request.caller };
// get the values from the request object to put into the service request
_.each(taskInfo.params, function (param) {
if (request.query[param]) {
serviceReq[param] = request.query[param];
}
});
// call the service method
taskInfo.service[taskInfo.method](serviceReq)
.then(function () {
reply().redirect(request.path + '?notify=' + taskInfo.notifySuccess);
})
.catch(function (err) {
log.error(err);
reply().redirect(request.path + '?notify=' + taskInfo.notifyFailure);
});
return true;
} | javascript | function isTaskHandled(request, reply) {
var taskName = request.query.task;
// if no task or task handler, don't do anything
if (!taskName && !taskHandlers[taskName]) { return false; }
// if task info doesn't have service or method, don't do anything
var taskInfo = taskHandlers[taskName];
if (!taskInfo || !taskInfo.service || !taskInfo.method || !taskInfo.service[taskInfo.method]) {
return false;
}
// if user is not logged in redirect to login then back to here
if (!request.caller || !request.caller.user) {
var currentUrl = request.url.pathname;
var loginUrl = currentUrl + '?modal=auth&submodal=login&redirect=' + currentUrl;
reply().redirect(loginUrl);
return true;
}
// start collecting the service request
var serviceReq = { caller: request.caller };
// get the values from the request object to put into the service request
_.each(taskInfo.params, function (param) {
if (request.query[param]) {
serviceReq[param] = request.query[param];
}
});
// call the service method
taskInfo.service[taskInfo.method](serviceReq)
.then(function () {
reply().redirect(request.path + '?notify=' + taskInfo.notifySuccess);
})
.catch(function (err) {
log.error(err);
reply().redirect(request.path + '?notify=' + taskInfo.notifyFailure);
});
return true;
} | [
"function",
"isTaskHandled",
"(",
"request",
",",
"reply",
")",
"{",
"var",
"taskName",
"=",
"request",
".",
"query",
".",
"task",
";",
"// if no task or task handler, don't do anything",
"if",
"(",
"!",
"taskName",
"&&",
"!",
"taskHandlers",
"[",
"taskName",
"]",
")",
"{",
"return",
"false",
";",
"}",
"// if task info doesn't have service or method, don't do anything",
"var",
"taskInfo",
"=",
"taskHandlers",
"[",
"taskName",
"]",
";",
"if",
"(",
"!",
"taskInfo",
"||",
"!",
"taskInfo",
".",
"service",
"||",
"!",
"taskInfo",
".",
"method",
"||",
"!",
"taskInfo",
".",
"service",
"[",
"taskInfo",
".",
"method",
"]",
")",
"{",
"return",
"false",
";",
"}",
"// if user is not logged in redirect to login then back to here",
"if",
"(",
"!",
"request",
".",
"caller",
"||",
"!",
"request",
".",
"caller",
".",
"user",
")",
"{",
"var",
"currentUrl",
"=",
"request",
".",
"url",
".",
"pathname",
";",
"var",
"loginUrl",
"=",
"currentUrl",
"+",
"'?modal=auth&submodal=login&redirect='",
"+",
"currentUrl",
";",
"reply",
"(",
")",
".",
"redirect",
"(",
"loginUrl",
")",
";",
"return",
"true",
";",
"}",
"// start collecting the service request",
"var",
"serviceReq",
"=",
"{",
"caller",
":",
"request",
".",
"caller",
"}",
";",
"// get the values from the request object to put into the service request",
"_",
".",
"each",
"(",
"taskInfo",
".",
"params",
",",
"function",
"(",
"param",
")",
"{",
"if",
"(",
"request",
".",
"query",
"[",
"param",
"]",
")",
"{",
"serviceReq",
"[",
"param",
"]",
"=",
"request",
".",
"query",
"[",
"param",
"]",
";",
"}",
"}",
")",
";",
"// call the service method",
"taskInfo",
".",
"service",
"[",
"taskInfo",
".",
"method",
"]",
"(",
"serviceReq",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"reply",
"(",
")",
".",
"redirect",
"(",
"request",
".",
"path",
"+",
"'?notify='",
"+",
"taskInfo",
".",
"notifySuccess",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"err",
")",
";",
"reply",
"(",
")",
".",
"redirect",
"(",
"request",
".",
"path",
"+",
"'?notify='",
"+",
"taskInfo",
".",
"notifyFailure",
")",
";",
"}",
")",
";",
"return",
"true",
";",
"}"
] | Handle one particular task
@param request
@param reply | [
"Handle",
"one",
"particular",
"task"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.tasks.js#L32-L73 |
52,999 | HenriJ/careless | vendor/browser-transforms.js | transformReact | function transformReact(source, options) {
// TODO: just use react-tools
options = options || {};
var visitorList;
if (options.harmony) {
visitorList = visitors.getAllVisitors();
} else {
visitorList = visitors.transformVisitors.react;
}
if (options.stripTypes) {
// Stripping types needs to happen before the other transforms
// unfortunately, due to bad interactions. For example,
// es6-rest-param-visitors conflict with stripping rest param type
// annotation
source = transform(typesSyntax.visitorList, source, options).code;
}
return transform(visitorList, source, {
sourceMap: supportsAccessors && options.sourceMap
});
} | javascript | function transformReact(source, options) {
// TODO: just use react-tools
options = options || {};
var visitorList;
if (options.harmony) {
visitorList = visitors.getAllVisitors();
} else {
visitorList = visitors.transformVisitors.react;
}
if (options.stripTypes) {
// Stripping types needs to happen before the other transforms
// unfortunately, due to bad interactions. For example,
// es6-rest-param-visitors conflict with stripping rest param type
// annotation
source = transform(typesSyntax.visitorList, source, options).code;
}
return transform(visitorList, source, {
sourceMap: supportsAccessors && options.sourceMap
});
} | [
"function",
"transformReact",
"(",
"source",
",",
"options",
")",
"{",
"// TODO: just use react-tools",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"visitorList",
";",
"if",
"(",
"options",
".",
"harmony",
")",
"{",
"visitorList",
"=",
"visitors",
".",
"getAllVisitors",
"(",
")",
";",
"}",
"else",
"{",
"visitorList",
"=",
"visitors",
".",
"transformVisitors",
".",
"react",
";",
"}",
"if",
"(",
"options",
".",
"stripTypes",
")",
"{",
"// Stripping types needs to happen before the other transforms",
"// unfortunately, due to bad interactions. For example,",
"// es6-rest-param-visitors conflict with stripping rest param type",
"// annotation",
"source",
"=",
"transform",
"(",
"typesSyntax",
".",
"visitorList",
",",
"source",
",",
"options",
")",
".",
"code",
";",
"}",
"return",
"transform",
"(",
"visitorList",
",",
"source",
",",
"{",
"sourceMap",
":",
"supportsAccessors",
"&&",
"options",
".",
"sourceMap",
"}",
")",
";",
"}"
] | Run provided code through jstransform.
@param {string} source Original source code
@param {object?} options Options to pass to jstransform
@return {object} object as returned from jstransform | [
"Run",
"provided",
"code",
"through",
"jstransform",
"."
] | 7dea2384b412bf2a03e111dae22055dd9bdf95fe | https://github.com/HenriJ/careless/blob/7dea2384b412bf2a03e111dae22055dd9bdf95fe/vendor/browser-transforms.js#L36-L57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.