_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
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) && theme && !req.getFullTheme) { req.appformsResultPayload.data.theme = theme._id; } else { //Want the full theme definition req.appformsResultPayload = { data: theme }; } next(); }); }
javascript
{ "resource": "" }
q2301
remove
train
function remove(req, res, next) { var params = { appId: req.params.id }; forms.deleteAppReferences(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
javascript
{ "resource": "" }
q2302
get
train
function get(req, res, next) { var params = { appId: req.params.projectid || req.params.id }; forms.getAppFormsForApp(_.extend(req.connectionOptions, params), formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
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 = { data: _.map(_.compact(appFormResult.forms), function(form) { return form._id.toString(); }), type: constants.resultTypes.formProjects }; next(); }); }
javascript
{ "resource": "" }
q2304
getConfig
train
function getConfig(req, res, next) { var params = { appId: req.params.projectid || req.params.id }; forms.getAppConfig(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
javascript
{ "resource": "" }
q2305
updateConfig
train
function updateConfig(req, res, next) { var params = { appId: req.params.id }; forms.updateAppConfig(req.connectionOptions, _.extend(req.body, params), formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
javascript
{ "resource": "" }
q2306
exportProjects
train
function exportProjects(req, res, next) { var options = req.connectionOptions; forms.exportAppForms(options, formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
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"); } forms.importAppForms(options, appFormsToImport, formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
javascript
{ "resource": "" }
q2308
exportProjectConfig
train
function exportProjectConfig(req, res, next) { var options = req.connectionOptions; forms.exportAppConfig(options, formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
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"); } forms.importAppConfig(options, projectConfigToImport, formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
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 { readAndCompileTemplate(function(err, compiledTemplate) { pdfTemplate = compiledTemplate; return cb(err, pdfTemplate); }); } }
javascript
{ "resource": "" }
q2311
write
train
function write(drizzleData) { return Promise.all([ writePages(drizzleData), writeCollections(drizzleData) ]).then( () => drizzleData, error => DrizzleError.error(error, drizzleData.options) ); }
javascript
{ "resource": "" }
q2312
relinkUniforms
train
function relinkUniforms(gl, program, locations, uniforms) { for(var i=0; i<uniforms.length; ++i) { locations[i] = gl.getUniformLocation(program, uniforms[i].name) } }
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 (typeof a.location === 'number') gl.bindAttribLocation(program, a.location, a.name) }) gl.linkProgram(program) if(!gl.getProgramParameter(program, gl.LINK_STATUS)) { var errLog = gl.getProgramInfoLog(program) console.error('gl-shader: Error linking shader program:', errLog) throw new Error('gl-shader: Error linking shader program:' + errLog) } //Return final linked shader object var shader = new Shader( gl, program, vertShader, fragShader ) shader.updateExports(uniforms, attributes) return shader }
javascript
{ "resource": "" }
q2314
parsePages
train
function parsePages(options) { return readFileTree(options.src.pages, options.keys.pages, options); }
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); // 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, Transform.prototype, options); readableMixins.call(this, options); writableMixins.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); this._compoundReadable = readable; this._compoundWritable = writable; this._waitingForReadableData = false; writable.on('chainerror', function(error) { // Forward the error on; if the chain is to be destructed, the compound stream's _abortStream() method will be called this.ignoreError(); self.emit('error', error); }); readable.on('readable', function() { if(self._waitingForReadableData) { self._waitingForReadableData = false; self._readSomeData(); } }); readable.on('end', function() { self.push(null); }); }
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) { return cb(buildErrorResponse({ error: new Error("Data Source Not Found"), systemDetail: "Requested ID: " + params[CONSTANTS.DATA_SOURCE_ID], code: ERROR_CODES.FH_FORMS_NOT_FOUND })); } var dataSourceJSON = dataSources[0]; dataSourceJSON = processDataSourceResponse(dataSourceJSON, { includeAuditLog: params.includeAuditLog }); return cb(undefined, dataSourceJSON); }); }, function checkForms(dataSourceJSON, cb) { //Checking For Any Forms Associated With The Data Source checkFormsUsingDataSource(connections, dataSourceJSON, cb); } ], cb); }
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 if (params.listDataSourcesNeedingUpdate) { dataSources = checkUpdateInterval(dataSources, currentTime); } logger.debug("Listing Data Sources", {dataSourceAfterFilter: dataSources}); dataSources = _.map(dataSources, processDataSourceResponse); return cb(undefined, dataSources); }); }, function getFormsUsingDataSources(dataSources, cb) { async.map(dataSources, function(dataSource, cb) { checkFormsUsingDataSource(connections, dataSource, cb); }, cb); } ], callback); }
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); } }); }, function createDataSource(dataSourceJSON, cb) { dataSourceJSON = misc.sanitiseJSON(dataSourceJSON); var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE); var newDataSource = new DataSource(dataSourceJSON); newDataSource.save(function(err) { if (err) { return cb(buildErrorResponse({ error: err, userDetail: "Invalid Data Source Creation Data.", systemDetail: err.errors, code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS })); } newDataSource = processDataSourceResponse(newDataSource.toJSON()); return cb(undefined, newDataSource); }); } ], callback); }
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, then do not delete it. logger.debug("Remove Data Source ", {updatedDataSource: updatedDataSource}); if (updatedDataSource.forms.length > 0) { return cb(buildErrorResponse({ error: new Error("Forms Are Associated With This Data Source. Please Disassociate Forms From This Data Source Before Deleting."), code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } return cb(undefined, updatedDataSource); }, function processResponse(updatedDataSource, cb) { //Removing The Data Source DataSource.remove({_id: updatedDataSource._id}, function(err) { if (err) { return cb(buildErrorResponse({ error: err, userDetail: "Unexpected Error When Removing A Data Source", code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } //Data Source Removed Successfully return cb(undefined, updatedDataSource); }); }, function removeAduditLogs(updatedDataSource, cb) { DataSource.clearAuditLogs(updatedDataSource._id, cb); } ], cb); }
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 is never saved. It is useful for consistent validation var testDataSource = new DataSource(dataSourceToValidate); //Validating Without Saving testDataSource.validate(function(err) { var valid = err ? false : true; var dataSourceJSON = testDataSource.toJSON(); dataSourceJSON = processDataSourceResponse(dataSourceJSON); dataSourceJSON = _.omit(dataSourceJSON, "lastRefreshed", "currentStatus", "updateTimestamp", CONSTANTS.DATA_SOURCE_ID); dataSourceJSON.validationResult = { valid: valid, message: valid ? "Data Source Is Valid" : "Invalid Data Source Update Data." }; return cb(undefined, dataSourceJSON); }); }
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) { var query = { }; //Searching By ID. query[CONSTANTS.DATA_SOURCE_ID] = dataSource[CONSTANTS.DATA_SOURCE_ID]; //Looking up a full data source document as we are updating lookUpDataSources(connections, { query: query, lean: false }, 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 })); } //If no data sources found create, otherwise update. if (dataSources.length === 0) { connections.deploy = true; create(connections, dataSource, cb); } else { update(connections, dataSource, cb); } }); } ], cb); }
javascript
{ "resource": "" }
q2323
parseMongoConnectionOptions
train
function parseMongoConnectionOptions(req, res, next) { var options = {}; options.uri = req.mongoUrl; req.connectionOptions = options; return next(); }
javascript
{ "resource": "" }
q2324
StringReadableStream
train
function StringReadableStream(str, options) { if(!options) options = {}; delete options.objectMode; delete options.readableObjectMode; Readable.call(this, options); this._currentString = str; this._currentStringPos = 0; this._stringChunkSize = options.chunkSize || 1024; }
javascript
{ "resource": "" }
q2325
parseTemplates
train
function parseTemplates(options) { return readFileTree(options.src.templates, options.keys.templates, options); }
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 }); logger.debug("List Forms Middleware ", opts); forms.getAllForms(opts, formsResultHandlers(constants.resultTypes.forms, req, next)); }
javascript
{ "resource": "" }
q2327
listDeployedForms
train
function listDeployedForms(req, res, next) { var projectForms = req.appformsResultPayload.data || []; logger.debug("Middleware: listDeployedForms: ", {connection: req.connectionOptions, projectForms: projectForms}); //Only Want The Project Ids projectForms = _.map(projectForms, function(form) { if (_.isObject(form)) { return form._id; } else { return form; } }); forms.findForms(req.connectionOptions, projectForms, formsResultHandlers(constants.resultTypes.forms, req, next)); }
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) { return next(err); } async.map(formsList, function(foundForm, cb) { var getParams = { "_id": foundForm._id, "showAdminFields": false }; forms.getForm(_.extend(_.clone(req.connectionOptions), getParams), cb); }, formsResultHandlers(constants.resultTypes.forms, req, next)); }); }
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 }; options = _.extend(options, params); logger.debug("Middleware: create form: ", {options: options}); forms.updateForm(options, req.body, formsResultHandlers(constants.resultTypes.forms, req, next)); }
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 }; options = _.extend(options, params); logger.debug("Middleware: Deploy form: ", {options: options}); forms.updateOrCreateForm(options, form, formsResultHandlers(constants.resultTypes.forms, req, next)); }
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 expectDataSourceCache: !showAdminAndDataSources }; logger.debug("Middleware: Get form: ", {getParams: getParams}); forms.getForm(_.extend(req.connectionOptions, getParams), formsResultHandlers(constants.resultTypes.forms, req, next)); }
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) { form = req.appformsResultPayload.data; } logger.debug("Middleware: Update form: ", {options: options, form: form}); forms.updateForm(options, form, formsResultHandlers(constants.resultTypes.forms, req, next)); }
javascript
{ "resource": "" }
q2333
undeploy
train
function undeploy(req, res, next) { var removeParams = { _id: req.params.id }; logger.debug("Middleware: undeploy form: ", {params: removeParams}); forms.deleteForm(_.extend(req.connectionOptions, removeParams), formsResultHandlers(constants.resultTypes.forms, req, next)); }
javascript
{ "resource": "" }
q2334
listSubscribers
train
function listSubscribers(req, res, next) { var listSubscribersParams = { _id: req.params.id }; logger.debug("Middleware: listSubscribers: ", {params: listSubscribersParams}); forms.getNotifications(_.extend(req.connectionOptions, listSubscribersParams), formsResultHandlers(constants.resultTypes.forms, req, next)); }
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}); forms.updateNotifications(_.extend(req.connectionOptions, updateSubscribersParams), subscribers, formsResultHandlers(constants.resultTypes.forms, req, next)); }
javascript
{ "resource": "" }
q2336
clone
train
function clone(req, res, next) { var cloneFormParams = { _id: req.params.id, name: req.body.name, userEmail: req.body.updatedBy }; logger.debug("Middleware: clone form: ", {params: cloneFormParams}); forms.cloneForm(_.extend(req.connectionOptions, cloneFormParams), formsResultHandlers(constants.resultTypes.forms, req, next)); }
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 }; logger.debug("Middleware: importForm form: ", {params: importFormParams}); forms.cloneForm(_.extend(req.connectionOptions, importFormParams), formsResultHandlers(constants.resultTypes.forms, req, next)); }
javascript
{ "resource": "" }
q2338
projects
train
function projects(req, res, next) { var params = { "formId": req.params.id }; logger.debug("Middleware: form projects: ", {params: params}); forms.getFormApps(_.extend(req.connectionOptions, params), formsResultHandlers(constants.resultTypes.formProjects, req, next)); }
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) { if (err) { logger.error("Middleware: form submissions ", {error: err}); } getSubmissionResponse = getSubmissionResponse || {}; req.appformsResultPayload = { data: getSubmissionResponse.submissions, type: constants.resultTypes.submissions }; next(err); }); }
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 }; logger.debug("Middleware: form submitFormData: ", {params: submissionParams}); forms.submitFormData(_.extend(submissionParams, req.connectionOptions), formsResultHandlers(constants.resultTypes.submissions, req, next)); }
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); } return addRuleCallback(null, frdoc); }); } async.map(rulesToCreate, addRule, cb); }
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); } for (var saveKey in ruleDetails) { // eslint-disable-line guard-for-in ruleToUpdate[saveKey] = ruleDetails[saveKey]; } ruleToUpdate.save(cb1); }); } async.map(rulesToUpdate, updateRule, cb); }
javascript
{ "resource": "" }
q2343
deleteRules
train
function deleteRules(rulesToDelete, cb) { var idsToRemove = _.pluck(rulesToDelete, "_id"); function deleteRule(fieldRuleId, cb1) { rulesModel.findByIdAndRemove(fieldRuleId, cb1); } async.each(idsToRemove, deleteRule, cb); }
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)); ms -= _maxTimeout; } return await new Promise(resolve => setTimeout(resolve, ms, seconds)); }
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 { return false; } }); //If the invalidFieldList is > 0, it means that one of the fields was invalid. return invalidFieldList.length > 0; }); var invalidField = invalidPages.length > 0; //Invalid if either the field is invalid, or it does not exist in the form. if (invalidField === true || !fieldExistsInForm) { return cb(true); } else { return cb(); } }
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 && section.repeating; }) .map(function(repeatingSection) { return repeatingSection._id.toString(); }) .uniq() .value(); }
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(); return conditionalStatements.length === 0 || rulesFlaggedForDeletion[pageRuleId]; }); fieldRulesToDelete = _.map(fieldRulesToDelete, function(fieldRule) { return fieldRule._id.toString(); }); pageRulesToDelete = _.map(pageRulesToDelete, function(pageRule) { return pageRule._id.toString(); }); //Now have all the rules that need to be deleted, these rules need to be removed from the field and page rules updatedFieldRules = _.filter(updatedFieldRules, function(updatedFieldRule) { return fieldRulesToDelete.indexOf(updatedFieldRule._id.toString()) === -1; }); updatedPageRules = _.filter(updatedPageRules, function(updatedPageRule) { return pageRulesToDelete.indexOf(updatedPageRule._id.toString()) === -1; }); form.fieldRules = updatedFieldRules; form.pageRules = updatedPageRules; form.save(function(err) { return cb(err); }); }
javascript
{ "resource": "" }
q2348
filterConditionalStatements
train
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; } }); }
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 patternKey in patterns) { if (!isCollection(patterns[patternKey])) { walkCollections(patterns[patternKey], drizzleData, writePromises); } } return writePromises; }
javascript
{ "resource": "" }
q2350
writeCollections
train
function writeCollections(drizzleData) { return Promise.all(walkCollections(drizzleData.patterns, drizzleData)).then( writePromises => drizzleData, error => DrizzleError.error(error, drizzleData.options.debug) ); }
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', 'Invalid argument type when creating an AttributeDictionary (it has to ' + 'be an object)' ); if (attributes instanceof Array) { for (var i = 0; i < attributes.length; i++) { _addAttribute(this, attributes[i]); } } else { for (var attribute in attributes) { _addAttribute(this, attributes[attribute], attribute); } } } Object.preventExtensions(this); Object.seal(this); }
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; } } if (!(attribute instanceof Attribute)) { attribute = Attribute.resolve(attribute); } expect(attribute.constructor).to.not.equal( Attribute, 'Invalid attribute "' + attribute.name + '". Attribute is an abstract ' + 'class and cannot be directly instantiated and added in an ' + 'AttributeDictionary' ); expect(attributeDictionary).to.not.have.ownProperty( attribute.name, 'Duplicated attribute name "' + attribute.name + '"' ); Object.defineProperty(attributeDictionary, attribute.name, { value: attribute, enumerable: true, writable: false, configurable: false }); }
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 AttributeDictionary ' + '(it has to be an Attribute)' ); var currentAttributes = []; for (var currentAttribute in attributeDictionary) { currentAttributes.push(attributeDictionary[currentAttribute]); } currentAttributes.push(attribute); return new AttributeDictionary(currentAttributes); }
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 if (dataTargets.length !== 1) { return cb(buildErrorResponse({ error: new Error("Data Target Not Found"), systemDetail: "Requested ID: " + params[CONSTANTS.DATA_TARGET_ID], code: ERROR_CODES.FH_FORMS_NOT_FOUND })); } return cb(undefined, dataTargets[0]); }); }, function checkForms(dataTargetJSON, cb) { //Checking For Any Forms Associated With The Data Target checkFormsUsingDataTarget(connections, dataTargetJSON, cb); } ], cb); }
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 })); } return cb(undefined, updatedDataTarget); }, function processResponse(updatedDataTarget, cb) { //Removing The Data Target var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET); DataTarget.remove({_id: updatedDataTarget._id}, function(err) { if (err) { return cb(buildErrorResponse({ error: err, userDetail: "Unexpected Error When Removing A Data Target", code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } //Data Target Removed Successfully return cb(); }); } ], cb); }
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: err, userDetail: "Unexpected Error When Searching For A Data Target", code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } return cb(undefined, dataTargets); }); } ], cb); }
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, cb) { dataTargetJSON = sanitiseJSON(dataTargetJSON); var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET); var newDataTarget = new DataTarget(dataTargetJSON); newDataTarget.save(function(err) { if (err) { return cb(buildErrorResponse({ error: err, userDetail: "Invalid Data Target Creation Data.", systemDetail: err.errors, code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS })); } return cb(undefined, newDataTarget.toJSON()); }); } ], cb); }
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, userDetail: "Invalid Data Target Creation Data.", systemDetail: err.errors, code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS })); } return cb(undefined, dataTarget); }); }
javascript
{ "resource": "" }
q2359
getSiblings
train
function getSiblings(el) { const allSiblings = getPreviousSiblings(el).concat(getNextSiblings(el)); return allSiblings.filter(filterSibling); }
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 { fieldCodes[fieldCode] = true; } } } else { invalidFieldCode = true; //Field codes must be a string. } return field; }); return page; }); if (duplicateFieldCode) { return new Error("Duplicate Field Codes Detected. Field Codes Must Be Unique In A Form."); } if (invalidFieldCode) { return new Error("Invalid Field Code. Field Codes Must Be A String."); } //All valid. can proceed to saving the form. return undefined; }
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 cb(err); } //If the number of found forms is > 0, then there is another form with the same name. Do not save the form. if (count > 0) { return cb(new Error("Form with name " + formName + " already exists found.")); } else {//No duplicates, can proceed with saving the form. return cb(); } }); }
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; } }); //Removing any undefined values return _.compact(fields); }); //Remove all nested arrays dataSources = _.flatten(dataSources); logger.debug("Got Form Data Sources", dataSources); //Only Want One Of Each Data Source return _.uniq(dataSources); }
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 if (options.expectDataSourceCache && type === models.MODELNAMES.DATA_SOURCE) { var missingCache = _.find(foundModels, function(dataSource) { return dataSource.cache.length === 0; }); if (missingCache) { return cb(buildErrorResponse({ error: new Error("Expected " + errorTextDataType + " Cached Data To Be Set"), systemDetail: "Expected Cache For " + errorTextDataType + " ID " + missingCache._id + " To Be Set", code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS })); } } //Checking that only one real time data target is assigned. if (type === models.MODELNAMES.DATA_TARGET) { var realTimeDataTargets = _.filter(foundModels, function(foundModel) { return foundModel.type === models.CONSTANTS.DATA_TARGET_TYPE_REAL_TIME; }); if (realTimeDataTargets.length > 1) { return cb(buildErrorResponse({ error: new Error("Only One Real Time Data Target Can Be Assigned To A Form"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS } )); } } return cb(undefined, foundModels); }); }
javascript
{ "resource": "" }
q2364
verifyDataSources
train
function verifyDataSources(formDataSourceIds, cb) { findMatchingDocuments(models.MODELNAMES.DATA_SOURCE, formDataSourceIds, dataSourceModel, cb); }
javascript
{ "resource": "" }
q2365
verifyDataTargets
train
function verifyDataTargets(dataTargetIds, cb) { findMatchingDocuments(models.MODELNAMES.DATA_TARGET, dataTargetIds, dataTargetModel, cb); }
javascript
{ "resource": "" }
q2366
verifyFormDataSourcesAndTargets
train
function verifyFormDataSourcesAndTargets(formData, cb) { var formDataSourceIds = getFormDataSources(formData); var dataTargets = formData.dataTargets || []; async.series({ dataSources : function(cb) { verifyDataSources(formDataSourceIds, cb); }, dataTargets: function(cb) { verifyDataTargets(dataTargets, cb); } }, 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); if (!this.options.session_token) this.options.session_token = retrieve('session_token', src); } this.options.user_token = retrieve('ut', src) || store('ut', this.keygen(), 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 }; if(call_opts.type === 'GET') call_opts.query = parameters; else { call_opts.data = JSON.stringify(parameters); } return new APICall(call_opts); }
javascript
{ "resource": "" }
q2369
train
function(notification, options) { options = opts(this, options); return new APICall({ action: 'push', type: 'POST', query: server_params(options), options: options, data: JSON.stringify(notification) }); }
javascript
{ "resource": "" }
q2370
train
function(id, options) { options = opts(this, options); return new APICall({ action: 'account/' + id, type: 'GET', query: server_params(options), options: options }); }
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 */ reader.onabort = function() { apicall.setData("FileReader aborted").abort(); } /** @private */ reader.onerror = function(e) { apicall.setData(e.target.error).abort(); } /** @private */ reader.onload = function(e) { upload(e.target.result); } // Don't need to transform Files to Blobs. if (File && file instanceof File) { if (!options.contentType && file.type != "") options.contentType = file.type; } else { file = new Blob([ new Uint8Array(file) ], {type: options.contentType || defaultType}); } reader.readAsDataURL(file); } else NotSupported(); return apicall; }
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] = iframe; } apicall.done(response); } else if (options.mode === 'buffer' && (ArrayBuffer || Buffer)) { apicall.setProcessor(function(data) { var buffer; if (Buffer) { buffer = new Buffer(data, 'binary'); } else { buffer = new ArrayBuffer(data.length); var charView = new Uint8Array(buffer); for (var i = 0; i < data.length; ++i) { charView[i] = data[i] & 0xFF; } } response.success[key] = buffer; return response; }).done(); } else { // Raw data return. Do not attempt to process the result. apicall.setProcessor(function(data) { response.success[key] = data; return response; }).done(); } return apicall; }
javascript
{ "resource": "" }
q2373
train
function(user_id, profile, options) { options = opts(this, options); return new APICall({ action: 'account/' + user_id, type: 'POST', options: options, query: server_params(options), data: JSON.stringify(profile) }); }
javascript
{ "resource": "" }
q2374
train
function(user_id, password, options) { options = opts(this, options); var payload = JSON.stringify({ password: password }); return new APICall({ action: 'account/' + user_id + '/password/change', type: 'POST', options: options, processResponse: APICall.basicResponse, data: payload }); }
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', type: 'POST', options: options, processResponse: APICall.basicResponse, data: payload }); }
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, type: 'POST', data: payload, processResponse: APICall.basicResponse, options: options }); }
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 = query.headers; if(query.params) urlParams.params = query.params; var apicall = new APICall({ action: url, type: query.method, query: urlParams, options: options, data: query.data, contentType: 'application/octet-stream' }); return apicall; }
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, this.options.appid); } } if (auth.password) { // Non-master key access config.data = JSON.stringify({ email: auth.email, username: auth.username, password: auth.password }) } else { // Master key access config.action += '/' + auth.email; } return new APICall(config); }
javascript
{ "resource": "" }
q2379
train
function(aclid, options){ options = opts(this, options); return new APICall({ action: 'access/' + aclid, type: 'DELETE', processResponse: APICall.basicResponse, options: options }); }
javascript
{ "resource": "" }
q2380
train
function() { if (this.options.applevel === true || this.options.applevel === false) return this.options.applevel; return this.options.session_token == null; }
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() { self.off(eventType, callback, context); callback.apply(this, arguments); }]); } return this; }
javascript
{ "resource": "" }
q2382
train
function(event/*, arg1...*/) { var events = this._events[event]; if (events != null) { var args = slice(arguments, 1); each(events, function(event) { event[2].apply(event[1], args); }); } return this; }
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, context); }); } else { this._events[eventType] = removeCallbacks(this._events[eventType], callback, context); } return this; }
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; delete this.xhr; } if (this.config) { this.config = undefined; delete this.config; } return this; }
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 "o" when copying an object (it has to be an object)' ); var oCopy = {}; for (var property in o) { oCopy[property] = o[property]; } return oCopy; }
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__ */ const base = __legendary_pancake_base_pathname__ // eslint-disable-line camelcase const pathname = found.pathname return `href="${base}${pathname}" data-to="${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 = validInvalid[0]; //Updating any data sources that are no longer valid var invalidDataSources = _.union(validInvalid[1], currentInvalidDataSources); return { valid: validDataSources, invalid: invalidDataSources }; }
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}); return cb(buildErrorResponse({ error: err, userDetail: "Unexpected Error When Searching For A Data Source", code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } //Map Found Data Source Documents var dsWithDocuments = _.map(dataSources, function(validDataSource) { var matchingDocument = _.find(foundDataSources, function(dataSourceDocument) { return _.isEqual(dataSourceDocument._id.toString(), validDataSource._id.toString()); }); //If the document is found, assign it to the object, if not, set an error if (matchingDocument) { validDataSource.document = matchingDocument; } else { validDataSource.error = buildErrorResponse({ error: new Error("Data Source Not Found"), userDetail: "Data Source Not Found", code: ERROR_CODES.FH_FORMS_NOT_FOUND }); } return validDataSource; }); var validInvalidDataSources = updateValidAndInvalidDataSources(dsWithDocuments, []); logger.debug("findDataSources", {validInvalidDataSources: validInvalidDataSources}); cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid); }); }
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 Source Data Cache"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}); } if (!misc.checkId(dataSourceUpdateData._id)) { dataSourceUpdateData.error = buildErrorResponse({error: new Error("Invalid ID Paramter " + dataSourceUpdateData._id), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}); } return dataSourceUpdateData; }); //Filter out any data sources with invalid parameters. cb(undefined, dataSources); }
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); return dataSourceData; }); async.map(dsWithDocuments, function(dataSourceWithDocument, cb) { return updateDataSourceEntry(params, dataSourceWithDocument, cb); }, function(err, updatedDocuments) { logger.debug("ARGUMENTS", arguments); //Documents are now either updated or failed var validInvalidDataSources = updateValidAndInvalidDataSources(updatedDocuments, dsWithNoDocuments); return cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid); }); }
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 useful for client/cloud apps that need to determine if they need to load the entire form again. Form.update({ "dataSources.formDataSources": {"$in": updatedDataSourceIds} }, { "$set": { "dataSources.lastRefresh": params.currentTime } }, { multi: true }, function(err) { if (err) { return cb(buildErrorResponse({ error: new Error("Error Updating Forms Refresh Fields"), code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR })); } //No error, forms updated, moving on cb(undefined, validDataSources, invalidDataSources); }); }
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({ error: err, userDetail: "Unexpected Error When Saving Data Source Data", code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR }); logger.error("Error Updating Data Source ", {error: dataSourceData.error, dataSourceDocument: dataSourceDocument, cache: dataSourceDocument.cache[0]}); //Not interested in the document if the save is invalid dataSourceData = _.omit(dataSourceData, 'document'); return cb(undefined, dataSourceData); } logger.debug("updateDataSourceEntry: Finished Updating Data Source", dataSourceDocument); //Save Was Successful, return updated document dataSourceData.document = dataSourceDocument; return cb(undefined, dataSourceData); }); }); } ], callback); }
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 }; } if (!dataSourceData.error && !dataSourceData.dataError) { //marking the status as ok. cacheElement.currentStatus = { status: "ok", error: null }; //Resetting the backOffIndex as it is a valid Data Source update. cacheElement.backOffIndex = 0; cacheElement.markModified('currentStatus'); } else { //The data source encountered an error. Increment the backOffIndex. cacheElement.backOffIndex = cacheElement.backOffIndex ? cacheElement.backOffIndex + 1 : 1; } //Mark The Submission As Refreshed cacheElement.lastRefreshed = params.currentTime; logger.debug("updateDataSourceEntry ", {cacheElementAfterValidate: cacheElement}); cb(); }); }, async.apply(saveAuditLogEntryAndUpdateDataSource, _.extend({ cacheElement: cacheElement, dataSourceDocument: dataSourceDocument, dataSourceData: dataSourceData }, params)) ], callback); }
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) { return processDataSourceResponse(validDataSourceData.document.toJSON()); }); logger.debug("prepareResponse After", validDataSources); var returnError; if (invalidDataSources.length > 0) { returnError = buildErrorResponse({ error: new Error("Error Updating Data Sources"), code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR }); } return cb(returnError, { validDataSourceUpdates: validDataSources, invalidDataSourceUpdates: invalidDataSources }); }
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++) { totalFileSizes += fileSizes[fileSizeIdx]; } return totalFileSizes; }; logger.debug("getSubmissionStorage", {options: options}); Promise.race([ // Don't wait longer than 30 seconds for mongodb mapReduce. // Note that it should still complete, but if it's not back in // 30 seconds, we continue without it. new Promise(resolve => setTimeout(resolve, 30000)), //Map-Reduce Operation to count the file sizes. connections.databaseConnection.collection('formsubmissions').mapReduce(mapFileSizesFunction, reduceFileSizesFunction, {out : {inline: 1}, verbose:true}) ]) .then(out => { fileSizesByForm = out && out.results ? out.results : []; return cb(); }) .catch(err => { //If there are no submissions, then the collection does not //exist. No need to error out of the request. if (err.message.indexOf("ns doesn't exist") > -1) { return cb(); } else { return cb(err); } }); }
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( `Property ${curr} not found on supplied object`, DrizzleError.LEVELS.ERROR ) ); } } return prev[curr]; }, obj); }
javascript
{ "resource": "" }
q2397
deepCollection
train
function deepCollection(collectionId, obj) { const pathBits = idKeys(collectionId); pathBits.pop(); pathBits.push('collection'); pathBits.shift(); return deepObj(pathBits, obj, false); }
javascript
{ "resource": "" }
q2398
isObject
train
function isObject(obj) { const objType = typeof obj; return objType === 'object' && Boolean(obj) && !Array.isArray(obj); }
javascript
{ "resource": "" }
q2399
flattenById
train
function flattenById(obj, keyedObj = {}) { if (obj.hasOwnProperty('id')) { keyedObj[obj.id] = obj; } for (var key in obj) { if (isObject(obj[key])) { flattenById(obj[key], keyedObj); } } return keyedObj; }
javascript
{ "resource": "" }