_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q2300
getTheme
train
function getTheme(req, res, next) { var params = { appId: req.params.projectid || req.params.id }; forms.getAppTheme(_.extend(req.connectionOptions, params), function(err, theme) { if (err) { return next(err); } req.appformsResultPayload = req.appformsResultPayload || {}; if (_.isObject(req.appformsResultPayload.data) &&
javascript
{ "resource": "" }
q2301
remove
train
function remove(req, res, next) { var params = { appId: req.params.id }; forms.deleteAppReferences(req.connectionOptions,
javascript
{ "resource": "" }
q2302
get
train
function get(req, res, next) { var params = { appId: req.params.projectid || req.params.id
javascript
{ "resource": "" }
q2303
getFormIds
train
function getFormIds(req, res, next) { var params = { appId: req.params.projectid || req.params.id }; forms.getAppFormsForApp(_.extend(req.connectionOptions, params), function(err, appFormResult) { if (err) { return next(err); } //Only Want The Form Ids req.appformsResultPayload
javascript
{ "resource": "" }
q2304
getConfig
train
function getConfig(req, res, next) { var params = { appId: req.params.projectid || req.params.id
javascript
{ "resource": "" }
q2305
updateConfig
train
function updateConfig(req, res, next) { var params = { appId: req.params.id }; forms.updateAppConfig(req.connectionOptions, _.extend(req.body, params),
javascript
{ "resource": "" }
q2306
exportProjects
train
function exportProjects(req, res, next) { var options = req.connectionOptions; forms.exportAppForms(options,
javascript
{ "resource": "" }
q2307
importProjects
train
function importProjects(req, res, next) { var options = req.connectionOptions; var appFormsToImport = req.body || []; if (!_.isArray(appFormsToImport)) { return next("Expected An Array Of App Form Entries"); }
javascript
{ "resource": "" }
q2308
exportProjectConfig
train
function exportProjectConfig(req, res, next) { var options = req.connectionOptions; forms.exportAppConfig(options,
javascript
{ "resource": "" }
q2309
importProjectConfig
train
function importProjectConfig(req, res, next) { var options = req.connectionOptions; var projectConfigToImport = req.body || []; if (!_.isArray(projectConfigToImport)) { return next("Expected An Array Of Project Config Values"); }
javascript
{ "resource": "" }
q2310
loadPdfTemplate
train
function loadPdfTemplate(params, cb) { logger.debug("renderPDF loadPdfTemplate", params); //Already have a compiled template, no need to compile it again. if (pdfTemplate) { return cb(null, pdfTemplate); } else
javascript
{ "resource": "" }
q2311
write
train
function write(drizzleData) { return Promise.all([ writePages(drizzleData), writeCollections(drizzleData) ]).then( () =>
javascript
{ "resource": "" }
q2312
relinkUniforms
train
function relinkUniforms(gl, program, locations, uniforms) { for(var i=0; i<uniforms.length; ++i) { locations[i]
javascript
{ "resource": "" }
q2313
createShader
train
function createShader( gl , vertSource , fragSource , uniforms , attributes) { //Compile vertex shader var vertShader = gl.createShader(gl.VERTEX_SHADER) gl.shaderSource(vertShader, vertSource) gl.compileShader(vertShader) if(!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { var errLog = gl.getShaderInfoLog(vertShader) console.error('gl-shader: Error compling vertex shader:', errLog) throw new Error('gl-shader: Error compiling vertex shader:' + errLog) } //Compile fragment shader var fragShader = gl.createShader(gl.FRAGMENT_SHADER) gl.shaderSource(fragShader, fragSource) gl.compileShader(fragShader) if(!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { var errLog = gl.getShaderInfoLog(fragShader) console.error('gl-shader: Error compiling fragment shader:', errLog) throw new Error('gl-shader: Error compiling fragment shader:' + errLog) } //Link program var program = gl.createProgram() gl.attachShader(program, fragShader) gl.attachShader(program, vertShader) //Optional default attriubte locations attributes.forEach(function(a) { if
javascript
{ "resource": "" }
q2314
parsePages
train
function parsePages(options) { return readFileTree(options.src.pages,
javascript
{ "resource": "" }
q2315
ZTransform
train
function ZTransform(options) { if(options) { if(options.objectMode) { options.readableObjectMode = true; options.writableObjectMode = true; } if(options.readableObjectMode && options.writableObjectMode) { options.objectMode = true; } if(typeof options.transform === 'function') { this._transform = options.transform; } if(typeof options.flush === 'function') { this._flush = options.flush; } } Transform.call(this, options);
javascript
{ "resource": "" }
q2316
CompoundDuplex
train
function CompoundDuplex(writable, readable, options) { var self = this; var convertToZStream = require('../index'); // for circular dependencies if(!readable || typeof readable.read !== 'function') { options = readable; readable = writable; writable = null; } if(writable && !writable._isZStream) { writable = convertToZStream(writable); } if(!readable._isZStream) { readable = convertToZStream(readable); } if(!writable) { if(typeof readable.getStreamChain !== 'function') { throw new Error('Can only use shorthand CompoundDuplex constructor if pipeline is all zstreams'); } writable = readable.getStreamChain().getStreams()[0]; } if(!options) options = {}; options.readableObjectMode = readable.isReadableObjectMode(); options.writableObjectMode = writable.isWritableObjectMode(); Duplex.call(this, options);
javascript
{ "resource": "" }
q2317
get
train
function get(connections, params, cb) { //validateParams //LookUpDataSource //CheckFormsThatAre Using The Data Source //Return Result. async.waterfall([ function validateParams(cb) { validate(params).has(CONSTANTS.DATA_SOURCE_ID, function(err) { if (err) { return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Get A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } return cb(undefined, params[CONSTANTS.DATA_SOURCE_ID]); }); }, function findDataSources(id, cb) { var query = { }; //Searching By ID. query[CONSTANTS.DATA_SOURCE_ID] = id; lookUpDataSources(connections, { query: query, lean: true, includeAuditLog: params.includeAuditLog, includeAuditLogData: params.includeAuditLogData }, function(err, dataSources) { if (err) { return cb(buildErrorResponse({ error: err, userDetail: "Unexpected Error When Searching For A Data Source", code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } //Checking if the data source exists. Should be only one if (dataSources.length !== 1) {
javascript
{ "resource": "" }
q2318
list
train
function list(connections, params, callback) { logger.debug("Listing Data Sources", params); var currentTime = new Date(params.currentTime); //If listing data sources needing a cache update, need to supply a valid date. if (params.listDataSourcesNeedingUpdate && !params.currentTime && currentTime.toString() !== "Invalid Date") { return callback(buildErrorResponse({error: new Error("An currentTime Date Object Is Required To List Data Sources Requiring Update"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } async.waterfall([ function findDataSources(cb) { var query = {}; lookUpDataSources(connections, { query: query, lean: true }, function(err, dataSources) { if (err) { return cb(buildErrorResponse({ error: err, userDetail: "Unexpected Error When Searching For A Data Source", code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } logger.debug("Listing Data Sources", {dataSources: dataSources}); //Only return Data Sources with a valid data source update time
javascript
{ "resource": "" }
q2319
create
train
function create(connections, dataSource, callback) { async.waterfall([ function validateParams(cb) { //If it is a deploy, the JSON can contain an _id param if (connections.deploy) { return cb(undefined, dataSource); } //Otherwise, check that it is not there. validate(dataSource).hasno(CONSTANTS.DATA_SOURCE_ID, function(err) { if (err) { return cb(buildErrorResponse({error: new Error("Data Source ID Should Not Be Included When Creating A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } cb(undefined, dataSource); }); }, function validateNameNotUsed(dataSource, cb) { //Duplicate Names Are Not Allowed. var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE); DataSource.count({name: dataSource.name}, function(err, numDuplicateDSs) { if (numDuplicateDSs && numDuplicateDSs > 0) { return cb({ userDetail: "Invalid Data To Create A Data Source" , systemDetail: "A Data Source With The Name " + dataSource.name + " Already Exists", code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS }); } else { return cb(err, dataSource); }
javascript
{ "resource": "" }
q2320
remove
train
function remove(connections, params, cb) { var failed = validate(params).has(CONSTANTS.DATA_SOURCE_ID); if (failed) { return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Remove A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } if (!misc.checkId(params[CONSTANTS.DATA_SOURCE_ID])) { return cb(buildErrorResponse({error: new Error("Invalid ID Parameter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE); async.waterfall([ function findAssociatedForms(cb) { checkFormsUsingDataSource(connections, params, cb); }, function verifyNoFormsAssociated(updatedDataSource, cb) { //If there are any forms using this data source,
javascript
{ "resource": "" }
q2321
validateDataSource
train
function validateDataSource(connections, dataSource, cb) { var dataSourceToValidate = _.clone(dataSource); var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE); //Expect The Data Source To Have Data var failure = validate(dataSourceToValidate).has(CONSTANTS.DATA_SOURCE_DATA); if (failure) { return cb(buildErrorResponse({ error: new Error("No Data Passed To Validate"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS })); } //Generate A Hash var hash = misc.generateHash(dataSourceToValidate.data); //Populate A Cache Object //LastRefreshed is populated just for the cache mongoose schema var cache = { dataHash: hash, currentStatus: { status: "ok" }, data: dataSourceToValidate.data, lastRefreshed: new Date().getTime(), updateTimestamp: new Date().getTime() }; dataSourceToValidate.cache = [cache]; //Create A New Mongoose. Note that this document
javascript
{ "resource": "" }
q2322
deploy
train
function deploy(connections, dataSource, cb) { async.waterfall([ function validateParams(cb) { var dataSourceValidator = validate(dataSource); //The data source parameter should have an ID property. dataSourceValidator.has(CONSTANTS.DATA_SOURCE_ID, function(err) { if (err) { return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Deploy A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } cb(undefined, dataSource); }); }, function findDataSource(dataSource, cb) {
javascript
{ "resource": "" }
q2323
parseMongoConnectionOptions
train
function parseMongoConnectionOptions(req, res, next) { var options = {}; options.uri = req.mongoUrl;
javascript
{ "resource": "" }
q2324
StringReadableStream
train
function StringReadableStream(str, options) { if(!options) options = {}; delete options.objectMode; delete options.readableObjectMode; Readable.call(this, options);
javascript
{ "resource": "" }
q2325
parseTemplates
train
function parseTemplates(options) { return readFileTree(options.src.templates,
javascript
{ "resource": "" }
q2326
list
train
function list(req, res, next) { var notStats = req.query && (req.query.notStats === 'true' || req.query.notStats === true); var opts = _.extend(req.connectionOptions, { notStats: notStats });
javascript
{ "resource": "" }
q2327
listDeployedForms
train
function listDeployedForms(req, res, next) { var projectForms = req.appformsResultPayload.data || []; logger.debug("Middleware: listDeployedForms: ", {connection: req.connectionOptions, projectForms: projectForms});
javascript
{ "resource": "" }
q2328
search
train
function search(req, res, next) { var projectForms = req.appformsResultPayload.data || []; //Only Want The Project Ids projectForms = _.map(projectForms, function(form) { if (_.isObject(form)) { return form._id; } else { return form; } }); var formsToFind = req.body || []; formsToFind = _.filter(projectForms, function(projFormId) { return formsToFind.indexOf(projFormId) > -1; }); logger.debug("Middleware: search forms: ", {connection: req.connectionOptions, projectForms: projectForms}); forms.findForms(req.connectionOptions, formsToFind, function(err, formsList) { if (err) {
javascript
{ "resource": "" }
q2329
create
train
function create(req, res, next) { var options = req.connectionOptions; req.user = req.user || {}; var params = { userEmail: req.user.email || req.body.updatedBy
javascript
{ "resource": "" }
q2330
deploy
train
function deploy(req, res, next) { var options = req.connectionOptions; var form = req.body; req.user = req.user || {}; if (req.appformsResultPayload && _.isObject(req.appformsResultPayload.data)) { form = req.appformsResultPayload.data; } //Expect A Data Source Data Set To Be Available If Deploying A Form. var params = { userEmail: req.user.email || req.body.updatedBy, expectDataSourceCache: true };
javascript
{ "resource": "" }
q2331
get
train
function get(req, res, next) { //Admin Fields And Data Sources Should Not Be Shown For App Requests var showAdminAndDataSources = !req.params.projectid; var getParams = { "_id": req.params.id, "showAdminFields": showAdminAndDataSources, includeDataSources: showAdminAndDataSources, //Data Source Caches are required for app requests
javascript
{ "resource": "" }
q2332
update
train
function update(req, res, next) { var options = req.connectionOptions; req.appformsResultPayload = req.appformsResultPayload || {}; var params = { userEmail: req.user.email }; options = _.extend(options, params); var form = req.body; if (_.isObject(req.appformsResultPayload.data) && !req.body._id) {
javascript
{ "resource": "" }
q2333
undeploy
train
function undeploy(req, res, next) { var removeParams = { _id: req.params.id }; logger.debug("Middleware:
javascript
{ "resource": "" }
q2334
listSubscribers
train
function listSubscribers(req, res, next) { var listSubscribersParams = { _id: req.params.id }; logger.debug("Middleware: listSubscribers: ", {params: listSubscribersParams});
javascript
{ "resource": "" }
q2335
updateSubscribers
train
function updateSubscribers(req, res, next) { var updateSubscribersParams = { _id: req.params.id }; var subscribers = req.body.subscribers; logger.debug("Middleware: listSubscribers: ", {params: updateSubscribersParams, subscribers: subscribers});
javascript
{ "resource": "" }
q2336
clone
train
function clone(req, res, next) { var cloneFormParams = { _id: req.params.id, name: req.body.name, userEmail: req.body.updatedBy
javascript
{ "resource": "" }
q2337
importForm
train
function importForm(req, res, next) { req.appformsResultPayload = req.appformsResultPayload || {}; var formData = (req.appformsResultPayload.data && req.appformsResultPayload.type === constants.resultTypes.formTemplate) ? req.appformsResultPayload.data : undefined ; var importFormParams = { form: formData, name: req.body.name, description: req.body.description, userEmail: req.user.email
javascript
{ "resource": "" }
q2338
projects
train
function projects(req, res, next) { var params = { "formId": req.params.id }; logger.debug("Middleware:
javascript
{ "resource": "" }
q2339
submissions
train
function submissions(req, res, next) { var params = { formId: req.params.id }; logger.debug("Middleware: form submissions: ", {params: params}); forms.getSubmissions(req.connectionOptions, params, function(err, getSubmissionResponse) {
javascript
{ "resource": "" }
q2340
submitFormData
train
function submitFormData(req, res, next) { var submission = req.body || {}; submission.appId = req.params.projectid; submission.appEnvironment = req.params.environment; submission.deviceId = submission.deviceId || "Device Unknown"; var submissionParams = { submission: submission
javascript
{ "resource": "" }
q2341
createRules
train
function createRules(rulesToCreate, cb) { function addRule(ruleToCreate, addRuleCallback) { var fr = new rulesModel(ruleToCreate); fr.save(function(err, frdoc) { if (err) { return addRuleCallback(err);
javascript
{ "resource": "" }
q2342
updateRules
train
function updateRules(rulesToUpdate, cb) { function updateRule(ruleDetails, cb1) { var id = ruleDetails._id; rulesModel.findOne({_id: id}, function(err, ruleToUpdate) { if (err) { return cb1(err); } if (ruleToUpdate === null && !options.createIfNotFound) { return cb1(new Error("No " + ruleType + " rule matches id " + id)); } else if (ruleToUpdate === null && options.createIfNotFound) { ruleToUpdate = new rulesModel(ruleDetails); }
javascript
{ "resource": "" }
q2343
deleteRules
train
function deleteRules(rulesToDelete, cb) { var idsToRemove = _.pluck(rulesToDelete, "_id"); function deleteRule(fieldRuleId, cb1) {
javascript
{ "resource": "" }
q2344
sleep
train
async function sleep(seconds) { let ms = seconds * 1000; while (ms > _maxTimeout) { // Support sleeping longer than the javascript max setTimeout... await new Promise(resolve => setTimeout(resolve, _maxTimeout));
javascript
{ "resource": "" }
q2345
isFieldStillValidTarget
train
function isFieldStillValidTarget(fieldOrPageIdToCheck, pages, cb) { var fieldExistsInForm = false; var invalidPages = _.filter(pages, function(page) { var currentPageId = page._id.toString(); if (currentPageId === fieldOrPageIdToCheck) { fieldExistsInForm = true; } var invalidFieldList = _.filter(page.fields, function(field) { var currentFieldId = field._id.toString(); if (currentFieldId === fieldOrPageIdToCheck) { //Current field exists fieldExistsInForm = true; //Field is admin only, therefore it is an invalid target for a rule. if (field.adminOnly) { return true; } else { return false; } } else {
javascript
{ "resource": "" }
q2346
getSourceRepeatingSections
train
function getSourceRepeatingSections(rule) { return _.chain(rule.ruleConditionalStatements) .map(function(ruleConditionalStatement) { var sourceId = ruleConditionalStatement.sourceField.toString(); return fieldSectionMapping[sourceId]; }) .filter(function(section) { return section &&
javascript
{ "resource": "" }
q2347
updateFormRules
train
function updateFormRules(cb) { //Filters out any conditional statements that are no longer valid. function filterConditionalStatements(rule) { return _.filter(rule.ruleConditionalStatements, function(ruleCondStatement) { var sourceField = ruleCondStatement.sourceField.toString(); if (invalidFields[sourceField]) { /** * If the user flagged the field in this rule for deletion, flag the rule for deletion. */ if (ruleDeletionFlags[sourceField]) { rulesFlaggedForDeletion[rule._id.toString()] = true; } return false; } else { return true; } }); } var updatedFieldRules = _.map(form.fieldRules, function(fieldRule) { var filteredConditionalStatements = filterConditionalStatements(fieldRule); var filteredTargets = _.filter(fieldRule.targetField, function(targetField) { if (invalidFields[targetField]) { return false; } else { return true; } }); fieldRule.ruleConditionalStatements = filteredConditionalStatements; fieldRule.targetField = filteredTargets; return fieldRule; }); var updatedPageRules = _.map(form.pageRules, function(pageRule) { pageRule.ruleConditionalStatements = filterConditionalStatements(pageRule); return pageRule; }); fieldRulesToDelete = _.filter(updatedFieldRules, function(fieldRule) { var targetFields = fieldRule.targetField; var conditionalStatements = fieldRule.ruleConditionalStatements; var fieldRuleId = fieldRule._id.toString(); return targetFields.length === 0 || conditionalStatements.length === 0 || rulesFlaggedForDeletion[fieldRuleId]; }); pageRulesToDelete = _.filter(updatedPageRules, function(pageRule) { var conditionalStatements = pageRule.ruleConditionalStatements; var pageRuleId = pageRule._id.toString();
javascript
{ "resource": "" }
q2348
filterConditionalStatements
train
function filterConditionalStatements(rule) { return _.filter(rule.ruleConditionalStatements, function(ruleCondStatement) { var sourceField = ruleCondStatement.sourceField.toString(); if (invalidFields[sourceField]) {
javascript
{ "resource": "" }
q2349
walkCollections
train
function walkCollections(patterns, drizzleData, writePromises = []) { if (hasCollection(patterns)) { writePromises.push( writePage( patterns.collection.id, patterns.collection, drizzleData.options.dest.patterns, drizzleData.options.keys.collections.plural ) ); } for (const
javascript
{ "resource": "" }
q2350
writeCollections
train
function writeCollections(drizzleData) { return Promise.all(walkCollections(drizzleData.patterns, drizzleData)).then( writePromises => drizzleData,
javascript
{ "resource": "" }
q2351
AttributeDictionary
train
function AttributeDictionary(attributes) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating an AttributeDictionary (it has ' + 'to be passed less than 2 arguments)' ); if (attributes) { expect(typeof attributes).to.equal( 'object',
javascript
{ "resource": "" }
q2352
_addAttribute
train
function _addAttribute() { var attributeDictionary = arguments[0]; var attribute = null; var name = null; if (arguments.length === 2) { attribute = arguments[1]; } else { attribute = arguments[1]; name = arguments[2]; } expect(attribute).to.be.an( 'object', 'Invalid argument type when adding an attribute ' + (name ? 'called "' + name + '" ' : '') + 'in an AttributeDictionary (it has to be an object)' ); if (name) { if (attribute.name) { expect(attribute.name).to.equal( name, 'Invalid argument "name" when adding an attribute called "' + attribute.name + '" in an AttributeDictionary (the name given in ' + 'argument and the name given in the attribute object should be equal)' ); } else { attribute.name = name; }
javascript
{ "resource": "" }
q2353
concat
train
function concat(attributeDictionary, attribute) { expect(arguments).to.have.length( 2, 'Invalid arguments length when concatenating an AttributeDictionary (it ' + 'has to be passed 2 arguments)' ); expect(attributeDictionary).to.be.instanceof( AttributeDictionary, 'Invalid argument "attributeDictionary" when concatenating an ' + 'AttributeDictionary (it has to be an AttributeDictionary)' ); expect(attribute).to.be.instanceof( Attribute, 'Invalid argument "attribute" when concatenating an
javascript
{ "resource": "" }
q2354
get
train
function get(connections, params, cb) { var failed = validate(params).has(CONSTANTS.DATA_TARGET_ID); if (failed) { return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Get A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } if (!misc.checkId(params._id)) { return cb(buildErrorResponse({error: new Error("Invalid ID Paramter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } async.waterfall([ function findDataTargets(cb) { var query = { }; //Searching By ID. query[CONSTANTS.DATA_TARGET_ID] = params._id; lookUpDataTargets(connections, { query: query, lean: true }, function(err, dataTargets) { if (err) { return cb(buildErrorResponse({ error: err, userDetail: "Unexpected Error When Searching For A Data Target", code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } //Checking if the Data Target exists. Should be only one
javascript
{ "resource": "" }
q2355
remove
train
function remove(connections, params, cb) { var failed = validate(params).has(CONSTANTS.DATA_TARGET_ID); if (failed) { return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Remove A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } if (!misc.checkId(params._id)) { return cb(buildErrorResponse({error: new Error("Invalid ID Paramter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } async.waterfall([ function findAssociatedForms(cb) { checkFormsUsingDataTarget(connections, params, cb); }, function verifyNoFormsAssociated(updatedDataTarget, cb) { //If there is more than one form using this data target, then do not delete it. if (updatedDataTarget.forms.length > 0) { return cb(buildErrorResponse({ error: new Error("Forms Are Associated With This Data Target. Please Disassociate Forms From This Data Target Before Deleting."), code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
javascript
{ "resource": "" }
q2356
list
train
function list(connections, params, cb) { async.waterfall([ function findDataTargets(cb) { lookUpDataTargets(connections, { query: {}, lean: true }, function(err, dataTargets) { if (err) { return cb(buildErrorResponse({ error:
javascript
{ "resource": "" }
q2357
create
train
function create(connections, dataTarget, cb) { async.waterfall([ function validateParams(cb) { validate(dataTarget).hasno(CONSTANTS.DATA_TARGET_ID, function(err) { if (err) { return cb(buildErrorResponse({error: new Error("Data Target ID Should Not Be Included When Creating A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } }); cb(undefined, dataTarget); }, function createDataTarget(dataTargetJSON,
javascript
{ "resource": "" }
q2358
validateDataTarget
train
function validateDataTarget(connections, dataTarget, cb) { var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET); var testDataTarget = new DataTarget(dataTarget); //Validating Without Saving testDataTarget.validate(function(err) { if (err) { return cb(buildErrorResponse({ error: err,
javascript
{ "resource": "" }
q2359
getSiblings
train
function getSiblings(el) { const allSiblings = getPreviousSiblings(el).concat(getNextSiblings(el));
javascript
{ "resource": "" }
q2360
validatefieldCodes
train
function validatefieldCodes() { //Flag for finding a duplicate field code var duplicateFieldCode = false; var invalidFieldCode = false; var fieldCodes = {}; formData.pages = _.map(formData.pages, function(page) { page.fields = _.map(page.fields, function(field) { var fieldCode = field.fieldCode; //If not set, then just return the field. if (fieldCode === null || typeof(fieldCode) === "undefined") { return field; } //Checking for duplicate field code. It must be a string. if (typeof(fieldCode) === "string") { //If the length of the code is 0, then don't save it. if (fieldCode.length === 0) { delete field.fieldCode; } else { //Checking for duplicate field code if (fieldCodes[fieldCode]) { duplicateFieldCode = true; //Flagging the field as duplicate } else {
javascript
{ "resource": "" }
q2361
validateDuplicateName
train
function validateDuplicateName(cb) { var formId = formData._id; var formName = formData.name; if (!formName) { return cb(new Error("No form name passed")); } var query = {}; //If there is a form id, then the query to the form model must exclude the current form id that is being updated. if (formId) { query.name = formName; //Excluding the formId that is being updated. query["_id"] = {"$nin": [formId]}; } else { //Just checking that the form name exists as a form is being created query.name = formName; } formModel.count(query, function(err, count) { if (err) { return
javascript
{ "resource": "" }
q2362
getFormDataSources
train
function getFormDataSources(formJSON) { var dataSources; var pages = formJSON.pages || []; dataSources = _.map(pages, function(page) { var fields = page.fields || []; fields = _.map(fields, function(field) { //If the field is defined as a Data Source field, and it has a data source, then return that data source. if (field.dataSourceType === models.FORM_CONSTANTS.DATA_SOURCE_TYPE_DATA_SOURCE && field.dataSource) { return field.dataSource; } else { return undefined; } });
javascript
{ "resource": "" }
q2363
findMatchingDocuments
train
function findMatchingDocuments(type, documentIDs, modelToSearch, cb) { var errorTextDataType = type === models.MODELNAMES.DATA_SOURCE ? "Data Sources" : "Data Targets"; //If the form contains no data sources, then no need to verify if (documentIDs.length === 0) { return cb(undefined, []); } var query = {_id: { "$in": documentIDs }}; modelToSearch.find(query).exec(function(err, foundModels) { if (err) { return cb(buildErrorResponse({ error: err, userDetail: "Unexpected Error Finding " + errorTextDataType })); } //There should be the same number of data source documents if (documentIDs.length !== foundModels.length) { var missingDocumentId = _.find(documentIDs, function(documentId) { return !_.findWhere(foundModels, {_id: documentId}); }); //If there is no missing data source, then something is wrong.. if (!missingDocumentId) { return cb(buildErrorResponse({ error: new Error("Unexpected Error When Finding " + errorTextDataType), systemDetail: "Expected A Missing " + errorTextDataType + " But Could Not Find It" })); } return cb(buildErrorResponse({ userDetail: "A " + errorTextDataType + " Contained In The Form Could Not Be Found", systemDetail: "Expected " + errorTextDataType + " With ID " + missingDocumentId + " To Be Found", code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS })); } //All documents found -- checking for cache if needed
javascript
{ "resource": "" }
q2364
verifyDataSources
train
function verifyDataSources(formDataSourceIds, cb) { findMatchingDocuments(models.MODELNAMES.D
javascript
{ "resource": "" }
q2365
verifyDataTargets
train
function verifyDataTargets(dataTargetIds, cb) { findMatchingDocuments(models.MODELNAMES.DA
javascript
{ "resource": "" }
q2366
verifyFormDataSourcesAndTargets
train
function verifyFormDataSourcesAndTargets(formData, cb) { var formDataSourceIds = getFormDataSources(formData); var dataTargets = formData.dataTargets || []; async.series({ dataSources : function(cb) {
javascript
{ "resource": "" }
q2367
WebService
train
function WebService(options) { this.options = opts(this, options); if(!this.options.apiroot) this.options.apiroot = "https://api.cloudmine.io"; var src = this.options.appid; if (options.savelogin) { if (!this.options.email) this.options.email = retrieve('email', src); if (!this.options.username) this.options.username = retrieve('username', src);
javascript
{ "resource": "" }
q2368
train
function(snippet, parameters, options) { options = opts(this, options); parameters = merge({}, options.params, parameters); options.params = null; options.snippet = null; var call_opts = { action: 'run/' + snippet, type: options.method || 'GET', options: options
javascript
{ "resource": "" }
q2369
train
function(notification, options) { options = opts(this, options); return new APICall({ action: 'push', type: 'POST',
javascript
{ "resource": "" }
q2370
train
function(id, options) { options = opts(this, options); return new APICall({ action: 'account/' + id,
javascript
{ "resource": "" }
q2371
train
function(key, file, options) { options = opts(this, options); if (!key) key = this.keygen(); if (!options.filename) options.filename = key; // Warning: may not necessarily use ajax to perform upload. var apicall = new APICall({ action: 'binary/' + key, type: 'post', later: true, encoding: 'binary', options: options, processResponse: APICall.basicResponse }); function upload(data, type) { if (!options.contentType) options.contentType = type || defaultType; APICall.binaryUpload(apicall, data, options.filename, options.contentType).done(); } if (isString(file) || (Buffer && file instanceof Buffer)) { // Upload by filename if (isNode) { if (isString(file)) file = fs.readFileSync(file); upload(file); } else NotSupported(); } else if (file.toDataURL) { // Canvas will have a toDataURL function. upload(file, 'image/png'); } else if (CanvasRenderingContext2D && file instanceof CanvasRenderingContext2D) { upload(file.canvas, 'image/png'); } else if (isBinary(file)) { // Binary files are base64 encoded from a buffer. var reader = new FileReader(); /** @private */
javascript
{ "resource": "" }
q2372
train
function(key, options) { options = opts(this, options); var response = {success: {}}, query; if (options.filename) { query = { force_download: true, apikey: options.apikey, session_token: options.session_token, filename: options.filename } } var apicall = new APICall({ action: 'binary/' + key, type: 'GET', later: true, encoding: 'binary', options: options, query: query }); // Download file directly to computer if given a filename. if (options.filename) { if (isNode) { apicall.setProcessor(function(data) { response.success[key] = fs.writeFileSync(options.filename, data, 'binary'); return response; }).done(); } else { function detach() { if (iframe.parentNode) document.body.removeChild(iframe); } var iframe = document.createElement('iframe'); iframe.style.display = 'none'; document.body.appendChild(iframe); setTimeout(function() { iframe.src = apicall.url; }, 25); iframe.onload = function() { clearTimeout(detach.timer); detach.timer = setTimeout(detach, 5000); }; detach.timer = setTimeout(detach, 60000); response.success[key]
javascript
{ "resource": "" }
q2373
train
function(user_id, profile, options) { options = opts(this, options); return new APICall({ action: 'account/' + user_id, type: 'POST', options: options,
javascript
{ "resource": "" }
q2374
train
function(user_id, password, options) { options = opts(this, options); var payload = JSON.stringify({ password: password });
javascript
{ "resource": "" }
q2375
train
function(email, options) { options = opts(this, options); options.applevel = true; var payload = JSON.stringify({ email: email }); return new APICall({ action: 'account/password/reset',
javascript
{ "resource": "" }
q2376
train
function(token, newPassword, options) { options = opts(this, options); options.applevel = true; var payload = JSON.stringify({ password: newPassword }); return new APICall({ action: "account/password/reset/" + token,
javascript
{ "resource": "" }
q2377
train
function(query, options) { options = opts(this, options); if(!options.session_token) throw new Error("Must be logged in to perform a social query"); if(query.headers && !isObject(query.headers)) throw new Error("Headers must be an object"); if(query.params && !isObject(query.params)) throw new Error("Extra parameters must be an object"); var url = "social/"+query.network+"/"+query.endpoint; var urlParams = {}; if(query.headers) urlParams.headers
javascript
{ "resource": "" }
q2378
train
function(auth, password, options) { if (isObject(auth)) options = password; else auth = {email: auth, password: password} options = opts(this, options); options.applevel = true; var config = { action: 'account', type: 'DELETE', options: options, processResponse: APICall.basicResponse }; // Drop session if we are referring to ourselves. if (auth.email == this.options.email) { this.options.session_token = null; this.options.email = null; if (options.savelogin) { store('email', null, this.options.appid); store('username', null, this.options.appid); store('session_token', null,
javascript
{ "resource": "" }
q2379
train
function(aclid, options){ options = opts(this, options); return new APICall({ action: 'access/' + aclid, type: 'DELETE',
javascript
{ "resource": "" }
q2380
train
function() { if (this.options.applevel === true || this.options.applevel === false) return this.options.applevel;
javascript
{ "resource": "" }
q2381
train
function(eventType, callback, context) { if (isFunction(callback)) { context = context || this; if (!this._events[eventType]) this._events[eventType] = []; // normal callback not called. var self = this; this._events[eventType].push([callback, context, function() {
javascript
{ "resource": "" }
q2382
train
function(event/*, arg1...*/) { var events = this._events[event]; if (events != null) { var args = slice(arguments, 1); each(events, function(event) {
javascript
{ "resource": "" }
q2383
train
function(eventType, callback, context) { if (eventType == null && callback == null && context == null) { this._events = {}; } else if (eventType == null) { each(this._events, function(value, key, collection) { collection._events[key] = removeCallbacks(value, callback,
javascript
{ "resource": "" }
q2384
train
function() { if (this.xhr) { this.xhr.abort(); } else if (this.config) { this.config.complete.call(this, this.xhr, 'abort'); } // Cleanup leftover state. if (this.xhr) { this.xhr = undefined;
javascript
{ "resource": "" }
q2385
copy
train
function copy(o) { expect(arguments).to.have.length( 1, 'Invalid argument length when copying an object (it has to be passed ' + '1 argument)' ); expect(o).to.be.an( 'object', 'Invalid argument
javascript
{ "resource": "" }
q2386
rerouteLinks
train
function rerouteLinks (html) { return html.replace(/href="(\.\/[a-z0-9\-]+\.md)"/g, (all, key) => { const found = documentationPages.filter((page) => page.key === key)[0] if (!found) return all /* global __legendary_pancake_base_pathname__ */
javascript
{ "resource": "" }
q2387
updateValidAndInvalidDataSources
train
function updateValidAndInvalidDataSources(dataSourcesToSplit, currentInvalidDataSources) { logger.debug("dataSourcesToSplit", dataSourcesToSplit); currentInvalidDataSources = currentInvalidDataSources || []; var validInvalid = _.partition(dataSourcesToSplit, function(dataSourceUpdateData) { if (dataSourceUpdateData) { return !dataSourceUpdateData.error; } return true; }); var validDataSources
javascript
{ "resource": "" }
q2388
findDataSources
train
function findDataSources(connections, dataSources, cb) { //Just Want The Data Source IDs. logger.debug("findDataSources", {dataSources: dataSources}); var dataSourceIDsToUpdate = _.map(dataSources, function(dataSourceUpdateData) { return dataSourceUpdateData.error ? null : dataSourceUpdateData._id; }); dataSourceIDsToUpdate = _.compact(dataSourceIDsToUpdate); //No Valid Data Sources To Update. No Need To Search For Data Sources if (dataSourceIDsToUpdate.length === 0) { return cb(undefined, dataSourceIDsToUpdate); } var query = { }; //Searching By ID. Just one mongo call to get them all. More Efficient query[CONSTANTS.DATA_SOURCE_ID] = { "$in": dataSourceIDsToUpdate }; lookUpDataSources(connections, { query: query }, function(err, foundDataSources) { if (err) { logger.error("Error Finding Data Sources ", {error: err});
javascript
{ "resource": "" }
q2389
validateParams
train
function validateParams(dataSources, cb) { dataSources = _.map(dataSources, function(dataSourceUpdateData) { var failed = validate(dataSourceUpdateData).has(CONSTANTS.DATA_SOURCE_ID); if (failed) { dataSourceUpdateData.error = buildErrorResponse({error: new Error("Invalid Parameters For Updating Data
javascript
{ "resource": "" }
q2390
updateDataSourceCaches
train
function updateDataSourceCaches(params, dsWithDocuments, dsWithNoDocuments, cb) { //Updating All Of The Data Sources //Generating Hashes For The Incoming Data Set. Useful for determining if the stored data set has changed. dsWithDocuments = _.map(dsWithDocuments, function(dataSourceData) { dataSourceData.dataHash = dataSourceData.error ? null : misc.generateHash(dataSourceData.data);
javascript
{ "resource": "" }
q2391
updateForms
train
function updateForms(params, validDataSources, invalidDataSources, cb) { //Only interested In Data Sources Where Data Was Actually Updated. If the data set is still the same, then no need to mark the form as updated the form. var dataSoucesUpdated = _.filter(validDataSources, function(dataSourceData) { return dataSourceData.dataChanged === true; }); //Updating Any Forms That Reference Updated Data Sources var updatedDataSourceIds = _.map(dataSoucesUpdated, function(validDataSourceData) { return validDataSourceData._id; }); //Need to find and update any forms associated with the data sources. var Form = models.get(params.connections.mongooseConnection, models.MODELNAMES.FORM); //Flagging Any Forms That Are Using The Updated Data Sources As Being Updated. This is
javascript
{ "resource": "" }
q2392
saveAuditLogEntryAndUpdateDataSource
train
function saveAuditLogEntryAndUpdateDataSource(params, callback) { var cacheElement = params.cacheElement; var dataSourceDocument = params.dataSourceDocument; var dataSourceData = params.dataSourceData; async.waterfall([ function saveAuditLog(cb) { //An Audit Log Entry Is Based On The Cache Update Entry. var auditLogEntry = cacheElement.toJSON(); //Adding Service Details To The Audit Log Entry _.extend(auditLogEntry, _.pick(dataSourceDocument, "serviceGuid", "endpoint")); //Adding the audit log var AuditLog = models.get(params.connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE_AUDIT_LOG); auditLogEntry.dataSource = dataSourceDocument._id; var auditLogToSave = new AuditLog(auditLogEntry); auditLogToSave.save(function(err, savedAuditLog) { if (err) { return cb(err); } dataSourceDocument.auditLogs.push(savedAuditLog); return cb(); }); }, function saveDataSource(cb) { //Having Attempted To Save, the updated data source has to be validated again to clear old validation errors before trying to save again. dataSourceDocument.validate(function() { //Data Source Data Is Now valid, can save it - whether it is in an error state or not. dataSourceDocument.save(function(err) { if (err) { dataSourceData.error = buildErrorResponse({
javascript
{ "resource": "" }
q2393
updateDataSourceEntry
train
function updateDataSourceEntry(params, dataSourceData, callback) { var dataToUpdate = dataSourceData.data; var dataSourceDocument = dataSourceData.document; logger.debug("updateDataSourceEntry ", params, dataSourceData); //If there is no cache entry, create a new one to validate. var cacheElement = dataSourceDocument.cache[0]; if (!cacheElement) { dataSourceDocument.cache.push({}); } cacheElement = dataSourceDocument.cache[0]; //Assigning the last attempt to update the data source cacheElement.updateTimestamp = params.currentTime; var existingData = cacheElement.data; var existingHash = cacheElement.dataHash; logger.debug("updateDataSourceEntry ", {dataToUpdate: dataToUpdate, cacheElement: cacheElement, existingData: existingData, existingHash: existingHash}); if (dataSourceData.dataError || dataSourceData.error) { cacheElement.currentStatus = { status: "error", error: dataSourceData.dataError || dataSourceData.error }; } else if (dataSourceData.dataHash !== cacheElement.dataHash) { //If the hashes are different, need to update the data set and hash cacheElement.data = dataToUpdate; cacheElement.dataHash = dataSourceData.dataHash; dataSourceData.dataChanged = true; } logger.debug("updateDataSourceEntry ", {cacheElementBeforeValidation: cacheElement}); async.waterfall([ function validateDataPassed(cb) { //Validating That the Data That Was Passed is correct. dataSourceDocument.save(function(err) { if (err) { logger.warn("Error Validating Data Source ", {error: err}); //Not Valid, don't try to save it, mark it as an error state dataSourceData.error = buildErrorResponse({ error: err, userDetail: "Invalid Data For Cache Update.", systemDetail: err.message, code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS }); //If there is a validation error, save it with the exiting data set Data Source for viewing later. cacheElement.data = existingData ? existingData : []; cacheElement.dataHash = existingHash; cacheElement.currentStatus = { status: "error", error: dataSourceData.error }; }
javascript
{ "resource": "" }
q2394
prepareResponse
train
function prepareResponse(validDataSources, invalidDataSources, cb) { //There Were Errors Updating Data Sources, should return an error logger.debug("prepareResponse Before", validDataSources); //For The Valid Data Sources, Just want the updated Document JSON validDataSources = _.map(validDataSources, function(validDataSourceData) {
javascript
{ "resource": "" }
q2395
getSubmissionStorage
train
function getSubmissionStorage(cb) { //If no stats are required, don't try and do the map-reduce operation. if (options.notStats) { return cb(); } // NOTE: this function executes in MongoDB rather than Node.js //Need a map-reduce operation to count the files, otherwise would have to load all submissions into memory which is bad. var mapFileSizesFunction = function() { var key = this.formId; var formFields = this.formFields || []; //Iterating over all form fields for (var formFieldIdx = 0; formFieldIdx < formFields.length; formFieldIdx++) { var formField = formFields[formFieldIdx]; var fieldValues = formField.fieldValues || []; //Iterating over all of the field values for (var fieldValueIdx = 0 ; fieldValueIdx < fieldValues.length ; fieldValueIdx++) { var fieldValue = fieldValues[fieldValueIdx] || {}; //If the value has a file size associated with it, then emit that file size if (fieldValue.fileSize) { emit(key, fieldValue.fileSize); // eslint-disable-line no-undef } } } }; // NOTE: this function executes in MongoDB rather than Node.js //Function to sum up all of the file sizes for each submission var reduceFileSizesFunction = function(formId, fileSizes) { var totalFileSizes = 0; for (var fileSizeIdx = 0; fileSizeIdx < fileSizes.length ; fileSizeIdx++) {
javascript
{ "resource": "" }
q2396
deepObj
train
function deepObj(pathKeys, obj, createEntries = true) { return pathKeys.reduce((prev, curr) => { if (typeof prev[curr] === 'undefined') { if (createEntries) { prev[curr] = {}; } else { DrizzleError.error( new DrizzleError(
javascript
{ "resource": "" }
q2397
deepCollection
train
function deepCollection(collectionId, obj) { const pathBits = idKeys(collectionId);
javascript
{ "resource": "" }
q2398
isObject
train
function isObject(obj) { const objType = typeof obj;
javascript
{ "resource": "" }
q2399
flattenById
train
function flattenById(obj, keyedObj = {}) { if (obj.hasOwnProperty('id')) { keyedObj[obj.id] = obj; } for (var key in obj) { if
javascript
{ "resource": "" }