repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
cloudfour/drizzle-builder
src/utils/object.js
resourceId
function resourceId(resourceFile, relativeTo, resourceCollection = '') { const pathKeys = relativePathArray(resourceFile.path, relativeTo).map( keyname ); const resourceBits = []; if (resourceCollection && resourceCollection.length !== 0) { resourceBits.push(resourceCollection); } return resourceBits .concat(pathKeys) .concat([keyname(resourceFile.path)]) .join('.'); }
javascript
function resourceId(resourceFile, relativeTo, resourceCollection = '') { const pathKeys = relativePathArray(resourceFile.path, relativeTo).map( keyname ); const resourceBits = []; if (resourceCollection && resourceCollection.length !== 0) { resourceBits.push(resourceCollection); } return resourceBits .concat(pathKeys) .concat([keyname(resourceFile.path)]) .join('.'); }
[ "function", "resourceId", "(", "resourceFile", ",", "relativeTo", ",", "resourceCollection", "=", "''", ")", "{", "const", "pathKeys", "=", "relativePathArray", "(", "resourceFile", ".", "path", ",", "relativeTo", ")", ".", "map", "(", "keyname", ")", ";", "const", "resourceBits", "=", "[", "]", ";", "if", "(", "resourceCollection", "&&", "resourceCollection", ".", "length", "!==", "0", ")", "{", "resourceBits", ".", "push", "(", "resourceCollection", ")", ";", "}", "return", "resourceBits", ".", "concat", "(", "pathKeys", ")", ".", "concat", "(", "[", "keyname", "(", "resourceFile", ".", "path", ")", "]", ")", ".", "join", "(", "'.'", ")", ";", "}" ]
Generate a resourceId for a file. Use file.path and base the ID elements on the path elements between relativeTo and file. Path elements will have special characters removed. @example resourceId( '/foo/bar/baz/ole/01-fun-times.hbs', '/foo/bar/baz/', 'patterns' ); // -> patterns.ole.fun-times @param {Object} Object representing file. Needs to have a `path` property @param {String|Array} relativeTo path to relative root or path elements to same in Array @param {String} resourceCollection Will be prepended as first element in ID if provided. @return {String} ID for this resource
[ "Generate", "a", "resourceId", "for", "a", "file", ".", "Use", "file", ".", "path", "and", "base", "the", "ID", "elements", "on", "the", "path", "elements", "between", "relativeTo", "and", "file", ".", "Path", "elements", "will", "have", "special", "characters", "removed", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/object.js#L108-L120
train
cloudfour/drizzle-builder
src/utils/object.js
isPathChild
function isPathChild(pathA, pathB) { const relPath = relative(normalizePath(pathA), normalizePath(pathB)); return relPath === '..'; }
javascript
function isPathChild(pathA, pathB) { const relPath = relative(normalizePath(pathA), normalizePath(pathB)); return relPath === '..'; }
[ "function", "isPathChild", "(", "pathA", ",", "pathB", ")", "{", "const", "relPath", "=", "relative", "(", "normalizePath", "(", "pathA", ")", ",", "normalizePath", "(", "pathB", ")", ")", ";", "return", "relPath", "===", "'..'", ";", "}" ]
Check if one path is a direct child of another. @param {String} pathA @param {String} pathB @return {Boolean} @example isPathChild('components/button', 'components'); // true
[ "Check", "if", "one", "path", "is", "a", "direct", "child", "of", "another", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/object.js#L183-L186
train
crispy1989/node-zstreams
lib/readable.js
ZReadable
function ZReadable(options) { if(options) { if(options.readableObjectMode) { options.objectMode = true; } //Add support for iojs simplified stream constructor if(typeof options.read === 'function') { this._read = options.read; } } Readable.call(this, options); streamMixins.call(this, Readable.prototype, options); readableMixins.call(this, options); }
javascript
function ZReadable(options) { if(options) { if(options.readableObjectMode) { options.objectMode = true; } //Add support for iojs simplified stream constructor if(typeof options.read === 'function') { this._read = options.read; } } Readable.call(this, options); streamMixins.call(this, Readable.prototype, options); readableMixins.call(this, options); }
[ "function", "ZReadable", "(", "options", ")", "{", "if", "(", "options", ")", "{", "if", "(", "options", ".", "readableObjectMode", ")", "{", "options", ".", "objectMode", "=", "true", ";", "}", "if", "(", "typeof", "options", ".", "read", "===", "'function'", ")", "{", "this", ".", "_read", "=", "options", ".", "read", ";", "}", "}", "Readable", ".", "call", "(", "this", ",", "options", ")", ";", "streamMixins", ".", "call", "(", "this", ",", "Readable", ".", "prototype", ",", "options", ")", ";", "readableMixins", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
ZReadable implements the Readable streams interface @class ZReadable @constructor @extends Readable @uses _Stream @uses _Readable @param {Object} [options] - Stream options
[ "ZReadable", "implements", "the", "Readable", "streams", "interface" ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/readable.js#L17-L30
train
feedhenry/fh-forms
lib/impl/getSubmissions/index.js
paginateList
function paginateList(formSubmissionModel, params, callback) { logger.debug("paginateList", params); var query = params.query || {}; var paginate = params.paginate || {}; var fieldModel = params.fieldModel; //Sorting can be defined by the user var sortBy = params.sortBy || { submissionCompletedTimestamp: -1 }; formSubmissionModel.paginate(query, { page: paginate.page, limit: paginate.limit, select: CONSTANTS.SUBMISSION_SUMMARY_FIELD_SELECTION, populate: {"path": "formFields.fieldId", "model": fieldModel, "select": "_id type name"}, sortBy: sortBy, lean: true }, function(err, submissionsResult) { //Returning pagination metadata. Useful for displaying tables etc. var paginationResult = _.extend({ pages: submissionsResult.pages, total: submissionsResult.total }, params); handleListResult(err, paginationResult, submissionsResult.docs, callback); }); }
javascript
function paginateList(formSubmissionModel, params, callback) { logger.debug("paginateList", params); var query = params.query || {}; var paginate = params.paginate || {}; var fieldModel = params.fieldModel; //Sorting can be defined by the user var sortBy = params.sortBy || { submissionCompletedTimestamp: -1 }; formSubmissionModel.paginate(query, { page: paginate.page, limit: paginate.limit, select: CONSTANTS.SUBMISSION_SUMMARY_FIELD_SELECTION, populate: {"path": "formFields.fieldId", "model": fieldModel, "select": "_id type name"}, sortBy: sortBy, lean: true }, function(err, submissionsResult) { //Returning pagination metadata. Useful for displaying tables etc. var paginationResult = _.extend({ pages: submissionsResult.pages, total: submissionsResult.total }, params); handleListResult(err, paginationResult, submissionsResult.docs, callback); }); }
[ "function", "paginateList", "(", "formSubmissionModel", ",", "params", ",", "callback", ")", "{", "logger", ".", "debug", "(", "\"paginateList\"", ",", "params", ")", ";", "var", "query", "=", "params", ".", "query", "||", "{", "}", ";", "var", "paginate", "=", "params", ".", "paginate", "||", "{", "}", ";", "var", "fieldModel", "=", "params", ".", "fieldModel", ";", "var", "sortBy", "=", "params", ".", "sortBy", "||", "{", "submissionCompletedTimestamp", ":", "-", "1", "}", ";", "formSubmissionModel", ".", "paginate", "(", "query", ",", "{", "page", ":", "paginate", ".", "page", ",", "limit", ":", "paginate", ".", "limit", ",", "select", ":", "CONSTANTS", ".", "SUBMISSION_SUMMARY_FIELD_SELECTION", ",", "populate", ":", "{", "\"path\"", ":", "\"formFields.fieldId\"", ",", "\"model\"", ":", "fieldModel", ",", "\"select\"", ":", "\"_id type name\"", "}", ",", "sortBy", ":", "sortBy", ",", "lean", ":", "true", "}", ",", "function", "(", "err", ",", "submissionsResult", ")", "{", "var", "paginationResult", "=", "_", ".", "extend", "(", "{", "pages", ":", "submissionsResult", ".", "pages", ",", "total", ":", "submissionsResult", ".", "total", "}", ",", "params", ")", ";", "handleListResult", "(", "err", ",", "paginationResult", ",", "submissionsResult", ".", "docs", ",", "callback", ")", ";", "}", ")", ";", "}" ]
paginateList - Returning a paginated list of submissions. @param {object} formSubmissionModel Submission Mongoose Model @param {object} params @param {object} params.query Query to filter by. @param {object} params.paginate Pagination parameters @param {number} params.paginate.page Pagination page @param {number} params.paginate.limit Page to return @param {number} params.paginate.filter String to filter submissions by @param {function} callback
[ "paginateList", "-", "Returning", "a", "paginated", "list", "of", "submissions", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getSubmissions/index.js#L21-L49
train
feedhenry/fh-forms
lib/impl/getSubmissions/index.js
nonPaginateList
function nonPaginateList(formSubmissionModel, params, callback) { logger.debug("nonPaginateList", params); var submissionQuery = formSubmissionModel.find(params.query || {}); var fieldModel = params.fieldModel; //Sorting can be defined by the user var sortBy = params.sortBy || { submissionCompletedTimestamp: -1 }; //If the full submission is not required, then limit the response payload size. if (!params.includeFullSubmission) { submissionQuery.select({"formSubmittedAgainst.name": 1, "_id": 1, "formId": 1, "appId": 1, "appEnvironment": 1, "formFields": 1}); } submissionQuery.sort(sortBy) .populate({"path": "formFields.fieldId", "model": fieldModel, "select": "_id type name"}) //Assigning a lean query to not parse the response as a mongoose document. This is to improve query performance. .lean() .exec(function(err, foundSubmissions) { handleListResult(err, params, foundSubmissions, callback); }); }
javascript
function nonPaginateList(formSubmissionModel, params, callback) { logger.debug("nonPaginateList", params); var submissionQuery = formSubmissionModel.find(params.query || {}); var fieldModel = params.fieldModel; //Sorting can be defined by the user var sortBy = params.sortBy || { submissionCompletedTimestamp: -1 }; //If the full submission is not required, then limit the response payload size. if (!params.includeFullSubmission) { submissionQuery.select({"formSubmittedAgainst.name": 1, "_id": 1, "formId": 1, "appId": 1, "appEnvironment": 1, "formFields": 1}); } submissionQuery.sort(sortBy) .populate({"path": "formFields.fieldId", "model": fieldModel, "select": "_id type name"}) //Assigning a lean query to not parse the response as a mongoose document. This is to improve query performance. .lean() .exec(function(err, foundSubmissions) { handleListResult(err, params, foundSubmissions, callback); }); }
[ "function", "nonPaginateList", "(", "formSubmissionModel", ",", "params", ",", "callback", ")", "{", "logger", ".", "debug", "(", "\"nonPaginateList\"", ",", "params", ")", ";", "var", "submissionQuery", "=", "formSubmissionModel", ".", "find", "(", "params", ".", "query", "||", "{", "}", ")", ";", "var", "fieldModel", "=", "params", ".", "fieldModel", ";", "var", "sortBy", "=", "params", ".", "sortBy", "||", "{", "submissionCompletedTimestamp", ":", "-", "1", "}", ";", "if", "(", "!", "params", ".", "includeFullSubmission", ")", "{", "submissionQuery", ".", "select", "(", "{", "\"formSubmittedAgainst.name\"", ":", "1", ",", "\"_id\"", ":", "1", ",", "\"formId\"", ":", "1", ",", "\"appId\"", ":", "1", ",", "\"appEnvironment\"", ":", "1", ",", "\"formFields\"", ":", "1", "}", ")", ";", "}", "submissionQuery", ".", "sort", "(", "sortBy", ")", ".", "populate", "(", "{", "\"path\"", ":", "\"formFields.fieldId\"", ",", "\"model\"", ":", "fieldModel", ",", "\"select\"", ":", "\"_id type name\"", "}", ")", ".", "lean", "(", ")", ".", "exec", "(", "function", "(", "err", ",", "foundSubmissions", ")", "{", "handleListResult", "(", "err", ",", "params", ",", "foundSubmissions", ",", "callback", ")", ";", "}", ")", ";", "}" ]
nonPaginateList - Listing submissions without pagination @param {object} formSubmissionModel Submission Mongoose Model @param {object} params @param {object} params.query Query to filter by. @param {function} callback
[ "nonPaginateList", "-", "Listing", "submissions", "without", "pagination" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getSubmissions/index.js#L59-L81
train
feedhenry/fh-forms
lib/impl/exportForms.js
updateMetadata
function updateMetadata(metadata, form) { metadata.files[form.id] = { name: form.name, path: path.join(ZIP_SUBFOLDER_NAME, form.id + '.json') }; }
javascript
function updateMetadata(metadata, form) { metadata.files[form.id] = { name: form.name, path: path.join(ZIP_SUBFOLDER_NAME, form.id + '.json') }; }
[ "function", "updateMetadata", "(", "metadata", ",", "form", ")", "{", "metadata", ".", "files", "[", "form", ".", "id", "]", "=", "{", "name", ":", "form", ".", "name", ",", "path", ":", "path", ".", "join", "(", "ZIP_SUBFOLDER_NAME", ",", "form", ".", "id", "+", "'.json'", ")", "}", ";", "}" ]
Push a new entry into the metadata `files` list
[ "Push", "a", "new", "entry", "into", "the", "metadata", "files", "list" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportForms.js#L13-L18
train
feedhenry/fh-forms
lib/impl/exportForms.js
writeFormsToZip
function writeFormsToZip(forms, callback) { var zip = archiver('zip') , metadata = {}; metadata.exportCreated = new Date(); metadata.files = {}; function processForms() { // Process all forms _.each(forms, function(form) { // Update metadata on the fly updateMetadata(metadata, form); zip.append(JSON.stringify(form), { name: path.join(ZIP_SUBFOLDER_NAME, form.id + '.json') }); }); // Last step: write the metadata file in the root folder zip.append(JSON.stringify(metadata), { name: METADATA_FILE_NAME }); zip.finalize(); } process.nextTick(processForms); callback(null, zip); }
javascript
function writeFormsToZip(forms, callback) { var zip = archiver('zip') , metadata = {}; metadata.exportCreated = new Date(); metadata.files = {}; function processForms() { // Process all forms _.each(forms, function(form) { // Update metadata on the fly updateMetadata(metadata, form); zip.append(JSON.stringify(form), { name: path.join(ZIP_SUBFOLDER_NAME, form.id + '.json') }); }); // Last step: write the metadata file in the root folder zip.append(JSON.stringify(metadata), { name: METADATA_FILE_NAME }); zip.finalize(); } process.nextTick(processForms); callback(null, zip); }
[ "function", "writeFormsToZip", "(", "forms", ",", "callback", ")", "{", "var", "zip", "=", "archiver", "(", "'zip'", ")", ",", "metadata", "=", "{", "}", ";", "metadata", ".", "exportCreated", "=", "new", "Date", "(", ")", ";", "metadata", ".", "files", "=", "{", "}", ";", "function", "processForms", "(", ")", "{", "_", ".", "each", "(", "forms", ",", "function", "(", "form", ")", "{", "updateMetadata", "(", "metadata", ",", "form", ")", ";", "zip", ".", "append", "(", "JSON", ".", "stringify", "(", "form", ")", ",", "{", "name", ":", "path", ".", "join", "(", "ZIP_SUBFOLDER_NAME", ",", "form", ".", "id", "+", "'.json'", ")", "}", ")", ";", "}", ")", ";", "zip", ".", "append", "(", "JSON", ".", "stringify", "(", "metadata", ")", ",", "{", "name", ":", "METADATA_FILE_NAME", "}", ")", ";", "zip", ".", "finalize", "(", ")", ";", "}", "process", ".", "nextTick", "(", "processForms", ")", ";", "callback", "(", "null", ",", "zip", ")", ";", "}" ]
Creates a zip stream and returns it in the callback. The zip archive that is created will contain a metadata.json file and a subfolder `ZIP_SUBFOLDER_NAME` where all the forms will be written to. @param forms A collection of fully populated form objects @param callback Invoked with the zip stream
[ "Creates", "a", "zip", "stream", "and", "returns", "it", "in", "the", "callback", ".", "The", "zip", "archive", "that", "is", "created", "will", "contain", "a", "metadata", ".", "json", "file", "and", "a", "subfolder", "ZIP_SUBFOLDER_NAME", "where", "all", "the", "forms", "will", "be", "written", "to", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportForms.js#L28-L55
train
cloudfour/drizzle-builder
src/prepare/partials.js
registerPartials
function registerPartials(src, options, prefix = '') { return readFiles(src.glob, options).then(partialFiles => { partialFiles.forEach(partialFile => { const partialKey = resourceId(partialFile, src.basedir, prefix); if (options.handlebars.partials.hasOwnProperty(partialKey)) { DrizzleError.error( new DrizzleError( `Partial key '${partialKey}' already registered on Handlebars instance: is this intentional?`, DrizzleError.LEVELS.WARN ), options ); } options.handlebars.registerPartial(partialKey, partialFile.contents); }); }); }
javascript
function registerPartials(src, options, prefix = '') { return readFiles(src.glob, options).then(partialFiles => { partialFiles.forEach(partialFile => { const partialKey = resourceId(partialFile, src.basedir, prefix); if (options.handlebars.partials.hasOwnProperty(partialKey)) { DrizzleError.error( new DrizzleError( `Partial key '${partialKey}' already registered on Handlebars instance: is this intentional?`, DrizzleError.LEVELS.WARN ), options ); } options.handlebars.registerPartial(partialKey, partialFile.contents); }); }); }
[ "function", "registerPartials", "(", "src", ",", "options", ",", "prefix", "=", "''", ")", "{", "return", "readFiles", "(", "src", ".", "glob", ",", "options", ")", ".", "then", "(", "partialFiles", "=>", "{", "partialFiles", ".", "forEach", "(", "partialFile", "=>", "{", "const", "partialKey", "=", "resourceId", "(", "partialFile", ",", "src", ".", "basedir", ",", "prefix", ")", ";", "if", "(", "options", ".", "handlebars", ".", "partials", ".", "hasOwnProperty", "(", "partialKey", ")", ")", "{", "DrizzleError", ".", "error", "(", "new", "DrizzleError", "(", "`", "${", "partialKey", "}", "`", ",", "DrizzleError", ".", "LEVELS", ".", "WARN", ")", ",", "options", ")", ";", "}", "options", ".", "handlebars", ".", "registerPartial", "(", "partialKey", ",", "partialFile", ".", "contents", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Register the files matching `src.glob` as partials. Keys are generated by using path relative to `src.basedir` separated by `.` @param {Object} src Object with `path` and `basedir` props @see defaults @param {Object} options @param {String} prefix Gets passed to `resourceId` as the `resourceCollection` argument. @see utils/object @return {Promise}
[ "Register", "the", "files", "matching", "src", ".", "glob", "as", "partials", ".", "Keys", "are", "generated", "by", "using", "path", "relative", "to", "src", ".", "basedir", "separated", "by", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/prepare/partials.js#L19-L36
train
cloudfour/drizzle-builder
src/prepare/partials.js
preparePartials
function preparePartials(options) { return Promise.all([ registerPartials(options.src.templates, options), // Partials as partials registerPartials(options.src.patterns, options, 'patterns') // Patterns ]).then(() => options, error => DrizzleError.error(error, options.debug)); }
javascript
function preparePartials(options) { return Promise.all([ registerPartials(options.src.templates, options), // Partials as partials registerPartials(options.src.patterns, options, 'patterns') // Patterns ]).then(() => options, error => DrizzleError.error(error, options.debug)); }
[ "function", "preparePartials", "(", "options", ")", "{", "return", "Promise", ".", "all", "(", "[", "registerPartials", "(", "options", ".", "src", ".", "templates", ",", "options", ")", ",", "registerPartials", "(", "options", ".", "src", ".", "patterns", ",", "options", ",", "'patterns'", ")", "]", ")", ".", "then", "(", "(", ")", "=>", "options", ",", "error", "=>", "DrizzleError", ".", "error", "(", "error", ",", "options", ".", "debug", ")", ")", ";", "}" ]
Register a glob of partials. @param {Object} Handlebars instance @param {String|Array} glob
[ "Register", "a", "glob", "of", "partials", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/prepare/partials.js#L43-L48
train
feedhenry/fh-forms
lib/impl/pdfGeneration/renderPDF.js
submissionToPDF
function submissionToPDF(params, cb) { logger.debug("renderPDF submissionToPDF", params); params = params || {}; var maxConcurrentPhantomPerWorker = params.maxConcurrentPhantomPerWorker || config.get().maxConcurrentPhantomPerWorker; if (!params.submission || !params.submission.formSubmittedAgainst || !params.options || !params.options.location) { return cb("Invalid Submission Data. Expected a submission and location parameter."); } pdfGenerationQueue = pdfGenerationQueue || createPDFGenerationQueue(maxConcurrentPhantomPerWorker); //Adding the export task to the queue pdfGenerationQueue.push(params, cb); }
javascript
function submissionToPDF(params, cb) { logger.debug("renderPDF submissionToPDF", params); params = params || {}; var maxConcurrentPhantomPerWorker = params.maxConcurrentPhantomPerWorker || config.get().maxConcurrentPhantomPerWorker; if (!params.submission || !params.submission.formSubmittedAgainst || !params.options || !params.options.location) { return cb("Invalid Submission Data. Expected a submission and location parameter."); } pdfGenerationQueue = pdfGenerationQueue || createPDFGenerationQueue(maxConcurrentPhantomPerWorker); //Adding the export task to the queue pdfGenerationQueue.push(params, cb); }
[ "function", "submissionToPDF", "(", "params", ",", "cb", ")", "{", "logger", ".", "debug", "(", "\"renderPDF submissionToPDF\"", ",", "params", ")", ";", "params", "=", "params", "||", "{", "}", ";", "var", "maxConcurrentPhantomPerWorker", "=", "params", ".", "maxConcurrentPhantomPerWorker", "||", "config", ".", "get", "(", ")", ".", "maxConcurrentPhantomPerWorker", ";", "if", "(", "!", "params", ".", "submission", "||", "!", "params", ".", "submission", ".", "formSubmittedAgainst", "||", "!", "params", ".", "options", "||", "!", "params", ".", "options", ".", "location", ")", "{", "return", "cb", "(", "\"Invalid Submission Data. Expected a submission and location parameter.\"", ")", ";", "}", "pdfGenerationQueue", "=", "pdfGenerationQueue", "||", "createPDFGenerationQueue", "(", "maxConcurrentPhantomPerWorker", ")", ";", "pdfGenerationQueue", ".", "push", "(", "params", ",", "cb", ")", ";", "}" ]
Converting A Submission To A PDF Document In this implementation, the generation function is added to a concurrent queue. The maxConcurrentPhantomPerWorker parameter controls the number of concurrent PDF generation processes per worker. This is to limit the amount of memory the phantomjs processes consume. @param params - submission - location - pdfTemplateLoc - maxConcurrentPhantomPerWorker - The maximum number of concurrent phantom processes per worker. This is to restrict the number of Phantom instances that are active as they consume a lot of memory. @param cb @returns {*}
[ "Converting", "A", "Submission", "To", "A", "PDF", "Document" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/renderPDF.js#L42-L56
train
cloudfour/drizzle-builder
src/utils/write.js
write
function write(filepath, contents) { return mkdirp(path.dirname(filepath)).then(() => { return writeFile(filepath, contents); }); }
javascript
function write(filepath, contents) { return mkdirp(path.dirname(filepath)).then(() => { return writeFile(filepath, contents); }); }
[ "function", "write", "(", "filepath", ",", "contents", ")", "{", "return", "mkdirp", "(", "path", ".", "dirname", "(", "filepath", ")", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "writeFile", "(", "filepath", ",", "contents", ")", ";", "}", ")", ";", "}" ]
Write `contents` to path at `filepath` @param {String} filepath @param {String} contents @return {Promise}
[ "Write", "contents", "to", "path", "at", "filepath" ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/write.js#L15-L19
train
cloudfour/drizzle-builder
src/utils/write.js
writePage
function writePage(resourceId, resourceObj, pathPrefix) { const outputPath = resourcePath(resourceId, pathPrefix); resourceObj.outputPath = outputPath; return write(outputPath, resourceObj.contents); }
javascript
function writePage(resourceId, resourceObj, pathPrefix) { const outputPath = resourcePath(resourceId, pathPrefix); resourceObj.outputPath = outputPath; return write(outputPath, resourceObj.contents); }
[ "function", "writePage", "(", "resourceId", ",", "resourceObj", ",", "pathPrefix", ")", "{", "const", "outputPath", "=", "resourcePath", "(", "resourceId", ",", "pathPrefix", ")", ";", "resourceObj", ".", "outputPath", "=", "outputPath", ";", "return", "write", "(", "outputPath", ",", "resourceObj", ".", "contents", ")", ";", "}" ]
Take an object's contents and write them to an HTML file on the filesystem. @param {String} resourceId e.g. pages.follow-me.down `.`-separated ID representing the hierarchical position of the resource in its object structure. Will be used to derive output path. @param {Object} resourceObj The object to output. Must have `contents` prop @param {String} pathPrefix The output path prefix (as defined in options.dest—@see defaults). @return {Promise}
[ "Take", "an", "object", "s", "contents", "and", "write", "them", "to", "an", "HTML", "file", "on", "the", "filesystem", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/write.js#L32-L36
train
back4app/back4app-entity
src/back/adapters/Adapter.js
Adapter
function Adapter() { expect(this).to.be.an( 'object', 'The Adapter\'s constructor can be only invoked from specialized' + 'classes\' constructors' ); expect(this.constructor).to.be.a( 'function', 'The Adapter\'s constructor can be only invoked from specialized' + 'classes\' constructors' ); expect(this.constructor).to.not.equal( Adapter, 'The Adapter is an abstract class and cannot be directly initialized' ); expect(this).to.be.instanceof( Adapter, 'The Adapter\'s constructor can be only invoked from specialized' + 'classes\' constructors' ); }
javascript
function Adapter() { expect(this).to.be.an( 'object', 'The Adapter\'s constructor can be only invoked from specialized' + 'classes\' constructors' ); expect(this.constructor).to.be.a( 'function', 'The Adapter\'s constructor can be only invoked from specialized' + 'classes\' constructors' ); expect(this.constructor).to.not.equal( Adapter, 'The Adapter is an abstract class and cannot be directly initialized' ); expect(this).to.be.instanceof( Adapter, 'The Adapter\'s constructor can be only invoked from specialized' + 'classes\' constructors' ); }
[ "function", "Adapter", "(", ")", "{", "expect", "(", "this", ")", ".", "to", ".", "be", ".", "an", "(", "'object'", ",", "'The Adapter\\'s constructor can be only invoked from specialized'", "+", "\\'", ")", ";", "'classes\\' constructors'", "\\'", "expect", "(", "this", ".", "constructor", ")", ".", "to", ".", "be", ".", "a", "(", "'function'", ",", "'The Adapter\\'s constructor can be only invoked from specialized'", "+", "\\'", ")", ";", "}" ]
Base class for database adapters. It cannot be directly initialized. @constructor @memberof module:back4app-entity/adapters @example var myAdapter = new MyAdapter(myConfig);
[ "Base", "class", "for", "database", "adapters", ".", "It", "cannot", "be", "directly", "initialized", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/adapters/Adapter.js#L15-L38
train
feedhenry/fh-forms
lib/impl/updateTheme.js
validateDuplicateName
function validateDuplicateName(cb) { var themeId = themeData._id; var themeName = themeData.name; if (!themeName) { return cb(new Error("No theme name passed.")); } var query = {}; //If there is a theme id, then the query to the theme model must exclude the current theme id that is being updated. if (themeId) { query.name = themeName; //Excluding the themeId that is being updated. query["_id"] = {"$nin": [themeId]}; } else { //Just checking that the theme name exists as a theme is being created query.name = themeName; } themeModel.count(query, function(err, count) { if (err) { return cb(err); } //If the number of found theme is > 0, then there is another theme with the same name. Do not save the theme. if (count > 0) { return cb(new Error("Theme with name " + themeName + " already exists.")); } else {//No duplicates, can proceed with saving the theme. return cb(); } }); }
javascript
function validateDuplicateName(cb) { var themeId = themeData._id; var themeName = themeData.name; if (!themeName) { return cb(new Error("No theme name passed.")); } var query = {}; //If there is a theme id, then the query to the theme model must exclude the current theme id that is being updated. if (themeId) { query.name = themeName; //Excluding the themeId that is being updated. query["_id"] = {"$nin": [themeId]}; } else { //Just checking that the theme name exists as a theme is being created query.name = themeName; } themeModel.count(query, function(err, count) { if (err) { return cb(err); } //If the number of found theme is > 0, then there is another theme with the same name. Do not save the theme. if (count > 0) { return cb(new Error("Theme with name " + themeName + " already exists.")); } else {//No duplicates, can proceed with saving the theme. return cb(); } }); }
[ "function", "validateDuplicateName", "(", "cb", ")", "{", "var", "themeId", "=", "themeData", ".", "_id", ";", "var", "themeName", "=", "themeData", ".", "name", ";", "if", "(", "!", "themeName", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"No theme name passed.\"", ")", ")", ";", "}", "var", "query", "=", "{", "}", ";", "if", "(", "themeId", ")", "{", "query", ".", "name", "=", "themeName", ";", "query", "[", "\"_id\"", "]", "=", "{", "\"$nin\"", ":", "[", "themeId", "]", "}", ";", "}", "else", "{", "query", ".", "name", "=", "themeName", ";", "}", "themeModel", ".", "count", "(", "query", ",", "function", "(", "err", ",", "count", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "count", ">", "0", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"Theme with name \"", "+", "themeName", "+", "\" already exists.\"", ")", ")", ";", "}", "else", "{", "return", "cb", "(", ")", ";", "}", "}", ")", ";", "}" ]
Validating theme duplicate names.
[ "Validating", "theme", "duplicate", "names", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateTheme.js#L34-L65
train
back4app/back4app-entity
src/back/models/methods.js
MethodDictionary
function MethodDictionary(methods) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating a new MethodDictionary (it has ' + 'to be passed less than 2 arguments)' ); if (methods) { expect(methods).to.be.an( 'object', 'Invalid argument type when creating a new MethodDictionary (it has to ' + 'be an object)' ); for (var method in methods) { _addMethod(this, methods[method], method); } } Object.preventExtensions(this); Object.seal(this); }
javascript
function MethodDictionary(methods) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating a new MethodDictionary (it has ' + 'to be passed less than 2 arguments)' ); if (methods) { expect(methods).to.be.an( 'object', 'Invalid argument type when creating a new MethodDictionary (it has to ' + 'be an object)' ); for (var method in methods) { _addMethod(this, methods[method], method); } } Object.preventExtensions(this); Object.seal(this); }
[ "function", "MethodDictionary", "(", "methods", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "2", ",", "'Invalid arguments length when creating a new MethodDictionary (it has '", "+", "'to be passed less than 2 arguments)'", ")", ";", "if", "(", "methods", ")", "{", "expect", "(", "methods", ")", ".", "to", ".", "be", ".", "an", "(", "'object'", ",", "'Invalid argument type when creating a new MethodDictionary (it has to '", "+", "'be an object)'", ")", ";", "for", "(", "var", "method", "in", "methods", ")", "{", "_addMethod", "(", "this", ",", "methods", "[", "method", "]", ",", "method", ")", ";", "}", "}", "Object", ".", "preventExtensions", "(", "this", ")", ";", "Object", ".", "seal", "(", "this", ")", ";", "}" ]
Dictionary of Entity Methods. An instance of MethodDictionary is not extensible. @constructor @memberof module:back4app-entity/models/methods @param {?Object.<!string, !function>} [methods] The methods to be added in the dictionary. They have to be given as a dictionary of functions. @example var methodDictionary = new MethodDictionary(); @example var methodDictionary = new MethodDictionary(null); @example var methodDictionary = new MethodDictionary({}); @example var methodDictionary = new MethodDictionary({ method1: function () { return 'method1'; }, method2: function () { return 'method2'; } });
[ "Dictionary", "of", "Entity", "Methods", ".", "An", "instance", "of", "MethodDictionary", "is", "not", "extensible", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/methods.js#L36-L57
train
back4app/back4app-entity
src/back/models/methods.js
_addMethod
function _addMethod(methodDictionary, func, name) { expect(func).to.be.a( 'function', 'Invalid argument "func" when adding a method called "' + name + '" in a ' + 'MethodDictionary (it has to be a function)' ); Object.defineProperty(methodDictionary, name, { value: func, enumerable: true, writable: false, configurable: false }); }
javascript
function _addMethod(methodDictionary, func, name) { expect(func).to.be.a( 'function', 'Invalid argument "func" when adding a method called "' + name + '" in a ' + 'MethodDictionary (it has to be a function)' ); Object.defineProperty(methodDictionary, name, { value: func, enumerable: true, writable: false, configurable: false }); }
[ "function", "_addMethod", "(", "methodDictionary", ",", "func", ",", "name", ")", "{", "expect", "(", "func", ")", ".", "to", ".", "be", ".", "a", "(", "'function'", ",", "'Invalid argument \"func\" when adding a method called \"'", "+", "name", "+", "'\" in a '", "+", "'MethodDictionary (it has to be a function)'", ")", ";", "Object", ".", "defineProperty", "(", "methodDictionary", ",", "name", ",", "{", "value", ":", "func", ",", "enumerable", ":", "true", ",", "writable", ":", "false", ",", "configurable", ":", "false", "}", ")", ";", "}" ]
Adds a new method to the dictionary. @name module:back4app-entity/models/methods~_addMethod @function @param {!module:back4app-entity/models/methods.MethodDictionary} methodDictionary This is the MethodDictionary instance to which the method will be added. @param {!function} func This is the method's function to be added. @param {!string} name This is the name of the method. @private @example MethodDictionary.add( methodDictionary, function () { return 'method3'; }, 'method3' );
[ "Adds", "a", "new", "method", "to", "the", "dictionary", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/methods.js#L78-L91
train
back4app/back4app-entity
src/back/models/methods.js
concat
function concat(methodDictionary, func, name) { expect(arguments).to.have.length( 3, 'Invalid arguments length when concatenating a MethodDictionary (it has ' + 'to be passed 3 arguments)' ); expect(methodDictionary).to.be.instanceof( MethodDictionary, 'Invalid argument "methodDictionary" when concatenating a ' + 'MethodDictionary (it has to be a MethodDictionary)' ); expect(func).to.be.a( 'function', 'Invalid argument "func" when concatenating a MethodDictionary ' + '(it has to be a function)' ); expect(name).to.be.a( 'string', 'Invalid argument "name" when concatenating a MethodDictionary ' + '(it has to be a string)' ); expect(methodDictionary).to.not.have.ownProperty( name, 'Duplicated method name "' + name + '"' ); var currentMethods = {}; for (var currentMethod in methodDictionary) { currentMethods[currentMethod] = methodDictionary[currentMethod]; } currentMethods[name] = func; return new MethodDictionary(currentMethods); }
javascript
function concat(methodDictionary, func, name) { expect(arguments).to.have.length( 3, 'Invalid arguments length when concatenating a MethodDictionary (it has ' + 'to be passed 3 arguments)' ); expect(methodDictionary).to.be.instanceof( MethodDictionary, 'Invalid argument "methodDictionary" when concatenating a ' + 'MethodDictionary (it has to be a MethodDictionary)' ); expect(func).to.be.a( 'function', 'Invalid argument "func" when concatenating a MethodDictionary ' + '(it has to be a function)' ); expect(name).to.be.a( 'string', 'Invalid argument "name" when concatenating a MethodDictionary ' + '(it has to be a string)' ); expect(methodDictionary).to.not.have.ownProperty( name, 'Duplicated method name "' + name + '"' ); var currentMethods = {}; for (var currentMethod in methodDictionary) { currentMethods[currentMethod] = methodDictionary[currentMethod]; } currentMethods[name] = func; return new MethodDictionary(currentMethods); }
[ "function", "concat", "(", "methodDictionary", ",", "func", ",", "name", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", "(", "3", ",", "'Invalid arguments length when concatenating a MethodDictionary (it has '", "+", "'to be passed 3 arguments)'", ")", ";", "expect", "(", "methodDictionary", ")", ".", "to", ".", "be", ".", "instanceof", "(", "MethodDictionary", ",", "'Invalid argument \"methodDictionary\" when concatenating a '", "+", "'MethodDictionary (it has to be a MethodDictionary)'", ")", ";", "expect", "(", "func", ")", ".", "to", ".", "be", ".", "a", "(", "'function'", ",", "'Invalid argument \"func\" when concatenating a MethodDictionary '", "+", "'(it has to be a function)'", ")", ";", "expect", "(", "name", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"name\" when concatenating a MethodDictionary '", "+", "'(it has to be a string)'", ")", ";", "expect", "(", "methodDictionary", ")", ".", "to", ".", "not", ".", "have", ".", "ownProperty", "(", "name", ",", "'Duplicated method name \"'", "+", "name", "+", "'\"'", ")", ";", "var", "currentMethods", "=", "{", "}", ";", "for", "(", "var", "currentMethod", "in", "methodDictionary", ")", "{", "currentMethods", "[", "currentMethod", "]", "=", "methodDictionary", "[", "currentMethod", "]", ";", "}", "currentMethods", "[", "name", "]", "=", "func", ";", "return", "new", "MethodDictionary", "(", "currentMethods", ")", ";", "}" ]
Concatenates a MethodDictionary instance with a new method and returns a new MethodDictionary. @name module:back4app-entity/models/methods.MethodDictionary.concat @function @param {!module:back4app-entity/models/methods.MethodDictionary} methodDictionary The MethodDictionary to be concatenated. @param {!function} func The method's function to be concatenated. @param {!string} name The method's name to be concatenated. @returns {module:back4app-entity/models/methods.MethodDictionary} The new concatenated MethodDictionary. @example var concatenatedMethodDictionary = MethodDictionary.concat( methodDictionary, function () { return 'newMethod'; }, 'newMethod' );
[ "Concatenates", "a", "MethodDictionary", "instance", "with", "a", "new", "method", "and", "returns", "a", "new", "MethodDictionary", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/methods.js#L111-L150
train
cloudfour/drizzle-builder
src/render/collections.js
renderCollection
function renderCollection(patterns, drizzleData, collectionKey) { const layoutKey = drizzleData.options.layouts.collection; let layoutObj; try { // DeepObj will throw if it fails, which is good and fine... layoutObj = deepObj(idKeys(layoutKey), drizzleData.templates, false); } catch (e) { // But Make this error more friendly and specific DrizzleError.error( new DrizzleError( `Could not find partial for default collection layout '${layoutKey}'. Check 'options.layouts.collection' and/or 'options.src.templates' values to make sure they are OK`, DrizzleError.LEVELS.ERROR ), drizzleData.options.debug ); } patterns.collection.contents = applyTemplate( layoutObj.contents, resourceContext(patterns.collection, drizzleData), drizzleData.options ); return patterns; }
javascript
function renderCollection(patterns, drizzleData, collectionKey) { const layoutKey = drizzleData.options.layouts.collection; let layoutObj; try { // DeepObj will throw if it fails, which is good and fine... layoutObj = deepObj(idKeys(layoutKey), drizzleData.templates, false); } catch (e) { // But Make this error more friendly and specific DrizzleError.error( new DrizzleError( `Could not find partial for default collection layout '${layoutKey}'. Check 'options.layouts.collection' and/or 'options.src.templates' values to make sure they are OK`, DrizzleError.LEVELS.ERROR ), drizzleData.options.debug ); } patterns.collection.contents = applyTemplate( layoutObj.contents, resourceContext(patterns.collection, drizzleData), drizzleData.options ); return patterns; }
[ "function", "renderCollection", "(", "patterns", ",", "drizzleData", ",", "collectionKey", ")", "{", "const", "layoutKey", "=", "drizzleData", ".", "options", ".", "layouts", ".", "collection", ";", "let", "layoutObj", ";", "try", "{", "layoutObj", "=", "deepObj", "(", "idKeys", "(", "layoutKey", ")", ",", "drizzleData", ".", "templates", ",", "false", ")", ";", "}", "catch", "(", "e", ")", "{", "DrizzleError", ".", "error", "(", "new", "DrizzleError", "(", "`", "${", "layoutKey", "}", "`", ",", "DrizzleError", ".", "LEVELS", ".", "ERROR", ")", ",", "drizzleData", ".", "options", ".", "debug", ")", ";", "}", "patterns", ".", "collection", ".", "contents", "=", "applyTemplate", "(", "layoutObj", ".", "contents", ",", "resourceContext", "(", "patterns", ".", "collection", ",", "drizzleData", ")", ",", "drizzleData", ".", "options", ")", ";", "return", "patterns", ";", "}" ]
For any given `patterns` entry, render a pattern-collection page for its `items`. Also, remove the `contents` property for individual patterns. Patterns will not render individual pages. This function mutates `patterns`. @param {Object} patterns The current level of the patterns tree we're rendering @param {Object} drizzleData All the data we have, including `options` @param {String} collectionKey The key of the current set of `patterns`. Used to derive the collection's "name" @return {Object} patterns data at this level.
[ "For", "any", "given", "patterns", "entry", "render", "a", "pattern", "-", "collection", "page", "for", "its", "items", ".", "Also", "remove", "the", "contents", "property", "for", "individual", "patterns", ".", "Patterns", "will", "not", "render", "individual", "pages", ".", "This", "function", "mutates", "patterns", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/render/collections.js#L19-L43
train
feedhenry/fh-forms
lib/utils/setup_connections.js
getDbName
function getDbName(uri) { var parsedMongooseUri = mongoUriParser.parse(uri); var dbName = parsedMongooseUri.database; return dbName; }
javascript
function getDbName(uri) { var parsedMongooseUri = mongoUriParser.parse(uri); var dbName = parsedMongooseUri.database; return dbName; }
[ "function", "getDbName", "(", "uri", ")", "{", "var", "parsedMongooseUri", "=", "mongoUriParser", ".", "parse", "(", "uri", ")", ";", "var", "dbName", "=", "parsedMongooseUri", ".", "database", ";", "return", "dbName", ";", "}" ]
Get the database name from the given mongodb uri. @param {string} uri the mongodb uri @returns {string} the name of the mongodb database
[ "Get", "the", "database", "name", "from", "the", "given", "mongodb", "uri", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/utils/setup_connections.js#L12-L16
train
ForstaLabs/librelay-node
src/crypto.js
function(message, signaling_key) { if (signaling_key.byteLength != 52) { throw new Error("Got invalid length signaling_key"); } if (message.byteLength < 1 + 16 + 10) { throw new Error("Got invalid length message"); } if (message[0] != 1) { throw new Error("Got bad version number: " + message[0]); } var aes_key = signaling_key.slice(0, 32); var mac_key = signaling_key.slice(32, 32 + 20); var iv = message.slice(1, 17); var ciphertext = message.slice(1 + 16, message.byteLength - 10); var ivAndCiphertext = message.slice(0, message.byteLength - 10); var mac = message.slice(message.byteLength - 10, message.byteLength); libsignal.crypto.verifyMAC(ivAndCiphertext, mac_key, mac, 10); return libsignal.crypto.decrypt(aes_key, ciphertext, iv); }
javascript
function(message, signaling_key) { if (signaling_key.byteLength != 52) { throw new Error("Got invalid length signaling_key"); } if (message.byteLength < 1 + 16 + 10) { throw new Error("Got invalid length message"); } if (message[0] != 1) { throw new Error("Got bad version number: " + message[0]); } var aes_key = signaling_key.slice(0, 32); var mac_key = signaling_key.slice(32, 32 + 20); var iv = message.slice(1, 17); var ciphertext = message.slice(1 + 16, message.byteLength - 10); var ivAndCiphertext = message.slice(0, message.byteLength - 10); var mac = message.slice(message.byteLength - 10, message.byteLength); libsignal.crypto.verifyMAC(ivAndCiphertext, mac_key, mac, 10); return libsignal.crypto.decrypt(aes_key, ciphertext, iv); }
[ "function", "(", "message", ",", "signaling_key", ")", "{", "if", "(", "signaling_key", ".", "byteLength", "!=", "52", ")", "{", "throw", "new", "Error", "(", "\"Got invalid length signaling_key\"", ")", ";", "}", "if", "(", "message", ".", "byteLength", "<", "1", "+", "16", "+", "10", ")", "{", "throw", "new", "Error", "(", "\"Got invalid length message\"", ")", ";", "}", "if", "(", "message", "[", "0", "]", "!=", "1", ")", "{", "throw", "new", "Error", "(", "\"Got bad version number: \"", "+", "message", "[", "0", "]", ")", ";", "}", "var", "aes_key", "=", "signaling_key", ".", "slice", "(", "0", ",", "32", ")", ";", "var", "mac_key", "=", "signaling_key", ".", "slice", "(", "32", ",", "32", "+", "20", ")", ";", "var", "iv", "=", "message", ".", "slice", "(", "1", ",", "17", ")", ";", "var", "ciphertext", "=", "message", ".", "slice", "(", "1", "+", "16", ",", "message", ".", "byteLength", "-", "10", ")", ";", "var", "ivAndCiphertext", "=", "message", ".", "slice", "(", "0", ",", "message", ".", "byteLength", "-", "10", ")", ";", "var", "mac", "=", "message", ".", "slice", "(", "message", ".", "byteLength", "-", "10", ",", "message", ".", "byteLength", ")", ";", "libsignal", ".", "crypto", ".", "verifyMAC", "(", "ivAndCiphertext", ",", "mac_key", ",", "mac", ",", "10", ")", ";", "return", "libsignal", ".", "crypto", ".", "decrypt", "(", "aes_key", ",", "ciphertext", ",", "iv", ")", ";", "}" ]
Decrypts message into a raw string
[ "Decrypts", "message", "into", "a", "raw", "string" ]
f411c6585772ac67b842767bc7ce23edcbfae4ae
https://github.com/ForstaLabs/librelay-node/blob/f411c6585772ac67b842767bc7ce23edcbfae4ae/src/crypto.js#L9-L27
train
terkelg/globalyzer
src/index.js
isglob
function isglob(str, { strict = true } = {}) { if (str === '') return false; let match, rgx = strict ? STRICT : RELAXED; while ((match = rgx.exec(str))) { if (match[2]) return true; let idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped, // set the index to the next closing character let open = match[1]; let close = open ? CHARS[open] : null; if (open && close) { let n = str.indexOf(close, idx); if (n !== -1) idx = n + 1; } str = str.slice(idx); } return false; }
javascript
function isglob(str, { strict = true } = {}) { if (str === '') return false; let match, rgx = strict ? STRICT : RELAXED; while ((match = rgx.exec(str))) { if (match[2]) return true; let idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped, // set the index to the next closing character let open = match[1]; let close = open ? CHARS[open] : null; if (open && close) { let n = str.indexOf(close, idx); if (n !== -1) idx = n + 1; } str = str.slice(idx); } return false; }
[ "function", "isglob", "(", "str", ",", "{", "strict", "=", "true", "}", "=", "{", "}", ")", "{", "if", "(", "str", "===", "''", ")", "return", "false", ";", "let", "match", ",", "rgx", "=", "strict", "?", "STRICT", ":", "RELAXED", ";", "while", "(", "(", "match", "=", "rgx", ".", "exec", "(", "str", ")", ")", ")", "{", "if", "(", "match", "[", "2", "]", ")", "return", "true", ";", "let", "idx", "=", "match", ".", "index", "+", "match", "[", "0", "]", ".", "length", ";", "let", "open", "=", "match", "[", "1", "]", ";", "let", "close", "=", "open", "?", "CHARS", "[", "open", "]", ":", "null", ";", "if", "(", "open", "&&", "close", ")", "{", "let", "n", "=", "str", ".", "indexOf", "(", "close", ",", "idx", ")", ";", "if", "(", "n", "!==", "-", "1", ")", "idx", "=", "n", "+", "1", ";", "}", "str", "=", "str", ".", "slice", "(", "idx", ")", ";", "}", "return", "false", ";", "}" ]
Detect if a string cointains glob @param {String} str Input string @param {Object} [options] Configuration object @param {Boolean} [options.strict=true] Use relaxed regex if true @returns {Boolean} true if string contains glob
[ "Detect", "if", "a", "string", "cointains", "glob" ]
c4f91bea1d168ecf39c52fe1a70b122f67b7d688
https://github.com/terkelg/globalyzer/blob/c4f91bea1d168ecf39c52fe1a70b122f67b7d688/src/index.js#L13-L33
train
terkelg/globalyzer
src/index.js
parent
function parent(str, { strict = false } = {}) { str = path.normalize(str).replace(/\/|\\/, '/'); // special case for strings ending in enclosure containing path separator if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/'; // preserves full path in case of trailing path separator str += 'a'; do {str = path.dirname(str)} while (isglob(str, {strict}) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str)); // remove escape chars and return result return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1'); }
javascript
function parent(str, { strict = false } = {}) { str = path.normalize(str).replace(/\/|\\/, '/'); // special case for strings ending in enclosure containing path separator if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/'; // preserves full path in case of trailing path separator str += 'a'; do {str = path.dirname(str)} while (isglob(str, {strict}) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str)); // remove escape chars and return result return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1'); }
[ "function", "parent", "(", "str", ",", "{", "strict", "=", "false", "}", "=", "{", "}", ")", "{", "str", "=", "path", ".", "normalize", "(", "str", ")", ".", "replace", "(", "/", "\\/|\\\\", "/", ",", "'/'", ")", ";", "if", "(", "/", "[\\{\\[].*[\\/]*.*[\\}\\]]$", "/", ".", "test", "(", "str", ")", ")", "str", "+=", "'/'", ";", "str", "+=", "'a'", ";", "do", "{", "str", "=", "path", ".", "dirname", "(", "str", ")", "}", "while", "(", "isglob", "(", "str", ",", "{", "strict", "}", ")", "||", "/", "(^|[^\\\\])([\\{\\[]|\\([^\\)]+$)", "/", ".", "test", "(", "str", ")", ")", ";", "return", "str", ".", "replace", "(", "/", "\\\\([\\*\\?\\|\\[\\]\\(\\)\\{\\}])", "/", "g", ",", "'$1'", ")", ";", "}" ]
Find the static part of a glob-path, split path and return path part @param {String} str Path/glob string @returns {String} static path section of glob
[ "Find", "the", "static", "part", "of", "a", "glob", "-", "path", "split", "path", "and", "return", "path", "part" ]
c4f91bea1d168ecf39c52fe1a70b122f67b7d688
https://github.com/terkelg/globalyzer/blob/c4f91bea1d168ecf39c52fe1a70b122f67b7d688/src/index.js#L42-L56
train
crispy1989/node-zstreams
lib/streams/classic-writable.js
ClassicWritable
function ClassicWritable(stream, options) { var self = this; PassThrough.call(this, options); classicMixins.call(this, stream, options); stream.on('error', function(error) { self.emit('error', error); }); self._isClosed = false; stream.on('close', function() { self._isClosed = true; }); if (!stream.end) stream.end = () => { /* do nothing */ }; this._zSuperObj.pipe.call(this, stream); }
javascript
function ClassicWritable(stream, options) { var self = this; PassThrough.call(this, options); classicMixins.call(this, stream, options); stream.on('error', function(error) { self.emit('error', error); }); self._isClosed = false; stream.on('close', function() { self._isClosed = true; }); if (!stream.end) stream.end = () => { /* do nothing */ }; this._zSuperObj.pipe.call(this, stream); }
[ "function", "ClassicWritable", "(", "stream", ",", "options", ")", "{", "var", "self", "=", "this", ";", "PassThrough", ".", "call", "(", "this", ",", "options", ")", ";", "classicMixins", ".", "call", "(", "this", ",", "stream", ",", "options", ")", ";", "stream", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "self", ".", "emit", "(", "'error'", ",", "error", ")", ";", "}", ")", ";", "self", ".", "_isClosed", "=", "false", ";", "stream", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "self", ".", "_isClosed", "=", "true", ";", "}", ")", ";", "if", "(", "!", "stream", ".", "end", ")", "stream", ".", "end", "=", "(", ")", "=>", "{", "}", ";", "this", ".", "_zSuperObj", ".", "pipe", ".", "call", "(", "this", ",", "stream", ")", ";", "}" ]
ClassicWritable wraps a "classic" writable stream. @class ClassicWritable @constructor @extends ZPassThrough @uses _Classic @param {Stream} stream - The classic stream being wrapped @param {Object} [options] - Stream options
[ "ClassicWritable", "wraps", "a", "classic", "writable", "stream", "." ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/classic-writable.js#L16-L32
train
feedhenry/fh-forms
lib/impl/getSubmissions/buildQuery.js
buildSingleFilterQueryObject
function buildSingleFilterQueryObject(paginationFilter) { return function(submissionQueryField) { var fieldQuery = { }; //formId and _id fields are ObjectIds. They must be valid in order to search for them. if (submissionQueryField === 'formId' || submissionQueryField === '_id') { if (mongoose.Types.ObjectId.isValid(paginationFilter)) { //Cannot use $regex when searching for ObjectIDs fieldQuery[submissionQueryField] = new mongoose.Types.ObjectId(paginationFilter); } else { //not a valid objectId, don't want to search for it. return null; } } else { fieldQuery[submissionQueryField] = {$regex: paginationFilter, $options: 'i'}; } return fieldQuery; }; }
javascript
function buildSingleFilterQueryObject(paginationFilter) { return function(submissionQueryField) { var fieldQuery = { }; //formId and _id fields are ObjectIds. They must be valid in order to search for them. if (submissionQueryField === 'formId' || submissionQueryField === '_id') { if (mongoose.Types.ObjectId.isValid(paginationFilter)) { //Cannot use $regex when searching for ObjectIDs fieldQuery[submissionQueryField] = new mongoose.Types.ObjectId(paginationFilter); } else { //not a valid objectId, don't want to search for it. return null; } } else { fieldQuery[submissionQueryField] = {$regex: paginationFilter, $options: 'i'}; } return fieldQuery; }; }
[ "function", "buildSingleFilterQueryObject", "(", "paginationFilter", ")", "{", "return", "function", "(", "submissionQueryField", ")", "{", "var", "fieldQuery", "=", "{", "}", ";", "if", "(", "submissionQueryField", "===", "'formId'", "||", "submissionQueryField", "===", "'_id'", ")", "{", "if", "(", "mongoose", ".", "Types", ".", "ObjectId", ".", "isValid", "(", "paginationFilter", ")", ")", "{", "fieldQuery", "[", "submissionQueryField", "]", "=", "new", "mongoose", ".", "Types", ".", "ObjectId", "(", "paginationFilter", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}", "else", "{", "fieldQuery", "[", "submissionQueryField", "]", "=", "{", "$regex", ":", "paginationFilter", ",", "$options", ":", "'i'", "}", ";", "}", "return", "fieldQuery", ";", "}", ";", "}" ]
buildSingleFilterQueryObject - Building a query object based on the field to be queried @param {string} paginationFilter Filter value @return {object} Generated Query for the field
[ "buildSingleFilterQueryObject", "-", "Building", "a", "query", "object", "based", "on", "the", "field", "to", "be", "queried" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getSubmissions/buildQuery.js#L12-L32
train
feedhenry/fh-forms
lib/impl/dataSources/update.js
validateParams
function validateParams(dataSource, 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 Update A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } //Data Source Cache Should Not Be Updated With This Function dataSourceValidator.hasno(CONSTANTS.DATA_SOURCE_DATA, CONSTANTS.DATA_SOURCE_CACHE, function() { if (err) { return cb(buildErrorResponse({error: new Error("Updating A Data Source Should Not Include Cache Data"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } cb(undefined, dataSource); }); }); }
javascript
function validateParams(dataSource, 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 Update A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } //Data Source Cache Should Not Be Updated With This Function dataSourceValidator.hasno(CONSTANTS.DATA_SOURCE_DATA, CONSTANTS.DATA_SOURCE_CACHE, function() { if (err) { return cb(buildErrorResponse({error: new Error("Updating A Data Source Should Not Include Cache Data"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS})); } cb(undefined, dataSource); }); }); }
[ "function", "validateParams", "(", "dataSource", ",", "cb", ")", "{", "var", "dataSourceValidator", "=", "validate", "(", "dataSource", ")", ";", "dataSourceValidator", ".", "has", "(", "CONSTANTS", ".", "DATA_SOURCE_ID", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "buildErrorResponse", "(", "{", "error", ":", "new", "Error", "(", "\"An ID Parameter Is Required To Update A Data Source\"", ")", ",", "code", ":", "ERROR_CODES", ".", "FH_FORMS_INVALID_PARAMETERS", "}", ")", ")", ";", "}", "dataSourceValidator", ".", "hasno", "(", "CONSTANTS", ".", "DATA_SOURCE_DATA", ",", "CONSTANTS", ".", "DATA_SOURCE_CACHE", ",", "function", "(", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "buildErrorResponse", "(", "{", "error", ":", "new", "Error", "(", "\"Updating A Data Source Should Not Include Cache Data\"", ")", ",", "code", ":", "ERROR_CODES", ".", "FH_FORMS_INVALID_PARAMETERS", "}", ")", ")", ";", "}", "cb", "(", "undefined", ",", "dataSource", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
validateParams - Validating A Data Source For Update. Should Have A _id parameter and no Data Set. @param {object} dataSource Data Source To Update @param {function} cb Callback @return {undefined}
[ "validateParams", "-", "Validating", "A", "Data", "Source", "For", "Update", ".", "Should", "Have", "A", "_id", "parameter", "and", "no", "Data", "Set", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/update.js#L20-L37
train
feedhenry/fh-forms
lib/impl/dataSources/update.js
findDataSource
function findDataSource(connections, 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 })); } //Should only be one data source if (dataSources.length !== 1) { return cb(buildErrorResponse({ error: new Error("Data Source Not Found"), systemDetail: "Requested ID: " + dataSource[CONSTANTS.DATA_SOURCE_ID], code: ERROR_CODES.FH_FORMS_NOT_FOUND })); } return cb(undefined, dataSource, dataSources[0]); }); }
javascript
function findDataSource(connections, 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 })); } //Should only be one data source if (dataSources.length !== 1) { return cb(buildErrorResponse({ error: new Error("Data Source Not Found"), systemDetail: "Requested ID: " + dataSource[CONSTANTS.DATA_SOURCE_ID], code: ERROR_CODES.FH_FORMS_NOT_FOUND })); } return cb(undefined, dataSource, dataSources[0]); }); }
[ "function", "findDataSource", "(", "connections", ",", "dataSource", ",", "cb", ")", "{", "var", "query", "=", "{", "}", ";", "query", "[", "CONSTANTS", ".", "DATA_SOURCE_ID", "]", "=", "dataSource", "[", "CONSTANTS", ".", "DATA_SOURCE_ID", "]", ";", "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", "(", "dataSources", ".", "length", "!==", "1", ")", "{", "return", "cb", "(", "buildErrorResponse", "(", "{", "error", ":", "new", "Error", "(", "\"Data Source Not Found\"", ")", ",", "systemDetail", ":", "\"Requested ID: \"", "+", "dataSource", "[", "CONSTANTS", ".", "DATA_SOURCE_ID", "]", ",", "code", ":", "ERROR_CODES", ".", "FH_FORMS_NOT_FOUND", "}", ")", ")", ";", "}", "return", "cb", "(", "undefined", ",", "dataSource", ",", "dataSources", "[", "0", "]", ")", ";", "}", ")", ";", "}" ]
findDataSource - Finding A Data Source @param {object} connections Mongoose And Mongo Connections @param {object} dataSource Data Source To Update @param {function} cb Callback @return {undefined}
[ "findDataSource", "-", "Finding", "A", "Data", "Source" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/update.js#L48-L80
train
DennisSchulmeister/lecture-slides.js
src/core/utils.js
shiftLinesLeft
function shiftLinesLeft(text) { // Determine type of linebreak let linebreak = determineLinebreaks(text); if (linebreak === "") return text; let lines = []; lines = text.split(linebreak); // Find amount to shift lines let commonPrefix = null; for (let i = 0; i < lines.length; i++) { if (!lines[i].length) continue; let whitespace = lines[i].match(/^\s*/); if (whitespace) whitespace = whitespace[0]; else whitespace = ""; if (commonPrefix === null || commonPrefix.startsWith(whitespace)) commonPrefix = whitespace; } // Shift lines and return result text = ""; let shift = commonPrefix.length; for (let i = 0; i < lines.length; i++) { if (lines[i].length) { lines[i] = lines[i].slice(shift, lines[i].length); } text += lines[i] + linebreak; } return text; }
javascript
function shiftLinesLeft(text) { // Determine type of linebreak let linebreak = determineLinebreaks(text); if (linebreak === "") return text; let lines = []; lines = text.split(linebreak); // Find amount to shift lines let commonPrefix = null; for (let i = 0; i < lines.length; i++) { if (!lines[i].length) continue; let whitespace = lines[i].match(/^\s*/); if (whitespace) whitespace = whitespace[0]; else whitespace = ""; if (commonPrefix === null || commonPrefix.startsWith(whitespace)) commonPrefix = whitespace; } // Shift lines and return result text = ""; let shift = commonPrefix.length; for (let i = 0; i < lines.length; i++) { if (lines[i].length) { lines[i] = lines[i].slice(shift, lines[i].length); } text += lines[i] + linebreak; } return text; }
[ "function", "shiftLinesLeft", "(", "text", ")", "{", "let", "linebreak", "=", "determineLinebreaks", "(", "text", ")", ";", "if", "(", "linebreak", "===", "\"\"", ")", "return", "text", ";", "let", "lines", "=", "[", "]", ";", "lines", "=", "text", ".", "split", "(", "linebreak", ")", ";", "let", "commonPrefix", "=", "null", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "lines", "[", "i", "]", ".", "length", ")", "continue", ";", "let", "whitespace", "=", "lines", "[", "i", "]", ".", "match", "(", "/", "^\\s*", "/", ")", ";", "if", "(", "whitespace", ")", "whitespace", "=", "whitespace", "[", "0", "]", ";", "else", "whitespace", "=", "\"\"", ";", "if", "(", "commonPrefix", "===", "null", "||", "commonPrefix", ".", "startsWith", "(", "whitespace", ")", ")", "commonPrefix", "=", "whitespace", ";", "}", "text", "=", "\"\"", ";", "let", "shift", "=", "commonPrefix", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "if", "(", "lines", "[", "i", "]", ".", "length", ")", "{", "lines", "[", "i", "]", "=", "lines", "[", "i", "]", ".", "slice", "(", "shift", ",", "lines", "[", "i", "]", ".", "length", ")", ";", "}", "text", "+=", "lines", "[", "i", "]", "+", "linebreak", ";", "}", "return", "text", ";", "}" ]
This function takes a text string and shifts all lines to the left so that as most leading spaces are removed as possible. All lines are shifted by the same amount which is determined as the minimum amount of white space at the beginning of all lines. @param {String} text Original text @return {String} Shifted text
[ "This", "function", "takes", "a", "text", "string", "and", "shifts", "all", "lines", "to", "the", "left", "so", "that", "as", "most", "leading", "spaces", "are", "removed", "as", "possible", ".", "All", "lines", "are", "shifted", "by", "the", "same", "amount", "which", "is", "determined", "as", "the", "minimum", "amount", "of", "white", "space", "at", "the", "beginning", "of", "all", "lines", "." ]
67a29d7fd2ae062a5853bb5067c0e5821b93695d
https://github.com/DennisSchulmeister/lecture-slides.js/blob/67a29d7fd2ae062a5853bb5067c0e5821b93695d/src/core/utils.js#L50-L84
train
DennisSchulmeister/lecture-slides.js
src/core/utils.js
removeLeadingLinebreaks
function removeLeadingLinebreaks(text) { let linebreak = determineLinebreaks(text); if (linebreak === "") return text; while (text.startsWith(linebreak)) { text = text.slice(linebreak.length); } return text; }
javascript
function removeLeadingLinebreaks(text) { let linebreak = determineLinebreaks(text); if (linebreak === "") return text; while (text.startsWith(linebreak)) { text = text.slice(linebreak.length); } return text; }
[ "function", "removeLeadingLinebreaks", "(", "text", ")", "{", "let", "linebreak", "=", "determineLinebreaks", "(", "text", ")", ";", "if", "(", "linebreak", "===", "\"\"", ")", "return", "text", ";", "while", "(", "text", ".", "startsWith", "(", "linebreak", ")", ")", "{", "text", "=", "text", ".", "slice", "(", "linebreak", ".", "length", ")", ";", "}", "return", "text", ";", "}" ]
Remove any leading empty lines found inside the given text. @param {String} text Original text @return {String} Trimmed text
[ "Remove", "any", "leading", "empty", "lines", "found", "inside", "the", "given", "text", "." ]
67a29d7fd2ae062a5853bb5067c0e5821b93695d
https://github.com/DennisSchulmeister/lecture-slides.js/blob/67a29d7fd2ae062a5853bb5067c0e5821b93695d/src/core/utils.js#L92-L101
train
DennisSchulmeister/lecture-slides.js
src/core/utils.js
removeTrailingLinebreaks
function removeTrailingLinebreaks(text) { let linebreak = determineLinebreaks(text); if (linebreak === "") return text; while (text.endsWith(linebreak)) { text = text.slice(0, 0 - linebreak.length); } return text; }
javascript
function removeTrailingLinebreaks(text) { let linebreak = determineLinebreaks(text); if (linebreak === "") return text; while (text.endsWith(linebreak)) { text = text.slice(0, 0 - linebreak.length); } return text; }
[ "function", "removeTrailingLinebreaks", "(", "text", ")", "{", "let", "linebreak", "=", "determineLinebreaks", "(", "text", ")", ";", "if", "(", "linebreak", "===", "\"\"", ")", "return", "text", ";", "while", "(", "text", ".", "endsWith", "(", "linebreak", ")", ")", "{", "text", "=", "text", ".", "slice", "(", "0", ",", "0", "-", "linebreak", ".", "length", ")", ";", "}", "return", "text", ";", "}" ]
Remove any trailing empty lines found inside the given text. @param {String} text Original text @return {String} Trimed text
[ "Remove", "any", "trailing", "empty", "lines", "found", "inside", "the", "given", "text", "." ]
67a29d7fd2ae062a5853bb5067c0e5821b93695d
https://github.com/DennisSchulmeister/lecture-slides.js/blob/67a29d7fd2ae062a5853bb5067c0e5821b93695d/src/core/utils.js#L109-L118
train
DennisSchulmeister/lecture-slides.js
src/core/utils.js
trimLines
function trimLines(text) { let linebreak = determineLinebreaks(text); if (linebreak === "") return text; let lines = []; lines = text.split(linebreak); text = ""; for (let i = 0; i < lines.length; i++) { let line = lines[i]; while (true) { let lastChar = line.slice(line.length-1, line.length); let repeat = false; switch (lastChar) { case " ": case "\t": line = line.slice(0, -1) repeat = true; } if (!repeat) break; } text += line + linebreak; } return text; }
javascript
function trimLines(text) { let linebreak = determineLinebreaks(text); if (linebreak === "") return text; let lines = []; lines = text.split(linebreak); text = ""; for (let i = 0; i < lines.length; i++) { let line = lines[i]; while (true) { let lastChar = line.slice(line.length-1, line.length); let repeat = false; switch (lastChar) { case " ": case "\t": line = line.slice(0, -1) repeat = true; } if (!repeat) break; } text += line + linebreak; } return text; }
[ "function", "trimLines", "(", "text", ")", "{", "let", "linebreak", "=", "determineLinebreaks", "(", "text", ")", ";", "if", "(", "linebreak", "===", "\"\"", ")", "return", "text", ";", "let", "lines", "=", "[", "]", ";", "lines", "=", "text", ".", "split", "(", "linebreak", ")", ";", "text", "=", "\"\"", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "let", "line", "=", "lines", "[", "i", "]", ";", "while", "(", "true", ")", "{", "let", "lastChar", "=", "line", ".", "slice", "(", "line", ".", "length", "-", "1", ",", "line", ".", "length", ")", ";", "let", "repeat", "=", "false", ";", "switch", "(", "lastChar", ")", "{", "case", "\" \"", ":", "case", "\"\\t\"", ":", "\\t", "line", "=", "line", ".", "slice", "(", "0", ",", "-", "1", ")", "}", "repeat", "=", "true", ";", "}", "if", "(", "!", "repeat", ")", "break", ";", "}", "text", "+=", "line", "+", "linebreak", ";", "}" ]
Remove any trailing spaces or tabs at the end of each line of a given text. @param {String} text Original text @return {String} Trimed text
[ "Remove", "any", "trailing", "spaces", "or", "tabs", "at", "the", "end", "of", "each", "line", "of", "a", "given", "text", "." ]
67a29d7fd2ae062a5853bb5067c0e5821b93695d
https://github.com/DennisSchulmeister/lecture-slides.js/blob/67a29d7fd2ae062a5853bb5067c0e5821b93695d/src/core/utils.js#L126-L155
train
clavery/grunt-generator
tasks/lib/generator.js
promiseWrap
function promiseWrap(x) { if(x.then && typeof x.then === "function") { return x; } var deferred = q.defer(); deferred.resolve(x); return deferred.promise; }
javascript
function promiseWrap(x) { if(x.then && typeof x.then === "function") { return x; } var deferred = q.defer(); deferred.resolve(x); return deferred.promise; }
[ "function", "promiseWrap", "(", "x", ")", "{", "if", "(", "x", ".", "then", "&&", "typeof", "x", ".", "then", "===", "\"function\"", ")", "{", "return", "x", ";", "}", "var", "deferred", "=", "q", ".", "defer", "(", ")", ";", "deferred", ".", "resolve", "(", "x", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
wrap non-promises in a promise for api simplicity
[ "wrap", "non", "-", "promises", "in", "a", "promise", "for", "api", "simplicity" ]
5b5e29798f04bfcac7c6ff46a146c0088eb79f94
https://github.com/clavery/grunt-generator/blob/5b5e29798f04bfcac7c6ff46a146c0088eb79f94/tasks/lib/generator.js#L39-L46
train
feedhenry/fh-forms
lib/impl/pdfGeneration/cacheFiles.js
cacheSubmissionFile
function cacheSubmissionFile(params, fileToStreamTo, cb) { //If the files are remote, use the mbaas client logger.debug("cacheFiles: cacheSubmissionFile submission", {params: params, fileToStreamTo: fileToStreamTo}); if (params.options.filesAreRemote) { return downloadFileFromMbaas(params, fileToStreamTo, cb); } //File is in the local database, load it there getSubmissionFile(params.connections, params.options, { _id: params.fileId }, function(err, fileDetails) { if (err) { logger.error("cacheFiles: cacheSubmissionFile getSubmissionFile", {error: err}); return cb(err); } fileDetails.stream.on('error', function(err) { logger.error("cacheFiles: cacheSubmissionFile Error Streaming File With Id: " + params.fileId); return cb(err); }); fileDetails.stream.on('end', function() { logger.debug("cacheFiles: cacheSubmissionFile Stream Complete For File With Id: " + params.fileId); return cb(undefined, fileDetails); }); //Streaming The File fileDetails.stream.pipe(fileToStreamTo); fileDetails.stream.resume(); }); }
javascript
function cacheSubmissionFile(params, fileToStreamTo, cb) { //If the files are remote, use the mbaas client logger.debug("cacheFiles: cacheSubmissionFile submission", {params: params, fileToStreamTo: fileToStreamTo}); if (params.options.filesAreRemote) { return downloadFileFromMbaas(params, fileToStreamTo, cb); } //File is in the local database, load it there getSubmissionFile(params.connections, params.options, { _id: params.fileId }, function(err, fileDetails) { if (err) { logger.error("cacheFiles: cacheSubmissionFile getSubmissionFile", {error: err}); return cb(err); } fileDetails.stream.on('error', function(err) { logger.error("cacheFiles: cacheSubmissionFile Error Streaming File With Id: " + params.fileId); return cb(err); }); fileDetails.stream.on('end', function() { logger.debug("cacheFiles: cacheSubmissionFile Stream Complete For File With Id: " + params.fileId); return cb(undefined, fileDetails); }); //Streaming The File fileDetails.stream.pipe(fileToStreamTo); fileDetails.stream.resume(); }); }
[ "function", "cacheSubmissionFile", "(", "params", ",", "fileToStreamTo", ",", "cb", ")", "{", "logger", ".", "debug", "(", "\"cacheFiles: cacheSubmissionFile submission\"", ",", "{", "params", ":", "params", ",", "fileToStreamTo", ":", "fileToStreamTo", "}", ")", ";", "if", "(", "params", ".", "options", ".", "filesAreRemote", ")", "{", "return", "downloadFileFromMbaas", "(", "params", ",", "fileToStreamTo", ",", "cb", ")", ";", "}", "getSubmissionFile", "(", "params", ".", "connections", ",", "params", ".", "options", ",", "{", "_id", ":", "params", ".", "fileId", "}", ",", "function", "(", "err", ",", "fileDetails", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "\"cacheFiles: cacheSubmissionFile getSubmissionFile\"", ",", "{", "error", ":", "err", "}", ")", ";", "return", "cb", "(", "err", ")", ";", "}", "fileDetails", ".", "stream", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "logger", ".", "error", "(", "\"cacheFiles: cacheSubmissionFile Error Streaming File With Id: \"", "+", "params", ".", "fileId", ")", ";", "return", "cb", "(", "err", ")", ";", "}", ")", ";", "fileDetails", ".", "stream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "logger", ".", "debug", "(", "\"cacheFiles: cacheSubmissionFile Stream Complete For File With Id: \"", "+", "params", ".", "fileId", ")", ";", "return", "cb", "(", "undefined", ",", "fileDetails", ")", ";", "}", ")", ";", "fileDetails", ".", "stream", ".", "pipe", "(", "fileToStreamTo", ")", ";", "fileDetails", ".", "stream", ".", "resume", "(", ")", ";", "}", ")", ";", "}" ]
Streaming The File From The Database. @param params - options - fileId - connections @param fileToStreamTo @param cb
[ "Streaming", "The", "File", "From", "The", "Database", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/cacheFiles.js#L99-L129
train
feedhenry/fh-forms
lib/impl/pdfGeneration/cacheFiles.js
mergeSubmissionFiles
function mergeSubmissionFiles(params, cb) { logger.debug("cacheFiles: mergeSubmissionFiles", params); var submission = params.submission; //No submission, cannot continue. if (!_.isObject(submission)) { return cb(buildErrorResponse({ err: new Error("Expected Submission Object To Cache Files For"), msg: "Error Exporting Submission As PDF", httpCode: 500 })); } var form = submission.formSubmittedAgainst; var fileFieldDetails = _.filter(submission.formFields, function(field) { return isFileFieldType(field.fieldId.type); }); fileFieldDetails = _.flatten(fileFieldDetails); var fieldTypes = _.groupBy(fileFieldDetails, function(field) { return field.fieldId.type; }); //Files That Have To Be Loaded From Mbaas var mbaasTypes = _.union(fieldTypes.photo, fieldTypes.signature); //Only Interested In The File Ids To Download var filesToDownload = _.map(mbaasTypes, function(field) { return _.map(field.fieldValues, function(fieldValue) { return fieldValue.groupId; }); }); filesToDownload = _.flatten(filesToDownload); logger.debug("cacheFiles: mergeSubmissionFiles filesToDownload", filesToDownload); //Now download all of the files.. async.mapSeries(filesToDownload, function(fileIdOrUrl, cb) { //Only want the callback to be called once. cb = _.once(cb); var fileUri = path.join(params.options.pdfExportDir, 'image_binary_' + fileIdOrUrl); var localFile = fs.createWriteStream(fileUri); //Loading The Submission File From THe Database / MbaaS cacheSubmissionFile({ fileId: fileIdOrUrl, connections: params.connections, options: params.options, submission: submission }, localFile, function(err, fileDetails) { if (err) { logger.error("cacheFiles: cacheSubmissionFile", {error: err}); } fileDetails = fileDetails || {}; fileDetails.url = "file://" + fileUri; fileDetails.fileId = fileIdOrUrl; logger.debug("cacheFiles: mergeSubmissionFiles fileDetails", fileDetails); return cb(err, _.omit(fileDetails, "stream")); }); }, function(err, cachedFiles) { if (err) { return cb(buildErrorResponse({ error: err, msg: "Error Cacheing Files For Submission Export", code: constants.ERROR_CODES.FH_FORMS_ERR_CODE_PDF_GENERATION, httpCode: 500 })); } //No Errors, all files are now cached for the submission submission.formSubmittedAgainst = populateSubmissionFileData({ form: form, submissionFiles: cachedFiles, downloadUrl: params.options.downloadUrl, fileUriPath: params.options.fileUriPath, submission: submission }); logger.debug("cacheFiles: mergeSubmissionFiles submission", submission); cb(undefined, submission); }); }
javascript
function mergeSubmissionFiles(params, cb) { logger.debug("cacheFiles: mergeSubmissionFiles", params); var submission = params.submission; //No submission, cannot continue. if (!_.isObject(submission)) { return cb(buildErrorResponse({ err: new Error("Expected Submission Object To Cache Files For"), msg: "Error Exporting Submission As PDF", httpCode: 500 })); } var form = submission.formSubmittedAgainst; var fileFieldDetails = _.filter(submission.formFields, function(field) { return isFileFieldType(field.fieldId.type); }); fileFieldDetails = _.flatten(fileFieldDetails); var fieldTypes = _.groupBy(fileFieldDetails, function(field) { return field.fieldId.type; }); //Files That Have To Be Loaded From Mbaas var mbaasTypes = _.union(fieldTypes.photo, fieldTypes.signature); //Only Interested In The File Ids To Download var filesToDownload = _.map(mbaasTypes, function(field) { return _.map(field.fieldValues, function(fieldValue) { return fieldValue.groupId; }); }); filesToDownload = _.flatten(filesToDownload); logger.debug("cacheFiles: mergeSubmissionFiles filesToDownload", filesToDownload); //Now download all of the files.. async.mapSeries(filesToDownload, function(fileIdOrUrl, cb) { //Only want the callback to be called once. cb = _.once(cb); var fileUri = path.join(params.options.pdfExportDir, 'image_binary_' + fileIdOrUrl); var localFile = fs.createWriteStream(fileUri); //Loading The Submission File From THe Database / MbaaS cacheSubmissionFile({ fileId: fileIdOrUrl, connections: params.connections, options: params.options, submission: submission }, localFile, function(err, fileDetails) { if (err) { logger.error("cacheFiles: cacheSubmissionFile", {error: err}); } fileDetails = fileDetails || {}; fileDetails.url = "file://" + fileUri; fileDetails.fileId = fileIdOrUrl; logger.debug("cacheFiles: mergeSubmissionFiles fileDetails", fileDetails); return cb(err, _.omit(fileDetails, "stream")); }); }, function(err, cachedFiles) { if (err) { return cb(buildErrorResponse({ error: err, msg: "Error Cacheing Files For Submission Export", code: constants.ERROR_CODES.FH_FORMS_ERR_CODE_PDF_GENERATION, httpCode: 500 })); } //No Errors, all files are now cached for the submission submission.formSubmittedAgainst = populateSubmissionFileData({ form: form, submissionFiles: cachedFiles, downloadUrl: params.options.downloadUrl, fileUriPath: params.options.fileUriPath, submission: submission }); logger.debug("cacheFiles: mergeSubmissionFiles submission", submission); cb(undefined, submission); }); }
[ "function", "mergeSubmissionFiles", "(", "params", ",", "cb", ")", "{", "logger", ".", "debug", "(", "\"cacheFiles: mergeSubmissionFiles\"", ",", "params", ")", ";", "var", "submission", "=", "params", ".", "submission", ";", "if", "(", "!", "_", ".", "isObject", "(", "submission", ")", ")", "{", "return", "cb", "(", "buildErrorResponse", "(", "{", "err", ":", "new", "Error", "(", "\"Expected Submission Object To Cache Files For\"", ")", ",", "msg", ":", "\"Error Exporting Submission As PDF\"", ",", "httpCode", ":", "500", "}", ")", ")", ";", "}", "var", "form", "=", "submission", ".", "formSubmittedAgainst", ";", "var", "fileFieldDetails", "=", "_", ".", "filter", "(", "submission", ".", "formFields", ",", "function", "(", "field", ")", "{", "return", "isFileFieldType", "(", "field", ".", "fieldId", ".", "type", ")", ";", "}", ")", ";", "fileFieldDetails", "=", "_", ".", "flatten", "(", "fileFieldDetails", ")", ";", "var", "fieldTypes", "=", "_", ".", "groupBy", "(", "fileFieldDetails", ",", "function", "(", "field", ")", "{", "return", "field", ".", "fieldId", ".", "type", ";", "}", ")", ";", "var", "mbaasTypes", "=", "_", ".", "union", "(", "fieldTypes", ".", "photo", ",", "fieldTypes", ".", "signature", ")", ";", "var", "filesToDownload", "=", "_", ".", "map", "(", "mbaasTypes", ",", "function", "(", "field", ")", "{", "return", "_", ".", "map", "(", "field", ".", "fieldValues", ",", "function", "(", "fieldValue", ")", "{", "return", "fieldValue", ".", "groupId", ";", "}", ")", ";", "}", ")", ";", "filesToDownload", "=", "_", ".", "flatten", "(", "filesToDownload", ")", ";", "logger", ".", "debug", "(", "\"cacheFiles: mergeSubmissionFiles filesToDownload\"", ",", "filesToDownload", ")", ";", "async", ".", "mapSeries", "(", "filesToDownload", ",", "function", "(", "fileIdOrUrl", ",", "cb", ")", "{", "cb", "=", "_", ".", "once", "(", "cb", ")", ";", "var", "fileUri", "=", "path", ".", "join", "(", "params", ".", "options", ".", "pdfExportDir", ",", "'image_binary_'", "+", "fileIdOrUrl", ")", ";", "var", "localFile", "=", "fs", ".", "createWriteStream", "(", "fileUri", ")", ";", "cacheSubmissionFile", "(", "{", "fileId", ":", "fileIdOrUrl", ",", "connections", ":", "params", ".", "connections", ",", "options", ":", "params", ".", "options", ",", "submission", ":", "submission", "}", ",", "localFile", ",", "function", "(", "err", ",", "fileDetails", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "\"cacheFiles: cacheSubmissionFile\"", ",", "{", "error", ":", "err", "}", ")", ";", "}", "fileDetails", "=", "fileDetails", "||", "{", "}", ";", "fileDetails", ".", "url", "=", "\"file://\"", "+", "fileUri", ";", "fileDetails", ".", "fileId", "=", "fileIdOrUrl", ";", "logger", ".", "debug", "(", "\"cacheFiles: mergeSubmissionFiles fileDetails\"", ",", "fileDetails", ")", ";", "return", "cb", "(", "err", ",", "_", ".", "omit", "(", "fileDetails", ",", "\"stream\"", ")", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ",", "cachedFiles", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "buildErrorResponse", "(", "{", "error", ":", "err", ",", "msg", ":", "\"Error Cacheing Files For Submission Export\"", ",", "code", ":", "constants", ".", "ERROR_CODES", ".", "FH_FORMS_ERR_CODE_PDF_GENERATION", ",", "httpCode", ":", "500", "}", ")", ")", ";", "}", "submission", ".", "formSubmittedAgainst", "=", "populateSubmissionFileData", "(", "{", "form", ":", "form", ",", "submissionFiles", ":", "cachedFiles", ",", "downloadUrl", ":", "params", ".", "options", ".", "downloadUrl", ",", "fileUriPath", ":", "params", ".", "options", ".", "fileUriPath", ",", "submission", ":", "submission", "}", ")", ";", "logger", ".", "debug", "(", "\"cacheFiles: mergeSubmissionFiles submission\"", ",", "submission", ")", ";", "cb", "(", "undefined", ",", "submission", ")", ";", "}", ")", ";", "}" ]
Caching any files needed for a submission to the file system. @param params - submission - connections - options @param cb @returns {*} @private
[ "Caching", "any", "files", "needed", "for", "a", "submission", "to", "the", "file", "system", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/cacheFiles.js#L152-L243
train
feedhenry/fh-forms
lib/impl/pdfGeneration/cacheFiles.js
removeCachedFiles
function removeCachedFiles(params, cb) { //Cleaning Up Any Files Cached To Render The Submission. logger.debug("cacheFiles: mergeSubmissionFiles Removing Cached Files For PDF Generation: ", params.submissionFiles); async.eachSeries(params.submissionFiles || [], function(submissionFileDetails, cb) { logger.debug("Removing Cached File: ", submissionFileDetails); fs.unlink(submissionFileDetails.url, function(err) { if (err) { logger.error('Error Removing File At' + submissionFileDetails.url); } return cb(); }); }, cb); }
javascript
function removeCachedFiles(params, cb) { //Cleaning Up Any Files Cached To Render The Submission. logger.debug("cacheFiles: mergeSubmissionFiles Removing Cached Files For PDF Generation: ", params.submissionFiles); async.eachSeries(params.submissionFiles || [], function(submissionFileDetails, cb) { logger.debug("Removing Cached File: ", submissionFileDetails); fs.unlink(submissionFileDetails.url, function(err) { if (err) { logger.error('Error Removing File At' + submissionFileDetails.url); } return cb(); }); }, cb); }
[ "function", "removeCachedFiles", "(", "params", ",", "cb", ")", "{", "logger", ".", "debug", "(", "\"cacheFiles: mergeSubmissionFiles Removing Cached Files For PDF Generation: \"", ",", "params", ".", "submissionFiles", ")", ";", "async", ".", "eachSeries", "(", "params", ".", "submissionFiles", "||", "[", "]", ",", "function", "(", "submissionFileDetails", ",", "cb", ")", "{", "logger", ".", "debug", "(", "\"Removing Cached File: \"", ",", "submissionFileDetails", ")", ";", "fs", ".", "unlink", "(", "submissionFileDetails", ".", "url", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "'Error Removing File At'", "+", "submissionFileDetails", ".", "url", ")", ";", "}", "return", "cb", "(", ")", ";", "}", ")", ";", "}", ",", "cb", ")", ";", "}" ]
Removing Any Cached Files Needed For Rendering The PDF @param params @param cb @private
[ "Removing", "Any", "Cached", "Files", "Needed", "For", "Rendering", "The", "PDF" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/cacheFiles.js#L251-L264
train
cloudfour/drizzle-builder
src/write/pages.js
walkPages
function walkPages(pages, drizzleData, writePromises = []) { if (isPage(pages)) { return writePage( pages.id, pages, drizzleData.options.dest.pages, drizzleData.options.keys.pages.plural ); } for (var pageKey in pages) { writePromises = writePromises.concat( walkPages(pages[pageKey], drizzleData, writePromises) ); } return writePromises; }
javascript
function walkPages(pages, drizzleData, writePromises = []) { if (isPage(pages)) { return writePage( pages.id, pages, drizzleData.options.dest.pages, drizzleData.options.keys.pages.plural ); } for (var pageKey in pages) { writePromises = writePromises.concat( walkPages(pages[pageKey], drizzleData, writePromises) ); } return writePromises; }
[ "function", "walkPages", "(", "pages", ",", "drizzleData", ",", "writePromises", "=", "[", "]", ")", "{", "if", "(", "isPage", "(", "pages", ")", ")", "{", "return", "writePage", "(", "pages", ".", "id", ",", "pages", ",", "drizzleData", ".", "options", ".", "dest", ".", "pages", ",", "drizzleData", ".", "options", ".", "keys", ".", "pages", ".", "plural", ")", ";", "}", "for", "(", "var", "pageKey", "in", "pages", ")", "{", "writePromises", "=", "writePromises", ".", "concat", "(", "walkPages", "(", "pages", "[", "pageKey", "]", ",", "drizzleData", ",", "writePromises", ")", ")", ";", "}", "return", "writePromises", ";", "}" ]
Traverse pages object and write out any page objects to files. An object is considered a page if it has a `contents` property. @param {Object} pages current level of pages tree @param {Object} drizzleData @param {Array} writePromises All write promises so far @return {Array} of Promises
[ "Traverse", "pages", "object", "and", "write", "out", "any", "page", "objects", "to", "files", ".", "An", "object", "is", "considered", "a", "page", "if", "it", "has", "a", "contents", "property", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/write/pages.js#L15-L30
train
cloudfour/drizzle-builder
src/write/pages.js
writePages
function writePages(drizzleData) { return Promise.all(walkPages(drizzleData.pages, drizzleData)).then( () => drizzleData, error => DrizzleError.error(error, drizzleData.options.debug) ); }
javascript
function writePages(drizzleData) { return Promise.all(walkPages(drizzleData.pages, drizzleData)).then( () => drizzleData, error => DrizzleError.error(error, drizzleData.options.debug) ); }
[ "function", "writePages", "(", "drizzleData", ")", "{", "return", "Promise", ".", "all", "(", "walkPages", "(", "drizzleData", ".", "pages", ",", "drizzleData", ")", ")", ".", "then", "(", "(", ")", "=>", "drizzleData", ",", "error", "=>", "DrizzleError", ".", "error", "(", "error", ",", "drizzleData", ".", "options", ".", "debug", ")", ")", ";", "}" ]
Write out HTML pages for pages data. @param {Object} drizzleData @return {Promise} resolving to drizzleData
[ "Write", "out", "HTML", "pages", "for", "pages", "data", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/write/pages.js#L38-L43
train
feedhenry/fh-forms
lib/impl/deleteAppRefrences.js
deleteAppForms
function deleteAppForms(cb) { var appId = params.appId; async.series([ function(cb) { // first remove the form itself var appFormsModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_FORMS); appFormsModel.find({appId: appId}).remove().exec(cb); }, function(cb) { // remove deleted from from any groups groups.removeAppFromAllGroups(connections, appId, cb); }, function deleteThemeRefrences(cb) { var appThemeModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_THEMES); appThemeModel.find({"appId":appId}).remove().exec(cb); }, function deleteAppConfigReferences(cb) { var appConfigModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_CONFIG); appConfigModel.find({"appId":appId}).remove().exec(cb); } ], function(err) { if (err) { return cb(err); } return cb(null); }); }
javascript
function deleteAppForms(cb) { var appId = params.appId; async.series([ function(cb) { // first remove the form itself var appFormsModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_FORMS); appFormsModel.find({appId: appId}).remove().exec(cb); }, function(cb) { // remove deleted from from any groups groups.removeAppFromAllGroups(connections, appId, cb); }, function deleteThemeRefrences(cb) { var appThemeModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_THEMES); appThemeModel.find({"appId":appId}).remove().exec(cb); }, function deleteAppConfigReferences(cb) { var appConfigModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_CONFIG); appConfigModel.find({"appId":appId}).remove().exec(cb); } ], function(err) { if (err) { return cb(err); } return cb(null); }); }
[ "function", "deleteAppForms", "(", "cb", ")", "{", "var", "appId", "=", "params", ".", "appId", ";", "async", ".", "series", "(", "[", "function", "(", "cb", ")", "{", "var", "appFormsModel", "=", "models", ".", "get", "(", "connections", ".", "mongooseConnection", ",", "models", ".", "MODELNAMES", ".", "APP_FORMS", ")", ";", "appFormsModel", ".", "find", "(", "{", "appId", ":", "appId", "}", ")", ".", "remove", "(", ")", ".", "exec", "(", "cb", ")", ";", "}", ",", "function", "(", "cb", ")", "{", "groups", ".", "removeAppFromAllGroups", "(", "connections", ",", "appId", ",", "cb", ")", ";", "}", ",", "function", "deleteThemeRefrences", "(", "cb", ")", "{", "var", "appThemeModel", "=", "models", ".", "get", "(", "connections", ".", "mongooseConnection", ",", "models", ".", "MODELNAMES", ".", "APP_THEMES", ")", ";", "appThemeModel", ".", "find", "(", "{", "\"appId\"", ":", "appId", "}", ")", ".", "remove", "(", ")", ".", "exec", "(", "cb", ")", ";", "}", ",", "function", "deleteAppConfigReferences", "(", "cb", ")", "{", "var", "appConfigModel", "=", "models", ".", "get", "(", "connections", ".", "mongooseConnection", ",", "models", ".", "MODELNAMES", ".", "APP_CONFIG", ")", ";", "appConfigModel", ".", "find", "(", "{", "\"appId\"", ":", "appId", "}", ")", ".", "remove", "(", ")", ".", "exec", "(", "cb", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}" ]
updates to AppForms sub collection
[ "updates", "to", "AppForms", "sub", "collection" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/deleteAppRefrences.js#L28-L53
train
feedhenry/fh-forms
lib/impl/pdfGeneration/renderSinglePDF.js
renderPDF
function renderPDF(params, cb) { var template = params.template; var session = params.session; var form = params.form; var submission = params.submission; submission.formName = form.name; var studioLocation = params.location; var generationTimestamp = params.generationTimestamp || Date.now(); var page; session.createPage() .then(function(_page) { logger.debug('page created'); page = _page; // A4 aspect ratio page.property('paperSize', {format: 'A4'}) .then(function() { logger.debug('page aspect ratio set'); //Can't load css files over https. Needs to be http. if (typeof(studioLocation) === "string") { studioLocation = studioLocation.replace("https://", "http://"); } form = processForm(form, submission); var html = template({ form: form.form, location: studioLocation, subexport: form.sub, js: params.js, css: params.css }); // inject html as we don't have a server to serve html to phantom page.setContent(html, null) .then(function(status) { logger.debug('content set. status', status); var file = path.join(params.pdfExportDir, form.sub.formSubmittedAgainst._id + '_' + form.sub._id + '_' + generationTimestamp + '.pdf'); page.render(file) .then(function() { logger.info('Rendered pdf:', {file: file}); page.close(); page = null; destroyPhantomSession(session, function() { return cb(null, file); }); }); }); }); }) .catch(function(e1) { logger.error('Exception rendering pdf', {exception: e1}); try { if (page) { page.close(); } } catch (e2) { // silent logger.warn('Error closing page after phantom exception', {exception: e2}); } return cb('Exception rendering pdf:' + e1.toString()); }); }
javascript
function renderPDF(params, cb) { var template = params.template; var session = params.session; var form = params.form; var submission = params.submission; submission.formName = form.name; var studioLocation = params.location; var generationTimestamp = params.generationTimestamp || Date.now(); var page; session.createPage() .then(function(_page) { logger.debug('page created'); page = _page; // A4 aspect ratio page.property('paperSize', {format: 'A4'}) .then(function() { logger.debug('page aspect ratio set'); //Can't load css files over https. Needs to be http. if (typeof(studioLocation) === "string") { studioLocation = studioLocation.replace("https://", "http://"); } form = processForm(form, submission); var html = template({ form: form.form, location: studioLocation, subexport: form.sub, js: params.js, css: params.css }); // inject html as we don't have a server to serve html to phantom page.setContent(html, null) .then(function(status) { logger.debug('content set. status', status); var file = path.join(params.pdfExportDir, form.sub.formSubmittedAgainst._id + '_' + form.sub._id + '_' + generationTimestamp + '.pdf'); page.render(file) .then(function() { logger.info('Rendered pdf:', {file: file}); page.close(); page = null; destroyPhantomSession(session, function() { return cb(null, file); }); }); }); }); }) .catch(function(e1) { logger.error('Exception rendering pdf', {exception: e1}); try { if (page) { page.close(); } } catch (e2) { // silent logger.warn('Error closing page after phantom exception', {exception: e2}); } return cb('Exception rendering pdf:' + e1.toString()); }); }
[ "function", "renderPDF", "(", "params", ",", "cb", ")", "{", "var", "template", "=", "params", ".", "template", ";", "var", "session", "=", "params", ".", "session", ";", "var", "form", "=", "params", ".", "form", ";", "var", "submission", "=", "params", ".", "submission", ";", "submission", ".", "formName", "=", "form", ".", "name", ";", "var", "studioLocation", "=", "params", ".", "location", ";", "var", "generationTimestamp", "=", "params", ".", "generationTimestamp", "||", "Date", ".", "now", "(", ")", ";", "var", "page", ";", "session", ".", "createPage", "(", ")", ".", "then", "(", "function", "(", "_page", ")", "{", "logger", ".", "debug", "(", "'page created'", ")", ";", "page", "=", "_page", ";", "page", ".", "property", "(", "'paperSize'", ",", "{", "format", ":", "'A4'", "}", ")", ".", "then", "(", "function", "(", ")", "{", "logger", ".", "debug", "(", "'page aspect ratio set'", ")", ";", "if", "(", "typeof", "(", "studioLocation", ")", "===", "\"string\"", ")", "{", "studioLocation", "=", "studioLocation", ".", "replace", "(", "\"https://\"", ",", "\"http://\"", ")", ";", "}", "form", "=", "processForm", "(", "form", ",", "submission", ")", ";", "var", "html", "=", "template", "(", "{", "form", ":", "form", ".", "form", ",", "location", ":", "studioLocation", ",", "subexport", ":", "form", ".", "sub", ",", "js", ":", "params", ".", "js", ",", "css", ":", "params", ".", "css", "}", ")", ";", "page", ".", "setContent", "(", "html", ",", "null", ")", ".", "then", "(", "function", "(", "status", ")", "{", "logger", ".", "debug", "(", "'content set. status'", ",", "status", ")", ";", "var", "file", "=", "path", ".", "join", "(", "params", ".", "pdfExportDir", ",", "form", ".", "sub", ".", "formSubmittedAgainst", ".", "_id", "+", "'_'", "+", "form", ".", "sub", ".", "_id", "+", "'_'", "+", "generationTimestamp", "+", "'.pdf'", ")", ";", "page", ".", "render", "(", "file", ")", ".", "then", "(", "function", "(", ")", "{", "logger", ".", "info", "(", "'Rendered pdf:'", ",", "{", "file", ":", "file", "}", ")", ";", "page", ".", "close", "(", ")", ";", "page", "=", "null", ";", "destroyPhantomSession", "(", "session", ",", "function", "(", ")", "{", "return", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "e1", ")", "{", "logger", ".", "error", "(", "'Exception rendering pdf'", ",", "{", "exception", ":", "e1", "}", ")", ";", "try", "{", "if", "(", "page", ")", "{", "page", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "e2", ")", "{", "logger", ".", "warn", "(", "'Error closing page after phantom exception'", ",", "{", "exception", ":", "e2", "}", ")", ";", "}", "return", "cb", "(", "'Exception rendering pdf:'", "+", "e1", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "}" ]
Rendering The HTML Template To A PDF Document @param params - template - session - form - submission - location - generationTimestamp @param cb @returns {*} @private
[ "Rendering", "The", "HTML", "Template", "To", "A", "PDF", "Document" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/renderSinglePDF.js#L22-L86
train
crispy1989/node-zstreams
lib/duplex.js
ZDuplex
function ZDuplex(options) { if(options) { if(options.objectMode) { options.readableObjectMode = true; options.writableObjectMode = true; } if(options.readableObjectMode && options.writableObjectMode) { options.objectMode = true; } //Add support for iojs simplified stream constructor if(typeof options.read === 'function') { this._read = options.read; } if(typeof options.write === 'function') { this._write = options.write; } if(typeof options.flush === 'function') { this._flush = options.flush; } } Duplex.call(this, options); // Register listeners for finish (v0.10) and prefinish (v0.12) to run _duplexPrefinish this._duplexFinished = false; this.once('finish', this._duplexPrefinish.bind(this)); this.once('prefinish', this._duplexPrefinish.bind(this)); // 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, Duplex.prototype, options); readableMixins.call(this, options); writableMixins.call(this, options); }
javascript
function ZDuplex(options) { if(options) { if(options.objectMode) { options.readableObjectMode = true; options.writableObjectMode = true; } if(options.readableObjectMode && options.writableObjectMode) { options.objectMode = true; } //Add support for iojs simplified stream constructor if(typeof options.read === 'function') { this._read = options.read; } if(typeof options.write === 'function') { this._write = options.write; } if(typeof options.flush === 'function') { this._flush = options.flush; } } Duplex.call(this, options); // Register listeners for finish (v0.10) and prefinish (v0.12) to run _duplexPrefinish this._duplexFinished = false; this.once('finish', this._duplexPrefinish.bind(this)); this.once('prefinish', this._duplexPrefinish.bind(this)); // 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, Duplex.prototype, options); readableMixins.call(this, options); writableMixins.call(this, options); }
[ "function", "ZDuplex", "(", "options", ")", "{", "if", "(", "options", ")", "{", "if", "(", "options", ".", "objectMode", ")", "{", "options", ".", "readableObjectMode", "=", "true", ";", "options", ".", "writableObjectMode", "=", "true", ";", "}", "if", "(", "options", ".", "readableObjectMode", "&&", "options", ".", "writableObjectMode", ")", "{", "options", ".", "objectMode", "=", "true", ";", "}", "if", "(", "typeof", "options", ".", "read", "===", "'function'", ")", "{", "this", ".", "_read", "=", "options", ".", "read", ";", "}", "if", "(", "typeof", "options", ".", "write", "===", "'function'", ")", "{", "this", ".", "_write", "=", "options", ".", "write", ";", "}", "if", "(", "typeof", "options", ".", "flush", "===", "'function'", ")", "{", "this", ".", "_flush", "=", "options", ".", "flush", ";", "}", "}", "Duplex", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_duplexFinished", "=", "false", ";", "this", ".", "once", "(", "'finish'", ",", "this", ".", "_duplexPrefinish", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "once", "(", "'prefinish'", ",", "this", ".", "_duplexPrefinish", ".", "bind", "(", "this", ")", ")", ";", "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", ",", "Duplex", ".", "prototype", ",", "options", ")", ";", "readableMixins", ".", "call", "(", "this", ",", "options", ")", ";", "writableMixins", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
ZDuplex implements the Duplex stream interface. ZDuplex also allows for a `_flush` function to facilitate cleanup. @class ZDuplex @constructor @extends Duplex @uses _Stream @uses _Readable @uses _Writable @param {Object} [options] - Stream options
[ "ZDuplex", "implements", "the", "Duplex", "stream", "interface", ".", "ZDuplex", "also", "allows", "for", "a", "_flush", "function", "to", "facilitate", "cleanup", "." ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/duplex.js#L20-L61
train
cloudfour/drizzle-builder
src/init.js
normalizePaths
function normalizePaths(opts) { for (var srcKey in opts.src) { if (!path.isAbsolute(opts.src[srcKey].glob)) { opts.src[srcKey].glob = path.resolve(opts.src[srcKey].glob); } if (!path.isAbsolute(opts.src[srcKey].basedir)) { opts.src[srcKey].basedir = path.resolve(opts.src[srcKey].basedir); } } }
javascript
function normalizePaths(opts) { for (var srcKey in opts.src) { if (!path.isAbsolute(opts.src[srcKey].glob)) { opts.src[srcKey].glob = path.resolve(opts.src[srcKey].glob); } if (!path.isAbsolute(opts.src[srcKey].basedir)) { opts.src[srcKey].basedir = path.resolve(opts.src[srcKey].basedir); } } }
[ "function", "normalizePaths", "(", "opts", ")", "{", "for", "(", "var", "srcKey", "in", "opts", ".", "src", ")", "{", "if", "(", "!", "path", ".", "isAbsolute", "(", "opts", ".", "src", "[", "srcKey", "]", ".", "glob", ")", ")", "{", "opts", ".", "src", "[", "srcKey", "]", ".", "glob", "=", "path", ".", "resolve", "(", "opts", ".", "src", "[", "srcKey", "]", ".", "glob", ")", ";", "}", "if", "(", "!", "path", ".", "isAbsolute", "(", "opts", ".", "src", "[", "srcKey", "]", ".", "basedir", ")", ")", "{", "opts", ".", "src", "[", "srcKey", "]", ".", "basedir", "=", "path", ".", "resolve", "(", "opts", ".", "src", "[", "srcKey", "]", ".", "basedir", ")", ";", "}", "}", "}" ]
For relative pathing to work, let's convert all paths in src options to absolute paths, if they are not already. @param {Object} opts Mutated in place.
[ "For", "relative", "pathing", "to", "work", "let", "s", "convert", "all", "paths", "in", "src", "options", "to", "absolute", "paths", "if", "they", "are", "not", "already", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/init.js#L12-L21
train
cloudfour/drizzle-builder
src/init.js
init
function init(options = {}, handlebars) { const opts = deepExtend({}, defaults, options); normalizePaths(opts); opts.handlebars = handlebars || Handlebars.create(); return Promise.resolve(opts); }
javascript
function init(options = {}, handlebars) { const opts = deepExtend({}, defaults, options); normalizePaths(opts); opts.handlebars = handlebars || Handlebars.create(); return Promise.resolve(opts); }
[ "function", "init", "(", "options", "=", "{", "}", ",", "handlebars", ")", "{", "const", "opts", "=", "deepExtend", "(", "{", "}", ",", "defaults", ",", "options", ")", ";", "normalizePaths", "(", "opts", ")", ";", "opts", ".", "handlebars", "=", "handlebars", "||", "Handlebars", ".", "create", "(", ")", ";", "return", "Promise", ".", "resolve", "(", "opts", ")", ";", "}" ]
Merge defaults into passed options. @param {Object} options @param {Object} handlebars Handlebars instance—it can be passed explicitly, primarily for testing purposes. @return {Promise} resolving to merged options
[ "Merge", "defaults", "into", "passed", "options", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/init.js#L31-L36
train
feedhenry/fh-forms
lib/impl/notification.js
buildSubmissionReceivedMessage
function buildSubmissionReceivedMessage(subscribers, formName, formSubmission) { var msg = {}; msg.subscribers = subscribers; msg.formId = formSubmission.formId; msg.appId = formSubmission.appId; msg.attachmentUrl = getAttachmentUrl(formSubmission); msg.formName = formName || "UNKNOWN FORM NAME"; msg.submissionStatus = formSubmission.status; msg.appEnvironment = formSubmission.appEnvironment; msg.submissionStarted = formSubmission.submissionStartedTimestamp; msg.submissionCompleted = formSubmission.submissionCompletedTimestamp; msg.submissionId = formSubmission._id; msg.deviceIPAddress = formSubmission.deviceIPAddress; msg.deviceId = formSubmission.deviceId; msg.submittedFields = []; var form = formSubmission.formSubmittedAgainst; // build helper structures var fieldPageMap = {}; var fieldSectionMap = {}; var sectionsInPage = {}; form.pages.forEach(function(page) { var currentSectionId = 'initial'; sectionsInPage[page._id] = [currentSectionId]; page.fields.forEach(function(field) { fieldPageMap[field._id] = page._id; if (field.type === 'sectionBreak') { currentSectionId = field._id; sectionsInPage[page._id].push(currentSectionId); } else { fieldSectionMap[field._id] = currentSectionId; } }); }); // get structured form fields var pages = getStructuredFields(formSubmission, fieldPageMap, fieldSectionMap); // construct message form.pages.forEach(function(page) { //is this page in submission? if (pages[page._id]) { var sections = sectionsInPage[page._id]; sections.forEach(function(section) { var repSections = pages[page._id][section]; if (repSections) { if (repSections.length === 1) { repSections[0].forEach(function(formField) { msg.submittedFields.push(getFieldMsg(formField, formSubmission)); }); } else { repSections.forEach(function(repSection, index) { msg.submittedFields.push(getField(section, formSubmission).name + ' - ' + (index + 1) + ':'); repSection.forEach(function(formField) { msg.submittedFields.push(getFieldMsg(formField, formSubmission)); }); }); } } }); } }); return msg; }
javascript
function buildSubmissionReceivedMessage(subscribers, formName, formSubmission) { var msg = {}; msg.subscribers = subscribers; msg.formId = formSubmission.formId; msg.appId = formSubmission.appId; msg.attachmentUrl = getAttachmentUrl(formSubmission); msg.formName = formName || "UNKNOWN FORM NAME"; msg.submissionStatus = formSubmission.status; msg.appEnvironment = formSubmission.appEnvironment; msg.submissionStarted = formSubmission.submissionStartedTimestamp; msg.submissionCompleted = formSubmission.submissionCompletedTimestamp; msg.submissionId = formSubmission._id; msg.deviceIPAddress = formSubmission.deviceIPAddress; msg.deviceId = formSubmission.deviceId; msg.submittedFields = []; var form = formSubmission.formSubmittedAgainst; // build helper structures var fieldPageMap = {}; var fieldSectionMap = {}; var sectionsInPage = {}; form.pages.forEach(function(page) { var currentSectionId = 'initial'; sectionsInPage[page._id] = [currentSectionId]; page.fields.forEach(function(field) { fieldPageMap[field._id] = page._id; if (field.type === 'sectionBreak') { currentSectionId = field._id; sectionsInPage[page._id].push(currentSectionId); } else { fieldSectionMap[field._id] = currentSectionId; } }); }); // get structured form fields var pages = getStructuredFields(formSubmission, fieldPageMap, fieldSectionMap); // construct message form.pages.forEach(function(page) { //is this page in submission? if (pages[page._id]) { var sections = sectionsInPage[page._id]; sections.forEach(function(section) { var repSections = pages[page._id][section]; if (repSections) { if (repSections.length === 1) { repSections[0].forEach(function(formField) { msg.submittedFields.push(getFieldMsg(formField, formSubmission)); }); } else { repSections.forEach(function(repSection, index) { msg.submittedFields.push(getField(section, formSubmission).name + ' - ' + (index + 1) + ':'); repSection.forEach(function(formField) { msg.submittedFields.push(getFieldMsg(formField, formSubmission)); }); }); } } }); } }); return msg; }
[ "function", "buildSubmissionReceivedMessage", "(", "subscribers", ",", "formName", ",", "formSubmission", ")", "{", "var", "msg", "=", "{", "}", ";", "msg", ".", "subscribers", "=", "subscribers", ";", "msg", ".", "formId", "=", "formSubmission", ".", "formId", ";", "msg", ".", "appId", "=", "formSubmission", ".", "appId", ";", "msg", ".", "attachmentUrl", "=", "getAttachmentUrl", "(", "formSubmission", ")", ";", "msg", ".", "formName", "=", "formName", "||", "\"UNKNOWN FORM NAME\"", ";", "msg", ".", "submissionStatus", "=", "formSubmission", ".", "status", ";", "msg", ".", "appEnvironment", "=", "formSubmission", ".", "appEnvironment", ";", "msg", ".", "submissionStarted", "=", "formSubmission", ".", "submissionStartedTimestamp", ";", "msg", ".", "submissionCompleted", "=", "formSubmission", ".", "submissionCompletedTimestamp", ";", "msg", ".", "submissionId", "=", "formSubmission", ".", "_id", ";", "msg", ".", "deviceIPAddress", "=", "formSubmission", ".", "deviceIPAddress", ";", "msg", ".", "deviceId", "=", "formSubmission", ".", "deviceId", ";", "msg", ".", "submittedFields", "=", "[", "]", ";", "var", "form", "=", "formSubmission", ".", "formSubmittedAgainst", ";", "var", "fieldPageMap", "=", "{", "}", ";", "var", "fieldSectionMap", "=", "{", "}", ";", "var", "sectionsInPage", "=", "{", "}", ";", "form", ".", "pages", ".", "forEach", "(", "function", "(", "page", ")", "{", "var", "currentSectionId", "=", "'initial'", ";", "sectionsInPage", "[", "page", ".", "_id", "]", "=", "[", "currentSectionId", "]", ";", "page", ".", "fields", ".", "forEach", "(", "function", "(", "field", ")", "{", "fieldPageMap", "[", "field", ".", "_id", "]", "=", "page", ".", "_id", ";", "if", "(", "field", ".", "type", "===", "'sectionBreak'", ")", "{", "currentSectionId", "=", "field", ".", "_id", ";", "sectionsInPage", "[", "page", ".", "_id", "]", ".", "push", "(", "currentSectionId", ")", ";", "}", "else", "{", "fieldSectionMap", "[", "field", ".", "_id", "]", "=", "currentSectionId", ";", "}", "}", ")", ";", "}", ")", ";", "var", "pages", "=", "getStructuredFields", "(", "formSubmission", ",", "fieldPageMap", ",", "fieldSectionMap", ")", ";", "form", ".", "pages", ".", "forEach", "(", "function", "(", "page", ")", "{", "if", "(", "pages", "[", "page", ".", "_id", "]", ")", "{", "var", "sections", "=", "sectionsInPage", "[", "page", ".", "_id", "]", ";", "sections", ".", "forEach", "(", "function", "(", "section", ")", "{", "var", "repSections", "=", "pages", "[", "page", ".", "_id", "]", "[", "section", "]", ";", "if", "(", "repSections", ")", "{", "if", "(", "repSections", ".", "length", "===", "1", ")", "{", "repSections", "[", "0", "]", ".", "forEach", "(", "function", "(", "formField", ")", "{", "msg", ".", "submittedFields", ".", "push", "(", "getFieldMsg", "(", "formField", ",", "formSubmission", ")", ")", ";", "}", ")", ";", "}", "else", "{", "repSections", ".", "forEach", "(", "function", "(", "repSection", ",", "index", ")", "{", "msg", ".", "submittedFields", ".", "push", "(", "getField", "(", "section", ",", "formSubmission", ")", ".", "name", "+", "' - '", "+", "(", "index", "+", "1", ")", "+", "':'", ")", ";", "repSection", ".", "forEach", "(", "function", "(", "formField", ")", "{", "msg", ".", "submittedFields", ".", "push", "(", "getFieldMsg", "(", "formField", ",", "formSubmission", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", "}", ")", ";", "}", "}", ")", ";", "return", "msg", ";", "}" ]
export for tests
[ "export", "for", "tests" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/notification.js#L73-L138
train
back4app/back4app-entity
src/back/models/errors.js
EntityNotFoundError
function EntityNotFoundError(entity, innerError) { /** * The name of the entity that was not found. * @type {?string} */ this.entity = entity; /** * The inner error that generated the current error. * @type {?Error} */ this.innerError = innerError; expect(arguments).to.have.length.below( 3, 'Invalid arguments length when creating a new EntityNotFoundError (it ' + 'has to be passed less than 3 arguments)' ); this.name = 'EntityNotFoundError'; this.message = 'Cannot find Entity'; if (entity) { expect(entity).to.be.a( 'string', 'Invalid argument "entity" when creating a new EntityNotFoundError ' + '(it has to be a string)' ); this.message += ' "' + entity + '"'; } this.stack = (new Error(this.message)).stack; if (innerError) { expect(innerError).to.be.an.instanceof( Error, 'Invalid argument "innerError" when creating a new EntityNotFoundError ' + '(it has to be an Error)' ); this.stack += '\n\n' + innerError.stack; } }
javascript
function EntityNotFoundError(entity, innerError) { /** * The name of the entity that was not found. * @type {?string} */ this.entity = entity; /** * The inner error that generated the current error. * @type {?Error} */ this.innerError = innerError; expect(arguments).to.have.length.below( 3, 'Invalid arguments length when creating a new EntityNotFoundError (it ' + 'has to be passed less than 3 arguments)' ); this.name = 'EntityNotFoundError'; this.message = 'Cannot find Entity'; if (entity) { expect(entity).to.be.a( 'string', 'Invalid argument "entity" when creating a new EntityNotFoundError ' + '(it has to be a string)' ); this.message += ' "' + entity + '"'; } this.stack = (new Error(this.message)).stack; if (innerError) { expect(innerError).to.be.an.instanceof( Error, 'Invalid argument "innerError" when creating a new EntityNotFoundError ' + '(it has to be an Error)' ); this.stack += '\n\n' + innerError.stack; } }
[ "function", "EntityNotFoundError", "(", "entity", ",", "innerError", ")", "{", "this", ".", "entity", "=", "entity", ";", "this", ".", "innerError", "=", "innerError", ";", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "3", ",", "'Invalid arguments length when creating a new EntityNotFoundError (it '", "+", "'has to be passed less than 3 arguments)'", ")", ";", "this", ".", "name", "=", "'EntityNotFoundError'", ";", "this", ".", "message", "=", "'Cannot find Entity'", ";", "if", "(", "entity", ")", "{", "expect", "(", "entity", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"entity\" when creating a new EntityNotFoundError '", "+", "'(it has to be a string)'", ")", ";", "this", ".", "message", "+=", "' \"'", "+", "entity", "+", "'\"'", ";", "}", "this", ".", "stack", "=", "(", "new", "Error", "(", "this", ".", "message", ")", ")", ".", "stack", ";", "if", "(", "innerError", ")", "{", "expect", "(", "innerError", ")", ".", "to", ".", "be", ".", "an", ".", "instanceof", "(", "Error", ",", "'Invalid argument \"innerError\" when creating a new EntityNotFoundError '", "+", "'(it has to be an Error)'", ")", ";", "this", ".", "stack", "+=", "'\\n\\n'", "+", "\\n", ";", "}", "}" ]
Error class to be used when an Entity was referenced and the platform was not able to find it. @constructor @extends Error @param {?string} [entity] The entity name to be displayed. @param {?Error} [innerError] The inner error. @memberof module:back4app-entity/models/errors @example try { var myEntity = require('./MyEntity'); } catch (e) { throw new EntityNotFoundError('MyEntity', e); }
[ "Error", "class", "to", "be", "used", "when", "an", "Entity", "was", "referenced", "and", "the", "platform", "was", "not", "able", "to", "find", "it", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/errors.js#L39-L78
train
back4app/back4app-entity
src/back/models/errors.js
AttributeTypeNotFoundError
function AttributeTypeNotFoundError(type, innerError) { /** * The attribute type that was not found. * @type {?string} */ this.type = type; /** * The inner error that generated the current error. * @type {?Error} */ this.innerError = innerError; expect(arguments).to.have.length.below( 3, 'Invalid arguments length when creating a new ' + 'AttributeTypeNotFoundError (it has to be passed less than 3 arguments)' ); this.name = 'AttributeTypeNotFoundError'; this.message = 'Cannot find Attribute type'; if (type) { expect(type).to.be.a( 'string', 'Invalid argument "type" when creating a new ' + 'AttributeTypeNotFoundError (it has to be a string)' ); this.message += ' "' + type + '"'; } this.stack = (new Error(this.message)).stack; if (innerError) { expect(innerError).to.be.an.instanceof( Error, 'Invalid argument "innerError" when creating a new ' + 'AttributeTypeNotFoundError (it has to be an Error)' ); this.stack += '\n\n' + innerError.stack; } }
javascript
function AttributeTypeNotFoundError(type, innerError) { /** * The attribute type that was not found. * @type {?string} */ this.type = type; /** * The inner error that generated the current error. * @type {?Error} */ this.innerError = innerError; expect(arguments).to.have.length.below( 3, 'Invalid arguments length when creating a new ' + 'AttributeTypeNotFoundError (it has to be passed less than 3 arguments)' ); this.name = 'AttributeTypeNotFoundError'; this.message = 'Cannot find Attribute type'; if (type) { expect(type).to.be.a( 'string', 'Invalid argument "type" when creating a new ' + 'AttributeTypeNotFoundError (it has to be a string)' ); this.message += ' "' + type + '"'; } this.stack = (new Error(this.message)).stack; if (innerError) { expect(innerError).to.be.an.instanceof( Error, 'Invalid argument "innerError" when creating a new ' + 'AttributeTypeNotFoundError (it has to be an Error)' ); this.stack += '\n\n' + innerError.stack; } }
[ "function", "AttributeTypeNotFoundError", "(", "type", ",", "innerError", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "innerError", "=", "innerError", ";", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "3", ",", "'Invalid arguments length when creating a new '", "+", "'AttributeTypeNotFoundError (it has to be passed less than 3 arguments)'", ")", ";", "this", ".", "name", "=", "'AttributeTypeNotFoundError'", ";", "this", ".", "message", "=", "'Cannot find Attribute type'", ";", "if", "(", "type", ")", "{", "expect", "(", "type", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"type\" when creating a new '", "+", "'AttributeTypeNotFoundError (it has to be a string)'", ")", ";", "this", ".", "message", "+=", "' \"'", "+", "type", "+", "'\"'", ";", "}", "this", ".", "stack", "=", "(", "new", "Error", "(", "this", ".", "message", ")", ")", ".", "stack", ";", "if", "(", "innerError", ")", "{", "expect", "(", "innerError", ")", ".", "to", ".", "be", ".", "an", ".", "instanceof", "(", "Error", ",", "'Invalid argument \"innerError\" when creating a new '", "+", "'AttributeTypeNotFoundError (it has to be an Error)'", ")", ";", "this", ".", "stack", "+=", "'\\n\\n'", "+", "\\n", ";", "}", "}" ]
Error class to be used when an Attribute type was referenced and the platform was not able to find it. @constructor @extends Error @param {?string} [type] The attribute type name to be displayed. @param {?Error} [innerError] The inner error. @memberof module:back4app-entity/models/errors @example try { var TypedAttribute = types.get('MyCustomAttribute'); } catch (e) { throw new AttributeTypeNotFoundError('MyCustomAttribute', e); }
[ "Error", "class", "to", "be", "used", "when", "an", "Attribute", "type", "was", "referenced", "and", "the", "platform", "was", "not", "able", "to", "find", "it", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/errors.js#L98-L137
train
back4app/back4app-entity
src/back/models/errors.js
ValidationError
function ValidationError( validationMessage, entity, attribute, position, innerError ) { /** * The validation message to be included in the error. * @type {?string} */ this.validationMessage = validationMessage; /** * The name of the entity that was not validated. * @type {?string} */ this.entity = entity; /** * The name of the attribute that was not validated. * @type {?string} */ this.attribute = attribute; /** * The position of the item in the attribute that was not validated. * @type {?(string|number)} */ this.position = position; /** * The inner error that generated the current error. * @type {?Error} */ this.innerError = innerError; expect(arguments).to.have.length.below( 6, 'Invalid arguments length when creating a new ' + 'AttributeTypeNotFoundError (it has to be passed less than 6 arguments)' ); this.name = 'ValidationError'; this.message = 'Error when validating an attribute'; if (attribute) { expect(attribute).to.be.a( 'string', 'Invalid argument "attribute" when creating a new ValidationError (it ' + 'has to be a string)' ); this.message += ' called "' + attribute + '"'; } this.message += ' of an entity'; if (entity) { expect(entity).to.be.a( 'string', 'Invalid argument "entity" when creating a new ValidationError (it has ' + 'to be a string)' ); this.message += ' called "' + entity + '"'; } if (position) { expect(['string', 'number']).to.include( typeof position, 'Invalid argument "position" when creating a new ValidationError (it ' + 'has to be a string or a number)' ); this.message += ' in position ' + position; } if (validationMessage) { expect(validationMessage).to.be.a( 'string', 'Invalid argument "validationMessage" when creating a new ' + 'ValidationError (it has to be a string)' ); this.message += ': ' + validationMessage; } this.stack = (new Error(this.message)).stack; if (innerError) { expect(innerError).to.be.an.instanceof( Error, 'Invalid argument "innerError" when creating a new ' + 'ValidationError (it has to be an Error)' ); this.stack += '\n\n' + innerError.stack; } }
javascript
function ValidationError( validationMessage, entity, attribute, position, innerError ) { /** * The validation message to be included in the error. * @type {?string} */ this.validationMessage = validationMessage; /** * The name of the entity that was not validated. * @type {?string} */ this.entity = entity; /** * The name of the attribute that was not validated. * @type {?string} */ this.attribute = attribute; /** * The position of the item in the attribute that was not validated. * @type {?(string|number)} */ this.position = position; /** * The inner error that generated the current error. * @type {?Error} */ this.innerError = innerError; expect(arguments).to.have.length.below( 6, 'Invalid arguments length when creating a new ' + 'AttributeTypeNotFoundError (it has to be passed less than 6 arguments)' ); this.name = 'ValidationError'; this.message = 'Error when validating an attribute'; if (attribute) { expect(attribute).to.be.a( 'string', 'Invalid argument "attribute" when creating a new ValidationError (it ' + 'has to be a string)' ); this.message += ' called "' + attribute + '"'; } this.message += ' of an entity'; if (entity) { expect(entity).to.be.a( 'string', 'Invalid argument "entity" when creating a new ValidationError (it has ' + 'to be a string)' ); this.message += ' called "' + entity + '"'; } if (position) { expect(['string', 'number']).to.include( typeof position, 'Invalid argument "position" when creating a new ValidationError (it ' + 'has to be a string or a number)' ); this.message += ' in position ' + position; } if (validationMessage) { expect(validationMessage).to.be.a( 'string', 'Invalid argument "validationMessage" when creating a new ' + 'ValidationError (it has to be a string)' ); this.message += ': ' + validationMessage; } this.stack = (new Error(this.message)).stack; if (innerError) { expect(innerError).to.be.an.instanceof( Error, 'Invalid argument "innerError" when creating a new ' + 'ValidationError (it has to be an Error)' ); this.stack += '\n\n' + innerError.stack; } }
[ "function", "ValidationError", "(", "validationMessage", ",", "entity", ",", "attribute", ",", "position", ",", "innerError", ")", "{", "this", ".", "validationMessage", "=", "validationMessage", ";", "this", ".", "entity", "=", "entity", ";", "this", ".", "attribute", "=", "attribute", ";", "this", ".", "position", "=", "position", ";", "this", ".", "innerError", "=", "innerError", ";", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "6", ",", "'Invalid arguments length when creating a new '", "+", "'AttributeTypeNotFoundError (it has to be passed less than 6 arguments)'", ")", ";", "this", ".", "name", "=", "'ValidationError'", ";", "this", ".", "message", "=", "'Error when validating an attribute'", ";", "if", "(", "attribute", ")", "{", "expect", "(", "attribute", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"attribute\" when creating a new ValidationError (it '", "+", "'has to be a string)'", ")", ";", "this", ".", "message", "+=", "' called \"'", "+", "attribute", "+", "'\"'", ";", "}", "this", ".", "message", "+=", "' of an entity'", ";", "if", "(", "entity", ")", "{", "expect", "(", "entity", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"entity\" when creating a new ValidationError (it has '", "+", "'to be a string)'", ")", ";", "this", ".", "message", "+=", "' called \"'", "+", "entity", "+", "'\"'", ";", "}", "if", "(", "position", ")", "{", "expect", "(", "[", "'string'", ",", "'number'", "]", ")", ".", "to", ".", "include", "(", "typeof", "position", ",", "'Invalid argument \"position\" when creating a new ValidationError (it '", "+", "'has to be a string or a number)'", ")", ";", "this", ".", "message", "+=", "' in position '", "+", "position", ";", "}", "if", "(", "validationMessage", ")", "{", "expect", "(", "validationMessage", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"validationMessage\" when creating a new '", "+", "'ValidationError (it has to be a string)'", ")", ";", "this", ".", "message", "+=", "': '", "+", "validationMessage", ";", "}", "this", ".", "stack", "=", "(", "new", "Error", "(", "this", ".", "message", ")", ")", ".", "stack", ";", "if", "(", "innerError", ")", "{", "expect", "(", "innerError", ")", ".", "to", ".", "be", ".", "an", ".", "instanceof", "(", "Error", ",", "'Invalid argument \"innerError\" when creating a new '", "+", "'ValidationError (it has to be an Error)'", ")", ";", "this", ".", "stack", "+=", "'\\n\\n'", "+", "\\n", ";", "}", "}" ]
Error class to be used when an attribute value is not valid for the attribute specification. @constructor @extends Error @param {?string} [validationMessage] The message explaining the validation error. @param {?string} [entity] The entity whose attribute is not valid. @param {?string} [attribute] The attribute that is not valid. @param {?(string|number)} [position] The position in the attribute that is not valid. @param {?Error} [innerError] The inner error. @memberof module:back4app-entity/models/errors @example try { throw new ValidationError( 'this attribute is required', 'MyEntity', 'myAttribute', 1, null ); } catch(e) { console.log(e.message); // Logs "Error when validating an attribute called // "myAttribute" of an entity called "MyEntity" in // position 1: this attribute is required" }
[ "Error", "class", "to", "be", "used", "when", "an", "attribute", "value", "is", "not", "valid", "for", "the", "attribute", "specification", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/errors.js#L257-L345
train
back4app/back4app-entity
src/back/models/errors.js
AdapterNotFoundError
function AdapterNotFoundError(adapterName, innerError) { /** * The name of the adapter that was not found. * @type {?string} */ this.adapterName = adapterName; /** * The inner error that generated the current error. * @type {?Error} */ this.innerError = innerError; expect(arguments).to.have.length.below( 3, 'Invalid arguments length when creating a new ' + 'EntityNotFoundError (it has to be passed less than 3 arguments)' ); this.name = 'AdapterNotFoundError'; this.message = 'Cannot find Adapter'; if (adapterName) { expect(adapterName).to.be.a( 'string', 'Invalid argument "adapterName" when creating a new ' + 'AdapterNotFoundError (it has to be a string)' ); this.message += ' "' + adapterName + '"'; } this.stack = (new Error(this.message)).stack; if (innerError) { expect(innerError).to.be.an.instanceof( Error, 'Invalid argument "innerError" when creating a new ' + 'AdapterNotFoundError (it has to be an Error)' ); this.stack += '\n\n' + innerError.stack; } }
javascript
function AdapterNotFoundError(adapterName, innerError) { /** * The name of the adapter that was not found. * @type {?string} */ this.adapterName = adapterName; /** * The inner error that generated the current error. * @type {?Error} */ this.innerError = innerError; expect(arguments).to.have.length.below( 3, 'Invalid arguments length when creating a new ' + 'EntityNotFoundError (it has to be passed less than 3 arguments)' ); this.name = 'AdapterNotFoundError'; this.message = 'Cannot find Adapter'; if (adapterName) { expect(adapterName).to.be.a( 'string', 'Invalid argument "adapterName" when creating a new ' + 'AdapterNotFoundError (it has to be a string)' ); this.message += ' "' + adapterName + '"'; } this.stack = (new Error(this.message)).stack; if (innerError) { expect(innerError).to.be.an.instanceof( Error, 'Invalid argument "innerError" when creating a new ' + 'AdapterNotFoundError (it has to be an Error)' ); this.stack += '\n\n' + innerError.stack; } }
[ "function", "AdapterNotFoundError", "(", "adapterName", ",", "innerError", ")", "{", "this", ".", "adapterName", "=", "adapterName", ";", "this", ".", "innerError", "=", "innerError", ";", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "3", ",", "'Invalid arguments length when creating a new '", "+", "'EntityNotFoundError (it has to be passed less than 3 arguments)'", ")", ";", "this", ".", "name", "=", "'AdapterNotFoundError'", ";", "this", ".", "message", "=", "'Cannot find Adapter'", ";", "if", "(", "adapterName", ")", "{", "expect", "(", "adapterName", ")", ".", "to", ".", "be", ".", "a", "(", "'string'", ",", "'Invalid argument \"adapterName\" when creating a new '", "+", "'AdapterNotFoundError (it has to be a string)'", ")", ";", "this", ".", "message", "+=", "' \"'", "+", "adapterName", "+", "'\"'", ";", "}", "this", ".", "stack", "=", "(", "new", "Error", "(", "this", ".", "message", ")", ")", ".", "stack", ";", "if", "(", "innerError", ")", "{", "expect", "(", "innerError", ")", ".", "to", ".", "be", ".", "an", ".", "instanceof", "(", "Error", ",", "'Invalid argument \"innerError\" when creating a new '", "+", "'AdapterNotFoundError (it has to be an Error)'", ")", ";", "this", ".", "stack", "+=", "'\\n\\n'", "+", "\\n", ";", "}", "}" ]
Error class to be used when an Adapter was referenced and the platform was not able to find it. @constructor @extends Error @param {?string} [adapterName] The adapter name to be displayed. @param {?Error} [innerError] The inner error. @memberof module:back4app-entity/models/errors @example if (settings.ADAPTERS.default) { return settings.ADAPTERS.default; } else { throw new errors.AdapterNotFoundError('default'); }
[ "Error", "class", "to", "be", "used", "when", "an", "Adapter", "was", "referenced", "and", "the", "platform", "was", "not", "able", "to", "find", "it", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/errors.js#L364-L403
train
back4app/back4app-entity
src/back/models/attributes/types/AssociationAttribute.js
AssociationAttribute
function AssociationAttribute() { /** * It is a readonly property with the Entity that is associated with the * current AssociationAttribute. * @name * module:back4app-entity/models/attributes/types.AssociationAttribute#Entity * @type {!Class} * @readonly * @throws {module:back4app-entity/models/errors.EntityNotFoundError} * @example * var associationAttribute = new AssociationAttribute( * 'associationAttribute', * MyEntity * ); * console.log(associationAttribute.Entity == MyEntity) // Logs "true" */ this.Entity = null; var _Entity = null; Object.defineProperty(this, 'Entity', { get: function () { if (typeof _Entity === 'string') { _Entity = models.Entity.getSpecialization(_Entity); } return _Entity; }, set: function () { throw new Error( 'Entity property of an AssociationAttribute instance cannot be changed' ); }, enumerable: true, configurable: false }); var argumentsArray = Array.prototype.slice.call(arguments); expect(argumentsArray).to.have.length.within( 1, 5, 'Invalid arguments length when creating an AssociationAttribute (it has ' + 'to be passed from 1 to 5 arguments)' ); if (argumentsArray.length === 1) { var associationAttribute = argumentsArray[0]; expect(associationAttribute).to.be.an( 'object', 'Invalid argument type when creating an Attribute (it has to be an ' + 'object)' ); associationAttribute = objects.copy(associationAttribute); _Entity = associationAttribute.entity; if (_Entity) { delete associationAttribute.entity; } else { expect(associationAttribute).to.have.ownProperty( 'Entity', 'Property "entity" or "Entity" is required when creating an ' + 'AssociationAttribute' ); _Entity = associationAttribute.Entity; delete associationAttribute.Entity; } argumentsArray[0] = associationAttribute; } else { _Entity = argumentsArray.splice(1, 1)[0]; } if (typeof _Entity !== 'string') { expect(_Entity).to.be.a( 'function', 'Invalid argument "entity" when creating an AssociationAttribute (it ' + 'has to be a Class)' ); expect(classes.isGeneral(models.Entity, _Entity)).to.equal( true, 'Invalid argument "entity" when creating an AssociationAttribute (it ' + 'has to be a subclass of Entity)' ); } Attribute.apply(this, argumentsArray); }
javascript
function AssociationAttribute() { /** * It is a readonly property with the Entity that is associated with the * current AssociationAttribute. * @name * module:back4app-entity/models/attributes/types.AssociationAttribute#Entity * @type {!Class} * @readonly * @throws {module:back4app-entity/models/errors.EntityNotFoundError} * @example * var associationAttribute = new AssociationAttribute( * 'associationAttribute', * MyEntity * ); * console.log(associationAttribute.Entity == MyEntity) // Logs "true" */ this.Entity = null; var _Entity = null; Object.defineProperty(this, 'Entity', { get: function () { if (typeof _Entity === 'string') { _Entity = models.Entity.getSpecialization(_Entity); } return _Entity; }, set: function () { throw new Error( 'Entity property of an AssociationAttribute instance cannot be changed' ); }, enumerable: true, configurable: false }); var argumentsArray = Array.prototype.slice.call(arguments); expect(argumentsArray).to.have.length.within( 1, 5, 'Invalid arguments length when creating an AssociationAttribute (it has ' + 'to be passed from 1 to 5 arguments)' ); if (argumentsArray.length === 1) { var associationAttribute = argumentsArray[0]; expect(associationAttribute).to.be.an( 'object', 'Invalid argument type when creating an Attribute (it has to be an ' + 'object)' ); associationAttribute = objects.copy(associationAttribute); _Entity = associationAttribute.entity; if (_Entity) { delete associationAttribute.entity; } else { expect(associationAttribute).to.have.ownProperty( 'Entity', 'Property "entity" or "Entity" is required when creating an ' + 'AssociationAttribute' ); _Entity = associationAttribute.Entity; delete associationAttribute.Entity; } argumentsArray[0] = associationAttribute; } else { _Entity = argumentsArray.splice(1, 1)[0]; } if (typeof _Entity !== 'string') { expect(_Entity).to.be.a( 'function', 'Invalid argument "entity" when creating an AssociationAttribute (it ' + 'has to be a Class)' ); expect(classes.isGeneral(models.Entity, _Entity)).to.equal( true, 'Invalid argument "entity" when creating an AssociationAttribute (it ' + 'has to be a subclass of Entity)' ); } Attribute.apply(this, argumentsArray); }
[ "function", "AssociationAttribute", "(", ")", "{", "this", ".", "Entity", "=", "null", ";", "var", "_Entity", "=", "null", ";", "Object", ".", "defineProperty", "(", "this", ",", "'Entity'", ",", "{", "get", ":", "function", "(", ")", "{", "if", "(", "typeof", "_Entity", "===", "'string'", ")", "{", "_Entity", "=", "models", ".", "Entity", ".", "getSpecialization", "(", "_Entity", ")", ";", "}", "return", "_Entity", ";", "}", ",", "set", ":", "function", "(", ")", "{", "throw", "new", "Error", "(", "'Entity property of an AssociationAttribute instance cannot be changed'", ")", ";", "}", ",", "enumerable", ":", "true", ",", "configurable", ":", "false", "}", ")", ";", "var", "argumentsArray", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "expect", "(", "argumentsArray", ")", ".", "to", ".", "have", ".", "length", ".", "within", "(", "1", ",", "5", ",", "'Invalid arguments length when creating an AssociationAttribute (it has '", "+", "'to be passed from 1 to 5 arguments)'", ")", ";", "if", "(", "argumentsArray", ".", "length", "===", "1", ")", "{", "var", "associationAttribute", "=", "argumentsArray", "[", "0", "]", ";", "expect", "(", "associationAttribute", ")", ".", "to", ".", "be", ".", "an", "(", "'object'", ",", "'Invalid argument type when creating an Attribute (it has to be an '", "+", "'object)'", ")", ";", "associationAttribute", "=", "objects", ".", "copy", "(", "associationAttribute", ")", ";", "_Entity", "=", "associationAttribute", ".", "entity", ";", "if", "(", "_Entity", ")", "{", "delete", "associationAttribute", ".", "entity", ";", "}", "else", "{", "expect", "(", "associationAttribute", ")", ".", "to", ".", "have", ".", "ownProperty", "(", "'Entity'", ",", "'Property \"entity\" or \"Entity\" is required when creating an '", "+", "'AssociationAttribute'", ")", ";", "_Entity", "=", "associationAttribute", ".", "Entity", ";", "delete", "associationAttribute", ".", "Entity", ";", "}", "argumentsArray", "[", "0", "]", "=", "associationAttribute", ";", "}", "else", "{", "_Entity", "=", "argumentsArray", ".", "splice", "(", "1", ",", "1", ")", "[", "0", "]", ";", "}", "if", "(", "typeof", "_Entity", "!==", "'string'", ")", "{", "expect", "(", "_Entity", ")", ".", "to", ".", "be", ".", "a", "(", "'function'", ",", "'Invalid argument \"entity\" when creating an AssociationAttribute (it '", "+", "'has to be a Class)'", ")", ";", "expect", "(", "classes", ".", "isGeneral", "(", "models", ".", "Entity", ",", "_Entity", ")", ")", ".", "to", ".", "equal", "(", "true", ",", "'Invalid argument \"entity\" when creating an AssociationAttribute (it '", "+", "'has to be a subclass of Entity)'", ")", ";", "}", "Attribute", ".", "apply", "(", "this", ",", "argumentsArray", ")", ";", "}" ]
Implementation of an Entity Attribute to store association data. @memberof module:back4app-entity/models/attributes/types @name AssociationAttribute @constructor @extends module:back4app-entity/models/attributes.Attribute @param {!Object} attribute This is the attribute to be added. It can be passed as an Object. @param {!string} attribute.name It is the name of the attribute. @param {!(string|Class)} attribute.entity It is the Entity that is associated with the current AssociationAttribute. @param {!string} [attribute.multiplicity='1'] It is the multiplicity of the attribute. It is optional and if not passed it will assume '1' as the default value. @param {?Object} [attribute.default] It is the default expression of the attribute. @param {?(string|Object.<!string, !string>)} [attribute.dataName] It is the name to be used to stored the attribute data in the repository. It can be given as a string that will be used by all adapters or as a dictionary specifying the data name for each adapter. If dataName is not given, the attribute's name will be used instead. @example var associationAttribute = new AssociationAttribute({ name: 'associationAttribute', entity: 'MyEntity', multiplicity: '0..1', default: null, dataName: { mongodb: 'mongodbAttribute' } }); Implementation of an Entity Attribute to store association data. @memberof module:back4app-entity/models/attributes/types @name AssociationAttribute @constructor @extends module:back4app-entity/models/attributes.Attribute @param {!string} name It is the name of the attribute. @param {!(string|Class)} entity It is the Entity that is associated with the current AssociationAttribute. @param {!string} [multiplicity='1'] It is the multiplicity of the attribute. It is optional and if not passed it will assume '1' as the default value. @param {?Object} [default] It is the default expression of the attribute. @param {?(string|Object.<!string, !string>)} [dataName] It is the name to be used to stored the attribute data in the repository. It can be given as a string that will be used by all adapters or as a dictionary specifying the data name for each adapter. If dataName is not given, the attribute's name will be used instead. @example var associationAttribute = new AssociationAttribute( 'associationAttribute', 'MyEntity', '0..1', null, { mongodb: 'mongodbAttribute' } );
[ "Implementation", "of", "an", "Entity", "Attribute", "to", "store", "association", "data", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/types/AssociationAttribute.js#L77-L167
train
crispy1989/node-zstreams
lib/streams/intersperse-stream.js
IntersperseStream
function IntersperseStream(seperator, options) { if(typeof seperator === 'object') { options = seperator; seperator = null; } options = !options ? {} : options; Transform.call(this, options); this._intersperseBuffer = null; this._intersperseSeperator = (seperator === null || seperator === undefined) ? '\n' : seperator; }
javascript
function IntersperseStream(seperator, options) { if(typeof seperator === 'object') { options = seperator; seperator = null; } options = !options ? {} : options; Transform.call(this, options); this._intersperseBuffer = null; this._intersperseSeperator = (seperator === null || seperator === undefined) ? '\n' : seperator; }
[ "function", "IntersperseStream", "(", "seperator", ",", "options", ")", "{", "if", "(", "typeof", "seperator", "===", "'object'", ")", "{", "options", "=", "seperator", ";", "seperator", "=", "null", ";", "}", "options", "=", "!", "options", "?", "{", "}", ":", "options", ";", "Transform", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_intersperseBuffer", "=", "null", ";", "this", ".", "_intersperseSeperator", "=", "(", "seperator", "===", "null", "||", "seperator", "===", "undefined", ")", "?", "'\\n'", ":", "\\n", ";", "}" ]
IntersperseStream intersperses a seperator between chunks in the stream @class IntersperseStream @constructor @extends Transform @param {String|Object|Number} [seperator='\n'] - Seperator to push between chunks @param {Object} [options] - Stream options object
[ "IntersperseStream", "intersperses", "a", "seperator", "between", "chunks", "in", "the", "stream" ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/intersperse-stream.js#L13-L24
train
cloudfour/drizzle-builder
src/parse/index.js
parseAll
function parseAll(options) { return Promise.all([ parseData(options), parsePages(options), parsePatterns(options), parseTemplates(options) ]).then( allData => parseTree(allData, options), error => DrizzleError.error(error, options.debug) ); }
javascript
function parseAll(options) { return Promise.all([ parseData(options), parsePages(options), parsePatterns(options), parseTemplates(options) ]).then( allData => parseTree(allData, options), error => DrizzleError.error(error, options.debug) ); }
[ "function", "parseAll", "(", "options", ")", "{", "return", "Promise", ".", "all", "(", "[", "parseData", "(", "options", ")", ",", "parsePages", "(", "options", ")", ",", "parsePatterns", "(", "options", ")", ",", "parseTemplates", "(", "options", ")", "]", ")", ".", "then", "(", "allData", "=>", "parseTree", "(", "allData", ",", "options", ")", ",", "error", "=>", "DrizzleError", ".", "error", "(", "error", ",", "options", ".", "debug", ")", ")", ";", "}" ]
Parse files with data from src and build a drizzleData object @param {Object} options @return {Promise} resolving to Drizzle data object
[ "Parse", "files", "with", "data", "from", "src", "and", "build", "a", "drizzleData", "object" ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/index.js#L17-L27
train
ForstaLabs/librelay-node
src/hub/registration.js
registerAccount
async function registerAccount(options) { options = options || {}; const atlasClient = options.atlasClient || await AtlasClient.factory(); const name = options.name || defaultName; const registrationId = libsignal.keyhelper.generateRegistrationId(); const password = generatePassword(); const signalingKey = generateSignalingKey(); const response = await atlasClient.fetch('/v1/provision/account', { method: 'PUT', json: { signalingKey: signalingKey.toString('base64'), supportsSms: false, fetchesMessages: true, registrationId, name, password } }); const addr = response.userId; const username = `${addr}.${response.deviceId}`; const identity = libsignal.keyhelper.generateIdentityKeyPair(); await storage.clearSessionStore(); await storage.removeOurIdentity(); await storage.removeIdentity(addr); await storage.saveIdentity(addr, identity.pubKey); await storage.saveOurIdentity(identity); await storage.putState('addr', addr); await storage.putState('serverUrl', response.serverUrl); await storage.putState('deviceId', response.deviceId); await storage.putState('name', name); await storage.putState('username', username); await storage.putState('password', password); await storage.putState('registrationId', registrationId); await storage.putState('signalingKey', signalingKey); const sc = new SignalClient(username, password, response.serverUrl); await sc.registerKeys(await sc.generateKeys()); }
javascript
async function registerAccount(options) { options = options || {}; const atlasClient = options.atlasClient || await AtlasClient.factory(); const name = options.name || defaultName; const registrationId = libsignal.keyhelper.generateRegistrationId(); const password = generatePassword(); const signalingKey = generateSignalingKey(); const response = await atlasClient.fetch('/v1/provision/account', { method: 'PUT', json: { signalingKey: signalingKey.toString('base64'), supportsSms: false, fetchesMessages: true, registrationId, name, password } }); const addr = response.userId; const username = `${addr}.${response.deviceId}`; const identity = libsignal.keyhelper.generateIdentityKeyPair(); await storage.clearSessionStore(); await storage.removeOurIdentity(); await storage.removeIdentity(addr); await storage.saveIdentity(addr, identity.pubKey); await storage.saveOurIdentity(identity); await storage.putState('addr', addr); await storage.putState('serverUrl', response.serverUrl); await storage.putState('deviceId', response.deviceId); await storage.putState('name', name); await storage.putState('username', username); await storage.putState('password', password); await storage.putState('registrationId', registrationId); await storage.putState('signalingKey', signalingKey); const sc = new SignalClient(username, password, response.serverUrl); await sc.registerKeys(await sc.generateKeys()); }
[ "async", "function", "registerAccount", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "const", "atlasClient", "=", "options", ".", "atlasClient", "||", "await", "AtlasClient", ".", "factory", "(", ")", ";", "const", "name", "=", "options", ".", "name", "||", "defaultName", ";", "const", "registrationId", "=", "libsignal", ".", "keyhelper", ".", "generateRegistrationId", "(", ")", ";", "const", "password", "=", "generatePassword", "(", ")", ";", "const", "signalingKey", "=", "generateSignalingKey", "(", ")", ";", "const", "response", "=", "await", "atlasClient", ".", "fetch", "(", "'/v1/provision/account'", ",", "{", "method", ":", "'PUT'", ",", "json", ":", "{", "signalingKey", ":", "signalingKey", ".", "toString", "(", "'base64'", ")", ",", "supportsSms", ":", "false", ",", "fetchesMessages", ":", "true", ",", "registrationId", ",", "name", ",", "password", "}", "}", ")", ";", "const", "addr", "=", "response", ".", "userId", ";", "const", "username", "=", "`", "${", "addr", "}", "${", "response", ".", "deviceId", "}", "`", ";", "const", "identity", "=", "libsignal", ".", "keyhelper", ".", "generateIdentityKeyPair", "(", ")", ";", "await", "storage", ".", "clearSessionStore", "(", ")", ";", "await", "storage", ".", "removeOurIdentity", "(", ")", ";", "await", "storage", ".", "removeIdentity", "(", "addr", ")", ";", "await", "storage", ".", "saveIdentity", "(", "addr", ",", "identity", ".", "pubKey", ")", ";", "await", "storage", ".", "saveOurIdentity", "(", "identity", ")", ";", "await", "storage", ".", "putState", "(", "'addr'", ",", "addr", ")", ";", "await", "storage", ".", "putState", "(", "'serverUrl'", ",", "response", ".", "serverUrl", ")", ";", "await", "storage", ".", "putState", "(", "'deviceId'", ",", "response", ".", "deviceId", ")", ";", "await", "storage", ".", "putState", "(", "'name'", ",", "name", ")", ";", "await", "storage", ".", "putState", "(", "'username'", ",", "username", ")", ";", "await", "storage", ".", "putState", "(", "'password'", ",", "password", ")", ";", "await", "storage", ".", "putState", "(", "'registrationId'", ",", "registrationId", ")", ";", "await", "storage", ".", "putState", "(", "'signalingKey'", ",", "signalingKey", ")", ";", "const", "sc", "=", "new", "SignalClient", "(", "username", ",", "password", ",", "response", ".", "serverUrl", ")", ";", "await", "sc", ".", "registerKeys", "(", "await", "sc", ".", "generateKeys", "(", ")", ")", ";", "}" ]
Create a new identity key and create or replace the signal account. Note that any existing devices asssociated with your account will be purged as a result of this action. This should only be used for new accounts or when you need to start over. @param {Object} [options] @param {string} [options.name] - The public name to store in the signal server. @param {AtlasClient} [options.atlasClient]
[ "Create", "a", "new", "identity", "key", "and", "create", "or", "replace", "the", "signal", "account", ".", "Note", "that", "any", "existing", "devices", "asssociated", "with", "your", "account", "will", "be", "purged", "as", "a", "result", "of", "this", "action", ".", "This", "should", "only", "be", "used", "for", "new", "accounts", "or", "when", "you", "need", "to", "start", "over", "." ]
f411c6585772ac67b842767bc7ce23edcbfae4ae
https://github.com/ForstaLabs/librelay-node/blob/f411c6585772ac67b842767bc7ce23edcbfae4ae/src/hub/registration.js#L41-L77
train
feedhenry/fh-forms
lib/common/forms-rule-engine.js
checkValueSubmitted
function checkValueSubmitted(submittedField, fieldDefinition, visible, cb) { if (!fieldDefinition.required) { return cb(undefined, null); } var valueSubmitted = submittedField && submittedField.fieldValues && (submittedField.fieldValues.length > 0); //No value submitted is only an error if the field is visible. //If the field value has been marked as not required, then don't fail a no-value submission var valueRequired = requiredFieldMap[fieldDefinition._id] && requiredFieldMap[fieldDefinition._id].valueRequired; if (!valueSubmitted && visible && valueRequired) { return cb(undefined, "No value submitted for field " + fieldDefinition.name); } return cb(undefined, null); }
javascript
function checkValueSubmitted(submittedField, fieldDefinition, visible, cb) { if (!fieldDefinition.required) { return cb(undefined, null); } var valueSubmitted = submittedField && submittedField.fieldValues && (submittedField.fieldValues.length > 0); //No value submitted is only an error if the field is visible. //If the field value has been marked as not required, then don't fail a no-value submission var valueRequired = requiredFieldMap[fieldDefinition._id] && requiredFieldMap[fieldDefinition._id].valueRequired; if (!valueSubmitted && visible && valueRequired) { return cb(undefined, "No value submitted for field " + fieldDefinition.name); } return cb(undefined, null); }
[ "function", "checkValueSubmitted", "(", "submittedField", ",", "fieldDefinition", ",", "visible", ",", "cb", ")", "{", "if", "(", "!", "fieldDefinition", ".", "required", ")", "{", "return", "cb", "(", "undefined", ",", "null", ")", ";", "}", "var", "valueSubmitted", "=", "submittedField", "&&", "submittedField", ".", "fieldValues", "&&", "(", "submittedField", ".", "fieldValues", ".", "length", ">", "0", ")", ";", "var", "valueRequired", "=", "requiredFieldMap", "[", "fieldDefinition", ".", "_id", "]", "&&", "requiredFieldMap", "[", "fieldDefinition", ".", "_id", "]", ".", "valueRequired", ";", "if", "(", "!", "valueSubmitted", "&&", "visible", "&&", "valueRequired", ")", "{", "return", "cb", "(", "undefined", ",", "\"No value submitted for field \"", "+", "fieldDefinition", ".", "name", ")", ";", "}", "return", "cb", "(", "undefined", ",", "null", ")", ";", "}" ]
just functions below this
[ "just", "functions", "below", "this" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/forms-rule-engine.js#L1042-L1058
train
feedhenry/fh-forms
lib/common/forms-rule-engine.js
isSafeString
function isSafeString(str) { var escape = ['&amp;', '&lt;', '&gt;', '&quot;', '&#x27;', '&#96;']; if (typeof str !== "string" || (escape.some(function(specialChar) { return str.indexOf(specialChar) >= 0; }))) { return true; } }
javascript
function isSafeString(str) { var escape = ['&amp;', '&lt;', '&gt;', '&quot;', '&#x27;', '&#96;']; if (typeof str !== "string" || (escape.some(function(specialChar) { return str.indexOf(specialChar) >= 0; }))) { return true; } }
[ "function", "isSafeString", "(", "str", ")", "{", "var", "escape", "=", "[", "'&amp;'", ",", "'&lt;'", ",", "'&gt;'", ",", "'&quot;'", ",", "'&#x27;'", ",", "'&#96;'", "]", ";", "if", "(", "typeof", "str", "!==", "\"string\"", "||", "(", "escape", ".", "some", "(", "function", "(", "specialChar", ")", "{", "return", "str", ".", "indexOf", "(", "specialChar", ")", ">=", "0", ";", "}", ")", ")", ")", "{", "return", "true", ";", "}", "}" ]
isSafeString - Checks if special characters in strings have already been escaped. @param {string} str The string to check. @return {boolean}
[ "isSafeString", "-", "Checks", "if", "special", "characters", "in", "strings", "have", "already", "been", "escaped", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/forms-rule-engine.js#L1271-L1278
train
feedhenry/fh-forms
lib/common/forms-rule-engine.js
validatorDropDown
function validatorDropDown(fieldValue, fieldDefinition, previousFieldValues, cb) { if (typeof(fieldValue) !== "string") { return cb(new Error("Expected submission to be string but got " + typeof(fieldValue))); } fieldDefinition.fieldOptions = fieldDefinition.fieldOptions || {}; fieldDefinition.fieldOptions.definition = fieldDefinition.fieldOptions.definition || {}; //Check values exists in the field definition if (!fieldDefinition.fieldOptions.definition.options) { return cb(new Error("No options exist for field " + fieldDefinition.name)); } //Finding the selected option var found = _.find(fieldDefinition.fieldOptions.definition.options, function(dropdownOption) { //check if fieldValue and the label need to be escaped isSafeString(fieldValue) ? null : fieldValue = _.escape(fieldValue); isSafeString(dropdownOption.label) ? null : dropdownOption.label = _.escape(dropdownOption.label); return dropdownOption.label === fieldValue; }); //Valid option, can return if (found) { return cb(); } //If the option is empty and the field is required, then the blank option is being submitted //The blank option is not valid for a required field. if (found === "" && fieldDefinition.required && fieldDefinition.fieldOptions.definition.include_blank_option) { return cb(new Error("The Blank Option is not valid. Please select a value.")); } else { //Otherwise, it is an invalid option return cb(new Error("Invalid option specified: " + fieldValue)); } }
javascript
function validatorDropDown(fieldValue, fieldDefinition, previousFieldValues, cb) { if (typeof(fieldValue) !== "string") { return cb(new Error("Expected submission to be string but got " + typeof(fieldValue))); } fieldDefinition.fieldOptions = fieldDefinition.fieldOptions || {}; fieldDefinition.fieldOptions.definition = fieldDefinition.fieldOptions.definition || {}; //Check values exists in the field definition if (!fieldDefinition.fieldOptions.definition.options) { return cb(new Error("No options exist for field " + fieldDefinition.name)); } //Finding the selected option var found = _.find(fieldDefinition.fieldOptions.definition.options, function(dropdownOption) { //check if fieldValue and the label need to be escaped isSafeString(fieldValue) ? null : fieldValue = _.escape(fieldValue); isSafeString(dropdownOption.label) ? null : dropdownOption.label = _.escape(dropdownOption.label); return dropdownOption.label === fieldValue; }); //Valid option, can return if (found) { return cb(); } //If the option is empty and the field is required, then the blank option is being submitted //The blank option is not valid for a required field. if (found === "" && fieldDefinition.required && fieldDefinition.fieldOptions.definition.include_blank_option) { return cb(new Error("The Blank Option is not valid. Please select a value.")); } else { //Otherwise, it is an invalid option return cb(new Error("Invalid option specified: " + fieldValue)); } }
[ "function", "validatorDropDown", "(", "fieldValue", ",", "fieldDefinition", ",", "previousFieldValues", ",", "cb", ")", "{", "if", "(", "typeof", "(", "fieldValue", ")", "!==", "\"string\"", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"Expected submission to be string but got \"", "+", "typeof", "(", "fieldValue", ")", ")", ")", ";", "}", "fieldDefinition", ".", "fieldOptions", "=", "fieldDefinition", ".", "fieldOptions", "||", "{", "}", ";", "fieldDefinition", ".", "fieldOptions", ".", "definition", "=", "fieldDefinition", ".", "fieldOptions", ".", "definition", "||", "{", "}", ";", "if", "(", "!", "fieldDefinition", ".", "fieldOptions", ".", "definition", ".", "options", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"No options exist for field \"", "+", "fieldDefinition", ".", "name", ")", ")", ";", "}", "var", "found", "=", "_", ".", "find", "(", "fieldDefinition", ".", "fieldOptions", ".", "definition", ".", "options", ",", "function", "(", "dropdownOption", ")", "{", "isSafeString", "(", "fieldValue", ")", "?", "null", ":", "fieldValue", "=", "_", ".", "escape", "(", "fieldValue", ")", ";", "isSafeString", "(", "dropdownOption", ".", "label", ")", "?", "null", ":", "dropdownOption", ".", "label", "=", "_", ".", "escape", "(", "dropdownOption", ".", "label", ")", ";", "return", "dropdownOption", ".", "label", "===", "fieldValue", ";", "}", ")", ";", "if", "(", "found", ")", "{", "return", "cb", "(", ")", ";", "}", "if", "(", "found", "===", "\"\"", "&&", "fieldDefinition", ".", "required", "&&", "fieldDefinition", ".", "fieldOptions", ".", "definition", ".", "include_blank_option", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"The Blank Option is not valid. Please select a value.\"", ")", ")", ";", "}", "else", "{", "return", "cb", "(", "new", "Error", "(", "\"Invalid option specified: \"", "+", "fieldValue", ")", ")", ";", "}", "}" ]
validatorDropDown - Validator function for dropdown fields. @param {string} fieldValue The value to validate @param {object} fieldDefinition Full JSON definition of the field @param {array} previousFieldValues Any values previously stored with the fields @param {function} cb Callback function
[ "validatorDropDown", "-", "Validator", "function", "for", "dropdown", "fields", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/forms-rule-engine.js#L1288-L1322
train
feedhenry/fh-forms
lib/common/forms-rule-engine.js
validatorRadio
function validatorRadio(fieldValue, fieldDefinition, previousFieldValues, cb) { if (typeof(fieldValue) !== "string") { return cb(new Error("Expected submission to be string but got " + typeof(fieldValue))); } //Check value exists in the field definition if (!fieldDefinition.fieldOptions.definition.options) { return cb(new Error("No options exist for field " + fieldDefinition.name)); } async.some(fieldDefinition.fieldOptions.definition.options, function(dropdownOption, cb) { //check if fieldValue and the label need to be escaped isSafeString(fieldValue) ? null : fieldValue = _.escape(fieldValue); isSafeString(dropdownOption.label) ? null : dropdownOption.label = _.escape(dropdownOption.label); return cb(dropdownOption.label === fieldValue); }, function(found) { if (!found) { return cb(new Error("Invalid option specified: " + fieldValue)); } else { return cb(); } }); }
javascript
function validatorRadio(fieldValue, fieldDefinition, previousFieldValues, cb) { if (typeof(fieldValue) !== "string") { return cb(new Error("Expected submission to be string but got " + typeof(fieldValue))); } //Check value exists in the field definition if (!fieldDefinition.fieldOptions.definition.options) { return cb(new Error("No options exist for field " + fieldDefinition.name)); } async.some(fieldDefinition.fieldOptions.definition.options, function(dropdownOption, cb) { //check if fieldValue and the label need to be escaped isSafeString(fieldValue) ? null : fieldValue = _.escape(fieldValue); isSafeString(dropdownOption.label) ? null : dropdownOption.label = _.escape(dropdownOption.label); return cb(dropdownOption.label === fieldValue); }, function(found) { if (!found) { return cb(new Error("Invalid option specified: " + fieldValue)); } else { return cb(); } }); }
[ "function", "validatorRadio", "(", "fieldValue", ",", "fieldDefinition", ",", "previousFieldValues", ",", "cb", ")", "{", "if", "(", "typeof", "(", "fieldValue", ")", "!==", "\"string\"", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"Expected submission to be string but got \"", "+", "typeof", "(", "fieldValue", ")", ")", ")", ";", "}", "if", "(", "!", "fieldDefinition", ".", "fieldOptions", ".", "definition", ".", "options", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"No options exist for field \"", "+", "fieldDefinition", ".", "name", ")", ")", ";", "}", "async", ".", "some", "(", "fieldDefinition", ".", "fieldOptions", ".", "definition", ".", "options", ",", "function", "(", "dropdownOption", ",", "cb", ")", "{", "isSafeString", "(", "fieldValue", ")", "?", "null", ":", "fieldValue", "=", "_", ".", "escape", "(", "fieldValue", ")", ";", "isSafeString", "(", "dropdownOption", ".", "label", ")", "?", "null", ":", "dropdownOption", ".", "label", "=", "_", ".", "escape", "(", "dropdownOption", ".", "label", ")", ";", "return", "cb", "(", "dropdownOption", ".", "label", "===", "fieldValue", ")", ";", "}", ",", "function", "(", "found", ")", "{", "if", "(", "!", "found", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"Invalid option specified: \"", "+", "fieldValue", ")", ")", ";", "}", "else", "{", "return", "cb", "(", ")", ";", "}", "}", ")", ";", "}" ]
validatorRadio - Validator function for radio fields. @param {string} fieldValue The value to validate @param {object} fieldDefinition Full JSON definition of the field @param {array} previousFieldValues Any values previously stored with the fields @param {function} cb Callback function
[ "validatorRadio", "-", "Validator", "function", "for", "radio", "fields", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/forms-rule-engine.js#L1332-L1354
train
feedhenry/fh-forms
lib/common/forms-rule-engine.js
validatorBarcode
function validatorBarcode(fieldValue, fieldDefinition, previousFieldValues, cb) { if (typeof(fieldValue) !== "object" || fieldValue === null) { return cb(new Error("Expected object but got " + typeof(fieldValue))); } if (typeof(fieldValue.text) !== "string" || fieldValue.text.length === 0) { return cb(new Error("Expected text parameter.")); } if (typeof(fieldValue.format) !== "string" || fieldValue.format.length === 0) { return cb(new Error("Expected format parameter.")); } return cb(); }
javascript
function validatorBarcode(fieldValue, fieldDefinition, previousFieldValues, cb) { if (typeof(fieldValue) !== "object" || fieldValue === null) { return cb(new Error("Expected object but got " + typeof(fieldValue))); } if (typeof(fieldValue.text) !== "string" || fieldValue.text.length === 0) { return cb(new Error("Expected text parameter.")); } if (typeof(fieldValue.format) !== "string" || fieldValue.format.length === 0) { return cb(new Error("Expected format parameter.")); } return cb(); }
[ "function", "validatorBarcode", "(", "fieldValue", ",", "fieldDefinition", ",", "previousFieldValues", ",", "cb", ")", "{", "if", "(", "typeof", "(", "fieldValue", ")", "!==", "\"object\"", "||", "fieldValue", "===", "null", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"Expected object but got \"", "+", "typeof", "(", "fieldValue", ")", ")", ")", ";", "}", "if", "(", "typeof", "(", "fieldValue", ".", "text", ")", "!==", "\"string\"", "||", "fieldValue", ".", "text", ".", "length", "===", "0", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"Expected text parameter.\"", ")", ")", ";", "}", "if", "(", "typeof", "(", "fieldValue", ".", "format", ")", "!==", "\"string\"", "||", "fieldValue", ".", "format", ".", "length", "===", "0", ")", "{", "return", "cb", "(", "new", "Error", "(", "\"Expected format parameter.\"", ")", ")", ";", "}", "return", "cb", "(", ")", ";", "}" ]
Function to validate a barcode submission Must be an object with the following contents { text: "<<content of barcode>>", format: "<<barcode content format>>" } @param fieldValue @param fieldDefinition @param previousFieldValues @param cb
[ "Function", "to", "validate", "a", "barcode", "submission" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/forms-rule-engine.js#L1497-L1511
train
feedhenry/fh-forms
lib/common/schemas/dataSourceCache.js
convertDSCacheToFieldOptions
function convertDSCacheToFieldOptions(fieldType, cacheEntries) { //Radio and Dropdown only allow the first option to be selected //Checkboxes can have multiple options selected. var alreadySelected = false; return _.map(cacheEntries, function(cacheEntry, index) { var valToReturn = { key: cacheEntry.key || index, label: cacheEntry.value, checked: cacheEntry.selected && (!alreadySelected || fieldType === CONSTANTS.FORM_CONSTANTS.FIELD_TYPE_CHECKBOXES) }; if (valToReturn.checked) { alreadySelected = true; } return valToReturn; }); }
javascript
function convertDSCacheToFieldOptions(fieldType, cacheEntries) { //Radio and Dropdown only allow the first option to be selected //Checkboxes can have multiple options selected. var alreadySelected = false; return _.map(cacheEntries, function(cacheEntry, index) { var valToReturn = { key: cacheEntry.key || index, label: cacheEntry.value, checked: cacheEntry.selected && (!alreadySelected || fieldType === CONSTANTS.FORM_CONSTANTS.FIELD_TYPE_CHECKBOXES) }; if (valToReturn.checked) { alreadySelected = true; } return valToReturn; }); }
[ "function", "convertDSCacheToFieldOptions", "(", "fieldType", ",", "cacheEntries", ")", "{", "var", "alreadySelected", "=", "false", ";", "return", "_", ".", "map", "(", "cacheEntries", ",", "function", "(", "cacheEntry", ",", "index", ")", "{", "var", "valToReturn", "=", "{", "key", ":", "cacheEntry", ".", "key", "||", "index", ",", "label", ":", "cacheEntry", ".", "value", ",", "checked", ":", "cacheEntry", ".", "selected", "&&", "(", "!", "alreadySelected", "||", "fieldType", "===", "CONSTANTS", ".", "FORM_CONSTANTS", ".", "FIELD_TYPE_CHECKBOXES", ")", "}", ";", "if", "(", "valToReturn", ".", "checked", ")", "{", "alreadySelected", "=", "true", ";", "}", "return", "valToReturn", ";", "}", ")", ";", "}" ]
Converting DS Cache Entries To Field Format @param fieldType @param cacheEntries @returns {Array} @private
[ "Converting", "DS", "Cache", "Entries", "To", "Field", "Format" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/schemas/dataSourceCache.js#L21-L37
train
cloudfour/drizzle-builder
src/utils/parse.js
isGlob
function isGlob(candidate) { if (typeof candidate === 'string' && candidate.length > 0) { return true; } if (Array.isArray(candidate) && candidate.length > 0) { return candidate.every(candidateEl => typeof candidateEl === 'string'); } return false; }
javascript
function isGlob(candidate) { if (typeof candidate === 'string' && candidate.length > 0) { return true; } if (Array.isArray(candidate) && candidate.length > 0) { return candidate.every(candidateEl => typeof candidateEl === 'string'); } return false; }
[ "function", "isGlob", "(", "candidate", ")", "{", "if", "(", "typeof", "candidate", "===", "'string'", "&&", "candidate", ".", "length", ">", "0", ")", "{", "return", "true", ";", "}", "if", "(", "Array", ".", "isArray", "(", "candidate", ")", "&&", "candidate", ".", "length", ">", "0", ")", "{", "return", "candidate", ".", "every", "(", "candidateEl", "=>", "typeof", "candidateEl", "===", "'string'", ")", ";", "}", "return", "false", ";", "}" ]
Utility function to test if a value COULD be a glob. A single string or an Array of strings counts. Just because this returns true, however, doesn't mean it is a glob that makes sense, just that it looks like one. @param {String|Array} candidate @return Boolean
[ "Utility", "function", "to", "test", "if", "a", "value", "COULD", "be", "a", "glob", ".", "A", "single", "string", "or", "an", "Array", "of", "strings", "counts", ".", "Just", "because", "this", "returns", "true", "however", "doesn", "t", "mean", "it", "is", "a", "glob", "that", "makes", "sense", "just", "that", "it", "looks", "like", "one", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/parse.js#L31-L39
train
cloudfour/drizzle-builder
src/utils/parse.js
parseField
function parseField(fieldKey, fieldData, options) { let parseFn = contents => ({ contents: contents }); let contents = fieldData; // Check to see if options.fieldParsers contains this key if (options.fieldParsers.hasOwnProperty(fieldKey)) { const parserKey = options.fieldParsers[fieldKey]; parseFn = options.parsers[parserKey].parseFn; contents = typeof fieldData === 'string' ? fieldData : fieldData.contents; } // Check to see if there is a manually-added parser in the data if (typeof fieldData === 'object' && fieldData.hasOwnProperty('parser')) { if (options.parsers.hasOwnProperty(fieldData.parser)) { parseFn = options.parsers[fieldData.parser].parseFn; } else { DrizzleError.error( new DrizzleError( `parser '${fieldData.parser}' set on field '${fieldKey}' not defined`, DrizzleError.LEVELS.WARN ), options.debug ); } contents = fieldData.contents; if (!fieldData.hasOwnProperty('contents')) { // TODO again } } return parseFn(contents); }
javascript
function parseField(fieldKey, fieldData, options) { let parseFn = contents => ({ contents: contents }); let contents = fieldData; // Check to see if options.fieldParsers contains this key if (options.fieldParsers.hasOwnProperty(fieldKey)) { const parserKey = options.fieldParsers[fieldKey]; parseFn = options.parsers[parserKey].parseFn; contents = typeof fieldData === 'string' ? fieldData : fieldData.contents; } // Check to see if there is a manually-added parser in the data if (typeof fieldData === 'object' && fieldData.hasOwnProperty('parser')) { if (options.parsers.hasOwnProperty(fieldData.parser)) { parseFn = options.parsers[fieldData.parser].parseFn; } else { DrizzleError.error( new DrizzleError( `parser '${fieldData.parser}' set on field '${fieldKey}' not defined`, DrizzleError.LEVELS.WARN ), options.debug ); } contents = fieldData.contents; if (!fieldData.hasOwnProperty('contents')) { // TODO again } } return parseFn(contents); }
[ "function", "parseField", "(", "fieldKey", ",", "fieldData", ",", "options", ")", "{", "let", "parseFn", "=", "contents", "=>", "(", "{", "contents", ":", "contents", "}", ")", ";", "let", "contents", "=", "fieldData", ";", "if", "(", "options", ".", "fieldParsers", ".", "hasOwnProperty", "(", "fieldKey", ")", ")", "{", "const", "parserKey", "=", "options", ".", "fieldParsers", "[", "fieldKey", "]", ";", "parseFn", "=", "options", ".", "parsers", "[", "parserKey", "]", ".", "parseFn", ";", "contents", "=", "typeof", "fieldData", "===", "'string'", "?", "fieldData", ":", "fieldData", ".", "contents", ";", "}", "if", "(", "typeof", "fieldData", "===", "'object'", "&&", "fieldData", ".", "hasOwnProperty", "(", "'parser'", ")", ")", "{", "if", "(", "options", ".", "parsers", ".", "hasOwnProperty", "(", "fieldData", ".", "parser", ")", ")", "{", "parseFn", "=", "options", ".", "parsers", "[", "fieldData", ".", "parser", "]", ".", "parseFn", ";", "}", "else", "{", "DrizzleError", ".", "error", "(", "new", "DrizzleError", "(", "`", "${", "fieldData", ".", "parser", "}", "${", "fieldKey", "}", "`", ",", "DrizzleError", ".", "LEVELS", ".", "WARN", ")", ",", "options", ".", "debug", ")", ";", "}", "contents", "=", "fieldData", ".", "contents", ";", "if", "(", "!", "fieldData", ".", "hasOwnProperty", "(", "'contents'", ")", ")", "{", "}", "}", "return", "parseFn", "(", "contents", ")", ";", "}" ]
Evaluate a single field of data and see if it should be run through a parser. @param {String} fieldKey @param {Object|String} fieldData @param {Object} options @return {Object} parsed data; contains `contents` property. @see parse/parsers
[ "Evaluate", "a", "single", "field", "of", "data", "and", "see", "if", "it", "should", "be", "run", "through", "a", "parser", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/parse.js#L77-L105
train
cloudfour/drizzle-builder
src/utils/parse.js
readFiles
function readFiles( glob, { parsers = {}, encoding = 'utf-8', globOpts = {} } = {} ) { return getFiles(glob, globOpts).then(paths => { return Promise.all( paths.map(filepath => { return readFile(filepath, encoding).then(fileData => { const parser = matchParser(filepath, parsers); fileData = parser(fileData, filepath); if (typeof fileData === 'string') { fileData = { contents: fileData }; } return Object.assign(fileData, { path: filepath }); }); }) ); }); }
javascript
function readFiles( glob, { parsers = {}, encoding = 'utf-8', globOpts = {} } = {} ) { return getFiles(glob, globOpts).then(paths => { return Promise.all( paths.map(filepath => { return readFile(filepath, encoding).then(fileData => { const parser = matchParser(filepath, parsers); fileData = parser(fileData, filepath); if (typeof fileData === 'string') { fileData = { contents: fileData }; } return Object.assign(fileData, { path: filepath }); }); }) ); }); }
[ "function", "readFiles", "(", "glob", ",", "{", "parsers", "=", "{", "}", ",", "encoding", "=", "'utf-8'", ",", "globOpts", "=", "{", "}", "}", "=", "{", "}", ")", "{", "return", "getFiles", "(", "glob", ",", "globOpts", ")", ".", "then", "(", "paths", "=>", "{", "return", "Promise", ".", "all", "(", "paths", ".", "map", "(", "filepath", "=>", "{", "return", "readFile", "(", "filepath", ",", "encoding", ")", ".", "then", "(", "fileData", "=>", "{", "const", "parser", "=", "matchParser", "(", "filepath", ",", "parsers", ")", ";", "fileData", "=", "parser", "(", "fileData", ",", "filepath", ")", ";", "if", "(", "typeof", "fileData", "===", "'string'", ")", "{", "fileData", "=", "{", "contents", ":", "fileData", "}", ";", "}", "return", "Object", ".", "assign", "(", "fileData", ",", "{", "path", ":", "filepath", "}", ")", ";", "}", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
Take a glob; read the files, optionally running a `contentFn` over the contents of the file. @param {glob} glob of files to read @param {Object} Options: - {Object} available parsers - {String} encoding - {Object} globOpts gets passed to getFiles @return {Promise} resolving to Array of Objects: - {String} path - {String|Mixed} contents: contents of file after contentFn
[ "Take", "a", "glob", ";", "read", "the", "files", "optionally", "running", "a", "contentFn", "over", "the", "contents", "of", "the", "file", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/parse.js#L137-L155
train
feedhenry/fh-forms
lib/middleware/themes.js
importTheme
function importTheme(req, res, next) { req.appformsResultPayload = req.appformsResultPayload || {}; var themeData = (req.appformsResultPayload.data && req.appformsResultPayload.type === constants.resultTypes.themeTemplate) ? req.appformsResultPayload.data : undefined ; var importThemeParams = { theme: themeData, name: req.body.name, description: req.body.description, userEmail: req.user.email }; forms.cloneTheme(_.extend(req.connectionOptions, importThemeParams), resultHandler(constants.resultTypes.themes, req, next)); }
javascript
function importTheme(req, res, next) { req.appformsResultPayload = req.appformsResultPayload || {}; var themeData = (req.appformsResultPayload.data && req.appformsResultPayload.type === constants.resultTypes.themeTemplate) ? req.appformsResultPayload.data : undefined ; var importThemeParams = { theme: themeData, name: req.body.name, description: req.body.description, userEmail: req.user.email }; forms.cloneTheme(_.extend(req.connectionOptions, importThemeParams), resultHandler(constants.resultTypes.themes, req, next)); }
[ "function", "importTheme", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "appformsResultPayload", "=", "req", ".", "appformsResultPayload", "||", "{", "}", ";", "var", "themeData", "=", "(", "req", ".", "appformsResultPayload", ".", "data", "&&", "req", ".", "appformsResultPayload", ".", "type", "===", "constants", ".", "resultTypes", ".", "themeTemplate", ")", "?", "req", ".", "appformsResultPayload", ".", "data", ":", "undefined", ";", "var", "importThemeParams", "=", "{", "theme", ":", "themeData", ",", "name", ":", "req", ".", "body", ".", "name", ",", "description", ":", "req", ".", "body", ".", "description", ",", "userEmail", ":", "req", ".", "user", ".", "email", "}", ";", "forms", ".", "cloneTheme", "(", "_", ".", "extend", "(", "req", ".", "connectionOptions", ",", "importThemeParams", ")", ",", "resultHandler", "(", "constants", ".", "resultTypes", ".", "themes", ",", "req", ",", "next", ")", ")", ";", "}" ]
Importing A Theme From A Template
[ "Importing", "A", "Theme", "From", "A", "Template" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/themes.js#L59-L71
train
feedhenry/fh-forms
lib/middleware/themes.js
exportThemes
function exportThemes(req, res, next) { var options = req.connectionOptions; forms.exportThemes(options, resultHandler(constants.resultTypes.themes, req, next)); }
javascript
function exportThemes(req, res, next) { var options = req.connectionOptions; forms.exportThemes(options, resultHandler(constants.resultTypes.themes, req, next)); }
[ "function", "exportThemes", "(", "req", ",", "res", ",", "next", ")", "{", "var", "options", "=", "req", ".", "connectionOptions", ";", "forms", ".", "exportThemes", "(", "options", ",", "resultHandler", "(", "constants", ".", "resultTypes", ".", "themes", ",", "req", ",", "next", ")", ")", ";", "}" ]
Exporting All Themes. @param req @param res @param next
[ "Exporting", "All", "Themes", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/themes.js#L95-L99
train
feedhenry/fh-forms
lib/middleware/themes.js
importThemes
function importThemes(req, res, next) { var options = req.connectionOptions; var themesToImport = req.body || []; if (!_.isArray(req.body)) { return next("Expected An Array Of Themes"); } forms.importThemes(options, themesToImport, resultHandler(constants.resultTypes.themes, req, next)); }
javascript
function importThemes(req, res, next) { var options = req.connectionOptions; var themesToImport = req.body || []; if (!_.isArray(req.body)) { return next("Expected An Array Of Themes"); } forms.importThemes(options, themesToImport, resultHandler(constants.resultTypes.themes, req, next)); }
[ "function", "importThemes", "(", "req", ",", "res", ",", "next", ")", "{", "var", "options", "=", "req", ".", "connectionOptions", ";", "var", "themesToImport", "=", "req", ".", "body", "||", "[", "]", ";", "if", "(", "!", "_", ".", "isArray", "(", "req", ".", "body", ")", ")", "{", "return", "next", "(", "\"Expected An Array Of Themes\"", ")", ";", "}", "forms", ".", "importThemes", "(", "options", ",", "themesToImport", ",", "resultHandler", "(", "constants", ".", "resultTypes", ".", "themes", ",", "req", ",", "next", ")", ")", ";", "}" ]
Importing Bulk Themes @param req @param res @param next
[ "Importing", "Bulk", "Themes" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/themes.js#L107-L117
train
yibn2008/dependency-analyze
lib/index.js
getDepInfo
function getDepInfo (dep, currFile, customDepResolve) { let depResolve if (!customDepResolve) { depResolve = defaultDepResolve } else { depResolve = (dep, currFile) => { // parse defaultResolve as third param return customDepResolve(dep, currFile, defaultDepResolve) } } let currType = getParseType(currFile) let type = getParseType(dep) || currType let info = { parent: currFile, // parent file path type: type, // current file type (js/css) raw: dep, // raw dependency name (require('./xxx') => './xxx') name: null, // formated dependency name ('~@alife/xxx' => '@alife/xxx') module: null, // module name (only external module) file: null // resolved file name (only relative file) } info.name = depResolve(dep, currFile) if (!info.name.startsWith('.')) { if (info.name.startsWith('@')) { info.module = info.name.split('/', 2).join('/') } else { info.module = info.name.split('/', 1)[0] } } else { info.file = fileResolve(info.name, currFile) if (!info.file) { throw new ResolveError(info.name, currFile) } } return info }
javascript
function getDepInfo (dep, currFile, customDepResolve) { let depResolve if (!customDepResolve) { depResolve = defaultDepResolve } else { depResolve = (dep, currFile) => { // parse defaultResolve as third param return customDepResolve(dep, currFile, defaultDepResolve) } } let currType = getParseType(currFile) let type = getParseType(dep) || currType let info = { parent: currFile, // parent file path type: type, // current file type (js/css) raw: dep, // raw dependency name (require('./xxx') => './xxx') name: null, // formated dependency name ('~@alife/xxx' => '@alife/xxx') module: null, // module name (only external module) file: null // resolved file name (only relative file) } info.name = depResolve(dep, currFile) if (!info.name.startsWith('.')) { if (info.name.startsWith('@')) { info.module = info.name.split('/', 2).join('/') } else { info.module = info.name.split('/', 1)[0] } } else { info.file = fileResolve(info.name, currFile) if (!info.file) { throw new ResolveError(info.name, currFile) } } return info }
[ "function", "getDepInfo", "(", "dep", ",", "currFile", ",", "customDepResolve", ")", "{", "let", "depResolve", "if", "(", "!", "customDepResolve", ")", "{", "depResolve", "=", "defaultDepResolve", "}", "else", "{", "depResolve", "=", "(", "dep", ",", "currFile", ")", "=>", "{", "return", "customDepResolve", "(", "dep", ",", "currFile", ",", "defaultDepResolve", ")", "}", "}", "let", "currType", "=", "getParseType", "(", "currFile", ")", "let", "type", "=", "getParseType", "(", "dep", ")", "||", "currType", "let", "info", "=", "{", "parent", ":", "currFile", ",", "type", ":", "type", ",", "raw", ":", "dep", ",", "name", ":", "null", ",", "module", ":", "null", ",", "file", ":", "null", "}", "info", ".", "name", "=", "depResolve", "(", "dep", ",", "currFile", ")", "if", "(", "!", "info", ".", "name", ".", "startsWith", "(", "'.'", ")", ")", "{", "if", "(", "info", ".", "name", ".", "startsWith", "(", "'@'", ")", ")", "{", "info", ".", "module", "=", "info", ".", "name", ".", "split", "(", "'/'", ",", "2", ")", ".", "join", "(", "'/'", ")", "}", "else", "{", "info", ".", "module", "=", "info", ".", "name", ".", "split", "(", "'/'", ",", "1", ")", "[", "0", "]", "}", "}", "else", "{", "info", ".", "file", "=", "fileResolve", "(", "info", ".", "name", ",", "currFile", ")", "if", "(", "!", "info", ".", "file", ")", "{", "throw", "new", "ResolveError", "(", "info", ".", "name", ",", "currFile", ")", "}", "}", "return", "info", "}" ]
get dependency info @param {String} dep dependency @param {String} currFile current file @param {Function} customDepResolve custom dep resolve function @return {Object}
[ "get", "dependency", "info" ]
b600dfd7545785861ef46c203f508824505d8862
https://github.com/yibn2008/dependency-analyze/blob/b600dfd7545785861ef46c203f508824505d8862/lib/index.js#L105-L145
train
yibn2008/dependency-analyze
lib/index.js
analyzeFile
function analyzeFile (file, content, filter, depResolve, depth, result) { depth = typeof depth === 'number' ? depth : Infinity result = result || {} if (depth < 1) { return } if (file in result) { return } debug('analyze file: file = %s, depth = %s', file, depth) let deps = parseFile(file, content) || [] let item = result[file] = { deps: [], relatives: [], modules: [] } // filter deps if (filter) { deps = deps.filter(dep => filter(dep, file)) } // convert deps.forEach(dep => { let info = getDepInfo(dep, file, depResolve) item.deps.push(info) if (info.module && item.modules.indexOf(info.module) < 0) { item.modules.push(info.module) } else if (info.file && item.relatives.indexOf(info.file) < 0) { item.relatives.push(info.file) // deep first traversing analyzeFile(info.file, fs.readFileSync(info.file, 'utf8'), filter, depResolve, depth - 1, result) } }) return result }
javascript
function analyzeFile (file, content, filter, depResolve, depth, result) { depth = typeof depth === 'number' ? depth : Infinity result = result || {} if (depth < 1) { return } if (file in result) { return } debug('analyze file: file = %s, depth = %s', file, depth) let deps = parseFile(file, content) || [] let item = result[file] = { deps: [], relatives: [], modules: [] } // filter deps if (filter) { deps = deps.filter(dep => filter(dep, file)) } // convert deps.forEach(dep => { let info = getDepInfo(dep, file, depResolve) item.deps.push(info) if (info.module && item.modules.indexOf(info.module) < 0) { item.modules.push(info.module) } else if (info.file && item.relatives.indexOf(info.file) < 0) { item.relatives.push(info.file) // deep first traversing analyzeFile(info.file, fs.readFileSync(info.file, 'utf8'), filter, depResolve, depth - 1, result) } }) return result }
[ "function", "analyzeFile", "(", "file", ",", "content", ",", "filter", ",", "depResolve", ",", "depth", ",", "result", ")", "{", "depth", "=", "typeof", "depth", "===", "'number'", "?", "depth", ":", "Infinity", "result", "=", "result", "||", "{", "}", "if", "(", "depth", "<", "1", ")", "{", "return", "}", "if", "(", "file", "in", "result", ")", "{", "return", "}", "debug", "(", "'analyze file: file = %s, depth = %s'", ",", "file", ",", "depth", ")", "let", "deps", "=", "parseFile", "(", "file", ",", "content", ")", "||", "[", "]", "let", "item", "=", "result", "[", "file", "]", "=", "{", "deps", ":", "[", "]", ",", "relatives", ":", "[", "]", ",", "modules", ":", "[", "]", "}", "if", "(", "filter", ")", "{", "deps", "=", "deps", ".", "filter", "(", "dep", "=>", "filter", "(", "dep", ",", "file", ")", ")", "}", "deps", ".", "forEach", "(", "dep", "=>", "{", "let", "info", "=", "getDepInfo", "(", "dep", ",", "file", ",", "depResolve", ")", "item", ".", "deps", ".", "push", "(", "info", ")", "if", "(", "info", ".", "module", "&&", "item", ".", "modules", ".", "indexOf", "(", "info", ".", "module", ")", "<", "0", ")", "{", "item", ".", "modules", ".", "push", "(", "info", ".", "module", ")", "}", "else", "if", "(", "info", ".", "file", "&&", "item", ".", "relatives", ".", "indexOf", "(", "info", ".", "file", ")", "<", "0", ")", "{", "item", ".", "relatives", ".", "push", "(", "info", ".", "file", ")", "analyzeFile", "(", "info", ".", "file", ",", "fs", ".", "readFileSync", "(", "info", ".", "file", ",", "'utf8'", ")", ",", "filter", ",", "depResolve", ",", "depth", "-", "1", ",", "result", ")", "}", "}", ")", "return", "result", "}" ]
recursively analyze single file @param {String} file file path @param {String} content file content @param {Function} filter filter function @param {Function} depResolve resolve dep to normal dep format @param {Number} depth max analyze depth @param {Object} result the analyed result @return {Object}
[ "recursively", "analyze", "single", "file" ]
b600dfd7545785861ef46c203f508824505d8862
https://github.com/yibn2008/dependency-analyze/blob/b600dfd7545785861ef46c203f508824505d8862/lib/index.js#L157-L200
train
yibn2008/dependency-analyze
lib/index.js
analyze
function analyze (entry, options) { options = options || {} let result = {} // support array if (!Array.isArray(entry)) { entry = [entry] } entry.forEach(file => { let content // normalize file if (typeof file === 'string') { content = fs.readFileSync(file, 'utf8') } else { content = file.content file = file.file } let filter = options.filter let depResolve = options.depResolve let depth = options.depth analyzeFile(file, content, filter, depResolve, depth, result) }) return result }
javascript
function analyze (entry, options) { options = options || {} let result = {} // support array if (!Array.isArray(entry)) { entry = [entry] } entry.forEach(file => { let content // normalize file if (typeof file === 'string') { content = fs.readFileSync(file, 'utf8') } else { content = file.content file = file.file } let filter = options.filter let depResolve = options.depResolve let depth = options.depth analyzeFile(file, content, filter, depResolve, depth, result) }) return result }
[ "function", "analyze", "(", "entry", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", "let", "result", "=", "{", "}", "if", "(", "!", "Array", ".", "isArray", "(", "entry", ")", ")", "{", "entry", "=", "[", "entry", "]", "}", "entry", ".", "forEach", "(", "file", "=>", "{", "let", "content", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "content", "=", "fs", ".", "readFileSync", "(", "file", ",", "'utf8'", ")", "}", "else", "{", "content", "=", "file", ".", "content", "file", "=", "file", ".", "file", "}", "let", "filter", "=", "options", ".", "filter", "let", "depResolve", "=", "options", ".", "depResolve", "let", "depth", "=", "options", ".", "depth", "analyzeFile", "(", "file", ",", "content", ",", "filter", ",", "depResolve", ",", "depth", ",", "result", ")", "}", ")", "return", "result", "}" ]
analyze dependencies of a file ``` return { <file>: { deps: [{ // all deps parent: currFile, // parent file path type: type, // current file type (js/css) raw: dep, // raw dependency name (require('./xxx') => './xxx') name: null, // formated dependency name ('~@alife/xxx' => '@alife/xxx') module: null, // module name (only external module) file: null, // resolved file name (only relative file) }, ...], relatives: [ ... ], // relative deps' absolute path modules: [ ... ], // all external modules name }, ... } ``` @param {Mixed} entry the analyze entry (or entries) - {Array} multiple files, the item of Array should be String or Object - {String} single file path - {Object} single file path and content - file: {String} file path - content: {String} file content @param {Object} options analyze options - filter: {Function} filter deps, will be invoked with `filter(dep, currFile)` - depResolve: {Function} custom resolve for relative file, will be invoked with `resolve(dep, currFile, defaultResolve)` - depth: {Number} set max depth to analyze (default is Infinity) @return {Object}
[ "analyze", "dependencies", "of", "a", "file" ]
b600dfd7545785861ef46c203f508824505d8862
https://github.com/yibn2008/dependency-analyze/blob/b600dfd7545785861ef46c203f508824505d8862/lib/index.js#L235-L264
train
yibn2008/dependency-analyze
lib/index.js
getParseType
function getParseType (file) { let ext = path.extname(file) for (let type in FILE_TYPE_MAP) { let exts = FILE_TYPE_MAP[type] if (exts.indexOf(ext) >= 0) { return type } } }
javascript
function getParseType (file) { let ext = path.extname(file) for (let type in FILE_TYPE_MAP) { let exts = FILE_TYPE_MAP[type] if (exts.indexOf(ext) >= 0) { return type } } }
[ "function", "getParseType", "(", "file", ")", "{", "let", "ext", "=", "path", ".", "extname", "(", "file", ")", "for", "(", "let", "type", "in", "FILE_TYPE_MAP", ")", "{", "let", "exts", "=", "FILE_TYPE_MAP", "[", "type", "]", "if", "(", "exts", ".", "indexOf", "(", "ext", ")", ">=", "0", ")", "{", "return", "type", "}", "}", "}" ]
get parser type of file @param {String} file @return {String}
[ "get", "parser", "type", "of", "file" ]
b600dfd7545785861ef46c203f508824505d8862
https://github.com/yibn2008/dependency-analyze/blob/b600dfd7545785861ef46c203f508824505d8862/lib/index.js#L271-L281
train
cloudfour/drizzle-builder
src/parse/data.js
parseData
function parseData(options) { return readFileTree(options.src.data, options.keys.data, options); }
javascript
function parseData(options) { return readFileTree(options.src.data, options.keys.data, options); }
[ "function", "parseData", "(", "options", ")", "{", "return", "readFileTree", "(", "options", ".", "src", ".", "data", ",", "options", ".", "keys", ".", "data", ",", "options", ")", ";", "}" ]
Parse data from data files @param {Object} options Options object with `src.data` property @return {Promise} resolving to parsed file data
[ "Parse", "data", "from", "data", "files" ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/data.js#L11-L13
train
davidemiceli/gender-detection
index.js
function(firstName, lang) { if (lang && male[firstName] && male[firstName][lang] && female[firstName] && female[firstName][lang]) { return 'unisex'; } else if (lang && male[firstName] && male[firstName][lang]) { return 'male'; } else if (lang && female[firstName] && female[firstName][lang]) { return 'female'; } else if (male[firstName] && female[firstName]) { return 'unisex'; } else if (male[firstName]) { return 'male'; } else if (female[firstName]) { return 'female'; } return 'unknown'; }
javascript
function(firstName, lang) { if (lang && male[firstName] && male[firstName][lang] && female[firstName] && female[firstName][lang]) { return 'unisex'; } else if (lang && male[firstName] && male[firstName][lang]) { return 'male'; } else if (lang && female[firstName] && female[firstName][lang]) { return 'female'; } else if (male[firstName] && female[firstName]) { return 'unisex'; } else if (male[firstName]) { return 'male'; } else if (female[firstName]) { return 'female'; } return 'unknown'; }
[ "function", "(", "firstName", ",", "lang", ")", "{", "if", "(", "lang", "&&", "male", "[", "firstName", "]", "&&", "male", "[", "firstName", "]", "[", "lang", "]", "&&", "female", "[", "firstName", "]", "&&", "female", "[", "firstName", "]", "[", "lang", "]", ")", "{", "return", "'unisex'", ";", "}", "else", "if", "(", "lang", "&&", "male", "[", "firstName", "]", "&&", "male", "[", "firstName", "]", "[", "lang", "]", ")", "{", "return", "'male'", ";", "}", "else", "if", "(", "lang", "&&", "female", "[", "firstName", "]", "&&", "female", "[", "firstName", "]", "[", "lang", "]", ")", "{", "return", "'female'", ";", "}", "else", "if", "(", "male", "[", "firstName", "]", "&&", "female", "[", "firstName", "]", ")", "{", "return", "'unisex'", ";", "}", "else", "if", "(", "male", "[", "firstName", "]", ")", "{", "return", "'male'", ";", "}", "else", "if", "(", "female", "[", "firstName", "]", ")", "{", "return", "'female'", ";", "}", "return", "'unknown'", ";", "}" ]
Match gender type from the first name
[ "Match", "gender", "type", "from", "the", "first", "name" ]
d78ae93d72541125b5d2effe3f49e007cd76a8bc
https://github.com/davidemiceli/gender-detection/blob/d78ae93d72541125b5d2effe3f49e007cd76a8bc/index.js#L8-L23
train
shamil/node-zabbix-sender
index.js
prepareData
function prepareData(items, with_timestamps, with_ns) { var data = { request: 'sender data', data: items }; if (with_timestamps) { var ts = Date.now() / 1000; data.clock = ts | 0; if (with_ns) { data.ns = (ts % 1) * 1000 * 1000000 | 0; } } var payload = new Buffer(JSON.stringify(data), 'utf8'), header = new Buffer(5 + 4); // ZBXD\1 + packed payload.length header.write('ZBXD\x01'); header.writeInt32LE(payload.length, 5); return Buffer.concat([header, new Buffer('\x00\x00\x00\x00'), payload]); }
javascript
function prepareData(items, with_timestamps, with_ns) { var data = { request: 'sender data', data: items }; if (with_timestamps) { var ts = Date.now() / 1000; data.clock = ts | 0; if (with_ns) { data.ns = (ts % 1) * 1000 * 1000000 | 0; } } var payload = new Buffer(JSON.stringify(data), 'utf8'), header = new Buffer(5 + 4); // ZBXD\1 + packed payload.length header.write('ZBXD\x01'); header.writeInt32LE(payload.length, 5); return Buffer.concat([header, new Buffer('\x00\x00\x00\x00'), payload]); }
[ "function", "prepareData", "(", "items", ",", "with_timestamps", ",", "with_ns", ")", "{", "var", "data", "=", "{", "request", ":", "'sender data'", ",", "data", ":", "items", "}", ";", "if", "(", "with_timestamps", ")", "{", "var", "ts", "=", "Date", ".", "now", "(", ")", "/", "1000", ";", "data", ".", "clock", "=", "ts", "|", "0", ";", "if", "(", "with_ns", ")", "{", "data", ".", "ns", "=", "(", "ts", "%", "1", ")", "*", "1000", "*", "1000000", "|", "0", ";", "}", "}", "var", "payload", "=", "new", "Buffer", "(", "JSON", ".", "stringify", "(", "data", ")", ",", "'utf8'", ")", ",", "header", "=", "new", "Buffer", "(", "5", "+", "4", ")", ";", "header", ".", "write", "(", "'ZBXD\\x01'", ")", ";", "\\x01", "header", ".", "writeInt32LE", "(", "payload", ".", "length", ",", "5", ")", ";", "}" ]
takes items array and prepares payload for sending
[ "takes", "items", "array", "and", "prepares", "payload", "for", "sending" ]
39b588e178fd3a0428918fdab382fd6bfc8473ba
https://github.com/shamil/node-zabbix-sender/blob/39b588e178fd3a0428918fdab382fd6bfc8473ba/index.js#L115-L136
train
maierfelix/glmw
dist/glmw-node.js
function(module, memory) { // @str module.str = function(address) { let view = memory.F32.subarray(address >> 2, (address >> 2) + 16); let out = ""; for (let ii = 0; ii < 16; ++ii) { if (ii + 1 < 16) out += view[ii] + ", "; else out += view[ii]; } return "mat4(" + out + ")"; }; // @view module.view = function(address) { let view = memory.F32.subarray(address >> 2, (address >> 2) + 16); //view.address = address; return view; }; // @exactEquals let _exactEquals = module.exactEquals; module.exactEquals = function(a, b) { return !!_exactEquals(a, b); }; // @equals let _equals = module.equals; module.equals = function(a, b) { return !!_equals(a, b); }; }
javascript
function(module, memory) { // @str module.str = function(address) { let view = memory.F32.subarray(address >> 2, (address >> 2) + 16); let out = ""; for (let ii = 0; ii < 16; ++ii) { if (ii + 1 < 16) out += view[ii] + ", "; else out += view[ii]; } return "mat4(" + out + ")"; }; // @view module.view = function(address) { let view = memory.F32.subarray(address >> 2, (address >> 2) + 16); //view.address = address; return view; }; // @exactEquals let _exactEquals = module.exactEquals; module.exactEquals = function(a, b) { return !!_exactEquals(a, b); }; // @equals let _equals = module.equals; module.equals = function(a, b) { return !!_equals(a, b); }; }
[ "function", "(", "module", ",", "memory", ")", "{", "module", ".", "str", "=", "function", "(", "address", ")", "{", "let", "view", "=", "memory", ".", "F32", ".", "subarray", "(", "address", ">>", "2", ",", "(", "address", ">>", "2", ")", "+", "16", ")", ";", "let", "out", "=", "\"\"", ";", "for", "(", "let", "ii", "=", "0", ";", "ii", "<", "16", ";", "++", "ii", ")", "{", "if", "(", "ii", "+", "1", "<", "16", ")", "out", "+=", "view", "[", "ii", "]", "+", "\", \"", ";", "else", "out", "+=", "view", "[", "ii", "]", ";", "}", "return", "\"mat4(\"", "+", "out", "+", "\")\"", ";", "}", ";", "module", ".", "view", "=", "function", "(", "address", ")", "{", "let", "view", "=", "memory", ".", "F32", ".", "subarray", "(", "address", ">>", "2", ",", "(", "address", ">>", "2", ")", "+", "16", ")", ";", "return", "view", ";", "}", ";", "let", "_exactEquals", "=", "module", ".", "exactEquals", ";", "module", ".", "exactEquals", "=", "function", "(", "a", ",", "b", ")", "{", "return", "!", "!", "_exactEquals", "(", "a", ",", "b", ")", ";", "}", ";", "let", "_equals", "=", "module", ".", "equals", ";", "module", ".", "equals", "=", "function", "(", "a", ",", "b", ")", "{", "return", "!", "!", "_equals", "(", "a", ",", "b", ")", ";", "}", ";", "}" ]
The following methods need to be bridged within js which results in some overhead
[ "The", "following", "methods", "need", "to", "be", "bridged", "within", "js", "which", "results", "in", "some", "overhead" ]
4b1b39868f1038ded299f4a983adf8882104124d
https://github.com/maierfelix/glmw/blob/4b1b39868f1038ded299f4a983adf8882104124d/dist/glmw-node.js#L122-L149
train
uphold/eslint-plugin-sql-template
rules/no-unsafe-query.js
isSqlQuery
function isSqlQuery(literal) { if (!literal) { return false; } try { parser.parse(literal); } catch (error) { return false; } return true; }
javascript
function isSqlQuery(literal) { if (!literal) { return false; } try { parser.parse(literal); } catch (error) { return false; } return true; }
[ "function", "isSqlQuery", "(", "literal", ")", "{", "if", "(", "!", "literal", ")", "{", "return", "false", ";", "}", "try", "{", "parser", ".", "parse", "(", "literal", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if `literal` is an SQL query.
[ "Check", "if", "literal", "is", "an", "SQL", "query", "." ]
9200864402bab77a88b8a827f61c17148751fd24
https://github.com/uphold/eslint-plugin-sql-template/blob/9200864402bab77a88b8a827f61c17148751fd24/rules/no-unsafe-query.js#L13-L25
train
uphold/eslint-plugin-sql-template
rules/no-unsafe-query.js
validate
function validate(node, context) { if (!node) { return; } if (node.type === 'TaggedTemplateExpression' && node.tag.name !== 'sql') { node = node.quasi; } if (node.type === 'TemplateLiteral' && node.expressions.length) { const literal = node.quasis.map(quasi => quasi.value.raw).join('x'); if (isSqlQuery(literal)) { context.report(node, 'Use the `sql` tagged template literal for raw queries'); } } }
javascript
function validate(node, context) { if (!node) { return; } if (node.type === 'TaggedTemplateExpression' && node.tag.name !== 'sql') { node = node.quasi; } if (node.type === 'TemplateLiteral' && node.expressions.length) { const literal = node.quasis.map(quasi => quasi.value.raw).join('x'); if (isSqlQuery(literal)) { context.report(node, 'Use the `sql` tagged template literal for raw queries'); } } }
[ "function", "validate", "(", "node", ",", "context", ")", "{", "if", "(", "!", "node", ")", "{", "return", ";", "}", "if", "(", "node", ".", "type", "===", "'TaggedTemplateExpression'", "&&", "node", ".", "tag", ".", "name", "!==", "'sql'", ")", "{", "node", "=", "node", ".", "quasi", ";", "}", "if", "(", "node", ".", "type", "===", "'TemplateLiteral'", "&&", "node", ".", "expressions", ".", "length", ")", "{", "const", "literal", "=", "node", ".", "quasis", ".", "map", "(", "quasi", "=>", "quasi", ".", "value", ".", "raw", ")", ".", "join", "(", "'x'", ")", ";", "if", "(", "isSqlQuery", "(", "literal", ")", ")", "{", "context", ".", "report", "(", "node", ",", "'Use the `sql` tagged template literal for raw queries'", ")", ";", "}", "}", "}" ]
Validate node.
[ "Validate", "node", "." ]
9200864402bab77a88b8a827f61c17148751fd24
https://github.com/uphold/eslint-plugin-sql-template/blob/9200864402bab77a88b8a827f61c17148751fd24/rules/no-unsafe-query.js#L31-L47
train
observing/square
lib/square.js
yep
function yep(data) { var err; if (data instanceof Error) err = data; if (!err && data) backup = collection.content = data; else collection.content = backup; self.logger.debug( 'Received a'+ (err ? 'n error' : ' processed') + ' response from the '+ layer.id +' plugin ' + (collection.length ? 'for a '+ collection.extension +' file' : '') ); if (err) err.stack.split('\n').forEach(function print(line) { self.logger.error(line); }); // Clean up before we continue layer.destroy(); capture.dispose(); processed = collection; done(err, processed); }
javascript
function yep(data) { var err; if (data instanceof Error) err = data; if (!err && data) backup = collection.content = data; else collection.content = backup; self.logger.debug( 'Received a'+ (err ? 'n error' : ' processed') + ' response from the '+ layer.id +' plugin ' + (collection.length ? 'for a '+ collection.extension +' file' : '') ); if (err) err.stack.split('\n').forEach(function print(line) { self.logger.error(line); }); // Clean up before we continue layer.destroy(); capture.dispose(); processed = collection; done(err, processed); }
[ "function", "yep", "(", "data", ")", "{", "var", "err", ";", "if", "(", "data", "instanceof", "Error", ")", "err", "=", "data", ";", "if", "(", "!", "err", "&&", "data", ")", "backup", "=", "collection", ".", "content", "=", "data", ";", "else", "collection", ".", "content", "=", "backup", ";", "self", ".", "logger", ".", "debug", "(", "'Received a'", "+", "(", "err", "?", "'n error'", ":", "' processed'", ")", "+", "' response from the '", "+", "layer", ".", "id", "+", "' plugin '", "+", "(", "collection", ".", "length", "?", "'for a '", "+", "collection", ".", "extension", "+", "' file'", ":", "''", ")", ")", ";", "if", "(", "err", ")", "err", ".", "stack", ".", "split", "(", "'\\n'", ")", ".", "\\n", "forEach", ";", "(", "function", "print", "(", "line", ")", "{", "self", ".", "logger", ".", "error", "(", "line", ")", ";", "}", ")", "layer", ".", "destroy", "(", ")", ";", "capture", ".", "dispose", "(", ")", ";", "processed", "=", "collection", ";", "}" ]
Handle plugin responses from either a data, error or disregard emit. @param {String|Error} data @api private
[ "Handle", "plugin", "responses", "from", "either", "a", "data", "error", "or", "disregard", "emit", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/square.js#L446-L469
train
observing/square
lib/square.js
find
function find(deleted, file) { var meta = bundle[file].meta , match = files.some(function some (file) { return file === meta.location || ~meta.location.indexOf(file) || (meta.compiler && ~meta.compiler.imported.join(',').indexOf(file)); }); if (!match) return; // If we check previous for deleted files, don't read content. if (!deleted) { self.hold(meta.location); // Temporary freeze of the event loop. self.package.bundle[file].meta.content = fs.readFileSync(meta.location, 'utf8'); } // Add the file extension to the extensions list so we can create // a dedicated rebuild. extensions.push(meta.output); changes.push(file); }
javascript
function find(deleted, file) { var meta = bundle[file].meta , match = files.some(function some (file) { return file === meta.location || ~meta.location.indexOf(file) || (meta.compiler && ~meta.compiler.imported.join(',').indexOf(file)); }); if (!match) return; // If we check previous for deleted files, don't read content. if (!deleted) { self.hold(meta.location); // Temporary freeze of the event loop. self.package.bundle[file].meta.content = fs.readFileSync(meta.location, 'utf8'); } // Add the file extension to the extensions list so we can create // a dedicated rebuild. extensions.push(meta.output); changes.push(file); }
[ "function", "find", "(", "deleted", ",", "file", ")", "{", "var", "meta", "=", "bundle", "[", "file", "]", ".", "meta", ",", "match", "=", "files", ".", "some", "(", "function", "some", "(", "file", ")", "{", "return", "file", "===", "meta", ".", "location", "||", "~", "meta", ".", "location", ".", "indexOf", "(", "file", ")", "||", "(", "meta", ".", "compiler", "&&", "~", "meta", ".", "compiler", ".", "imported", ".", "join", "(", "','", ")", ".", "indexOf", "(", "file", ")", ")", ";", "}", ")", ";", "if", "(", "!", "match", ")", "return", ";", "if", "(", "!", "deleted", ")", "{", "self", ".", "hold", "(", "meta", ".", "location", ")", ";", "self", ".", "package", ".", "bundle", "[", "file", "]", ".", "meta", ".", "content", "=", "fs", ".", "readFileSync", "(", "meta", ".", "location", ",", "'utf8'", ")", ";", "}", "extensions", ".", "push", "(", "meta", ".", "output", ")", ";", "changes", ".", "push", "(", "file", ")", ";", "}" ]
Find file in the bundle. @param {Boolean} deleted are we checking for deleted files @param {String} file @api private
[ "Find", "file", "in", "the", "bundle", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/square.js#L1271-L1290
train
observing/square
lib/square.js
insert
function insert(match, commenttype, statement, file) { var location = path.resolve(reference, file) , data = ''; // // If it's not an absolute path, try to require.resolve the file. // if (!fs.existsSync(location)) try { location = require.resolve(file); } catch (e) { } if (!fs.existsSync(location)) { return self.critical( '// [square] @%s statement %s in %s does not exist' , statement , file.red , reference.red ); } if (~seen.indexOf(location)) { return self.critical('recursive [square] import statement detected %s', match); } // We processed the file, mark it as seen to protect us against recursive // includes. seen.push(location); data += self.commentWrap('[square] Directive: ' + location, extension); data += fs.readFileSync(location, 'utf8').trim(); // Pass the contents back in to the directive again so we can also process // the directives inside the directive. return self.directive(data, extension, path.dirname(location), seen); }
javascript
function insert(match, commenttype, statement, file) { var location = path.resolve(reference, file) , data = ''; // // If it's not an absolute path, try to require.resolve the file. // if (!fs.existsSync(location)) try { location = require.resolve(file); } catch (e) { } if (!fs.existsSync(location)) { return self.critical( '// [square] @%s statement %s in %s does not exist' , statement , file.red , reference.red ); } if (~seen.indexOf(location)) { return self.critical('recursive [square] import statement detected %s', match); } // We processed the file, mark it as seen to protect us against recursive // includes. seen.push(location); data += self.commentWrap('[square] Directive: ' + location, extension); data += fs.readFileSync(location, 'utf8').trim(); // Pass the contents back in to the directive again so we can also process // the directives inside the directive. return self.directive(data, extension, path.dirname(location), seen); }
[ "function", "insert", "(", "match", ",", "commenttype", ",", "statement", ",", "file", ")", "{", "var", "location", "=", "path", ".", "resolve", "(", "reference", ",", "file", ")", ",", "data", "=", "''", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "location", ")", ")", "try", "{", "location", "=", "require", ".", "resolve", "(", "file", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "if", "(", "!", "fs", ".", "existsSync", "(", "location", ")", ")", "{", "return", "self", ".", "critical", "(", "'// [square] @%s statement %s in %s does not exist'", ",", "statement", ",", "file", ".", "red", ",", "reference", ".", "red", ")", ";", "}", "if", "(", "~", "seen", ".", "indexOf", "(", "location", ")", ")", "{", "return", "self", ".", "critical", "(", "'recursive [square] import statement detected %s'", ",", "match", ")", ";", "}", "seen", ".", "push", "(", "location", ")", ";", "data", "+=", "self", ".", "commentWrap", "(", "'[square] Directive: '", "+", "location", ",", "extension", ")", ";", "data", "+=", "fs", ".", "readFileSync", "(", "location", ",", "'utf8'", ")", ".", "trim", "(", ")", ";", "return", "self", ".", "directive", "(", "data", ",", "extension", ",", "path", ".", "dirname", "(", "location", ")", ",", "seen", ")", ";", "}" ]
Process the directive. @param {String} match complete matched result @param {String} commenttype type of comment @param {String} statement import statement name @param {String} file the file that needs to be inlined @returns {String} @api private
[ "Process", "the", "directive", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/square.js#L1336-L1370
train
observing/square
lib/square.js
prev
function prev(index, lines) { while (index--) { var line = lines[index].trim(); if (line && !/^(\/\/|\/\*)/.test(line)) { return { line: line, index: index }; } } return {}; }
javascript
function prev(index, lines) { while (index--) { var line = lines[index].trim(); if (line && !/^(\/\/|\/\*)/.test(line)) { return { line: line, index: index }; } } return {}; }
[ "function", "prev", "(", "index", ",", "lines", ")", "{", "while", "(", "index", "--", ")", "{", "var", "line", "=", "lines", "[", "index", "]", ".", "trim", "(", ")", ";", "if", "(", "line", "&&", "!", "/", "^(\\/\\/|\\/\\*)", "/", ".", "test", "(", "line", ")", ")", "{", "return", "{", "line", ":", "line", ",", "index", ":", "index", "}", ";", "}", "}", "return", "{", "}", ";", "}" ]
Find the previous line that contains content, ignoring whitespace and newlines. @param {Number} index @param {Array} lines @returns {Object} @api private
[ "Find", "the", "previous", "line", "that", "contains", "content", "ignoring", "whitespace", "and", "newlines", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/square.js#L1381-L1391
train
observing/square
lib/square.js
writer
function writer(err, collections) { if (err) return done(err); // @TODO make sure that self.write only accepts 2 arguments and reads the // type from the supplied collection object. self.logger.debug('Writing files'); async.map(collections, self.write.bind(self), done); }
javascript
function writer(err, collections) { if (err) return done(err); // @TODO make sure that self.write only accepts 2 arguments and reads the // type from the supplied collection object. self.logger.debug('Writing files'); async.map(collections, self.write.bind(self), done); }
[ "function", "writer", "(", "err", ",", "collections", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "self", ".", "logger", ".", "debug", "(", "'Writing files'", ")", ";", "async", ".", "map", "(", "collections", ",", "self", ".", "write", ".", "bind", "(", "self", ")", ",", "done", ")", ";", "}" ]
Write the processed collections to disk. @param {Error} err @param {Array} collections
[ "Write", "the", "processed", "collections", "to", "disk", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/square.js#L1517-L1524
train
observing/square
lib/square.js
done
function done(err, files) { // On processing errors notify the watcher (if listening) that square is idle. if (err && self.writable) { self.logger.error(err); return fn(err); } // Stop our cache, it will be activated again when we need it self.cache.stop(); // Merge the results array to a key=>value object files = (files || []).reduce(function reduceFiles(memo, collection) { memo[collection.basename] = collection; return memo; }, {}); // Building is done, call callback if available. self.logger.info('Successfully generated %s', Object.keys(files).join(', ').green); if (err && !args.function) self.critical(err); if (args.function) args.function.call(self, err, files, extensions); }
javascript
function done(err, files) { // On processing errors notify the watcher (if listening) that square is idle. if (err && self.writable) { self.logger.error(err); return fn(err); } // Stop our cache, it will be activated again when we need it self.cache.stop(); // Merge the results array to a key=>value object files = (files || []).reduce(function reduceFiles(memo, collection) { memo[collection.basename] = collection; return memo; }, {}); // Building is done, call callback if available. self.logger.info('Successfully generated %s', Object.keys(files).join(', ').green); if (err && !args.function) self.critical(err); if (args.function) args.function.call(self, err, files, extensions); }
[ "function", "done", "(", "err", ",", "files", ")", "{", "if", "(", "err", "&&", "self", ".", "writable", ")", "{", "self", ".", "logger", ".", "error", "(", "err", ")", ";", "return", "fn", "(", "err", ")", ";", "}", "self", ".", "cache", ".", "stop", "(", ")", ";", "files", "=", "(", "files", "||", "[", "]", ")", ".", "reduce", "(", "function", "reduceFiles", "(", "memo", ",", "collection", ")", "{", "memo", "[", "collection", ".", "basename", "]", "=", "collection", ";", "return", "memo", ";", "}", ",", "{", "}", ")", ";", "self", ".", "logger", ".", "info", "(", "'Successfully generated %s'", ",", "Object", ".", "keys", "(", "files", ")", ".", "join", "(", "', '", ")", ".", "green", ")", ";", "if", "(", "err", "&&", "!", "args", ".", "function", ")", "self", ".", "critical", "(", "err", ")", ";", "if", "(", "args", ".", "function", ")", "args", ".", "function", ".", "call", "(", "self", ",", "err", ",", "files", ",", "extensions", ")", ";", "}" ]
Callback function for when the build is finished. @param {Error} err
[ "Callback", "function", "for", "when", "the", "build", "is", "finished", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/square.js#L1531-L1551
train
observing/square
lib/square.js
getObjectByKey
function getObjectByKey(data, prop) { if (!prop || !~prop.indexOf('.')) return data[prop]; var result = prop , structure = data; for (var paths = prop.split('.'), i = 0, length = paths.length; i < length; i++) { result = structure[+paths[i] || paths[i]]; structure = result; } return result || data[prop]; }
javascript
function getObjectByKey(data, prop) { if (!prop || !~prop.indexOf('.')) return data[prop]; var result = prop , structure = data; for (var paths = prop.split('.'), i = 0, length = paths.length; i < length; i++) { result = structure[+paths[i] || paths[i]]; structure = result; } return result || data[prop]; }
[ "function", "getObjectByKey", "(", "data", ",", "prop", ")", "{", "if", "(", "!", "prop", "||", "!", "~", "prop", ".", "indexOf", "(", "'.'", ")", ")", "return", "data", "[", "prop", "]", ";", "var", "result", "=", "prop", ",", "structure", "=", "data", ";", "for", "(", "var", "paths", "=", "prop", ".", "split", "(", "'.'", ")", ",", "i", "=", "0", ",", "length", "=", "paths", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "result", "=", "structure", "[", "+", "paths", "[", "i", "]", "||", "paths", "[", "i", "]", "]", ";", "structure", "=", "result", ";", "}", "return", "result", "||", "data", "[", "prop", "]", ";", "}" ]
Small helper function that allows you get a key from an object by specifying it's depth using dot notations. Example: - path.to.0.keys - key.depth @param {Ojbect|Array} data @param {String} prop @returns {Mixed} @api private
[ "Small", "helper", "function", "that", "allows", "you", "get", "a", "key", "from", "an", "object", "by", "specifying", "it", "s", "depth", "using", "dot", "notations", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/square.js#L1642-L1654
train
observing/square
lib/square.js
finished
function finished(err) { if (err) self.critical('Failed to store %s. %s.', base, err.message); if (fn) fn(err, collection); }
javascript
function finished(err) { if (err) self.critical('Failed to store %s. %s.', base, err.message); if (fn) fn(err, collection); }
[ "function", "finished", "(", "err", ")", "{", "if", "(", "err", ")", "self", ".", "critical", "(", "'Failed to store %s. %s.'", ",", "base", ",", "err", ".", "message", ")", ";", "if", "(", "fn", ")", "fn", "(", "err", ",", "collection", ")", ";", "}" ]
Simple finish function to ensure that we always call our callback when it's supplied. No matter what kind of write we need to perform. @param {Error} err optional error
[ "Simple", "finish", "function", "to", "ensure", "that", "we", "always", "call", "our", "callback", "when", "it", "s", "supplied", ".", "No", "matter", "what", "kind", "of", "write", "we", "need", "to", "perform", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/square.js#L1749-L1752
train
observing/square
lib/cli.js
spinner
function spinner(silent) { var interval = 100 , frames = spinner.frames , len = frames.length , i = 0; if (silent) return; spinner.interval = setInterval(function tick() { process.stdout.write( '\r' + frames[i++ % len] + 'Waiting for file changes'.white ); }, interval); }
javascript
function spinner(silent) { var interval = 100 , frames = spinner.frames , len = frames.length , i = 0; if (silent) return; spinner.interval = setInterval(function tick() { process.stdout.write( '\r' + frames[i++ % len] + 'Waiting for file changes'.white ); }, interval); }
[ "function", "spinner", "(", "silent", ")", "{", "var", "interval", "=", "100", ",", "frames", "=", "spinner", ".", "frames", ",", "len", "=", "frames", ".", "length", ",", "i", "=", "0", ";", "if", "(", "silent", ")", "return", ";", "spinner", ".", "interval", "=", "setInterval", "(", "function", "tick", "(", ")", "{", "process", ".", "stdout", ".", "write", "(", "'\\r'", "+", "\\r", "+", "frames", "[", "i", "++", "%", "len", "]", ")", ";", "}", ",", "'Waiting for file changes'", ".", "white", ")", ";", "}" ]
Display a spinner in the terminal the the users receive feedback and know that we are watching their files for changes. @param {Boolean} silent no logging output @api private
[ "Display", "a", "spinner", "in", "the", "terminal", "the", "the", "users", "receive", "feedback", "and", "know", "that", "we", "are", "watching", "their", "files", "for", "changes", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/cli.js#L208-L223
train
observing/square
plugins/minify.js
full
function full(source) { for (var i = 0, item; i < source.length; i++) { item = source.splice(i, 1)[0]; seen.push(item); if (source.length === 0) permutations.push(seen.slice()); full(source); source.splice(i, 0, item); seen.pop(); } return permutations; }
javascript
function full(source) { for (var i = 0, item; i < source.length; i++) { item = source.splice(i, 1)[0]; seen.push(item); if (source.length === 0) permutations.push(seen.slice()); full(source); source.splice(i, 0, item); seen.pop(); } return permutations; }
[ "function", "full", "(", "source", ")", "{", "for", "(", "var", "i", "=", "0", ",", "item", ";", "i", "<", "source", ".", "length", ";", "i", "++", ")", "{", "item", "=", "source", ".", "splice", "(", "i", ",", "1", ")", "[", "0", "]", ";", "seen", ".", "push", "(", "item", ")", ";", "if", "(", "source", ".", "length", "===", "0", ")", "permutations", ".", "push", "(", "seen", ".", "slice", "(", ")", ")", ";", "full", "(", "source", ")", ";", "source", ".", "splice", "(", "i", ",", "0", ",", "item", ")", ";", "seen", ".", "pop", "(", ")", ";", "}", "return", "permutations", ";", "}" ]
Full iterator for the permutations @param {Array} source @returns {Array} permutations @api private
[ "Full", "iterator", "for", "the", "permutations" ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/minify.js#L278-L291
train
observing/square
plugins/minify.js
fast
function fast(source) { var i = source.length; while (i--) { combinations.push(source.slice(0, i + 1)); if (i === 1) fast(source.slice(i)); } return combinations; }
javascript
function fast(source) { var i = source.length; while (i--) { combinations.push(source.slice(0, i + 1)); if (i === 1) fast(source.slice(i)); } return combinations; }
[ "function", "fast", "(", "source", ")", "{", "var", "i", "=", "source", ".", "length", ";", "while", "(", "i", "--", ")", "{", "combinations", ".", "push", "(", "source", ".", "slice", "(", "0", ",", "i", "+", "1", ")", ")", ";", "if", "(", "i", "===", "1", ")", "fast", "(", "source", ".", "slice", "(", "i", ")", ")", ";", "}", "return", "combinations", ";", "}" ]
Fast iterator for the combinations @param {Array} source @returns {Array} combinations @api private
[ "Fast", "iterator", "for", "the", "combinations" ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/minify.js#L300-L309
train
observing/square
lib/watch.js
Watcher
function Watcher(square, port, silent) { var self = this; this.square = square; this.silent = silent || false; this.socket = this.live.call(this, port); this.config = path.resolve(process.env.PWD, this.square.package.location); // Initialize the live reload, also trigger watching and process the file list. this.init = function init() { self.watch.apply(self, arguments[1]); }; // Require fs.notify and findit, trigger the watch. async.parallel([canihaz['fs.notify'], canihaz.findit], this.init); }
javascript
function Watcher(square, port, silent) { var self = this; this.square = square; this.silent = silent || false; this.socket = this.live.call(this, port); this.config = path.resolve(process.env.PWD, this.square.package.location); // Initialize the live reload, also trigger watching and process the file list. this.init = function init() { self.watch.apply(self, arguments[1]); }; // Require fs.notify and findit, trigger the watch. async.parallel([canihaz['fs.notify'], canihaz.findit], this.init); }
[ "function", "Watcher", "(", "square", ",", "port", ",", "silent", ")", "{", "var", "self", "=", "this", ";", "this", ".", "square", "=", "square", ";", "this", ".", "silent", "=", "silent", "||", "false", ";", "this", ".", "socket", "=", "this", ".", "live", ".", "call", "(", "this", ",", "port", ")", ";", "this", ".", "config", "=", "path", ".", "resolve", "(", "process", ".", "env", ".", "PWD", ",", "this", ".", "square", ".", "package", ".", "location", ")", ";", "this", ".", "init", "=", "function", "init", "(", ")", "{", "self", ".", "watch", ".", "apply", "(", "self", ",", "arguments", "[", "1", "]", ")", ";", "}", ";", "async", ".", "parallel", "(", "[", "canihaz", "[", "'fs.notify'", "]", ",", "canihaz", ".", "findit", "]", ",", "this", ".", "init", ")", ";", "}" ]
Constructor for a watcher. @constructor @param {object} square instance @param {Number} port socket.io reload port @param {Boolean} silent no logging at all @api public
[ "Constructor", "for", "a", "watcher", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/watch.js#L24-L39
train
observing/square
lib/watch.js
getPath
function getPath(path, callback) { fs.lstat(path, function(err, stats) { if(err) return callback(err); // Check if it's a link if(stats.isSymbolicLink()) fs.readlink(path, callback); callback(err, path); }); }
javascript
function getPath(path, callback) { fs.lstat(path, function(err, stats) { if(err) return callback(err); // Check if it's a link if(stats.isSymbolicLink()) fs.readlink(path, callback); callback(err, path); }); }
[ "function", "getPath", "(", "path", ",", "callback", ")", "{", "fs", ".", "lstat", "(", "path", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "if", "(", "stats", ".", "isSymbolicLink", "(", ")", ")", "fs", ".", "readlink", "(", "path", ",", "callback", ")", ";", "callback", "(", "err", ",", "path", ")", ";", "}", ")", ";", "}" ]
Helper for finder to also handle symlinks. @param {String} path @param {Function} callback @api private
[ "Helper", "for", "finder", "to", "also", "handle", "symlinks", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/watch.js#L48-L57
train
observing/square
lib/watch.js
filter
function filter(location) { var file = path.basename(location) , vim = file.charAt(file.length - 1) === '~' , extension = path.extname(location).slice(1); // filter out the duplicates if (~changes.indexOf(location) || vim) return; changes.push(location); process.nextTick(limited); }
javascript
function filter(location) { var file = path.basename(location) , vim = file.charAt(file.length - 1) === '~' , extension = path.extname(location).slice(1); // filter out the duplicates if (~changes.indexOf(location) || vim) return; changes.push(location); process.nextTick(limited); }
[ "function", "filter", "(", "location", ")", "{", "var", "file", "=", "path", ".", "basename", "(", "location", ")", ",", "vim", "=", "file", ".", "charAt", "(", "file", ".", "length", "-", "1", ")", "===", "'~'", ",", "extension", "=", "path", ".", "extname", "(", "location", ")", ".", "slice", "(", "1", ")", ";", "if", "(", "~", "changes", ".", "indexOf", "(", "location", ")", "||", "vim", ")", "return", ";", "changes", ".", "push", "(", "location", ")", ";", "process", ".", "nextTick", "(", "limited", ")", ";", "}" ]
Filter out the bad files and try to remove some noise. For example vim generates some silly swap files in directories or other silly thumb files The this context of this file will be set the current directory that we are watching. @param {String} file @api private
[ "Filter", "out", "the", "bad", "files", "and", "try", "to", "remove", "some", "noise", ".", "For", "example", "vim", "generates", "some", "silly", "swap", "files", "in", "directories", "or", "other", "silly", "thumb", "files" ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/watch.js#L195-L205
train
observing/square
plugins/update.js
done
function done(err, content) { if (err) return cb(err); var code = JSON.parse(self.square.package.source) , current = bundle.version || self.version(bundle.meta.content) , source; code.bundle[key].version = version; bundle.version = version; bundle.content = content; // now that we have updated the shizzle, we can write a new file // also update the old source with the new version source = JSON.stringify(code, null, 2); self.square.package.source = source; try { async.parallel([ async.apply(fs.writeFile, self.square.package.location, source) , async.apply(fs.writeFile, bundle.meta.location, content) ], function (err, results) { self.square.logger.notice( 'sucessfully updated %s from version %s to %s' , key , current.grey , version.green ); cb(err); }); } catch (e) { err = e; } }
javascript
function done(err, content) { if (err) return cb(err); var code = JSON.parse(self.square.package.source) , current = bundle.version || self.version(bundle.meta.content) , source; code.bundle[key].version = version; bundle.version = version; bundle.content = content; // now that we have updated the shizzle, we can write a new file // also update the old source with the new version source = JSON.stringify(code, null, 2); self.square.package.source = source; try { async.parallel([ async.apply(fs.writeFile, self.square.package.location, source) , async.apply(fs.writeFile, bundle.meta.location, content) ], function (err, results) { self.square.logger.notice( 'sucessfully updated %s from version %s to %s' , key , current.grey , version.green ); cb(err); }); } catch (e) { err = e; } }
[ "function", "done", "(", "err", ",", "content", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "var", "code", "=", "JSON", ".", "parse", "(", "self", ".", "square", ".", "package", ".", "source", ")", ",", "current", "=", "bundle", ".", "version", "||", "self", ".", "version", "(", "bundle", ".", "meta", ".", "content", ")", ",", "source", ";", "code", ".", "bundle", "[", "key", "]", ".", "version", "=", "version", ";", "bundle", ".", "version", "=", "version", ";", "bundle", ".", "content", "=", "content", ";", "source", "=", "JSON", ".", "stringify", "(", "code", ",", "null", ",", "2", ")", ";", "self", ".", "square", ".", "package", ".", "source", "=", "source", ";", "try", "{", "async", ".", "parallel", "(", "[", "async", ".", "apply", "(", "fs", ".", "writeFile", ",", "self", ".", "square", ".", "package", ".", "location", ",", "source", ")", ",", "async", ".", "apply", "(", "fs", ".", "writeFile", ",", "bundle", ".", "meta", ".", "location", ",", "content", ")", "]", ",", "function", "(", "err", ",", "results", ")", "{", "self", ".", "square", ".", "logger", ".", "notice", "(", "'sucessfully updated %s from version %s to %s'", ",", "key", ",", "current", ".", "grey", ",", "version", ".", "green", ")", ";", "cb", "(", "err", ")", ";", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "err", "=", "e", ";", "}", "}" ]
Handle file upgrades. @param {Mixed} err @param {String} content @api private
[ "Handle", "file", "upgrades", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/update.js#L156-L187
train
observing/square
plugins/lib/child.js
compile
function compile (extension, content, options, fn) { // allow optional options argument if (_.isFunction(options)) { fn = options; options = {}; } var config = _.clone(compile.configuration) , args = flags.slice(0) , buffer = '' , errors = '' , compressor; if (compile.configuration.type) { config.type = extension; } // generate the --key value options, both the key and the value should added // seperately to the `args` array or the child_process will chocke. Object.keys(config).filter(function filter (option) { return config[option]; }).forEach(function format (option) { var bool = _.isBoolean(config[option]); if (!bool || config[option]) { args.push('--' + option); if (!bool) args.push(config[option]); } }); // apply the configuration _.extend(config, options); // spawn the shit and set the correct encoding compressor = spawn(type, args); compressor.stdout.setEncoding('utf8'); compressor.stderr.setEncoding('utf8'); /** * Buffer up the results so we can concat them once the compression is * finished. * * @param {Buffer} chunk * @api private */ compressor.stdout.on('data', function data (chunk) { buffer += chunk; }); compressor.stderr.on('data', function data (err) { errors += err; }); /** * The compressor has finished can we now process the data and see if it was * a success. * * @param {Number} code * @api private */ compressor.on('close', function close (code) { // invalid states if (errors.length) return fn(new Error(errors)); if (code !== 0) return fn(new Error('process exited with code ' + code)); if (!buffer.length) return fn(new Error('no data returned ' + type + args)); // correctly processed the data fn(null, buffer); }); // write out the content that needs to be minified compressor.stdin.end(content); }
javascript
function compile (extension, content, options, fn) { // allow optional options argument if (_.isFunction(options)) { fn = options; options = {}; } var config = _.clone(compile.configuration) , args = flags.slice(0) , buffer = '' , errors = '' , compressor; if (compile.configuration.type) { config.type = extension; } // generate the --key value options, both the key and the value should added // seperately to the `args` array or the child_process will chocke. Object.keys(config).filter(function filter (option) { return config[option]; }).forEach(function format (option) { var bool = _.isBoolean(config[option]); if (!bool || config[option]) { args.push('--' + option); if (!bool) args.push(config[option]); } }); // apply the configuration _.extend(config, options); // spawn the shit and set the correct encoding compressor = spawn(type, args); compressor.stdout.setEncoding('utf8'); compressor.stderr.setEncoding('utf8'); /** * Buffer up the results so we can concat them once the compression is * finished. * * @param {Buffer} chunk * @api private */ compressor.stdout.on('data', function data (chunk) { buffer += chunk; }); compressor.stderr.on('data', function data (err) { errors += err; }); /** * The compressor has finished can we now process the data and see if it was * a success. * * @param {Number} code * @api private */ compressor.on('close', function close (code) { // invalid states if (errors.length) return fn(new Error(errors)); if (code !== 0) return fn(new Error('process exited with code ' + code)); if (!buffer.length) return fn(new Error('no data returned ' + type + args)); // correctly processed the data fn(null, buffer); }); // write out the content that needs to be minified compressor.stdin.end(content); }
[ "function", "compile", "(", "extension", ",", "content", ",", "options", ",", "fn", ")", "{", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "fn", "=", "options", ";", "options", "=", "{", "}", ";", "}", "var", "config", "=", "_", ".", "clone", "(", "compile", ".", "configuration", ")", ",", "args", "=", "flags", ".", "slice", "(", "0", ")", ",", "buffer", "=", "''", ",", "errors", "=", "''", ",", "compressor", ";", "if", "(", "compile", ".", "configuration", ".", "type", ")", "{", "config", ".", "type", "=", "extension", ";", "}", "Object", ".", "keys", "(", "config", ")", ".", "filter", "(", "function", "filter", "(", "option", ")", "{", "return", "config", "[", "option", "]", ";", "}", ")", ".", "forEach", "(", "function", "format", "(", "option", ")", "{", "var", "bool", "=", "_", ".", "isBoolean", "(", "config", "[", "option", "]", ")", ";", "if", "(", "!", "bool", "||", "config", "[", "option", "]", ")", "{", "args", ".", "push", "(", "'--'", "+", "option", ")", ";", "if", "(", "!", "bool", ")", "args", ".", "push", "(", "config", "[", "option", "]", ")", ";", "}", "}", ")", ";", "_", ".", "extend", "(", "config", ",", "options", ")", ";", "compressor", "=", "spawn", "(", "type", ",", "args", ")", ";", "compressor", ".", "stdout", ".", "setEncoding", "(", "'utf8'", ")", ";", "compressor", ".", "stderr", ".", "setEncoding", "(", "'utf8'", ")", ";", "compressor", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "data", "(", "chunk", ")", "{", "buffer", "+=", "chunk", ";", "}", ")", ";", "compressor", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "data", "(", "err", ")", "{", "errors", "+=", "err", ";", "}", ")", ";", "compressor", ".", "on", "(", "'close'", ",", "function", "close", "(", "code", ")", "{", "if", "(", "errors", ".", "length", ")", "return", "fn", "(", "new", "Error", "(", "errors", ")", ")", ";", "if", "(", "code", "!==", "0", ")", "return", "fn", "(", "new", "Error", "(", "'process exited with code '", "+", "code", ")", ")", ";", "if", "(", "!", "buffer", ".", "length", ")", "return", "fn", "(", "new", "Error", "(", "'no data returned '", "+", "type", "+", "args", ")", ")", ";", "fn", "(", "null", ",", "buffer", ")", ";", "}", ")", ";", "compressor", ".", "stdin", ".", "end", "(", "content", ")", ";", "}" ]
Delegrate all the hard core processing to the vendor file. @param {String} extension file extenstion @param {String} content file contents @param {Object} options options @param {Function} fn error first callback @api public
[ "Delegrate", "all", "the", "hard", "core", "processing", "to", "the", "vendor", "file", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lib/child.js#L31-L105
train
observing/square
plugins/lib/crusher.js
message
function message(worker, task) { var callback = worker.queue[task.id] , err; // Rebuild the Error object so we can pass it to our callbacks if (task.err) { err = new Error(task.err.message); err.stack = task.err.stack; } // Kill the whole fucking system, we are in a fucked up state and should die // badly, so just throw something and have the process.uncaughtException // handle it. if (!callback) { if (err) console.error(err); console.error(task); throw new Error('Unable to process message from worker, can\'t locate the callback!'); } callback(err, task); delete worker.queue[task.id]; }
javascript
function message(worker, task) { var callback = worker.queue[task.id] , err; // Rebuild the Error object so we can pass it to our callbacks if (task.err) { err = new Error(task.err.message); err.stack = task.err.stack; } // Kill the whole fucking system, we are in a fucked up state and should die // badly, so just throw something and have the process.uncaughtException // handle it. if (!callback) { if (err) console.error(err); console.error(task); throw new Error('Unable to process message from worker, can\'t locate the callback!'); } callback(err, task); delete worker.queue[task.id]; }
[ "function", "message", "(", "worker", ",", "task", ")", "{", "var", "callback", "=", "worker", ".", "queue", "[", "task", ".", "id", "]", ",", "err", ";", "if", "(", "task", ".", "err", ")", "{", "err", "=", "new", "Error", "(", "task", ".", "err", ".", "message", ")", ";", "err", ".", "stack", "=", "task", ".", "err", ".", "stack", ";", "}", "if", "(", "!", "callback", ")", "{", "if", "(", "err", ")", "console", ".", "error", "(", "err", ")", ";", "console", ".", "error", "(", "task", ")", ";", "throw", "new", "Error", "(", "'Unable to process message from worker, can\\'t locate the callback!'", ")", ";", "}", "\\'", "callback", "(", "err", ",", "task", ")", ";", "}" ]
Message handler for the workers. @param {Worker} worker @param {Error} err @param {Object} task the updated task @api private
[ "Message", "handler", "for", "the", "workers", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lib/crusher.js#L264-L285
train
observing/square
plugin.js
Plugin
function Plugin(square, collection) { if (!(this instanceof Plugin)) return new Plugin(square, collection); if (!square) throw new Error('Missing square instance'); if (!collection) throw new Error('Missing collection'); var self = this; this.square = square; // Reference to the current square instance. this.async = async; // Handle async operation. this._ = _; // Utilities. this.logger = {}; // Our logging utility. this.collection = collection; // Reference to the original collection. // Provide a default namespace to the logging method, we are going to prefix // it with the plugin's name which will help with the debug ability of this // module. Object.keys(square.logger.levels).forEach(function generate(level) { self.logger[level] = square.logger[level].bind( square.logger , '[plugin::'+ self.id +']' ); }); // Merge the given collection with the plugin, but don't override the default // values. Object.keys(collection).forEach(function each(key) { self[key] = collection[key]; }); // Force an async nature of the plugin interface, this also allows us to // attach or listen to methods after we have constructed the plugin. process.nextTick(this.configure.bind(this)); }
javascript
function Plugin(square, collection) { if (!(this instanceof Plugin)) return new Plugin(square, collection); if (!square) throw new Error('Missing square instance'); if (!collection) throw new Error('Missing collection'); var self = this; this.square = square; // Reference to the current square instance. this.async = async; // Handle async operation. this._ = _; // Utilities. this.logger = {}; // Our logging utility. this.collection = collection; // Reference to the original collection. // Provide a default namespace to the logging method, we are going to prefix // it with the plugin's name which will help with the debug ability of this // module. Object.keys(square.logger.levels).forEach(function generate(level) { self.logger[level] = square.logger[level].bind( square.logger , '[plugin::'+ self.id +']' ); }); // Merge the given collection with the plugin, but don't override the default // values. Object.keys(collection).forEach(function each(key) { self[key] = collection[key]; }); // Force an async nature of the plugin interface, this also allows us to // attach or listen to methods after we have constructed the plugin. process.nextTick(this.configure.bind(this)); }
[ "function", "Plugin", "(", "square", ",", "collection", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Plugin", ")", ")", "return", "new", "Plugin", "(", "square", ",", "collection", ")", ";", "if", "(", "!", "square", ")", "throw", "new", "Error", "(", "'Missing square instance'", ")", ";", "if", "(", "!", "collection", ")", "throw", "new", "Error", "(", "'Missing collection'", ")", ";", "var", "self", "=", "this", ";", "this", ".", "square", "=", "square", ";", "this", ".", "async", "=", "async", ";", "this", ".", "_", "=", "_", ";", "this", ".", "logger", "=", "{", "}", ";", "this", ".", "collection", "=", "collection", ";", "Object", ".", "keys", "(", "square", ".", "logger", ".", "levels", ")", ".", "forEach", "(", "function", "generate", "(", "level", ")", "{", "self", ".", "logger", "[", "level", "]", "=", "square", ".", "logger", "[", "level", "]", ".", "bind", "(", "square", ".", "logger", ",", "'[plugin::'", "+", "self", ".", "id", "+", "']'", ")", ";", "}", ")", ";", "Object", ".", "keys", "(", "collection", ")", ".", "forEach", "(", "function", "each", "(", "key", ")", "{", "self", "[", "key", "]", "=", "collection", "[", "key", "]", ";", "}", ")", ";", "process", ".", "nextTick", "(", "this", ".", "configure", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Plugin interface for square. @constructor @param {Square} square @param {Object} collection @api public
[ "Plugin", "interface", "for", "square", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugin.js#L32-L64
train
observing/square
plugin.js
configure
function configure() { var pkg = this.square.package , configuration = pkg.configuration , type = this.type || Plugin.modifier , self = this , load = []; // Check for the distribution and if it should accept the given extension, // extend self with the context of the plugin. if (!~type.indexOf('once') && (!this.distributable() || !this.accepted())) { this.logger.debug( 'disregarding this plugin for extension: '+ this.extension +', distribution: '+ this.distribution ); return this.emit('disregard'); } // Check if there are any configuration options in the package. if (_.isObject(pkg.plugins) && this.id in pkg.plugins) { this.merge(this, pkg.plugins[this.id]); } // Merge in the plugin configuration. if ( configuration && _.isObject(configuration.plugins) && this.id in configuration.plugins ) { this.merge(this, configuration.plugins[this.id]); } // Check if the bundle it self also had specific configurations for this // plugin. if (this.id in this && _.isObject(this[this.id])) { this.merge(this, this[this.id]); } // Ensure that our requires is an array, before we continue if (!Array.isArray(this.requires)) this.requires = [this.requires]; // Check if we need to lazy load any dependencies if (this.requires && this.requires.length) { load = this.requires.map(function (file) { if (typeof file !== 'object') return file; if (!('extension' in file)) return file.name || file; if (file.extension === self.extension) return file.name || file; return undefined; }).filter(Boolean); // Only get existing files // Only fetch shizzle when we actually have shizzle to fetch here if (load.length) return canihaz.apply(canihaz, load.concat(function canihaz(err) { if (err) return self.emit('error', err); // Add all the libraries to the context, the `canihaz#all` returns an // error first, and then all libraries it installed or required in the // order as given to it, which is in our case the `this.requires` order. Array.prototype.slice.call(arguments, 1).forEach(function (lib, index) { self[load[index]] = lib; }); // We are now fully initialized. if (self.initialize) self.initialize(); })); } // We are now fully initialized. if (self.initialize) self.initialize(); }
javascript
function configure() { var pkg = this.square.package , configuration = pkg.configuration , type = this.type || Plugin.modifier , self = this , load = []; // Check for the distribution and if it should accept the given extension, // extend self with the context of the plugin. if (!~type.indexOf('once') && (!this.distributable() || !this.accepted())) { this.logger.debug( 'disregarding this plugin for extension: '+ this.extension +', distribution: '+ this.distribution ); return this.emit('disregard'); } // Check if there are any configuration options in the package. if (_.isObject(pkg.plugins) && this.id in pkg.plugins) { this.merge(this, pkg.plugins[this.id]); } // Merge in the plugin configuration. if ( configuration && _.isObject(configuration.plugins) && this.id in configuration.plugins ) { this.merge(this, configuration.plugins[this.id]); } // Check if the bundle it self also had specific configurations for this // plugin. if (this.id in this && _.isObject(this[this.id])) { this.merge(this, this[this.id]); } // Ensure that our requires is an array, before we continue if (!Array.isArray(this.requires)) this.requires = [this.requires]; // Check if we need to lazy load any dependencies if (this.requires && this.requires.length) { load = this.requires.map(function (file) { if (typeof file !== 'object') return file; if (!('extension' in file)) return file.name || file; if (file.extension === self.extension) return file.name || file; return undefined; }).filter(Boolean); // Only get existing files // Only fetch shizzle when we actually have shizzle to fetch here if (load.length) return canihaz.apply(canihaz, load.concat(function canihaz(err) { if (err) return self.emit('error', err); // Add all the libraries to the context, the `canihaz#all` returns an // error first, and then all libraries it installed or required in the // order as given to it, which is in our case the `this.requires` order. Array.prototype.slice.call(arguments, 1).forEach(function (lib, index) { self[load[index]] = lib; }); // We are now fully initialized. if (self.initialize) self.initialize(); })); } // We are now fully initialized. if (self.initialize) self.initialize(); }
[ "function", "configure", "(", ")", "{", "var", "pkg", "=", "this", ".", "square", ".", "package", ",", "configuration", "=", "pkg", ".", "configuration", ",", "type", "=", "this", ".", "type", "||", "Plugin", ".", "modifier", ",", "self", "=", "this", ",", "load", "=", "[", "]", ";", "if", "(", "!", "~", "type", ".", "indexOf", "(", "'once'", ")", "&&", "(", "!", "this", ".", "distributable", "(", ")", "||", "!", "this", ".", "accepted", "(", ")", ")", ")", "{", "this", ".", "logger", ".", "debug", "(", "'disregarding this plugin for extension: '", "+", "this", ".", "extension", "+", "', distribution: '", "+", "this", ".", "distribution", ")", ";", "return", "this", ".", "emit", "(", "'disregard'", ")", ";", "}", "if", "(", "_", ".", "isObject", "(", "pkg", ".", "plugins", ")", "&&", "this", ".", "id", "in", "pkg", ".", "plugins", ")", "{", "this", ".", "merge", "(", "this", ",", "pkg", ".", "plugins", "[", "this", ".", "id", "]", ")", ";", "}", "if", "(", "configuration", "&&", "_", ".", "isObject", "(", "configuration", ".", "plugins", ")", "&&", "this", ".", "id", "in", "configuration", ".", "plugins", ")", "{", "this", ".", "merge", "(", "this", ",", "configuration", ".", "plugins", "[", "this", ".", "id", "]", ")", ";", "}", "if", "(", "this", ".", "id", "in", "this", "&&", "_", ".", "isObject", "(", "this", "[", "this", ".", "id", "]", ")", ")", "{", "this", ".", "merge", "(", "this", ",", "this", "[", "this", ".", "id", "]", ")", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "this", ".", "requires", ")", ")", "this", ".", "requires", "=", "[", "this", ".", "requires", "]", ";", "if", "(", "this", ".", "requires", "&&", "this", ".", "requires", ".", "length", ")", "{", "load", "=", "this", ".", "requires", ".", "map", "(", "function", "(", "file", ")", "{", "if", "(", "typeof", "file", "!==", "'object'", ")", "return", "file", ";", "if", "(", "!", "(", "'extension'", "in", "file", ")", ")", "return", "file", ".", "name", "||", "file", ";", "if", "(", "file", ".", "extension", "===", "self", ".", "extension", ")", "return", "file", ".", "name", "||", "file", ";", "return", "undefined", ";", "}", ")", ".", "filter", "(", "Boolean", ")", ";", "if", "(", "load", ".", "length", ")", "return", "canihaz", ".", "apply", "(", "canihaz", ",", "load", ".", "concat", "(", "function", "canihaz", "(", "err", ")", "{", "if", "(", "err", ")", "return", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ".", "forEach", "(", "function", "(", "lib", ",", "index", ")", "{", "self", "[", "load", "[", "index", "]", "]", "=", "lib", ";", "}", ")", ";", "if", "(", "self", ".", "initialize", ")", "self", ".", "initialize", "(", ")", ";", "}", ")", ")", ";", "}", "if", "(", "self", ".", "initialize", ")", "self", ".", "initialize", "(", ")", ";", "}" ]
Configure the plugin, prepare all the things. @api private
[ "Configure", "the", "plugin", "prepare", "all", "the", "things", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugin.js#L128-L196
train
observing/square
plugins/lint.js
parser
function parser (content, options, fn) { var jshintrc = path.join(process.env.HOME || process.env.USERPROFILE, '.jshintrc') , jshintninja = configurator(jshintrc) , config = options.jshint; // extend all the things config = _.extend(config, jshintninja); canihaz.jshint(function lazyload (err, jshint) { if (err) return fn(err); var validates = jshint.JSHINT(content, config) , errors; if (!validates) errors = formatters.js(jshint.JSHINT.errors); fn(null, errors); }); }
javascript
function parser (content, options, fn) { var jshintrc = path.join(process.env.HOME || process.env.USERPROFILE, '.jshintrc') , jshintninja = configurator(jshintrc) , config = options.jshint; // extend all the things config = _.extend(config, jshintninja); canihaz.jshint(function lazyload (err, jshint) { if (err) return fn(err); var validates = jshint.JSHINT(content, config) , errors; if (!validates) errors = formatters.js(jshint.JSHINT.errors); fn(null, errors); }); }
[ "function", "parser", "(", "content", ",", "options", ",", "fn", ")", "{", "var", "jshintrc", "=", "path", ".", "join", "(", "process", ".", "env", ".", "HOME", "||", "process", ".", "env", ".", "USERPROFILE", ",", "'.jshintrc'", ")", ",", "jshintninja", "=", "configurator", "(", "jshintrc", ")", ",", "config", "=", "options", ".", "jshint", ";", "config", "=", "_", ".", "extend", "(", "config", ",", "jshintninja", ")", ";", "canihaz", ".", "jshint", "(", "function", "lazyload", "(", "err", ",", "jshint", ")", "{", "if", "(", "err", ")", "return", "fn", "(", "err", ")", ";", "var", "validates", "=", "jshint", ".", "JSHINT", "(", "content", ",", "config", ")", ",", "errors", ";", "if", "(", "!", "validates", ")", "errors", "=", "formatters", ".", "js", "(", "jshint", ".", "JSHINT", ".", "errors", ")", ";", "fn", "(", "null", ",", "errors", ")", ";", "}", ")", ";", "}" ]
JSHint the content @param {String} content @param {Object} options @param {Function} fn @api private
[ "JSHint", "the", "content" ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lint.js#L127-L144
train
observing/square
plugins/lint.js
formatter
function formatter (fail) { return fail.map(function oops (err) { return { line: err.line , column: err.character , message: err.reason , ref: err }; }); }
javascript
function formatter (fail) { return fail.map(function oops (err) { return { line: err.line , column: err.character , message: err.reason , ref: err }; }); }
[ "function", "formatter", "(", "fail", ")", "{", "return", "fail", ".", "map", "(", "function", "oops", "(", "err", ")", "{", "return", "{", "line", ":", "err", ".", "line", ",", "column", ":", "err", ".", "character", ",", "message", ":", "err", ".", "reason", ",", "ref", ":", "err", "}", ";", "}", ")", ";", "}" ]
Format the output of the jshint tool. @param {Array} fail @returns {Array} @api private
[ "Format", "the", "output", "of", "the", "jshint", "tool", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lint.js#L192-L201
train
observing/square
plugins/lint.js
function (file, errors, options) { var reports = [] , content = file.content.split('\n'); errors.forEach(function error (err) { // some linters don't return the location -_- if (!err.line) return reports.push(err.message.grey, ''); var start = err.line > 3 ? err.line - 3 : 0 , stop = err.line + 2 , range = content.slice(start, stop) , numbers = _.range(start + 1, stop + 1) , len = stop.toString().length; reports.push('Lint error: ' + err.line + ' col ' + err.column); range.map(function reformat (line) { var lineno = numbers.shift() , offender = lineno === err.line , inline = /\'[^\']+?\'/ , slice; // this is the actual line with the error, so we should start finding // what the error is and how we could highlight it in the output if (offender) { if (line.length < err.column) { // we are missing something at the end of the line.. so add a red // square line += ' '.inverse.red; } else { // we have a direct match on a statement if (inline.test(err.message)) { slice = err.message.match(inline)[0].replace(/\'/g, ''); } else { // it's happening in the center of things, so we can start // coloring inside the shizzle slice = line.slice(err.column - 1); } line = line.replace(slice, slice.inverse.red); } } reports.push(' ' + pad(lineno, len) + ' | ' + line); }); reports.push(''); reports.push(err.message.grey); reports.push(''); }); // output the shizzle reports.forEach(function output (line) { this.logger.error(line); }.bind(this)); }
javascript
function (file, errors, options) { var reports = [] , content = file.content.split('\n'); errors.forEach(function error (err) { // some linters don't return the location -_- if (!err.line) return reports.push(err.message.grey, ''); var start = err.line > 3 ? err.line - 3 : 0 , stop = err.line + 2 , range = content.slice(start, stop) , numbers = _.range(start + 1, stop + 1) , len = stop.toString().length; reports.push('Lint error: ' + err.line + ' col ' + err.column); range.map(function reformat (line) { var lineno = numbers.shift() , offender = lineno === err.line , inline = /\'[^\']+?\'/ , slice; // this is the actual line with the error, so we should start finding // what the error is and how we could highlight it in the output if (offender) { if (line.length < err.column) { // we are missing something at the end of the line.. so add a red // square line += ' '.inverse.red; } else { // we have a direct match on a statement if (inline.test(err.message)) { slice = err.message.match(inline)[0].replace(/\'/g, ''); } else { // it's happening in the center of things, so we can start // coloring inside the shizzle slice = line.slice(err.column - 1); } line = line.replace(slice, slice.inverse.red); } } reports.push(' ' + pad(lineno, len) + ' | ' + line); }); reports.push(''); reports.push(err.message.grey); reports.push(''); }); // output the shizzle reports.forEach(function output (line) { this.logger.error(line); }.bind(this)); }
[ "function", "(", "file", ",", "errors", ",", "options", ")", "{", "var", "reports", "=", "[", "]", ",", "content", "=", "file", ".", "content", ".", "split", "(", "'\\n'", ")", ";", "\\n", "errors", ".", "forEach", "(", "function", "error", "(", "err", ")", "{", "if", "(", "!", "err", ".", "line", ")", "return", "reports", ".", "push", "(", "err", ".", "message", ".", "grey", ",", "''", ")", ";", "var", "start", "=", "err", ".", "line", ">", "3", "?", "err", ".", "line", "-", "3", ":", "0", ",", "stop", "=", "err", ".", "line", "+", "2", ",", "range", "=", "content", ".", "slice", "(", "start", ",", "stop", ")", ",", "numbers", "=", "_", ".", "range", "(", "start", "+", "1", ",", "stop", "+", "1", ")", ",", "len", "=", "stop", ".", "toString", "(", ")", ".", "length", ";", "reports", ".", "push", "(", "'Lint error: '", "+", "err", ".", "line", "+", "' col '", "+", "err", ".", "column", ")", ";", "range", ".", "map", "(", "function", "reformat", "(", "line", ")", "{", "var", "lineno", "=", "numbers", ".", "shift", "(", ")", ",", "offender", "=", "lineno", "===", "err", ".", "line", ",", "inline", "=", "/", "\\'[^\\']+?\\'", "/", ",", "slice", ";", "if", "(", "offender", ")", "{", "if", "(", "line", ".", "length", "<", "err", ".", "column", ")", "{", "line", "+=", "' '", ".", "inverse", ".", "red", ";", "}", "else", "{", "if", "(", "inline", ".", "test", "(", "err", ".", "message", ")", ")", "{", "slice", "=", "err", ".", "message", ".", "match", "(", "inline", ")", "[", "0", "]", ".", "replace", "(", "/", "\\'", "/", "g", ",", "''", ")", ";", "}", "else", "{", "slice", "=", "line", ".", "slice", "(", "err", ".", "column", "-", "1", ")", ";", "}", "line", "=", "line", ".", "replace", "(", "slice", ",", "slice", ".", "inverse", ".", "red", ")", ";", "}", "}", "reports", ".", "push", "(", "' '", "+", "pad", "(", "lineno", ",", "len", ")", "+", "' | '", "+", "line", ")", ";", "}", ")", ";", "reports", ".", "push", "(", "''", ")", ";", "reports", ".", "push", "(", "err", ".", "message", ".", "grey", ")", ";", "reports", ".", "push", "(", "''", ")", ";", "}", ")", ";", "}" ]
Simple output of the errors in a human readable fashion. @param {Object} file @param {Array} errors @api pprivate
[ "Simple", "output", "of", "the", "errors", "in", "a", "human", "readable", "fashion", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lint.js#L238-L293
train
observing/square
plugins/lint.js
configurator
function configurator (location) { return !(location && fs.existsSync(location)) ? {} : JSON.parse( fs.readFileSync(location, 'UTF-8') .replace(/\/\*[\s\S]*(?:\*\/)/g, '') // removes /* comments */ .replace(/\/\/[^\n\r]*/g, '') // removes // comments ); }
javascript
function configurator (location) { return !(location && fs.existsSync(location)) ? {} : JSON.parse( fs.readFileSync(location, 'UTF-8') .replace(/\/\*[\s\S]*(?:\*\/)/g, '') // removes /* comments */ .replace(/\/\/[^\n\r]*/g, '') // removes // comments ); }
[ "function", "configurator", "(", "location", ")", "{", "return", "!", "(", "location", "&&", "fs", ".", "existsSync", "(", "location", ")", ")", "?", "{", "}", ":", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "location", ",", "'UTF-8'", ")", ".", "replace", "(", "/", "\\/\\*[\\s\\S]*(?:\\*\\/)", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "\\/\\/[^\\n\\r]*", "/", "g", ",", "''", ")", ")", ";", "}" ]
Simple configuration parser, which is less strict then a regular JSON parser. @param {String} path @returns {Object}
[ "Simple", "configuration", "parser", "which", "is", "less", "strict", "then", "a", "regular", "JSON", "parser", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lint.js#L317-L325
train
SilentCicero/ipfs-mini
src/index.js
createBoundary
function createBoundary(data) { while (true) { var boundary = `----IPFSMini${Math.random() * 100000}.${Math.random() * 100000}`; if (data.indexOf(boundary) === -1) { return boundary; } } }
javascript
function createBoundary(data) { while (true) { var boundary = `----IPFSMini${Math.random() * 100000}.${Math.random() * 100000}`; if (data.indexOf(boundary) === -1) { return boundary; } } }
[ "function", "createBoundary", "(", "data", ")", "{", "while", "(", "true", ")", "{", "var", "boundary", "=", "`", "${", "Math", ".", "random", "(", ")", "*", "100000", "}", "${", "Math", ".", "random", "(", ")", "*", "100000", "}", "`", ";", "if", "(", "data", ".", "indexOf", "(", "boundary", ")", "===", "-", "1", ")", "{", "return", "boundary", ";", "}", "}", "}" ]
creates a boundary that isn't part of the payload
[ "creates", "a", "boundary", "that", "isn", "t", "part", "of", "the", "payload" ]
8a007116995ec84e26901b6bd3eb119c6b06aca7
https://github.com/SilentCicero/ipfs-mini/blob/8a007116995ec84e26901b6bd3eb119c6b06aca7/src/index.js#L102-L109
train
larvit/larvitimages
index.js
returnFile
function returnFile(cb) { fs.readFile(fileToLoad, function (err, fileBuf) { if (err || ! fileBuf) { createFile(function (err) { if (err) return cb(err); returnFile(cb); }); return; } cb(null, fileBuf, fileToLoad); }); }
javascript
function returnFile(cb) { fs.readFile(fileToLoad, function (err, fileBuf) { if (err || ! fileBuf) { createFile(function (err) { if (err) return cb(err); returnFile(cb); }); return; } cb(null, fileBuf, fileToLoad); }); }
[ "function", "returnFile", "(", "cb", ")", "{", "fs", ".", "readFile", "(", "fileToLoad", ",", "function", "(", "err", ",", "fileBuf", ")", "{", "if", "(", "err", "||", "!", "fileBuf", ")", "{", "createFile", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "returnFile", "(", "cb", ")", ";", "}", ")", ";", "return", ";", "}", "cb", "(", "null", ",", "fileBuf", ",", "fileToLoad", ")", ";", "}", ")", ";", "}" ]
Check if cached file exists, and if so, return it
[ "Check", "if", "cached", "file", "exists", "and", "if", "so", "return", "it" ]
6f918fc7d6e6e932fb177d9d42106fd6c3daffa1
https://github.com/larvit/larvitimages/blob/6f918fc7d6e6e932fb177d9d42106fd6c3daffa1/index.js#L340-L351
train
nico3333fr/van11y-accessible-modal-window-aria
dist/van11y-accessible-modal-window-aria.js
createOverlay
function createOverlay(config) { var id = MODAL_OVERLAY_ID; var overlayText = config.text || MODAL_OVERLAY_TXT; var overlayClass = config.prefixClass + MODAL_OVERLAY_CLASS_SUFFIX; var overlayBackgroundEnabled = config.backgroundEnabled === 'disabled' ? 'disabled' : 'enabled'; return '<span\n id="' + id + '"\n class="' + overlayClass + '"\n ' + MODAL_OVERLAY_BG_ENABLED_ATTR + '="' + overlayBackgroundEnabled + '"\n title="' + overlayText + '"\n >\n <span class="' + VISUALLY_HIDDEN_CLASS + '">' + overlayText + '</span>\n </span>'; }
javascript
function createOverlay(config) { var id = MODAL_OVERLAY_ID; var overlayText = config.text || MODAL_OVERLAY_TXT; var overlayClass = config.prefixClass + MODAL_OVERLAY_CLASS_SUFFIX; var overlayBackgroundEnabled = config.backgroundEnabled === 'disabled' ? 'disabled' : 'enabled'; return '<span\n id="' + id + '"\n class="' + overlayClass + '"\n ' + MODAL_OVERLAY_BG_ENABLED_ATTR + '="' + overlayBackgroundEnabled + '"\n title="' + overlayText + '"\n >\n <span class="' + VISUALLY_HIDDEN_CLASS + '">' + overlayText + '</span>\n </span>'; }
[ "function", "createOverlay", "(", "config", ")", "{", "var", "id", "=", "MODAL_OVERLAY_ID", ";", "var", "overlayText", "=", "config", ".", "text", "||", "MODAL_OVERLAY_TXT", ";", "var", "overlayClass", "=", "config", ".", "prefixClass", "+", "MODAL_OVERLAY_CLASS_SUFFIX", ";", "var", "overlayBackgroundEnabled", "=", "config", ".", "backgroundEnabled", "===", "'disabled'", "?", "'disabled'", ":", "'enabled'", ";", "return", "'<span\\n id=\"'", "+", "\\n", "+", "id", "+", "'\"\\n class=\"'", "+", "\\n", "+", "overlayClass", "+", "'\"\\n '", "+", "\\n", "+", "MODAL_OVERLAY_BG_ENABLED_ATTR", "+", "'=\"'", "+", "overlayBackgroundEnabled", "+", "'\"\\n title=\"'", "+", "\\n", "+", "overlayText", "+", "'\"\\n >\\n <span class=\"'", ";", "}" ]
Create the template for an overlay @param {Object} config @return {String}
[ "Create", "the", "template", "for", "an", "overlay" ]
77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9
https://github.com/nico3333fr/van11y-accessible-modal-window-aria/blob/77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9/dist/van11y-accessible-modal-window-aria.js#L133-L141
train
nico3333fr/van11y-accessible-modal-window-aria
dist/van11y-accessible-modal-window-aria.js
createModal
function createModal(config) { var id = MODAL_JS_ID; var modalClassName = config.modalPrefixClass + MODAL_CLASS_SUFFIX; var modalClassWrapper = config.modalPrefixClass + MODAL_WRAPPER_CLASS_SUFFIX; var buttonCloseClassName = config.modalPrefixClass + MODAL_BUTTON_CLASS_SUFFIX; var buttonCloseInner = config.modalCloseImgPath ? '<img src="' + config.modalCloseImgPath + '" alt="' + config.modalCloseText + '" class="' + config.modalPrefixClass + MODAL_CLOSE_IMG_CLASS_SUFFIX + '" />' : '<span class="' + config.modalPrefixClass + MODAL_CLOSE_TEXT_CLASS_SUFFIX + '">\n ' + config.modalCloseText + '\n </span>'; var contentClassName = config.modalPrefixClass + MODAL_CONTENT_CLASS_SUFFIX; var titleClassName = config.modalPrefixClass + MODAL_TITLE_CLASS_SUFFIX; var title = config.modalTitle !== '' ? '<h1 id="' + MODAL_TITLE_ID + '" class="' + titleClassName + '">\n ' + config.modalTitle + '\n </h1>' : ''; var button_close = '<button type="button" class="' + MODAL_BUTTON_JS_CLASS + ' ' + buttonCloseClassName + '" id="' + MODAL_BUTTON_JS_ID + '" title="' + config.modalCloseTitle + '" ' + MODAL_BUTTON_CONTENT_BACK_ID + '="' + config.modalContentId + '" ' + MODAL_BUTTON_FOCUS_BACK_ID + '="' + config.modalFocusBackId + '">\n ' + buttonCloseInner + '\n </button>'; var content = config.modalText; var describedById = config.modalDescribedById !== '' ? ATTR_DESCRIBEDBY + '="' + config.modalDescribedById + '"' : ''; // If there is no content but an id we try to fetch content id if (content === '' && config.modalContentId) { var contentFromId = findById(config.modalContentId); if (contentFromId) { content = '<div id="' + MODAL_CONTENT_JS_ID + '">\n ' + contentFromId.innerHTML + '\n </div'; // we remove content from its source to avoid id duplicates, etc. contentFromId.innerHTML = ''; } } return '<dialog id="' + id + '" class="' + modalClassName + '" ' + ATTR_ROLE + '="' + MODAL_ROLE + '" ' + describedById + ' ' + ATTR_OPEN + ' ' + ATTR_LABELLEDBY + '="' + MODAL_TITLE_ID + '">\n <div role="document" class="' + modalClassWrapper + '">\n ' + button_close + '\n <div class="' + contentClassName + '">\n ' + title + '\n ' + content + '\n </div>\n </div>\n </dialog>'; }
javascript
function createModal(config) { var id = MODAL_JS_ID; var modalClassName = config.modalPrefixClass + MODAL_CLASS_SUFFIX; var modalClassWrapper = config.modalPrefixClass + MODAL_WRAPPER_CLASS_SUFFIX; var buttonCloseClassName = config.modalPrefixClass + MODAL_BUTTON_CLASS_SUFFIX; var buttonCloseInner = config.modalCloseImgPath ? '<img src="' + config.modalCloseImgPath + '" alt="' + config.modalCloseText + '" class="' + config.modalPrefixClass + MODAL_CLOSE_IMG_CLASS_SUFFIX + '" />' : '<span class="' + config.modalPrefixClass + MODAL_CLOSE_TEXT_CLASS_SUFFIX + '">\n ' + config.modalCloseText + '\n </span>'; var contentClassName = config.modalPrefixClass + MODAL_CONTENT_CLASS_SUFFIX; var titleClassName = config.modalPrefixClass + MODAL_TITLE_CLASS_SUFFIX; var title = config.modalTitle !== '' ? '<h1 id="' + MODAL_TITLE_ID + '" class="' + titleClassName + '">\n ' + config.modalTitle + '\n </h1>' : ''; var button_close = '<button type="button" class="' + MODAL_BUTTON_JS_CLASS + ' ' + buttonCloseClassName + '" id="' + MODAL_BUTTON_JS_ID + '" title="' + config.modalCloseTitle + '" ' + MODAL_BUTTON_CONTENT_BACK_ID + '="' + config.modalContentId + '" ' + MODAL_BUTTON_FOCUS_BACK_ID + '="' + config.modalFocusBackId + '">\n ' + buttonCloseInner + '\n </button>'; var content = config.modalText; var describedById = config.modalDescribedById !== '' ? ATTR_DESCRIBEDBY + '="' + config.modalDescribedById + '"' : ''; // If there is no content but an id we try to fetch content id if (content === '' && config.modalContentId) { var contentFromId = findById(config.modalContentId); if (contentFromId) { content = '<div id="' + MODAL_CONTENT_JS_ID + '">\n ' + contentFromId.innerHTML + '\n </div'; // we remove content from its source to avoid id duplicates, etc. contentFromId.innerHTML = ''; } } return '<dialog id="' + id + '" class="' + modalClassName + '" ' + ATTR_ROLE + '="' + MODAL_ROLE + '" ' + describedById + ' ' + ATTR_OPEN + ' ' + ATTR_LABELLEDBY + '="' + MODAL_TITLE_ID + '">\n <div role="document" class="' + modalClassWrapper + '">\n ' + button_close + '\n <div class="' + contentClassName + '">\n ' + title + '\n ' + content + '\n </div>\n </div>\n </dialog>'; }
[ "function", "createModal", "(", "config", ")", "{", "var", "id", "=", "MODAL_JS_ID", ";", "var", "modalClassName", "=", "config", ".", "modalPrefixClass", "+", "MODAL_CLASS_SUFFIX", ";", "var", "modalClassWrapper", "=", "config", ".", "modalPrefixClass", "+", "MODAL_WRAPPER_CLASS_SUFFIX", ";", "var", "buttonCloseClassName", "=", "config", ".", "modalPrefixClass", "+", "MODAL_BUTTON_CLASS_SUFFIX", ";", "var", "buttonCloseInner", "=", "config", ".", "modalCloseImgPath", "?", "'<img src=\"'", "+", "config", ".", "modalCloseImgPath", "+", "'\" alt=\"'", "+", "config", ".", "modalCloseText", "+", "'\" class=\"'", "+", "config", ".", "modalPrefixClass", "+", "MODAL_CLOSE_IMG_CLASS_SUFFIX", "+", "'\" />'", ":", "'<span class=\"'", "+", "config", ".", "modalPrefixClass", "+", "MODAL_CLOSE_TEXT_CLASS_SUFFIX", "+", "'\">\\n '", "+", "\\n", "+", "config", ".", "modalCloseText", ";", "'\\n </span>'", "\\n", "var", "contentClassName", "=", "config", ".", "modalPrefixClass", "+", "MODAL_CONTENT_CLASS_SUFFIX", ";", "var", "titleClassName", "=", "config", ".", "modalPrefixClass", "+", "MODAL_TITLE_CLASS_SUFFIX", ";", "var", "title", "=", "config", ".", "modalTitle", "!==", "''", "?", "'<h1 id=\"'", "+", "MODAL_TITLE_ID", "+", "'\" class=\"'", "+", "titleClassName", "+", "'\">\\n '", "+", "\\n", "+", "config", ".", "modalTitle", ":", "'\\n </h1>'", ";", "\\n", "''", "var", "button_close", "=", "'<button type=\"button\" class=\"'", "+", "MODAL_BUTTON_JS_CLASS", "+", "' '", "+", "buttonCloseClassName", "+", "'\" id=\"'", "+", "MODAL_BUTTON_JS_ID", "+", "'\" title=\"'", "+", "config", ".", "modalCloseTitle", "+", "'\" '", "+", "MODAL_BUTTON_CONTENT_BACK_ID", "+", "'=\"'", "+", "config", ".", "modalContentId", "+", "'\" '", "+", "MODAL_BUTTON_FOCUS_BACK_ID", "+", "'=\"'", "+", "config", ".", "modalFocusBackId", "+", "'\">\\n '", "+", "\\n", "+", "buttonCloseInner", ";", "}" ]
Create the template for a modal @param {Object} config @return {String}
[ "Create", "the", "template", "for", "a", "modal" ]
77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9
https://github.com/nico3333fr/van11y-accessible-modal-window-aria/blob/77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9/dist/van11y-accessible-modal-window-aria.js#L148-L173
train
nico3333fr/van11y-accessible-modal-window-aria
dist/van11y-accessible-modal-window-aria.js
$listModals
function $listModals() { var node = arguments.length <= 0 || arguments[0] === undefined ? doc : arguments[0]; return [].slice.call(node.querySelectorAll('.' + MODAL_JS_CLASS)); }
javascript
function $listModals() { var node = arguments.length <= 0 || arguments[0] === undefined ? doc : arguments[0]; return [].slice.call(node.querySelectorAll('.' + MODAL_JS_CLASS)); }
[ "function", "$listModals", "(", ")", "{", "var", "node", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "doc", ":", "arguments", "[", "0", "]", ";", "return", "[", "]", ".", "slice", ".", "call", "(", "node", ".", "querySelectorAll", "(", "'.'", "+", "MODAL_JS_CLASS", ")", ")", ";", "}" ]
Find all modals inside a container @param {Node} node Default document @return {Array}
[ "Find", "all", "modals", "inside", "a", "container" ]
77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9
https://github.com/nico3333fr/van11y-accessible-modal-window-aria/blob/77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9/dist/van11y-accessible-modal-window-aria.js#L199-L202
train