repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
back4app/back4app-entity | src/back/models/attributes/Attribute.js | getDataName | function getDataName(adapterName) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when getting the data name of an Attribute ' +
'(it has to be passed less than 2 arguments)');
if (adapterName) {
expect(adapterName).to.be.a(
'string',
'Invalid argument "adapterName" when getting the data name of an ' +
'Attribute (it has to be a string)'
);
if (
this.dataName &&
typeof this.dataName === 'object' &&
this.dataName.hasOwnProperty(adapterName)
) {
return this.dataName[adapterName];
}
}
if (this.dataName && typeof this.dataName === 'string') {
return this.dataName;
} else {
return this.name;
}
} | javascript | function getDataName(adapterName) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when getting the data name of an Attribute ' +
'(it has to be passed less than 2 arguments)');
if (adapterName) {
expect(adapterName).to.be.a(
'string',
'Invalid argument "adapterName" when getting the data name of an ' +
'Attribute (it has to be a string)'
);
if (
this.dataName &&
typeof this.dataName === 'object' &&
this.dataName.hasOwnProperty(adapterName)
) {
return this.dataName[adapterName];
}
}
if (this.dataName && typeof this.dataName === 'string') {
return this.dataName;
} else {
return this.name;
}
} | [
"function",
"getDataName",
"(",
"adapterName",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"below",
"(",
"2",
",",
"'Invalid arguments length when getting the data name of an Attribute '",
"+",
"'(it has to be passed less than 2 arguments)'",
")",
";",
"if",
"(",
"adapterName",
")",
"{",
"expect",
"(",
"adapterName",
")",
".",
"to",
".",
"be",
".",
"a",
"(",
"'string'",
",",
"'Invalid argument \"adapterName\" when getting the data name of an '",
"+",
"'Attribute (it has to be a string)'",
")",
";",
"if",
"(",
"this",
".",
"dataName",
"&&",
"typeof",
"this",
".",
"dataName",
"===",
"'object'",
"&&",
"this",
".",
"dataName",
".",
"hasOwnProperty",
"(",
"adapterName",
")",
")",
"{",
"return",
"this",
".",
"dataName",
"[",
"adapterName",
"]",
";",
"}",
"}",
"if",
"(",
"this",
".",
"dataName",
"&&",
"typeof",
"this",
".",
"dataName",
"===",
"'string'",
")",
"{",
"return",
"this",
".",
"dataName",
";",
"}",
"else",
"{",
"return",
"this",
".",
"name",
";",
"}",
"}"
] | Gets the data name of an Entity attribute to be used in an adapter.
@name module:back4app-entity/models/attributes.Attribute#getDataName
@function
@param {?string} [adapterName] The name of the adapter of which the data
name is wanted.
@returns {string} The data name.
@example
var dataName = MyEntity.attributes.myAttribute.getDataName('default'); | [
"Gets",
"the",
"data",
"name",
"of",
"an",
"Entity",
"attribute",
"to",
"be",
"used",
"in",
"an",
"adapter",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/Attribute.js#L694-L721 | train |
feedhenry/fh-forms | lib/impl/submissionExportHelper/csvValues.js | generateCSVSingleValue | function generateCSVSingleValue(field, val, downloadUrl, submissionId) {
var line = '';
var fieldValue = val;
if (!(typeof (fieldValue) === 'undefined' || fieldValue === null)) {
//Value is something, add the value
if (field.type === 'checkboxes') {
fieldValue = val.selections;
} else if (fieldTypeUtils.isFileType(field.type)) {
//File types have two fields, a name and url to be added
if (val.fileName) {
fieldValue = val.fileName;
} else {
fieldValue = '<not uploaded>';
}
} else if (fieldTypeUtils.isBarcodeType(field.type)) {
if (val.format) {
fieldValue = val.format;
} else {
fieldValue = "<not set>";
}
}
line += csvStr(fieldValue);
line += ',';
//If it is a file type, then the url should also be added
if (fieldTypeUtils.isFileType(field.type)) {
if (val.groupId) {
fieldValue = downloadUrl.replace(":id", submissionId).replace(":fileId", val
.groupId);
} else {
fieldValue = '<not uploaded>';
}
line += csvStr(fieldValue);
line += ',';
} else if (fieldTypeUtils.isBarcodeType(field.type)) {
if (val.text) {
fieldValue = val.text;
} else {
fieldValue = "<not set>";
}
line += csvStr(fieldValue);
line += ',';
}
} else {
//No value, spacers have to be added.
//For file type, the file name and url are included. Therefore blank values have to be spaced twice.
if (fieldTypeUtils.isFileType(field.type) || fieldTypeUtils.isBarcodeType(
field.type)) {
line += ',,';
} else {
line += ',';
}
}
return line;
} | javascript | function generateCSVSingleValue(field, val, downloadUrl, submissionId) {
var line = '';
var fieldValue = val;
if (!(typeof (fieldValue) === 'undefined' || fieldValue === null)) {
//Value is something, add the value
if (field.type === 'checkboxes') {
fieldValue = val.selections;
} else if (fieldTypeUtils.isFileType(field.type)) {
//File types have two fields, a name and url to be added
if (val.fileName) {
fieldValue = val.fileName;
} else {
fieldValue = '<not uploaded>';
}
} else if (fieldTypeUtils.isBarcodeType(field.type)) {
if (val.format) {
fieldValue = val.format;
} else {
fieldValue = "<not set>";
}
}
line += csvStr(fieldValue);
line += ',';
//If it is a file type, then the url should also be added
if (fieldTypeUtils.isFileType(field.type)) {
if (val.groupId) {
fieldValue = downloadUrl.replace(":id", submissionId).replace(":fileId", val
.groupId);
} else {
fieldValue = '<not uploaded>';
}
line += csvStr(fieldValue);
line += ',';
} else if (fieldTypeUtils.isBarcodeType(field.type)) {
if (val.text) {
fieldValue = val.text;
} else {
fieldValue = "<not set>";
}
line += csvStr(fieldValue);
line += ',';
}
} else {
//No value, spacers have to be added.
//For file type, the file name and url are included. Therefore blank values have to be spaced twice.
if (fieldTypeUtils.isFileType(field.type) || fieldTypeUtils.isBarcodeType(
field.type)) {
line += ',,';
} else {
line += ',';
}
}
return line;
} | [
"function",
"generateCSVSingleValue",
"(",
"field",
",",
"val",
",",
"downloadUrl",
",",
"submissionId",
")",
"{",
"var",
"line",
"=",
"''",
";",
"var",
"fieldValue",
"=",
"val",
";",
"if",
"(",
"!",
"(",
"typeof",
"(",
"fieldValue",
")",
"===",
"'undefined'",
"||",
"fieldValue",
"===",
"null",
")",
")",
"{",
"if",
"(",
"field",
".",
"type",
"===",
"'checkboxes'",
")",
"{",
"fieldValue",
"=",
"val",
".",
"selections",
";",
"}",
"else",
"if",
"(",
"fieldTypeUtils",
".",
"isFileType",
"(",
"field",
".",
"type",
")",
")",
"{",
"if",
"(",
"val",
".",
"fileName",
")",
"{",
"fieldValue",
"=",
"val",
".",
"fileName",
";",
"}",
"else",
"{",
"fieldValue",
"=",
"'<not uploaded>'",
";",
"}",
"}",
"else",
"if",
"(",
"fieldTypeUtils",
".",
"isBarcodeType",
"(",
"field",
".",
"type",
")",
")",
"{",
"if",
"(",
"val",
".",
"format",
")",
"{",
"fieldValue",
"=",
"val",
".",
"format",
";",
"}",
"else",
"{",
"fieldValue",
"=",
"\"<not set>\"",
";",
"}",
"}",
"line",
"+=",
"csvStr",
"(",
"fieldValue",
")",
";",
"line",
"+=",
"','",
";",
"if",
"(",
"fieldTypeUtils",
".",
"isFileType",
"(",
"field",
".",
"type",
")",
")",
"{",
"if",
"(",
"val",
".",
"groupId",
")",
"{",
"fieldValue",
"=",
"downloadUrl",
".",
"replace",
"(",
"\":id\"",
",",
"submissionId",
")",
".",
"replace",
"(",
"\":fileId\"",
",",
"val",
".",
"groupId",
")",
";",
"}",
"else",
"{",
"fieldValue",
"=",
"'<not uploaded>'",
";",
"}",
"line",
"+=",
"csvStr",
"(",
"fieldValue",
")",
";",
"line",
"+=",
"','",
";",
"}",
"else",
"if",
"(",
"fieldTypeUtils",
".",
"isBarcodeType",
"(",
"field",
".",
"type",
")",
")",
"{",
"if",
"(",
"val",
".",
"text",
")",
"{",
"fieldValue",
"=",
"val",
".",
"text",
";",
"}",
"else",
"{",
"fieldValue",
"=",
"\"<not set>\"",
";",
"}",
"line",
"+=",
"csvStr",
"(",
"fieldValue",
")",
";",
"line",
"+=",
"','",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"fieldTypeUtils",
".",
"isFileType",
"(",
"field",
".",
"type",
")",
"||",
"fieldTypeUtils",
".",
"isBarcodeType",
"(",
"field",
".",
"type",
")",
")",
"{",
"line",
"+=",
"',,'",
";",
"}",
"else",
"{",
"line",
"+=",
"','",
";",
"}",
"}",
"return",
"line",
";",
"}"
] | generateCSVSingleValue - Generating A Single Value For A Field
@param {object} field Field Definition To Generate A CSV For
@param {object/string/number} val Field Value
@param {string} downloadUrl URL template for downloading files
@param {object} submissionId Submission ID
@return {type} description | [
"generateCSVSingleValue",
"-",
"Generating",
"A",
"Single",
"Value",
"For",
"A",
"Field"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvValues.js#L14-L72 | train |
feedhenry/fh-forms | lib/impl/submissionExportHelper/csvValues.js | generateCSVFieldValues | function generateCSVFieldValues(baseField, ff, downloadUrl, sub) {
var line = '';
var fieldValues = [];
if (ff) {
fieldValues = misc.filterOutNullData(ff.fieldValues);
}
if (baseField && baseField.repeating) {
for (var j = 0; j < baseField.fieldOptions.definition.maxRepeat; j++) {
line += generateCSVSingleValue(baseField, fieldValues[j], downloadUrl, sub._id);
}
} else {
line += generateCSVSingleValue(baseField, fieldValues[0], downloadUrl, sub._id);
}
return line;
} | javascript | function generateCSVFieldValues(baseField, ff, downloadUrl, sub) {
var line = '';
var fieldValues = [];
if (ff) {
fieldValues = misc.filterOutNullData(ff.fieldValues);
}
if (baseField && baseField.repeating) {
for (var j = 0; j < baseField.fieldOptions.definition.maxRepeat; j++) {
line += generateCSVSingleValue(baseField, fieldValues[j], downloadUrl, sub._id);
}
} else {
line += generateCSVSingleValue(baseField, fieldValues[0], downloadUrl, sub._id);
}
return line;
} | [
"function",
"generateCSVFieldValues",
"(",
"baseField",
",",
"ff",
",",
"downloadUrl",
",",
"sub",
")",
"{",
"var",
"line",
"=",
"''",
";",
"var",
"fieldValues",
"=",
"[",
"]",
";",
"if",
"(",
"ff",
")",
"{",
"fieldValues",
"=",
"misc",
".",
"filterOutNullData",
"(",
"ff",
".",
"fieldValues",
")",
";",
"}",
"if",
"(",
"baseField",
"&&",
"baseField",
".",
"repeating",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"baseField",
".",
"fieldOptions",
".",
"definition",
".",
"maxRepeat",
";",
"j",
"++",
")",
"{",
"line",
"+=",
"generateCSVSingleValue",
"(",
"baseField",
",",
"fieldValues",
"[",
"j",
"]",
",",
"downloadUrl",
",",
"sub",
".",
"_id",
")",
";",
"}",
"}",
"else",
"{",
"line",
"+=",
"generateCSVSingleValue",
"(",
"baseField",
",",
"fieldValues",
"[",
"0",
"]",
",",
"downloadUrl",
",",
"sub",
".",
"_id",
")",
";",
"}",
"return",
"line",
";",
"}"
] | generateCSVFieldValues - description
@param {type} baseField description
@param {type} ff description
@param {type} downloadUrl description
@param {type} sub description
@return {type} description | [
"generateCSVFieldValues",
"-",
"description"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvValues.js#L83-L100 | train |
feedhenry/fh-forms | lib/impl/importForms/index.js | checkWorkingDir | function checkWorkingDir(workingDir, cb) {
fs.stat(workingDir, function(err, stats) {
var errMessage;
if (err) {
errMessage = "The directory " + workingDir + " does not exist.";
logger.error(errMessage);
return cb(errMessage);
}
//Checking that it is a directory
if (!stats.isDirectory()) {
errMessage = "Expected " + workingDir + " to be a directory";
logger.error(errMessage);
return cb(errMessage);
}
return cb();
});
} | javascript | function checkWorkingDir(workingDir, cb) {
fs.stat(workingDir, function(err, stats) {
var errMessage;
if (err) {
errMessage = "The directory " + workingDir + " does not exist.";
logger.error(errMessage);
return cb(errMessage);
}
//Checking that it is a directory
if (!stats.isDirectory()) {
errMessage = "Expected " + workingDir + " to be a directory";
logger.error(errMessage);
return cb(errMessage);
}
return cb();
});
} | [
"function",
"checkWorkingDir",
"(",
"workingDir",
",",
"cb",
")",
"{",
"fs",
".",
"stat",
"(",
"workingDir",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"var",
"errMessage",
";",
"if",
"(",
"err",
")",
"{",
"errMessage",
"=",
"\"The directory \"",
"+",
"workingDir",
"+",
"\" does not exist.\"",
";",
"logger",
".",
"error",
"(",
"errMessage",
")",
";",
"return",
"cb",
"(",
"errMessage",
")",
";",
"}",
"if",
"(",
"!",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"errMessage",
"=",
"\"Expected \"",
"+",
"workingDir",
"+",
"\" to be a directory\"",
";",
"logger",
".",
"error",
"(",
"errMessage",
")",
";",
"return",
"cb",
"(",
"errMessage",
")",
";",
"}",
"return",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
] | checkWorkingDir - Checking that the working directory exists and is a directory.
@param {string} workingDir Path to the working directory
@param {function} cb | [
"checkWorkingDir",
"-",
"Checking",
"that",
"the",
"working",
"directory",
"exists",
"and",
"is",
"a",
"directory",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/index.js#L43-L61 | train |
feedhenry/fh-forms | lib/impl/importForms/index.js | checkZipFile | function checkZipFile(zipFilePath, cb) {
//Checking that it is a ZIP file
mimeInspector.detectFile(zipFilePath, function(err, fileMimetype) {
var errMessage;
if (err) {
logger.error("Error detecting ZIP file", err);
return cb(err);
}
if (fileMimetype !== 'application/zip') {
errMessage = "Expected the file MIME type to be application/zip but was " + fileMimetype;
logger.error(errMessage);
}
return cb(errMessage);
});
} | javascript | function checkZipFile(zipFilePath, cb) {
//Checking that it is a ZIP file
mimeInspector.detectFile(zipFilePath, function(err, fileMimetype) {
var errMessage;
if (err) {
logger.error("Error detecting ZIP file", err);
return cb(err);
}
if (fileMimetype !== 'application/zip') {
errMessage = "Expected the file MIME type to be application/zip but was " + fileMimetype;
logger.error(errMessage);
}
return cb(errMessage);
});
} | [
"function",
"checkZipFile",
"(",
"zipFilePath",
",",
"cb",
")",
"{",
"mimeInspector",
".",
"detectFile",
"(",
"zipFilePath",
",",
"function",
"(",
"err",
",",
"fileMimetype",
")",
"{",
"var",
"errMessage",
";",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error detecting ZIP file\"",
",",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"if",
"(",
"fileMimetype",
"!==",
"'application/zip'",
")",
"{",
"errMessage",
"=",
"\"Expected the file MIME type to be application/zip but was \"",
"+",
"fileMimetype",
";",
"logger",
".",
"error",
"(",
"errMessage",
")",
";",
"}",
"return",
"cb",
"(",
"errMessage",
")",
";",
"}",
")",
";",
"}"
] | checkZipFile - Checking that the file exists and is a zip file.
@param {string} zipFilePath Path to the zip file.
@param {function} cb description | [
"checkZipFile",
"-",
"Checking",
"that",
"the",
"file",
"exists",
"and",
"is",
"a",
"zip",
"file",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/index.js#L70-L86 | train |
feedhenry/fh-forms | lib/impl/importForms/index.js | importForms | function importForms(connections, params, callback) {
params = params || {};
logger.debug("Importing Forms ", params);
//Validating
var paramsValidator = validate(params);
var failed = paramsValidator.has(ZIP_FILE_PATH, WORKING_DIR);
if (failed) {
return callback("Validation Failed " + (failed[ZIP_FILE_PATH] || failed[WORKING_DIR]));
}
//Random directory name.
var newDirectoryName = (new mongoose.Types.ObjectId()).toString();
var unzipDirectoryPath = path.join(params.workingDir, "/", newDirectoryName);
async.waterfall([
function checkFiles(cb) {
async.parallel([
async.apply(checkWorkingDir, params.workingDir),
async.apply(checkZipFile, params.zipFilePath)
], function(err) {
//Not interested in passing any of the results from the aync.parallel to the waterfall callback
cb(err);
});
},
function createUniqueDirToUnzipTo(cb) {
//Need to create a new directory
mkdirp(unzipDirectoryPath, function(err) {
return cb(err);
});
},
async.apply(unzipFile, {
zipFilePath: params.zipFilePath,
workingDir: unzipDirectoryPath,
queueConcurrency: 5
}),
function validateInput(cb) {
inputValidator(unzipDirectoryPath, true, cb);
},
async.apply(importFromDir, connections, unzipDirectoryPath)
], function(err, importedForms) {
if (err) {
logger.error("Error Importing Forms ", err);
}
//we always need to cleanup
cleanupFiles(unzipDirectoryPath, params.zipFilePath);
return callback(err, importedForms);
});
} | javascript | function importForms(connections, params, callback) {
params = params || {};
logger.debug("Importing Forms ", params);
//Validating
var paramsValidator = validate(params);
var failed = paramsValidator.has(ZIP_FILE_PATH, WORKING_DIR);
if (failed) {
return callback("Validation Failed " + (failed[ZIP_FILE_PATH] || failed[WORKING_DIR]));
}
//Random directory name.
var newDirectoryName = (new mongoose.Types.ObjectId()).toString();
var unzipDirectoryPath = path.join(params.workingDir, "/", newDirectoryName);
async.waterfall([
function checkFiles(cb) {
async.parallel([
async.apply(checkWorkingDir, params.workingDir),
async.apply(checkZipFile, params.zipFilePath)
], function(err) {
//Not interested in passing any of the results from the aync.parallel to the waterfall callback
cb(err);
});
},
function createUniqueDirToUnzipTo(cb) {
//Need to create a new directory
mkdirp(unzipDirectoryPath, function(err) {
return cb(err);
});
},
async.apply(unzipFile, {
zipFilePath: params.zipFilePath,
workingDir: unzipDirectoryPath,
queueConcurrency: 5
}),
function validateInput(cb) {
inputValidator(unzipDirectoryPath, true, cb);
},
async.apply(importFromDir, connections, unzipDirectoryPath)
], function(err, importedForms) {
if (err) {
logger.error("Error Importing Forms ", err);
}
//we always need to cleanup
cleanupFiles(unzipDirectoryPath, params.zipFilePath);
return callback(err, importedForms);
});
} | [
"function",
"importForms",
"(",
"connections",
",",
"params",
",",
"callback",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Importing Forms \"",
",",
"params",
")",
";",
"var",
"paramsValidator",
"=",
"validate",
"(",
"params",
")",
";",
"var",
"failed",
"=",
"paramsValidator",
".",
"has",
"(",
"ZIP_FILE_PATH",
",",
"WORKING_DIR",
")",
";",
"if",
"(",
"failed",
")",
"{",
"return",
"callback",
"(",
"\"Validation Failed \"",
"+",
"(",
"failed",
"[",
"ZIP_FILE_PATH",
"]",
"||",
"failed",
"[",
"WORKING_DIR",
"]",
")",
")",
";",
"}",
"var",
"newDirectoryName",
"=",
"(",
"new",
"mongoose",
".",
"Types",
".",
"ObjectId",
"(",
")",
")",
".",
"toString",
"(",
")",
";",
"var",
"unzipDirectoryPath",
"=",
"path",
".",
"join",
"(",
"params",
".",
"workingDir",
",",
"\"/\"",
",",
"newDirectoryName",
")",
";",
"async",
".",
"waterfall",
"(",
"[",
"function",
"checkFiles",
"(",
"cb",
")",
"{",
"async",
".",
"parallel",
"(",
"[",
"async",
".",
"apply",
"(",
"checkWorkingDir",
",",
"params",
".",
"workingDir",
")",
",",
"async",
".",
"apply",
"(",
"checkZipFile",
",",
"params",
".",
"zipFilePath",
")",
"]",
",",
"function",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"createUniqueDirToUnzipTo",
"(",
"cb",
")",
"{",
"mkdirp",
"(",
"unzipDirectoryPath",
",",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"async",
".",
"apply",
"(",
"unzipFile",
",",
"{",
"zipFilePath",
":",
"params",
".",
"zipFilePath",
",",
"workingDir",
":",
"unzipDirectoryPath",
",",
"queueConcurrency",
":",
"5",
"}",
")",
",",
"function",
"validateInput",
"(",
"cb",
")",
"{",
"inputValidator",
"(",
"unzipDirectoryPath",
",",
"true",
",",
"cb",
")",
";",
"}",
",",
"async",
".",
"apply",
"(",
"importFromDir",
",",
"connections",
",",
"unzipDirectoryPath",
")",
"]",
",",
"function",
"(",
"err",
",",
"importedForms",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error Importing Forms \"",
",",
"err",
")",
";",
"}",
"cleanupFiles",
"(",
"unzipDirectoryPath",
",",
"params",
".",
"zipFilePath",
")",
";",
"return",
"callback",
"(",
"err",
",",
"importedForms",
")",
";",
"}",
")",
";",
"}"
] | importForms - Importing Form Definitions From A ZIP File.
The ZIP file will be unzipped to a working directory where the forms will be imported from.
@param {object} connections
@param {object} connections.mongooseConnection The Mongoose Connection
@param {object} params
@param {string} params.zipFilePath A Path to a ZIP file on the file system.
@param {string} params.workingDir A Path to a directory where the zip file can be unzipped to.
@param {function} callback
@return {type} | [
"importForms",
"-",
"Importing",
"Form",
"Definitions",
"From",
"A",
"ZIP",
"File",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/index.js#L102-L153 | train |
feedhenry/fh-forms | lib/impl/importForms/unzipFile.js | makeExportDirectory | function makeExportDirectory(params, callback) {
var newDirPath = params.workingDir + "/" + params.entry.fileName;
mkdirp(newDirPath, function(err) {
if (err) {
logger.debug("Error making directory " + newDirPath, err);
return callback(err);
}
params.zipfile.readEntry();
return callback(err);
});
} | javascript | function makeExportDirectory(params, callback) {
var newDirPath = params.workingDir + "/" + params.entry.fileName;
mkdirp(newDirPath, function(err) {
if (err) {
logger.debug("Error making directory " + newDirPath, err);
return callback(err);
}
params.zipfile.readEntry();
return callback(err);
});
} | [
"function",
"makeExportDirectory",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"newDirPath",
"=",
"params",
".",
"workingDir",
"+",
"\"/\"",
"+",
"params",
".",
"entry",
".",
"fileName",
";",
"mkdirp",
"(",
"newDirPath",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Error making directory \"",
"+",
"newDirPath",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"params",
".",
"zipfile",
".",
"readEntry",
"(",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] | makeExportDirectory - Making a directory in the same structure as the zip file.
@param {object} params
@param {object} params.entry Single Zip file entry
@param {object} params.zipfile Reference To THe Parent Zip File.
@param {string} params.workingDir Directory being unzipped into.
@param {function} callback | [
"makeExportDirectory",
"-",
"Making",
"a",
"directory",
"in",
"the",
"same",
"structure",
"as",
"the",
"zip",
"file",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L18-L28 | train |
feedhenry/fh-forms | lib/impl/importForms/unzipFile.js | streamFileEntry | function streamFileEntry(params, callback) {
params.zipfile.openReadStream(params.entry, function(err, readStream) {
if (err) {
return callback(err);
}
// ensure parent directory exists
var newFilePath = params.workingDir + "/" + params.entry.fileName;
mkdirp(path.dirname(newFilePath), function(err) {
if (err) {
logger.debug("Error making directory " + newFilePath, err);
return callback(err);
}
readStream.pipe(fs.createWriteStream(newFilePath));
readStream.on("end", function() {
params.zipfile.readEntry();
callback();
});
readStream.on('error', function(err) {
callback(err);
});
});
});
} | javascript | function streamFileEntry(params, callback) {
params.zipfile.openReadStream(params.entry, function(err, readStream) {
if (err) {
return callback(err);
}
// ensure parent directory exists
var newFilePath = params.workingDir + "/" + params.entry.fileName;
mkdirp(path.dirname(newFilePath), function(err) {
if (err) {
logger.debug("Error making directory " + newFilePath, err);
return callback(err);
}
readStream.pipe(fs.createWriteStream(newFilePath));
readStream.on("end", function() {
params.zipfile.readEntry();
callback();
});
readStream.on('error', function(err) {
callback(err);
});
});
});
} | [
"function",
"streamFileEntry",
"(",
"params",
",",
"callback",
")",
"{",
"params",
".",
"zipfile",
".",
"openReadStream",
"(",
"params",
".",
"entry",
",",
"function",
"(",
"err",
",",
"readStream",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"newFilePath",
"=",
"params",
".",
"workingDir",
"+",
"\"/\"",
"+",
"params",
".",
"entry",
".",
"fileName",
";",
"mkdirp",
"(",
"path",
".",
"dirname",
"(",
"newFilePath",
")",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Error making directory \"",
"+",
"newFilePath",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"readStream",
".",
"pipe",
"(",
"fs",
".",
"createWriteStream",
"(",
"newFilePath",
")",
")",
";",
"readStream",
".",
"on",
"(",
"\"end\"",
",",
"function",
"(",
")",
"{",
"params",
".",
"zipfile",
".",
"readEntry",
"(",
")",
";",
"callback",
"(",
")",
";",
"}",
")",
";",
"readStream",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | streamFileEntry - Streaming a single uncompressed file from the zip file to the working folder.
The folder structure of the zip file is maintained.
@param {object} params
@param {object} params.zipfile Reference to the parent zip file
@param {object} params.entry Single Zip file entry
@param {string} params.workingDir Directory being unzipped into.
@param {function} callback
@return {type} description | [
"streamFileEntry",
"-",
"Streaming",
"a",
"single",
"uncompressed",
"file",
"from",
"the",
"zip",
"file",
"to",
"the",
"working",
"folder",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L43-L65 | train |
feedhenry/fh-forms | lib/impl/importForms/unzipFile.js | unzipWorker | function unzipWorker(unzipTask, workerCb) {
var zipfile = unzipTask.zipfile;
var entry = unzipTask.entry;
var workingDir = unzipTask.workingDir;
if (/\/$/.test(entry.fileName)) {
// directory file names end with '/'
makeExportDirectory({
entry: entry,
zipfile: zipfile,
workingDir: workingDir
}, workerCb);
} else {
// file entry
streamFileEntry({
zipfile: zipfile,
entry: entry,
workingDir: workingDir
}, workerCb);
}
} | javascript | function unzipWorker(unzipTask, workerCb) {
var zipfile = unzipTask.zipfile;
var entry = unzipTask.entry;
var workingDir = unzipTask.workingDir;
if (/\/$/.test(entry.fileName)) {
// directory file names end with '/'
makeExportDirectory({
entry: entry,
zipfile: zipfile,
workingDir: workingDir
}, workerCb);
} else {
// file entry
streamFileEntry({
zipfile: zipfile,
entry: entry,
workingDir: workingDir
}, workerCb);
}
} | [
"function",
"unzipWorker",
"(",
"unzipTask",
",",
"workerCb",
")",
"{",
"var",
"zipfile",
"=",
"unzipTask",
".",
"zipfile",
";",
"var",
"entry",
"=",
"unzipTask",
".",
"entry",
";",
"var",
"workingDir",
"=",
"unzipTask",
".",
"workingDir",
";",
"if",
"(",
"/",
"\\/$",
"/",
".",
"test",
"(",
"entry",
".",
"fileName",
")",
")",
"{",
"makeExportDirectory",
"(",
"{",
"entry",
":",
"entry",
",",
"zipfile",
":",
"zipfile",
",",
"workingDir",
":",
"workingDir",
"}",
",",
"workerCb",
")",
";",
"}",
"else",
"{",
"streamFileEntry",
"(",
"{",
"zipfile",
":",
"zipfile",
",",
"entry",
":",
"entry",
",",
"workingDir",
":",
"workingDir",
"}",
",",
"workerCb",
")",
";",
"}",
"}"
] | unzipWorker - Async Queue worker to pipe the unzipped file to a folder.
@param {object} unzipTask description
@param {function} workerCb description | [
"unzipWorker",
"-",
"Async",
"Queue",
"worker",
"to",
"pipe",
"the",
"unzipped",
"file",
"to",
"a",
"folder",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L74-L93 | train |
feedhenry/fh-forms | lib/impl/importForms/unzipFile.js | unzipToWorkingDir | function unzipToWorkingDir(params, callback) {
var unzipError;
var queue = async.queue(unzipWorker, params.queueConcurrency || 5);
//Pushing a single file unzip to the queue.
function getQueueEntry(zipfile) {
return function queueEntry(entry) {
queue.push({
zipfile: zipfile,
workingDir: params.workingDir,
entry: entry
}, function(err) {
if (err) {
logger.debug("Error unzipping file params.zipFilePath", err);
//If one of the files has failed to unzip correctly. No point in continuing to unzip. Close the zip file.
zipfile.close();
}
});
};
}
unzip.open(params.zipFilePath, {lazyEntries: true}, function(err, zipfile) {
if (err) {
return callback(err);
}
zipfile.on("entry", getQueueEntry(zipfile));
zipfile.readEntry();
zipfile.on('error', function(err) {
logger.error("Error unzipping Zip File " + params.zipFilePath, err);
unzipError = err;
});
zipfile.on('close', function() {
//When the queue is empty and the zip file has finisihed scanning files, then the unzip is finished
logger.debug("Zip File " + params.zipFilePath + " Unzipped");
callback(unzipError);
});
});
} | javascript | function unzipToWorkingDir(params, callback) {
var unzipError;
var queue = async.queue(unzipWorker, params.queueConcurrency || 5);
//Pushing a single file unzip to the queue.
function getQueueEntry(zipfile) {
return function queueEntry(entry) {
queue.push({
zipfile: zipfile,
workingDir: params.workingDir,
entry: entry
}, function(err) {
if (err) {
logger.debug("Error unzipping file params.zipFilePath", err);
//If one of the files has failed to unzip correctly. No point in continuing to unzip. Close the zip file.
zipfile.close();
}
});
};
}
unzip.open(params.zipFilePath, {lazyEntries: true}, function(err, zipfile) {
if (err) {
return callback(err);
}
zipfile.on("entry", getQueueEntry(zipfile));
zipfile.readEntry();
zipfile.on('error', function(err) {
logger.error("Error unzipping Zip File " + params.zipFilePath, err);
unzipError = err;
});
zipfile.on('close', function() {
//When the queue is empty and the zip file has finisihed scanning files, then the unzip is finished
logger.debug("Zip File " + params.zipFilePath + " Unzipped");
callback(unzipError);
});
});
} | [
"function",
"unzipToWorkingDir",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"unzipError",
";",
"var",
"queue",
"=",
"async",
".",
"queue",
"(",
"unzipWorker",
",",
"params",
".",
"queueConcurrency",
"||",
"5",
")",
";",
"function",
"getQueueEntry",
"(",
"zipfile",
")",
"{",
"return",
"function",
"queueEntry",
"(",
"entry",
")",
"{",
"queue",
".",
"push",
"(",
"{",
"zipfile",
":",
"zipfile",
",",
"workingDir",
":",
"params",
".",
"workingDir",
",",
"entry",
":",
"entry",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Error unzipping file params.zipFilePath\"",
",",
"err",
")",
";",
"zipfile",
".",
"close",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"}",
"unzip",
".",
"open",
"(",
"params",
".",
"zipFilePath",
",",
"{",
"lazyEntries",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"zipfile",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"zipfile",
".",
"on",
"(",
"\"entry\"",
",",
"getQueueEntry",
"(",
"zipfile",
")",
")",
";",
"zipfile",
".",
"readEntry",
"(",
")",
";",
"zipfile",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error unzipping Zip File \"",
"+",
"params",
".",
"zipFilePath",
",",
"err",
")",
";",
"unzipError",
"=",
"err",
";",
"}",
")",
";",
"zipfile",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Zip File \"",
"+",
"params",
".",
"zipFilePath",
"+",
"\" Unzipped\"",
")",
";",
"callback",
"(",
"unzipError",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | unzipToWorkingDir - Unzipping a file to a working directory.
Using a queue to control the number of files decompressing at a time.
@param {object} params
@param {string} params.zipFilePath Path to the ZIP file to unzip.
@param {number} params.queueConcurrency Concurrency Of the async queue
@param {string} params.workingDir Unzip Working Directory
@param {function} callback | [
"unzipToWorkingDir",
"-",
"Unzipping",
"a",
"file",
"to",
"a",
"working",
"directory",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L107-L148 | train |
feedhenry/fh-forms | lib/impl/importForms/unzipFile.js | getQueueEntry | function getQueueEntry(zipfile) {
return function queueEntry(entry) {
queue.push({
zipfile: zipfile,
workingDir: params.workingDir,
entry: entry
}, function(err) {
if (err) {
logger.debug("Error unzipping file params.zipFilePath", err);
//If one of the files has failed to unzip correctly. No point in continuing to unzip. Close the zip file.
zipfile.close();
}
});
};
} | javascript | function getQueueEntry(zipfile) {
return function queueEntry(entry) {
queue.push({
zipfile: zipfile,
workingDir: params.workingDir,
entry: entry
}, function(err) {
if (err) {
logger.debug("Error unzipping file params.zipFilePath", err);
//If one of the files has failed to unzip correctly. No point in continuing to unzip. Close the zip file.
zipfile.close();
}
});
};
} | [
"function",
"getQueueEntry",
"(",
"zipfile",
")",
"{",
"return",
"function",
"queueEntry",
"(",
"entry",
")",
"{",
"queue",
".",
"push",
"(",
"{",
"zipfile",
":",
"zipfile",
",",
"workingDir",
":",
"params",
".",
"workingDir",
",",
"entry",
":",
"entry",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Error unzipping file params.zipFilePath\"",
",",
"err",
")",
";",
"zipfile",
".",
"close",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"}"
] | Pushing a single file unzip to the queue. | [
"Pushing",
"a",
"single",
"file",
"unzip",
"to",
"the",
"queue",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L113-L127 | train |
feedhenry/fh-forms | lib/common/misc.js | filterOutNullData | function filterOutNullData(fieldValues) {
return _.filter(fieldValues || [], function(val) {
return val === false || val === 0 || val;
});
} | javascript | function filterOutNullData(fieldValues) {
return _.filter(fieldValues || [], function(val) {
return val === false || val === 0 || val;
});
} | [
"function",
"filterOutNullData",
"(",
"fieldValues",
")",
"{",
"return",
"_",
".",
"filter",
"(",
"fieldValues",
"||",
"[",
"]",
",",
"function",
"(",
"val",
")",
"{",
"return",
"val",
"===",
"false",
"||",
"val",
"===",
"0",
"||",
"val",
";",
"}",
")",
";",
"}"
] | filterOutNullData - Utility function to remove all 'null' or 'undefined' values.
0 and false are considered valid field value entries.
@param {array} fieldValues Array of field values to filter.
@return {array} Filtered field values. | [
"filterOutNullData",
"-",
"Utility",
"function",
"to",
"remove",
"all",
"null",
"or",
"undefined",
"values",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L31-L35 | train |
feedhenry/fh-forms | lib/common/misc.js | addAdminFieldToSubmission | function addAdminFieldToSubmission(field) {
//Full field object is used in the return as existing fields are populated already.
var subObject = {
fieldId : field,
fieldValues: []
};
submission.formFields.push(subObject);
} | javascript | function addAdminFieldToSubmission(field) {
//Full field object is used in the return as existing fields are populated already.
var subObject = {
fieldId : field,
fieldValues: []
};
submission.formFields.push(subObject);
} | [
"function",
"addAdminFieldToSubmission",
"(",
"field",
")",
"{",
"var",
"subObject",
"=",
"{",
"fieldId",
":",
"field",
",",
"fieldValues",
":",
"[",
"]",
"}",
";",
"submission",
".",
"formFields",
".",
"push",
"(",
"subObject",
")",
";",
"}"
] | The field definition can either be in the submission that has a populated fieldId,
Or the field definition is an admin field that is in the formSubmitted against.
As this field is not included in a client submission, a scan of the formSubmitted against must be made.
@param field
@param formJSON | [
"The",
"field",
"definition",
"can",
"either",
"be",
"in",
"the",
"submission",
"that",
"has",
"a",
"populated",
"fieldId",
"Or",
"the",
"field",
"definition",
"is",
"an",
"admin",
"field",
"that",
"is",
"in",
"the",
"formSubmitted",
"against",
".",
"As",
"this",
"field",
"is",
"not",
"included",
"in",
"a",
"client",
"submission",
"a",
"scan",
"of",
"the",
"formSubmitted",
"against",
"must",
"be",
"made",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L51-L59 | train |
feedhenry/fh-forms | lib/common/misc.js | convertAllObjectIdsToString | function convertAllObjectIdsToString(form) {
form._id = form._id ? form._id.toString() : form._id;
form.pages = _.map(form.pages, function(page) {
page._id = page._id ? page._id.toString() : page._id;
page.fields = _.map(page.fields, function(field) {
field._id = field._id ? field._id.toString() : field._id;
return field;
});
return page;
});
return form;
} | javascript | function convertAllObjectIdsToString(form) {
form._id = form._id ? form._id.toString() : form._id;
form.pages = _.map(form.pages, function(page) {
page._id = page._id ? page._id.toString() : page._id;
page.fields = _.map(page.fields, function(field) {
field._id = field._id ? field._id.toString() : field._id;
return field;
});
return page;
});
return form;
} | [
"function",
"convertAllObjectIdsToString",
"(",
"form",
")",
"{",
"form",
".",
"_id",
"=",
"form",
".",
"_id",
"?",
"form",
".",
"_id",
".",
"toString",
"(",
")",
":",
"form",
".",
"_id",
";",
"form",
".",
"pages",
"=",
"_",
".",
"map",
"(",
"form",
".",
"pages",
",",
"function",
"(",
"page",
")",
"{",
"page",
".",
"_id",
"=",
"page",
".",
"_id",
"?",
"page",
".",
"_id",
".",
"toString",
"(",
")",
":",
"page",
".",
"_id",
";",
"page",
".",
"fields",
"=",
"_",
".",
"map",
"(",
"page",
".",
"fields",
",",
"function",
"(",
"field",
")",
"{",
"field",
".",
"_id",
"=",
"field",
".",
"_id",
"?",
"field",
".",
"_id",
".",
"toString",
"(",
")",
":",
"field",
".",
"_id",
";",
"return",
"field",
";",
"}",
")",
";",
"return",
"page",
";",
"}",
")",
";",
"return",
"form",
";",
"}"
] | Handy Function To convert All ObjectIds to strings. | [
"Handy",
"Function",
"To",
"convert",
"All",
"ObjectIds",
"to",
"strings",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L86-L99 | train |
feedhenry/fh-forms | lib/common/misc.js | getMostRecentRefresh | function getMostRecentRefresh(formLastUpdated, dataLastUpdated) {
var formTimestamp = new Date(formLastUpdated).getTime();
var dataTimestamp = new Date(dataLastUpdated).getTime();
if (!dataLastUpdated) {
return formLastUpdated;
}
if (dataTimestamp > formTimestamp) {
return dataLastUpdated;
} else {
return formLastUpdated;
}
} | javascript | function getMostRecentRefresh(formLastUpdated, dataLastUpdated) {
var formTimestamp = new Date(formLastUpdated).getTime();
var dataTimestamp = new Date(dataLastUpdated).getTime();
if (!dataLastUpdated) {
return formLastUpdated;
}
if (dataTimestamp > formTimestamp) {
return dataLastUpdated;
} else {
return formLastUpdated;
}
} | [
"function",
"getMostRecentRefresh",
"(",
"formLastUpdated",
",",
"dataLastUpdated",
")",
"{",
"var",
"formTimestamp",
"=",
"new",
"Date",
"(",
"formLastUpdated",
")",
".",
"getTime",
"(",
")",
";",
"var",
"dataTimestamp",
"=",
"new",
"Date",
"(",
"dataLastUpdated",
")",
".",
"getTime",
"(",
")",
";",
"if",
"(",
"!",
"dataLastUpdated",
")",
"{",
"return",
"formLastUpdated",
";",
"}",
"if",
"(",
"dataTimestamp",
">",
"formTimestamp",
")",
"{",
"return",
"dataLastUpdated",
";",
"}",
"else",
"{",
"return",
"formLastUpdated",
";",
"}",
"}"
] | Function to compare to timestamps and return the most recent. | [
"Function",
"to",
"compare",
"to",
"timestamps",
"and",
"return",
"the",
"most",
"recent",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L102-L115 | train |
feedhenry/fh-forms | lib/common/misc.js | checkId | function checkId(id) {
id = id || "";
id = id.toString();
return _.isString(id) && id.length === 24;
} | javascript | function checkId(id) {
id = id || "";
id = id.toString();
return _.isString(id) && id.length === 24;
} | [
"function",
"checkId",
"(",
"id",
")",
"{",
"id",
"=",
"id",
"||",
"\"\"",
";",
"id",
"=",
"id",
".",
"toString",
"(",
")",
";",
"return",
"_",
".",
"isString",
"(",
"id",
")",
"&&",
"id",
".",
"length",
"===",
"24",
";",
"}"
] | Checking Mongo ID Param | [
"Checking",
"Mongo",
"ID",
"Param"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L168-L172 | train |
feedhenry/fh-forms | lib/common/misc.js | buildErrorResponse | function buildErrorResponse(params) {
params = params || {};
params.error = params.error || {};
var ERROR_CODES = models.CONSTANTS.ERROR_CODES;
if (params.error.userDetail) {
return params.error;
}
if (params.error) {
var message = params.error.message || "";
//If the message is about validation, the return a validation http response
if (message.indexOf("validation") > -1) {
params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS;
}
}
//Mongoose Validation Failed
if (params.error && params.error.errors) {
var fieldKey = _.keys(params.error.errors)[0];
params.userDetail = params.userDetail || params.error.errors[fieldKey].message;
params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS;
}
var userDetail = params.userDetail || params.error.userDetail || params.error.message || "An Unexpected Error Occurred";
var systemDetail = params.systemDetail || params.error.systemDetail || params.error.stack || "";
var code = params.code || ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR;
return {
userDetail: userDetail,
systemDetail: systemDetail,
code: code
};
} | javascript | function buildErrorResponse(params) {
params = params || {};
params.error = params.error || {};
var ERROR_CODES = models.CONSTANTS.ERROR_CODES;
if (params.error.userDetail) {
return params.error;
}
if (params.error) {
var message = params.error.message || "";
//If the message is about validation, the return a validation http response
if (message.indexOf("validation") > -1) {
params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS;
}
}
//Mongoose Validation Failed
if (params.error && params.error.errors) {
var fieldKey = _.keys(params.error.errors)[0];
params.userDetail = params.userDetail || params.error.errors[fieldKey].message;
params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS;
}
var userDetail = params.userDetail || params.error.userDetail || params.error.message || "An Unexpected Error Occurred";
var systemDetail = params.systemDetail || params.error.systemDetail || params.error.stack || "";
var code = params.code || ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR;
return {
userDetail: userDetail,
systemDetail: systemDetail,
code: code
};
} | [
"function",
"buildErrorResponse",
"(",
"params",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"params",
".",
"error",
"=",
"params",
".",
"error",
"||",
"{",
"}",
";",
"var",
"ERROR_CODES",
"=",
"models",
".",
"CONSTANTS",
".",
"ERROR_CODES",
";",
"if",
"(",
"params",
".",
"error",
".",
"userDetail",
")",
"{",
"return",
"params",
".",
"error",
";",
"}",
"if",
"(",
"params",
".",
"error",
")",
"{",
"var",
"message",
"=",
"params",
".",
"error",
".",
"message",
"||",
"\"\"",
";",
"if",
"(",
"message",
".",
"indexOf",
"(",
"\"validation\"",
")",
">",
"-",
"1",
")",
"{",
"params",
".",
"code",
"=",
"params",
".",
"code",
"||",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
";",
"}",
"}",
"if",
"(",
"params",
".",
"error",
"&&",
"params",
".",
"error",
".",
"errors",
")",
"{",
"var",
"fieldKey",
"=",
"_",
".",
"keys",
"(",
"params",
".",
"error",
".",
"errors",
")",
"[",
"0",
"]",
";",
"params",
".",
"userDetail",
"=",
"params",
".",
"userDetail",
"||",
"params",
".",
"error",
".",
"errors",
"[",
"fieldKey",
"]",
".",
"message",
";",
"params",
".",
"code",
"=",
"params",
".",
"code",
"||",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
";",
"}",
"var",
"userDetail",
"=",
"params",
".",
"userDetail",
"||",
"params",
".",
"error",
".",
"userDetail",
"||",
"params",
".",
"error",
".",
"message",
"||",
"\"An Unexpected Error Occurred\"",
";",
"var",
"systemDetail",
"=",
"params",
".",
"systemDetail",
"||",
"params",
".",
"error",
".",
"systemDetail",
"||",
"params",
".",
"error",
".",
"stack",
"||",
"\"\"",
";",
"var",
"code",
"=",
"params",
".",
"code",
"||",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
";",
"return",
"{",
"userDetail",
":",
"userDetail",
",",
"systemDetail",
":",
"systemDetail",
",",
"code",
":",
"code",
"}",
";",
"}"
] | Common Error Response builder.
Thee should be a common error response from all feedhenry components.
@param params - object containing error structures. | [
"Common",
"Error",
"Response",
"builder",
".",
"Thee",
"should",
"be",
"a",
"common",
"error",
"response",
"from",
"all",
"feedhenry",
"components",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L197-L230 | train |
feedhenry/fh-forms | lib/common/misc.js | pruneIds | function pruneIds(form) {
var testForm = _.clone(form);
testForm.pages = _.map(testForm.pages, function(page) {
page.fields = _.map(page.fields, function(field) {
return _.omit(field, '_id');
});
return _.omit(page, '_id');
});
return _.omit(testForm, '_id');
} | javascript | function pruneIds(form) {
var testForm = _.clone(form);
testForm.pages = _.map(testForm.pages, function(page) {
page.fields = _.map(page.fields, function(field) {
return _.omit(field, '_id');
});
return _.omit(page, '_id');
});
return _.omit(testForm, '_id');
} | [
"function",
"pruneIds",
"(",
"form",
")",
"{",
"var",
"testForm",
"=",
"_",
".",
"clone",
"(",
"form",
")",
";",
"testForm",
".",
"pages",
"=",
"_",
".",
"map",
"(",
"testForm",
".",
"pages",
",",
"function",
"(",
"page",
")",
"{",
"page",
".",
"fields",
"=",
"_",
".",
"map",
"(",
"page",
".",
"fields",
",",
"function",
"(",
"field",
")",
"{",
"return",
"_",
".",
"omit",
"(",
"field",
",",
"'_id'",
")",
";",
"}",
")",
";",
"return",
"_",
".",
"omit",
"(",
"page",
",",
"'_id'",
")",
";",
"}",
")",
";",
"return",
"_",
".",
"omit",
"(",
"testForm",
",",
"'_id'",
")",
";",
"}"
] | Removing All underscore ids | [
"Removing",
"All",
"underscore",
"ids"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L233-L244 | train |
feedhenry/fh-forms | lib/common/misc.js | buildFormFileSizes | function buildFormFileSizes(submissions) {
//Grouping By Form Id
var fileSizesByForm = _.groupBy(submissions, 'formId');
//Getting all files associated with the submissions
fileSizesByForm = _.mapObject(fileSizesByForm, function(formSubs) {
//Getting File Sizes For All Entries In All Submissions Related To formId
var allSubmissionSizes = _.map(formSubs, function(submission) {
//For a single submission, get all file sizes
var submissionFileSizes = _.map(submission.formFields, function(formField) {
return _.map(_.compact(formField.fieldValues), function(fieldValue) {
return fieldValue.fileSize;
});
});
var totalSize = _.compact(_.flatten(submissionFileSizes));
//Adding all the file sizes for a single submission.
return _.reduce(totalSize, function(memo, fileSize) {
return memo + fileSize;
}, 0);
});
//Adding all file sizes for all submissions
return _.reduce(_.flatten(allSubmissionSizes), function(memo, fileSize) {
return memo + fileSize;
}, 0);
});
return fileSizesByForm;
} | javascript | function buildFormFileSizes(submissions) {
//Grouping By Form Id
var fileSizesByForm = _.groupBy(submissions, 'formId');
//Getting all files associated with the submissions
fileSizesByForm = _.mapObject(fileSizesByForm, function(formSubs) {
//Getting File Sizes For All Entries In All Submissions Related To formId
var allSubmissionSizes = _.map(formSubs, function(submission) {
//For a single submission, get all file sizes
var submissionFileSizes = _.map(submission.formFields, function(formField) {
return _.map(_.compact(formField.fieldValues), function(fieldValue) {
return fieldValue.fileSize;
});
});
var totalSize = _.compact(_.flatten(submissionFileSizes));
//Adding all the file sizes for a single submission.
return _.reduce(totalSize, function(memo, fileSize) {
return memo + fileSize;
}, 0);
});
//Adding all file sizes for all submissions
return _.reduce(_.flatten(allSubmissionSizes), function(memo, fileSize) {
return memo + fileSize;
}, 0);
});
return fileSizesByForm;
} | [
"function",
"buildFormFileSizes",
"(",
"submissions",
")",
"{",
"var",
"fileSizesByForm",
"=",
"_",
".",
"groupBy",
"(",
"submissions",
",",
"'formId'",
")",
";",
"fileSizesByForm",
"=",
"_",
".",
"mapObject",
"(",
"fileSizesByForm",
",",
"function",
"(",
"formSubs",
")",
"{",
"var",
"allSubmissionSizes",
"=",
"_",
".",
"map",
"(",
"formSubs",
",",
"function",
"(",
"submission",
")",
"{",
"var",
"submissionFileSizes",
"=",
"_",
".",
"map",
"(",
"submission",
".",
"formFields",
",",
"function",
"(",
"formField",
")",
"{",
"return",
"_",
".",
"map",
"(",
"_",
".",
"compact",
"(",
"formField",
".",
"fieldValues",
")",
",",
"function",
"(",
"fieldValue",
")",
"{",
"return",
"fieldValue",
".",
"fileSize",
";",
"}",
")",
";",
"}",
")",
";",
"var",
"totalSize",
"=",
"_",
".",
"compact",
"(",
"_",
".",
"flatten",
"(",
"submissionFileSizes",
")",
")",
";",
"return",
"_",
".",
"reduce",
"(",
"totalSize",
",",
"function",
"(",
"memo",
",",
"fileSize",
")",
"{",
"return",
"memo",
"+",
"fileSize",
";",
"}",
",",
"0",
")",
";",
"}",
")",
";",
"return",
"_",
".",
"reduce",
"(",
"_",
".",
"flatten",
"(",
"allSubmissionSizes",
")",
",",
"function",
"(",
"memo",
",",
"fileSize",
")",
"{",
"return",
"memo",
"+",
"fileSize",
";",
"}",
",",
"0",
")",
";",
"}",
")",
";",
"return",
"fileSizesByForm",
";",
"}"
] | Utility Function To Add All Files Storage Sizes For Submission
@param submissions | [
"Utility",
"Function",
"To",
"Add",
"All",
"Files",
"Storage",
"Sizes",
"For",
"Submission"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L250-L282 | train |
feedhenry/fh-forms | lib/impl/getForm.js | getDataSourceIds | function getDataSourceIds(forms) {
var dataSources = _.map(forms, function(form) {
return _.map(form.dataSources.formDataSources, function(dataSourceMeta) {
return dataSourceMeta._id.toString();
});
});
dataSources = _.flatten(dataSources);
//Only want unique data source Ids as multiple forms may use the same data source.
return _.uniq(dataSources);
} | javascript | function getDataSourceIds(forms) {
var dataSources = _.map(forms, function(form) {
return _.map(form.dataSources.formDataSources, function(dataSourceMeta) {
return dataSourceMeta._id.toString();
});
});
dataSources = _.flatten(dataSources);
//Only want unique data source Ids as multiple forms may use the same data source.
return _.uniq(dataSources);
} | [
"function",
"getDataSourceIds",
"(",
"forms",
")",
"{",
"var",
"dataSources",
"=",
"_",
".",
"map",
"(",
"forms",
",",
"function",
"(",
"form",
")",
"{",
"return",
"_",
".",
"map",
"(",
"form",
".",
"dataSources",
".",
"formDataSources",
",",
"function",
"(",
"dataSourceMeta",
")",
"{",
"return",
"dataSourceMeta",
".",
"_id",
".",
"toString",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"dataSources",
"=",
"_",
".",
"flatten",
"(",
"dataSources",
")",
";",
"return",
"_",
".",
"uniq",
"(",
"dataSources",
")",
";",
"}"
] | Extract a list of data sources from forms
@param forms | [
"Extract",
"a",
"list",
"of",
"data",
"sources",
"from",
"forms"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getForm.js#L130-L142 | train |
feedhenry/fh-forms | lib/impl/getForm.js | populateFieldDataFromDataSources | function populateFieldDataFromDataSources(populatedForms, cb) {
logger.debug("populateFieldDataFromDataSources", populatedForms);
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
//If no data source cache data is expected, then there is no need to load the Data Source Cache Data.
if (!options.expectDataSourceCache) {
return cb(undefined, populatedForms);
}
var dataSourceIds = getDataSourceIds(populatedForms);
logger.debug("populateFieldDataFromDataSources", {dataSourceIds: dataSourceIds});
//If none of the forms refer to any data sources, then no need to search
if (dataSourceIds.length === 0) {
return cb(undefined, populatedForms);
}
var query = {
_id: {
"$in": dataSourceIds
}
};
//One query to populate all data sources
DataSource.find(query).exec(function(err, dataSources) {
if (err) {
logger.error("Error Finding Data Sources", {error: err, dataSourceIds:dataSourceIds});
return cb(err);
}
logger.debug("populateFieldDataFromDataSources", {dataSources: dataSources});
var validatonError = _validateReturnedDataSources(dataSourceIds, dataSources);
if (validatonError) {
logger.error("Error Getting Form With Data Sources", {error: validatonError});
return cb(validatonError);
}
var cacheEntries = {};
//Assigning a lookup for cache entries
_.each(dataSources, function(dataSource) {
cacheEntries[dataSource._id] = dataSource.cache[0].data;
});
//Overriding field options for a field with data source data if the field is defined as being sourced from a data source.
populatedForms = _.map(populatedForms, function(populatedForm) {
populatedForm.pages = _.map(populatedForm.pages, function(page) {
page.fields = _.map(page.fields, function(field) {
//If it is a data source type field, then return the data source data
if (field.dataSourceType === models.FORM_CONSTANTS.DATA_SOURCE_TYPE_DATA_SOURCE) {
//No guarantee these are set
field.fieldOptions = field.fieldOptions || {};
field.fieldOptions.definition = field.fieldOptions.definition || {};
//Setting the data source data
field.fieldOptions.definition.options = models.convertDSCacheToFieldOptions(field.type, cacheEntries[field.dataSource]);
}
return field;
});
return page;
});
return populatedForm;
});
logger.debug("populateFieldDataFromDataSources", {populatedForms: JSON.stringify(populatedForms)});
//Finished, return the merged forms
return cb(undefined, populatedForms);
});
} | javascript | function populateFieldDataFromDataSources(populatedForms, cb) {
logger.debug("populateFieldDataFromDataSources", populatedForms);
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
//If no data source cache data is expected, then there is no need to load the Data Source Cache Data.
if (!options.expectDataSourceCache) {
return cb(undefined, populatedForms);
}
var dataSourceIds = getDataSourceIds(populatedForms);
logger.debug("populateFieldDataFromDataSources", {dataSourceIds: dataSourceIds});
//If none of the forms refer to any data sources, then no need to search
if (dataSourceIds.length === 0) {
return cb(undefined, populatedForms);
}
var query = {
_id: {
"$in": dataSourceIds
}
};
//One query to populate all data sources
DataSource.find(query).exec(function(err, dataSources) {
if (err) {
logger.error("Error Finding Data Sources", {error: err, dataSourceIds:dataSourceIds});
return cb(err);
}
logger.debug("populateFieldDataFromDataSources", {dataSources: dataSources});
var validatonError = _validateReturnedDataSources(dataSourceIds, dataSources);
if (validatonError) {
logger.error("Error Getting Form With Data Sources", {error: validatonError});
return cb(validatonError);
}
var cacheEntries = {};
//Assigning a lookup for cache entries
_.each(dataSources, function(dataSource) {
cacheEntries[dataSource._id] = dataSource.cache[0].data;
});
//Overriding field options for a field with data source data if the field is defined as being sourced from a data source.
populatedForms = _.map(populatedForms, function(populatedForm) {
populatedForm.pages = _.map(populatedForm.pages, function(page) {
page.fields = _.map(page.fields, function(field) {
//If it is a data source type field, then return the data source data
if (field.dataSourceType === models.FORM_CONSTANTS.DATA_SOURCE_TYPE_DATA_SOURCE) {
//No guarantee these are set
field.fieldOptions = field.fieldOptions || {};
field.fieldOptions.definition = field.fieldOptions.definition || {};
//Setting the data source data
field.fieldOptions.definition.options = models.convertDSCacheToFieldOptions(field.type, cacheEntries[field.dataSource]);
}
return field;
});
return page;
});
return populatedForm;
});
logger.debug("populateFieldDataFromDataSources", {populatedForms: JSON.stringify(populatedForms)});
//Finished, return the merged forms
return cb(undefined, populatedForms);
});
} | [
"function",
"populateFieldDataFromDataSources",
"(",
"populatedForms",
",",
"cb",
")",
"{",
"logger",
".",
"debug",
"(",
"\"populateFieldDataFromDataSources\"",
",",
"populatedForms",
")",
";",
"var",
"DataSource",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE",
")",
";",
"if",
"(",
"!",
"options",
".",
"expectDataSourceCache",
")",
"{",
"return",
"cb",
"(",
"undefined",
",",
"populatedForms",
")",
";",
"}",
"var",
"dataSourceIds",
"=",
"getDataSourceIds",
"(",
"populatedForms",
")",
";",
"logger",
".",
"debug",
"(",
"\"populateFieldDataFromDataSources\"",
",",
"{",
"dataSourceIds",
":",
"dataSourceIds",
"}",
")",
";",
"if",
"(",
"dataSourceIds",
".",
"length",
"===",
"0",
")",
"{",
"return",
"cb",
"(",
"undefined",
",",
"populatedForms",
")",
";",
"}",
"var",
"query",
"=",
"{",
"_id",
":",
"{",
"\"$in\"",
":",
"dataSourceIds",
"}",
"}",
";",
"DataSource",
".",
"find",
"(",
"query",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"dataSources",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error Finding Data Sources\"",
",",
"{",
"error",
":",
"err",
",",
"dataSourceIds",
":",
"dataSourceIds",
"}",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"populateFieldDataFromDataSources\"",
",",
"{",
"dataSources",
":",
"dataSources",
"}",
")",
";",
"var",
"validatonError",
"=",
"_validateReturnedDataSources",
"(",
"dataSourceIds",
",",
"dataSources",
")",
";",
"if",
"(",
"validatonError",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error Getting Form With Data Sources\"",
",",
"{",
"error",
":",
"validatonError",
"}",
")",
";",
"return",
"cb",
"(",
"validatonError",
")",
";",
"}",
"var",
"cacheEntries",
"=",
"{",
"}",
";",
"_",
".",
"each",
"(",
"dataSources",
",",
"function",
"(",
"dataSource",
")",
"{",
"cacheEntries",
"[",
"dataSource",
".",
"_id",
"]",
"=",
"dataSource",
".",
"cache",
"[",
"0",
"]",
".",
"data",
";",
"}",
")",
";",
"populatedForms",
"=",
"_",
".",
"map",
"(",
"populatedForms",
",",
"function",
"(",
"populatedForm",
")",
"{",
"populatedForm",
".",
"pages",
"=",
"_",
".",
"map",
"(",
"populatedForm",
".",
"pages",
",",
"function",
"(",
"page",
")",
"{",
"page",
".",
"fields",
"=",
"_",
".",
"map",
"(",
"page",
".",
"fields",
",",
"function",
"(",
"field",
")",
"{",
"if",
"(",
"field",
".",
"dataSourceType",
"===",
"models",
".",
"FORM_CONSTANTS",
".",
"DATA_SOURCE_TYPE_DATA_SOURCE",
")",
"{",
"field",
".",
"fieldOptions",
"=",
"field",
".",
"fieldOptions",
"||",
"{",
"}",
";",
"field",
".",
"fieldOptions",
".",
"definition",
"=",
"field",
".",
"fieldOptions",
".",
"definition",
"||",
"{",
"}",
";",
"field",
".",
"fieldOptions",
".",
"definition",
".",
"options",
"=",
"models",
".",
"convertDSCacheToFieldOptions",
"(",
"field",
".",
"type",
",",
"cacheEntries",
"[",
"field",
".",
"dataSource",
"]",
")",
";",
"}",
"return",
"field",
";",
"}",
")",
";",
"return",
"page",
";",
"}",
")",
";",
"return",
"populatedForm",
";",
"}",
")",
";",
"logger",
".",
"debug",
"(",
"\"populateFieldDataFromDataSources\"",
",",
"{",
"populatedForms",
":",
"JSON",
".",
"stringify",
"(",
"populatedForms",
")",
"}",
")",
";",
"return",
"cb",
"(",
"undefined",
",",
"populatedForms",
")",
";",
"}",
")",
";",
"}"
] | Any fields that require data source data need to be populated | [
"Any",
"fields",
"that",
"require",
"data",
"source",
"data",
"need",
"to",
"be",
"populated"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getForm.js#L145-L218 | train |
feedhenry/fh-forms | lib/impl/getForm.js | pruneDataSourceInfo | function pruneDataSourceInfo(form) {
if (options.includeDataSources) {
return form;
}
delete form.dataSources;
form.pages = _.map(form.pages, function(page) {
page.fields = _.map(page.fields, function(field) {
delete field.dataSource;
delete field.dataSourceType;
return field;
});
return page;
});
return form;
} | javascript | function pruneDataSourceInfo(form) {
if (options.includeDataSources) {
return form;
}
delete form.dataSources;
form.pages = _.map(form.pages, function(page) {
page.fields = _.map(page.fields, function(field) {
delete field.dataSource;
delete field.dataSourceType;
return field;
});
return page;
});
return form;
} | [
"function",
"pruneDataSourceInfo",
"(",
"form",
")",
"{",
"if",
"(",
"options",
".",
"includeDataSources",
")",
"{",
"return",
"form",
";",
"}",
"delete",
"form",
".",
"dataSources",
";",
"form",
".",
"pages",
"=",
"_",
".",
"map",
"(",
"form",
".",
"pages",
",",
"function",
"(",
"page",
")",
"{",
"page",
".",
"fields",
"=",
"_",
".",
"map",
"(",
"page",
".",
"fields",
",",
"function",
"(",
"field",
")",
"{",
"delete",
"field",
".",
"dataSource",
";",
"delete",
"field",
".",
"dataSourceType",
";",
"return",
"field",
";",
"}",
")",
";",
"return",
"page",
";",
"}",
")",
";",
"return",
"form",
";",
"}"
] | Removing form data source information. | [
"Removing",
"form",
"data",
"source",
"information",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getForm.js#L236-L254 | train |
flumedb/flumeview-reduce | write.js | function (state, ev) {
if(state.dirtyTs + 200 < ev.ts && state.queue) {
state.cleanTs = ev.ts
state.writing = true
state.dirty = false
return {state: state, effects: {type: 'write'}}
}
return state
} | javascript | function (state, ev) {
if(state.dirtyTs + 200 < ev.ts && state.queue) {
state.cleanTs = ev.ts
state.writing = true
state.dirty = false
return {state: state, effects: {type: 'write'}}
}
return state
} | [
"function",
"(",
"state",
",",
"ev",
")",
"{",
"if",
"(",
"state",
".",
"dirtyTs",
"+",
"200",
"<",
"ev",
".",
"ts",
"&&",
"state",
".",
"queue",
")",
"{",
"state",
".",
"cleanTs",
"=",
"ev",
".",
"ts",
"state",
".",
"writing",
"=",
"true",
"state",
".",
"dirty",
"=",
"false",
"return",
"{",
"state",
":",
"state",
",",
"effects",
":",
"{",
"type",
":",
"'write'",
"}",
"}",
"}",
"return",
"state",
"}"
] | don't actually start writing immediately. incase writes are coming in fast... this will delay until they stop for 200 ms | [
"don",
"t",
"actually",
"start",
"writing",
"immediately",
".",
"incase",
"writes",
"are",
"coming",
"in",
"fast",
"...",
"this",
"will",
"delay",
"until",
"they",
"stop",
"for",
"200",
"ms"
] | 0c881037358af065b78842475b94eacc68e7e303 | https://github.com/flumedb/flumeview-reduce/blob/0c881037358af065b78842475b94eacc68e7e303/write.js#L39-L47 | train |
|
feedhenry/fh-forms | lib/impl/pdfGeneration/processForm.js | function(field) {
var converted = field.fieldId;
converted.values = field.fieldValues;
converted.sectionIndex = field.sectionIndex;
return converted;
} | javascript | function(field) {
var converted = field.fieldId;
converted.values = field.fieldValues;
converted.sectionIndex = field.sectionIndex;
return converted;
} | [
"function",
"(",
"field",
")",
"{",
"var",
"converted",
"=",
"field",
".",
"fieldId",
";",
"converted",
".",
"values",
"=",
"field",
".",
"fieldValues",
";",
"converted",
".",
"sectionIndex",
"=",
"field",
".",
"sectionIndex",
";",
"return",
"converted",
";",
"}"
] | Fields in submissions and fields in forms have a little bit different structure, this method converts submission
field into a form field.
@param field | [
"Fields",
"in",
"submissions",
"and",
"fields",
"in",
"forms",
"have",
"a",
"little",
"bit",
"different",
"structure",
"this",
"method",
"converts",
"submission",
"field",
"into",
"a",
"form",
"field",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/processForm.js#L10-L15 | train |
|
feedhenry/fh-forms | lib/impl/pdfGeneration/processForm.js | function(section, pageFields, submittedFields) {
var thisSection = section;
var fieldsInSection = sectionUtils.getFieldsInSection(section._id, pageFields);
var renderData = [];
var addedSectionBreaks = false;
var idsOfFieldsInTheSection = [];
_.each(fieldsInSection, function(field) {
idsOfFieldsInTheSection.push(field._id);
var thisFieldInSection = _.filter(submittedFields, function(subField) {
return subField.fieldId._id === field._id;
});
if (!addedSectionBreaks) {
_.each(thisFieldInSection, function(field, index) {
var sectionForIndex = _.clone(thisSection);
sectionForIndex.idx = index + 1;
field.sectionIndex = field.sectionIndex || 0;
renderData[field.sectionIndex] = [sectionForIndex];
});
addedSectionBreaks = true;
}
_.each(thisFieldInSection, function(field) {
field.sectionIndex = field.sectionIndex || 0;
renderData[field.sectionIndex].push(convertFieldToFormFormat(field));
});
});
renderData = _.flatten(renderData);
return {renderData: renderData, fieldsInSection: idsOfFieldsInTheSection};
} | javascript | function(section, pageFields, submittedFields) {
var thisSection = section;
var fieldsInSection = sectionUtils.getFieldsInSection(section._id, pageFields);
var renderData = [];
var addedSectionBreaks = false;
var idsOfFieldsInTheSection = [];
_.each(fieldsInSection, function(field) {
idsOfFieldsInTheSection.push(field._id);
var thisFieldInSection = _.filter(submittedFields, function(subField) {
return subField.fieldId._id === field._id;
});
if (!addedSectionBreaks) {
_.each(thisFieldInSection, function(field, index) {
var sectionForIndex = _.clone(thisSection);
sectionForIndex.idx = index + 1;
field.sectionIndex = field.sectionIndex || 0;
renderData[field.sectionIndex] = [sectionForIndex];
});
addedSectionBreaks = true;
}
_.each(thisFieldInSection, function(field) {
field.sectionIndex = field.sectionIndex || 0;
renderData[field.sectionIndex].push(convertFieldToFormFormat(field));
});
});
renderData = _.flatten(renderData);
return {renderData: renderData, fieldsInSection: idsOfFieldsInTheSection};
} | [
"function",
"(",
"section",
",",
"pageFields",
",",
"submittedFields",
")",
"{",
"var",
"thisSection",
"=",
"section",
";",
"var",
"fieldsInSection",
"=",
"sectionUtils",
".",
"getFieldsInSection",
"(",
"section",
".",
"_id",
",",
"pageFields",
")",
";",
"var",
"renderData",
"=",
"[",
"]",
";",
"var",
"addedSectionBreaks",
"=",
"false",
";",
"var",
"idsOfFieldsInTheSection",
"=",
"[",
"]",
";",
"_",
".",
"each",
"(",
"fieldsInSection",
",",
"function",
"(",
"field",
")",
"{",
"idsOfFieldsInTheSection",
".",
"push",
"(",
"field",
".",
"_id",
")",
";",
"var",
"thisFieldInSection",
"=",
"_",
".",
"filter",
"(",
"submittedFields",
",",
"function",
"(",
"subField",
")",
"{",
"return",
"subField",
".",
"fieldId",
".",
"_id",
"===",
"field",
".",
"_id",
";",
"}",
")",
";",
"if",
"(",
"!",
"addedSectionBreaks",
")",
"{",
"_",
".",
"each",
"(",
"thisFieldInSection",
",",
"function",
"(",
"field",
",",
"index",
")",
"{",
"var",
"sectionForIndex",
"=",
"_",
".",
"clone",
"(",
"thisSection",
")",
";",
"sectionForIndex",
".",
"idx",
"=",
"index",
"+",
"1",
";",
"field",
".",
"sectionIndex",
"=",
"field",
".",
"sectionIndex",
"||",
"0",
";",
"renderData",
"[",
"field",
".",
"sectionIndex",
"]",
"=",
"[",
"sectionForIndex",
"]",
";",
"}",
")",
";",
"addedSectionBreaks",
"=",
"true",
";",
"}",
"_",
".",
"each",
"(",
"thisFieldInSection",
",",
"function",
"(",
"field",
")",
"{",
"field",
".",
"sectionIndex",
"=",
"field",
".",
"sectionIndex",
"||",
"0",
";",
"renderData",
"[",
"field",
".",
"sectionIndex",
"]",
".",
"push",
"(",
"convertFieldToFormFormat",
"(",
"field",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"renderData",
"=",
"_",
".",
"flatten",
"(",
"renderData",
")",
";",
"return",
"{",
"renderData",
":",
"renderData",
",",
"fieldsInSection",
":",
"idsOfFieldsInTheSection",
"}",
";",
"}"
] | Builds and returns data used to render repeating sections.
@param section
@param pageFields
@param submittedFields
@returns {{renderData: Array, fieldsInSection: Array}} | [
"Builds",
"and",
"returns",
"data",
"used",
"to",
"render",
"repeating",
"sections",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/processForm.js#L24-L57 | train |
|
crispy1989/node-zstreams | lib/streams/request-stream.js | RequestStream | function RequestStream(requestStream, options) {
var self = this;
if(!options) options = {};
if(options.allowedStatusCodes === undefined) {
options.allowedStatusCodes = [200, 201, 202, 203, 204, 205, 206];
}
if(options.readErrorResponse === undefined) {
options.readErrorResponse = true;
}
ClassicDuplex.call(this, requestStream, options);
this._readErrorResponse = !!options.readErrorResponse;
this._allowedStatusCodes = options.allowedStatusCodes;
requestStream.on('response', function(response) {
self._currentResponse = response;
self.emit('response', response);
if(Array.isArray(self._allowedStatusCodes)) {
var statusCode = ''+response.statusCode;
var statusCodeIsAllowed = false;
for(var i = 0; i < self._allowedStatusCodes.length; i++) {
if(''+self._allowedStatusCodes[i] === statusCode) {
statusCodeIsAllowed = true;
}
}
if(!statusCodeIsAllowed) {
self._handleErrorInResponse(response, new Error('Received error status code: ' + statusCode));
}
}
});
if(requestStream.method === 'GET') {
this._compoundWritable.end();
}
} | javascript | function RequestStream(requestStream, options) {
var self = this;
if(!options) options = {};
if(options.allowedStatusCodes === undefined) {
options.allowedStatusCodes = [200, 201, 202, 203, 204, 205, 206];
}
if(options.readErrorResponse === undefined) {
options.readErrorResponse = true;
}
ClassicDuplex.call(this, requestStream, options);
this._readErrorResponse = !!options.readErrorResponse;
this._allowedStatusCodes = options.allowedStatusCodes;
requestStream.on('response', function(response) {
self._currentResponse = response;
self.emit('response', response);
if(Array.isArray(self._allowedStatusCodes)) {
var statusCode = ''+response.statusCode;
var statusCodeIsAllowed = false;
for(var i = 0; i < self._allowedStatusCodes.length; i++) {
if(''+self._allowedStatusCodes[i] === statusCode) {
statusCodeIsAllowed = true;
}
}
if(!statusCodeIsAllowed) {
self._handleErrorInResponse(response, new Error('Received error status code: ' + statusCode));
}
}
});
if(requestStream.method === 'GET') {
this._compoundWritable.end();
}
} | [
"function",
"RequestStream",
"(",
"requestStream",
",",
"options",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"options",
")",
"options",
"=",
"{",
"}",
";",
"if",
"(",
"options",
".",
"allowedStatusCodes",
"===",
"undefined",
")",
"{",
"options",
".",
"allowedStatusCodes",
"=",
"[",
"200",
",",
"201",
",",
"202",
",",
"203",
",",
"204",
",",
"205",
",",
"206",
"]",
";",
"}",
"if",
"(",
"options",
".",
"readErrorResponse",
"===",
"undefined",
")",
"{",
"options",
".",
"readErrorResponse",
"=",
"true",
";",
"}",
"ClassicDuplex",
".",
"call",
"(",
"this",
",",
"requestStream",
",",
"options",
")",
";",
"this",
".",
"_readErrorResponse",
"=",
"!",
"!",
"options",
".",
"readErrorResponse",
";",
"this",
".",
"_allowedStatusCodes",
"=",
"options",
".",
"allowedStatusCodes",
";",
"requestStream",
".",
"on",
"(",
"'response'",
",",
"function",
"(",
"response",
")",
"{",
"self",
".",
"_currentResponse",
"=",
"response",
";",
"self",
".",
"emit",
"(",
"'response'",
",",
"response",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"self",
".",
"_allowedStatusCodes",
")",
")",
"{",
"var",
"statusCode",
"=",
"''",
"+",
"response",
".",
"statusCode",
";",
"var",
"statusCodeIsAllowed",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"self",
".",
"_allowedStatusCodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"''",
"+",
"self",
".",
"_allowedStatusCodes",
"[",
"i",
"]",
"===",
"statusCode",
")",
"{",
"statusCodeIsAllowed",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"statusCodeIsAllowed",
")",
"{",
"self",
".",
"_handleErrorInResponse",
"(",
"response",
",",
"new",
"Error",
"(",
"'Received error status code: '",
"+",
"statusCode",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"if",
"(",
"requestStream",
".",
"method",
"===",
"'GET'",
")",
"{",
"this",
".",
"_compoundWritable",
".",
"end",
"(",
")",
";",
"}",
"}"
] | This stream exists for the sole purpose of wrapping the commonly used npm module
'request' to make it act like a real duplex stream. The "stream" it returns is
not a real streams2 stream, and does not work with the zstreams conversion methods.
This class will emit errors from the request stream and will also emit the 'response'
event proxied from the request stream. Additionally, it will emit errors if an error
response code is received (see options.allowedStatusCodes) . Error emitted because
of a disallowed status code will, by default, read in the entire response body before
emitting the error, and will assign error.responseBody to be the response body.
@class RequestStream
@constructor
@param {Request} requestStream - The "stream" returned from request()
@param {Object} options - Options to change behavior of the stream
@param {String[]|Number[]|Null} [options.allowedStatusCodes=[200, 201, 202, 203, 204, 205, 206]] -
If a response is received with a HTTP status code not in this list, it is considered an error.
@param {Boolean} [options.readErrorResponse=true] - If set to false,
it disables unpiping the stream and reading in the full response body when an error
status code is received. | [
"This",
"stream",
"exists",
"for",
"the",
"sole",
"purpose",
"of",
"wrapping",
"the",
"commonly",
"used",
"npm",
"module",
"request",
"to",
"make",
"it",
"act",
"like",
"a",
"real",
"duplex",
"stream",
".",
"The",
"stream",
"it",
"returns",
"is",
"not",
"a",
"real",
"streams2",
"stream",
"and",
"does",
"not",
"work",
"with",
"the",
"zstreams",
"conversion",
"methods",
"."
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/request-stream.js#L25-L57 | train |
makeup-js/makeup-screenreader-trap | docs/static/bundle.js | filterAncestor | function filterAncestor(item) {
return item.nodeType === 1 && item.tagName.toLowerCase() !== 'body' && item.tagName.toLowerCase() !== 'html';
} | javascript | function filterAncestor(item) {
return item.nodeType === 1 && item.tagName.toLowerCase() !== 'body' && item.tagName.toLowerCase() !== 'html';
} | [
"function",
"filterAncestor",
"(",
"item",
")",
"{",
"return",
"item",
".",
"nodeType",
"===",
"1",
"&&",
"item",
".",
"tagName",
".",
"toLowerCase",
"(",
")",
"!==",
"'body'",
"&&",
"item",
".",
"tagName",
".",
"toLowerCase",
"(",
")",
"!==",
"'html'",
";",
"}"
] | filter function for ancestor elements | [
"filter",
"function",
"for",
"ancestor",
"elements"
] | 4ce73c000f66194028d9992ee000c7c50b242148 | https://github.com/makeup-js/makeup-screenreader-trap/blob/4ce73c000f66194028d9992ee000c7c50b242148/docs/static/bundle.js#L667-L669 | train |
crispy1989/node-zstreams | lib/streams/classic-duplex.js | ClassicDuplex | function ClassicDuplex(stream, options) {
var readable, writable, classicReadable, classicWritable, self = this;
readable = new PassThrough();
writable = new PassThrough();
CompoundDuplex.call(self, writable, readable, options);
classicMixins.call(this, stream, options);
classicReadable = this._internalReadable = new ClassicReadable(stream, options);
classicReadable.on('error', this._duplexHandleInternalError.bind(this));
classicWritable = this._internalWritable = new ClassicWritable(stream, options);
classicWritable.on('error', this._duplexHandleInternalError.bind(this));
writable.pipe(classicWritable);
classicReadable.pipe(readable);
} | javascript | function ClassicDuplex(stream, options) {
var readable, writable, classicReadable, classicWritable, self = this;
readable = new PassThrough();
writable = new PassThrough();
CompoundDuplex.call(self, writable, readable, options);
classicMixins.call(this, stream, options);
classicReadable = this._internalReadable = new ClassicReadable(stream, options);
classicReadable.on('error', this._duplexHandleInternalError.bind(this));
classicWritable = this._internalWritable = new ClassicWritable(stream, options);
classicWritable.on('error', this._duplexHandleInternalError.bind(this));
writable.pipe(classicWritable);
classicReadable.pipe(readable);
} | [
"function",
"ClassicDuplex",
"(",
"stream",
",",
"options",
")",
"{",
"var",
"readable",
",",
"writable",
",",
"classicReadable",
",",
"classicWritable",
",",
"self",
"=",
"this",
";",
"readable",
"=",
"new",
"PassThrough",
"(",
")",
";",
"writable",
"=",
"new",
"PassThrough",
"(",
")",
";",
"CompoundDuplex",
".",
"call",
"(",
"self",
",",
"writable",
",",
"readable",
",",
"options",
")",
";",
"classicMixins",
".",
"call",
"(",
"this",
",",
"stream",
",",
"options",
")",
";",
"classicReadable",
"=",
"this",
".",
"_internalReadable",
"=",
"new",
"ClassicReadable",
"(",
"stream",
",",
"options",
")",
";",
"classicReadable",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"_duplexHandleInternalError",
".",
"bind",
"(",
"this",
")",
")",
";",
"classicWritable",
"=",
"this",
".",
"_internalWritable",
"=",
"new",
"ClassicWritable",
"(",
"stream",
",",
"options",
")",
";",
"classicWritable",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"_duplexHandleInternalError",
".",
"bind",
"(",
"this",
")",
")",
";",
"writable",
".",
"pipe",
"(",
"classicWritable",
")",
";",
"classicReadable",
".",
"pipe",
"(",
"readable",
")",
";",
"}"
] | ClassicDuplex wraps a "classic" duplex stream.
@class ClassicDuplex
@constructor
@extends CompoundDuplex
@uses _Classic
@param {Stream} stream - The classic stream being wrapped
@param {Object} [options] - Stream options | [
"ClassicDuplex",
"wraps",
"a",
"classic",
"duplex",
"stream",
"."
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/classic-duplex.js#L19-L35 | train |
back4app/back4app-entity | src/back/models/EntitySpecification.js | _loadEntity | function _loadEntity() {
if (_Entity && _Entity !== models.Entity) {
if (_nameValidation) {
_Entity.adapter.loadEntity(_Entity);
for (var attribute in _attributes) {
_loadEntityAttribute(_attributes[attribute]);
}
}
for (var method in _methods) {
_loadEntityMethod(_methods[method], method);
}
}
} | javascript | function _loadEntity() {
if (_Entity && _Entity !== models.Entity) {
if (_nameValidation) {
_Entity.adapter.loadEntity(_Entity);
for (var attribute in _attributes) {
_loadEntityAttribute(_attributes[attribute]);
}
}
for (var method in _methods) {
_loadEntityMethod(_methods[method], method);
}
}
} | [
"function",
"_loadEntity",
"(",
")",
"{",
"if",
"(",
"_Entity",
"&&",
"_Entity",
"!==",
"models",
".",
"Entity",
")",
"{",
"if",
"(",
"_nameValidation",
")",
"{",
"_Entity",
".",
"adapter",
".",
"loadEntity",
"(",
"_Entity",
")",
";",
"for",
"(",
"var",
"attribute",
"in",
"_attributes",
")",
"{",
"_loadEntityAttribute",
"(",
"_attributes",
"[",
"attribute",
"]",
")",
";",
"}",
"}",
"for",
"(",
"var",
"method",
"in",
"_methods",
")",
"{",
"_loadEntityMethod",
"(",
"_methods",
"[",
"method",
"]",
",",
"method",
")",
";",
"}",
"}",
"}"
] | Loads the attributes and methods of the Entity that is associated with the
current specification.
@name module:back4app-entity/models.EntitySpecification~_loadEntity
@function
@private
@example
_loadEntity(); | [
"Loads",
"the",
"attributes",
"and",
"methods",
"of",
"the",
"Entity",
"that",
"is",
"associated",
"with",
"the",
"current",
"specification",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L570-L584 | train |
back4app/back4app-entity | src/back/models/EntitySpecification.js | _loadEntityAttribute | function _loadEntityAttribute(attribute) {
expect(_methods).to.not.have.ownProperty(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is a method with same name in the current Entity and it cannot ' +
'be overloaded'
);
if (_Entity.General) {
expect(_Entity.General.attributes).to.not.have.ownProperty(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is an attribute with same name in a parent of current Entity ' +
'and it cannot be overriden'
);
expect(_Entity.General.methods).to.not.respondTo(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is a method with same name in a parent of current Entity ' +
'and it cannot be overriden'
);
}
var entitySpecializations = _Entity.specializations;
for (var specialization in entitySpecializations) {
expect(entitySpecializations[specialization].specification.attributes)
.to.not.have.ownProperty(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is an attribute with same name in a child of current Entity'
);
expect(entitySpecializations[specialization].specification.methods)
.to.not.have.ownProperty(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is a method with same name in a child of current Entity'
);
}
_Entity.adapter.loadEntityAttribute(_Entity, attribute);
} | javascript | function _loadEntityAttribute(attribute) {
expect(_methods).to.not.have.ownProperty(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is a method with same name in the current Entity and it cannot ' +
'be overloaded'
);
if (_Entity.General) {
expect(_Entity.General.attributes).to.not.have.ownProperty(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is an attribute with same name in a parent of current Entity ' +
'and it cannot be overriden'
);
expect(_Entity.General.methods).to.not.respondTo(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is a method with same name in a parent of current Entity ' +
'and it cannot be overriden'
);
}
var entitySpecializations = _Entity.specializations;
for (var specialization in entitySpecializations) {
expect(entitySpecializations[specialization].specification.attributes)
.to.not.have.ownProperty(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is an attribute with same name in a child of current Entity'
);
expect(entitySpecializations[specialization].specification.methods)
.to.not.have.ownProperty(
attribute.name,
'failed to load entity attribute "' + attribute.name + '" because ' +
'there is a method with same name in a child of current Entity'
);
}
_Entity.adapter.loadEntityAttribute(_Entity, attribute);
} | [
"function",
"_loadEntityAttribute",
"(",
"attribute",
")",
"{",
"expect",
"(",
"_methods",
")",
".",
"to",
".",
"not",
".",
"have",
".",
"ownProperty",
"(",
"attribute",
".",
"name",
",",
"'failed to load entity attribute \"'",
"+",
"attribute",
".",
"name",
"+",
"'\" because '",
"+",
"'there is a method with same name in the current Entity and it cannot '",
"+",
"'be overloaded'",
")",
";",
"if",
"(",
"_Entity",
".",
"General",
")",
"{",
"expect",
"(",
"_Entity",
".",
"General",
".",
"attributes",
")",
".",
"to",
".",
"not",
".",
"have",
".",
"ownProperty",
"(",
"attribute",
".",
"name",
",",
"'failed to load entity attribute \"'",
"+",
"attribute",
".",
"name",
"+",
"'\" because '",
"+",
"'there is an attribute with same name in a parent of current Entity '",
"+",
"'and it cannot be overriden'",
")",
";",
"expect",
"(",
"_Entity",
".",
"General",
".",
"methods",
")",
".",
"to",
".",
"not",
".",
"respondTo",
"(",
"attribute",
".",
"name",
",",
"'failed to load entity attribute \"'",
"+",
"attribute",
".",
"name",
"+",
"'\" because '",
"+",
"'there is a method with same name in a parent of current Entity '",
"+",
"'and it cannot be overriden'",
")",
";",
"}",
"var",
"entitySpecializations",
"=",
"_Entity",
".",
"specializations",
";",
"for",
"(",
"var",
"specialization",
"in",
"entitySpecializations",
")",
"{",
"expect",
"(",
"entitySpecializations",
"[",
"specialization",
"]",
".",
"specification",
".",
"attributes",
")",
".",
"to",
".",
"not",
".",
"have",
".",
"ownProperty",
"(",
"attribute",
".",
"name",
",",
"'failed to load entity attribute \"'",
"+",
"attribute",
".",
"name",
"+",
"'\" because '",
"+",
"'there is an attribute with same name in a child of current Entity'",
")",
";",
"expect",
"(",
"entitySpecializations",
"[",
"specialization",
"]",
".",
"specification",
".",
"methods",
")",
".",
"to",
".",
"not",
".",
"have",
".",
"ownProperty",
"(",
"attribute",
".",
"name",
",",
"'failed to load entity attribute \"'",
"+",
"attribute",
".",
"name",
"+",
"'\" because '",
"+",
"'there is a method with same name in a child of current Entity'",
")",
";",
"}",
"_Entity",
".",
"adapter",
".",
"loadEntityAttribute",
"(",
"_Entity",
",",
"attribute",
")",
";",
"}"
] | Loads an attribute of the Entity that is associated with the current
specification.
@name
module:back4app-entity/models.EntitySpecification~_loadEntityAttribute
@function
@param {!module:back4app-entity/models/attributes.Attribute} attribute The
attribute to be loaded.
@private
@example
_loadEntityAttribute(someAttribute); | [
"Loads",
"an",
"attribute",
"of",
"the",
"Entity",
"that",
"is",
"associated",
"with",
"the",
"current",
"specification",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L598-L640 | train |
back4app/back4app-entity | src/back/models/EntitySpecification.js | _loadEntityMethod | function _loadEntityMethod(func, name) {
expect(_attributes).to.not.have.ownProperty(
name,
'failed to load entity method "' + name + '" because there is an ' +
'attribute with same name in the current Entity and it cannot be ' +
'overloaded'
);
if (_Entity.General) {
expect(_Entity.General.attributes).to.not.have.ownProperty(
name,
'failed to load entity method "' + name + '" because there is an ' +
'attribute with same name in a parent of current Entity and it ' +
'cannot be overriden'
);
}
var entitySpecializations = _Entity.specializations;
for (var specialization in entitySpecializations) {
expect(entitySpecializations[specialization].specification.attributes)
.to.not.have.ownProperty(
name,
'failed to load entity method "' + name + '" because there is an ' +
'attribute with same name in a child of current Entity'
);
}
_Entity.prototype[name] = func;
} | javascript | function _loadEntityMethod(func, name) {
expect(_attributes).to.not.have.ownProperty(
name,
'failed to load entity method "' + name + '" because there is an ' +
'attribute with same name in the current Entity and it cannot be ' +
'overloaded'
);
if (_Entity.General) {
expect(_Entity.General.attributes).to.not.have.ownProperty(
name,
'failed to load entity method "' + name + '" because there is an ' +
'attribute with same name in a parent of current Entity and it ' +
'cannot be overriden'
);
}
var entitySpecializations = _Entity.specializations;
for (var specialization in entitySpecializations) {
expect(entitySpecializations[specialization].specification.attributes)
.to.not.have.ownProperty(
name,
'failed to load entity method "' + name + '" because there is an ' +
'attribute with same name in a child of current Entity'
);
}
_Entity.prototype[name] = func;
} | [
"function",
"_loadEntityMethod",
"(",
"func",
",",
"name",
")",
"{",
"expect",
"(",
"_attributes",
")",
".",
"to",
".",
"not",
".",
"have",
".",
"ownProperty",
"(",
"name",
",",
"'failed to load entity method \"'",
"+",
"name",
"+",
"'\" because there is an '",
"+",
"'attribute with same name in the current Entity and it cannot be '",
"+",
"'overloaded'",
")",
";",
"if",
"(",
"_Entity",
".",
"General",
")",
"{",
"expect",
"(",
"_Entity",
".",
"General",
".",
"attributes",
")",
".",
"to",
".",
"not",
".",
"have",
".",
"ownProperty",
"(",
"name",
",",
"'failed to load entity method \"'",
"+",
"name",
"+",
"'\" because there is an '",
"+",
"'attribute with same name in a parent of current Entity and it '",
"+",
"'cannot be overriden'",
")",
";",
"}",
"var",
"entitySpecializations",
"=",
"_Entity",
".",
"specializations",
";",
"for",
"(",
"var",
"specialization",
"in",
"entitySpecializations",
")",
"{",
"expect",
"(",
"entitySpecializations",
"[",
"specialization",
"]",
".",
"specification",
".",
"attributes",
")",
".",
"to",
".",
"not",
".",
"have",
".",
"ownProperty",
"(",
"name",
",",
"'failed to load entity method \"'",
"+",
"name",
"+",
"'\" because there is an '",
"+",
"'attribute with same name in a child of current Entity'",
")",
";",
"}",
"_Entity",
".",
"prototype",
"[",
"name",
"]",
"=",
"func",
";",
"}"
] | Loads a method of the Entity that is associated with the current
specification.
@name
module:back4app-entity/models.EntitySpecification~_loadEntityMethod
@function
@param {!function} func The method's function to be loaded.
@param {!string} name The method's name to be loaded.
@private
@example
_loadEntityMethod(someMethodFunction, someMethodName); | [
"Loads",
"a",
"method",
"of",
"the",
"Entity",
"that",
"is",
"associated",
"with",
"the",
"current",
"specification",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L654-L682 | train |
back4app/back4app-entity | src/back/models/EntitySpecification.js | addAttribute | function addAttribute() {
var attribute =
arguments.length === 1 && arguments[0] instanceof attributes.Attribute ?
arguments[0] :
attributes.Attribute.resolve.apply(
null,
Array.prototype.slice.call(arguments)
);
var newAttributes = attributes.AttributeDictionary.concat(
_attributes,
attribute
);
if (_Entity) {
_loadEntityAttribute(attribute);
}
_attributes = newAttributes;
} | javascript | function addAttribute() {
var attribute =
arguments.length === 1 && arguments[0] instanceof attributes.Attribute ?
arguments[0] :
attributes.Attribute.resolve.apply(
null,
Array.prototype.slice.call(arguments)
);
var newAttributes = attributes.AttributeDictionary.concat(
_attributes,
attribute
);
if (_Entity) {
_loadEntityAttribute(attribute);
}
_attributes = newAttributes;
} | [
"function",
"addAttribute",
"(",
")",
"{",
"var",
"attribute",
"=",
"arguments",
".",
"length",
"===",
"1",
"&&",
"arguments",
"[",
"0",
"]",
"instanceof",
"attributes",
".",
"Attribute",
"?",
"arguments",
"[",
"0",
"]",
":",
"attributes",
".",
"Attribute",
".",
"resolve",
".",
"apply",
"(",
"null",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
")",
";",
"var",
"newAttributes",
"=",
"attributes",
".",
"AttributeDictionary",
".",
"concat",
"(",
"_attributes",
",",
"attribute",
")",
";",
"if",
"(",
"_Entity",
")",
"{",
"_loadEntityAttribute",
"(",
"attribute",
")",
";",
"}",
"_attributes",
"=",
"newAttributes",
";",
"}"
] | Adds a new attribute to the attributes in the specification.
@name module:back4app-entity/models.EntitySpecification#addAttribute
@function
@param {!module:back4app-entity/models/attributes.Attribute} attribute This
is the attribute to be added. It can be passed as a
{@link module:back4app-entity/models/attributes.Attribute} instance.
@param {?string} [name] This is the name of the attribute.
@example
entitySpecification.addAttribute(
new StringAttribute('attribute'),
'attribute'
);
Adds a new attribute to the attributes in the specification
@name module:back4app-entity/models.EntitySpecification#addAttribute
@function
@param {!Object} attribute This is the attribute to be added. It can be
passed as an Object, as specified in
{@link module:back4app-entity/models/attributes.Attribute}.
@param {!string} [attribute.name] It is the name of the attribute. It is
optional if it is passed as an argument in the function.
@param {!string} [attribute.type='Object'] It is the type of the attribute.
It is optional and if not passed it will assume 'Object' as the default
value.
@param {!string} [attribute.multiplicity='1'] It is the multiplicity of the
attribute. It is optional and if not passed it will assume '1' as the
default value.
@param {?(boolean|number|string|Object|function)} [attribute.default] It is
the default expression of the attribute.
@param {?string} [name] This is the name of the attribute.
@example
entitySpecification.addAttribute({
name: 'attribute',
type: 'string',
multiplicity: '0..1',
default: 'default'
}, 'attribute');
Adds a new attribute to the attributes in the specification.
@name module:back4app-entity/models.EntitySpecification#addAttribute
@function
@param {!string} name It is the name of the attribute.
@param {!string} [type='Object'] It is the type of the attribute. It is
optional and if not passed it will assume 'Object' as the default value.
@param {!string} [multiplicity='1'] It is the multiplicity of the
attribute. It is optional and if not passed it will assume '1' as the
default value.
@param {?(boolean|number|string|Object|function)} [default] It is the
default expression of the attribute.
@example
entitySpecification.addAttribute(
'attribute',
'string',
'0..1',
'default'
); | [
"Adds",
"a",
"new",
"attribute",
"to",
"the",
"attributes",
"in",
"the",
"specification",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L744-L763 | train |
back4app/back4app-entity | src/back/models/EntitySpecification.js | addMethod | function addMethod(func, name) {
var newMethods = methods.MethodDictionary.concat(
_methods,
func,
name
);
if (_Entity) {
_loadEntityMethod(func, name);
}
_methods = newMethods;
} | javascript | function addMethod(func, name) {
var newMethods = methods.MethodDictionary.concat(
_methods,
func,
name
);
if (_Entity) {
_loadEntityMethod(func, name);
}
_methods = newMethods;
} | [
"function",
"addMethod",
"(",
"func",
",",
"name",
")",
"{",
"var",
"newMethods",
"=",
"methods",
".",
"MethodDictionary",
".",
"concat",
"(",
"_methods",
",",
"func",
",",
"name",
")",
";",
"if",
"(",
"_Entity",
")",
"{",
"_loadEntityMethod",
"(",
"func",
",",
"name",
")",
";",
"}",
"_methods",
"=",
"newMethods",
";",
"}"
] | Adds a new method to the methods in the specification.
@name module:back4app-entity/models.EntitySpecification#addMethod
@function
@param {!function} func This is the method's function to be added.
@param {!string} name This is the name of the method.
@example
entitySpecification.addMethod(
function () { return 'newMethod'; },
'newMethod'
); | [
"Adds",
"a",
"new",
"method",
"to",
"the",
"methods",
"in",
"the",
"specification",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L777-L789 | train |
crispy1989/node-zstreams | lib/mixins/_stream.js | _Stream | function _Stream(superObj) {
var self = this;
this._zSuperObj = superObj;
this._isZStream = true;
this._ignoreStreamError = false;
this._zStreamId = streamIdCounter++;
this._currentStreamChain = new StreamChain(true);
this._currentStreamChain._addStream(this);
this._zStreamRank = 0;
this.on('error', function(error) {
// If there are no other 'error' handlers on this stream, trigger a chainerror
if(self.listeners('error').length <= 1) {
self.triggerChainError(error);
}
});
} | javascript | function _Stream(superObj) {
var self = this;
this._zSuperObj = superObj;
this._isZStream = true;
this._ignoreStreamError = false;
this._zStreamId = streamIdCounter++;
this._currentStreamChain = new StreamChain(true);
this._currentStreamChain._addStream(this);
this._zStreamRank = 0;
this.on('error', function(error) {
// If there are no other 'error' handlers on this stream, trigger a chainerror
if(self.listeners('error').length <= 1) {
self.triggerChainError(error);
}
});
} | [
"function",
"_Stream",
"(",
"superObj",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"_zSuperObj",
"=",
"superObj",
";",
"this",
".",
"_isZStream",
"=",
"true",
";",
"this",
".",
"_ignoreStreamError",
"=",
"false",
";",
"this",
".",
"_zStreamId",
"=",
"streamIdCounter",
"++",
";",
"this",
".",
"_currentStreamChain",
"=",
"new",
"StreamChain",
"(",
"true",
")",
";",
"this",
".",
"_currentStreamChain",
".",
"_addStream",
"(",
"this",
")",
";",
"this",
".",
"_zStreamRank",
"=",
"0",
";",
"this",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"self",
".",
"listeners",
"(",
"'error'",
")",
".",
"length",
"<=",
"1",
")",
"{",
"self",
".",
"triggerChainError",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}"
] | Writable mixins for ZStream streams.
This class cannot be instantiated in itself. Its prototype methods must be added to the prototype
of the class it's being mixed into, and its constructor must be called from the superclass's constructor.
@class _Stream
@constructor
@param {Function} superObj - The prototype functions of the superclass the mixin is added on top of. For example, Writable.prototype or Transform.prototype. | [
"Writable",
"mixins",
"for",
"ZStream",
"streams",
"."
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/mixins/_stream.js#L16-L32 | train |
feedhenry/fh-forms | lib/impl/importForms/importFromDir.js | getFormFiles | function getFormFiles(metaDataFilePath) {
var formsZipMetaData = require(metaDataFilePath);
if (formsZipMetaData && formsZipMetaData.files) {
var formFiles = formsZipMetaData.files;
return _.map(formFiles, function(formDetails) {
return formDetails.path;
});
} else {
return [];
}
} | javascript | function getFormFiles(metaDataFilePath) {
var formsZipMetaData = require(metaDataFilePath);
if (formsZipMetaData && formsZipMetaData.files) {
var formFiles = formsZipMetaData.files;
return _.map(formFiles, function(formDetails) {
return formDetails.path;
});
} else {
return [];
}
} | [
"function",
"getFormFiles",
"(",
"metaDataFilePath",
")",
"{",
"var",
"formsZipMetaData",
"=",
"require",
"(",
"metaDataFilePath",
")",
";",
"if",
"(",
"formsZipMetaData",
"&&",
"formsZipMetaData",
".",
"files",
")",
"{",
"var",
"formFiles",
"=",
"formsZipMetaData",
".",
"files",
";",
"return",
"_",
".",
"map",
"(",
"formFiles",
",",
"function",
"(",
"formDetails",
")",
"{",
"return",
"formDetails",
".",
"path",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"[",
"]",
";",
"}",
"}"
] | Returns an array that contains the form file paths
@param {String} metaDataFilePath the path to the unzipped form meta data file
@return {Array} an array that contains the relative paths of the form files | [
"Returns",
"an",
"array",
"that",
"contains",
"the",
"form",
"file",
"paths"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/importFromDir.js#L15-L25 | train |
feedhenry/fh-forms | lib/impl/exportSubmissions.js | getStatusUpdater | function getStatusUpdater(connections, isAsync) {
return function updateExportStatus(statusUpdate, cb) {
cb = cb || _.noop;
if (isAsync) {
updateCSVExportStatus(connections, statusUpdate, cb);
} else {
return cb();
}
};
} | javascript | function getStatusUpdater(connections, isAsync) {
return function updateExportStatus(statusUpdate, cb) {
cb = cb || _.noop;
if (isAsync) {
updateCSVExportStatus(connections, statusUpdate, cb);
} else {
return cb();
}
};
} | [
"function",
"getStatusUpdater",
"(",
"connections",
",",
"isAsync",
")",
"{",
"return",
"function",
"updateExportStatus",
"(",
"statusUpdate",
",",
"cb",
")",
"{",
"cb",
"=",
"cb",
"||",
"_",
".",
"noop",
";",
"if",
"(",
"isAsync",
")",
"{",
"updateCSVExportStatus",
"(",
"connections",
",",
"statusUpdate",
",",
"cb",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
")",
";",
"}",
"}",
";",
"}"
] | Creating an updater function for export
@param connections Mongoose and mongodb connections
@param {boolean} isAsync Flag to indicated whether the CSV export is synchronous or asynchronous.
@returns {function} updateExportStatus | [
"Creating",
"an",
"updater",
"function",
"for",
"export"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L22-L31 | train |
feedhenry/fh-forms | lib/impl/exportSubmissions.js | generateQuery | function generateQuery(searchParams, cb) {
if (searchParams.query ) {
searchSubmissions.queryBuilder(searchParams.query, cb);
} else {
return cb(undefined, buildQuery(searchParams));
}
} | javascript | function generateQuery(searchParams, cb) {
if (searchParams.query ) {
searchSubmissions.queryBuilder(searchParams.query, cb);
} else {
return cb(undefined, buildQuery(searchParams));
}
} | [
"function",
"generateQuery",
"(",
"searchParams",
",",
"cb",
")",
"{",
"if",
"(",
"searchParams",
".",
"query",
")",
"{",
"searchSubmissions",
".",
"queryBuilder",
"(",
"searchParams",
".",
"query",
",",
"cb",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"undefined",
",",
"buildQuery",
"(",
"searchParams",
")",
")",
";",
"}",
"}"
] | generateQuery - Generating either a basic query or advanced search query
@param {object} searchParams params to search submissions by
@param {array} searchParams.formId Array of form IDs to search for
@param {array} searchParams.subid Array of submission IDs to search for
@param {string} searchParams.filter A string value to filter the submissions by metadata
@param {string} searchParams.query An advanced submission query object
@param {array} searchParams.appId Array of Project IDs to search for
@param {function} cb
@return {object} Generated mongo query | [
"generateQuery",
"-",
"Generating",
"either",
"a",
"basic",
"query",
"or",
"advanced",
"search",
"query"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L45-L51 | train |
feedhenry/fh-forms | lib/impl/exportSubmissions.js | buildCompositeForm | function buildCompositeForm(formSubmissionModel, formId, singleFormQuery, statusUpdaterFunction, cb) {
var mergedFields = {};
mergedFields[formId] = {};
logger.debug("buildCompositeForm start");
statusUpdaterFunction({
message: "Creating form metadata for submissions with form ID: " + formId
});
var mapReduceOptions = {
map: function() {
//The only difference will be the "lastUpdated" timestamp.
emit(this.formSubmittedAgainst.lastUpdated, this.formSubmittedAgainst); // eslint-disable-line no-undef
},
reduce: function(lastUpdatedTimestamp, formEntries) {
//Only want one of each form definition for each different timestamp
var formEntry = formEntries[0];
//Only need the pages, _id and name
if (formEntry && formEntry.pages) {
return {
_id: formEntry._id,
name: formEntry.name,
pages: formEntry.pages
};
} else {
return null;
}
},
query: singleFormQuery
};
formSubmissionModel.mapReduce(mapReduceOptions, function(err, subFormsSubmittedAgainst) {
if (err) {
logger.error("Error Using mapReduce ", err);
return cb(err);
}
statusUpdaterFunction({
message: "Finished Creating form metadata for submissions with form ID: " + formId
});
logger.debug("buildCompositeForm finish");
var formName = "";
_.each(subFormsSubmittedAgainst, function(subFormSubmittedAgainst) {
formName = formName || subFormSubmittedAgainst.value.name;
mergedFields[formId] = mergeFormFields(mergedFields[formId] || {}, subFormSubmittedAgainst.value);
});
return cb(null, mergedFields, formName);
});
} | javascript | function buildCompositeForm(formSubmissionModel, formId, singleFormQuery, statusUpdaterFunction, cb) {
var mergedFields = {};
mergedFields[formId] = {};
logger.debug("buildCompositeForm start");
statusUpdaterFunction({
message: "Creating form metadata for submissions with form ID: " + formId
});
var mapReduceOptions = {
map: function() {
//The only difference will be the "lastUpdated" timestamp.
emit(this.formSubmittedAgainst.lastUpdated, this.formSubmittedAgainst); // eslint-disable-line no-undef
},
reduce: function(lastUpdatedTimestamp, formEntries) {
//Only want one of each form definition for each different timestamp
var formEntry = formEntries[0];
//Only need the pages, _id and name
if (formEntry && formEntry.pages) {
return {
_id: formEntry._id,
name: formEntry.name,
pages: formEntry.pages
};
} else {
return null;
}
},
query: singleFormQuery
};
formSubmissionModel.mapReduce(mapReduceOptions, function(err, subFormsSubmittedAgainst) {
if (err) {
logger.error("Error Using mapReduce ", err);
return cb(err);
}
statusUpdaterFunction({
message: "Finished Creating form metadata for submissions with form ID: " + formId
});
logger.debug("buildCompositeForm finish");
var formName = "";
_.each(subFormsSubmittedAgainst, function(subFormSubmittedAgainst) {
formName = formName || subFormSubmittedAgainst.value.name;
mergedFields[formId] = mergeFormFields(mergedFields[formId] || {}, subFormSubmittedAgainst.value);
});
return cb(null, mergedFields, formName);
});
} | [
"function",
"buildCompositeForm",
"(",
"formSubmissionModel",
",",
"formId",
",",
"singleFormQuery",
",",
"statusUpdaterFunction",
",",
"cb",
")",
"{",
"var",
"mergedFields",
"=",
"{",
"}",
";",
"mergedFields",
"[",
"formId",
"]",
"=",
"{",
"}",
";",
"logger",
".",
"debug",
"(",
"\"buildCompositeForm start\"",
")",
";",
"statusUpdaterFunction",
"(",
"{",
"message",
":",
"\"Creating form metadata for submissions with form ID: \"",
"+",
"formId",
"}",
")",
";",
"var",
"mapReduceOptions",
"=",
"{",
"map",
":",
"function",
"(",
")",
"{",
"emit",
"(",
"this",
".",
"formSubmittedAgainst",
".",
"lastUpdated",
",",
"this",
".",
"formSubmittedAgainst",
")",
";",
"}",
",",
"reduce",
":",
"function",
"(",
"lastUpdatedTimestamp",
",",
"formEntries",
")",
"{",
"var",
"formEntry",
"=",
"formEntries",
"[",
"0",
"]",
";",
"if",
"(",
"formEntry",
"&&",
"formEntry",
".",
"pages",
")",
"{",
"return",
"{",
"_id",
":",
"formEntry",
".",
"_id",
",",
"name",
":",
"formEntry",
".",
"name",
",",
"pages",
":",
"formEntry",
".",
"pages",
"}",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
",",
"query",
":",
"singleFormQuery",
"}",
";",
"formSubmissionModel",
".",
"mapReduce",
"(",
"mapReduceOptions",
",",
"function",
"(",
"err",
",",
"subFormsSubmittedAgainst",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error Using mapReduce \"",
",",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"statusUpdaterFunction",
"(",
"{",
"message",
":",
"\"Finished Creating form metadata for submissions with form ID: \"",
"+",
"formId",
"}",
")",
";",
"logger",
".",
"debug",
"(",
"\"buildCompositeForm finish\"",
")",
";",
"var",
"formName",
"=",
"\"\"",
";",
"_",
".",
"each",
"(",
"subFormsSubmittedAgainst",
",",
"function",
"(",
"subFormSubmittedAgainst",
")",
"{",
"formName",
"=",
"formName",
"||",
"subFormSubmittedAgainst",
".",
"value",
".",
"name",
";",
"mergedFields",
"[",
"formId",
"]",
"=",
"mergeFormFields",
"(",
"mergedFields",
"[",
"formId",
"]",
"||",
"{",
"}",
",",
"subFormSubmittedAgainst",
".",
"value",
")",
";",
"}",
")",
";",
"return",
"cb",
"(",
"null",
",",
"mergedFields",
",",
"formName",
")",
";",
"}",
")",
";",
"}"
] | buildCompositeForm - Building a merged list of fields based on the
@param {Model} formSubmissionModel The Submission mongoose Model
@param {string} formId The ID of the form to search for
@param {object} singleFormQuery A mongo query to find all of the submissions to search for
@param {function} statusUpdaterFunction A function to update the status of an async submission export
@param {function} cb | [
"buildCompositeForm",
"-",
"Building",
"a",
"merged",
"list",
"of",
"fields",
"based",
"on",
"the"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L62-L116 | train |
feedhenry/fh-forms | lib/impl/exportSubmissions.js | buildCSVsForSingleMergedForm | function buildCSVsForSingleMergedForm(formSubmissionModel, params, cb) {
var formId = params.formId;
var formName = params.formName;
var date = params.date;
var mergedFields = params.mergedFields;
var fieldHeader = params.fieldHeader;
var singleFormQuery = params.singleFormQuery;
var downloadUrl = params.downloadUrl;
var fullSubmissionCSVString = "";
//Form Name might not be unique but the ID will always be.
var fileName = date + "-" + formId + "-" + (formName.split(' ').join('_'));
//Query the submissions for the formId
//LEAN
//Select only the metadata and formFields in the submission.
// Stream response
// Build CSV string for each entry.
// Add to the zip file.
cb = _.once(cb);
params.statusUpdaterFunction({
message: "Beginning export of submissions for form ID: " + formId
});
var exportProgressInterval = setInterval(function() {
params.statusUpdaterFunction({
message: "Exporting submission " + params.exportCounter.numSubsExported + " of " + params.exportCounter.numSubmissionsToExport
});
}, 1000);
//First, generate headers.
fullSubmissionCSVString = csvHeaders.generateCSVHeaders(_.keys(mergedFields[formId]), mergedFields[formId], fieldHeader);
var submissionQueryStream = formSubmissionModel.find(singleFormQuery).select({
"formSubmittedAgainst.pages": 0,
"formSubmittedAgainst.pageRules": 0,
"formSubmittedAgainst.fieldRules": 0
}).lean().stream();
submissionQueryStream.on('data', function addSubmissionToCSV(submissionJSON) {
//Merge the form fields
fullSubmissionCSVString += processSingleSubmission({
mergedFields: mergedFields,
submission: submissionJSON,
date: date,
fieldHeader: fieldHeader,
downloadUrl: downloadUrl
});
params.exportCounter.numSubsExported ++;
}).on('error', function(err) {
logger.error("Error streaming submissions ", err);
clearInterval(exportProgressInterval);
return cb(err);
}).on('close', function() {
clearInterval(exportProgressInterval);
return cb(undefined, {
formId: formId,
fileName: fileName,
csvString: fullSubmissionCSVString
});
});
} | javascript | function buildCSVsForSingleMergedForm(formSubmissionModel, params, cb) {
var formId = params.formId;
var formName = params.formName;
var date = params.date;
var mergedFields = params.mergedFields;
var fieldHeader = params.fieldHeader;
var singleFormQuery = params.singleFormQuery;
var downloadUrl = params.downloadUrl;
var fullSubmissionCSVString = "";
//Form Name might not be unique but the ID will always be.
var fileName = date + "-" + formId + "-" + (formName.split(' ').join('_'));
//Query the submissions for the formId
//LEAN
//Select only the metadata and formFields in the submission.
// Stream response
// Build CSV string for each entry.
// Add to the zip file.
cb = _.once(cb);
params.statusUpdaterFunction({
message: "Beginning export of submissions for form ID: " + formId
});
var exportProgressInterval = setInterval(function() {
params.statusUpdaterFunction({
message: "Exporting submission " + params.exportCounter.numSubsExported + " of " + params.exportCounter.numSubmissionsToExport
});
}, 1000);
//First, generate headers.
fullSubmissionCSVString = csvHeaders.generateCSVHeaders(_.keys(mergedFields[formId]), mergedFields[formId], fieldHeader);
var submissionQueryStream = formSubmissionModel.find(singleFormQuery).select({
"formSubmittedAgainst.pages": 0,
"formSubmittedAgainst.pageRules": 0,
"formSubmittedAgainst.fieldRules": 0
}).lean().stream();
submissionQueryStream.on('data', function addSubmissionToCSV(submissionJSON) {
//Merge the form fields
fullSubmissionCSVString += processSingleSubmission({
mergedFields: mergedFields,
submission: submissionJSON,
date: date,
fieldHeader: fieldHeader,
downloadUrl: downloadUrl
});
params.exportCounter.numSubsExported ++;
}).on('error', function(err) {
logger.error("Error streaming submissions ", err);
clearInterval(exportProgressInterval);
return cb(err);
}).on('close', function() {
clearInterval(exportProgressInterval);
return cb(undefined, {
formId: formId,
fileName: fileName,
csvString: fullSubmissionCSVString
});
});
} | [
"function",
"buildCSVsForSingleMergedForm",
"(",
"formSubmissionModel",
",",
"params",
",",
"cb",
")",
"{",
"var",
"formId",
"=",
"params",
".",
"formId",
";",
"var",
"formName",
"=",
"params",
".",
"formName",
";",
"var",
"date",
"=",
"params",
".",
"date",
";",
"var",
"mergedFields",
"=",
"params",
".",
"mergedFields",
";",
"var",
"fieldHeader",
"=",
"params",
".",
"fieldHeader",
";",
"var",
"singleFormQuery",
"=",
"params",
".",
"singleFormQuery",
";",
"var",
"downloadUrl",
"=",
"params",
".",
"downloadUrl",
";",
"var",
"fullSubmissionCSVString",
"=",
"\"\"",
";",
"var",
"fileName",
"=",
"date",
"+",
"\"-\"",
"+",
"formId",
"+",
"\"-\"",
"+",
"(",
"formName",
".",
"split",
"(",
"' '",
")",
".",
"join",
"(",
"'_'",
")",
")",
";",
"cb",
"=",
"_",
".",
"once",
"(",
"cb",
")",
";",
"params",
".",
"statusUpdaterFunction",
"(",
"{",
"message",
":",
"\"Beginning export of submissions for form ID: \"",
"+",
"formId",
"}",
")",
";",
"var",
"exportProgressInterval",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"params",
".",
"statusUpdaterFunction",
"(",
"{",
"message",
":",
"\"Exporting submission \"",
"+",
"params",
".",
"exportCounter",
".",
"numSubsExported",
"+",
"\" of \"",
"+",
"params",
".",
"exportCounter",
".",
"numSubmissionsToExport",
"}",
")",
";",
"}",
",",
"1000",
")",
";",
"fullSubmissionCSVString",
"=",
"csvHeaders",
".",
"generateCSVHeaders",
"(",
"_",
".",
"keys",
"(",
"mergedFields",
"[",
"formId",
"]",
")",
",",
"mergedFields",
"[",
"formId",
"]",
",",
"fieldHeader",
")",
";",
"var",
"submissionQueryStream",
"=",
"formSubmissionModel",
".",
"find",
"(",
"singleFormQuery",
")",
".",
"select",
"(",
"{",
"\"formSubmittedAgainst.pages\"",
":",
"0",
",",
"\"formSubmittedAgainst.pageRules\"",
":",
"0",
",",
"\"formSubmittedAgainst.fieldRules\"",
":",
"0",
"}",
")",
".",
"lean",
"(",
")",
".",
"stream",
"(",
")",
";",
"submissionQueryStream",
".",
"on",
"(",
"'data'",
",",
"function",
"addSubmissionToCSV",
"(",
"submissionJSON",
")",
"{",
"fullSubmissionCSVString",
"+=",
"processSingleSubmission",
"(",
"{",
"mergedFields",
":",
"mergedFields",
",",
"submission",
":",
"submissionJSON",
",",
"date",
":",
"date",
",",
"fieldHeader",
":",
"fieldHeader",
",",
"downloadUrl",
":",
"downloadUrl",
"}",
")",
";",
"params",
".",
"exportCounter",
".",
"numSubsExported",
"++",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error streaming submissions \"",
",",
"err",
")",
";",
"clearInterval",
"(",
"exportProgressInterval",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"clearInterval",
"(",
"exportProgressInterval",
")",
";",
"return",
"cb",
"(",
"undefined",
",",
"{",
"formId",
":",
"formId",
",",
"fileName",
":",
"fileName",
",",
"csvString",
":",
"fullSubmissionCSVString",
"}",
")",
";",
"}",
")",
";",
"}"
] | buildCSVsForSingleMergedForm - Building a CSV representation of a submission based on the merged definiton of all of the versions of the form it was submitted against.
@param {Model} formSubmissionModel The Submission mongoose Model
@param {type} params
@param {string} params.formId
@param {function} params.statusUpdaterFunction Function to update the status of a submission export.
@param {string} params.date Formatted date of export
@param {string} params.formName Form Name
@param {object} params.mergedFields Set of merged field definitions
@param {string} params.fieldHeader Field header to use for export
@param {object} params.singleFormQuery Query to search for submissions based in a form ID
@param {number} params.exportCounter.numSubmissionsToExport The total number of submissions to export
@param {number} params.exportCounter.numSubsExported The total number of submissions exported to date
@param {string} params.downloadUrl The downloadUrl template to use when generating submission file URLs.
@param {function} cb | [
"buildCSVsForSingleMergedForm",
"-",
"Building",
"a",
"CSV",
"representation",
"of",
"a",
"submission",
"based",
"on",
"the",
"merged",
"definiton",
"of",
"all",
"of",
"the",
"versions",
"of",
"the",
"form",
"it",
"was",
"submitted",
"against",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L136-L198 | train |
feedhenry/fh-forms | lib/impl/exportSubmissions.js | buildCSVsForSingleForm | function buildCSVsForSingleForm(formSubmissionModel, params, formId, callback) {
logger.debug("buildCSVsForSingleForm", params, formId);
var date = params.date;
var searchParams = params.searchParams || {};
var fieldHeader = searchParams.fieldHeader;
var downloadUrl = searchParams.downloadUrl || "";
formId = formId.toString();
params.statusUpdaterFunction({
message: "Starting export of submissions for form with ID:" + formId
});
generateQuery(_.defaults({
formId: formId
}, searchParams), function(err, singleFormQuery) {
if (err) {
return callback(err);
}
async.waterfall([
async.apply(buildCompositeForm, formSubmissionModel, formId, singleFormQuery, params.statusUpdaterFunction),
function buildSubmissionCSVForSingleForm(mergedFields, formName, cb) {
buildCSVsForSingleMergedForm(formSubmissionModel, {
date: date,
fieldHeader: fieldHeader,
downloadUrl: downloadUrl,
mergedFields: mergedFields,
formName: formName,
formId: formId,
exportCounter: params.exportCounter,
singleFormQuery: singleFormQuery,
statusUpdaterFunction: params.statusUpdaterFunction
}, cb);
}
], callback);
});
} | javascript | function buildCSVsForSingleForm(formSubmissionModel, params, formId, callback) {
logger.debug("buildCSVsForSingleForm", params, formId);
var date = params.date;
var searchParams = params.searchParams || {};
var fieldHeader = searchParams.fieldHeader;
var downloadUrl = searchParams.downloadUrl || "";
formId = formId.toString();
params.statusUpdaterFunction({
message: "Starting export of submissions for form with ID:" + formId
});
generateQuery(_.defaults({
formId: formId
}, searchParams), function(err, singleFormQuery) {
if (err) {
return callback(err);
}
async.waterfall([
async.apply(buildCompositeForm, formSubmissionModel, formId, singleFormQuery, params.statusUpdaterFunction),
function buildSubmissionCSVForSingleForm(mergedFields, formName, cb) {
buildCSVsForSingleMergedForm(formSubmissionModel, {
date: date,
fieldHeader: fieldHeader,
downloadUrl: downloadUrl,
mergedFields: mergedFields,
formName: formName,
formId: formId,
exportCounter: params.exportCounter,
singleFormQuery: singleFormQuery,
statusUpdaterFunction: params.statusUpdaterFunction
}, cb);
}
], callback);
});
} | [
"function",
"buildCSVsForSingleForm",
"(",
"formSubmissionModel",
",",
"params",
",",
"formId",
",",
"callback",
")",
"{",
"logger",
".",
"debug",
"(",
"\"buildCSVsForSingleForm\"",
",",
"params",
",",
"formId",
")",
";",
"var",
"date",
"=",
"params",
".",
"date",
";",
"var",
"searchParams",
"=",
"params",
".",
"searchParams",
"||",
"{",
"}",
";",
"var",
"fieldHeader",
"=",
"searchParams",
".",
"fieldHeader",
";",
"var",
"downloadUrl",
"=",
"searchParams",
".",
"downloadUrl",
"||",
"\"\"",
";",
"formId",
"=",
"formId",
".",
"toString",
"(",
")",
";",
"params",
".",
"statusUpdaterFunction",
"(",
"{",
"message",
":",
"\"Starting export of submissions for form with ID:\"",
"+",
"formId",
"}",
")",
";",
"generateQuery",
"(",
"_",
".",
"defaults",
"(",
"{",
"formId",
":",
"formId",
"}",
",",
"searchParams",
")",
",",
"function",
"(",
"err",
",",
"singleFormQuery",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"async",
".",
"waterfall",
"(",
"[",
"async",
".",
"apply",
"(",
"buildCompositeForm",
",",
"formSubmissionModel",
",",
"formId",
",",
"singleFormQuery",
",",
"params",
".",
"statusUpdaterFunction",
")",
",",
"function",
"buildSubmissionCSVForSingleForm",
"(",
"mergedFields",
",",
"formName",
",",
"cb",
")",
"{",
"buildCSVsForSingleMergedForm",
"(",
"formSubmissionModel",
",",
"{",
"date",
":",
"date",
",",
"fieldHeader",
":",
"fieldHeader",
",",
"downloadUrl",
":",
"downloadUrl",
",",
"mergedFields",
":",
"mergedFields",
",",
"formName",
":",
"formName",
",",
"formId",
":",
"formId",
",",
"exportCounter",
":",
"params",
".",
"exportCounter",
",",
"singleFormQuery",
":",
"singleFormQuery",
",",
"statusUpdaterFunction",
":",
"params",
".",
"statusUpdaterFunction",
"}",
",",
"cb",
")",
";",
"}",
"]",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | buildCSVsForSingleForm - Generating the full CSV file for a single form.
@param {Model} formSubmissionModel description
@param {object} params
@param {function} params.statusUpdaterFunction Function to update the status of the export.
@param {string} params.formId
@param {string} params.date Formatted date of export
@param {object} params.searchParams Submission Parameters To Search By
@param {array} params.searchParams.formId Array of form IDs to search for
@param {array} params.searchParams.subid Array of submission IDs to search for
@param {string} params.searchParams.filter A string value to filter the submissions by metadata
@param {array} params.searchParams.appId Array of Project IDs to search for
@param {string} params.searchParams.fieldHeader Field header to use (fieldName or fieldCode)
@param {string} params.searchParams.downloadUrl URL to use for file downloads
@param {number} params.exportCounter.numSubmissionsToExport The total number of submissions to export
@param {number} params.exportCounter.numSubsExported The total number of submissions exported to date
@param {string} formId The ID of the form to export
@param {function} callback
@return {type} | [
"buildCSVsForSingleForm",
"-",
"Generating",
"the",
"full",
"CSV",
"file",
"for",
"a",
"single",
"form",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L221-L259 | train |
crispy1989/node-zstreams | lib/writable.js | ZWritable | function ZWritable(options) {
if(options) {
if(options.writableObjectMode) {
options.objectMode = true;
}
//Add support for iojs simplified stream constructor
if(typeof options.write === 'function') {
this._write = options.write;
}
if(typeof options.flush === 'function') {
this._flush = options.flush;
}
}
Transform.call(this, options);
streamMixins.call(this, Transform.prototype, options);
writableMixins.call(this, options);
} | javascript | function ZWritable(options) {
if(options) {
if(options.writableObjectMode) {
options.objectMode = true;
}
//Add support for iojs simplified stream constructor
if(typeof options.write === 'function') {
this._write = options.write;
}
if(typeof options.flush === 'function') {
this._flush = options.flush;
}
}
Transform.call(this, options);
streamMixins.call(this, Transform.prototype, options);
writableMixins.call(this, options);
} | [
"function",
"ZWritable",
"(",
"options",
")",
"{",
"if",
"(",
"options",
")",
"{",
"if",
"(",
"options",
".",
"writableObjectMode",
")",
"{",
"options",
".",
"objectMode",
"=",
"true",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"write",
"===",
"'function'",
")",
"{",
"this",
".",
"_write",
"=",
"options",
".",
"write",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"flush",
"===",
"'function'",
")",
"{",
"this",
".",
"_flush",
"=",
"options",
".",
"flush",
";",
"}",
"}",
"Transform",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"streamMixins",
".",
"call",
"(",
"this",
",",
"Transform",
".",
"prototype",
",",
"options",
")",
";",
"writableMixins",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"}"
] | ZWritable implements the Writable stream interface with the _write function.
ZWritable also accepts a `_flush` function to facilitate cleanup.
@class ZWritable
@constructor
@extends Transform
@uses _Stream
@uses _Writable
@param {Object} [options] - Stream options | [
"ZWritable",
"implements",
"the",
"Writable",
"stream",
"interface",
"with",
"the",
"_write",
"function",
".",
"ZWritable",
"also",
"accepts",
"a",
"_flush",
"function",
"to",
"facilitate",
"cleanup",
"."
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/writable.js#L18-L35 | train |
feedhenry/fh-forms | lib/impl/dataSources/checkUpdateInterval.js | needsAnUpdate | function needsAnUpdate(dataSource, currentTime) {
//The last time the Data Source was refreshed
var lastRefreshedMs = new Date(dataSource.cache[0].lastRefreshed).valueOf();
currentTime = new Date(currentTime);
var conf = config.get();
var defaults = config.defaults();
//The number of minutes between backoffs
var minsPerBackOffIndex = conf.minsPerBackOffIndex || defaults.minsPerBackOffIndex;
//The number of milliseconds to wait until the Data Source needs to be refreshed.
var refreshIntervalMs = dataSource.refreshInterval * MIN_MS;
var backOffIndex = dataSource.cache[0].backOffIndex || 0;
//The number of milliseconds to wait because of backing off from errors.
var backOffMs = backOffIndex * (minsPerBackOffIndex * MIN_MS);
//Will only wait a max of a week between failed updates.
backOffMs = Math.min(backOffMs, conf.dsMaxIntervalMs || defaults.dsMaxIntervalMs);
//The next time the Data Source will refresh will either be normal interval or the backOff interval, whichever is the largest.
var nextRefreshMs = Math.max(refreshIntervalMs, backOffMs);
//Checking if the total of the three times is <= currentTime. If it is, then the data source should try to update.
return new Date(lastRefreshedMs + nextRefreshMs) <= currentTime;
} | javascript | function needsAnUpdate(dataSource, currentTime) {
//The last time the Data Source was refreshed
var lastRefreshedMs = new Date(dataSource.cache[0].lastRefreshed).valueOf();
currentTime = new Date(currentTime);
var conf = config.get();
var defaults = config.defaults();
//The number of minutes between backoffs
var minsPerBackOffIndex = conf.minsPerBackOffIndex || defaults.minsPerBackOffIndex;
//The number of milliseconds to wait until the Data Source needs to be refreshed.
var refreshIntervalMs = dataSource.refreshInterval * MIN_MS;
var backOffIndex = dataSource.cache[0].backOffIndex || 0;
//The number of milliseconds to wait because of backing off from errors.
var backOffMs = backOffIndex * (minsPerBackOffIndex * MIN_MS);
//Will only wait a max of a week between failed updates.
backOffMs = Math.min(backOffMs, conf.dsMaxIntervalMs || defaults.dsMaxIntervalMs);
//The next time the Data Source will refresh will either be normal interval or the backOff interval, whichever is the largest.
var nextRefreshMs = Math.max(refreshIntervalMs, backOffMs);
//Checking if the total of the three times is <= currentTime. If it is, then the data source should try to update.
return new Date(lastRefreshedMs + nextRefreshMs) <= currentTime;
} | [
"function",
"needsAnUpdate",
"(",
"dataSource",
",",
"currentTime",
")",
"{",
"var",
"lastRefreshedMs",
"=",
"new",
"Date",
"(",
"dataSource",
".",
"cache",
"[",
"0",
"]",
".",
"lastRefreshed",
")",
".",
"valueOf",
"(",
")",
";",
"currentTime",
"=",
"new",
"Date",
"(",
"currentTime",
")",
";",
"var",
"conf",
"=",
"config",
".",
"get",
"(",
")",
";",
"var",
"defaults",
"=",
"config",
".",
"defaults",
"(",
")",
";",
"var",
"minsPerBackOffIndex",
"=",
"conf",
".",
"minsPerBackOffIndex",
"||",
"defaults",
".",
"minsPerBackOffIndex",
";",
"var",
"refreshIntervalMs",
"=",
"dataSource",
".",
"refreshInterval",
"*",
"MIN_MS",
";",
"var",
"backOffIndex",
"=",
"dataSource",
".",
"cache",
"[",
"0",
"]",
".",
"backOffIndex",
"||",
"0",
";",
"var",
"backOffMs",
"=",
"backOffIndex",
"*",
"(",
"minsPerBackOffIndex",
"*",
"MIN_MS",
")",
";",
"backOffMs",
"=",
"Math",
".",
"min",
"(",
"backOffMs",
",",
"conf",
".",
"dsMaxIntervalMs",
"||",
"defaults",
".",
"dsMaxIntervalMs",
")",
";",
"var",
"nextRefreshMs",
"=",
"Math",
".",
"max",
"(",
"refreshIntervalMs",
",",
"backOffMs",
")",
";",
"return",
"new",
"Date",
"(",
"lastRefreshedMs",
"+",
"nextRefreshMs",
")",
"<=",
"currentTime",
";",
"}"
] | needsAnUpdate - Comparing the current time to when the data source needs to be updated.
The backoff calculation is based on the assumption that
- update fails: wait 1 interval
- update fails again: wait 2 intervals
- update fails again: wait 3 interval
...
...
...
- update fails again: wait a max of a week between refreshes
@param {object} dataSource A data source to check
@param {date} currentTime The time to scan for
@param {number} minsPerBackOffIndex The number of minutes to back-off per backOff interval
@return {boolean} true/false | [
"needsAnUpdate",
"-",
"Comparing",
"the",
"current",
"time",
"to",
"when",
"the",
"data",
"source",
"needs",
"to",
"be",
"updated",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/checkUpdateInterval.js#L23-L48 | train |
feedhenry/fh-forms | lib/impl/deleteTheme.js | validateThemeNotInUseByApps | function validateThemeNotInUseByApps(cb) {
var appThemeModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_THEMES);
appThemeModel.count({"theme" : options._id}, function(err, countAppsUsingTheme) {
if (err) {
return cb(err);
}
if (countAppsUsingTheme > 0) {
return cb(new Error("Cannot delete theme in use by apps. Apps Using this theme" + countAppsUsingTheme));
}
return cb();
});
} | javascript | function validateThemeNotInUseByApps(cb) {
var appThemeModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_THEMES);
appThemeModel.count({"theme" : options._id}, function(err, countAppsUsingTheme) {
if (err) {
return cb(err);
}
if (countAppsUsingTheme > 0) {
return cb(new Error("Cannot delete theme in use by apps. Apps Using this theme" + countAppsUsingTheme));
}
return cb();
});
} | [
"function",
"validateThemeNotInUseByApps",
"(",
"cb",
")",
"{",
"var",
"appThemeModel",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"APP_THEMES",
")",
";",
"appThemeModel",
".",
"count",
"(",
"{",
"\"theme\"",
":",
"options",
".",
"_id",
"}",
",",
"function",
"(",
"err",
",",
"countAppsUsingTheme",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"if",
"(",
"countAppsUsingTheme",
">",
"0",
")",
"{",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"Cannot delete theme in use by apps. Apps Using this theme\"",
"+",
"countAppsUsingTheme",
")",
")",
";",
"}",
"return",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
] | Themes associated with app should not be deleted. | [
"Themes",
"associated",
"with",
"app",
"should",
"not",
"be",
"deleted",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/deleteTheme.js#L26-L40 | train |
cloudfour/drizzle-builder | src/helpers/pattern.js | registerPatternHelpers | function registerPatternHelpers(options) {
const Handlebars = options.handlebars;
if (Handlebars.helpers.pattern) {
DrizzleError.error(
new DrizzleError(
'`pattern` helper already registered',
DrizzleError.LEVELS.WARN
),
options.debug
);
}
/**
* The `pattern` helper allows the embedding of patterns anywhere
* and they can get their correct local context.
*/
Handlebars.registerHelper('pattern', (id, rootContext, opts) => {
const renderedTemplate = renderPatternPartial(
id,
rootContext.drizzle,
Handlebars
);
return renderedTemplate;
});
if (Handlebars.helpers.patternSource) {
DrizzleError.error(
new DrizzleError(
'`patternSource` helper already registered',
DrizzleError.LEVELS.WARN
),
options.debug
);
}
/**
* Similar to `pattern` but the returned string is HTML-escaped.
* Can be used for rendering source in `<pre>` tags.
*/
Handlebars.registerHelper('patternSource', (id, rootContext, opts) => {
const renderedTemplate = renderPatternPartial(
id,
rootContext.drizzle,
Handlebars
);
const sourceMarkup = beautify(renderedTemplate, options.beautifier);
return Handlebars.Utils.escapeExpression(sourceMarkup);
});
return Handlebars;
} | javascript | function registerPatternHelpers(options) {
const Handlebars = options.handlebars;
if (Handlebars.helpers.pattern) {
DrizzleError.error(
new DrizzleError(
'`pattern` helper already registered',
DrizzleError.LEVELS.WARN
),
options.debug
);
}
/**
* The `pattern` helper allows the embedding of patterns anywhere
* and they can get their correct local context.
*/
Handlebars.registerHelper('pattern', (id, rootContext, opts) => {
const renderedTemplate = renderPatternPartial(
id,
rootContext.drizzle,
Handlebars
);
return renderedTemplate;
});
if (Handlebars.helpers.patternSource) {
DrizzleError.error(
new DrizzleError(
'`patternSource` helper already registered',
DrizzleError.LEVELS.WARN
),
options.debug
);
}
/**
* Similar to `pattern` but the returned string is HTML-escaped.
* Can be used for rendering source in `<pre>` tags.
*/
Handlebars.registerHelper('patternSource', (id, rootContext, opts) => {
const renderedTemplate = renderPatternPartial(
id,
rootContext.drizzle,
Handlebars
);
const sourceMarkup = beautify(renderedTemplate, options.beautifier);
return Handlebars.Utils.escapeExpression(sourceMarkup);
});
return Handlebars;
} | [
"function",
"registerPatternHelpers",
"(",
"options",
")",
"{",
"const",
"Handlebars",
"=",
"options",
".",
"handlebars",
";",
"if",
"(",
"Handlebars",
".",
"helpers",
".",
"pattern",
")",
"{",
"DrizzleError",
".",
"error",
"(",
"new",
"DrizzleError",
"(",
"'`pattern` helper already registered'",
",",
"DrizzleError",
".",
"LEVELS",
".",
"WARN",
")",
",",
"options",
".",
"debug",
")",
";",
"}",
"Handlebars",
".",
"registerHelper",
"(",
"'pattern'",
",",
"(",
"id",
",",
"rootContext",
",",
"opts",
")",
"=>",
"{",
"const",
"renderedTemplate",
"=",
"renderPatternPartial",
"(",
"id",
",",
"rootContext",
".",
"drizzle",
",",
"Handlebars",
")",
";",
"return",
"renderedTemplate",
";",
"}",
")",
";",
"if",
"(",
"Handlebars",
".",
"helpers",
".",
"patternSource",
")",
"{",
"DrizzleError",
".",
"error",
"(",
"new",
"DrizzleError",
"(",
"'`patternSource` helper already registered'",
",",
"DrizzleError",
".",
"LEVELS",
".",
"WARN",
")",
",",
"options",
".",
"debug",
")",
";",
"}",
"Handlebars",
".",
"registerHelper",
"(",
"'patternSource'",
",",
"(",
"id",
",",
"rootContext",
",",
"opts",
")",
"=>",
"{",
"const",
"renderedTemplate",
"=",
"renderPatternPartial",
"(",
"id",
",",
"rootContext",
".",
"drizzle",
",",
"Handlebars",
")",
";",
"const",
"sourceMarkup",
"=",
"beautify",
"(",
"renderedTemplate",
",",
"options",
".",
"beautifier",
")",
";",
"return",
"Handlebars",
".",
"Utils",
".",
"escapeExpression",
"(",
"sourceMarkup",
")",
";",
"}",
")",
";",
"return",
"Handlebars",
";",
"}"
] | Register some drizzle-specific pattern helpers | [
"Register",
"some",
"drizzle",
"-",
"specific",
"pattern",
"helpers"
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/helpers/pattern.js#L34-L81 | train |
feedhenry/fh-forms | lib/middleware/dataSources.js | deploy | function deploy(req, res, next) {
var dataSource = req.body;
dataSource._id = req.params.id;
forms.dataSources.deploy(req.connectionOptions, dataSource, dataSourcesHandler(constants.resultTypes.dataSources, req, next));
} | javascript | function deploy(req, res, next) {
var dataSource = req.body;
dataSource._id = req.params.id;
forms.dataSources.deploy(req.connectionOptions, dataSource, dataSourcesHandler(constants.resultTypes.dataSources, req, next));
} | [
"function",
"deploy",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"dataSource",
"=",
"req",
".",
"body",
";",
"dataSource",
".",
"_id",
"=",
"req",
".",
"params",
".",
"id",
";",
"forms",
".",
"dataSources",
".",
"deploy",
"(",
"req",
".",
"connectionOptions",
",",
"dataSource",
",",
"dataSourcesHandler",
"(",
"constants",
".",
"resultTypes",
".",
"dataSources",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Deploying A Data Source. This will update if already exists or create one if not.
@param req
@param res
@param next | [
"Deploying",
"A",
"Data",
"Source",
".",
"This",
"will",
"update",
"if",
"already",
"exists",
"or",
"create",
"one",
"if",
"not",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/dataSources.js#L53-L59 | train |
stackgl/gl-shader-core | lib/reflect.js | makeReflectTypes | function makeReflectTypes(uniforms, useIndex) {
var obj = {}
for(var i=0; i<uniforms.length; ++i) {
var n = uniforms[i].name
var parts = n.split(".")
var o = obj
for(var j=0; j<parts.length; ++j) {
var x = parts[j].split("[")
if(x.length > 1) {
if(!(x[0] in o)) {
o[x[0]] = []
}
o = o[x[0]]
for(var k=1; k<x.length; ++k) {
var y = parseInt(x[k])
if(k<x.length-1 || j<parts.length-1) {
if(!(y in o)) {
if(k < x.length-1) {
o[y] = []
} else {
o[y] = {}
}
}
o = o[y]
} else {
if(useIndex) {
o[y] = i
} else {
o[y] = uniforms[i].type
}
}
}
} else if(j < parts.length-1) {
if(!(x[0] in o)) {
o[x[0]] = {}
}
o = o[x[0]]
} else {
if(useIndex) {
o[x[0]] = i
} else {
o[x[0]] = uniforms[i].type
}
}
}
}
return obj
} | javascript | function makeReflectTypes(uniforms, useIndex) {
var obj = {}
for(var i=0; i<uniforms.length; ++i) {
var n = uniforms[i].name
var parts = n.split(".")
var o = obj
for(var j=0; j<parts.length; ++j) {
var x = parts[j].split("[")
if(x.length > 1) {
if(!(x[0] in o)) {
o[x[0]] = []
}
o = o[x[0]]
for(var k=1; k<x.length; ++k) {
var y = parseInt(x[k])
if(k<x.length-1 || j<parts.length-1) {
if(!(y in o)) {
if(k < x.length-1) {
o[y] = []
} else {
o[y] = {}
}
}
o = o[y]
} else {
if(useIndex) {
o[y] = i
} else {
o[y] = uniforms[i].type
}
}
}
} else if(j < parts.length-1) {
if(!(x[0] in o)) {
o[x[0]] = {}
}
o = o[x[0]]
} else {
if(useIndex) {
o[x[0]] = i
} else {
o[x[0]] = uniforms[i].type
}
}
}
}
return obj
} | [
"function",
"makeReflectTypes",
"(",
"uniforms",
",",
"useIndex",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"uniforms",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"n",
"=",
"uniforms",
"[",
"i",
"]",
".",
"name",
"var",
"parts",
"=",
"n",
".",
"split",
"(",
"\".\"",
")",
"var",
"o",
"=",
"obj",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"parts",
".",
"length",
";",
"++",
"j",
")",
"{",
"var",
"x",
"=",
"parts",
"[",
"j",
"]",
".",
"split",
"(",
"\"[\"",
")",
"if",
"(",
"x",
".",
"length",
">",
"1",
")",
"{",
"if",
"(",
"!",
"(",
"x",
"[",
"0",
"]",
"in",
"o",
")",
")",
"{",
"o",
"[",
"x",
"[",
"0",
"]",
"]",
"=",
"[",
"]",
"}",
"o",
"=",
"o",
"[",
"x",
"[",
"0",
"]",
"]",
"for",
"(",
"var",
"k",
"=",
"1",
";",
"k",
"<",
"x",
".",
"length",
";",
"++",
"k",
")",
"{",
"var",
"y",
"=",
"parseInt",
"(",
"x",
"[",
"k",
"]",
")",
"if",
"(",
"k",
"<",
"x",
".",
"length",
"-",
"1",
"||",
"j",
"<",
"parts",
".",
"length",
"-",
"1",
")",
"{",
"if",
"(",
"!",
"(",
"y",
"in",
"o",
")",
")",
"{",
"if",
"(",
"k",
"<",
"x",
".",
"length",
"-",
"1",
")",
"{",
"o",
"[",
"y",
"]",
"=",
"[",
"]",
"}",
"else",
"{",
"o",
"[",
"y",
"]",
"=",
"{",
"}",
"}",
"}",
"o",
"=",
"o",
"[",
"y",
"]",
"}",
"else",
"{",
"if",
"(",
"useIndex",
")",
"{",
"o",
"[",
"y",
"]",
"=",
"i",
"}",
"else",
"{",
"o",
"[",
"y",
"]",
"=",
"uniforms",
"[",
"i",
"]",
".",
"type",
"}",
"}",
"}",
"}",
"else",
"if",
"(",
"j",
"<",
"parts",
".",
"length",
"-",
"1",
")",
"{",
"if",
"(",
"!",
"(",
"x",
"[",
"0",
"]",
"in",
"o",
")",
")",
"{",
"o",
"[",
"x",
"[",
"0",
"]",
"]",
"=",
"{",
"}",
"}",
"o",
"=",
"o",
"[",
"x",
"[",
"0",
"]",
"]",
"}",
"else",
"{",
"if",
"(",
"useIndex",
")",
"{",
"o",
"[",
"x",
"[",
"0",
"]",
"]",
"=",
"i",
"}",
"else",
"{",
"o",
"[",
"x",
"[",
"0",
"]",
"]",
"=",
"uniforms",
"[",
"i",
"]",
".",
"type",
"}",
"}",
"}",
"}",
"return",
"obj",
"}"
] | Construct type info for reflection. This iterates over the flattened list of uniform type values and smashes them into a JSON object. The leaves of the resulting object are either indices or type strings representing primitive glslify types | [
"Construct",
"type",
"info",
"for",
"reflection",
".",
"This",
"iterates",
"over",
"the",
"flattened",
"list",
"of",
"uniform",
"type",
"values",
"and",
"smashes",
"them",
"into",
"a",
"JSON",
"object",
".",
"The",
"leaves",
"of",
"the",
"resulting",
"object",
"are",
"either",
"indices",
"or",
"type",
"strings",
"representing",
"primitive",
"glslify",
"types"
] | 25e021e9239ad7b73ce08ff0fdc97e2e68e1d075 | https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/lib/reflect.js#L10-L57 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | getRequestFileParameters | function getRequestFileParameters(req, res, next) {
//A valid getForms request must have an appId parameter set
var submitFileParams = {};
submitFileParams.fileDetails = {};
//Get the content body for normal parameter
var filesInRequest = req.files;
if (_.size(filesInRequest) === 0) {
logger.error("Middleware: getRequestFileParameters, Expected A File To Have Been Sent ", {params: req.params});
return next(new Error("Expected A File To Have Been Submitted"));
}
var fileDetails = _.map(filesInRequest, function(fileValue) {
return fileValue;
});
fileDetails = _.first(fileDetails);
logger.debug("Middleware: getRequestFileParameters ", {fileDetails: fileDetails, body: req.body});
submitFileParams.fileDetails = {
fileStream: fileDetails.path,
fileName: fileDetails.originalname || fileDetails.name,
fileType: fileDetails.mimetype,
fileSize: fileDetails.size
};
req.appformsResultPayload = {
data: submitFileParams,
type: constants.resultTypes.submissions
};
logger.debug("Middleware: getRequestFileParameters ", {params: req.appformsResultPayload});
return next();
} | javascript | function getRequestFileParameters(req, res, next) {
//A valid getForms request must have an appId parameter set
var submitFileParams = {};
submitFileParams.fileDetails = {};
//Get the content body for normal parameter
var filesInRequest = req.files;
if (_.size(filesInRequest) === 0) {
logger.error("Middleware: getRequestFileParameters, Expected A File To Have Been Sent ", {params: req.params});
return next(new Error("Expected A File To Have Been Submitted"));
}
var fileDetails = _.map(filesInRequest, function(fileValue) {
return fileValue;
});
fileDetails = _.first(fileDetails);
logger.debug("Middleware: getRequestFileParameters ", {fileDetails: fileDetails, body: req.body});
submitFileParams.fileDetails = {
fileStream: fileDetails.path,
fileName: fileDetails.originalname || fileDetails.name,
fileType: fileDetails.mimetype,
fileSize: fileDetails.size
};
req.appformsResultPayload = {
data: submitFileParams,
type: constants.resultTypes.submissions
};
logger.debug("Middleware: getRequestFileParameters ", {params: req.appformsResultPayload});
return next();
} | [
"function",
"getRequestFileParameters",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"submitFileParams",
"=",
"{",
"}",
";",
"submitFileParams",
".",
"fileDetails",
"=",
"{",
"}",
";",
"var",
"filesInRequest",
"=",
"req",
".",
"files",
";",
"if",
"(",
"_",
".",
"size",
"(",
"filesInRequest",
")",
"===",
"0",
")",
"{",
"logger",
".",
"error",
"(",
"\"Middleware: getRequestFileParameters, Expected A File To Have Been Sent \"",
",",
"{",
"params",
":",
"req",
".",
"params",
"}",
")",
";",
"return",
"next",
"(",
"new",
"Error",
"(",
"\"Expected A File To Have Been Submitted\"",
")",
")",
";",
"}",
"var",
"fileDetails",
"=",
"_",
".",
"map",
"(",
"filesInRequest",
",",
"function",
"(",
"fileValue",
")",
"{",
"return",
"fileValue",
";",
"}",
")",
";",
"fileDetails",
"=",
"_",
".",
"first",
"(",
"fileDetails",
")",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: getRequestFileParameters \"",
",",
"{",
"fileDetails",
":",
"fileDetails",
",",
"body",
":",
"req",
".",
"body",
"}",
")",
";",
"submitFileParams",
".",
"fileDetails",
"=",
"{",
"fileStream",
":",
"fileDetails",
".",
"path",
",",
"fileName",
":",
"fileDetails",
".",
"originalname",
"||",
"fileDetails",
".",
"name",
",",
"fileType",
":",
"fileDetails",
".",
"mimetype",
",",
"fileSize",
":",
"fileDetails",
".",
"size",
"}",
";",
"req",
".",
"appformsResultPayload",
"=",
"{",
"data",
":",
"submitFileParams",
",",
"type",
":",
"constants",
".",
"resultTypes",
".",
"submissions",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: getRequestFileParameters \"",
",",
"{",
"params",
":",
"req",
".",
"appformsResultPayload",
"}",
")",
";",
"return",
"next",
"(",
")",
";",
"}"
] | Middleware For Populating File Parameters From A Multipart Request
Used For Updating Submission Files
@param req
@param res
@returns next | [
"Middleware",
"For",
"Populating",
"File",
"Parameters",
"From",
"A",
"Multipart",
"Request"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L30-L66 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | list | function list(req, res, next) {
logger.debug("Middleware Submissions List ", {connectionOptions: req.connectionOptions});
forms.getSubmissions(req.connectionOptions, {}, _getSubmissionsResultHandler(req, next));
} | javascript | function list(req, res, next) {
logger.debug("Middleware Submissions List ", {connectionOptions: req.connectionOptions});
forms.getSubmissions(req.connectionOptions, {}, _getSubmissionsResultHandler(req, next));
} | [
"function",
"list",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Middleware Submissions List \"",
",",
"{",
"connectionOptions",
":",
"req",
".",
"connectionOptions",
"}",
")",
";",
"forms",
".",
"getSubmissions",
"(",
"req",
".",
"connectionOptions",
",",
"{",
"}",
",",
"_getSubmissionsResultHandler",
"(",
"req",
",",
"next",
")",
")",
";",
"}"
] | List All Submissions
@param req
@param res
@param next | [
"List",
"All",
"Submissions"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L75-L78 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | listProjectSubmissions | function listProjectSubmissions(req, res, next) {
var formId = req.body.formId;
var subIds = req.body.subid;
var params = {
wantRestrictions: false,
appId: req.params.projectid
};
//Assigning Form Search If Set
if (_.isString(formId)) {
params.formId = formId;
}
//Assigning Submission Search Params If Set
if (_.isArray(subIds)) {
params.subid = subIds;
} else if (_.isString(subIds)) {
params.subid = [subIds];
}
logger.debug("Middleware listProjectSubmissions ", {params: params});
forms.getSubmissions(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next));
} | javascript | function listProjectSubmissions(req, res, next) {
var formId = req.body.formId;
var subIds = req.body.subid;
var params = {
wantRestrictions: false,
appId: req.params.projectid
};
//Assigning Form Search If Set
if (_.isString(formId)) {
params.formId = formId;
}
//Assigning Submission Search Params If Set
if (_.isArray(subIds)) {
params.subid = subIds;
} else if (_.isString(subIds)) {
params.subid = [subIds];
}
logger.debug("Middleware listProjectSubmissions ", {params: params});
forms.getSubmissions(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next));
} | [
"function",
"listProjectSubmissions",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"formId",
"=",
"req",
".",
"body",
".",
"formId",
";",
"var",
"subIds",
"=",
"req",
".",
"body",
".",
"subid",
";",
"var",
"params",
"=",
"{",
"wantRestrictions",
":",
"false",
",",
"appId",
":",
"req",
".",
"params",
".",
"projectid",
"}",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"formId",
")",
")",
"{",
"params",
".",
"formId",
"=",
"formId",
";",
"}",
"if",
"(",
"_",
".",
"isArray",
"(",
"subIds",
")",
")",
"{",
"params",
".",
"subid",
"=",
"subIds",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isString",
"(",
"subIds",
")",
")",
"{",
"params",
".",
"subid",
"=",
"[",
"subIds",
"]",
";",
"}",
"logger",
".",
"debug",
"(",
"\"Middleware listProjectSubmissions \"",
",",
"{",
"params",
":",
"params",
"}",
")",
";",
"forms",
".",
"getSubmissions",
"(",
"req",
".",
"connectionOptions",
",",
"params",
",",
"submissionsHandler",
"(",
"constants",
".",
"resultTypes",
".",
"submissions",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Search Submissions That Belong To The Project.
@param req
@param res
@param next | [
"Search",
"Submissions",
"That",
"Belong",
"To",
"The",
"Project",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L86-L110 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | remove | function remove(req, res, next) {
var params = {"_id": req.params.id};
logger.debug("Middleware Submissions Remove ", {params: params});
forms.deleteSubmission(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next));
} | javascript | function remove(req, res, next) {
var params = {"_id": req.params.id};
logger.debug("Middleware Submissions Remove ", {params: params});
forms.deleteSubmission(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next));
} | [
"function",
"remove",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"\"_id\"",
":",
"req",
".",
"params",
".",
"id",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware Submissions Remove \"",
",",
"{",
"params",
":",
"params",
"}",
")",
";",
"forms",
".",
"deleteSubmission",
"(",
"req",
".",
"connectionOptions",
",",
"params",
",",
"submissionsHandler",
"(",
"constants",
".",
"resultTypes",
".",
"submissions",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Remove A Single Submission
@param req
@param res
@param next | [
"Remove",
"A",
"Single",
"Submission"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L158-L163 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | getSubmissionFile | function getSubmissionFile(req, res, next) {
var params = {"_id": req.params.fileId};
logger.debug("Middleware getSubmissionFile ", {params: params});
forms.getSubmissionFile(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next));
} | javascript | function getSubmissionFile(req, res, next) {
var params = {"_id": req.params.fileId};
logger.debug("Middleware getSubmissionFile ", {params: params});
forms.getSubmissionFile(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next));
} | [
"function",
"getSubmissionFile",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"\"_id\"",
":",
"req",
".",
"params",
".",
"fileId",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware getSubmissionFile \"",
",",
"{",
"params",
":",
"params",
"}",
")",
";",
"forms",
".",
"getSubmissionFile",
"(",
"req",
".",
"connectionOptions",
",",
"params",
",",
"submissionsHandler",
"(",
"constants",
".",
"resultTypes",
".",
"submissions",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Get A Single Submission File
@param req
@param res
@param next | [
"Get",
"A",
"Single",
"Submission",
"File"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L173-L177 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | updateSubmissionFile | function updateSubmissionFile(req, res, next) {
var fileUpdateOptions = req.appformsResultPayload.data;
fileUpdateOptions.submission = {
submissionId: req.params.id,
fieldId: req.params.fieldId
};
//Remove the cached file when finished
fileUpdateOptions.keepFile = false;
//Adding A New File If Required
fileUpdateOptions.addingNewSubmissionFile = req.addingNewSubmissionFile;
//If not adding a new file, the fileId param is expected to be the file group id
if (!fileUpdateOptions.addingNewSubmissionFile) {
fileUpdateOptions.fileDetails.groupId = req.params.fileId;
} else {
fileUpdateOptions.fileDetails.hashName = req.params.fileId;
}
logger.debug("Middleware updateSubmissionFile ", {fileUpdateOptions: fileUpdateOptions});
forms.updateSubmissionFile(_.extend(fileUpdateOptions, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next));
} | javascript | function updateSubmissionFile(req, res, next) {
var fileUpdateOptions = req.appformsResultPayload.data;
fileUpdateOptions.submission = {
submissionId: req.params.id,
fieldId: req.params.fieldId
};
//Remove the cached file when finished
fileUpdateOptions.keepFile = false;
//Adding A New File If Required
fileUpdateOptions.addingNewSubmissionFile = req.addingNewSubmissionFile;
//If not adding a new file, the fileId param is expected to be the file group id
if (!fileUpdateOptions.addingNewSubmissionFile) {
fileUpdateOptions.fileDetails.groupId = req.params.fileId;
} else {
fileUpdateOptions.fileDetails.hashName = req.params.fileId;
}
logger.debug("Middleware updateSubmissionFile ", {fileUpdateOptions: fileUpdateOptions});
forms.updateSubmissionFile(_.extend(fileUpdateOptions, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next));
} | [
"function",
"updateSubmissionFile",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"fileUpdateOptions",
"=",
"req",
".",
"appformsResultPayload",
".",
"data",
";",
"fileUpdateOptions",
".",
"submission",
"=",
"{",
"submissionId",
":",
"req",
".",
"params",
".",
"id",
",",
"fieldId",
":",
"req",
".",
"params",
".",
"fieldId",
"}",
";",
"fileUpdateOptions",
".",
"keepFile",
"=",
"false",
";",
"fileUpdateOptions",
".",
"addingNewSubmissionFile",
"=",
"req",
".",
"addingNewSubmissionFile",
";",
"if",
"(",
"!",
"fileUpdateOptions",
".",
"addingNewSubmissionFile",
")",
"{",
"fileUpdateOptions",
".",
"fileDetails",
".",
"groupId",
"=",
"req",
".",
"params",
".",
"fileId",
";",
"}",
"else",
"{",
"fileUpdateOptions",
".",
"fileDetails",
".",
"hashName",
"=",
"req",
".",
"params",
".",
"fileId",
";",
"}",
"logger",
".",
"debug",
"(",
"\"Middleware updateSubmissionFile \"",
",",
"{",
"fileUpdateOptions",
":",
"fileUpdateOptions",
"}",
")",
";",
"forms",
".",
"updateSubmissionFile",
"(",
"_",
".",
"extend",
"(",
"fileUpdateOptions",
",",
"req",
".",
"connectionOptions",
")",
",",
"submissionsHandler",
"(",
"constants",
".",
"resultTypes",
".",
"submissions",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Update A Single Submission File
@param req
@param res
@param next | [
"Update",
"A",
"Single",
"Submission",
"File"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L186-L210 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | addSubmissionFile | function addSubmissionFile(req, res, next) {
req.addingNewSubmissionFile = true;
updateSubmissionFile(req, res, next);
} | javascript | function addSubmissionFile(req, res, next) {
req.addingNewSubmissionFile = true;
updateSubmissionFile(req, res, next);
} | [
"function",
"addSubmissionFile",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"req",
".",
"addingNewSubmissionFile",
"=",
"true",
";",
"updateSubmissionFile",
"(",
"req",
",",
"res",
",",
"next",
")",
";",
"}"
] | Adding A New File To A Submission
@param req
@param res
@param next | [
"Adding",
"A",
"New",
"File",
"To",
"A",
"Submission"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L218-L222 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | status | function status(req, res, next) {
var params = {
submission: {
submissionId: req.params.id
}
};
logger.debug("Middleware Submission status ", {params: params});
forms.getSubmissionStatus(_.extend(params, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next));
} | javascript | function status(req, res, next) {
var params = {
submission: {
submissionId: req.params.id
}
};
logger.debug("Middleware Submission status ", {params: params});
forms.getSubmissionStatus(_.extend(params, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next));
} | [
"function",
"status",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"submission",
":",
"{",
"submissionId",
":",
"req",
".",
"params",
".",
"id",
"}",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware Submission status \"",
",",
"{",
"params",
":",
"params",
"}",
")",
";",
"forms",
".",
"getSubmissionStatus",
"(",
"_",
".",
"extend",
"(",
"params",
",",
"req",
".",
"connectionOptions",
")",
",",
"submissionsHandler",
"(",
"constants",
".",
"resultTypes",
".",
"submissions",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Middleware For Getting The Current Status Of A Submission
@param req
@param res
@param next | [
"Middleware",
"For",
"Getting",
"The",
"Current",
"Status",
"Of",
"A",
"Submission"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L279-L289 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | search | function search(req, res, next) {
var queryParams = req.body;
logger.debug("Middleware Submission Search ", {params: queryParams});
forms.submissionSearch(req.connectionOptions, queryParams, _getSubmissionsResultHandler(req, next));
} | javascript | function search(req, res, next) {
var queryParams = req.body;
logger.debug("Middleware Submission Search ", {params: queryParams});
forms.submissionSearch(req.connectionOptions, queryParams, _getSubmissionsResultHandler(req, next));
} | [
"function",
"search",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"queryParams",
"=",
"req",
".",
"body",
";",
"logger",
".",
"debug",
"(",
"\"Middleware Submission Search \"",
",",
"{",
"params",
":",
"queryParams",
"}",
")",
";",
"forms",
".",
"submissionSearch",
"(",
"req",
".",
"connectionOptions",
",",
"queryParams",
",",
"_getSubmissionsResultHandler",
"(",
"req",
",",
"next",
")",
")",
";",
"}"
] | Search For Submissions. Used For Advanced Search
@param req
@param res
@param next | [
"Search",
"For",
"Submissions",
".",
"Used",
"For",
"Advanced",
"Search"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L317-L323 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | exportSubmissions | function exportSubmissions(req, res, next) {
var params = {
"appId" : req.body.projectId,
"subid": req.body.subid,
"formId": req.body.formId,
"fieldHeader": req.body.fieldHeader,
"downloadUrl": req.body.fileUrl,
"filter": req.body.filter,
"query": req.body.query,
"wantRestrictions": false
};
logger.debug("Middleware exportSubmissions ", {req: req, body: req.body, params: params});
forms.exportSubmissions(req.connectionOptions, params, function(err, submissionCsvValues) {
if (err) {
logger.error("Middleware Export Submissions ", {error: err});
return next(err);
}
logger.debug("Middleware exportSubmissions submissionCsvValues", {submissionCsvValues: submissionCsvValues.length});
_processExportResponse(submissionCsvValues, res, next);
});
} | javascript | function exportSubmissions(req, res, next) {
var params = {
"appId" : req.body.projectId,
"subid": req.body.subid,
"formId": req.body.formId,
"fieldHeader": req.body.fieldHeader,
"downloadUrl": req.body.fileUrl,
"filter": req.body.filter,
"query": req.body.query,
"wantRestrictions": false
};
logger.debug("Middleware exportSubmissions ", {req: req, body: req.body, params: params});
forms.exportSubmissions(req.connectionOptions, params, function(err, submissionCsvValues) {
if (err) {
logger.error("Middleware Export Submissions ", {error: err});
return next(err);
}
logger.debug("Middleware exportSubmissions submissionCsvValues", {submissionCsvValues: submissionCsvValues.length});
_processExportResponse(submissionCsvValues, res, next);
});
} | [
"function",
"exportSubmissions",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"\"appId\"",
":",
"req",
".",
"body",
".",
"projectId",
",",
"\"subid\"",
":",
"req",
".",
"body",
".",
"subid",
",",
"\"formId\"",
":",
"req",
".",
"body",
".",
"formId",
",",
"\"fieldHeader\"",
":",
"req",
".",
"body",
".",
"fieldHeader",
",",
"\"downloadUrl\"",
":",
"req",
".",
"body",
".",
"fileUrl",
",",
"\"filter\"",
":",
"req",
".",
"body",
".",
"filter",
",",
"\"query\"",
":",
"req",
".",
"body",
".",
"query",
",",
"\"wantRestrictions\"",
":",
"false",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware exportSubmissions \"",
",",
"{",
"req",
":",
"req",
",",
"body",
":",
"req",
".",
"body",
",",
"params",
":",
"params",
"}",
")",
";",
"forms",
".",
"exportSubmissions",
"(",
"req",
".",
"connectionOptions",
",",
"params",
",",
"function",
"(",
"err",
",",
"submissionCsvValues",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Middleware Export Submissions \"",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"return",
"next",
"(",
"err",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"Middleware exportSubmissions submissionCsvValues\"",
",",
"{",
"submissionCsvValues",
":",
"submissionCsvValues",
".",
"length",
"}",
")",
";",
"_processExportResponse",
"(",
"submissionCsvValues",
",",
"res",
",",
"next",
")",
";",
"}",
")",
";",
"}"
] | Export Submissions As CSV Files Contained In A Single Zip
@param req
@param res
@param next | [
"Export",
"Submissions",
"As",
"CSV",
"Files",
"Contained",
"In",
"A",
"Single",
"Zip"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L349-L373 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | generatePDF | function generatePDF(req, res, next) {
req.appformsResultPayload = req.appformsResultPayload || {};
//If there is already a submission result, render this. This is useful for cases where the submission is fetched from another database and rendered elsewhere.
var existingSubmission = req.appformsResultPayload.data;
var params = {
_id: req.params.id,
pdfExportDir: req.pdfExportDir,
downloadUrl: '' + req.protocol + '://' + req.hostname,
existingSubmission: existingSubmission,
environment: req.environment,
mbaasConf: req.mbaasConf,
domain: req.user.domain,
filesAreRemote: req.filesAreRemote,
fileUriPath: req.fileUriPath,
location: req.coreLocation,
pdfTemplateLoc: req.pdfTemplateLoc,
maxConcurrentPhantomPerWorker: req.maxConcurrentPhantomPerWorker
};
logger.debug("Middleware generatePDF ", {params: params});
forms.generateSubmissionPdf(_.extend(params, req.connectionOptions), function(err, submissionPdfLocation) {
if (err) {
logger.error("Middleware generatePDF", {error: err});
return next(err);
}
logger.debug("Middleware generatePDF ", {submissionPdfLocation: submissionPdfLocation});
//Streaming the file as an attachment
res.download(submissionPdfLocation, '' + req.params.id + ".pdf", function(fileDownloadError) {
//Download Complete, remove the cached file
fs.unlink(submissionPdfLocation, function() {
if (fileDownloadError) {
logger.error("Middleware generatePDF ", {error: fileDownloadError});
//If the headers have not been sent to the client, can use the error handler
if (!res.headersSent) {
return next(fileDownloadError);
}
}
});
});
});
} | javascript | function generatePDF(req, res, next) {
req.appformsResultPayload = req.appformsResultPayload || {};
//If there is already a submission result, render this. This is useful for cases where the submission is fetched from another database and rendered elsewhere.
var existingSubmission = req.appformsResultPayload.data;
var params = {
_id: req.params.id,
pdfExportDir: req.pdfExportDir,
downloadUrl: '' + req.protocol + '://' + req.hostname,
existingSubmission: existingSubmission,
environment: req.environment,
mbaasConf: req.mbaasConf,
domain: req.user.domain,
filesAreRemote: req.filesAreRemote,
fileUriPath: req.fileUriPath,
location: req.coreLocation,
pdfTemplateLoc: req.pdfTemplateLoc,
maxConcurrentPhantomPerWorker: req.maxConcurrentPhantomPerWorker
};
logger.debug("Middleware generatePDF ", {params: params});
forms.generateSubmissionPdf(_.extend(params, req.connectionOptions), function(err, submissionPdfLocation) {
if (err) {
logger.error("Middleware generatePDF", {error: err});
return next(err);
}
logger.debug("Middleware generatePDF ", {submissionPdfLocation: submissionPdfLocation});
//Streaming the file as an attachment
res.download(submissionPdfLocation, '' + req.params.id + ".pdf", function(fileDownloadError) {
//Download Complete, remove the cached file
fs.unlink(submissionPdfLocation, function() {
if (fileDownloadError) {
logger.error("Middleware generatePDF ", {error: fileDownloadError});
//If the headers have not been sent to the client, can use the error handler
if (!res.headersSent) {
return next(fileDownloadError);
}
}
});
});
});
} | [
"function",
"generatePDF",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"req",
".",
"appformsResultPayload",
"=",
"req",
".",
"appformsResultPayload",
"||",
"{",
"}",
";",
"var",
"existingSubmission",
"=",
"req",
".",
"appformsResultPayload",
".",
"data",
";",
"var",
"params",
"=",
"{",
"_id",
":",
"req",
".",
"params",
".",
"id",
",",
"pdfExportDir",
":",
"req",
".",
"pdfExportDir",
",",
"downloadUrl",
":",
"''",
"+",
"req",
".",
"protocol",
"+",
"'://'",
"+",
"req",
".",
"hostname",
",",
"existingSubmission",
":",
"existingSubmission",
",",
"environment",
":",
"req",
".",
"environment",
",",
"mbaasConf",
":",
"req",
".",
"mbaasConf",
",",
"domain",
":",
"req",
".",
"user",
".",
"domain",
",",
"filesAreRemote",
":",
"req",
".",
"filesAreRemote",
",",
"fileUriPath",
":",
"req",
".",
"fileUriPath",
",",
"location",
":",
"req",
".",
"coreLocation",
",",
"pdfTemplateLoc",
":",
"req",
".",
"pdfTemplateLoc",
",",
"maxConcurrentPhantomPerWorker",
":",
"req",
".",
"maxConcurrentPhantomPerWorker",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware generatePDF \"",
",",
"{",
"params",
":",
"params",
"}",
")",
";",
"forms",
".",
"generateSubmissionPdf",
"(",
"_",
".",
"extend",
"(",
"params",
",",
"req",
".",
"connectionOptions",
")",
",",
"function",
"(",
"err",
",",
"submissionPdfLocation",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Middleware generatePDF\"",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"return",
"next",
"(",
"err",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"Middleware generatePDF \"",
",",
"{",
"submissionPdfLocation",
":",
"submissionPdfLocation",
"}",
")",
";",
"res",
".",
"download",
"(",
"submissionPdfLocation",
",",
"''",
"+",
"req",
".",
"params",
".",
"id",
"+",
"\".pdf\"",
",",
"function",
"(",
"fileDownloadError",
")",
"{",
"fs",
".",
"unlink",
"(",
"submissionPdfLocation",
",",
"function",
"(",
")",
"{",
"if",
"(",
"fileDownloadError",
")",
"{",
"logger",
".",
"error",
"(",
"\"Middleware generatePDF \"",
",",
"{",
"error",
":",
"fileDownloadError",
"}",
")",
";",
"if",
"(",
"!",
"res",
".",
"headersSent",
")",
"{",
"return",
"next",
"(",
"fileDownloadError",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Middleware For Generating A PDF Representation Of A Submission
This is the last step in a request. It will be terminated here unless there is an error.
@param req
@param res
@param next | [
"Middleware",
"For",
"Generating",
"A",
"PDF",
"Representation",
"Of",
"A",
"Submission"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L383-L429 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | _processExportResponse | function _processExportResponse(csvs, res, next) {
var zip = archiver('zip');
// convert csv entries to in-memory zip file and stream response
res.setHeader('Content-type', 'application/zip');
res.setHeader('Content-disposition', 'attachment; filename=submissions.zip');
zip.pipe(res);
for (var form in csvs) { // eslint-disable-line guard-for-in
var csv = csvs[form];
zip.append(csv, {name: form + '.csv'});
}
var respSent = false;
zip.on('error', function(err) {
logger.error("_processExportResponse ", {error: err});
if (err) {
if (!respSent) {
respSent = true;
return next(err);
}
}
});
zip.finalize(function(err) {
if (err) {
logger.error("_processExportResponse finalize", {error: err});
if (!respSent) {
respSent = true;
return next(err);
}
logger.debug("_processExportResponse finalize headers sent");
}
logger.debug("_processExportResponse finalize finished");
});
} | javascript | function _processExportResponse(csvs, res, next) {
var zip = archiver('zip');
// convert csv entries to in-memory zip file and stream response
res.setHeader('Content-type', 'application/zip');
res.setHeader('Content-disposition', 'attachment; filename=submissions.zip');
zip.pipe(res);
for (var form in csvs) { // eslint-disable-line guard-for-in
var csv = csvs[form];
zip.append(csv, {name: form + '.csv'});
}
var respSent = false;
zip.on('error', function(err) {
logger.error("_processExportResponse ", {error: err});
if (err) {
if (!respSent) {
respSent = true;
return next(err);
}
}
});
zip.finalize(function(err) {
if (err) {
logger.error("_processExportResponse finalize", {error: err});
if (!respSent) {
respSent = true;
return next(err);
}
logger.debug("_processExportResponse finalize headers sent");
}
logger.debug("_processExportResponse finalize finished");
});
} | [
"function",
"_processExportResponse",
"(",
"csvs",
",",
"res",
",",
"next",
")",
"{",
"var",
"zip",
"=",
"archiver",
"(",
"'zip'",
")",
";",
"res",
".",
"setHeader",
"(",
"'Content-type'",
",",
"'application/zip'",
")",
";",
"res",
".",
"setHeader",
"(",
"'Content-disposition'",
",",
"'attachment; filename=submissions.zip'",
")",
";",
"zip",
".",
"pipe",
"(",
"res",
")",
";",
"for",
"(",
"var",
"form",
"in",
"csvs",
")",
"{",
"var",
"csv",
"=",
"csvs",
"[",
"form",
"]",
";",
"zip",
".",
"append",
"(",
"csv",
",",
"{",
"name",
":",
"form",
"+",
"'.csv'",
"}",
")",
";",
"}",
"var",
"respSent",
"=",
"false",
";",
"zip",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"_processExportResponse \"",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"respSent",
")",
"{",
"respSent",
"=",
"true",
";",
"return",
"next",
"(",
"err",
")",
";",
"}",
"}",
"}",
")",
";",
"zip",
".",
"finalize",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"_processExportResponse finalize\"",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"if",
"(",
"!",
"respSent",
")",
"{",
"respSent",
"=",
"true",
";",
"return",
"next",
"(",
"err",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"_processExportResponse finalize headers sent\"",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"_processExportResponse finalize finished\"",
")",
";",
"}",
")",
";",
"}"
] | Function for processing submissions into a zip file containing csv files. | [
"Function",
"for",
"processing",
"submissions",
"into",
"a",
"zip",
"file",
"containing",
"csv",
"files",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L435-L472 | train |
feedhenry/fh-forms | lib/middleware/submissions.js | processFileResponse | function processFileResponse(req, res, next) {
var fileDetails = req.appformsResultPayload.data;
if (fileDetails.stream) {
var headers = {};
headers["Content-Type"] = fileDetails.type;//Setting the file content type. Mime types are set by the file handler.
headers["Content-Disposition"] = "attachment; filename=" + fileDetails.name;
res.writeHead(200, headers);
fileDetails.stream.pipe(res);
fileDetails.stream.resume(); //Unpausing the stream as it was paused by the file handler
} else {
return next('Error getting submitted file - result: ' + JSON.stringify(fileDetails));
}
} | javascript | function processFileResponse(req, res, next) {
var fileDetails = req.appformsResultPayload.data;
if (fileDetails.stream) {
var headers = {};
headers["Content-Type"] = fileDetails.type;//Setting the file content type. Mime types are set by the file handler.
headers["Content-Disposition"] = "attachment; filename=" + fileDetails.name;
res.writeHead(200, headers);
fileDetails.stream.pipe(res);
fileDetails.stream.resume(); //Unpausing the stream as it was paused by the file handler
} else {
return next('Error getting submitted file - result: ' + JSON.stringify(fileDetails));
}
} | [
"function",
"processFileResponse",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"fileDetails",
"=",
"req",
".",
"appformsResultPayload",
".",
"data",
";",
"if",
"(",
"fileDetails",
".",
"stream",
")",
"{",
"var",
"headers",
"=",
"{",
"}",
";",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"fileDetails",
".",
"type",
";",
"headers",
"[",
"\"Content-Disposition\"",
"]",
"=",
"\"attachment; filename=\"",
"+",
"fileDetails",
".",
"name",
";",
"res",
".",
"writeHead",
"(",
"200",
",",
"headers",
")",
";",
"fileDetails",
".",
"stream",
".",
"pipe",
"(",
"res",
")",
";",
"fileDetails",
".",
"stream",
".",
"resume",
"(",
")",
";",
"}",
"else",
"{",
"return",
"next",
"(",
"'Error getting submitted file - result: '",
"+",
"JSON",
".",
"stringify",
"(",
"fileDetails",
")",
")",
";",
"}",
"}"
] | Function for handling a file response. Used when loading files from a submission
@param req
@param res
@param next | [
"Function",
"for",
"handling",
"a",
"file",
"response",
".",
"Used",
"when",
"loading",
"files",
"from",
"a",
"submission"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L481-L493 | train |
feedhenry/fh-forms | lib/impl/getSubmissions/processListResult.js | reformatFormIdAndName | function reformatFormIdAndName(submission) {
var formName = "Unknown";
if (submission && submission.formId && submission.formId.name) {
formName = submission.formId.name;
}
if (submission && submission.formSubmittedAgainst) {
formName = submission.formSubmittedAgainst.name;
}
submission.formName = formName;
submission.formId = submission.formId.toString();
return submission;
} | javascript | function reformatFormIdAndName(submission) {
var formName = "Unknown";
if (submission && submission.formId && submission.formId.name) {
formName = submission.formId.name;
}
if (submission && submission.formSubmittedAgainst) {
formName = submission.formSubmittedAgainst.name;
}
submission.formName = formName;
submission.formId = submission.formId.toString();
return submission;
} | [
"function",
"reformatFormIdAndName",
"(",
"submission",
")",
"{",
"var",
"formName",
"=",
"\"Unknown\"",
";",
"if",
"(",
"submission",
"&&",
"submission",
".",
"formId",
"&&",
"submission",
".",
"formId",
".",
"name",
")",
"{",
"formName",
"=",
"submission",
".",
"formId",
".",
"name",
";",
"}",
"if",
"(",
"submission",
"&&",
"submission",
".",
"formSubmittedAgainst",
")",
"{",
"formName",
"=",
"submission",
".",
"formSubmittedAgainst",
".",
"name",
";",
"}",
"submission",
".",
"formName",
"=",
"formName",
";",
"submission",
".",
"formId",
"=",
"submission",
".",
"formId",
".",
"toString",
"(",
")",
";",
"return",
"submission",
";",
"}"
] | reformatFormIdAndName - Reformatting the form ID associated with the submission.
@param {object} submission Submission to process.
@return {object} Updated submission | [
"reformatFormIdAndName",
"-",
"Reformatting",
"the",
"form",
"ID",
"associated",
"with",
"the",
"submission",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getSubmissions/processListResult.js#L11-L24 | train |
feedhenry/fh-forms | lib/impl/getSubmissions/processListResult.js | restrictSubmissionForSummary | function restrictSubmissionForSummary(submission) {
submission.formFields = _.filter(submission.formFields, function(formField) {
return CONSTANTS.FIELD_TYPES_INCLUDED_IN_SUMMARY.indexOf(formField.fieldId.type) >= 0;
});
submission.formFields = _.first(submission.formFields, CONSTANTS.NUM_FIELDS_INCLUDED_IN_SUMMARY);
return submission;
} | javascript | function restrictSubmissionForSummary(submission) {
submission.formFields = _.filter(submission.formFields, function(formField) {
return CONSTANTS.FIELD_TYPES_INCLUDED_IN_SUMMARY.indexOf(formField.fieldId.type) >= 0;
});
submission.formFields = _.first(submission.formFields, CONSTANTS.NUM_FIELDS_INCLUDED_IN_SUMMARY);
return submission;
} | [
"function",
"restrictSubmissionForSummary",
"(",
"submission",
")",
"{",
"submission",
".",
"formFields",
"=",
"_",
".",
"filter",
"(",
"submission",
".",
"formFields",
",",
"function",
"(",
"formField",
")",
"{",
"return",
"CONSTANTS",
".",
"FIELD_TYPES_INCLUDED_IN_SUMMARY",
".",
"indexOf",
"(",
"formField",
".",
"fieldId",
".",
"type",
")",
">=",
"0",
";",
"}",
")",
";",
"submission",
".",
"formFields",
"=",
"_",
".",
"first",
"(",
"submission",
".",
"formFields",
",",
"CONSTANTS",
".",
"NUM_FIELDS_INCLUDED_IN_SUMMARY",
")",
";",
"return",
"submission",
";",
"}"
] | Only Includes Fields In The Summary
@param submission
@returns {Object} | [
"Only",
"Includes",
"Fields",
"In",
"The",
"Summary"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getSubmissions/processListResult.js#L31-L39 | train |
feedhenry/fh-forms | lib/impl/deleteSubmission.js | function(submission) {
return _.flatten(submission.formFields.map(function(field) {
return field.fieldValues.filter(hasGroupId);
}).map(function(fieldValue) {
return fieldValue.map(extractGroupId);
}));
} | javascript | function(submission) {
return _.flatten(submission.formFields.map(function(field) {
return field.fieldValues.filter(hasGroupId);
}).map(function(fieldValue) {
return fieldValue.map(extractGroupId);
}));
} | [
"function",
"(",
"submission",
")",
"{",
"return",
"_",
".",
"flatten",
"(",
"submission",
".",
"formFields",
".",
"map",
"(",
"function",
"(",
"field",
")",
"{",
"return",
"field",
".",
"fieldValues",
".",
"filter",
"(",
"hasGroupId",
")",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"fieldValue",
")",
"{",
"return",
"fieldValue",
".",
"map",
"(",
"extractGroupId",
")",
";",
"}",
")",
")",
";",
"}"
] | Returns all the `groupId` values for the passed-in submission.
A submission can have multiple fields, and each field can have
multiple fieldValues. | [
"Returns",
"all",
"the",
"groupId",
"values",
"for",
"the",
"passed",
"-",
"in",
"submission",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/deleteSubmission.js#L21-L27 | train |
|
techcoop/react-material-site | scripts/prebuild.js | spawnWatcher | function spawnWatcher() {
var subprocess = spawn(process.argv[0], ['prebuild.js', '--watcher'], {detached: true, stdio: 'ignore'})
subprocess.unref()
} | javascript | function spawnWatcher() {
var subprocess = spawn(process.argv[0], ['prebuild.js', '--watcher'], {detached: true, stdio: 'ignore'})
subprocess.unref()
} | [
"function",
"spawnWatcher",
"(",
")",
"{",
"var",
"subprocess",
"=",
"spawn",
"(",
"process",
".",
"argv",
"[",
"0",
"]",
",",
"[",
"'prebuild.js'",
",",
"'--watcher'",
"]",
",",
"{",
"detached",
":",
"true",
",",
"stdio",
":",
"'ignore'",
"}",
")",
"subprocess",
".",
"unref",
"(",
")",
"}"
] | Spawn watcher process | [
"Spawn",
"watcher",
"process"
] | cb2973dbccfa17426abc8cd6f342910203c7f007 | https://github.com/techcoop/react-material-site/blob/cb2973dbccfa17426abc8cd6f342910203c7f007/scripts/prebuild.js#L65-L68 | train |
techcoop/react-material-site | scripts/prebuild.js | createIndex | function createIndex() {
var directory = 'src/views'
var directories = fs.readdirSync(directory)
try {
var lines = ['// This is a generated file, do not edit, or disable "prebuild" command in package.json if you want to take control']
for (var i = 0; i < directories.length; i++) {
var path = directory + '/' + directories[i];
if (fs.existsSync(path) && fs.lstatSync(path).isDirectory()) {
var file = directories[i] + '.js'
if (fs.existsSync(directory + '/' + directories[i] + '/' + file)) {
lines.push('export { default as ' + directories[i] + ' } from \'./' + directories[i] + '/' + directories[i] + '\'')
}
}
}
fs.writeFileSync(directory + '/index.js', lines.join('\n') + '\n');
} catch (err) {
console.log(err)
}
} | javascript | function createIndex() {
var directory = 'src/views'
var directories = fs.readdirSync(directory)
try {
var lines = ['// This is a generated file, do not edit, or disable "prebuild" command in package.json if you want to take control']
for (var i = 0; i < directories.length; i++) {
var path = directory + '/' + directories[i];
if (fs.existsSync(path) && fs.lstatSync(path).isDirectory()) {
var file = directories[i] + '.js'
if (fs.existsSync(directory + '/' + directories[i] + '/' + file)) {
lines.push('export { default as ' + directories[i] + ' } from \'./' + directories[i] + '/' + directories[i] + '\'')
}
}
}
fs.writeFileSync(directory + '/index.js', lines.join('\n') + '\n');
} catch (err) {
console.log(err)
}
} | [
"function",
"createIndex",
"(",
")",
"{",
"var",
"directory",
"=",
"'src/views'",
"var",
"directories",
"=",
"fs",
".",
"readdirSync",
"(",
"directory",
")",
"try",
"{",
"var",
"lines",
"=",
"[",
"'// This is a generated file, do not edit, or disable \"prebuild\" command in package.json if you want to take control'",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"directories",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"path",
"=",
"directory",
"+",
"'/'",
"+",
"directories",
"[",
"i",
"]",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"path",
")",
"&&",
"fs",
".",
"lstatSync",
"(",
"path",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"var",
"file",
"=",
"directories",
"[",
"i",
"]",
"+",
"'.js'",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"directory",
"+",
"'/'",
"+",
"directories",
"[",
"i",
"]",
"+",
"'/'",
"+",
"file",
")",
")",
"{",
"lines",
".",
"push",
"(",
"'export { default as '",
"+",
"directories",
"[",
"i",
"]",
"+",
"' } from \\'./'",
"+",
"\\'",
"+",
"directories",
"[",
"i",
"]",
"+",
"'/'",
"+",
"directories",
"[",
"i",
"]",
")",
"}",
"}",
"}",
"'\\''",
"}",
"\\'",
"}"
] | Creates index file for views | [
"Creates",
"index",
"file",
"for",
"views"
] | cb2973dbccfa17426abc8cd6f342910203c7f007 | https://github.com/techcoop/react-material-site/blob/cb2973dbccfa17426abc8cd6f342910203c7f007/scripts/prebuild.js#L71-L91 | train |
feedhenry/fh-forms | lib/impl/submissionExportHelper/csvHeaders.js | generateFieldHeader | function generateFieldHeader(field, headerName, fieldRepeatIndex) {
var csv = '';
//If the field is repeating, the structure of the header is different
if (_.isNumber(fieldRepeatIndex)) {
//If it is a file type field, need to add two fields for the file name and url
if (fieldTypeUtils.isFileType(field.type)) {
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-name") + ",";
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-url");
} else if (fieldTypeUtils.isBarcodeType(field.type)) {
//If it is a barcode type field, need to add two fields for the format name and text
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-format") +
",";
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-text");
} else {
//Otherwise, just append the index.
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1));
}
} else {
//If it is a file type field, need to add two fields for the file name and url
if (fieldTypeUtils.isFileType(field.type)) {
csv += csvStr(headerName + "-name") + ",";
csv += csvStr(headerName + "-url");
} else if (fieldTypeUtils.isBarcodeType(field.type)) {
//If it is a barcode type field, need to add two fields for the format name and text
csv += csvStr(headerName + "-format") + ",";
csv += csvStr(headerName + "-text");
} else {
csv += csvStr(headerName);
}
}
return csv;
} | javascript | function generateFieldHeader(field, headerName, fieldRepeatIndex) {
var csv = '';
//If the field is repeating, the structure of the header is different
if (_.isNumber(fieldRepeatIndex)) {
//If it is a file type field, need to add two fields for the file name and url
if (fieldTypeUtils.isFileType(field.type)) {
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-name") + ",";
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-url");
} else if (fieldTypeUtils.isBarcodeType(field.type)) {
//If it is a barcode type field, need to add two fields for the format name and text
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-format") +
",";
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-text");
} else {
//Otherwise, just append the index.
csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1));
}
} else {
//If it is a file type field, need to add two fields for the file name and url
if (fieldTypeUtils.isFileType(field.type)) {
csv += csvStr(headerName + "-name") + ",";
csv += csvStr(headerName + "-url");
} else if (fieldTypeUtils.isBarcodeType(field.type)) {
//If it is a barcode type field, need to add two fields for the format name and text
csv += csvStr(headerName + "-format") + ",";
csv += csvStr(headerName + "-text");
} else {
csv += csvStr(headerName);
}
}
return csv;
} | [
"function",
"generateFieldHeader",
"(",
"field",
",",
"headerName",
",",
"fieldRepeatIndex",
")",
"{",
"var",
"csv",
"=",
"''",
";",
"if",
"(",
"_",
".",
"isNumber",
"(",
"fieldRepeatIndex",
")",
")",
"{",
"if",
"(",
"fieldTypeUtils",
".",
"isFileType",
"(",
"field",
".",
"type",
")",
")",
"{",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"'-'",
"+",
"(",
"fieldRepeatIndex",
"+",
"1",
")",
"+",
"\"-name\"",
")",
"+",
"\",\"",
";",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"'-'",
"+",
"(",
"fieldRepeatIndex",
"+",
"1",
")",
"+",
"\"-url\"",
")",
";",
"}",
"else",
"if",
"(",
"fieldTypeUtils",
".",
"isBarcodeType",
"(",
"field",
".",
"type",
")",
")",
"{",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"'-'",
"+",
"(",
"fieldRepeatIndex",
"+",
"1",
")",
"+",
"\"-format\"",
")",
"+",
"\",\"",
";",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"'-'",
"+",
"(",
"fieldRepeatIndex",
"+",
"1",
")",
"+",
"\"-text\"",
")",
";",
"}",
"else",
"{",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"'-'",
"+",
"(",
"fieldRepeatIndex",
"+",
"1",
")",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"fieldTypeUtils",
".",
"isFileType",
"(",
"field",
".",
"type",
")",
")",
"{",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"\"-name\"",
")",
"+",
"\",\"",
";",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"\"-url\"",
")",
";",
"}",
"else",
"if",
"(",
"fieldTypeUtils",
".",
"isBarcodeType",
"(",
"field",
".",
"type",
")",
")",
"{",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"\"-format\"",
")",
"+",
"\",\"",
";",
"csv",
"+=",
"csvStr",
"(",
"headerName",
"+",
"\"-text\"",
")",
";",
"}",
"else",
"{",
"csv",
"+=",
"csvStr",
"(",
"headerName",
")",
";",
"}",
"}",
"return",
"csv",
";",
"}"
] | generateFieldHeader - Generating A single field header.
@param {object} field Field definition
@param {string} headerName Header Name to add
@param {number} fieldRepeatIndex The index of a repeating field (null if it is not repeating)
@return {string} Generated CSV | [
"generateFieldHeader",
"-",
"Generating",
"A",
"single",
"field",
"header",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvHeaders.js#L20-L52 | train |
feedhenry/fh-forms | lib/impl/submissionExportHelper/csvHeaders.js | generateCSVHeader | function generateCSVHeader(csv, field, headerName, fieldRepeatIndex) {
//If the previous csv value is set, then a ',' is needed to separate.
if (csv) {
csv += ',';
}
// Sanity check after the headers to ensure we don't have a double ,, appearing
// The above if is necessary and cannot be removed
if (endsWith(csv, ',,')) {
csv = csv.slice(0, -1);
}
csv += generateFieldHeader(field, headerName, fieldRepeatIndex);
return csv;
} | javascript | function generateCSVHeader(csv, field, headerName, fieldRepeatIndex) {
//If the previous csv value is set, then a ',' is needed to separate.
if (csv) {
csv += ',';
}
// Sanity check after the headers to ensure we don't have a double ,, appearing
// The above if is necessary and cannot be removed
if (endsWith(csv, ',,')) {
csv = csv.slice(0, -1);
}
csv += generateFieldHeader(field, headerName, fieldRepeatIndex);
return csv;
} | [
"function",
"generateCSVHeader",
"(",
"csv",
",",
"field",
",",
"headerName",
",",
"fieldRepeatIndex",
")",
"{",
"if",
"(",
"csv",
")",
"{",
"csv",
"+=",
"','",
";",
"}",
"if",
"(",
"endsWith",
"(",
"csv",
",",
"',,'",
")",
")",
"{",
"csv",
"=",
"csv",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"}",
"csv",
"+=",
"generateFieldHeader",
"(",
"field",
",",
"headerName",
",",
"fieldRepeatIndex",
")",
";",
"return",
"csv",
";",
"}"
] | generateCSVHeader - Generating the Headers For All Of The Fields In The CSV
@param {string} csv Existing CSV String.
@param {object} field Field definition
@param {string} headerName Header Name to add
@param {number} fieldRepeatIndex The index of a repeating field (null if it is not repeating)
@return {string} Generated CSV | [
"generateCSVHeader",
"-",
"Generating",
"the",
"Headers",
"For",
"All",
"Of",
"The",
"Fields",
"In",
"The",
"CSV"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvHeaders.js#L63-L79 | train |
feedhenry/fh-forms | lib/impl/submissionExportHelper/csvHeaders.js | generateCSVHeaders | function generateCSVHeaders(fieldKeys, mergedFieldEntries, fieldHeader) {
var csv = '';
var fieldRepeatIndex = 0;
// Here we need to add the metaDataHeaders
_.each(metaDataHeaders, function(headerName) {
csv += headerName + ',';
});
var fieldKeysProcessed = [];
var fieldsProcessed = {};
fieldKeys.forEach(function(fieldKey) {
// check if its a repeating form (and extra headers required)
var field = mergedFieldEntries[fieldKey];
if (field.type === 'sectionBreak' && field.repeating) {
var fieldsInThisSection = sectionUtils.getFieldsInSection(field._id, _.values(mergedFieldEntries));
_.each(fieldsInThisSection, function(field) {
fieldsProcessed[field._id] = true;
});
for (var i = 0; i < field.fieldOptions.definition.maxRepeat; i++) {
_.each(fieldsInThisSection, function(fieldInThisSection) {
fieldKeysProcessed.push({key: fieldInThisSection._id, sectionIndex: i + 1, inRepeatingForm: true});
});
}
} else if (!fieldsProcessed[fieldKey]) {
fieldKeysProcessed.push({key: fieldKey});
}
});
//for each form get each of the unique fields and add a header
fieldKeysProcessed.forEach(function(processedField) {
// check if its a repeating form (and extra headers required)
var field = mergedFieldEntries[processedField.key];
//Fields may not have a field code, if not just use the field name.
var headerName = typeof (field[fieldHeader]) === "string" ? field[fieldHeader] : field.name;
if (processedField.inRepeatingForm) {
headerName = '(section repeat: ' + processedField.sectionIndex + ') ' + headerName;
}
if (field.repeating === true) {
for (fieldRepeatIndex = 0; fieldRepeatIndex < field.fieldOptions.definition.maxRepeat; fieldRepeatIndex++) {
csv = generateCSVHeader(csv, field, headerName, fieldRepeatIndex);
}
} else {
csv = generateCSVHeader(csv, field, headerName, null);
}
});
csv += '\r\n';
return csv;
} | javascript | function generateCSVHeaders(fieldKeys, mergedFieldEntries, fieldHeader) {
var csv = '';
var fieldRepeatIndex = 0;
// Here we need to add the metaDataHeaders
_.each(metaDataHeaders, function(headerName) {
csv += headerName + ',';
});
var fieldKeysProcessed = [];
var fieldsProcessed = {};
fieldKeys.forEach(function(fieldKey) {
// check if its a repeating form (and extra headers required)
var field = mergedFieldEntries[fieldKey];
if (field.type === 'sectionBreak' && field.repeating) {
var fieldsInThisSection = sectionUtils.getFieldsInSection(field._id, _.values(mergedFieldEntries));
_.each(fieldsInThisSection, function(field) {
fieldsProcessed[field._id] = true;
});
for (var i = 0; i < field.fieldOptions.definition.maxRepeat; i++) {
_.each(fieldsInThisSection, function(fieldInThisSection) {
fieldKeysProcessed.push({key: fieldInThisSection._id, sectionIndex: i + 1, inRepeatingForm: true});
});
}
} else if (!fieldsProcessed[fieldKey]) {
fieldKeysProcessed.push({key: fieldKey});
}
});
//for each form get each of the unique fields and add a header
fieldKeysProcessed.forEach(function(processedField) {
// check if its a repeating form (and extra headers required)
var field = mergedFieldEntries[processedField.key];
//Fields may not have a field code, if not just use the field name.
var headerName = typeof (field[fieldHeader]) === "string" ? field[fieldHeader] : field.name;
if (processedField.inRepeatingForm) {
headerName = '(section repeat: ' + processedField.sectionIndex + ') ' + headerName;
}
if (field.repeating === true) {
for (fieldRepeatIndex = 0; fieldRepeatIndex < field.fieldOptions.definition.maxRepeat; fieldRepeatIndex++) {
csv = generateCSVHeader(csv, field, headerName, fieldRepeatIndex);
}
} else {
csv = generateCSVHeader(csv, field, headerName, null);
}
});
csv += '\r\n';
return csv;
} | [
"function",
"generateCSVHeaders",
"(",
"fieldKeys",
",",
"mergedFieldEntries",
",",
"fieldHeader",
")",
"{",
"var",
"csv",
"=",
"''",
";",
"var",
"fieldRepeatIndex",
"=",
"0",
";",
"_",
".",
"each",
"(",
"metaDataHeaders",
",",
"function",
"(",
"headerName",
")",
"{",
"csv",
"+=",
"headerName",
"+",
"','",
";",
"}",
")",
";",
"var",
"fieldKeysProcessed",
"=",
"[",
"]",
";",
"var",
"fieldsProcessed",
"=",
"{",
"}",
";",
"fieldKeys",
".",
"forEach",
"(",
"function",
"(",
"fieldKey",
")",
"{",
"var",
"field",
"=",
"mergedFieldEntries",
"[",
"fieldKey",
"]",
";",
"if",
"(",
"field",
".",
"type",
"===",
"'sectionBreak'",
"&&",
"field",
".",
"repeating",
")",
"{",
"var",
"fieldsInThisSection",
"=",
"sectionUtils",
".",
"getFieldsInSection",
"(",
"field",
".",
"_id",
",",
"_",
".",
"values",
"(",
"mergedFieldEntries",
")",
")",
";",
"_",
".",
"each",
"(",
"fieldsInThisSection",
",",
"function",
"(",
"field",
")",
"{",
"fieldsProcessed",
"[",
"field",
".",
"_id",
"]",
"=",
"true",
";",
"}",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"field",
".",
"fieldOptions",
".",
"definition",
".",
"maxRepeat",
";",
"i",
"++",
")",
"{",
"_",
".",
"each",
"(",
"fieldsInThisSection",
",",
"function",
"(",
"fieldInThisSection",
")",
"{",
"fieldKeysProcessed",
".",
"push",
"(",
"{",
"key",
":",
"fieldInThisSection",
".",
"_id",
",",
"sectionIndex",
":",
"i",
"+",
"1",
",",
"inRepeatingForm",
":",
"true",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"fieldsProcessed",
"[",
"fieldKey",
"]",
")",
"{",
"fieldKeysProcessed",
".",
"push",
"(",
"{",
"key",
":",
"fieldKey",
"}",
")",
";",
"}",
"}",
")",
";",
"fieldKeysProcessed",
".",
"forEach",
"(",
"function",
"(",
"processedField",
")",
"{",
"var",
"field",
"=",
"mergedFieldEntries",
"[",
"processedField",
".",
"key",
"]",
";",
"var",
"headerName",
"=",
"typeof",
"(",
"field",
"[",
"fieldHeader",
"]",
")",
"===",
"\"string\"",
"?",
"field",
"[",
"fieldHeader",
"]",
":",
"field",
".",
"name",
";",
"if",
"(",
"processedField",
".",
"inRepeatingForm",
")",
"{",
"headerName",
"=",
"'(section repeat: '",
"+",
"processedField",
".",
"sectionIndex",
"+",
"') '",
"+",
"headerName",
";",
"}",
"if",
"(",
"field",
".",
"repeating",
"===",
"true",
")",
"{",
"for",
"(",
"fieldRepeatIndex",
"=",
"0",
";",
"fieldRepeatIndex",
"<",
"field",
".",
"fieldOptions",
".",
"definition",
".",
"maxRepeat",
";",
"fieldRepeatIndex",
"++",
")",
"{",
"csv",
"=",
"generateCSVHeader",
"(",
"csv",
",",
"field",
",",
"headerName",
",",
"fieldRepeatIndex",
")",
";",
"}",
"}",
"else",
"{",
"csv",
"=",
"generateCSVHeader",
"(",
"csv",
",",
"field",
",",
"headerName",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"csv",
"+=",
"'\\r\\n'",
";",
"\\r",
"}"
] | generateCSVHeaders - Generating CSV Headers from a merged form definition
@param {array} fieldKeys Field IDs
@param {object} mergedFieldEntries Merged field definitions
@param {string} fieldHeader Header type to use (fieldName, fieldCode)
@return {string} | [
"generateCSVHeaders",
"-",
"Generating",
"CSV",
"Headers",
"from",
"a",
"merged",
"form",
"definition"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvHeaders.js#L106-L157 | train |
stackgl/gl-shader-core | lib/create-attributes.js | ShaderAttribute | function ShaderAttribute(gl, program, location, dimension, name, constFunc, relink) {
this._gl = gl
this._program = program
this._location = location
this._dimension = dimension
this._name = name
this._constFunc = constFunc
this._relink = relink
} | javascript | function ShaderAttribute(gl, program, location, dimension, name, constFunc, relink) {
this._gl = gl
this._program = program
this._location = location
this._dimension = dimension
this._name = name
this._constFunc = constFunc
this._relink = relink
} | [
"function",
"ShaderAttribute",
"(",
"gl",
",",
"program",
",",
"location",
",",
"dimension",
",",
"name",
",",
"constFunc",
",",
"relink",
")",
"{",
"this",
".",
"_gl",
"=",
"gl",
"this",
".",
"_program",
"=",
"program",
"this",
".",
"_location",
"=",
"location",
"this",
".",
"_dimension",
"=",
"dimension",
"this",
".",
"_name",
"=",
"name",
"this",
".",
"_constFunc",
"=",
"constFunc",
"this",
".",
"_relink",
"=",
"relink",
"}"
] | Shader attribute class | [
"Shader",
"attribute",
"class"
] | 25e021e9239ad7b73ce08ff0fdc97e2e68e1d075 | https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/lib/create-attributes.js#L6-L14 | train |
stackgl/gl-shader-core | lib/create-attributes.js | addVectorAttribute | function addVectorAttribute(gl, program, location, dimension, obj, name, doLink) {
var constFuncArgs = [ 'gl', 'v' ]
var varNames = []
for(var i=0; i<dimension; ++i) {
constFuncArgs.push('x'+i)
varNames.push('x'+i)
}
constFuncArgs.push([
'if(x0.length===void 0){return gl.vertexAttrib', dimension, 'f(v,', varNames.join(), ')}else{return gl.vertexAttrib', dimension, 'fv(v,x0)}'
].join(''))
var constFunc = Function.apply(undefined, constFuncArgs)
var attr = new ShaderAttribute(gl, program, location, dimension, name, constFunc, doLink)
Object.defineProperty(obj, name, {
set: function(x) {
gl.disableVertexAttribArray(attr._location)
constFunc(gl, attr._location, x)
return x
}
, get: function() {
return attr
}
, enumerable: true
})
} | javascript | function addVectorAttribute(gl, program, location, dimension, obj, name, doLink) {
var constFuncArgs = [ 'gl', 'v' ]
var varNames = []
for(var i=0; i<dimension; ++i) {
constFuncArgs.push('x'+i)
varNames.push('x'+i)
}
constFuncArgs.push([
'if(x0.length===void 0){return gl.vertexAttrib', dimension, 'f(v,', varNames.join(), ')}else{return gl.vertexAttrib', dimension, 'fv(v,x0)}'
].join(''))
var constFunc = Function.apply(undefined, constFuncArgs)
var attr = new ShaderAttribute(gl, program, location, dimension, name, constFunc, doLink)
Object.defineProperty(obj, name, {
set: function(x) {
gl.disableVertexAttribArray(attr._location)
constFunc(gl, attr._location, x)
return x
}
, get: function() {
return attr
}
, enumerable: true
})
} | [
"function",
"addVectorAttribute",
"(",
"gl",
",",
"program",
",",
"location",
",",
"dimension",
",",
"obj",
",",
"name",
",",
"doLink",
")",
"{",
"var",
"constFuncArgs",
"=",
"[",
"'gl'",
",",
"'v'",
"]",
"var",
"varNames",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"dimension",
";",
"++",
"i",
")",
"{",
"constFuncArgs",
".",
"push",
"(",
"'x'",
"+",
"i",
")",
"varNames",
".",
"push",
"(",
"'x'",
"+",
"i",
")",
"}",
"constFuncArgs",
".",
"push",
"(",
"[",
"'if(x0.length===void 0){return gl.vertexAttrib'",
",",
"dimension",
",",
"'f(v,'",
",",
"varNames",
".",
"join",
"(",
")",
",",
"')}else{return gl.vertexAttrib'",
",",
"dimension",
",",
"'fv(v,x0)}'",
"]",
".",
"join",
"(",
"''",
")",
")",
"var",
"constFunc",
"=",
"Function",
".",
"apply",
"(",
"undefined",
",",
"constFuncArgs",
")",
"var",
"attr",
"=",
"new",
"ShaderAttribute",
"(",
"gl",
",",
"program",
",",
"location",
",",
"dimension",
",",
"name",
",",
"constFunc",
",",
"doLink",
")",
"Object",
".",
"defineProperty",
"(",
"obj",
",",
"name",
",",
"{",
"set",
":",
"function",
"(",
"x",
")",
"{",
"gl",
".",
"disableVertexAttribArray",
"(",
"attr",
".",
"_location",
")",
"constFunc",
"(",
"gl",
",",
"attr",
".",
"_location",
",",
"x",
")",
"return",
"x",
"}",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"attr",
"}",
",",
"enumerable",
":",
"true",
"}",
")",
"}"
] | Adds a vector attribute to obj | [
"Adds",
"a",
"vector",
"attribute",
"to",
"obj"
] | 25e021e9239ad7b73ce08ff0fdc97e2e68e1d075 | https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/lib/create-attributes.js#L40-L63 | train |
stackgl/gl-shader-core | lib/create-attributes.js | createAttributeWrapper | function createAttributeWrapper(gl, program, attributes, doLink) {
var obj = {}
for(var i=0, n=attributes.length; i<n; ++i) {
var a = attributes[i]
var name = a.name
var type = a.type
var location = gl.getAttribLocation(program, name)
switch(type) {
case 'bool':
case 'int':
case 'float':
addVectorAttribute(gl, program, location, 1, obj, name, doLink)
break
default:
if(type.indexOf('vec') >= 0) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid data type for attribute ' + name + ': ' + type)
}
addVectorAttribute(gl, program, location, d, obj, name, doLink)
} else {
throw new Error('gl-shader: Unknown data type for attribute ' + name + ': ' + type)
}
break
}
}
return obj
} | javascript | function createAttributeWrapper(gl, program, attributes, doLink) {
var obj = {}
for(var i=0, n=attributes.length; i<n; ++i) {
var a = attributes[i]
var name = a.name
var type = a.type
var location = gl.getAttribLocation(program, name)
switch(type) {
case 'bool':
case 'int':
case 'float':
addVectorAttribute(gl, program, location, 1, obj, name, doLink)
break
default:
if(type.indexOf('vec') >= 0) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid data type for attribute ' + name + ': ' + type)
}
addVectorAttribute(gl, program, location, d, obj, name, doLink)
} else {
throw new Error('gl-shader: Unknown data type for attribute ' + name + ': ' + type)
}
break
}
}
return obj
} | [
"function",
"createAttributeWrapper",
"(",
"gl",
",",
"program",
",",
"attributes",
",",
"doLink",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"attributes",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"var",
"a",
"=",
"attributes",
"[",
"i",
"]",
"var",
"name",
"=",
"a",
".",
"name",
"var",
"type",
"=",
"a",
".",
"type",
"var",
"location",
"=",
"gl",
".",
"getAttribLocation",
"(",
"program",
",",
"name",
")",
"switch",
"(",
"type",
")",
"{",
"case",
"'bool'",
":",
"case",
"'int'",
":",
"case",
"'float'",
":",
"addVectorAttribute",
"(",
"gl",
",",
"program",
",",
"location",
",",
"1",
",",
"obj",
",",
"name",
",",
"doLink",
")",
"break",
"default",
":",
"if",
"(",
"type",
".",
"indexOf",
"(",
"'vec'",
")",
">=",
"0",
")",
"{",
"var",
"d",
"=",
"type",
".",
"charCodeAt",
"(",
"type",
".",
"length",
"-",
"1",
")",
"-",
"48",
"if",
"(",
"d",
"<",
"2",
"||",
"d",
">",
"4",
")",
"{",
"throw",
"new",
"Error",
"(",
"'gl-shader: Invalid data type for attribute '",
"+",
"name",
"+",
"': '",
"+",
"type",
")",
"}",
"addVectorAttribute",
"(",
"gl",
",",
"program",
",",
"location",
",",
"d",
",",
"obj",
",",
"name",
",",
"doLink",
")",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'gl-shader: Unknown data type for attribute '",
"+",
"name",
"+",
"': '",
"+",
"type",
")",
"}",
"break",
"}",
"}",
"return",
"obj",
"}"
] | Create shims for attributes | [
"Create",
"shims",
"for",
"attributes"
] | 25e021e9239ad7b73ce08ff0fdc97e2e68e1d075 | https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/lib/create-attributes.js#L66-L95 | train |
cloudfour/drizzle-builder | src/render/index.js | render | function render(drizzleData) {
return Promise.all([
renderPages(drizzleData),
renderCollections(drizzleData)
]).then(
allData => {
return {
data: drizzleData.data,
pages: allData[0],
patterns: allData[1],
templates: drizzleData.templates,
options: drizzleData.options,
tree: drizzleData.tree
};
},
error => DrizzleError.error(error, drizzleData.options.debug)
);
} | javascript | function render(drizzleData) {
return Promise.all([
renderPages(drizzleData),
renderCollections(drizzleData)
]).then(
allData => {
return {
data: drizzleData.data,
pages: allData[0],
patterns: allData[1],
templates: drizzleData.templates,
options: drizzleData.options,
tree: drizzleData.tree
};
},
error => DrizzleError.error(error, drizzleData.options.debug)
);
} | [
"function",
"render",
"(",
"drizzleData",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"[",
"renderPages",
"(",
"drizzleData",
")",
",",
"renderCollections",
"(",
"drizzleData",
")",
"]",
")",
".",
"then",
"(",
"allData",
"=>",
"{",
"return",
"{",
"data",
":",
"drizzleData",
".",
"data",
",",
"pages",
":",
"allData",
"[",
"0",
"]",
",",
"patterns",
":",
"allData",
"[",
"1",
"]",
",",
"templates",
":",
"drizzleData",
".",
"templates",
",",
"options",
":",
"drizzleData",
".",
"options",
",",
"tree",
":",
"drizzleData",
".",
"tree",
"}",
";",
"}",
",",
"error",
"=>",
"DrizzleError",
".",
"error",
"(",
"error",
",",
"drizzleData",
".",
"options",
".",
"debug",
")",
")",
";",
"}"
] | Render pages and pattern-collection pages.
@param {Object} drizzleData All data built so far
@return {Promise} resolving to drizzleData | [
"Render",
"pages",
"and",
"pattern",
"-",
"collection",
"pages",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/render/index.js#L12-L29 | train |
crispy1989/node-zstreams | lib/conversion.js | convertToZStream | function convertToZStream(stream, options) {
if(stream._isZStream) return stream;
if(isRequestStream(stream)) {
// Request Stream
return new RequestStream(stream, options);
}
if(isClassicStream(stream)) {
if(stream.readable && stream.writable) {
// Duplex
return new ClassicDuplex(stream, options);
} else if(stream.readable) {
// Readable
return new ClassicReadable(stream, options);
} else {
// Writable
return new ClassicWritable(stream, options);
}
}
var origFuncs = {};
for(var key in stream) {
origFuncs[key] = stream[key];
}
// Use duck typing in case of multiple stream implementations
extend(stream, streamMixins.prototype);
streamMixins.call(stream, origFuncs);
if(stream.read) {
extend(stream, readableMixins.prototype);
readableMixins.call(stream);
}
if(stream.write) {
extend(stream, writableMixins.prototype);
writableMixins.call(stream);
}
if(typeof process === 'object' && (stream === process.stdout || stream === process.stderr)) {
// Don't abort stdio streams on error
stream._zNoAbort = true;
}
return stream;
} | javascript | function convertToZStream(stream, options) {
if(stream._isZStream) return stream;
if(isRequestStream(stream)) {
// Request Stream
return new RequestStream(stream, options);
}
if(isClassicStream(stream)) {
if(stream.readable && stream.writable) {
// Duplex
return new ClassicDuplex(stream, options);
} else if(stream.readable) {
// Readable
return new ClassicReadable(stream, options);
} else {
// Writable
return new ClassicWritable(stream, options);
}
}
var origFuncs = {};
for(var key in stream) {
origFuncs[key] = stream[key];
}
// Use duck typing in case of multiple stream implementations
extend(stream, streamMixins.prototype);
streamMixins.call(stream, origFuncs);
if(stream.read) {
extend(stream, readableMixins.prototype);
readableMixins.call(stream);
}
if(stream.write) {
extend(stream, writableMixins.prototype);
writableMixins.call(stream);
}
if(typeof process === 'object' && (stream === process.stdout || stream === process.stderr)) {
// Don't abort stdio streams on error
stream._zNoAbort = true;
}
return stream;
} | [
"function",
"convertToZStream",
"(",
"stream",
",",
"options",
")",
"{",
"if",
"(",
"stream",
".",
"_isZStream",
")",
"return",
"stream",
";",
"if",
"(",
"isRequestStream",
"(",
"stream",
")",
")",
"{",
"return",
"new",
"RequestStream",
"(",
"stream",
",",
"options",
")",
";",
"}",
"if",
"(",
"isClassicStream",
"(",
"stream",
")",
")",
"{",
"if",
"(",
"stream",
".",
"readable",
"&&",
"stream",
".",
"writable",
")",
"{",
"return",
"new",
"ClassicDuplex",
"(",
"stream",
",",
"options",
")",
";",
"}",
"else",
"if",
"(",
"stream",
".",
"readable",
")",
"{",
"return",
"new",
"ClassicReadable",
"(",
"stream",
",",
"options",
")",
";",
"}",
"else",
"{",
"return",
"new",
"ClassicWritable",
"(",
"stream",
",",
"options",
")",
";",
"}",
"}",
"var",
"origFuncs",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"stream",
")",
"{",
"origFuncs",
"[",
"key",
"]",
"=",
"stream",
"[",
"key",
"]",
";",
"}",
"extend",
"(",
"stream",
",",
"streamMixins",
".",
"prototype",
")",
";",
"streamMixins",
".",
"call",
"(",
"stream",
",",
"origFuncs",
")",
";",
"if",
"(",
"stream",
".",
"read",
")",
"{",
"extend",
"(",
"stream",
",",
"readableMixins",
".",
"prototype",
")",
";",
"readableMixins",
".",
"call",
"(",
"stream",
")",
";",
"}",
"if",
"(",
"stream",
".",
"write",
")",
"{",
"extend",
"(",
"stream",
",",
"writableMixins",
".",
"prototype",
")",
";",
"writableMixins",
".",
"call",
"(",
"stream",
")",
";",
"}",
"if",
"(",
"typeof",
"process",
"===",
"'object'",
"&&",
"(",
"stream",
"===",
"process",
".",
"stdout",
"||",
"stream",
"===",
"process",
".",
"stderr",
")",
")",
"{",
"stream",
".",
"_zNoAbort",
"=",
"true",
";",
"}",
"return",
"stream",
";",
"}"
] | Convert a Stream into a ZStream. Either by wrapping it, or adding ZStream mixins
@class zstreams
@static
@method convertToZStream
@param {Stream} stream - The stream to try converting into a ZStream
@param {Object} [options] - If expecting to convert, this will be passed as options into the stream being instanciated. | [
"Convert",
"a",
"Stream",
"into",
"a",
"ZStream",
".",
"Either",
"by",
"wrapping",
"it",
"or",
"adding",
"ZStream",
"mixins"
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/conversion.js#L39-L80 | train |
back4app/back4app-entity | src/back/models/Entity.js | isDirty | function isDirty(attribute) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when checking if an Entity attribute is ' +
'dirty (it has to be passed less than 2 arguments)'
);
var attributes = this.Entity.attributes;
if (attribute) {
expect(attribute).to.be.a(
'string',
'Invalid argument "attribute" when checking if an Entity attribute ' +
'is dirty (it has to be a string)'
);
expect(attributes).to.have.ownProperty(
attribute,
'Invalid argument "attribute" when checking an Entity attribute ' +
'is dirty (this attribute does not exist in the Entity)'
);
var newAttributes = {};
newAttributes[attribute] = attributes[attribute];
attributes = newAttributes;
}
if (this.isNew) {
return true;
}
for (var attributeName in attributes) {
if (_cleanSet) {
if (_attributeIsSet[attributeName]) {
if (
!_attributeStorageValues.hasOwnProperty(attributeName) ||
_attributeStorageValues[attributeName] !== this[attributeName]
) {
return true;
}
}
} else {
if (
!_attributeStorageValues.hasOwnProperty(attributeName) ||
_attributeStorageValues[attributeName] !== this[attributeName]
) {
return true;
}
}
}
return false;
} | javascript | function isDirty(attribute) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when checking if an Entity attribute is ' +
'dirty (it has to be passed less than 2 arguments)'
);
var attributes = this.Entity.attributes;
if (attribute) {
expect(attribute).to.be.a(
'string',
'Invalid argument "attribute" when checking if an Entity attribute ' +
'is dirty (it has to be a string)'
);
expect(attributes).to.have.ownProperty(
attribute,
'Invalid argument "attribute" when checking an Entity attribute ' +
'is dirty (this attribute does not exist in the Entity)'
);
var newAttributes = {};
newAttributes[attribute] = attributes[attribute];
attributes = newAttributes;
}
if (this.isNew) {
return true;
}
for (var attributeName in attributes) {
if (_cleanSet) {
if (_attributeIsSet[attributeName]) {
if (
!_attributeStorageValues.hasOwnProperty(attributeName) ||
_attributeStorageValues[attributeName] !== this[attributeName]
) {
return true;
}
}
} else {
if (
!_attributeStorageValues.hasOwnProperty(attributeName) ||
_attributeStorageValues[attributeName] !== this[attributeName]
) {
return true;
}
}
}
return false;
} | [
"function",
"isDirty",
"(",
"attribute",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"below",
"(",
"2",
",",
"'Invalid arguments length when checking if an Entity attribute is '",
"+",
"'dirty (it has to be passed less than 2 arguments)'",
")",
";",
"var",
"attributes",
"=",
"this",
".",
"Entity",
".",
"attributes",
";",
"if",
"(",
"attribute",
")",
"{",
"expect",
"(",
"attribute",
")",
".",
"to",
".",
"be",
".",
"a",
"(",
"'string'",
",",
"'Invalid argument \"attribute\" when checking if an Entity attribute '",
"+",
"'is dirty (it has to be a string)'",
")",
";",
"expect",
"(",
"attributes",
")",
".",
"to",
".",
"have",
".",
"ownProperty",
"(",
"attribute",
",",
"'Invalid argument \"attribute\" when checking an Entity attribute '",
"+",
"'is dirty (this attribute does not exist in the Entity)'",
")",
";",
"var",
"newAttributes",
"=",
"{",
"}",
";",
"newAttributes",
"[",
"attribute",
"]",
"=",
"attributes",
"[",
"attribute",
"]",
";",
"attributes",
"=",
"newAttributes",
";",
"}",
"if",
"(",
"this",
".",
"isNew",
")",
"{",
"return",
"true",
";",
"}",
"for",
"(",
"var",
"attributeName",
"in",
"attributes",
")",
"{",
"if",
"(",
"_cleanSet",
")",
"{",
"if",
"(",
"_attributeIsSet",
"[",
"attributeName",
"]",
")",
"{",
"if",
"(",
"!",
"_attributeStorageValues",
".",
"hasOwnProperty",
"(",
"attributeName",
")",
"||",
"_attributeStorageValues",
"[",
"attributeName",
"]",
"!==",
"this",
"[",
"attributeName",
"]",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"_attributeStorageValues",
".",
"hasOwnProperty",
"(",
"attributeName",
")",
"||",
"_attributeStorageValues",
"[",
"attributeName",
"]",
"!==",
"this",
"[",
"attributeName",
"]",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks if an Entity attribute is dirty.
@name module:back4app-entity/models.Entity#isDirty
@function
@param {?string} [attribute] The name of the attribute to be checked. If no
attribute is passed, all attributes will be checked.
@returns {boolean} True if is dirty and false otherwise.
@example
console.log(myEntity.isDirty('myAttribute')); // Validates attribute
// "myAttribute" of
// Entity "myEntity"
@example
console.log(myEntity.isDirty()); // Checks all attributes of "myEntity" | [
"Checks",
"if",
"an",
"Entity",
"attribute",
"is",
"dirty",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L373-L425 | train |
back4app/back4app-entity | src/back/models/Entity.js | clean | function clean(attribute) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when cleaning an Entity attribute (it has ' +
'to be passed less than 2 arguments)'
);
var attributes = this.Entity.attributes;
if (attribute) {
expect(attribute).to.be.a(
'string',
'Invalid argument "attribute" when cleaning an Entity attribute (it ' +
'has to be a string)'
);
expect(attributes).to.have.ownProperty(
attribute,
'Invalid argument "attribute" when cleaning an Entity attribute ' +
'(this attribute does not exist in the Entity)'
);
var newAttributes = {};
newAttributes[attribute] = attributes[attribute];
attributes = newAttributes;
}
for (var attributeName in attributes) {
_attributeStorageValues[attributeName] = this[attributeName];
_attributeIsSet[attributeName] = false;
}
} | javascript | function clean(attribute) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when cleaning an Entity attribute (it has ' +
'to be passed less than 2 arguments)'
);
var attributes = this.Entity.attributes;
if (attribute) {
expect(attribute).to.be.a(
'string',
'Invalid argument "attribute" when cleaning an Entity attribute (it ' +
'has to be a string)'
);
expect(attributes).to.have.ownProperty(
attribute,
'Invalid argument "attribute" when cleaning an Entity attribute ' +
'(this attribute does not exist in the Entity)'
);
var newAttributes = {};
newAttributes[attribute] = attributes[attribute];
attributes = newAttributes;
}
for (var attributeName in attributes) {
_attributeStorageValues[attributeName] = this[attributeName];
_attributeIsSet[attributeName] = false;
}
} | [
"function",
"clean",
"(",
"attribute",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"below",
"(",
"2",
",",
"'Invalid arguments length when cleaning an Entity attribute (it has '",
"+",
"'to be passed less than 2 arguments)'",
")",
";",
"var",
"attributes",
"=",
"this",
".",
"Entity",
".",
"attributes",
";",
"if",
"(",
"attribute",
")",
"{",
"expect",
"(",
"attribute",
")",
".",
"to",
".",
"be",
".",
"a",
"(",
"'string'",
",",
"'Invalid argument \"attribute\" when cleaning an Entity attribute (it '",
"+",
"'has to be a string)'",
")",
";",
"expect",
"(",
"attributes",
")",
".",
"to",
".",
"have",
".",
"ownProperty",
"(",
"attribute",
",",
"'Invalid argument \"attribute\" when cleaning an Entity attribute '",
"+",
"'(this attribute does not exist in the Entity)'",
")",
";",
"var",
"newAttributes",
"=",
"{",
"}",
";",
"newAttributes",
"[",
"attribute",
"]",
"=",
"attributes",
"[",
"attribute",
"]",
";",
"attributes",
"=",
"newAttributes",
";",
"}",
"for",
"(",
"var",
"attributeName",
"in",
"attributes",
")",
"{",
"_attributeStorageValues",
"[",
"attributeName",
"]",
"=",
"this",
"[",
"attributeName",
"]",
";",
"_attributeIsSet",
"[",
"attributeName",
"]",
"=",
"false",
";",
"}",
"}"
] | Cleans an Entity attribute.
@name module:back4app-entity/models.Entity#clean
@function
@param {?string} [attribute] The name of the attribute to be cleaned. If no
attribute is passed, all attributes will be cleaned.
@example
myEntity.clean('myAttribute'); // Cleans attribute "myAttribute" of
// Entity "myEntity"
@example
myEntity.clean(); // Cleans all attributes of "myEntity" | [
"Cleans",
"an",
"Entity",
"attribute",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L439-L470 | train |
back4app/back4app-entity | src/back/models/Entity.js | _visitSpecializations | function _visitSpecializations(entities, visitedEntities) {
for (var entityName in entities) {
if (!visitedEntities.hasOwnProperty(entityName)) {
visitedEntities[entityName] = entities[entityName];
_visitSpecializations(
entities[entityName].directSpecializations,
visitedEntities
);
}
}
} | javascript | function _visitSpecializations(entities, visitedEntities) {
for (var entityName in entities) {
if (!visitedEntities.hasOwnProperty(entityName)) {
visitedEntities[entityName] = entities[entityName];
_visitSpecializations(
entities[entityName].directSpecializations,
visitedEntities
);
}
}
} | [
"function",
"_visitSpecializations",
"(",
"entities",
",",
"visitedEntities",
")",
"{",
"for",
"(",
"var",
"entityName",
"in",
"entities",
")",
"{",
"if",
"(",
"!",
"visitedEntities",
".",
"hasOwnProperty",
"(",
"entityName",
")",
")",
"{",
"visitedEntities",
"[",
"entityName",
"]",
"=",
"entities",
"[",
"entityName",
"]",
";",
"_visitSpecializations",
"(",
"entities",
"[",
"entityName",
"]",
".",
"directSpecializations",
",",
"visitedEntities",
")",
";",
"}",
"}",
"}"
] | Visits all specializations of a list of entities.
@name module:back4app-entity/models.Entity~_visitSpecializations
@function
@param entities The entities whose specializations shall be visited.
@param visitedEntities The list of visited entities.
@private
@example
var specializations = [];
_visitSpecializations(MyEntity.directSpecializations, specializations);
console.log(specializations); // Logs all specializations of MyEntity | [
"Visits",
"all",
"specializations",
"of",
"a",
"list",
"of",
"entities",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L743-L754 | train |
back4app/back4app-entity | src/back/models/Entity.js | function (CurrentEntity) {
return function (entity) {
expect(arguments).to.have.length(
1,
'Invalid arguments length when getting an Entity specialization (it ' +
'has to be passed 1 argument)'
);
expect(entity).to.be.a(
'string',
'Invalid argument when creating a new Entity function (it has to be ' +
'a string'
);
var entities = CurrentEntity.specializations;
try {
expect(entities).to.have.ownProperty(entity);
} catch (e) {
throw new errors.EntityNotFoundError(
entity,
e
);
}
return entities[entity];
};
} | javascript | function (CurrentEntity) {
return function (entity) {
expect(arguments).to.have.length(
1,
'Invalid arguments length when getting an Entity specialization (it ' +
'has to be passed 1 argument)'
);
expect(entity).to.be.a(
'string',
'Invalid argument when creating a new Entity function (it has to be ' +
'a string'
);
var entities = CurrentEntity.specializations;
try {
expect(entities).to.have.ownProperty(entity);
} catch (e) {
throw new errors.EntityNotFoundError(
entity,
e
);
}
return entities[entity];
};
} | [
"function",
"(",
"CurrentEntity",
")",
"{",
"return",
"function",
"(",
"entity",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"1",
",",
"'Invalid arguments length when getting an Entity specialization (it '",
"+",
"'has to be passed 1 argument)'",
")",
";",
"expect",
"(",
"entity",
")",
".",
"to",
".",
"be",
".",
"a",
"(",
"'string'",
",",
"'Invalid argument when creating a new Entity function (it has to be '",
"+",
"'a string'",
")",
";",
"var",
"entities",
"=",
"CurrentEntity",
".",
"specializations",
";",
"try",
"{",
"expect",
"(",
"entities",
")",
".",
"to",
".",
"have",
".",
"ownProperty",
"(",
"entity",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"errors",
".",
"EntityNotFoundError",
"(",
"entity",
",",
"e",
")",
";",
"}",
"return",
"entities",
"[",
"entity",
"]",
";",
"}",
";",
"}"
] | Private function used to get the getSpecialization function specific for the
current Entity class.
@name module:back4app-entity/models.Entity~_getGetSpecializationFunction
@function
@param {!Class} CurrentEntity The current entity class for which the new
function will be created.
@returns {Function} The new function.
@private
@example
Entity.getSpecialization = _getGetSpecializationFunction(Entity); | [
"Private",
"function",
"used",
"to",
"get",
"the",
"getSpecialization",
"function",
"specific",
"for",
"the",
"current",
"Entity",
"class",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1236-L1263 | train |
|
back4app/back4app-entity | src/back/models/Entity.js | function (CurrentEntity) {
return function (entity) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when creating a new Entity function (it has ' +
'to be passed less than 2 arguments)'
);
return function (attributeValues) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when creating a new Entity (it has ' +
'not to be passed less than 2 arguments)'
);
var EntityClass = CurrentEntity;
if (entity) {
EntityClass = Entity.getSpecialization(entity);
}
return new EntityClass(attributeValues);
};
};
} | javascript | function (CurrentEntity) {
return function (entity) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when creating a new Entity function (it has ' +
'to be passed less than 2 arguments)'
);
return function (attributeValues) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when creating a new Entity (it has ' +
'not to be passed less than 2 arguments)'
);
var EntityClass = CurrentEntity;
if (entity) {
EntityClass = Entity.getSpecialization(entity);
}
return new EntityClass(attributeValues);
};
};
} | [
"function",
"(",
"CurrentEntity",
")",
"{",
"return",
"function",
"(",
"entity",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"below",
"(",
"2",
",",
"'Invalid arguments length when creating a new Entity function (it has '",
"+",
"'to be passed less than 2 arguments)'",
")",
";",
"return",
"function",
"(",
"attributeValues",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"below",
"(",
"2",
",",
"'Invalid arguments length when creating a new Entity (it has '",
"+",
"'not to be passed less than 2 arguments)'",
")",
";",
"var",
"EntityClass",
"=",
"CurrentEntity",
";",
"if",
"(",
"entity",
")",
"{",
"EntityClass",
"=",
"Entity",
".",
"getSpecialization",
"(",
"entity",
")",
";",
"}",
"return",
"new",
"EntityClass",
"(",
"attributeValues",
")",
";",
"}",
";",
"}",
";",
"}"
] | Private function used to get the new function specific for the current Entity
class.
@name module:back4app-entity/models.Entity~_getNewFunction
@function
@param {!Class} CurrentEntity The current entity class for which the new
function will be created.
@returns {function} The new function.
@private
@example
Entity.new = _getNewFunction(Entity); | [
"Private",
"function",
"used",
"to",
"get",
"the",
"new",
"function",
"specific",
"for",
"the",
"current",
"Entity",
"class",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1290-L1314 | train |
|
back4app/back4app-entity | src/back/models/Entity.js | function (CurrentEntity) {
return function (attributeValues) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when creating a new "' +
CurrentEntity.specification.name +
'" instance (it has to be passed less than 2 arguments)');
return new Promise(function (resolve, reject) {
var newEntity = new CurrentEntity(attributeValues);
newEntity
.save({
forceCreate: true
})
.then(function () {
resolve(newEntity);
})
.catch(reject);
});
};
} | javascript | function (CurrentEntity) {
return function (attributeValues) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when creating a new "' +
CurrentEntity.specification.name +
'" instance (it has to be passed less than 2 arguments)');
return new Promise(function (resolve, reject) {
var newEntity = new CurrentEntity(attributeValues);
newEntity
.save({
forceCreate: true
})
.then(function () {
resolve(newEntity);
})
.catch(reject);
});
};
} | [
"function",
"(",
"CurrentEntity",
")",
"{",
"return",
"function",
"(",
"attributeValues",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"below",
"(",
"2",
",",
"'Invalid arguments length when creating a new \"'",
"+",
"CurrentEntity",
".",
"specification",
".",
"name",
"+",
"'\" instance (it has to be passed less than 2 arguments)'",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"newEntity",
"=",
"new",
"CurrentEntity",
"(",
"attributeValues",
")",
";",
"newEntity",
".",
"save",
"(",
"{",
"forceCreate",
":",
"true",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"resolve",
"(",
"newEntity",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Private function used to get the create function specific for the current
Entity class.
@name module:back4app-entity/models.Entity~_getCreateFunction
@function
@param {!Class} CurrentEntity The current entity class for which the new
function will be created.
@returns {function} The new function.
@private
@example
Entity.create = _getCreateFunction(Entity); | [
"Private",
"function",
"used",
"to",
"get",
"the",
"create",
"function",
"specific",
"for",
"the",
"current",
"Entity",
"class",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1343-L1364 | train |
|
back4app/back4app-entity | src/back/models/Entity.js | _getFindFunction | function _getFindFunction(CurrentEntity) {
return function (query, params) {
expect(arguments).to.have.length.within(
1,
2,
'Invalid arguments length when finding an Entity ' +
'(it has to be passed 1 or 2 arguments)'
);
expect(query).to.be.an(
'object',
'Invalid argument when finding an Entity (it has to be an object)'
);
return Promise.try(function () {
var adapter = CurrentEntity.adapter;
return adapter.findObjects(CurrentEntity, query, params);
});
};
} | javascript | function _getFindFunction(CurrentEntity) {
return function (query, params) {
expect(arguments).to.have.length.within(
1,
2,
'Invalid arguments length when finding an Entity ' +
'(it has to be passed 1 or 2 arguments)'
);
expect(query).to.be.an(
'object',
'Invalid argument when finding an Entity (it has to be an object)'
);
return Promise.try(function () {
var adapter = CurrentEntity.adapter;
return adapter.findObjects(CurrentEntity, query, params);
});
};
} | [
"function",
"_getFindFunction",
"(",
"CurrentEntity",
")",
"{",
"return",
"function",
"(",
"query",
",",
"params",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"within",
"(",
"1",
",",
"2",
",",
"'Invalid arguments length when finding an Entity '",
"+",
"'(it has to be passed 1 or 2 arguments)'",
")",
";",
"expect",
"(",
"query",
")",
".",
"to",
".",
"be",
".",
"an",
"(",
"'object'",
",",
"'Invalid argument when finding an Entity (it has to be an object)'",
")",
";",
"return",
"Promise",
".",
"try",
"(",
"function",
"(",
")",
"{",
"var",
"adapter",
"=",
"CurrentEntity",
".",
"adapter",
";",
"return",
"adapter",
".",
"findObjects",
"(",
"CurrentEntity",
",",
"query",
",",
"params",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Private function used to get the `find` function specific for the current
Entity class.
@name module:back4app-entity/models.Entity~_getFindFunction
@function
@param {!Class} CurrentEntity The current entity class for which the new
function will be created.
@returns {function} The find function.
@private
@example
Entity.find = _getFindFunction(Entity); | [
"Private",
"function",
"used",
"to",
"get",
"the",
"find",
"function",
"specific",
"for",
"the",
"current",
"Entity",
"class",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1449-L1468 | train |
back4app/back4app-entity | src/back/models/Entity.js | isValid | function isValid(attribute) {
try {
this.validate(attribute);
} catch (e) {
if (e instanceof errors.ValidationError) {
return false;
} else {
throw e;
}
}
return true;
} | javascript | function isValid(attribute) {
try {
this.validate(attribute);
} catch (e) {
if (e instanceof errors.ValidationError) {
return false;
} else {
throw e;
}
}
return true;
} | [
"function",
"isValid",
"(",
"attribute",
")",
"{",
"try",
"{",
"this",
".",
"validate",
"(",
"attribute",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"errors",
".",
"ValidationError",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"throw",
"e",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Validates an entity and returns a boolean indicating if it is valid.
@name module:back4app-entity/models.Entity#isValid
@function
@param {?string} [attribute] The name of the attribute to be validated. If no
attribute is passed, all attributes will be validated.
@returns {boolean} The validation result.
@example
myEntity.isValid('myAttribute'); // Validates attribute "myAttribute" of
// Entity "myEntity" and returns true/false
@example
myEntity.isValid(); // Validates all attributes of "myEntity" and returns
// true/false | [
"Validates",
"an",
"entity",
"and",
"returns",
"a",
"boolean",
"indicating",
"if",
"it",
"is",
"valid",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1550-L1561 | train |
cloudfour/drizzle-builder | src/utils/shared.js | relativePathArray | function relativePathArray(filePath, fromPath) {
filePath = path.normalize(filePath);
fromPath = path.normalize(fromPath);
if (filePath.indexOf(fromPath) === -1 || filePath === fromPath) {
// TODO Error handling: this should cause a warn
return [];
}
const keys = path.relative(fromPath, path.dirname(filePath));
if (keys && keys.length !== 0) {
return keys.split(path.sep);
}
return [];
} | javascript | function relativePathArray(filePath, fromPath) {
filePath = path.normalize(filePath);
fromPath = path.normalize(fromPath);
if (filePath.indexOf(fromPath) === -1 || filePath === fromPath) {
// TODO Error handling: this should cause a warn
return [];
}
const keys = path.relative(fromPath, path.dirname(filePath));
if (keys && keys.length !== 0) {
return keys.split(path.sep);
}
return [];
} | [
"function",
"relativePathArray",
"(",
"filePath",
",",
"fromPath",
")",
"{",
"filePath",
"=",
"path",
".",
"normalize",
"(",
"filePath",
")",
";",
"fromPath",
"=",
"path",
".",
"normalize",
"(",
"fromPath",
")",
";",
"if",
"(",
"filePath",
".",
"indexOf",
"(",
"fromPath",
")",
"===",
"-",
"1",
"||",
"filePath",
"===",
"fromPath",
")",
"{",
"return",
"[",
"]",
";",
"}",
"const",
"keys",
"=",
"path",
".",
"relative",
"(",
"fromPath",
",",
"path",
".",
"dirname",
"(",
"filePath",
")",
")",
";",
"if",
"(",
"keys",
"&&",
"keys",
".",
"length",
"!==",
"0",
")",
"{",
"return",
"keys",
".",
"split",
"(",
"path",
".",
"sep",
")",
";",
"}",
"return",
"[",
"]",
";",
"}"
] | Given a file's path and a string representing a directory name,
return an Array that only contains directories at or beneath that
directory.
@example relativePathArray('/foo/bar/baz/ding/dong/tink.txt', 'baz')
// -> ['baz', 'ding', 'dong']
@param {String} filePath
@param {String} fromPath
@return {Array} | [
"Given",
"a",
"file",
"s",
"path",
"and",
"a",
"string",
"representing",
"a",
"directory",
"name",
"return",
"an",
"Array",
"that",
"only",
"contains",
"directories",
"at",
"or",
"beneath",
"that",
"directory",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/shared.js#L33-L45 | train |
cloudfour/drizzle-builder | src/utils/shared.js | resourcePath | function resourcePath(resourceId, dest = '') {
const subPath = idKeys(resourceId);
// Remove first item because it is the "resource type"
// If there _is_ only one item in the ID, it will be left alone
// To serve as the filename.
if (subPath.length !== 0 && subPath.length > 1) {
subPath.shift();
}
const filename = subPath.pop() + '.html';
const outputPath = path.normalize(
path.join(dest, subPath.join(path.sep), filename)
);
return outputPath;
} | javascript | function resourcePath(resourceId, dest = '') {
const subPath = idKeys(resourceId);
// Remove first item because it is the "resource type"
// If there _is_ only one item in the ID, it will be left alone
// To serve as the filename.
if (subPath.length !== 0 && subPath.length > 1) {
subPath.shift();
}
const filename = subPath.pop() + '.html';
const outputPath = path.normalize(
path.join(dest, subPath.join(path.sep), filename)
);
return outputPath;
} | [
"function",
"resourcePath",
"(",
"resourceId",
",",
"dest",
"=",
"''",
")",
"{",
"const",
"subPath",
"=",
"idKeys",
"(",
"resourceId",
")",
";",
"if",
"(",
"subPath",
".",
"length",
"!==",
"0",
"&&",
"subPath",
".",
"length",
">",
"1",
")",
"{",
"subPath",
".",
"shift",
"(",
")",
";",
"}",
"const",
"filename",
"=",
"subPath",
".",
"pop",
"(",
")",
"+",
"'.html'",
";",
"const",
"outputPath",
"=",
"path",
".",
"normalize",
"(",
"path",
".",
"join",
"(",
"dest",
",",
"subPath",
".",
"join",
"(",
"path",
".",
"sep",
")",
",",
"filename",
")",
")",
";",
"return",
"outputPath",
";",
"}"
] | Generate a path for a resource based on its ID.
@param {String} resourceId '.'-separated ID for this resource
@param {String} dest This path will be prepended
@return {String} path | [
"Generate",
"a",
"path",
"for",
"a",
"resource",
"based",
"on",
"its",
"ID",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/shared.js#L53-L66 | train |
crispy1989/node-zstreams | lib/passthrough.js | ZPassThrough | function ZPassThrough(options) {
if(options) {
if(options.objectMode) {
options.readableObjectMode = true;
options.writableObjectMode = true;
}
if(options.readableObjectMode && options.writableObjectMode) {
options.objectMode = true;
}
}
PassThrough.call(this, options);
// note: exclamation marks are used to convert to booleans
if(options && !options.objectMode && (!options.readableObjectMode) !== (!options.writableObjectMode)) {
this._writableState.objectMode = !!options.writableObjectMode;
this._readableState.objectMode = !!options.readableObjectMode;
}
if(options && options.readableObjectMode) {
this._readableState.highWaterMark = 16;
}
if(options && options.writableObjectMode) {
this._writableState.highWaterMark = 16;
}
streamMixins.call(this, PassThrough.prototype, options);
readableMixins.call(this, options);
writableMixins.call(this, options);
} | javascript | function ZPassThrough(options) {
if(options) {
if(options.objectMode) {
options.readableObjectMode = true;
options.writableObjectMode = true;
}
if(options.readableObjectMode && options.writableObjectMode) {
options.objectMode = true;
}
}
PassThrough.call(this, options);
// note: exclamation marks are used to convert to booleans
if(options && !options.objectMode && (!options.readableObjectMode) !== (!options.writableObjectMode)) {
this._writableState.objectMode = !!options.writableObjectMode;
this._readableState.objectMode = !!options.readableObjectMode;
}
if(options && options.readableObjectMode) {
this._readableState.highWaterMark = 16;
}
if(options && options.writableObjectMode) {
this._writableState.highWaterMark = 16;
}
streamMixins.call(this, PassThrough.prototype, options);
readableMixins.call(this, options);
writableMixins.call(this, options);
} | [
"function",
"ZPassThrough",
"(",
"options",
")",
"{",
"if",
"(",
"options",
")",
"{",
"if",
"(",
"options",
".",
"objectMode",
")",
"{",
"options",
".",
"readableObjectMode",
"=",
"true",
";",
"options",
".",
"writableObjectMode",
"=",
"true",
";",
"}",
"if",
"(",
"options",
".",
"readableObjectMode",
"&&",
"options",
".",
"writableObjectMode",
")",
"{",
"options",
".",
"objectMode",
"=",
"true",
";",
"}",
"}",
"PassThrough",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"if",
"(",
"options",
"&&",
"!",
"options",
".",
"objectMode",
"&&",
"(",
"!",
"options",
".",
"readableObjectMode",
")",
"!==",
"(",
"!",
"options",
".",
"writableObjectMode",
")",
")",
"{",
"this",
".",
"_writableState",
".",
"objectMode",
"=",
"!",
"!",
"options",
".",
"writableObjectMode",
";",
"this",
".",
"_readableState",
".",
"objectMode",
"=",
"!",
"!",
"options",
".",
"readableObjectMode",
";",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"readableObjectMode",
")",
"{",
"this",
".",
"_readableState",
".",
"highWaterMark",
"=",
"16",
";",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"writableObjectMode",
")",
"{",
"this",
".",
"_writableState",
".",
"highWaterMark",
"=",
"16",
";",
"}",
"streamMixins",
".",
"call",
"(",
"this",
",",
"PassThrough",
".",
"prototype",
",",
"options",
")",
";",
"readableMixins",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"writableMixins",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"}"
] | ZPassThrough writes everything written to it into the other side
@class ZPassThrough
@constructor
@extends PassThrough
@uses _Stream
@uses _Readable
@uses _Writable
@param {Object} [options] - Stream options | [
"ZPassThrough",
"writes",
"everything",
"written",
"to",
"it",
"into",
"the",
"other",
"side"
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/passthrough.js#L19-L44 | train |
cloudfour/drizzle-builder | src/helpers/page.js | destRoot | function destRoot(type, drizzle) {
const options = drizzle.options;
// TODO: this is unfortunate, and due to difficulty using defaults.keys
const keys = new Map([
['page', 'pages'],
['collection', 'collections'],
['pattern', 'patterns']
]);
return relativePath(options.dest.root, options.dest[keys.get(type)]);
} | javascript | function destRoot(type, drizzle) {
const options = drizzle.options;
// TODO: this is unfortunate, and due to difficulty using defaults.keys
const keys = new Map([
['page', 'pages'],
['collection', 'collections'],
['pattern', 'patterns']
]);
return relativePath(options.dest.root, options.dest[keys.get(type)]);
} | [
"function",
"destRoot",
"(",
"type",
",",
"drizzle",
")",
"{",
"const",
"options",
"=",
"drizzle",
".",
"options",
";",
"const",
"keys",
"=",
"new",
"Map",
"(",
"[",
"[",
"'page'",
",",
"'pages'",
"]",
",",
"[",
"'collection'",
",",
"'collections'",
"]",
",",
"[",
"'pattern'",
",",
"'patterns'",
"]",
"]",
")",
";",
"return",
"relativePath",
"(",
"options",
".",
"dest",
".",
"root",
",",
"options",
".",
"dest",
"[",
"keys",
".",
"get",
"(",
"type",
")",
"]",
")",
";",
"}"
] | Return a relative base path for .html destinations.
@param {String} type
The resource type identifier (e.g. "page", "pattern", "collection")
@param {Object} drizzle
The Drizzle root context.
@return {String}
The relative base path for the supplied resource type. | [
"Return",
"a",
"relative",
"base",
"path",
"for",
".",
"html",
"destinations",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/helpers/page.js#L39-L50 | train |
cloudfour/drizzle-builder | src/parse/patterns.js | isHidden | function isHidden(collection, pattern, patternKey) {
return (
(collection.hidden && collection.hidden.indexOf(patternKey) !== -1) ||
(pattern.data && pattern.data.hidden)
);
} | javascript | function isHidden(collection, pattern, patternKey) {
return (
(collection.hidden && collection.hidden.indexOf(patternKey) !== -1) ||
(pattern.data && pattern.data.hidden)
);
} | [
"function",
"isHidden",
"(",
"collection",
",",
"pattern",
",",
"patternKey",
")",
"{",
"return",
"(",
"(",
"collection",
".",
"hidden",
"&&",
"collection",
".",
"hidden",
".",
"indexOf",
"(",
"patternKey",
")",
"!==",
"-",
"1",
")",
"||",
"(",
"pattern",
".",
"data",
"&&",
"pattern",
".",
"data",
".",
"hidden",
")",
")",
";",
"}"
] | Should this pattern be hidden per collection or pattern metadata?
@param {Object} collection Collection obj
@param {Object} pattern Pattern obj
@param {String} patternKey
@return {Boolean} | [
"Should",
"this",
"pattern",
"be",
"hidden",
"per",
"collection",
"or",
"pattern",
"metadata?"
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/patterns.js#L43-L48 | train |
cloudfour/drizzle-builder | src/parse/patterns.js | isCollection | function isCollection(obj) {
if (isPattern(obj)) {
return false;
}
return Object.keys(obj).some(childKey => isPattern(obj[childKey]));
} | javascript | function isCollection(obj) {
if (isPattern(obj)) {
return false;
}
return Object.keys(obj).some(childKey => isPattern(obj[childKey]));
} | [
"function",
"isCollection",
"(",
"obj",
")",
"{",
"if",
"(",
"isPattern",
"(",
"obj",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"some",
"(",
"childKey",
"=>",
"isPattern",
"(",
"obj",
"[",
"childKey",
"]",
")",
")",
";",
"}"
] | Is the obj a collection?
@param {Object} obj
@return {Boolean} | [
"Is",
"the",
"obj",
"a",
"collection?"
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/patterns.js#L55-L60 | train |
cloudfour/drizzle-builder | src/parse/patterns.js | buildPattern | function buildPattern(patternObj, options) {
const patternFile = { path: patternObj.path };
return Object.assign(patternObj, {
name:
(patternObj.data && patternObj.data.name) ||
titleCase(resourceKey(patternFile))
});
} | javascript | function buildPattern(patternObj, options) {
const patternFile = { path: patternObj.path };
return Object.assign(patternObj, {
name:
(patternObj.data && patternObj.data.name) ||
titleCase(resourceKey(patternFile))
});
} | [
"function",
"buildPattern",
"(",
"patternObj",
",",
"options",
")",
"{",
"const",
"patternFile",
"=",
"{",
"path",
":",
"patternObj",
".",
"path",
"}",
";",
"return",
"Object",
".",
"assign",
"(",
"patternObj",
",",
"{",
"name",
":",
"(",
"patternObj",
".",
"data",
"&&",
"patternObj",
".",
"data",
".",
"name",
")",
"||",
"titleCase",
"(",
"resourceKey",
"(",
"patternFile",
")",
")",
"}",
")",
";",
"}"
] | Flesh out an individual pattern object.
@param {Object} patternObj
@param {Object} options
@return {Object} built-out pattern | [
"Flesh",
"out",
"an",
"individual",
"pattern",
"object",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/patterns.js#L91-L98 | train |
cloudfour/drizzle-builder | src/parse/patterns.js | buildPatterns | function buildPatterns(collectionObj, options) {
const patterns = {};
for (const childKey in collectionObj) {
if (isPattern(collectionObj[childKey])) {
patterns[childKey] = buildPattern(collectionObj[childKey], options);
delete collectionObj[childKey];
}
}
return patterns;
} | javascript | function buildPatterns(collectionObj, options) {
const patterns = {};
for (const childKey in collectionObj) {
if (isPattern(collectionObj[childKey])) {
patterns[childKey] = buildPattern(collectionObj[childKey], options);
delete collectionObj[childKey];
}
}
return patterns;
} | [
"function",
"buildPatterns",
"(",
"collectionObj",
",",
"options",
")",
"{",
"const",
"patterns",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"childKey",
"in",
"collectionObj",
")",
"{",
"if",
"(",
"isPattern",
"(",
"collectionObj",
"[",
"childKey",
"]",
")",
")",
"{",
"patterns",
"[",
"childKey",
"]",
"=",
"buildPattern",
"(",
"collectionObj",
"[",
"childKey",
"]",
",",
"options",
")",
";",
"delete",
"collectionObj",
"[",
"childKey",
"]",
";",
"}",
"}",
"return",
"patterns",
";",
"}"
] | Flesh out all of the patterns that are within `collectionObj`. This is
before any of these patterns get assigned to `items` or `patterns` on
`collectionObj.collection`.
@param {Object} collectionObj The containing object with pattern children
that will ultimately be managed under
collectionObj.collection (items and patterns)
@param {Object} options
@return {Object} patterns Built-out pattern objects | [
"Flesh",
"out",
"all",
"of",
"the",
"patterns",
"that",
"are",
"within",
"collectionObj",
".",
"This",
"is",
"before",
"any",
"of",
"these",
"patterns",
"get",
"assigned",
"to",
"items",
"or",
"patterns",
"on",
"collectionObj",
".",
"collection",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/patterns.js#L111-L120 | train |
cloudfour/drizzle-builder | src/parse/patterns.js | buildCollection | function buildCollection(collectionObj, options) {
const items = buildPatterns(collectionObj, options);
const pseudoFile = { path: collectionPath(items) };
return readFiles(collectionGlob(items), options).then(collData => {
const collectionMeta = collData.length ? collData[0].contents : {};
collectionObj.collection = Object.assign(
{
name: titleCase(collectionKey(items)),
resourceType: options.keys.collections.singular,
id: resourceId(
pseudoFile,
options.src.patterns.basedir,
options.keys.collections.plural
)
},
collectionMeta
);
checkNamespaceCollision(
['items', 'patterns'],
collectionObj.collection,
`Collection ${collectionObj.collection.name}`,
options
);
collectionObj.collection.items = items;
collectionObj.collection.patterns = buildOrderedPatterns(
collectionObj.collection
);
return collectionObj;
});
} | javascript | function buildCollection(collectionObj, options) {
const items = buildPatterns(collectionObj, options);
const pseudoFile = { path: collectionPath(items) };
return readFiles(collectionGlob(items), options).then(collData => {
const collectionMeta = collData.length ? collData[0].contents : {};
collectionObj.collection = Object.assign(
{
name: titleCase(collectionKey(items)),
resourceType: options.keys.collections.singular,
id: resourceId(
pseudoFile,
options.src.patterns.basedir,
options.keys.collections.plural
)
},
collectionMeta
);
checkNamespaceCollision(
['items', 'patterns'],
collectionObj.collection,
`Collection ${collectionObj.collection.name}`,
options
);
collectionObj.collection.items = items;
collectionObj.collection.patterns = buildOrderedPatterns(
collectionObj.collection
);
return collectionObj;
});
} | [
"function",
"buildCollection",
"(",
"collectionObj",
",",
"options",
")",
"{",
"const",
"items",
"=",
"buildPatterns",
"(",
"collectionObj",
",",
"options",
")",
";",
"const",
"pseudoFile",
"=",
"{",
"path",
":",
"collectionPath",
"(",
"items",
")",
"}",
";",
"return",
"readFiles",
"(",
"collectionGlob",
"(",
"items",
")",
",",
"options",
")",
".",
"then",
"(",
"collData",
"=>",
"{",
"const",
"collectionMeta",
"=",
"collData",
".",
"length",
"?",
"collData",
"[",
"0",
"]",
".",
"contents",
":",
"{",
"}",
";",
"collectionObj",
".",
"collection",
"=",
"Object",
".",
"assign",
"(",
"{",
"name",
":",
"titleCase",
"(",
"collectionKey",
"(",
"items",
")",
")",
",",
"resourceType",
":",
"options",
".",
"keys",
".",
"collections",
".",
"singular",
",",
"id",
":",
"resourceId",
"(",
"pseudoFile",
",",
"options",
".",
"src",
".",
"patterns",
".",
"basedir",
",",
"options",
".",
"keys",
".",
"collections",
".",
"plural",
")",
"}",
",",
"collectionMeta",
")",
";",
"checkNamespaceCollision",
"(",
"[",
"'items'",
",",
"'patterns'",
"]",
",",
"collectionObj",
".",
"collection",
",",
"`",
"${",
"collectionObj",
".",
"collection",
".",
"name",
"}",
"`",
",",
"options",
")",
";",
"collectionObj",
".",
"collection",
".",
"items",
"=",
"items",
";",
"collectionObj",
".",
"collection",
".",
"patterns",
"=",
"buildOrderedPatterns",
"(",
"collectionObj",
".",
"collection",
")",
";",
"return",
"collectionObj",
";",
"}",
")",
";",
"}"
] | Build an individual collection object. Give it some metadata based on
defaults and any metadata file found in its path. Build the Array of
patterns that should appear on this pattern collection's page.
@param {Object} collectionObj The containing object that holds the patterns
that are part of this collection.
@param {Object} options
@return {Promise} resolving to {Object} representing the containing object
for this collection (as distinct from
collectionObj.collection, which is what this
function tacks on). | [
"Build",
"an",
"individual",
"collection",
"object",
".",
"Give",
"it",
"some",
"metadata",
"based",
"on",
"defaults",
"and",
"any",
"metadata",
"file",
"found",
"in",
"its",
"path",
".",
"Build",
"the",
"Array",
"of",
"patterns",
"that",
"should",
"appear",
"on",
"this",
"pattern",
"collection",
"s",
"page",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/patterns.js#L171-L200 | train |
cloudfour/drizzle-builder | src/parse/patterns.js | buildCollections | function buildCollections(patternObj, options, collectionPromises = []) {
if (isPattern(patternObj)) {
return collectionPromises;
}
if (isCollection(patternObj)) {
collectionPromises.push(buildCollection(patternObj, options));
}
for (const patternKey in patternObj) {
if (patternKey !== 'collection') {
buildCollections(patternObj[patternKey], options, collectionPromises);
}
}
return collectionPromises;
} | javascript | function buildCollections(patternObj, options, collectionPromises = []) {
if (isPattern(patternObj)) {
return collectionPromises;
}
if (isCollection(patternObj)) {
collectionPromises.push(buildCollection(patternObj, options));
}
for (const patternKey in patternObj) {
if (patternKey !== 'collection') {
buildCollections(patternObj[patternKey], options, collectionPromises);
}
}
return collectionPromises;
} | [
"function",
"buildCollections",
"(",
"patternObj",
",",
"options",
",",
"collectionPromises",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"isPattern",
"(",
"patternObj",
")",
")",
"{",
"return",
"collectionPromises",
";",
"}",
"if",
"(",
"isCollection",
"(",
"patternObj",
")",
")",
"{",
"collectionPromises",
".",
"push",
"(",
"buildCollection",
"(",
"patternObj",
",",
"options",
")",
")",
";",
"}",
"for",
"(",
"const",
"patternKey",
"in",
"patternObj",
")",
"{",
"if",
"(",
"patternKey",
"!==",
"'collection'",
")",
"{",
"buildCollections",
"(",
"patternObj",
"[",
"patternKey",
"]",
",",
"options",
",",
"collectionPromises",
")",
";",
"}",
"}",
"return",
"collectionPromises",
";",
"}"
] | Traverse and build collections data and their contained patterns based on
parsed pattern data.
@param {Object} patternObj Patterns at the current level of traverse.
@param {Object} options
@param {Array} collectionPromises Array of `{Promise}`s representing
reading collection metadata | [
"Traverse",
"and",
"build",
"collections",
"data",
"and",
"their",
"contained",
"patterns",
"based",
"on",
"parsed",
"pattern",
"data",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/patterns.js#L211-L224 | train |
cloudfour/drizzle-builder | src/parse/patterns.js | parsePatterns | function parsePatterns(options) {
return readFileTree(
options.src.patterns,
options.keys.patterns,
options
).then(patternObj => {
return Promise.all(buildCollections(patternObj, options)).then(
() => patternObj,
error => DrizzleError.error(error, options.debug)
);
});
} | javascript | function parsePatterns(options) {
return readFileTree(
options.src.patterns,
options.keys.patterns,
options
).then(patternObj => {
return Promise.all(buildCollections(patternObj, options)).then(
() => patternObj,
error => DrizzleError.error(error, options.debug)
);
});
} | [
"function",
"parsePatterns",
"(",
"options",
")",
"{",
"return",
"readFileTree",
"(",
"options",
".",
"src",
".",
"patterns",
",",
"options",
".",
"keys",
".",
"patterns",
",",
"options",
")",
".",
"then",
"(",
"patternObj",
"=>",
"{",
"return",
"Promise",
".",
"all",
"(",
"buildCollections",
"(",
"patternObj",
",",
"options",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"patternObj",
",",
"error",
"=>",
"DrizzleError",
".",
"error",
"(",
"error",
",",
"options",
".",
"debug",
")",
")",
";",
"}",
")",
";",
"}"
] | Parse pattern files and then flesh out individual pattern objects and
build collection data.
@param {Object} options
@return {Promise} resolving to pattern/collection data | [
"Parse",
"pattern",
"files",
"and",
"then",
"flesh",
"out",
"individual",
"pattern",
"objects",
"and",
"build",
"collection",
"data",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/patterns.js#L233-L244 | train |
feedhenry/fh-forms | lib/shared-mongo-connections.js | getAdminDbUrl | function getAdminDbUrl(mongoConnectionString, formUser, poolSize) {
var parsedMongoUrl = mongoUrlParser.parse(mongoConnectionString);
parsedMongoUrl.username = formUser.user;
parsedMongoUrl.password = formUser.pass;
//according to this: https://docs.mongodb.com/v2.4/reference/user-privileges/#any-database-roles, this type of user should be created in the `admin` database.
parsedMongoUrl.database = "admin";
parsedMongoUrl.options = parsedMongoUrl.options || {};
parsedMongoUrl.options.poolSize = poolSize || MONGODB_DEFAULT_POOL_SIZE;
var mongourl = mongoUrlParser.format(parsedMongoUrl);
return mongourl;
} | javascript | function getAdminDbUrl(mongoConnectionString, formUser, poolSize) {
var parsedMongoUrl = mongoUrlParser.parse(mongoConnectionString);
parsedMongoUrl.username = formUser.user;
parsedMongoUrl.password = formUser.pass;
//according to this: https://docs.mongodb.com/v2.4/reference/user-privileges/#any-database-roles, this type of user should be created in the `admin` database.
parsedMongoUrl.database = "admin";
parsedMongoUrl.options = parsedMongoUrl.options || {};
parsedMongoUrl.options.poolSize = poolSize || MONGODB_DEFAULT_POOL_SIZE;
var mongourl = mongoUrlParser.format(parsedMongoUrl);
return mongourl;
} | [
"function",
"getAdminDbUrl",
"(",
"mongoConnectionString",
",",
"formUser",
",",
"poolSize",
")",
"{",
"var",
"parsedMongoUrl",
"=",
"mongoUrlParser",
".",
"parse",
"(",
"mongoConnectionString",
")",
";",
"parsedMongoUrl",
".",
"username",
"=",
"formUser",
".",
"user",
";",
"parsedMongoUrl",
".",
"password",
"=",
"formUser",
".",
"pass",
";",
"parsedMongoUrl",
".",
"database",
"=",
"\"admin\"",
";",
"parsedMongoUrl",
".",
"options",
"=",
"parsedMongoUrl",
".",
"options",
"||",
"{",
"}",
";",
"parsedMongoUrl",
".",
"options",
".",
"poolSize",
"=",
"poolSize",
"||",
"MONGODB_DEFAULT_POOL_SIZE",
";",
"var",
"mongourl",
"=",
"mongoUrlParser",
".",
"format",
"(",
"parsedMongoUrl",
")",
";",
"return",
"mongourl",
";",
"}"
] | Get the url of the mongodb database that will the given formUser to connect.
@param {string} mongoConnectionString a mongodb url that should at least contain the mongodb hosts
@param {object} formUser a mongodb user that should have the "readWriteAnyDatabase" role to access any database. This type of user should exist in the mongo `admin` database.
@param {string} formUser.user the username
@param {string} formUser.pass the user password
@param {int} poolSize the poolSize of the mongodb connection. Default to 20.
@return {string} the mongodb connection url | [
"Get",
"the",
"url",
"of",
"the",
"mongodb",
"database",
"that",
"will",
"the",
"given",
"formUser",
"to",
"connect",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/shared-mongo-connections.js#L17-L27 | train |
feedhenry/fh-forms | lib/shared-mongo-connections.js | getMongodbConnection | function getMongodbConnection(mongoDbUrl, logger, cb) {
logger.debug("creating mongodb connection for data_source_update job", {mongoDbUrl: mongoDbUrl});
MongoClient.connect(mongoDbUrl, cb);
} | javascript | function getMongodbConnection(mongoDbUrl, logger, cb) {
logger.debug("creating mongodb connection for data_source_update job", {mongoDbUrl: mongoDbUrl});
MongoClient.connect(mongoDbUrl, cb);
} | [
"function",
"getMongodbConnection",
"(",
"mongoDbUrl",
",",
"logger",
",",
"cb",
")",
"{",
"logger",
".",
"debug",
"(",
"\"creating mongodb connection for data_source_update job\"",
",",
"{",
"mongoDbUrl",
":",
"mongoDbUrl",
"}",
")",
";",
"MongoClient",
".",
"connect",
"(",
"mongoDbUrl",
",",
"cb",
")",
";",
"}"
] | Create a new mongodb connection.
@param {string} mongoDbUrl the url to connect to the mongodb database
@param {object} logger
@param {function} cb the callback function | [
"Create",
"a",
"new",
"mongodb",
"connection",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/shared-mongo-connections.js#L35-L38 | train |
feedhenry/fh-forms | lib/shared-mongo-connections.js | getMongooseConnection | function getMongooseConnection(mongoDbUrl, logger, cb) {
logger.debug("creating mongoose connection for data_source_update job", {mongoDbUrl: mongoDbUrl});
var mongooseConnection = mongoose.createConnection(mongoDbUrl);
return cb(undefined, mongooseConnection);
} | javascript | function getMongooseConnection(mongoDbUrl, logger, cb) {
logger.debug("creating mongoose connection for data_source_update job", {mongoDbUrl: mongoDbUrl});
var mongooseConnection = mongoose.createConnection(mongoDbUrl);
return cb(undefined, mongooseConnection);
} | [
"function",
"getMongooseConnection",
"(",
"mongoDbUrl",
",",
"logger",
",",
"cb",
")",
"{",
"logger",
".",
"debug",
"(",
"\"creating mongoose connection for data_source_update job\"",
",",
"{",
"mongoDbUrl",
":",
"mongoDbUrl",
"}",
")",
";",
"var",
"mongooseConnection",
"=",
"mongoose",
".",
"createConnection",
"(",
"mongoDbUrl",
")",
";",
"return",
"cb",
"(",
"undefined",
",",
"mongooseConnection",
")",
";",
"}"
] | Create a new mongoose connection.
@param {string} mongoDbUrl the url to connect to the mongodb database
@param {object} logger
@param {function} cb the callback function | [
"Create",
"a",
"new",
"mongoose",
"connection",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/shared-mongo-connections.js#L46-L50 | train |
cloudfour/drizzle-builder | src/utils/list.js | sortByProp | function sortByProp(prop, list) {
const get = R.is(Array, prop) ? R.path : R.prop;
return R.sort((elA, elB) => {
const a = get(prop, elA);
const b = get(prop, elB);
return sortObjects(a, b);
}, list);
} | javascript | function sortByProp(prop, list) {
const get = R.is(Array, prop) ? R.path : R.prop;
return R.sort((elA, elB) => {
const a = get(prop, elA);
const b = get(prop, elB);
return sortObjects(a, b);
}, list);
} | [
"function",
"sortByProp",
"(",
"prop",
",",
"list",
")",
"{",
"const",
"get",
"=",
"R",
".",
"is",
"(",
"Array",
",",
"prop",
")",
"?",
"R",
".",
"path",
":",
"R",
".",
"prop",
";",
"return",
"R",
".",
"sort",
"(",
"(",
"elA",
",",
"elB",
")",
"=>",
"{",
"const",
"a",
"=",
"get",
"(",
"prop",
",",
"elA",
")",
";",
"const",
"b",
"=",
"get",
"(",
"prop",
",",
"elB",
")",
";",
"return",
"sortObjects",
"(",
"a",
",",
"b",
")",
";",
"}",
",",
"list",
")",
";",
"}"
] | Sort an array of objects by property.
@param {String|Array} prop
A property to sort by. If passed as an array, it
will be treated as a deep property path.
@param {Array} list
An array of objects to sort.
@return {Array}
A sorted copy of the passed array.
@example
sortByProp('order', items);
// [{order: 1}, {order: 2}]
@example
sortByProp(['data', 'title'], items);
// [{data: {title: 'a'}}, {data: {title: 'b'}}] | [
"Sort",
"an",
"array",
"of",
"objects",
"by",
"property",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/list.js#L27-L34 | train |
crispy1989/node-zstreams | lib/streams/classic-readable.js | ClassicReadable | function ClassicReadable(stream, options) {
Readable.call(this, options);
classicMixins.call(this, stream, options);
// Readable streams already include a wrapping for Classic Streams
this.wrap(stream);
} | javascript | function ClassicReadable(stream, options) {
Readable.call(this, options);
classicMixins.call(this, stream, options);
// Readable streams already include a wrapping for Classic Streams
this.wrap(stream);
} | [
"function",
"ClassicReadable",
"(",
"stream",
",",
"options",
")",
"{",
"Readable",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"classicMixins",
".",
"call",
"(",
"this",
",",
"stream",
",",
"options",
")",
";",
"this",
".",
"wrap",
"(",
"stream",
")",
";",
"}"
] | ClassicReadable wraps a "classic" readable stream.
@class ClassicReadable
@constructor
@extends ZReadable
@uses _Classic
@param {Stream} stream - The classic stream being wrapped
@param {Object} [options] - Stream options | [
"ClassicReadable",
"wraps",
"a",
"classic",
"readable",
"stream",
"."
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/classic-readable.js#L16-L22 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | list | function list(req, res, next) {
forms.getAllAppForms(req.connectionOptions, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function list(req, res, next) {
forms.getAllAppForms(req.connectionOptions, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"list",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"forms",
".",
"getAllAppForms",
"(",
"req",
".",
"connectionOptions",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | List All Form Projects
@param req
@param res
@param next | [
"List",
"All",
"Form",
"Projects"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L12-L14 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | update | function update(req, res, next) {
var params = {
appId: req.params.id || req.body._id,
forms: req.body.forms || []
};
forms.updateAppForms(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function update(req, res, next) {
var params = {
appId: req.params.id || req.body._id,
forms: req.body.forms || []
};
forms.updateAppForms(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"update",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"appId",
":",
"req",
".",
"params",
".",
"id",
"||",
"req",
".",
"body",
".",
"_id",
",",
"forms",
":",
"req",
".",
"body",
".",
"forms",
"||",
"[",
"]",
"}",
";",
"forms",
".",
"updateAppForms",
"(",
"req",
".",
"connectionOptions",
",",
"params",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Update Projects Using A Form
@param req
@param res
@param next | [
"Update",
"Projects",
"Using",
"A",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L22-L28 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | updateTheme | function updateTheme(req, res, next) {
//No theme sent, no need update the project theme
if (!req.body.theme) {
return next();
}
var params = {
appId: req.params.id || req.body._id,
theme: req.body.theme
};
forms.setAppTheme(_.extend(req.connectionOptions, params), formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function updateTheme(req, res, next) {
//No theme sent, no need update the project theme
if (!req.body.theme) {
return next();
}
var params = {
appId: req.params.id || req.body._id,
theme: req.body.theme
};
forms.setAppTheme(_.extend(req.connectionOptions, params), formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"updateTheme",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"!",
"req",
".",
"body",
".",
"theme",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"var",
"params",
"=",
"{",
"appId",
":",
"req",
".",
"params",
".",
"id",
"||",
"req",
".",
"body",
".",
"_id",
",",
"theme",
":",
"req",
".",
"body",
".",
"theme",
"}",
";",
"forms",
".",
"setAppTheme",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"params",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Middleware For Updating A Theme Associated With A Project
@param req
@param res
@param next | [
"Middleware",
"For",
"Updating",
"A",
"Theme",
"Associated",
"With",
"A",
"Project"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L37-L49 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | getFullTheme | function getFullTheme(req, res, next) {
req.getFullTheme = true;
getTheme(req, res, next);
} | javascript | function getFullTheme(req, res, next) {
req.getFullTheme = true;
getTheme(req, res, next);
} | [
"function",
"getFullTheme",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"req",
".",
"getFullTheme",
"=",
"true",
";",
"getTheme",
"(",
"req",
",",
"res",
",",
"next",
")",
";",
"}"
] | Middleware To Get A Full Theme Definition | [
"Middleware",
"To",
"Get",
"A",
"Full",
"Theme",
"Definition"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L55-L59 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.