id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
28,900
mportuga/eslint-detailed-reporter
lib/template-generator.js
renderSourceCode
function renderSourceCode(sourceCode, messages, parentIndex) { return codeWrapperTemplate({ parentIndex, sourceCode: _.map(sourceCode.split('\n'), function(code, lineNumber) { const lineMessages = _.filter(messages, {line: lineNumber + 1}), severity = _.get(lineMessages[0], 'severity') || 0; let template = ''; // checks if there is a problem on the current line and renders it if (!_.isEmpty(lineMessages)) { template += _.map(lineMessages, renderIssue).join(''); } // adds a line of code to the template (with line number and severity color if appropriate template += codeTemplate({ lineNumber: lineNumber + 1, code, severity: severityString(severity) }); return template; }).join('\n') }); }
javascript
function renderSourceCode(sourceCode, messages, parentIndex) { return codeWrapperTemplate({ parentIndex, sourceCode: _.map(sourceCode.split('\n'), function(code, lineNumber) { const lineMessages = _.filter(messages, {line: lineNumber + 1}), severity = _.get(lineMessages[0], 'severity') || 0; let template = ''; // checks if there is a problem on the current line and renders it if (!_.isEmpty(lineMessages)) { template += _.map(lineMessages, renderIssue).join(''); } // adds a line of code to the template (with line number and severity color if appropriate template += codeTemplate({ lineNumber: lineNumber + 1, code, severity: severityString(severity) }); return template; }).join('\n') }); }
[ "function", "renderSourceCode", "(", "sourceCode", ",", "messages", ",", "parentIndex", ")", "{", "return", "codeWrapperTemplate", "(", "{", "parentIndex", ",", "sourceCode", ":", "_", ".", "map", "(", "sourceCode", ".", "split", "(", "'\\n'", ")", ",", "fun...
Renders the source code for the files that have issues and marks the lines that have problems @param {string} sourceCode source code string @param {array} messages array of messages with the problems in a file @param {int} parentIndex file index @returns {string} HTML string of the code file that is being linted
[ "Renders", "the", "source", "code", "for", "the", "files", "that", "have", "issues", "and", "marks", "the", "lines", "that", "have", "problems" ]
731af360846962e6bf7d9a92a6e8f96ef2710fb0
https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L163-L187
28,901
mportuga/eslint-detailed-reporter
lib/template-generator.js
renderResultDetails
function renderResultDetails(sourceCode, messages, parentIndex) { const topIssues = messages.length < 10 ? '' : _.groupBy(messages, 'severity'); return resultDetailsTemplate({ parentIndex, sourceCode: renderSourceCode(sourceCode, messages, parentIndex), detailSummary: resultSummaryTemplate({ topIssues: renderSummaryDetails(topIssues), issues: _.map(messages, renderIssue).join('') }) }); }
javascript
function renderResultDetails(sourceCode, messages, parentIndex) { const topIssues = messages.length < 10 ? '' : _.groupBy(messages, 'severity'); return resultDetailsTemplate({ parentIndex, sourceCode: renderSourceCode(sourceCode, messages, parentIndex), detailSummary: resultSummaryTemplate({ topIssues: renderSummaryDetails(topIssues), issues: _.map(messages, renderIssue).join('') }) }); }
[ "function", "renderResultDetails", "(", "sourceCode", ",", "messages", ",", "parentIndex", ")", "{", "const", "topIssues", "=", "messages", ".", "length", "<", "10", "?", "''", ":", "_", ".", "groupBy", "(", "messages", ",", "'severity'", ")", ";", "return...
Renders the result details with tabs for source code and a summary @param {string} sourceCode source code string @param {array} messages array of messages with the problems in a file @param {int} parentIndex file index @returns {string} HTML string of result details
[ "Renders", "the", "result", "details", "with", "tabs", "for", "source", "code", "and", "a", "summary" ]
731af360846962e6bf7d9a92a6e8f96ef2710fb0
https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L196-L207
28,902
mportuga/eslint-detailed-reporter
lib/template-generator.js
renderProblemFiles
function renderProblemFiles(files, currDir) { return _.map(files, function(fileDetails) { return filesTemplate({ fileId: _.camelCase(fileDetails.filePath), filePath: fileDetails.filePath.replace(currDir, ''), errorCount: fileDetails.errorCount, warningCount: fileDetails.warningCount }); }).join('\n'); }
javascript
function renderProblemFiles(files, currDir) { return _.map(files, function(fileDetails) { return filesTemplate({ fileId: _.camelCase(fileDetails.filePath), filePath: fileDetails.filePath.replace(currDir, ''), errorCount: fileDetails.errorCount, warningCount: fileDetails.warningCount }); }).join('\n'); }
[ "function", "renderProblemFiles", "(", "files", ",", "currDir", ")", "{", "return", "_", ".", "map", "(", "files", ",", "function", "(", "fileDetails", ")", "{", "return", "filesTemplate", "(", "{", "fileId", ":", "_", ".", "camelCase", "(", "fileDetails",...
Renders list of problem files @param {array} files @param {String} currDir Current working directory @return {string} HTML string describing the files.
[ "Renders", "list", "of", "problem", "files" ]
731af360846962e6bf7d9a92a6e8f96ef2710fb0
https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L267-L276
28,903
mportuga/eslint-detailed-reporter
lib/template-generator.js
writeFile
function writeFile(filePath, fileContent, regex) { fs.writeFileSync(filePath, fileContent.replace(regex, '')); }
javascript
function writeFile(filePath, fileContent, regex) { fs.writeFileSync(filePath, fileContent.replace(regex, '')); }
[ "function", "writeFile", "(", "filePath", ",", "fileContent", ",", "regex", ")", "{", "fs", ".", "writeFileSync", "(", "filePath", ",", "fileContent", ".", "replace", "(", "regex", ",", "''", ")", ")", ";", "}" ]
Writes a file at the specified location and removes the specified strings @param {string} filePath The path of the new file @param {string} fileContent The contents of the new file @param {RegExp} regex A regex with strings to be removed from the fileContent @return {void} n/a
[ "Writes", "a", "file", "at", "the", "specified", "location", "and", "removes", "the", "specified", "strings" ]
731af360846962e6bf7d9a92a6e8f96ef2710fb0
https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L285-L287
28,904
mportuga/eslint-detailed-reporter
lib/template-generator.js
getOutputDir
function getOutputDir() { const outputOptionIdx = process.argv.indexOf('-o') !== -1 ? process.argv.indexOf('-o') : process.argv.indexOf('--output-file'), argsLength = process.argv.length, outputDirOption = '--outputDirectory='; if (process.argv[1].includes('grunt')) { for (var i = 2; i < argsLength; i++) { if (process.argv[i].includes(outputDirOption)) { return `/${process.argv[i].replace(outputDirOption, '')}`; } } return '/reports/'; // defaults to a reports folder if nothing else is found } else if (outputOptionIdx !== -1) { return `/${process.argv[outputOptionIdx + 1].split('/')[0]}/`; } return ''; }
javascript
function getOutputDir() { const outputOptionIdx = process.argv.indexOf('-o') !== -1 ? process.argv.indexOf('-o') : process.argv.indexOf('--output-file'), argsLength = process.argv.length, outputDirOption = '--outputDirectory='; if (process.argv[1].includes('grunt')) { for (var i = 2; i < argsLength; i++) { if (process.argv[i].includes(outputDirOption)) { return `/${process.argv[i].replace(outputDirOption, '')}`; } } return '/reports/'; // defaults to a reports folder if nothing else is found } else if (outputOptionIdx !== -1) { return `/${process.argv[outputOptionIdx + 1].split('/')[0]}/`; } return ''; }
[ "function", "getOutputDir", "(", ")", "{", "const", "outputOptionIdx", "=", "process", ".", "argv", ".", "indexOf", "(", "'-o'", ")", "!==", "-", "1", "?", "process", ".", "argv", ".", "indexOf", "(", "'-o'", ")", ":", "process", ".", "argv", ".", "i...
Returns the output directory for the report @return {String} the output directory for the report
[ "Returns", "the", "output", "directory", "for", "the", "report" ]
731af360846962e6bf7d9a92a6e8f96ef2710fb0
https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L293-L310
28,905
mportuga/eslint-detailed-reporter
lib/template-generator.js
buildScriptsAndStyleFiles
function buildScriptsAndStyleFiles(outputPath) { const stylesRegex = /<style>|<\/style>/gi, scriptsRegex = /<script type="text\/javascript">|<\/script>/gi; // creates the report directory if it doesn't exist if (!fs.existsSync(outputPath)) { fs.mkdirSync(outputPath); } // create the styles.css and main.js files writeFile(`${outputPath}styles.css`, styles(), stylesRegex); writeFile(`${outputPath}main.js`, scripts(), scriptsRegex); }
javascript
function buildScriptsAndStyleFiles(outputPath) { const stylesRegex = /<style>|<\/style>/gi, scriptsRegex = /<script type="text\/javascript">|<\/script>/gi; // creates the report directory if it doesn't exist if (!fs.existsSync(outputPath)) { fs.mkdirSync(outputPath); } // create the styles.css and main.js files writeFile(`${outputPath}styles.css`, styles(), stylesRegex); writeFile(`${outputPath}main.js`, scripts(), scriptsRegex); }
[ "function", "buildScriptsAndStyleFiles", "(", "outputPath", ")", "{", "const", "stylesRegex", "=", "/", "<style>|<\\/style>", "/", "gi", ",", "scriptsRegex", "=", "/", "<script type=\"text\\/javascript\">|<\\/script>", "/", "gi", ";", "// creates the report directory if it ...
Creates a styles.css and a main.js file for the report @param {string} currWorkingDir The current working directory
[ "Creates", "a", "styles", ".", "css", "and", "a", "main", ".", "js", "file", "for", "the", "report" ]
731af360846962e6bf7d9a92a6e8f96ef2710fb0
https://github.com/mportuga/eslint-detailed-reporter/blob/731af360846962e6bf7d9a92a6e8f96ef2710fb0/lib/template-generator.js#L325-L337
28,906
jasonrojas/node-captions
lib/macros.js
function(text) { var openItalic = false, cText = [], italicStart = new RegExp(/\{italic\}/), commandBreak = new RegExp(/\{break\}/), italicEnd = new RegExp(/\{end-italic\}/), finalText = "", textArray = text.split(''), idx = 0; for (idx = 0; idx <= textArray.length; idx++) { cText.push(textArray[idx]); if (italicStart.test(cText.join('')) && openItalic === false) { // found an italic start, push to array, reset. finalText += cText.join(''); cText = []; openItalic = true; } else if (commandBreak.test(cText.join('')) && openItalic === false) { finalText += cText.join(''); cText = []; openItalic = false; } else if (commandBreak.test(cText.join('')) && openItalic === true) { finalText += cText.join('').replace(commandBreak, '{end-italic}{break}'); cText = []; openItalic = false; } else if (italicStart.test(cText.join('')) && openItalic === true) { // found an italic start within another italic...prepend an end finalText += cText.join('').replace(italicStart, ''); cText = []; openItalic = true; } else if (italicEnd.test(cText.join('')) && openItalic === true) { finalText += cText.join(''); cText = []; openItalic = false; } else if (italicEnd.test(cText.join('')) && openItalic === false) { //drop useless end italics that are out of place. finalText += cText.join('').replace(italicEnd, ''); cText = []; openItalic = false; } if (idx === text.length) { if (openItalic) { finalText += cText.join('') + '{end-italic}'; } else { finalText += cText.join(''); } cText = []; } } return finalText; }
javascript
function(text) { var openItalic = false, cText = [], italicStart = new RegExp(/\{italic\}/), commandBreak = new RegExp(/\{break\}/), italicEnd = new RegExp(/\{end-italic\}/), finalText = "", textArray = text.split(''), idx = 0; for (idx = 0; idx <= textArray.length; idx++) { cText.push(textArray[idx]); if (italicStart.test(cText.join('')) && openItalic === false) { // found an italic start, push to array, reset. finalText += cText.join(''); cText = []; openItalic = true; } else if (commandBreak.test(cText.join('')) && openItalic === false) { finalText += cText.join(''); cText = []; openItalic = false; } else if (commandBreak.test(cText.join('')) && openItalic === true) { finalText += cText.join('').replace(commandBreak, '{end-italic}{break}'); cText = []; openItalic = false; } else if (italicStart.test(cText.join('')) && openItalic === true) { // found an italic start within another italic...prepend an end finalText += cText.join('').replace(italicStart, ''); cText = []; openItalic = true; } else if (italicEnd.test(cText.join('')) && openItalic === true) { finalText += cText.join(''); cText = []; openItalic = false; } else if (italicEnd.test(cText.join('')) && openItalic === false) { //drop useless end italics that are out of place. finalText += cText.join('').replace(italicEnd, ''); cText = []; openItalic = false; } if (idx === text.length) { if (openItalic) { finalText += cText.join('') + '{end-italic}'; } else { finalText += cText.join(''); } cText = []; } } return finalText; }
[ "function", "(", "text", ")", "{", "var", "openItalic", "=", "false", ",", "cText", "=", "[", "]", ",", "italicStart", "=", "new", "RegExp", "(", "/", "\\{italic\\}", "/", ")", ",", "commandBreak", "=", "new", "RegExp", "(", "/", "\\{break\\}", "/", ...
fixes italics.. @function @public @param {string} text - Translated text
[ "fixes", "italics", ".." ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/macros.js#L20-L73
28,907
jasonrojas/node-captions
lib/scc.js
function(file, options, callback) { var lines; fs.readFile(file, options, function(err, data) { if (err) { //err return callback(err); } if (/\r\n/.test(data.toString())) { lines = data.toString().split('\r\n'); } else { lines = data.toString().split('\n'); } if (module.exports.verify(lines[0])) { callback(undefined, lines); } else { callback("INVALID_SCC_FORMAT"); } }); }
javascript
function(file, options, callback) { var lines; fs.readFile(file, options, function(err, data) { if (err) { //err return callback(err); } if (/\r\n/.test(data.toString())) { lines = data.toString().split('\r\n'); } else { lines = data.toString().split('\n'); } if (module.exports.verify(lines[0])) { callback(undefined, lines); } else { callback("INVALID_SCC_FORMAT"); } }); }
[ "function", "(", "file", ",", "options", ",", "callback", ")", "{", "var", "lines", ";", "fs", ".", "readFile", "(", "file", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "//err", "return", "callbac...
Reads a SCC file and verifies it sees the proper header @function @param {string} file - File to read @param {callback} callback - WHen the read is successful callback. @public
[ "Reads", "a", "SCC", "file", "and", "verifies", "it", "sees", "the", "proper", "header" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/scc.js#L90-L108
28,908
jasonrojas/node-captions
lib/scc.js
function(lines) { var idx = 0; jsonCaptions = []; for (idx = 0; idx < lines.length; idx++) { if (!module.exports.verify(lines[idx])) { module.exports.translateLine(lines[idx].toLowerCase()); } } if (paintBuffer.length > 0) { rollUp(true); } if (jsonCaptions[jsonCaptions.length - 1].endTimeMicro === undefined) { jsonCaptions[jsonCaptions.length - 1].endTimeMicro = jsonCaptions[jsonCaptions.length - 1].startTimeMicro; } return jsonCaptions; }
javascript
function(lines) { var idx = 0; jsonCaptions = []; for (idx = 0; idx < lines.length; idx++) { if (!module.exports.verify(lines[idx])) { module.exports.translateLine(lines[idx].toLowerCase()); } } if (paintBuffer.length > 0) { rollUp(true); } if (jsonCaptions[jsonCaptions.length - 1].endTimeMicro === undefined) { jsonCaptions[jsonCaptions.length - 1].endTimeMicro = jsonCaptions[jsonCaptions.length - 1].startTimeMicro; } return jsonCaptions; }
[ "function", "(", "lines", ")", "{", "var", "idx", "=", "0", ";", "jsonCaptions", "=", "[", "]", ";", "for", "(", "idx", "=", "0", ";", "idx", "<", "lines", ".", "length", ";", "idx", "++", ")", "{", "if", "(", "!", "module", ".", "exports", "...
Converts the SCC file to a proprietary JSON format @function @param {string} data - Entire SCC file content @public
[ "Converts", "the", "SCC", "file", "to", "a", "proprietary", "JSON", "format" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/scc.js#L125-L140
28,909
jasonrojas/node-captions
lib/scc.js
function(timeStamp) { var secondsPerStamp = 1.001, timesplit = timeStamp.split(':'), timestampSeconds = (parseInt(timesplit[0], 10) * 3600 + parseInt(timesplit[1], 10) * 60 + parseInt(timesplit[2], 10) + parseInt(timesplit[3], 10) / 30), seconds = timestampSeconds * secondsPerStamp, microSeconds = seconds * 1000 * 1000; return (microSeconds > 0) ? microSeconds : 0; }
javascript
function(timeStamp) { var secondsPerStamp = 1.001, timesplit = timeStamp.split(':'), timestampSeconds = (parseInt(timesplit[0], 10) * 3600 + parseInt(timesplit[1], 10) * 60 + parseInt(timesplit[2], 10) + parseInt(timesplit[3], 10) / 30), seconds = timestampSeconds * secondsPerStamp, microSeconds = seconds * 1000 * 1000; return (microSeconds > 0) ? microSeconds : 0; }
[ "function", "(", "timeStamp", ")", "{", "var", "secondsPerStamp", "=", "1.001", ",", "timesplit", "=", "timeStamp", ".", "split", "(", "':'", ")", ",", "timestampSeconds", "=", "(", "parseInt", "(", "timesplit", "[", "0", "]", ",", "10", ")", "*", "360...
Converts SCC timestamps to microseconds @function @public @param {string} timeStamp - Timestamp of SCC line
[ "Converts", "SCC", "timestamps", "to", "microseconds" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/scc.js#L302-L312
28,910
jasonrojas/node-captions
lib/smpte_tt.js
function(captions) { var SMPTE_TT_BODY = ''; // SMPTE_TT_BODY += SMPTE_TT.header.join('\n') + '\n'; captions.forEach(function(caption) { if (caption.text.length > 0 && validateText(caption.text)) { if ((/&/.test(caption.text)) && (!(/&amp;/.test(caption.text)) || !(/&gt;/.test(caption.text)) || !(/&lt;/.test(caption.text)))) { caption.text = caption.text.replace(/&/g, '&amp;'); } if ((/</.test(caption.text)) && !(/&lt;/.test(caption.text))) { caption.text = caption.text.replace(/</g, '&lt;'); } if ((/>/.test(caption.text)) && !(/&gt;/.test(caption.text))) { caption.text = caption.text.replace(/>/g, '&gt;'); } SMPTE_TT_BODY += SMPTE_TT.lineTemplate.replace('{startTime}', module.exports.formatTime(caption.startTimeMicro)) .replace('{endTime}', module.exports.formatTime(caption.endTimeMicro)) .replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text)))) + '\n'; } }); return SMPTE_TT_BODY + SMPTE_TT.footer.join('\n') + '\n'; }
javascript
function(captions) { var SMPTE_TT_BODY = ''; // SMPTE_TT_BODY += SMPTE_TT.header.join('\n') + '\n'; captions.forEach(function(caption) { if (caption.text.length > 0 && validateText(caption.text)) { if ((/&/.test(caption.text)) && (!(/&amp;/.test(caption.text)) || !(/&gt;/.test(caption.text)) || !(/&lt;/.test(caption.text)))) { caption.text = caption.text.replace(/&/g, '&amp;'); } if ((/</.test(caption.text)) && !(/&lt;/.test(caption.text))) { caption.text = caption.text.replace(/</g, '&lt;'); } if ((/>/.test(caption.text)) && !(/&gt;/.test(caption.text))) { caption.text = caption.text.replace(/>/g, '&gt;'); } SMPTE_TT_BODY += SMPTE_TT.lineTemplate.replace('{startTime}', module.exports.formatTime(caption.startTimeMicro)) .replace('{endTime}', module.exports.formatTime(caption.endTimeMicro)) .replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text)))) + '\n'; } }); return SMPTE_TT_BODY + SMPTE_TT.footer.join('\n') + '\n'; }
[ "function", "(", "captions", ")", "{", "var", "SMPTE_TT_BODY", "=", "''", ";", "//", "SMPTE_TT_BODY", "+=", "SMPTE_TT", ".", "header", ".", "join", "(", "'\\n'", ")", "+", "'\\n'", ";", "captions", ".", "forEach", "(", "function", "(", "caption", ")", ...
Generate SAMI captions from JSON @function @param {array} captions - File to read @public
[ "Generate", "SAMI", "captions", "from", "JSON" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/smpte_tt.js#L29-L51
28,911
jonschlinkert/npmignore
index.js
extract
function extract(npmignore) { if (npmignore == null) { throw new Error('npmignore expects a string.'); } var lines = split(npmignore); var len = lines.length; var npmignored = false; var git = []; var npm = []; var i = 0; while (i < len) { var line = lines[i++]; if (re.test(line)) { npmignored = true; } if (npmignored) { npm.push(line); } else { git.push(line); } } return npm; }
javascript
function extract(npmignore) { if (npmignore == null) { throw new Error('npmignore expects a string.'); } var lines = split(npmignore); var len = lines.length; var npmignored = false; var git = []; var npm = []; var i = 0; while (i < len) { var line = lines[i++]; if (re.test(line)) { npmignored = true; } if (npmignored) { npm.push(line); } else { git.push(line); } } return npm; }
[ "function", "extract", "(", "npmignore", ")", "{", "if", "(", "npmignore", "==", "null", ")", "{", "throw", "new", "Error", "(", "'npmignore expects a string.'", ")", ";", "}", "var", "lines", "=", "split", "(", "npmignore", ")", ";", "var", "len", "=", ...
Extract relevant lines from `.npmignore` @param {String} `npmignore` string @return {Array} Array of lines
[ "Extract", "relevant", "lines", "from", ".", "npmignore" ]
90b32c48d56d8351759d1dfe627747c79c76bb06
https://github.com/jonschlinkert/npmignore/blob/90b32c48d56d8351759d1dfe627747c79c76bb06/index.js#L63-L89
28,912
jonschlinkert/npmignore
index.js
diff
function diff(arr, remove) { if (arr == null) { return []; } if (remove == null) { return arr; } var res = []; var len = arr.length; var i = 0; while (i < len) { var ele = arr[i++]; if (remove.indexOf(ele) === -1) { res.push(ele); } } return res; }
javascript
function diff(arr, remove) { if (arr == null) { return []; } if (remove == null) { return arr; } var res = []; var len = arr.length; var i = 0; while (i < len) { var ele = arr[i++]; if (remove.indexOf(ele) === -1) { res.push(ele); } } return res; }
[ "function", "diff", "(", "arr", ",", "remove", ")", "{", "if", "(", "arr", "==", "null", ")", "{", "return", "[", "]", ";", "}", "if", "(", "remove", "==", "null", ")", "{", "return", "arr", ";", "}", "var", "res", "=", "[", "]", ";", "var", ...
Remove unwanted elements and uniquify the given `array`. @param {Array} `array` The array to uniquify @return {Array} `remove` Array of elements to remove @api private
[ "Remove", "unwanted", "elements", "and", "uniquify", "the", "given", "array", "." ]
90b32c48d56d8351759d1dfe627747c79c76bb06
https://github.com/jonschlinkert/npmignore/blob/90b32c48d56d8351759d1dfe627747c79c76bb06/index.js#L148-L170
28,913
jasonrojas/node-captions
lib/smi.js
function(data) { var SAMI_BODY = '', captions = data; SAMI_BODY += SAMI.header.join('\n') + '\n'; captions.forEach(function(caption) { if (caption.text === '') { caption.text = '&nbsp;'; } SAMI_BODY += SAMI.lineTemplate.replace('{startTime}', Math.floor(caption.startTimeMicro / 1000)) .replace('{text}', module.exports.renderMacros(caption.text)) + '\n'; }); return SAMI_BODY + SAMI.footer.join('\n') + '\n'; }
javascript
function(data) { var SAMI_BODY = '', captions = data; SAMI_BODY += SAMI.header.join('\n') + '\n'; captions.forEach(function(caption) { if (caption.text === '') { caption.text = '&nbsp;'; } SAMI_BODY += SAMI.lineTemplate.replace('{startTime}', Math.floor(caption.startTimeMicro / 1000)) .replace('{text}', module.exports.renderMacros(caption.text)) + '\n'; }); return SAMI_BODY + SAMI.footer.join('\n') + '\n'; }
[ "function", "(", "data", ")", "{", "var", "SAMI_BODY", "=", "''", ",", "captions", "=", "data", ";", "SAMI_BODY", "+=", "SAMI", ".", "header", ".", "join", "(", "'\\n'", ")", "+", "'\\n'", ";", "captions", ".", "forEach", "(", "function", "(", "capti...
generates SAMI from JSON @function @public @param {string} data - proprietary JSON data to translate to SAMI
[ "generates", "SAMI", "from", "JSON" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/smi.js#L18-L32
28,914
jasonrojas/node-captions
lib/srt.js
function(captions) { var SRT_BODY = [], counter = 1; captions.forEach(function(caption) { if (caption.text.length > 0 && validateText(caption.text)) { SRT_BODY.push(counter); SRT_BODY.push(module.exports.formatTime(caption.startTimeMicro) + ' --> ' + module.exports.formatTime(caption.endTimeMicro)); SRT_BODY.push(module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text))) + '\n'); counter++; } }); return SRT_BODY.join('\n'); }
javascript
function(captions) { var SRT_BODY = [], counter = 1; captions.forEach(function(caption) { if (caption.text.length > 0 && validateText(caption.text)) { SRT_BODY.push(counter); SRT_BODY.push(module.exports.formatTime(caption.startTimeMicro) + ' --> ' + module.exports.formatTime(caption.endTimeMicro)); SRT_BODY.push(module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text))) + '\n'); counter++; } }); return SRT_BODY.join('\n'); }
[ "function", "(", "captions", ")", "{", "var", "SRT_BODY", "=", "[", "]", ",", "counter", "=", "1", ";", "captions", ".", "forEach", "(", "function", "(", "caption", ")", "{", "if", "(", "caption", ".", "text", ".", "length", ">", "0", "&&", "valida...
Generates SRT captions from JSON @function @param {array} captions - JSON array of captions @public
[ "Generates", "SRT", "captions", "from", "JSON" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L31-L43
28,915
jasonrojas/node-captions
lib/srt.js
function(file, options, callback) { fs.readFile(file, options, function(err, data) { if (err) { return callback(err); } module.exports.parse(data.toString(), function(parseErr, lines) { if (parseErr) { return callback(parseErr); } callback(undefined, lines); }); }); }
javascript
function(file, options, callback) { fs.readFile(file, options, function(err, data) { if (err) { return callback(err); } module.exports.parse(data.toString(), function(parseErr, lines) { if (parseErr) { return callback(parseErr); } callback(undefined, lines); }); }); }
[ "function", "(", "file", ",", "options", ",", "callback", ")", "{", "fs", ".", "readFile", "(", "file", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}...
Reads a SRT file and verifies it sees the proper header @function @param {string} file - path to file @param {callback} callback - callback to call when complete @public
[ "Reads", "a", "SRT", "file", "and", "verifies", "it", "sees", "the", "proper", "header" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L71-L83
28,916
jasonrojas/node-captions
lib/srt.js
function(filedata, callback) { var lines; lines = filedata.toString().split(/(?:\r\n|\r|\n)/gm); if (module.exports.verify(lines)) { return callback(undefined, lines); } return callback('INVALID_SRT_FORMAT'); }
javascript
function(filedata, callback) { var lines; lines = filedata.toString().split(/(?:\r\n|\r|\n)/gm); if (module.exports.verify(lines)) { return callback(undefined, lines); } return callback('INVALID_SRT_FORMAT'); }
[ "function", "(", "filedata", ",", "callback", ")", "{", "var", "lines", ";", "lines", "=", "filedata", ".", "toString", "(", ")", ".", "split", "(", "/", "(?:\\r\\n|\\r|\\n)", "/", "gm", ")", ";", "if", "(", "module", ".", "exports", ".", "verify", "...
Parses srt captions, errors if format is invalid @function @param {string} filedata - String of caption data @param {callback} callback - function to call when complete @public
[ "Parses", "srt", "captions", "errors", "if", "format", "is", "invalid" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L91-L98
28,917
jasonrojas/node-captions
lib/srt.js
function(data) { var json = {}, index = 0, id, text, startTimeMicro, durationMicro, invalidText = /^\s+$/, endTimeMicro, time, lastNonEmptyLine; function getLastNonEmptyLine(linesArray) { var idx = linesArray.length - 1; while (idx >= 0 && !linesArray[idx]) { idx--; } return idx; } json.captions = []; lastNonEmptyLine = getLastNonEmptyLine(data) + 1; while (index < lastNonEmptyLine) { if (data[index]) { text = []; //Find the ID line.. if (/^[0-9]+$/.test(data[index])) { //found id line id = parseInt(data[index], 10); index++; } if (!data[index].split) { // for some reason this is not a string index++; continue; } //next line has to be timestamp right? right? time = data[index].split(/[\t ]*-->[\t ]*/); startTimeMicro = module.exports.translateTime(time[0]); endTimeMicro = module.exports.translateTime(time[1]); durationMicro = parseInt(parseInt(endTimeMicro, 10) - parseInt(startTimeMicro, 10), 10); if (!startTimeMicro || !endTimeMicro) { // no valid timestamp index++; continue; } index++; while (data[index]) { text.push(data[index]); index++; if (!data[index] && !invalidText.test(text.join('\n'))) { json.captions.push({ id: id, text: module.exports.addMacros(text.join('\n')), startTimeMicro: startTimeMicro, durationSeconds: parseInt(durationMicro / 1000, 10) / 1000, endTimeMicro: endTimeMicro }); break; } } } index++; } return json.captions; }
javascript
function(data) { var json = {}, index = 0, id, text, startTimeMicro, durationMicro, invalidText = /^\s+$/, endTimeMicro, time, lastNonEmptyLine; function getLastNonEmptyLine(linesArray) { var idx = linesArray.length - 1; while (idx >= 0 && !linesArray[idx]) { idx--; } return idx; } json.captions = []; lastNonEmptyLine = getLastNonEmptyLine(data) + 1; while (index < lastNonEmptyLine) { if (data[index]) { text = []; //Find the ID line.. if (/^[0-9]+$/.test(data[index])) { //found id line id = parseInt(data[index], 10); index++; } if (!data[index].split) { // for some reason this is not a string index++; continue; } //next line has to be timestamp right? right? time = data[index].split(/[\t ]*-->[\t ]*/); startTimeMicro = module.exports.translateTime(time[0]); endTimeMicro = module.exports.translateTime(time[1]); durationMicro = parseInt(parseInt(endTimeMicro, 10) - parseInt(startTimeMicro, 10), 10); if (!startTimeMicro || !endTimeMicro) { // no valid timestamp index++; continue; } index++; while (data[index]) { text.push(data[index]); index++; if (!data[index] && !invalidText.test(text.join('\n'))) { json.captions.push({ id: id, text: module.exports.addMacros(text.join('\n')), startTimeMicro: startTimeMicro, durationSeconds: parseInt(durationMicro / 1000, 10) / 1000, endTimeMicro: endTimeMicro }); break; } } } index++; } return json.captions; }
[ "function", "(", "data", ")", "{", "var", "json", "=", "{", "}", ",", "index", "=", "0", ",", "id", ",", "text", ",", "startTimeMicro", ",", "durationMicro", ",", "invalidText", "=", "/", "^\\s+$", "/", ",", "endTimeMicro", ",", "time", ",", "lastNon...
converts SRT to JSON format @function @param {array} data - output from read usually @public
[ "converts", "SRT", "to", "JSON", "format" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L116-L183
28,918
jasonrojas/node-captions
lib/srt.js
function(timestamp) { if (!timestamp) { return; } //TODO check this //var secondsPerStamp = 1.001, var timesplit = timestamp.replace(',', ':').split(':'); return (parseInt(timesplit[0], 10) * 3600 + parseInt(timesplit[1], 10) * 60 + parseInt(timesplit[2], 10) + parseInt(timesplit[3], 10) / 1000) * 1000 * 1000; }
javascript
function(timestamp) { if (!timestamp) { return; } //TODO check this //var secondsPerStamp = 1.001, var timesplit = timestamp.replace(',', ':').split(':'); return (parseInt(timesplit[0], 10) * 3600 + parseInt(timesplit[1], 10) * 60 + parseInt(timesplit[2], 10) + parseInt(timesplit[3], 10) / 1000) * 1000 * 1000; }
[ "function", "(", "timestamp", ")", "{", "if", "(", "!", "timestamp", ")", "{", "return", ";", "}", "//TODO check this", "//var secondsPerStamp = 1.001,", "var", "timesplit", "=", "timestamp", ".", "replace", "(", "','", ",", "':'", ")", ".", "split", "(", ...
translates timestamp to microseconds @function @param {string} timestamp - string timestamp from srt file @public
[ "translates", "timestamp", "to", "microseconds" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L190-L202
28,919
jasonrojas/node-captions
lib/srt.js
function(text) { return macros.cleanMacros(text.replace(/\n/g, '{break}').replace(/<i>/g, '{italic}').replace(/<\/i>/g, '{end-italic}')); }
javascript
function(text) { return macros.cleanMacros(text.replace(/\n/g, '{break}').replace(/<i>/g, '{italic}').replace(/<\/i>/g, '{end-italic}')); }
[ "function", "(", "text", ")", "{", "return", "macros", ".", "cleanMacros", "(", "text", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'{break}'", ")", ".", "replace", "(", "/", "<i>", "/", "g", ",", "'{italic}'", ")", ".", "replace", "(", "/", ...
converts SRT stylings to macros @function @param {string} text - text to render macros for @public
[ "converts", "SRT", "stylings", "to", "macros" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L209-L211
28,920
raveljs/ravel
lib/util/redis_session_store.js
finishBasicPromise
function finishBasicPromise (resolve, reject) { return (err, res) => { if (err) { return reject(err); } else { return resolve(res); } }; }
javascript
function finishBasicPromise (resolve, reject) { return (err, res) => { if (err) { return reject(err); } else { return resolve(res); } }; }
[ "function", "finishBasicPromise", "(", "resolve", ",", "reject", ")", "{", "return", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "else", "{", "return", "resolve", "(", "res", ")...
Shorthand for adapting callbacks to `Promise`s. @param {Function} resolve - A resolve function. @param {Function} reject - A reject function. @private
[ "Shorthand", "for", "adapting", "callbacks", "to", "Promise", "s", "." ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/util/redis_session_store.js#L13-L21
28,921
raveljs/ravel
lib/core/routes.js
initRoutes
function initRoutes (ravelInstance, koaRouter) { const proto = Object.getPrototypeOf(this); // handle class-level @mapping decorators const classMeta = Metadata.getClassMeta(proto, '@mapping', Object.create(null)); for (const r of Object.keys(classMeta)) { buildRoute(ravelInstance, this, koaRouter, r, classMeta[r]); } // handle methods decorated with @mapping const meta = Metadata.getMeta(proto).method; const annotatedMethods = Object.keys(meta); for (const r of annotatedMethods) { const methodMeta = Metadata.getMethodMetaValue(proto, r, '@mapping', 'info'); if (methodMeta) { buildRoute(ravelInstance, this, koaRouter, r, methodMeta); } } }
javascript
function initRoutes (ravelInstance, koaRouter) { const proto = Object.getPrototypeOf(this); // handle class-level @mapping decorators const classMeta = Metadata.getClassMeta(proto, '@mapping', Object.create(null)); for (const r of Object.keys(classMeta)) { buildRoute(ravelInstance, this, koaRouter, r, classMeta[r]); } // handle methods decorated with @mapping const meta = Metadata.getMeta(proto).method; const annotatedMethods = Object.keys(meta); for (const r of annotatedMethods) { const methodMeta = Metadata.getMethodMetaValue(proto, r, '@mapping', 'info'); if (methodMeta) { buildRoute(ravelInstance, this, koaRouter, r, methodMeta); } } }
[ "function", "initRoutes", "(", "ravelInstance", ",", "koaRouter", ")", "{", "const", "proto", "=", "Object", ".", "getPrototypeOf", "(", "this", ")", ";", "// handle class-level @mapping decorators", "const", "classMeta", "=", "Metadata", ".", "getClassMeta", "(", ...
Initializer for this `Routes` class. @param {Ravel} ravelInstance - Instance of a Ravel app. @param {Object} koaRouter - Instance of koa-router. @private
[ "Initializer", "for", "this", "Routes", "class", "." ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/core/routes.js#L141-L158
28,922
appcues/snabbdom-virtualize
src/nodes.js
getClasses
function getClasses(element) { const className = element.className; const classes = {}; if (className !== null && className.length > 0) { className.split(' ').forEach((className) => { if (className.trim().length) { classes[className.trim()] = true; } }); } return classes; }
javascript
function getClasses(element) { const className = element.className; const classes = {}; if (className !== null && className.length > 0) { className.split(' ').forEach((className) => { if (className.trim().length) { classes[className.trim()] = true; } }); } return classes; }
[ "function", "getClasses", "(", "element", ")", "{", "const", "className", "=", "element", ".", "className", ";", "const", "classes", "=", "{", "}", ";", "if", "(", "className", "!==", "null", "&&", "className", ".", "length", ">", "0", ")", "{", "class...
Builds the class object for the VNode.
[ "Builds", "the", "class", "object", "for", "the", "VNode", "." ]
f3fd12de0911ed575751e5c13f94c3ffc6d795c4
https://github.com/appcues/snabbdom-virtualize/blob/f3fd12de0911ed575751e5c13f94c3ffc6d795c4/src/nodes.js#L85-L96
28,923
appcues/snabbdom-virtualize
src/nodes.js
getStyle
function getStyle(element) { const style = element.style; const styles = {}; for (let i = 0; i < style.length; i++) { const name = style.item(i); const transformedName = transformName(name); styles[transformedName] = style.getPropertyValue(name); } return styles; }
javascript
function getStyle(element) { const style = element.style; const styles = {}; for (let i = 0; i < style.length; i++) { const name = style.item(i); const transformedName = transformName(name); styles[transformedName] = style.getPropertyValue(name); } return styles; }
[ "function", "getStyle", "(", "element", ")", "{", "const", "style", "=", "element", ".", "style", ";", "const", "styles", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "style", ".", "length", ";", "i", "++", ")", "{", "co...
Builds the style object for the VNode.
[ "Builds", "the", "style", "object", "for", "the", "VNode", "." ]
f3fd12de0911ed575751e5c13f94c3ffc6d795c4
https://github.com/appcues/snabbdom-virtualize/blob/f3fd12de0911ed575751e5c13f94c3ffc6d795c4/src/nodes.js#L99-L108
28,924
raveljs/ravel
lib/core/params.js
function (value) { const IllegalValue = this.$err.IllegalValue; if (typeof value !== 'string') { return value; } const result = value.replace(ENVVAR_PATTERN, function () { const varname = arguments[1]; if (process.env[varname] === undefined) { throw new IllegalValue(`Environment variable ${varname} was referenced but not set`); } return process.env[varname]; }); return result; }
javascript
function (value) { const IllegalValue = this.$err.IllegalValue; if (typeof value !== 'string') { return value; } const result = value.replace(ENVVAR_PATTERN, function () { const varname = arguments[1]; if (process.env[varname] === undefined) { throw new IllegalValue(`Environment variable ${varname} was referenced but not set`); } return process.env[varname]; }); return result; }
[ "function", "(", "value", ")", "{", "const", "IllegalValue", "=", "this", ".", "$err", ".", "IllegalValue", ";", "if", "(", "typeof", "value", "!==", "'string'", ")", "{", "return", "value", ";", "}", "const", "result", "=", "value", ".", "replace", "(...
Interpolates config values with the values of the environment variables of the process. @private @param {any} value - The value specified for a parameter; possibly an environment variable.
[ "Interpolates", "config", "values", "with", "the", "values", "of", "the", "environment", "variables", "of", "the", "process", "." ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/core/params.js#L30-L44
28,925
duereg/normalize-object
src/normalize-object.js
normalize
function normalize(obj, caseType = 'camel') { let ret = obj; const method = methods[caseType]; if (Array.isArray(obj)) { ret = []; let i = 0; while (i < obj.length) { ret.push(normalize(obj[i], caseType)); ++i; } } else if (isPlainObject(obj)) { ret = {}; // eslint-disable-next-line guard-for-in, no-restricted-syntax for (const k in obj) { ret[method(k)] = normalize(obj[k], caseType); } } return ret; }
javascript
function normalize(obj, caseType = 'camel') { let ret = obj; const method = methods[caseType]; if (Array.isArray(obj)) { ret = []; let i = 0; while (i < obj.length) { ret.push(normalize(obj[i], caseType)); ++i; } } else if (isPlainObject(obj)) { ret = {}; // eslint-disable-next-line guard-for-in, no-restricted-syntax for (const k in obj) { ret[method(k)] = normalize(obj[k], caseType); } } return ret; }
[ "function", "normalize", "(", "obj", ",", "caseType", "=", "'camel'", ")", "{", "let", "ret", "=", "obj", ";", "const", "method", "=", "methods", "[", "caseType", "]", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "ret", "=", ...
Normalize all keys of `obj` recursively. @param {Object} obj to normalize @param {String} caseType type of case to convert object to @return {Object} @api public
[ "Normalize", "all", "keys", "of", "obj", "recursively", "." ]
21768211e549b3b85f1a9432d79692738c590ef5
https://github.com/duereg/normalize-object/blob/21768211e549b3b85f1a9432d79692738c590ef5/src/normalize-object.js#L17-L38
28,926
raveljs/ravel
lib/core/module.js
connectHandlers
function connectHandlers (decorator, event) { const handlers = Metadata.getClassMeta(Object.getPrototypeOf(self), decorator, Object.create(null)); for (const f of Object.keys(handlers)) { ravelInstance.once(event, (...args) => { ravelInstance.$log.trace(`${name}: Invoking ${decorator} ${f}`); handlers[f].apply(self, args); }); } }
javascript
function connectHandlers (decorator, event) { const handlers = Metadata.getClassMeta(Object.getPrototypeOf(self), decorator, Object.create(null)); for (const f of Object.keys(handlers)) { ravelInstance.once(event, (...args) => { ravelInstance.$log.trace(`${name}: Invoking ${decorator} ${f}`); handlers[f].apply(self, args); }); } }
[ "function", "connectHandlers", "(", "decorator", ",", "event", ")", "{", "const", "handlers", "=", "Metadata", ".", "getClassMeta", "(", "Object", ".", "getPrototypeOf", "(", "self", ")", ",", "decorator", ",", "Object", ".", "create", "(", "null", ")", ")...
connect any Ravel lifecycle handlers to the appropriate events
[ "connect", "any", "Ravel", "lifecycle", "handlers", "to", "the", "appropriate", "events" ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/core/module.js#L21-L29
28,927
apathetic/scrollify
dist/scrollify.es6.js
translateX
function translateX(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 0; var offset = (to - from) * progress + from; this.transforms.position[0] = offset; }
javascript
function translateX(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 0; var offset = (to - from) * progress + from; this.transforms.position[0] = offset; }
[ "function", "translateX", "(", "progress", ")", "{", "var", "to", "=", "(", "this", ".", "options", ".", "to", "!==", "undefined", ")", "?", "this", ".", "options", ".", "to", ":", "0", ";", "var", "from", "=", "(", "this", ".", "options", ".", "...
Translate an element along the X-axis. @param {Float} progress Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Translate", "an", "element", "along", "the", "X", "-", "axis", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L656-L662
28,928
apathetic/scrollify
dist/scrollify.es6.js
scale
function scale(progress) { var to = (this.options.to !== undefined) ? this.options.to : 1; var from = (this.options.from !== undefined) ? this.options.from : this.transforms.scale[0]; var scale = (to - from) * progress + from; this.transforms.scale[0] = scale; this.transforms.scale[1] = scale; }
javascript
function scale(progress) { var to = (this.options.to !== undefined) ? this.options.to : 1; var from = (this.options.from !== undefined) ? this.options.from : this.transforms.scale[0]; var scale = (to - from) * progress + from; this.transforms.scale[0] = scale; this.transforms.scale[1] = scale; }
[ "function", "scale", "(", "progress", ")", "{", "var", "to", "=", "(", "this", ".", "options", ".", "to", "!==", "undefined", ")", "?", "this", ".", "options", ".", "to", ":", "1", ";", "var", "from", "=", "(", "this", ".", "options", ".", "from"...
Uniformly scale an element along both axis'. @param {Float} progress Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Uniformly", "scale", "an", "element", "along", "both", "axis", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L706-L713
28,929
apathetic/scrollify
dist/scrollify.es6.js
fade
function fade(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 1; var opacity = (to - from) * progress + from; this.element.style.opacity = opacity; }
javascript
function fade(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 1; var opacity = (to - from) * progress + from; this.element.style.opacity = opacity; }
[ "function", "fade", "(", "progress", ")", "{", "var", "to", "=", "(", "this", ".", "options", ".", "to", "!==", "undefined", ")", "?", "this", ".", "options", ".", "to", ":", "0", ";", "var", "from", "=", "(", "this", ".", "options", ".", "from",...
Update an element's opacity. @param {Float} progress Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Update", "an", "element", "s", "opacity", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L721-L727
28,930
apathetic/scrollify
dist/scrollify.es6.js
blur
function blur(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 0; var amount = (to - from) * progress + from; this.element.style.filter = 'blur(' + amount + 'px)'; }
javascript
function blur(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 0; var amount = (to - from) * progress + from; this.element.style.filter = 'blur(' + amount + 'px)'; }
[ "function", "blur", "(", "progress", ")", "{", "var", "to", "=", "(", "this", ".", "options", ".", "to", "!==", "undefined", ")", "?", "this", ".", "options", ".", "to", ":", "0", ";", "var", "from", "=", "(", "this", ".", "options", ".", "from",...
Update an element's blur. @param {Float} progress Current progress of the scene, between 0 and 1. @this {Object} @return {void}
[ "Update", "an", "element", "s", "blur", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L735-L741
28,931
apathetic/scrollify
dist/scrollify.es6.js
parallax
function parallax(progress) { var range = this.options.range || 0; var offset = progress * range; // TODO add provision for speed as well this.transforms.position[1] = offset; // just vertical for now }
javascript
function parallax(progress) { var range = this.options.range || 0; var offset = progress * range; // TODO add provision for speed as well this.transforms.position[1] = offset; // just vertical for now }
[ "function", "parallax", "(", "progress", ")", "{", "var", "range", "=", "this", ".", "options", ".", "range", "||", "0", ";", "var", "offset", "=", "progress", "*", "range", ";", "// TODO add provision for speed as well", "this", ".", "transforms", ".", "pos...
Parallax an element. @param {Float} progress Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Parallax", "an", "element", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L749-L754
28,932
apathetic/scrollify
dist/scrollify.es6.js
toggle
function toggle(progress) { var opts = this.options; var element = this.element; var times = Object.keys(opts); times.forEach(function(time) { var css = opts[time]; if (progress > time) { element.classList.add(css); } else { element.classList.remove(css); } }); }
javascript
function toggle(progress) { var opts = this.options; var element = this.element; var times = Object.keys(opts); times.forEach(function(time) { var css = opts[time]; if (progress > time) { element.classList.add(css); } else { element.classList.remove(css); } }); }
[ "function", "toggle", "(", "progress", ")", "{", "var", "opts", "=", "this", ".", "options", ";", "var", "element", "=", "this", ".", "element", ";", "var", "times", "=", "Object", ".", "keys", "(", "opts", ")", ";", "times", ".", "forEach", "(", "...
Toggle a class on or off. @param {Float} progress: Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Toggle", "a", "class", "on", "or", "off", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L762-L776
28,933
bpmn-io/bpmn-questionnaire
lib/components/Diagram.js
Diagram
function Diagram(index, options, question) { this.index = index; this.options = options; this.question = question; this.element = createElement(h('li.list-group-item', { style: { width: '100%', height: '500px' } })); this.viewer; if (options.xml) { // Load XML this.xml = options.xml; } else if (options.url) { var that = this; // Load XML via AJAX var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { that.xml = xhr.responseText; } }; xhr.open("GET", options.url, true); xhr.send(); } else { throw new Error('Unable to load diagram, no resource specified'); } this.initState = Immutable({ selected: [] }); this.state = this.initState.asMutable({deep: true}); }
javascript
function Diagram(index, options, question) { this.index = index; this.options = options; this.question = question; this.element = createElement(h('li.list-group-item', { style: { width: '100%', height: '500px' } })); this.viewer; if (options.xml) { // Load XML this.xml = options.xml; } else if (options.url) { var that = this; // Load XML via AJAX var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { that.xml = xhr.responseText; } }; xhr.open("GET", options.url, true); xhr.send(); } else { throw new Error('Unable to load diagram, no resource specified'); } this.initState = Immutable({ selected: [] }); this.state = this.initState.asMutable({deep: true}); }
[ "function", "Diagram", "(", "index", ",", "options", ",", "question", ")", "{", "this", ".", "index", "=", "index", ";", "this", ".", "options", "=", "options", ";", "this", ".", "question", "=", "question", ";", "this", ".", "element", "=", "createEle...
Diagram component. @param {number} index - Index of question. @param {Object} options - Options. @param {Object} question - Reference to the Question instance.
[ "Diagram", "component", "." ]
1f4dc63272f99a491a7ce2a5db7c1d56c3e82132
https://github.com/bpmn-io/bpmn-questionnaire/blob/1f4dc63272f99a491a7ce2a5db7c1d56c3e82132/lib/components/Diagram.js#L25-L73
28,934
raveljs/ravel
lib/util/kvstore.js
createClient
function createClient (ravelInstance, restrict = true) { const localRedis = ravelInstance.get('redis port') === undefined || ravelInstance.get('redis host') === undefined; ravelInstance.on('post init', () => { ravelInstance.$log.info(localRedis ? 'Using in-memory key-value store. Please do not scale this app horizontally.' : `Using redis at ${ravelInstance.get('redis host')}:${ravelInstance.get('redis port')}`); }); let client; if (localRedis) { const mock = require('redis-mock'); mock.removeAllListeners(); // redis-mock doesn't clean up after itself very well. client = mock.createClient(); client.flushall(); // in case this has been required before } else { client = redis.createClient( ravelInstance.get('redis port'), ravelInstance.get('redis host'), { 'no_ready_check': true, 'retry_strategy': retryStrategy(ravelInstance) }); } if (ravelInstance.get('redis password')) { client.auth(ravelInstance.get('redis password')); } // log errors client.on('error', ravelInstance.$log.error); // keepalive when not testing const redisKeepaliveInterval = setInterval(() => { client && client.ping && client.ping(); }, ravelInstance.get('redis keepalive interval')); ravelInstance.once('end', () => { clearInterval(redisKeepaliveInterval); }); if (restrict) { disable(client, 'quit'); disable(client, 'subscribe'); disable(client, 'psubscribe'); disable(client, 'unsubscribe'); disable(client, 'punsubscribe'); } else { const origQuit = client.quit; client.quit = function (...args) { clearInterval(redisKeepaliveInterval); return origQuit.apply(client, args); }; } client.clone = function () { return createClient(ravelInstance, false); }; return client; }
javascript
function createClient (ravelInstance, restrict = true) { const localRedis = ravelInstance.get('redis port') === undefined || ravelInstance.get('redis host') === undefined; ravelInstance.on('post init', () => { ravelInstance.$log.info(localRedis ? 'Using in-memory key-value store. Please do not scale this app horizontally.' : `Using redis at ${ravelInstance.get('redis host')}:${ravelInstance.get('redis port')}`); }); let client; if (localRedis) { const mock = require('redis-mock'); mock.removeAllListeners(); // redis-mock doesn't clean up after itself very well. client = mock.createClient(); client.flushall(); // in case this has been required before } else { client = redis.createClient( ravelInstance.get('redis port'), ravelInstance.get('redis host'), { 'no_ready_check': true, 'retry_strategy': retryStrategy(ravelInstance) }); } if (ravelInstance.get('redis password')) { client.auth(ravelInstance.get('redis password')); } // log errors client.on('error', ravelInstance.$log.error); // keepalive when not testing const redisKeepaliveInterval = setInterval(() => { client && client.ping && client.ping(); }, ravelInstance.get('redis keepalive interval')); ravelInstance.once('end', () => { clearInterval(redisKeepaliveInterval); }); if (restrict) { disable(client, 'quit'); disable(client, 'subscribe'); disable(client, 'psubscribe'); disable(client, 'unsubscribe'); disable(client, 'punsubscribe'); } else { const origQuit = client.quit; client.quit = function (...args) { clearInterval(redisKeepaliveInterval); return origQuit.apply(client, args); }; } client.clone = function () { return createClient(ravelInstance, false); }; return client; }
[ "function", "createClient", "(", "ravelInstance", ",", "restrict", "=", "true", ")", "{", "const", "localRedis", "=", "ravelInstance", ".", "get", "(", "'redis port'", ")", "===", "undefined", "||", "ravelInstance", ".", "get", "(", "'redis host'", ")", "===",...
Returns a fresh connection to Redis. @param {Ravel} ravelInstance - An instance of a Ravel app. @param {boolean} restrict - Iff true, disable `exit`, `subcribe`, `psubscribe`, `unsubscribe` and `punsubscribe`. @returns {Object} Returns a fresh connection to Redis. @private
[ "Returns", "a", "fresh", "connection", "to", "Redis", "." ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/util/kvstore.js#L52-L107
28,935
bpmn-io/bpmn-questionnaire
lib/BpmnQuestionnaire.js
BpmnQuestionnaire
function BpmnQuestionnaire(options) { // Check if options was provided if (!options) { throw new Error('No options provided'); } if (has(options, 'questionnaireJson')) { this.questionnaireJson = options.questionnaireJson; } else { // Report error throw new Error('No questionnaire specified'); } // Events this.events = new EventEmitter(); // Services this.services = { translator: (function(){ var translator; if(has(options, 'plugins.translator')) { // translator = new Translator(options.plugins.translator) translator = new Translator(options.plugins.translator); } else { translator = new Translator(); } return translator.translate.bind(translator); }()) } // Check if types were provided if (options.types) { this.types = options.types; } // Check if questions were provided if (this.questionnaireJson.questions.length) { this.questions = []; var that = this; // Create questions this.questionnaireJson.questions.forEach(function(question, index) { // Check if type of question was provided if (!typeof that.types[question.type] === 'function') { // Report error throw new Error('Type not specified'); } else { // Add instance of question to array of questions that.questions.push( new that.types[question.type](index, question, that) ); } }); } else { // Report error throw new Error('No questions specified'); } // Initial state is immutable this.initState = Immutable({ currentQuestion: 0, progress: 0, view: 'intro' }); // Set state to mutable copy of initial state this.state = this.initState.asMutable({deep: true}); // Set up loop this.loop = mainLoop(this.state, this.render.bind(this), { create: require("virtual-dom/create-element"), diff: require("virtual-dom/diff"), patch: require("virtual-dom/patch") }); // Check if container element was specified if (!options.container) { throw new Error('No container element specified'); } // Append questionnaire to container element if (typeof options.container === 'string') { // Search for element with given ID var container = document.getElementById(options.container); // Error handling if (!container) { throw new Error('Container element not found'); } this.container = container; } else if (options.container.appendChild) { // Append questionnaire this.container = options.container; } else { throw new Error('Container element not found'); } // Append questionnaire this.container.appendChild(this.loop.target); }
javascript
function BpmnQuestionnaire(options) { // Check if options was provided if (!options) { throw new Error('No options provided'); } if (has(options, 'questionnaireJson')) { this.questionnaireJson = options.questionnaireJson; } else { // Report error throw new Error('No questionnaire specified'); } // Events this.events = new EventEmitter(); // Services this.services = { translator: (function(){ var translator; if(has(options, 'plugins.translator')) { // translator = new Translator(options.plugins.translator) translator = new Translator(options.plugins.translator); } else { translator = new Translator(); } return translator.translate.bind(translator); }()) } // Check if types were provided if (options.types) { this.types = options.types; } // Check if questions were provided if (this.questionnaireJson.questions.length) { this.questions = []; var that = this; // Create questions this.questionnaireJson.questions.forEach(function(question, index) { // Check if type of question was provided if (!typeof that.types[question.type] === 'function') { // Report error throw new Error('Type not specified'); } else { // Add instance of question to array of questions that.questions.push( new that.types[question.type](index, question, that) ); } }); } else { // Report error throw new Error('No questions specified'); } // Initial state is immutable this.initState = Immutable({ currentQuestion: 0, progress: 0, view: 'intro' }); // Set state to mutable copy of initial state this.state = this.initState.asMutable({deep: true}); // Set up loop this.loop = mainLoop(this.state, this.render.bind(this), { create: require("virtual-dom/create-element"), diff: require("virtual-dom/diff"), patch: require("virtual-dom/patch") }); // Check if container element was specified if (!options.container) { throw new Error('No container element specified'); } // Append questionnaire to container element if (typeof options.container === 'string') { // Search for element with given ID var container = document.getElementById(options.container); // Error handling if (!container) { throw new Error('Container element not found'); } this.container = container; } else if (options.container.appendChild) { // Append questionnaire this.container = options.container; } else { throw new Error('Container element not found'); } // Append questionnaire this.container.appendChild(this.loop.target); }
[ "function", "BpmnQuestionnaire", "(", "options", ")", "{", "// Check if options was provided", "if", "(", "!", "options", ")", "{", "throw", "new", "Error", "(", "'No options provided'", ")", ";", "}", "if", "(", "has", "(", "options", ",", "'questionnaireJson'"...
Creates a new instance of a questionnaire and appends it to a container element. @constructor @param {Object} options - Options. @param {Object} options.questionnaireJson - Questionnaire. @param {Object} options.types - Types. @param {Object|string} - options.container - Element or ID of element that's going to contain the questionnaire.
[ "Creates", "a", "new", "instance", "of", "a", "questionnaire", "and", "appends", "it", "to", "a", "container", "element", "." ]
1f4dc63272f99a491a7ce2a5db7c1d56c3e82132
https://github.com/bpmn-io/bpmn-questionnaire/blob/1f4dc63272f99a491a7ce2a5db7c1d56c3e82132/lib/BpmnQuestionnaire.js#L42-L152
28,936
bpmn-io/bpmn-questionnaire
lib/BpmnQuestionnaire.js
function (index, options, questionnaire) { this.index = index; this.options = options; this.questionnaire = questionnaire; if (options.diagram) { this.diagram = new Diagram(index, options.diagram, this); } // Initial state is immutable this.initState = Immutable({ validAnswer: false, rightAnswer: false, view: 'question' }); // Prevent overwriting default properties of state and assign provided properties to initial state if (has(spec, 'addToState')) { if(!has(spec.addToState, 'validAnswer') && !has(spec.addToState, 'rightAnswer') && !has(spec.addToState, 'view')) { // Merge immutable with object this.initState = this.initState.merge(spec.addToState); } } // Set state to mutable copy of initial state this.state = this.initState.asMutable({deep: true}); }
javascript
function (index, options, questionnaire) { this.index = index; this.options = options; this.questionnaire = questionnaire; if (options.diagram) { this.diagram = new Diagram(index, options.diagram, this); } // Initial state is immutable this.initState = Immutable({ validAnswer: false, rightAnswer: false, view: 'question' }); // Prevent overwriting default properties of state and assign provided properties to initial state if (has(spec, 'addToState')) { if(!has(spec.addToState, 'validAnswer') && !has(spec.addToState, 'rightAnswer') && !has(spec.addToState, 'view')) { // Merge immutable with object this.initState = this.initState.merge(spec.addToState); } } // Set state to mutable copy of initial state this.state = this.initState.asMutable({deep: true}); }
[ "function", "(", "index", ",", "options", ",", "questionnaire", ")", "{", "this", ".", "index", "=", "index", ";", "this", ".", "options", "=", "options", ";", "this", ".", "questionnaire", "=", "questionnaire", ";", "if", "(", "options", ".", "diagram",...
Contructor function that serves as a base for every type. Methods and properties defined in spec will be assigned to the prototype of this constructor. @param {number} index - Index of question inside the array of questions. @param {Object} options - Object containing the actual question. @param {Object} questionnaire - Reference to the questionnaire instance.
[ "Contructor", "function", "that", "serves", "as", "a", "base", "for", "every", "type", ".", "Methods", "and", "properties", "defined", "in", "spec", "will", "be", "assigned", "to", "the", "prototype", "of", "this", "constructor", "." ]
1f4dc63272f99a491a7ce2a5db7c1d56c3e82132
https://github.com/bpmn-io/bpmn-questionnaire/blob/1f4dc63272f99a491a7ce2a5db7c1d56c3e82132/lib/BpmnQuestionnaire.js#L360-L390
28,937
cmrigney/fast-xml2js
index.js
parseString
function parseString(xml, cb) { return fastxml2js.parseString(xml, function(err, data) { //So that it's asynchronous process.nextTick(function() { cb(err, data); }); }); }
javascript
function parseString(xml, cb) { return fastxml2js.parseString(xml, function(err, data) { //So that it's asynchronous process.nextTick(function() { cb(err, data); }); }); }
[ "function", "parseString", "(", "xml", ",", "cb", ")", "{", "return", "fastxml2js", ".", "parseString", "(", "xml", ",", "function", "(", "err", ",", "data", ")", "{", "//So that it's asynchronous", "process", ".", "nextTick", "(", "function", "(", ")", "{...
Callback after xml is parsed @callback parseCallback @param {string} err Error string describing an error that occurred @param {object} obj Resulting parsed JS object Parses an XML string into a JS object @param {string} xml @param {parseCallback} cb
[ "Callback", "after", "xml", "is", "parsed" ]
65b235b04eb0af386f61c59b4fb50063142a1653
https://github.com/cmrigney/fast-xml2js/blob/65b235b04eb0af386f61c59b4fb50063142a1653/index.js#L15-L22
28,938
crucialfelix/supercolliderjs
src/dryads/middleware/scserver.js
_callIfFn
function _callIfFn(thing, context, properties) { return _.isFunction(thing) ? thing(context, properties) : thing; }
javascript
function _callIfFn(thing, context, properties) { return _.isFunction(thing) ? thing(context, properties) : thing; }
[ "function", "_callIfFn", "(", "thing", ",", "context", ",", "properties", ")", "{", "return", "_", ".", "isFunction", "(", "thing", ")", "?", "thing", "(", "context", ",", "properties", ")", ":", "thing", ";", "}" ]
If its a Function then call it with context and properties @private
[ "If", "its", "a", "Function", "then", "call", "it", "with", "context", "and", "properties" ]
77a26c02cf1cdfe5b86699810ab46c6c315f975c
https://github.com/crucialfelix/supercolliderjs/blob/77a26c02cf1cdfe5b86699810ab46c6c315f975c/src/dryads/middleware/scserver.js#L141-L143
28,939
YogaGlo/grunt-docker-compose
tasks/dockerCompose.js
servicesRunning
function servicesRunning() { var composeArgs = ['ps']; // If we're tailing just the main service's logs, then we only check that service if (service === '<%= dockerCompose.options.mainService %>') { composeArgs.push(grunt.config.get('dockerCompose.options.mainService')); } // get the stdout of docker-compose ps, store as Array, and drop the header lines. var serviceList = spawn('docker-compose', composeArgs).stdout.toString().split('\n').slice(2), upCount = 0; // if we are left with 1 line or less, then nothing is running. if (serviceList.length <= 1) { return false; } function isUp(service) { if (service.indexOf('Up') > 0) { upCount++; } } serviceList.forEach(isUp); return upCount > 0; }
javascript
function servicesRunning() { var composeArgs = ['ps']; // If we're tailing just the main service's logs, then we only check that service if (service === '<%= dockerCompose.options.mainService %>') { composeArgs.push(grunt.config.get('dockerCompose.options.mainService')); } // get the stdout of docker-compose ps, store as Array, and drop the header lines. var serviceList = spawn('docker-compose', composeArgs).stdout.toString().split('\n').slice(2), upCount = 0; // if we are left with 1 line or less, then nothing is running. if (serviceList.length <= 1) { return false; } function isUp(service) { if (service.indexOf('Up') > 0) { upCount++; } } serviceList.forEach(isUp); return upCount > 0; }
[ "function", "servicesRunning", "(", ")", "{", "var", "composeArgs", "=", "[", "'ps'", "]", ";", "// If we're tailing just the main service's logs, then we only check that service", "if", "(", "service", "===", "'<%= dockerCompose.options.mainService %>'", ")", "{", "composeAr...
do we have any services running?
[ "do", "we", "have", "any", "services", "running?" ]
6c7f0ab9133d2b049a3497eb05f11f83fbd8c73d
https://github.com/YogaGlo/grunt-docker-compose/blob/6c7f0ab9133d2b049a3497eb05f11f83fbd8c73d/tasks/dockerCompose.js#L253-L279
28,940
elo7/async-define
async-define.js
_define
function _define(/* <exports>, name, dependencies, factory */) { var // extract arguments argv = arguments, argc = argv.length, // extract arguments from function call - (exports?, name?, modules?, factory) exports = argv[argc - 4] || {}, name = argv[argc - 3] || Math.floor(new Date().getTime() * (Math.random())), // if name is undefined or falsy value we add some timestamp like to name. dependencies = argv[argc - 2] || [], factory = argv[argc - 1], // helper variables params = [], dependencies_satisfied = true, dependency_name, result, config_dependencies_iterator = 0, dependencies_iterator = 0, config_dependencies_index = -1; if (DEVELOPMENT) { _set_debug_timer(); } // config dependecies if (_define.prototype.config_dependencies && _define.prototype.config_dependencies.constructor === Array) { var config_dependencies = _define.prototype.config_dependencies || []; var config_dependencies_size = config_dependencies.length; for (; config_dependencies_iterator < config_dependencies_size; config_dependencies_iterator++) { if (name === config_dependencies[config_dependencies_iterator]) { config_dependencies_index = config_dependencies_iterator; } } if (config_dependencies_index !== -1) { config_dependencies.splice(config_dependencies_index, 1) } else { dependencies = dependencies.concat(config_dependencies); } } // find params for (; dependencies_iterator < dependencies.length; dependencies_iterator++) { dependency_name = dependencies[dependencies_iterator]; // if this dependency exists, push it to param injection if (modules.hasOwnProperty(dependency_name)) { params.push(modules[dependency_name]); } else if (dependency_name === 'exports') { params.push(exports); } else { if (argc !== 4) { // if 4 values, is reexecuting // no module found. save these arguments for future execution. define_queue[dependency_name] = define_queue[dependency_name] || []; define_queue[dependency_name].push([exports, name, dependencies, factory]); } dependencies_satisfied = false; } } // all dependencies are satisfied, so proceed if (dependencies_satisfied) { if (!modules.hasOwnProperty(name)) { // execute this module result = factory.apply(this, params); if (result) { modules[name] = result; } else { // assuming result is in exports object modules[name] = exports; } } // execute others waiting for this module while (define_queue[name] && (argv = define_queue[name].pop())) { _define.apply(this, argv); } } }
javascript
function _define(/* <exports>, name, dependencies, factory */) { var // extract arguments argv = arguments, argc = argv.length, // extract arguments from function call - (exports?, name?, modules?, factory) exports = argv[argc - 4] || {}, name = argv[argc - 3] || Math.floor(new Date().getTime() * (Math.random())), // if name is undefined or falsy value we add some timestamp like to name. dependencies = argv[argc - 2] || [], factory = argv[argc - 1], // helper variables params = [], dependencies_satisfied = true, dependency_name, result, config_dependencies_iterator = 0, dependencies_iterator = 0, config_dependencies_index = -1; if (DEVELOPMENT) { _set_debug_timer(); } // config dependecies if (_define.prototype.config_dependencies && _define.prototype.config_dependencies.constructor === Array) { var config_dependencies = _define.prototype.config_dependencies || []; var config_dependencies_size = config_dependencies.length; for (; config_dependencies_iterator < config_dependencies_size; config_dependencies_iterator++) { if (name === config_dependencies[config_dependencies_iterator]) { config_dependencies_index = config_dependencies_iterator; } } if (config_dependencies_index !== -1) { config_dependencies.splice(config_dependencies_index, 1) } else { dependencies = dependencies.concat(config_dependencies); } } // find params for (; dependencies_iterator < dependencies.length; dependencies_iterator++) { dependency_name = dependencies[dependencies_iterator]; // if this dependency exists, push it to param injection if (modules.hasOwnProperty(dependency_name)) { params.push(modules[dependency_name]); } else if (dependency_name === 'exports') { params.push(exports); } else { if (argc !== 4) { // if 4 values, is reexecuting // no module found. save these arguments for future execution. define_queue[dependency_name] = define_queue[dependency_name] || []; define_queue[dependency_name].push([exports, name, dependencies, factory]); } dependencies_satisfied = false; } } // all dependencies are satisfied, so proceed if (dependencies_satisfied) { if (!modules.hasOwnProperty(name)) { // execute this module result = factory.apply(this, params); if (result) { modules[name] = result; } else { // assuming result is in exports object modules[name] = exports; } } // execute others waiting for this module while (define_queue[name] && (argv = define_queue[name].pop())) { _define.apply(this, argv); } } }
[ "function", "_define", "(", "/* <exports>, name, dependencies, factory */", ")", "{", "var", "// extract arguments", "argv", "=", "arguments", ",", "argc", "=", "argv", ".", "length", ",", "// extract arguments from function call - (exports?, name?, modules?, factory)", "export...
the 'define' function
[ "the", "define", "function" ]
33d411de98c8004de4ffe1c6515643fc8ae5e192
https://github.com/elo7/async-define/blob/33d411de98c8004de4ffe1c6515643fc8ae5e192/async-define.js#L95-L176
28,941
nymag/dom
index.js
matches
function matches(node, selector) { var parent, matches, i; if (node.matches) { return node.matches(selector); } else { parent = node.parentElement; matches = parent ? parent.querySelectorAll(selector) : []; i = 0; while (matches[i] && matches[i] !== node) { i++; } return !!matches[i]; } }
javascript
function matches(node, selector) { var parent, matches, i; if (node.matches) { return node.matches(selector); } else { parent = node.parentElement; matches = parent ? parent.querySelectorAll(selector) : []; i = 0; while (matches[i] && matches[i] !== node) { i++; } return !!matches[i]; } }
[ "function", "matches", "(", "node", ",", "selector", ")", "{", "var", "parent", ",", "matches", ",", "i", ";", "if", "(", "node", ".", "matches", ")", "{", "return", "node", ".", "matches", "(", "selector", ")", ";", "}", "else", "{", "parent", "="...
Returns true if the element would be selected by the specified selector. Essentially a polyfill, but necessary for `closest`. @param {Node} node preferably an Element for better performance, but it will accept any Node. @param {string} selector @returns {boolean}
[ "Returns", "true", "if", "the", "element", "would", "be", "selected", "by", "the", "specified", "selector", ".", "Essentially", "a", "polyfill", "but", "necessary", "for", "closest", "." ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L81-L95
28,942
nymag/dom
index.js
closest
function closest(node, parentSelector) { var cursor = node; if (!parentSelector || typeof parentSelector !== 'string') { throw new Error('Please specify a selector to match against!'); } while (cursor && !matches(cursor, parentSelector)) { cursor = cursor.parentNode; } if (!cursor) { return null; } else { return cursor; } }
javascript
function closest(node, parentSelector) { var cursor = node; if (!parentSelector || typeof parentSelector !== 'string') { throw new Error('Please specify a selector to match against!'); } while (cursor && !matches(cursor, parentSelector)) { cursor = cursor.parentNode; } if (!cursor) { return null; } else { return cursor; } }
[ "function", "closest", "(", "node", ",", "parentSelector", ")", "{", "var", "cursor", "=", "node", ";", "if", "(", "!", "parentSelector", "||", "typeof", "parentSelector", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Please specify a selector t...
get closest element that matches selector starting with the element itself and traversing up through parents. @param {Element} node @param {string} parentSelector @return {Element|null}
[ "get", "closest", "element", "that", "matches", "selector", "starting", "with", "the", "element", "itself", "and", "traversing", "up", "through", "parents", "." ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L103-L119
28,943
nymag/dom
index.js
wrapElements
function wrapElements(els, wrapper) { var wrapperEl = document.createElement(wrapper); // make sure elements are in an array if (els instanceof HTMLElement) { els = [els]; } else { els = Array.prototype.slice.call(els); } _each(els, function (el) { // put it into the wrapper, remove it from its parent el.parentNode.removeChild(el); wrapperEl.appendChild(el); }); // return the wrapped elements return wrapperEl; }
javascript
function wrapElements(els, wrapper) { var wrapperEl = document.createElement(wrapper); // make sure elements are in an array if (els instanceof HTMLElement) { els = [els]; } else { els = Array.prototype.slice.call(els); } _each(els, function (el) { // put it into the wrapper, remove it from its parent el.parentNode.removeChild(el); wrapperEl.appendChild(el); }); // return the wrapped elements return wrapperEl; }
[ "function", "wrapElements", "(", "els", ",", "wrapper", ")", "{", "var", "wrapperEl", "=", "document", ".", "createElement", "(", "wrapper", ")", ";", "// make sure elements are in an array", "if", "(", "els", "instanceof", "HTMLElement", ")", "{", "els", "=", ...
wrap elements in another element @param {NodeList|Element} els @param {string} wrapper @returns {Element} wrapperEl
[ "wrap", "elements", "in", "another", "element" ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L178-L196
28,944
nymag/dom
index.js
unwrapElements
function unwrapElements(parent, wrapper) { var el = wrapper.childNodes[0]; // ok, so this looks weird, right? // turns out, appending nodes to another node will remove them // from the live NodeList, so we can keep iterating over the // first item in that list and grab all of them. Nice! while (el) { parent.appendChild(el); el = wrapper.childNodes[0]; } parent.removeChild(wrapper); }
javascript
function unwrapElements(parent, wrapper) { var el = wrapper.childNodes[0]; // ok, so this looks weird, right? // turns out, appending nodes to another node will remove them // from the live NodeList, so we can keep iterating over the // first item in that list and grab all of them. Nice! while (el) { parent.appendChild(el); el = wrapper.childNodes[0]; } parent.removeChild(wrapper); }
[ "function", "unwrapElements", "(", "parent", ",", "wrapper", ")", "{", "var", "el", "=", "wrapper", ".", "childNodes", "[", "0", "]", ";", "// ok, so this looks weird, right?", "// turns out, appending nodes to another node will remove them", "// from the live NodeList, so we...
unwrap elements from another element @param {Element} parent @param {Element} wrapper
[ "unwrap", "elements", "from", "another", "element" ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L203-L216
28,945
nymag/dom
index.js
createRemoveNodeHandler
function createRemoveNodeHandler(el, fn) { return function (mutations, observer) { mutations.forEach(function (mutation) { if (_includes(mutation.removedNodes, el)) { fn(); observer.disconnect(); } }); }; }
javascript
function createRemoveNodeHandler(el, fn) { return function (mutations, observer) { mutations.forEach(function (mutation) { if (_includes(mutation.removedNodes, el)) { fn(); observer.disconnect(); } }); }; }
[ "function", "createRemoveNodeHandler", "(", "el", ",", "fn", ")", "{", "return", "function", "(", "mutations", ",", "observer", ")", "{", "mutations", ".", "forEach", "(", "function", "(", "mutation", ")", "{", "if", "(", "_includes", "(", "mutation", ".",...
Create a remove node handler that runs fn and removes the observer. @param {Element} el @param {Function} fn @returns {Function}
[ "Create", "a", "remove", "node", "handler", "that", "runs", "fn", "and", "removes", "the", "observer", "." ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L224-L233
28,946
nymag/dom
index.js
getPos
function getPos(el) { var rect = el.getBoundingClientRect(), scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; return { top: rect.top + scrollY, bottom: rect.top + rect.height + scrollY, height: rect.height }; }
javascript
function getPos(el) { var rect = el.getBoundingClientRect(), scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; return { top: rect.top + scrollY, bottom: rect.top + rect.height + scrollY, height: rect.height }; }
[ "function", "getPos", "(", "el", ")", "{", "var", "rect", "=", "el", ".", "getBoundingClientRect", "(", ")", ",", "scrollY", "=", "window", ".", "pageYOffset", "||", "document", ".", "documentElement", ".", "scrollTop", "||", "document", ".", "body", ".", ...
Get the position of a DOM element @param {Element} el @return {object}
[ "Get", "the", "position", "of", "a", "DOM", "element" ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L252-L261
28,947
ShoppinPal/vend-nodejs-sdk
lib/utils.js
function(tokenService, domainPrefix) { var tokenUrl = tokenService.replace(/\{DOMAIN_PREFIX\}/, domainPrefix); log.debug('token Url: '+ tokenUrl); return tokenUrl; }
javascript
function(tokenService, domainPrefix) { var tokenUrl = tokenService.replace(/\{DOMAIN_PREFIX\}/, domainPrefix); log.debug('token Url: '+ tokenUrl); return tokenUrl; }
[ "function", "(", "tokenService", ",", "domainPrefix", ")", "{", "var", "tokenUrl", "=", "tokenService", ".", "replace", "(", "/", "\\{DOMAIN_PREFIX\\}", "/", ",", "domainPrefix", ")", ";", "log", ".", "debug", "(", "'token Url: '", "+", "tokenUrl", ")", ";",...
If tokenService already has a domainPrefix set because the API consumer passed in a full URL instead of a substitutable one ... then the replace acts as a no-op. @param tokenService @param domain_prefix @returns {*|XML|string|void}
[ "If", "tokenService", "already", "has", "a", "domainPrefix", "set", "because", "the", "API", "consumer", "passed", "in", "a", "full", "URL", "instead", "of", "a", "substitutable", "one", "...", "then", "the", "replace", "acts", "as", "a", "no", "-", "op", ...
7ba24d12b5e68f9e364725fbcdfaff483d81a47c
https://github.com/ShoppinPal/vend-nodejs-sdk/blob/7ba24d12b5e68f9e364725fbcdfaff483d81a47c/lib/utils.js#L66-L70
28,948
gethuman/pancakes
lib/factories/adapter.factory.js
AdapterFactory
function AdapterFactory(injector) { if (!injector.adapters) { return; } var me = this; this.adapterMap = {}; _.each(injector.adapterMap, function (adapterName, adapterType) { var adapter = injector.adapters[adapterName]; if (adapter) { me.adapterMap[adapterType + 'adapter'] = adapter; } }); }
javascript
function AdapterFactory(injector) { if (!injector.adapters) { return; } var me = this; this.adapterMap = {}; _.each(injector.adapterMap, function (adapterName, adapterType) { var adapter = injector.adapters[adapterName]; if (adapter) { me.adapterMap[adapterType + 'adapter'] = adapter; } }); }
[ "function", "AdapterFactory", "(", "injector", ")", "{", "if", "(", "!", "injector", ".", "adapters", ")", "{", "return", ";", "}", "var", "me", "=", "this", ";", "this", ".", "adapterMap", "=", "{", "}", ";", "_", ".", "each", "(", "injector", "."...
Initialize the cache @param injector @constructor
[ "Initialize", "the", "cache" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/adapter.factory.js#L14-L25
28,949
gethuman/pancakes
lib/utensils.js
getCamelCase
function getCamelCase(filePath) { if (!filePath) { return ''; } // clip off everything by after the last slash and the .js filePath = filePath.substring(filePath.lastIndexOf(delim) + 1); if (filePath.substring(filePath.length - 3) === '.js') { filePath = filePath.substring(0, filePath.length - 3); } // replace dots with caps var parts = filePath.split('.'); var i; for (i = 1; i < parts.length; i++) { parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } // replace dashs with caps filePath = parts.join(''); parts = filePath.split('-'); for (i = 1; i < parts.length; i++) { parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } return parts.join(''); }
javascript
function getCamelCase(filePath) { if (!filePath) { return ''; } // clip off everything by after the last slash and the .js filePath = filePath.substring(filePath.lastIndexOf(delim) + 1); if (filePath.substring(filePath.length - 3) === '.js') { filePath = filePath.substring(0, filePath.length - 3); } // replace dots with caps var parts = filePath.split('.'); var i; for (i = 1; i < parts.length; i++) { parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } // replace dashs with caps filePath = parts.join(''); parts = filePath.split('-'); for (i = 1; i < parts.length; i++) { parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } return parts.join(''); }
[ "function", "getCamelCase", "(", "filePath", ")", "{", "if", "(", "!", "filePath", ")", "{", "return", "''", ";", "}", "// clip off everything by after the last slash and the .js", "filePath", "=", "filePath", ".", "substring", "(", "filePath", ".", "lastIndexOf", ...
Get module name from a full file path. This is done by removing the parent dirs and replacing dot naming with camelCase @param filePath Full file path to a pancakes module @return {String} The name of the module.
[ "Get", "module", "name", "from", "a", "full", "file", "path", ".", "This", "is", "done", "by", "removing", "the", "parent", "dirs", "and", "replacing", "dot", "naming", "with", "camelCase" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L31-L59
28,950
gethuman/pancakes
lib/utensils.js
getPascalCase
function getPascalCase(filePath) { var camelCase = getCamelCase(filePath); return camelCase.substring(0, 1).toUpperCase() + camelCase.substring(1); }
javascript
function getPascalCase(filePath) { var camelCase = getCamelCase(filePath); return camelCase.substring(0, 1).toUpperCase() + camelCase.substring(1); }
[ "function", "getPascalCase", "(", "filePath", ")", "{", "var", "camelCase", "=", "getCamelCase", "(", "filePath", ")", ";", "return", "camelCase", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "camelCase", ".", "substring", ...
Get the Pascal Case for a given path @param filePath @returns {string}
[ "Get", "the", "Pascal", "Case", "for", "a", "given", "path" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L66-L69
28,951
gethuman/pancakes
lib/utensils.js
getModulePath
function getModulePath(filePath, fileName) { if (isJavaScript(fileName)) { fileName = fileName.substring(0, fileName.length - 3); } return filePath + '/' + fileName; }
javascript
function getModulePath(filePath, fileName) { if (isJavaScript(fileName)) { fileName = fileName.substring(0, fileName.length - 3); } return filePath + '/' + fileName; }
[ "function", "getModulePath", "(", "filePath", ",", "fileName", ")", "{", "if", "(", "isJavaScript", "(", "fileName", ")", ")", "{", "fileName", "=", "fileName", ".", "substring", "(", "0", ",", "fileName", ".", "length", "-", "3", ")", ";", "}", "retur...
Get the module path that will be used with the require @param filePath @param fileName @returns {string}
[ "Get", "the", "module", "path", "that", "will", "be", "used", "with", "the", "require" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L101-L107
28,952
gethuman/pancakes
lib/utensils.js
parseIfJson
function parseIfJson(val) { if (_.isString(val)) { val = val.trim(); if (val.substring(0, 1) === '{' && val.substring(val.length - 1) === '}') { try { val = JSON.parse(val); } catch (ex) { /* eslint no-console:0 */ console.log(ex); } } } return val; }
javascript
function parseIfJson(val) { if (_.isString(val)) { val = val.trim(); if (val.substring(0, 1) === '{' && val.substring(val.length - 1) === '}') { try { val = JSON.parse(val); } catch (ex) { /* eslint no-console:0 */ console.log(ex); } } } return val; }
[ "function", "parseIfJson", "(", "val", ")", "{", "if", "(", "_", ".", "isString", "(", "val", ")", ")", "{", "val", "=", "val", ".", "trim", "(", ")", ";", "if", "(", "val", ".", "substring", "(", "0", ",", "1", ")", "===", "'{'", "&&", "val"...
If a value is a string of json, parse it out into an object @param val @returns {*}
[ "If", "a", "value", "is", "a", "string", "of", "json", "parse", "it", "out", "into", "an", "object" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L114-L128
28,953
gethuman/pancakes
lib/utensils.js
chainPromises
function chainPromises(calls, val) { if (!calls || !calls.length) { return Q.when(val); } return calls.reduce(Q.when, Q.when(val)); }
javascript
function chainPromises(calls, val) { if (!calls || !calls.length) { return Q.when(val); } return calls.reduce(Q.when, Q.when(val)); }
[ "function", "chainPromises", "(", "calls", ",", "val", ")", "{", "if", "(", "!", "calls", "||", "!", "calls", ".", "length", ")", "{", "return", "Q", ".", "when", "(", "val", ")", ";", "}", "return", "calls", ".", "reduce", "(", "Q", ".", "when",...
Simple function for chaining an array of promise functions. Every function in the promise chain needs to be uniform and accept the same input parameter. This is used for a number of things, but most importantly for the service call chain by API. @param calls Functions that should all take in a value and return a promise or another object @param val The initial value to be passed into the promise chain
[ "Simple", "function", "for", "chaining", "an", "array", "of", "promise", "functions", ".", "Every", "function", "in", "the", "promise", "chain", "needs", "to", "be", "uniform", "and", "accept", "the", "same", "input", "parameter", ".", "This", "is", "used", ...
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L139-L142
28,954
gethuman/pancakes
lib/utensils.js
checksum
function checksum(str) { crcTbl = crcTbl || makeCRCTable(); /* jslint bitwise: true */ var crc = 0 ^ (-1); for (var i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTbl[(crc ^ str.charCodeAt(i)) & 0xFF]; } return (crc ^ (-1)) >>> 0; }
javascript
function checksum(str) { crcTbl = crcTbl || makeCRCTable(); /* jslint bitwise: true */ var crc = 0 ^ (-1); for (var i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTbl[(crc ^ str.charCodeAt(i)) & 0xFF]; } return (crc ^ (-1)) >>> 0; }
[ "function", "checksum", "(", "str", ")", "{", "crcTbl", "=", "crcTbl", "||", "makeCRCTable", "(", ")", ";", "/* jslint bitwise: true */", "var", "crc", "=", "0", "^", "(", "-", "1", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "str", ...
Generate a checkum for a string @param str @returns {number}
[ "Generate", "a", "checkum", "for", "a", "string" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L195-L206
28,955
gethuman/pancakes
lib/dependency.injector.js
DependencyInjector
function DependencyInjector(opts) { var rootDefault = p.join(__dirname, '../../..'); this.rootDir = opts.rootDir || rootDefault; // project base dir (default is a guess) this.require = opts.require || require; // we need require from the project this.container = opts.container || 'api'; // resource has diff profiles for diff containers this.servicesDir = opts.servicesDir || 'services'; // dir where services reside this.tplDir = opts.tplDir || 'dist/tpls'; // precompiled templates this.debug = opts.debug || false; // debug mode will have us firing more events this.debugPattern = opts.debugPattern; // by default if debug on, we view EVERYTHING this.debugHandler = opts.debugHandler; // function used when debug event occurs this.adapters = opts.adapters || {}; // if client uses plugins, they will pass in adapters this.reactors = opts.reactors || {}; // if client uses plugins, they will pass in reactors this.adapterMap = this.loadAdapterMap(opts); // mappings from adapter type to impl this.aliases = this.loadAliases(opts); // mapping of names to locations this.factories = this.loadFactories(opts); // load all the factories }
javascript
function DependencyInjector(opts) { var rootDefault = p.join(__dirname, '../../..'); this.rootDir = opts.rootDir || rootDefault; // project base dir (default is a guess) this.require = opts.require || require; // we need require from the project this.container = opts.container || 'api'; // resource has diff profiles for diff containers this.servicesDir = opts.servicesDir || 'services'; // dir where services reside this.tplDir = opts.tplDir || 'dist/tpls'; // precompiled templates this.debug = opts.debug || false; // debug mode will have us firing more events this.debugPattern = opts.debugPattern; // by default if debug on, we view EVERYTHING this.debugHandler = opts.debugHandler; // function used when debug event occurs this.adapters = opts.adapters || {}; // if client uses plugins, they will pass in adapters this.reactors = opts.reactors || {}; // if client uses plugins, they will pass in reactors this.adapterMap = this.loadAdapterMap(opts); // mappings from adapter type to impl this.aliases = this.loadAliases(opts); // mapping of names to locations this.factories = this.loadFactories(opts); // load all the factories }
[ "function", "DependencyInjector", "(", "opts", ")", "{", "var", "rootDefault", "=", "p", ".", "join", "(", "__dirname", ",", "'../../..'", ")", ";", "this", ".", "rootDir", "=", "opts", ".", "rootDir", "||", "rootDefault", ";", "// project base dir (default is...
Initialize the injector with input options @param opts @constructor
[ "Initialize", "the", "injector", "with", "input", "options" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L27-L42
28,956
gethuman/pancakes
lib/dependency.injector.js
loadFactories
function loadFactories(opts) { this.flapjackFactory = new FlapjackFactory(this); return [ new InternalObjFactory(this), new AdapterFactory(this), new ServiceFactory(this), new ModelFactory(this), new UipartFactory(this), this.flapjackFactory, new ModulePluginFactory(this, opts.modulePlugins), new DefaultFactory(this) ]; }
javascript
function loadFactories(opts) { this.flapjackFactory = new FlapjackFactory(this); return [ new InternalObjFactory(this), new AdapterFactory(this), new ServiceFactory(this), new ModelFactory(this), new UipartFactory(this), this.flapjackFactory, new ModulePluginFactory(this, opts.modulePlugins), new DefaultFactory(this) ]; }
[ "function", "loadFactories", "(", "opts", ")", "{", "this", ".", "flapjackFactory", "=", "new", "FlapjackFactory", "(", "this", ")", ";", "return", "[", "new", "InternalObjFactory", "(", "this", ")", ",", "new", "AdapterFactory", "(", "this", ")", ",", "ne...
Load all the factories @returns {Array}
[ "Load", "all", "the", "factories" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L74-L87
28,957
gethuman/pancakes
lib/dependency.injector.js
loadMappings
function loadMappings(rootDir, paths) { var mappings = {}, i, j, fullPath, fileNames, fileName, path, name, val; if (!paths) { return mappings; } for (i = 0; i < paths.length; i++) { path = paths[i]; fullPath = rootDir + '/' + path; // if the directory doesn't exist, then skip to the next loop iteration if (!fs.existsSync(p.normalize(fullPath))) { continue; } // loop through all files in this folder fileNames = fs.readdirSync(p.normalize(fullPath)); for (j = 0; j < fileNames.length; j++) { fileName = fileNames[j]; // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) { name = utils.getCamelCase(fileName); val = utils.getModulePath(path, fileName); mappings[name] = val; mappings[name.substring(0, 1).toUpperCase() + name.substring(1)] = val; // store PascalCase as well } // else if we are dealing with a directory, recurse down into the folder else if (fs.lstatSync(p.join(fullPath, fileName)).isDirectory()) { _.extend(mappings, this.loadMappings(rootDir, [path + '/' + fileName])); } } } return mappings; }
javascript
function loadMappings(rootDir, paths) { var mappings = {}, i, j, fullPath, fileNames, fileName, path, name, val; if (!paths) { return mappings; } for (i = 0; i < paths.length; i++) { path = paths[i]; fullPath = rootDir + '/' + path; // if the directory doesn't exist, then skip to the next loop iteration if (!fs.existsSync(p.normalize(fullPath))) { continue; } // loop through all files in this folder fileNames = fs.readdirSync(p.normalize(fullPath)); for (j = 0; j < fileNames.length; j++) { fileName = fileNames[j]; // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) { name = utils.getCamelCase(fileName); val = utils.getModulePath(path, fileName); mappings[name] = val; mappings[name.substring(0, 1).toUpperCase() + name.substring(1)] = val; // store PascalCase as well } // else if we are dealing with a directory, recurse down into the folder else if (fs.lstatSync(p.join(fullPath, fileName)).isDirectory()) { _.extend(mappings, this.loadMappings(rootDir, [path + '/' + fileName])); } } } return mappings; }
[ "function", "loadMappings", "(", "rootDir", ",", "paths", ")", "{", "var", "mappings", "=", "{", "}", ",", "i", ",", "j", ",", "fullPath", ",", "fileNames", ",", "fileName", ",", "path", ",", "name", ",", "val", ";", "if", "(", "!", "paths", ")", ...
Based on a given directory, get the mappings of camelCase name for a given file to the file's relative path from the app root. @param rootDir @param paths @returns {{}} The mappings of param name to location
[ "Based", "on", "a", "given", "directory", "get", "the", "mappings", "of", "camelCase", "name", "for", "a", "given", "file", "to", "the", "file", "s", "relative", "path", "from", "the", "app", "root", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L122-L160
28,958
gethuman/pancakes
lib/dependency.injector.js
exists
function exists(modulePath, options) { if (this.aliases[modulePath]) { modulePath = this.aliases[modulePath]; } var len = this.factories.length - 1; // -1 because we don't want the default factory for (var i = 0; this.factories && i < len; i++) { if (this.factories[i].isCandidate(modulePath, options)) { return true; } } return false; }
javascript
function exists(modulePath, options) { if (this.aliases[modulePath]) { modulePath = this.aliases[modulePath]; } var len = this.factories.length - 1; // -1 because we don't want the default factory for (var i = 0; this.factories && i < len; i++) { if (this.factories[i].isCandidate(modulePath, options)) { return true; } } return false; }
[ "function", "exists", "(", "modulePath", ",", "options", ")", "{", "if", "(", "this", ".", "aliases", "[", "modulePath", "]", ")", "{", "modulePath", "=", "this", ".", "aliases", "[", "modulePath", "]", ";", "}", "var", "len", "=", "this", ".", "fact...
Determine if an @param modulePath @param options @returns {boolean}
[ "Determine", "if", "an" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L168-L182
28,959
gethuman/pancakes
lib/dependency.injector.js
loadModule
function loadModule(modulePath, moduleStack, options) { var newModule, i; options = options || {}; // if modulePath is null return null if (!modulePath) { return null; } // if actual flapjack sent in as the module path then switch things around so modulePath name is unique if (_.isFunction(modulePath)) { options.flapjack = modulePath; modulePath = 'module-' + (new Date()).getTime(); } // if we already have a flapjack, make the modulePath unique per the options else if (options.flapjack) { modulePath = (options.app || 'common') + '.' + modulePath + '.' + (options.type || 'default'); } // else we need to get code from the file system, so check to see if we need to switch a mapped name to its path else if (this.aliases[modulePath]) { modulePath = this.aliases[modulePath]; } // if module name already in the stack, then circular reference moduleStack = moduleStack || []; if (moduleStack.indexOf(modulePath) >= 0) { throw new Error('Circular reference since ' + modulePath + ' is in ' + JSON.stringify(moduleStack)); } // add the path to the stack so we don't have a circular dependency moduleStack.push(modulePath); // try to find a factory that can create/get a module for the given path for (i = 0; this.factories && i < this.factories.length; i++) { if (this.factories[i].isCandidate(modulePath, options)) { newModule = this.factories[i].create(modulePath, moduleStack, options); break; } } // if no module found log error if (!newModule && moduleStack && moduleStack.length > 1) { /* eslint no-console:0 */ console.log('ERROR: ' + moduleStack[moduleStack.length - 2] + ' dependency ' + modulePath + ' not found.'); } // pop the current item off the stack moduleStack.pop(); // return the new module (or the default {} if no factories found) return newModule; }
javascript
function loadModule(modulePath, moduleStack, options) { var newModule, i; options = options || {}; // if modulePath is null return null if (!modulePath) { return null; } // if actual flapjack sent in as the module path then switch things around so modulePath name is unique if (_.isFunction(modulePath)) { options.flapjack = modulePath; modulePath = 'module-' + (new Date()).getTime(); } // if we already have a flapjack, make the modulePath unique per the options else if (options.flapjack) { modulePath = (options.app || 'common') + '.' + modulePath + '.' + (options.type || 'default'); } // else we need to get code from the file system, so check to see if we need to switch a mapped name to its path else if (this.aliases[modulePath]) { modulePath = this.aliases[modulePath]; } // if module name already in the stack, then circular reference moduleStack = moduleStack || []; if (moduleStack.indexOf(modulePath) >= 0) { throw new Error('Circular reference since ' + modulePath + ' is in ' + JSON.stringify(moduleStack)); } // add the path to the stack so we don't have a circular dependency moduleStack.push(modulePath); // try to find a factory that can create/get a module for the given path for (i = 0; this.factories && i < this.factories.length; i++) { if (this.factories[i].isCandidate(modulePath, options)) { newModule = this.factories[i].create(modulePath, moduleStack, options); break; } } // if no module found log error if (!newModule && moduleStack && moduleStack.length > 1) { /* eslint no-console:0 */ console.log('ERROR: ' + moduleStack[moduleStack.length - 2] + ' dependency ' + modulePath + ' not found.'); } // pop the current item off the stack moduleStack.pop(); // return the new module (or the default {} if no factories found) return newModule; }
[ "function", "loadModule", "(", "modulePath", ",", "moduleStack", ",", "options", ")", "{", "var", "newModule", ",", "i", ";", "options", "=", "options", "||", "{", "}", ";", "// if modulePath is null return null", "if", "(", "!", "modulePath", ")", "{", "ret...
Load a module using the pancakes injector. The injector relies on a number of factories to do the actual injection. The first factory that can handle a given modulePath input attempts to generate an object or return something from cache that can then be returned back to the caller. @param modulePath Path to module @param moduleStack Stack of modules in recursive call (to prevent circular references) @param options Optional values used by some factories
[ "Load", "a", "module", "using", "the", "pancakes", "injector", ".", "The", "injector", "relies", "on", "a", "number", "of", "factories", "to", "do", "the", "actual", "injection", ".", "The", "first", "factory", "that", "can", "handle", "a", "given", "modul...
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L193-L245
28,960
gethuman/pancakes
lib/dependency.injector.js
injectFlapjack
function injectFlapjack(flapjack, moduleStack, options) { options = options || {}; // if server is false, then return null var moduleInfo = annotations.getModuleInfo(flapjack); if (moduleInfo && moduleInfo.server === false && !options.test) { return null; } // param map is combo of param map set by user, params discovered and current annotation var aliases = _.extend({}, this.aliases, annotations.getServerAliases(flapjack, null)); var params = annotations.getParameters(flapjack); var deps = options.dependencies || {}; var paramModules = []; var me = this; // loop through the params so we can collect the object that will be injected _.each(params, function (param) { var dep = deps[param]; // if mapping exists, switch to the mapping (ex. pancakes -> lib/pancakes) if (aliases[param]) { param = aliases[param]; } // either get the module from the input dependencies or recursively call inject try { paramModules.push(dep || deps[param] || me.loadModule(param, moduleStack)); } catch (ex) { var errMsg = ex.stack || ex; throw new Error('While injecting function, ran into invalid parameter.\nparam: ' + param + '\nstack: ' + JSON.stringify(moduleStack) + '\nfunction: ' + flapjack.toString().substring(0, 100) + '...\nerror: ' + errMsg); } }); // call the flapjack function passing in the array of modules as parameters return flapjack.apply(null, paramModules); }
javascript
function injectFlapjack(flapjack, moduleStack, options) { options = options || {}; // if server is false, then return null var moduleInfo = annotations.getModuleInfo(flapjack); if (moduleInfo && moduleInfo.server === false && !options.test) { return null; } // param map is combo of param map set by user, params discovered and current annotation var aliases = _.extend({}, this.aliases, annotations.getServerAliases(flapjack, null)); var params = annotations.getParameters(flapjack); var deps = options.dependencies || {}; var paramModules = []; var me = this; // loop through the params so we can collect the object that will be injected _.each(params, function (param) { var dep = deps[param]; // if mapping exists, switch to the mapping (ex. pancakes -> lib/pancakes) if (aliases[param]) { param = aliases[param]; } // either get the module from the input dependencies or recursively call inject try { paramModules.push(dep || deps[param] || me.loadModule(param, moduleStack)); } catch (ex) { var errMsg = ex.stack || ex; throw new Error('While injecting function, ran into invalid parameter.\nparam: ' + param + '\nstack: ' + JSON.stringify(moduleStack) + '\nfunction: ' + flapjack.toString().substring(0, 100) + '...\nerror: ' + errMsg); } }); // call the flapjack function passing in the array of modules as parameters return flapjack.apply(null, paramModules); }
[ "function", "injectFlapjack", "(", "flapjack", ",", "moduleStack", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "// if server is false, then return null", "var", "moduleInfo", "=", "annotations", ".", "getModuleInfo", "(", "flapjack", ...
Given a flapjack load all the params and instantiated it. This fn is used by the FlapjackFactory and ModulePluginFactory. @param flapjack @param moduleStack @param options @returns {*}
[ "Given", "a", "flapjack", "load", "all", "the", "params", "and", "instantiated", "it", ".", "This", "fn", "is", "used", "by", "the", "FlapjackFactory", "and", "ModulePluginFactory", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L256-L295
28,961
gethuman/pancakes
lib/factories/module.plugin.factory.js
loadModulePlugins
function loadModulePlugins(modulePlugins) { var serverModules = {}; var me = this; // add modules from each plugin to the serverModules map _.each(modulePlugins, function (modulePlugin) { _.extend(serverModules, me.loadModules(modulePlugin.rootDir, modulePlugin.serverModuleDirs)); }); return serverModules; }
javascript
function loadModulePlugins(modulePlugins) { var serverModules = {}; var me = this; // add modules from each plugin to the serverModules map _.each(modulePlugins, function (modulePlugin) { _.extend(serverModules, me.loadModules(modulePlugin.rootDir, modulePlugin.serverModuleDirs)); }); return serverModules; }
[ "function", "loadModulePlugins", "(", "modulePlugins", ")", "{", "var", "serverModules", "=", "{", "}", ";", "var", "me", "=", "this", ";", "// add modules from each plugin to the serverModules map", "_", ".", "each", "(", "modulePlugins", ",", "function", "(", "m...
Loop through each plugin and add each module to a map @param modulePlugins
[ "Loop", "through", "each", "plugin", "and", "add", "each", "module", "to", "a", "map" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/module.plugin.factory.js#L31-L41
28,962
gethuman/pancakes
lib/factories/module.plugin.factory.js
loadModules
function loadModules(rootDir, paths) { var serverModules = {}; var me = this; // return empty object if no rootDir or paths if (!rootDir || !paths) { return serverModules; } // loop through paths and load all modules in those directories _.each(paths, function (relativePath) { var fullPath = path.normalize(rootDir + delim + relativePath); // if the directory doesn't exist, then skip to the next loop iteration if (fs.existsSync(fullPath)) { _.each(fs.readdirSync(fullPath), function (fileName) { // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) { var nameLower = utils.getCamelCase(fileName).toLowerCase(); var fullFilePath = path.normalize(fullPath + '/' + fileName); // there are 2 diff potential aliases for any given server module serverModules[nameLower + 'fromplugin'] = serverModules[nameLower] = require(fullFilePath); } // else if we are dealing with a directory, recurse down into the folder else if (fs.lstatSync(path.join(fullPath, fileName)).isDirectory()) { _.extend(serverModules, me.loadModules(rootDir, [relativePath + '/' + fileName])); } }); } }); return serverModules; }
javascript
function loadModules(rootDir, paths) { var serverModules = {}; var me = this; // return empty object if no rootDir or paths if (!rootDir || !paths) { return serverModules; } // loop through paths and load all modules in those directories _.each(paths, function (relativePath) { var fullPath = path.normalize(rootDir + delim + relativePath); // if the directory doesn't exist, then skip to the next loop iteration if (fs.existsSync(fullPath)) { _.each(fs.readdirSync(fullPath), function (fileName) { // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) { var nameLower = utils.getCamelCase(fileName).toLowerCase(); var fullFilePath = path.normalize(fullPath + '/' + fileName); // there are 2 diff potential aliases for any given server module serverModules[nameLower + 'fromplugin'] = serverModules[nameLower] = require(fullFilePath); } // else if we are dealing with a directory, recurse down into the folder else if (fs.lstatSync(path.join(fullPath, fileName)).isDirectory()) { _.extend(serverModules, me.loadModules(rootDir, [relativePath + '/' + fileName])); } }); } }); return serverModules; }
[ "function", "loadModules", "(", "rootDir", ",", "paths", ")", "{", "var", "serverModules", "=", "{", "}", ";", "var", "me", "=", "this", ";", "// return empty object if no rootDir or paths", "if", "(", "!", "rootDir", "||", "!", "paths", ")", "{", "return", ...
Recursively go through dirs and add modules to a server modules map that is returned @param rootDir @param paths @returns {*}
[ "Recursively", "go", "through", "dirs", "and", "add", "modules", "to", "a", "server", "modules", "map", "that", "is", "returned" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/module.plugin.factory.js#L49-L84
28,963
gethuman/pancakes
lib/api.route.handler.js
traverseFilters
function traverseFilters(config, levels, levelIdx) { var lastIdx = levels.length - 1; var val, filters; if (!config || levelIdx > lastIdx) { return null; } val = config[levels[levelIdx]]; if (levelIdx === lastIdx) { if (val) { return val; } else { return config.all; } } else { filters = traverseFilters(val, levels, levelIdx + 1); if (!filters) { filters = traverseFilters(config.all, levels, levelIdx + 1); } return filters; } }
javascript
function traverseFilters(config, levels, levelIdx) { var lastIdx = levels.length - 1; var val, filters; if (!config || levelIdx > lastIdx) { return null; } val = config[levels[levelIdx]]; if (levelIdx === lastIdx) { if (val) { return val; } else { return config.all; } } else { filters = traverseFilters(val, levels, levelIdx + 1); if (!filters) { filters = traverseFilters(config.all, levels, levelIdx + 1); } return filters; } }
[ "function", "traverseFilters", "(", "config", ",", "levels", ",", "levelIdx", ")", "{", "var", "lastIdx", "=", "levels", ".", "length", "-", "1", ";", "var", "val", ",", "filters", ";", "if", "(", "!", "config", "||", "levelIdx", ">", "lastIdx", ")", ...
Recurse through the filter config to get the right filter values @param config @param levels @param levelIdx @returns {*}
[ "Recurse", "through", "the", "filter", "config", "to", "get", "the", "right", "filter", "values" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/api.route.handler.js#L27-L51
28,964
gethuman/pancakes
lib/api.route.handler.js
getFilters
function getFilters(resourceName, adapterName, operation) { var filterConfig = injector.loadModule('filterConfig'); var filters = { before: [], after: [] }; if (!filterConfig) { return filters; } var levels = [resourceName, adapterName, operation, 'before']; filters.before = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) { return injector.loadModule(name + 'Filter'); }); levels = [resourceName, adapterName, operation, 'after']; filters.after = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) { return injector.loadModule(name + 'Filter'); }); return filters; }
javascript
function getFilters(resourceName, adapterName, operation) { var filterConfig = injector.loadModule('filterConfig'); var filters = { before: [], after: [] }; if (!filterConfig) { return filters; } var levels = [resourceName, adapterName, operation, 'before']; filters.before = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) { return injector.loadModule(name + 'Filter'); }); levels = [resourceName, adapterName, operation, 'after']; filters.after = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) { return injector.loadModule(name + 'Filter'); }); return filters; }
[ "function", "getFilters", "(", "resourceName", ",", "adapterName", ",", "operation", ")", "{", "var", "filterConfig", "=", "injector", ".", "loadModule", "(", "'filterConfig'", ")", ";", "var", "filters", "=", "{", "before", ":", "[", "]", ",", "after", ":...
Get before and after filters based on the current request and the filter config @param resourceName @param adapterName @param operation @returns {{}}
[ "Get", "before", "and", "after", "filters", "based", "on", "the", "current", "request", "and", "the", "filter", "config" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/api.route.handler.js#L60-L77
28,965
gethuman/pancakes
lib/api.route.handler.js
processApiCall
function processApiCall(resource, operation, requestParams) { var service = injector.loadModule(utensils.getCamelCase(resource.name + '.service')); var adapterName = resource.adapters.api; // remove the keys that start with onBehalfOf _.each(requestParams, function (val, key) { if (key.indexOf('onBehalfOf') === 0) { delete requestParams[key]; } }); // hack fix for when _id not filled in if (requestParams._id === '{_id}') { delete requestParams._id; } // loop through request values and parse json for (var key in requestParams) { if (requestParams.hasOwnProperty(key)) { requestParams[key] = utensils.parseIfJson(requestParams[key]); } } var filters = getFilters(resource.name, adapterName, operation); return utensils.chainPromises(filters.before, requestParams) .then(function (filteredRequest) { requestParams = filteredRequest; return service[operation](requestParams); }) .then(function (data) { return utensils.chainPromises(filters.after, { caller: requestParams.caller, lang: requestParams.lang, resource: resource, inputData: requestParams.data, data: data }); }); }
javascript
function processApiCall(resource, operation, requestParams) { var service = injector.loadModule(utensils.getCamelCase(resource.name + '.service')); var adapterName = resource.adapters.api; // remove the keys that start with onBehalfOf _.each(requestParams, function (val, key) { if (key.indexOf('onBehalfOf') === 0) { delete requestParams[key]; } }); // hack fix for when _id not filled in if (requestParams._id === '{_id}') { delete requestParams._id; } // loop through request values and parse json for (var key in requestParams) { if (requestParams.hasOwnProperty(key)) { requestParams[key] = utensils.parseIfJson(requestParams[key]); } } var filters = getFilters(resource.name, adapterName, operation); return utensils.chainPromises(filters.before, requestParams) .then(function (filteredRequest) { requestParams = filteredRequest; return service[operation](requestParams); }) .then(function (data) { return utensils.chainPromises(filters.after, { caller: requestParams.caller, lang: requestParams.lang, resource: resource, inputData: requestParams.data, data: data }); }); }
[ "function", "processApiCall", "(", "resource", ",", "operation", ",", "requestParams", ")", "{", "var", "service", "=", "injector", ".", "loadModule", "(", "utensils", ".", "getCamelCase", "(", "resource", ".", "name", "+", "'.service'", ")", ")", ";", "var"...
Process an API call. This method is called from the server plugin. Basically, the server plugin is in charge of taking the API request initially and translating the input values from the web framework specific format to the pancakes format. Then the server plugin calls this method with the generic pancancakes values. @param resource @param operation @param requestParams
[ "Process", "an", "API", "call", ".", "This", "method", "is", "called", "from", "the", "server", "plugin", ".", "Basically", "the", "server", "plugin", "is", "in", "charge", "of", "taking", "the", "API", "request", "initially", "and", "translating", "the", ...
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/api.route.handler.js#L89-L125
28,966
gethuman/pancakes
lib/web.route.handler.js
loadInlineCss
function loadInlineCss(rootDir, apps) { _.each(apps, function (app, appName) { _.each(app.routes, function (route) { var filePath = rootDir + '/app/' + appName + '/inline/' + route.name + '.css'; if (route.inline && fs.existsSync(filePath)) { inlineCssCache[appName + '||' + route.name] = fs.readFileSync(filePath, { encoding: 'utf8' }); } }); }); }
javascript
function loadInlineCss(rootDir, apps) { _.each(apps, function (app, appName) { _.each(app.routes, function (route) { var filePath = rootDir + '/app/' + appName + '/inline/' + route.name + '.css'; if (route.inline && fs.existsSync(filePath)) { inlineCssCache[appName + '||' + route.name] = fs.readFileSync(filePath, { encoding: 'utf8' }); } }); }); }
[ "function", "loadInlineCss", "(", "rootDir", ",", "apps", ")", "{", "_", ".", "each", "(", "apps", ",", "function", "(", "app", ",", "appName", ")", "{", "_", ".", "each", "(", "app", ".", "routes", ",", "function", "(", "route", ")", "{", "var", ...
Load all inline css files from the file system @param rootDir @param apps
[ "Load", "all", "inline", "css", "files", "from", "the", "file", "system" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L39-L48
28,967
gethuman/pancakes
lib/web.route.handler.js
convertUrlSegmentToRegex
function convertUrlSegmentToRegex(segment) { // if it has this format "{stuff}" - then it's regex-y var beginIdx = segment.indexOf('{'); var endIdx = segment.indexOf('}'); if (beginIdx < 0) { return segment; } // if capturing regex and trim trailing "}" // this could be a named regex {id:[0-9]+} or just name {companySlug} var pieces = segment.split(':'); if (pieces.length === 2) { if ( pieces[1] === (urlPathPatternSymbol + '}') ) { // special case where we want to capture the whole remaining path, even slashes, like /search/a/b/c/ return urlPathPattern; } else { return '(' + pieces[1].substring(0, pieces[1].length - 1) + ')'; } } else if (pieces.length === 1) { return segment.substring(0, beginIdx) + '[^\\/]+' + segment.substring(endIdx + 1); } else { throw new Error('Weird URL segment- don\'t know how to parse! ' + segment); } }
javascript
function convertUrlSegmentToRegex(segment) { // if it has this format "{stuff}" - then it's regex-y var beginIdx = segment.indexOf('{'); var endIdx = segment.indexOf('}'); if (beginIdx < 0) { return segment; } // if capturing regex and trim trailing "}" // this could be a named regex {id:[0-9]+} or just name {companySlug} var pieces = segment.split(':'); if (pieces.length === 2) { if ( pieces[1] === (urlPathPatternSymbol + '}') ) { // special case where we want to capture the whole remaining path, even slashes, like /search/a/b/c/ return urlPathPattern; } else { return '(' + pieces[1].substring(0, pieces[1].length - 1) + ')'; } } else if (pieces.length === 1) { return segment.substring(0, beginIdx) + '[^\\/]+' + segment.substring(endIdx + 1); } else { throw new Error('Weird URL segment- don\'t know how to parse! ' + segment); } }
[ "function", "convertUrlSegmentToRegex", "(", "segment", ")", "{", "// if it has this format \"{stuff}\" - then it's regex-y", "var", "beginIdx", "=", "segment", ".", "indexOf", "(", "'{'", ")", ";", "var", "endIdx", "=", "segment", ".", "indexOf", "(", "'}'", ")", ...
Convert a segment of URL to a regex pattern for full URL casting below @param segment @returns string A segment as a URL pattern string
[ "Convert", "a", "segment", "of", "URL", "to", "a", "regex", "pattern", "for", "full", "URL", "casting", "below" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L55-L83
28,968
gethuman/pancakes
lib/web.route.handler.js
getTokenValuesFromUrl
function getTokenValuesFromUrl(pattern, url) { var tokenValues = {}, urlSegments = url.split('/'); pattern.split('/').forEach(function (segment, idx) { // this has this form {stuff}, so let's dig var beginIdx = segment.indexOf('{'); var endIdx = segment.indexOf('}'); var endLen = segment.length - endIdx - 1; var urlSegment = urlSegments[idx]; if (beginIdx > -1) { // peel off the { and } at the ends segment = segment.substring(beginIdx + 1, endIdx); var pieces = segment.split(':'); if (pieces.length === 2 && pieces[1] === urlPathPatternSymbol ) { var vals = [urlSegment.substring(beginIdx, urlSegment.length - endLen)]; for ( var i = idx + 1, len = urlSegments.length; i < len; i++ ) { vals.push(urlSegments[i]); } tokenValues[pieces[0]] = vals.join('%20'); // join any remaining segments with a space } else if (pieces.length === 2 || pieces.length === 1) { tokenValues[pieces[0]] = urlSegment.substring(beginIdx, urlSegment.length - endLen); } } // else no token to grab }); return tokenValues; }
javascript
function getTokenValuesFromUrl(pattern, url) { var tokenValues = {}, urlSegments = url.split('/'); pattern.split('/').forEach(function (segment, idx) { // this has this form {stuff}, so let's dig var beginIdx = segment.indexOf('{'); var endIdx = segment.indexOf('}'); var endLen = segment.length - endIdx - 1; var urlSegment = urlSegments[idx]; if (beginIdx > -1) { // peel off the { and } at the ends segment = segment.substring(beginIdx + 1, endIdx); var pieces = segment.split(':'); if (pieces.length === 2 && pieces[1] === urlPathPatternSymbol ) { var vals = [urlSegment.substring(beginIdx, urlSegment.length - endLen)]; for ( var i = idx + 1, len = urlSegments.length; i < len; i++ ) { vals.push(urlSegments[i]); } tokenValues[pieces[0]] = vals.join('%20'); // join any remaining segments with a space } else if (pieces.length === 2 || pieces.length === 1) { tokenValues[pieces[0]] = urlSegment.substring(beginIdx, urlSegment.length - endLen); } } // else no token to grab }); return tokenValues; }
[ "function", "getTokenValuesFromUrl", "(", "pattern", ",", "url", ")", "{", "var", "tokenValues", "=", "{", "}", ",", "urlSegments", "=", "url", ".", "split", "(", "'/'", ")", ";", "pattern", ".", "split", "(", "'/'", ")", ".", "forEach", "(", "function...
Use a given pattern to extract tokens from a given URL @param pattern @param url @returns {{}}
[ "Use", "a", "given", "pattern", "to", "extract", "tokens", "from", "a", "given", "URL" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L129-L161
28,969
gethuman/pancakes
lib/web.route.handler.js
getRouteInfo
function getRouteInfo(appName, urlRequest, query, lang, user, referrer) { var activeUser = user ? { _id: user._id, name: user.username, role: user.role, user: user } : {}; // if route info already in cache, return it var cacheKey = appName + '||' + lang + '||' + urlRequest; var cachedRouteInfo = routeInfoCache[cacheKey]; if (!user && cachedRouteInfo) { cachedRouteInfo.query = query; // query shouldn't be cached return cachedRouteInfo; } // if urlRequest ends in .html it is an amp request so treat it as such var isAmp = /\.html$/.test(urlRequest); if (isAmp) { urlRequest = urlRequest.substring(0, urlRequest.length - 5); } // get the routes and then find the info that matches the current URL var url = urlRequest.toLowerCase(); var i, route, routeInfo; var routes = getRoutes(appName); if (routes) { // loop through routes trying to find the one that matches for (i = 0; i < routes.length; i++) { route = routes[i]; // if there is a match, save the info to cache and return it if (route.urlRegex.test(url)) { routeInfo = _.extend({ appName: appName, referrer: referrer, lang: lang, url: urlRequest, query: query, activeUser: activeUser, isAmp: isAmp, tokens: getTokenValuesFromUrl(route.urlPattern, urlRequest) }, route); // change layout wrapper to amp if request is for amp if (isAmp) { routeInfo.wrapper = 'amp'; } // if no user, then save request in cache if (!user) { routeInfoCache[cacheKey] = routeInfo; } return routeInfo; } } } // if we get here, then no route found, so throw 404 error throw new Error('404: ' + appName + ' ' + urlRequest + ' is not a valid request'); }
javascript
function getRouteInfo(appName, urlRequest, query, lang, user, referrer) { var activeUser = user ? { _id: user._id, name: user.username, role: user.role, user: user } : {}; // if route info already in cache, return it var cacheKey = appName + '||' + lang + '||' + urlRequest; var cachedRouteInfo = routeInfoCache[cacheKey]; if (!user && cachedRouteInfo) { cachedRouteInfo.query = query; // query shouldn't be cached return cachedRouteInfo; } // if urlRequest ends in .html it is an amp request so treat it as such var isAmp = /\.html$/.test(urlRequest); if (isAmp) { urlRequest = urlRequest.substring(0, urlRequest.length - 5); } // get the routes and then find the info that matches the current URL var url = urlRequest.toLowerCase(); var i, route, routeInfo; var routes = getRoutes(appName); if (routes) { // loop through routes trying to find the one that matches for (i = 0; i < routes.length; i++) { route = routes[i]; // if there is a match, save the info to cache and return it if (route.urlRegex.test(url)) { routeInfo = _.extend({ appName: appName, referrer: referrer, lang: lang, url: urlRequest, query: query, activeUser: activeUser, isAmp: isAmp, tokens: getTokenValuesFromUrl(route.urlPattern, urlRequest) }, route); // change layout wrapper to amp if request is for amp if (isAmp) { routeInfo.wrapper = 'amp'; } // if no user, then save request in cache if (!user) { routeInfoCache[cacheKey] = routeInfo; } return routeInfo; } } } // if we get here, then no route found, so throw 404 error throw new Error('404: ' + appName + ' ' + urlRequest + ' is not a valid request'); }
[ "function", "getRouteInfo", "(", "appName", ",", "urlRequest", ",", "query", ",", "lang", ",", "user", ",", "referrer", ")", "{", "var", "activeUser", "=", "user", "?", "{", "_id", ":", "user", ".", "_id", ",", "name", ":", "user", ".", "username", "...
Get info for particular route @param appName @param urlRequest @param query @param lang @param user @param referrer @returns {{}} The routeInfo for a particular request
[ "Get", "info", "for", "particular", "route" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L208-L269
28,970
gethuman/pancakes
lib/web.route.handler.js
setDefaults
function setDefaults(model, defaults) { if (!defaults) { return; } _.each(defaults, function (value, key) { if (model[key] === undefined) { model[key] = value; } }); }
javascript
function setDefaults(model, defaults) { if (!defaults) { return; } _.each(defaults, function (value, key) { if (model[key] === undefined) { model[key] = value; } }); }
[ "function", "setDefaults", "(", "model", ",", "defaults", ")", "{", "if", "(", "!", "defaults", ")", "{", "return", ";", "}", "_", ".", "each", "(", "defaults", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "model", "[", "key", ...
If a default value doesn't exist in the model, set it @param model @param defaults
[ "If", "a", "default", "value", "doesn", "t", "exist", "in", "the", "model", "set", "it" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L276-L284
28,971
gethuman/pancakes
lib/web.route.handler.js
getInitialModel
function getInitialModel(routeInfo, page) { var initModelDeps = { appName: routeInfo.appName, tokens: routeInfo.tokens, routeInfo: routeInfo, defaults: page.defaults, activeUser: routeInfo.activeUser || {}, currentScope: {} }; // if no model, just return empty object if (!page.model) { return Q.when({}); } // if function, inject and the returned value is the model else if (_.isFunction(page.model)) { return Q.when(injector.loadModule(page.model, null, { dependencies: initModelDeps })); } else { throw new Error(routeInfo.name + ' page invalid model() format: ' + page.model); } }
javascript
function getInitialModel(routeInfo, page) { var initModelDeps = { appName: routeInfo.appName, tokens: routeInfo.tokens, routeInfo: routeInfo, defaults: page.defaults, activeUser: routeInfo.activeUser || {}, currentScope: {} }; // if no model, just return empty object if (!page.model) { return Q.when({}); } // if function, inject and the returned value is the model else if (_.isFunction(page.model)) { return Q.when(injector.loadModule(page.model, null, { dependencies: initModelDeps })); } else { throw new Error(routeInfo.name + ' page invalid model() format: ' + page.model); } }
[ "function", "getInitialModel", "(", "routeInfo", ",", "page", ")", "{", "var", "initModelDeps", "=", "{", "appName", ":", "routeInfo", ".", "appName", ",", "tokens", ":", "routeInfo", ".", "tokens", ",", "routeInfo", ":", "routeInfo", ",", "defaults", ":", ...
Get the initial model for a given page @param routeInfo @param page
[ "Get", "the", "initial", "model", "for", "a", "given", "page" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L291-L312
28,972
gethuman/pancakes
lib/web.route.handler.js
processWebRequest
function processWebRequest(routeInfo, callbacks) { var appName = routeInfo.appName; var serverOnly = !!routeInfo.query.server; var page = injector.loadModule('app/' + appName + '/pages/' + routeInfo.name + '.page'); // get the callbacks var serverPreprocessing = callbacks.serverPreprocessing || function () { return false; }; var appAddToModel = callbacks.addToModel || function () {}; var pageCacheService = callbacks.pageCacheService || defaultPageCache; var initialModel, cacheKey; return getInitialModel(routeInfo, page) .then(function (model) { initialModel = model || {}; // if the server pre-processing returns true, then return without doing anything // this is because the pre-processor sent a reply to the user already if (serverPreprocessing(routeInfo, page, model)) { return true; } //TODO: may be weird edge cases with this. need to test more to ensure performance and uniqueness // but note that we have an hour default timeout for the redis cache just in case // and we have the redis LRU config set up so the least recently used will get pushed out cacheKey = utensils.checksum(routeInfo.lang + '||' + routeInfo.appName + '||' + routeInfo.url + '||' + JSON.stringify(model)); return pageCacheService.get({ key: cacheKey }); }) .then(function (cachedPage) { if (cachedPage === true) { return null; } if (cachedPage && !serverOnly) { return cachedPage; } // allow the app level to modify the model before rendering appAddToModel(initialModel, routeInfo); // finally use the client side plugin to do the rendering return clientPlugin.renderPage(routeInfo, page, initialModel, inlineCssCache[appName + '||' + routeInfo.name]); }) .then(function (renderedPage) { if (!serverOnly && renderedPage) { pageCacheService.set({ key: cacheKey, value: renderedPage }); } return renderedPage; }); }
javascript
function processWebRequest(routeInfo, callbacks) { var appName = routeInfo.appName; var serverOnly = !!routeInfo.query.server; var page = injector.loadModule('app/' + appName + '/pages/' + routeInfo.name + '.page'); // get the callbacks var serverPreprocessing = callbacks.serverPreprocessing || function () { return false; }; var appAddToModel = callbacks.addToModel || function () {}; var pageCacheService = callbacks.pageCacheService || defaultPageCache; var initialModel, cacheKey; return getInitialModel(routeInfo, page) .then(function (model) { initialModel = model || {}; // if the server pre-processing returns true, then return without doing anything // this is because the pre-processor sent a reply to the user already if (serverPreprocessing(routeInfo, page, model)) { return true; } //TODO: may be weird edge cases with this. need to test more to ensure performance and uniqueness // but note that we have an hour default timeout for the redis cache just in case // and we have the redis LRU config set up so the least recently used will get pushed out cacheKey = utensils.checksum(routeInfo.lang + '||' + routeInfo.appName + '||' + routeInfo.url + '||' + JSON.stringify(model)); return pageCacheService.get({ key: cacheKey }); }) .then(function (cachedPage) { if (cachedPage === true) { return null; } if (cachedPage && !serverOnly) { return cachedPage; } // allow the app level to modify the model before rendering appAddToModel(initialModel, routeInfo); // finally use the client side plugin to do the rendering return clientPlugin.renderPage(routeInfo, page, initialModel, inlineCssCache[appName + '||' + routeInfo.name]); }) .then(function (renderedPage) { if (!serverOnly && renderedPage) { pageCacheService.set({ key: cacheKey, value: renderedPage }); } return renderedPage; }); }
[ "function", "processWebRequest", "(", "routeInfo", ",", "callbacks", ")", "{", "var", "appName", "=", "routeInfo", ".", "appName", ";", "var", "serverOnly", "=", "!", "!", "routeInfo", ".", "query", ".", "server", ";", "var", "page", "=", "injector", ".", ...
This function is called by the server plugin when we have a request and we need to process it. The plugin should handle translating the server platform specific values into our routeInfo @param routeInfo @param callbacks
[ "This", "function", "is", "called", "by", "the", "server", "plugin", "when", "we", "have", "a", "request", "and", "we", "need", "to", "process", "it", ".", "The", "plugin", "should", "handle", "translating", "the", "server", "platform", "specific", "values",...
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L322-L368
28,973
gethuman/pancakes
lib/transformers/transformer.factory.js
generateTransformer
function generateTransformer(name, transformerFns, templateDir, pluginOptions) { var Transformer = function () {}; var transformer = new Transformer(); // add function mixins to the transformer _.extend(transformer, transformerFns, baseTransformer, annotationHelper, utensils, pluginOptions); // add reference to the template function transformer.setTemplate(templateDir, name, pluginOptions.clientType); // each transformer can reference each other transformer.transformers = cache; // return the transformer return transformer; }
javascript
function generateTransformer(name, transformerFns, templateDir, pluginOptions) { var Transformer = function () {}; var transformer = new Transformer(); // add function mixins to the transformer _.extend(transformer, transformerFns, baseTransformer, annotationHelper, utensils, pluginOptions); // add reference to the template function transformer.setTemplate(templateDir, name, pluginOptions.clientType); // each transformer can reference each other transformer.transformers = cache; // return the transformer return transformer; }
[ "function", "generateTransformer", "(", "name", ",", "transformerFns", ",", "templateDir", ",", "pluginOptions", ")", "{", "var", "Transformer", "=", "function", "(", ")", "{", "}", ";", "var", "transformer", "=", "new", "Transformer", "(", ")", ";", "// add...
Generate a transformer object based off the input params @param name @param transformerFns @param templateDir @param pluginOptions
[ "Generate", "a", "transformer", "object", "based", "off", "the", "input", "params" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/transformer.factory.js#L20-L36
28,974
gethuman/pancakes
lib/transformers/transformer.factory.js
getTransformer
function getTransformer(name, clientPlugin, pluginOptions) { // if in cache, just return it if (cache[name]) { return cache[name]; } var transformers = clientPlugin.transformers; var templateDir = clientPlugin.templateDir; // if no transformer, throw error if (!transformers[name]) { throw new Error('No transformer called ' + name); } // generate all the transformers _.each(transformers, function (transformer, transformerName) { cache[transformerName] = generateTransformer(transformerName, transformer, templateDir, pluginOptions); }); // return the specific one that was requested return cache[name]; }
javascript
function getTransformer(name, clientPlugin, pluginOptions) { // if in cache, just return it if (cache[name]) { return cache[name]; } var transformers = clientPlugin.transformers; var templateDir = clientPlugin.templateDir; // if no transformer, throw error if (!transformers[name]) { throw new Error('No transformer called ' + name); } // generate all the transformers _.each(transformers, function (transformer, transformerName) { cache[transformerName] = generateTransformer(transformerName, transformer, templateDir, pluginOptions); }); // return the specific one that was requested return cache[name]; }
[ "function", "getTransformer", "(", "name", ",", "clientPlugin", ",", "pluginOptions", ")", "{", "// if in cache, just return it", "if", "(", "cache", "[", "name", "]", ")", "{", "return", "cache", "[", "name", "]", ";", "}", "var", "transformers", "=", "clie...
Get a particular transformer from cache or generate it @param name @param clientPlugin @param pluginOptions
[ "Get", "a", "particular", "transformer", "from", "cache", "or", "generate", "it" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/transformer.factory.js#L44-L62
28,975
gethuman/pancakes
lib/pancakes.js
init
function init(opts) { opts = opts || {}; // include pancakes instance into options that we pass to plugins opts.pluginOptions = opts.pluginOptions || {}; opts.pluginOptions.pancakes = exports; injector = new DependencyInjector(opts); var ClientPlugin = opts.clientPlugin; var ServerPlugin = opts.serverPlugin; if (ClientPlugin) { clientPlugin = new ClientPlugin(opts); } if (ServerPlugin) { serverPlugin = new ServerPlugin(opts); } apiRouteHandler.init({ injector: injector }); webRouteHandler.init({ injector: injector, clientPlugin: clientPlugin, rootDir: opts.rootDir }); }
javascript
function init(opts) { opts = opts || {}; // include pancakes instance into options that we pass to plugins opts.pluginOptions = opts.pluginOptions || {}; opts.pluginOptions.pancakes = exports; injector = new DependencyInjector(opts); var ClientPlugin = opts.clientPlugin; var ServerPlugin = opts.serverPlugin; if (ClientPlugin) { clientPlugin = new ClientPlugin(opts); } if (ServerPlugin) { serverPlugin = new ServerPlugin(opts); } apiRouteHandler.init({ injector: injector }); webRouteHandler.init({ injector: injector, clientPlugin: clientPlugin, rootDir: opts.rootDir }); }
[ "function", "init", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "// include pancakes instance into options that we pass to plugins", "opts", ".", "pluginOptions", "=", "opts", ".", "pluginOptions", "||", "{", "}", ";", "opts", ".", "pluginOp...
For now this is just a passthrough to the injector's init function @param opts
[ "For", "now", "this", "is", "just", "a", "passthrough", "to", "the", "injector", "s", "init", "function" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L24-L40
28,976
gethuman/pancakes
lib/pancakes.js
initContainer
function initContainer(opts) { var apps, appDir; container = opts.container; // if batch, preload that dir container === 'batch' ? opts.preload.push('batch') : opts.preload.push('middleware'); if (container === 'webserver') { appDir = path.join(opts.rootDir, '/app'); apps = fs.readdirSync(appDir); _.each(apps, function (app) { opts.preload = opts.preload.concat([ 'app/' + app + '/filters', 'app/' + app + '/utils' ]); }); } init(opts); }
javascript
function initContainer(opts) { var apps, appDir; container = opts.container; // if batch, preload that dir container === 'batch' ? opts.preload.push('batch') : opts.preload.push('middleware'); if (container === 'webserver') { appDir = path.join(opts.rootDir, '/app'); apps = fs.readdirSync(appDir); _.each(apps, function (app) { opts.preload = opts.preload.concat([ 'app/' + app + '/filters', 'app/' + app + '/utils' ]); }); } init(opts); }
[ "function", "initContainer", "(", "opts", ")", "{", "var", "apps", ",", "appDir", ";", "container", "=", "opts", ".", "container", ";", "// if batch, preload that dir", "container", "===", "'batch'", "?", "opts", ".", "preload", ".", "push", "(", "'batch'", ...
Convenience function for apps to use. Calls init after setting some values. @param opts
[ "Convenience", "function", "for", "apps", "to", "use", ".", "Calls", "init", "after", "setting", "some", "values", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L48-L70
28,977
gethuman/pancakes
lib/pancakes.js
requireModule
function requireModule(filePath, refreshFlag) { if (refreshFlag) { delete injector.require.cache[filePath]; } return injector.require(filePath); }
javascript
function requireModule(filePath, refreshFlag) { if (refreshFlag) { delete injector.require.cache[filePath]; } return injector.require(filePath); }
[ "function", "requireModule", "(", "filePath", ",", "refreshFlag", ")", "{", "if", "(", "refreshFlag", ")", "{", "delete", "injector", ".", "require", ".", "cache", "[", "filePath", "]", ";", "}", "return", "injector", ".", "require", "(", "filePath", ")", ...
Use the injector require which should be passed in during initialization @param filePath @param refreshFlag @returns {injector.require|*|require}
[ "Use", "the", "injector", "require", "which", "should", "be", "passed", "in", "during", "initialization" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L78-L83
28,978
gethuman/pancakes
lib/pancakes.js
getService
function getService(name) { if (name.indexOf('.') >= 0) { name = utils.getCamelCase(name); } if (!name.match(/^.*Service$/)) { name += 'Service'; } return cook(name); }
javascript
function getService(name) { if (name.indexOf('.') >= 0) { name = utils.getCamelCase(name); } if (!name.match(/^.*Service$/)) { name += 'Service'; } return cook(name); }
[ "function", "getService", "(", "name", ")", "{", "if", "(", "name", ".", "indexOf", "(", "'.'", ")", ">=", "0", ")", "{", "name", "=", "utils", ".", "getCamelCase", "(", "name", ")", ";", "}", "if", "(", "!", "name", ".", "match", "(", "/", "^....
Get the service for a given resource name @param name
[ "Get", "the", "service", "for", "a", "given", "resource", "name" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L98-L108
28,979
gethuman/pancakes
lib/pancakes.js
transform
function transform(flapjack, pluginOptions, runtimeOptions) { var name = runtimeOptions.transformer; var transformer = transformerFactory.getTransformer(name, clientPlugin, pluginOptions); var options = _.extend({}, pluginOptions, runtimeOptions); return transformer.transform(flapjack, options); }
javascript
function transform(flapjack, pluginOptions, runtimeOptions) { var name = runtimeOptions.transformer; var transformer = transformerFactory.getTransformer(name, clientPlugin, pluginOptions); var options = _.extend({}, pluginOptions, runtimeOptions); return transformer.transform(flapjack, options); }
[ "function", "transform", "(", "flapjack", ",", "pluginOptions", ",", "runtimeOptions", ")", "{", "var", "name", "=", "runtimeOptions", ".", "transformer", ";", "var", "transformer", "=", "transformerFactory", ".", "getTransformer", "(", "name", ",", "clientPlugin"...
Use the transformer factory to find a transformer and return the generated code @param flapjack @param pluginOptions @param runtimeOptions @returns {*}
[ "Use", "the", "transformer", "factory", "to", "find", "a", "transformer", "and", "return", "the", "generated", "code" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L138-L143
28,980
creationix/topcube
sampleapp/www/todos.js
function(e) { var tooltip = this.$(".ui-tooltip-top"); var val = this.input.val(); tooltip.fadeOut(); if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout); if (val == '' || val == this.input.attr('placeholder')) return; var show = function(){ tooltip.show().fadeIn(); }; this.tooltipTimeout = _.delay(show, 1000); }
javascript
function(e) { var tooltip = this.$(".ui-tooltip-top"); var val = this.input.val(); tooltip.fadeOut(); if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout); if (val == '' || val == this.input.attr('placeholder')) return; var show = function(){ tooltip.show().fadeIn(); }; this.tooltipTimeout = _.delay(show, 1000); }
[ "function", "(", "e", ")", "{", "var", "tooltip", "=", "this", ".", "$", "(", "\".ui-tooltip-top\"", ")", ";", "var", "val", "=", "this", ".", "input", ".", "val", "(", ")", ";", "tooltip", ".", "fadeOut", "(", ")", ";", "if", "(", "this", ".", ...
Lazily show the tooltip that tells you to press `enter` to save a new todo item, after one second.
[ "Lazily", "show", "the", "tooltip", "that", "tells", "you", "to", "press", "enter", "to", "save", "a", "new", "todo", "item", "after", "one", "second", "." ]
96ff0177bf8f490cabd78eb7b63be6b1bc126d23
https://github.com/creationix/topcube/blob/96ff0177bf8f490cabd78eb7b63be6b1bc126d23/sampleapp/www/todos.js#L241-L249
28,981
gethuman/pancakes
lib/factories/uipart.factory.js
getUiPart
function getUiPart(modulePath, options) { var rootDir = this.injector.rootDir; var tplDir = (options && options.tplDir) || 'dist' + delim + 'tpls'; var pathParts = modulePath.split(delim); var appName = pathParts[1]; var len = modulePath.length; var filePath, fullModulePath, uipart, viewObj; // filePath has .js, modulePath does not if (modulePath.substring(len - 3) === '.js') { filePath = rootDir + delim + modulePath; fullModulePath = rootDir + delim + modulePath.substring(0, len - 3); } else { filePath = rootDir + delim + modulePath + '.js'; fullModulePath = rootDir + delim + modulePath; } // if exists, get it if (fs.existsSync(filePath)) { uipart = this.injector.require(fullModulePath); } // else if in an app folder, try the common folder else if (appName !== 'common') { fullModulePath = fullModulePath.replace(delim + appName + delim, delim + 'common' + delim); uipart = this.injector.require(fullModulePath); appName = 'common'; } // if no view, check to see if precompiled in tpl dir var viewFile = fullModulePath.replace( delim + 'app' + delim + appName + delim, delim + tplDir + delim + appName + delim ); if (!uipart.view && fs.existsSync(viewFile + '.js')) { viewObj = this.injector.require(viewFile); uipart.view = function () { return viewObj; }; } return uipart; }
javascript
function getUiPart(modulePath, options) { var rootDir = this.injector.rootDir; var tplDir = (options && options.tplDir) || 'dist' + delim + 'tpls'; var pathParts = modulePath.split(delim); var appName = pathParts[1]; var len = modulePath.length; var filePath, fullModulePath, uipart, viewObj; // filePath has .js, modulePath does not if (modulePath.substring(len - 3) === '.js') { filePath = rootDir + delim + modulePath; fullModulePath = rootDir + delim + modulePath.substring(0, len - 3); } else { filePath = rootDir + delim + modulePath + '.js'; fullModulePath = rootDir + delim + modulePath; } // if exists, get it if (fs.existsSync(filePath)) { uipart = this.injector.require(fullModulePath); } // else if in an app folder, try the common folder else if (appName !== 'common') { fullModulePath = fullModulePath.replace(delim + appName + delim, delim + 'common' + delim); uipart = this.injector.require(fullModulePath); appName = 'common'; } // if no view, check to see if precompiled in tpl dir var viewFile = fullModulePath.replace( delim + 'app' + delim + appName + delim, delim + tplDir + delim + appName + delim ); if (!uipart.view && fs.existsSync(viewFile + '.js')) { viewObj = this.injector.require(viewFile); uipart.view = function () { return viewObj; }; } return uipart; }
[ "function", "getUiPart", "(", "modulePath", ",", "options", ")", "{", "var", "rootDir", "=", "this", ".", "injector", ".", "rootDir", ";", "var", "tplDir", "=", "(", "options", "&&", "options", ".", "tplDir", ")", "||", "'dist'", "+", "delim", "+", "'t...
Get a UI Part @param modulePath @param options @returns {*}
[ "Get", "a", "UI", "Part" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/uipart.factory.js#L55-L97
28,982
gethuman/pancakes
lib/factories/service.factory.js
ServiceFactory
function ServiceFactory(injector) { this.cache = {}; this.injector = injector || {}; // if we are in debug mode, then add the debug handler var pattern = this.injector.debugPattern || '*.*.*.*.*'; var handler = this.injector.debugHandler || debugHandler; if (this.injector.debug) { eventBus.on(pattern, handler); } }
javascript
function ServiceFactory(injector) { this.cache = {}; this.injector = injector || {}; // if we are in debug mode, then add the debug handler var pattern = this.injector.debugPattern || '*.*.*.*.*'; var handler = this.injector.debugHandler || debugHandler; if (this.injector.debug) { eventBus.on(pattern, handler); } }
[ "function", "ServiceFactory", "(", "injector", ")", "{", "this", ".", "cache", "=", "{", "}", ";", "this", ".", "injector", "=", "injector", "||", "{", "}", ";", "// if we are in debug mode, then add the debug handler", "var", "pattern", "=", "this", ".", "inj...
Simple function to clear the cache @param injector @constructor
[ "Simple", "function", "to", "clear", "the", "cache" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L20-L30
28,983
gethuman/pancakes
lib/factories/service.factory.js
isCandidate
function isCandidate(modulePath) { modulePath = modulePath || ''; var len = modulePath.length; return modulePath.indexOf('/') < 0 && len > 7 && modulePath.substring(modulePath.length - 7) === 'Service'; }
javascript
function isCandidate(modulePath) { modulePath = modulePath || ''; var len = modulePath.length; return modulePath.indexOf('/') < 0 && len > 7 && modulePath.substring(modulePath.length - 7) === 'Service'; }
[ "function", "isCandidate", "(", "modulePath", ")", "{", "modulePath", "=", "modulePath", "||", "''", ";", "var", "len", "=", "modulePath", ".", "length", ";", "return", "modulePath", ".", "indexOf", "(", "'/'", ")", "<", "0", "&&", "len", ">", "7", "&&...
Candidate if no slash and the modulePath ends in 'Service' @param modulePath @returns {boolean}
[ "Candidate", "if", "no", "slash", "and", "the", "modulePath", "ends", "in", "Service" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L39-L44
28,984
gethuman/pancakes
lib/factories/service.factory.js
getServiceInfo
function getServiceInfo(serviceName, adapterMap) { var serviceInfo = { serviceName: serviceName }; var serviceParts = utils.splitCamelCase(serviceName); // turn oneTwoThree into ['one', 'two', 'three'] var nbrParts = serviceParts.length; // first check to see if the second to last part is an adapter serviceInfo.adapterName = serviceParts[nbrParts - 2]; // NOTE: last item in array is 'Service' if (adapterMap[serviceInfo.adapterName]) { serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 2).join('.'); } // if not, it means we are dealing with a straight service (ex. postService) else { serviceInfo.adapterName = 'service'; serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 1).join('.'); } serviceInfo.adapterImpl = adapterMap[serviceInfo.adapterName]; return serviceInfo; }
javascript
function getServiceInfo(serviceName, adapterMap) { var serviceInfo = { serviceName: serviceName }; var serviceParts = utils.splitCamelCase(serviceName); // turn oneTwoThree into ['one', 'two', 'three'] var nbrParts = serviceParts.length; // first check to see if the second to last part is an adapter serviceInfo.adapterName = serviceParts[nbrParts - 2]; // NOTE: last item in array is 'Service' if (adapterMap[serviceInfo.adapterName]) { serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 2).join('.'); } // if not, it means we are dealing with a straight service (ex. postService) else { serviceInfo.adapterName = 'service'; serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 1).join('.'); } serviceInfo.adapterImpl = adapterMap[serviceInfo.adapterName]; return serviceInfo; }
[ "function", "getServiceInfo", "(", "serviceName", ",", "adapterMap", ")", "{", "var", "serviceInfo", "=", "{", "serviceName", ":", "serviceName", "}", ";", "var", "serviceParts", "=", "utils", ".", "splitCamelCase", "(", "serviceName", ")", ";", "// turn oneTwoT...
Figure out information about the service based on the module path and the adapter map @param serviceName @param adapterMap @returns {{}}
[ "Figure", "out", "information", "about", "the", "service", "based", "on", "the", "module", "path", "and", "the", "adapter", "map" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L90-L109
28,985
gethuman/pancakes
lib/factories/service.factory.js
getResource
function getResource(serviceInfo, moduleStack) { var resourceName = serviceInfo.resourceName; var resourcePath = '/resources/' + resourceName + '/' + resourceName + '.resource'; return this.loadIfExists(resourcePath, moduleStack, 'Could not find resource file'); }
javascript
function getResource(serviceInfo, moduleStack) { var resourceName = serviceInfo.resourceName; var resourcePath = '/resources/' + resourceName + '/' + resourceName + '.resource'; return this.loadIfExists(resourcePath, moduleStack, 'Could not find resource file'); }
[ "function", "getResource", "(", "serviceInfo", ",", "moduleStack", ")", "{", "var", "resourceName", "=", "serviceInfo", ".", "resourceName", ";", "var", "resourcePath", "=", "'/resources/'", "+", "resourceName", "+", "'/'", "+", "resourceName", "+", "'.resource'",...
Get a resource based on the @param serviceInfo @param moduleStack @returns {{}} A resource object
[ "Get", "a", "resource", "based", "on", "the" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L117-L121
28,986
gethuman/pancakes
lib/factories/service.factory.js
getAdapter
function getAdapter(serviceInfo, resource, moduleStack) { var adapterName = serviceInfo.adapterName; // if adapter name is 'service' and there is a default, switch to the default if (adapterName === 'service' && resource.adapters[this.injector.container]) { adapterName = serviceInfo.adapterName = resource.adapters[this.injector.container]; serviceInfo.adapterImpl = this.injector.adapterMap[adapterName]; serviceInfo.serviceName = utils.getCamelCase(serviceInfo.resourceName + '.' + serviceInfo.adapterName + '.service'); } // if that doesn't work, we will assume the adapter is in the current codebase, so go get it var overridePath = '/resources/' + serviceInfo.resourceName + '/' + serviceInfo.resourceName + '.' + (adapterName === 'service' ? adapterName : adapterName + '.service'); var adapterPath = '/adapters/' + adapterName + '/' + serviceInfo.adapterImpl + '.' + adapterName + '.adapter'; // if override exists, use that one, else use the lower level adapter var Adapter = this.loadIfExists(overridePath, moduleStack, null) || this.injector.adapters[serviceInfo.adapterImpl] || this.loadIfExists(adapterPath, moduleStack, null); // if still no adapter found, then there is an issue if (!Adapter) { throw new Error('ServiceFactory could not find adapter ' + adapterName + ' paths ' + overridePath + ' and ' + adapterPath); } return new Adapter(resource); }
javascript
function getAdapter(serviceInfo, resource, moduleStack) { var adapterName = serviceInfo.adapterName; // if adapter name is 'service' and there is a default, switch to the default if (adapterName === 'service' && resource.adapters[this.injector.container]) { adapterName = serviceInfo.adapterName = resource.adapters[this.injector.container]; serviceInfo.adapterImpl = this.injector.adapterMap[adapterName]; serviceInfo.serviceName = utils.getCamelCase(serviceInfo.resourceName + '.' + serviceInfo.adapterName + '.service'); } // if that doesn't work, we will assume the adapter is in the current codebase, so go get it var overridePath = '/resources/' + serviceInfo.resourceName + '/' + serviceInfo.resourceName + '.' + (adapterName === 'service' ? adapterName : adapterName + '.service'); var adapterPath = '/adapters/' + adapterName + '/' + serviceInfo.adapterImpl + '.' + adapterName + '.adapter'; // if override exists, use that one, else use the lower level adapter var Adapter = this.loadIfExists(overridePath, moduleStack, null) || this.injector.adapters[serviceInfo.adapterImpl] || this.loadIfExists(adapterPath, moduleStack, null); // if still no adapter found, then there is an issue if (!Adapter) { throw new Error('ServiceFactory could not find adapter ' + adapterName + ' paths ' + overridePath + ' and ' + adapterPath); } return new Adapter(resource); }
[ "function", "getAdapter", "(", "serviceInfo", ",", "resource", ",", "moduleStack", ")", "{", "var", "adapterName", "=", "serviceInfo", ".", "adapterName", ";", "// if adapter name is 'service' and there is a default, switch to the default", "if", "(", "adapterName", "===", ...
Get a adapter based on the service info and what exists on the file system @param serviceInfo @param resource @param moduleStack
[ "Get", "a", "adapter", "based", "on", "the", "service", "info", "and", "what", "exists", "on", "the", "file", "system" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L130-L160
28,987
gethuman/pancakes
lib/factories/service.factory.js
loadIfExists
function loadIfExists(path, moduleStack, errMsg) { var servicesDir = this.injector.servicesDir; var servicesFullPath = this.injector.rootDir + '/' + servicesDir; // if the file doesn't exist, either throw an error (if msg passed in), else just return null if (!fs.existsSync(p.join(servicesFullPath, path + '.js'))) { if (errMsg) { throw new Error(errMsg + ' ' + servicesFullPath + path + '.js'); } else { return null; } } // else load the module return this.injector.loadModule(servicesDir + path, moduleStack); }
javascript
function loadIfExists(path, moduleStack, errMsg) { var servicesDir = this.injector.servicesDir; var servicesFullPath = this.injector.rootDir + '/' + servicesDir; // if the file doesn't exist, either throw an error (if msg passed in), else just return null if (!fs.existsSync(p.join(servicesFullPath, path + '.js'))) { if (errMsg) { throw new Error(errMsg + ' ' + servicesFullPath + path + '.js'); } else { return null; } } // else load the module return this.injector.loadModule(servicesDir + path, moduleStack); }
[ "function", "loadIfExists", "(", "path", ",", "moduleStack", ",", "errMsg", ")", "{", "var", "servicesDir", "=", "this", ".", "injector", ".", "servicesDir", ";", "var", "servicesFullPath", "=", "this", ".", "injector", ".", "rootDir", "+", "'/'", "+", "se...
Load a module if it exists @param path @param moduleStack @param errMsg @returns {*}
[ "Load", "a", "module", "if", "it", "exists" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L169-L185
28,988
gethuman/pancakes
lib/factories/service.factory.js
putItAllTogether
function putItAllTogether(serviceInfo, resource, adapter) { var me = this; var debug = this.injector.debug; // loop through the methods _.each(resource.methods[serviceInfo.adapterName], function (method) { if (!adapter[method]) { return; } // we are going to monkey patch the target method on the adapter, so save the original method var origMethod = adapter[method].bind(adapter); var eventNameBase = { resource: serviceInfo.resourceName, adapter: serviceInfo.adapterName, method: method }; // create the new service function adapter[method] = function (req) { req = req || {}; // clean out request _.each(req, function (value, name) { if (value && value === 'undefined') { delete req[name]; } }); // add event for data before anything happens (used only for debugging) if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); } // first validate the request return me.validateRequestParams(req, resource, method, serviceInfo.adapterName) .then(function () { // add event before calling the original method (used only for debugging) if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); } // call the original target method on the adapter return origMethod(req); }) .then(function (res) { // emit event after origin method called; this is what most // reactors key off of (can be disabled with noemit flag) if (!req.noemit && !req.multi && method !== 'find') { var payload = { caller: req.caller, inputId: req._id, targetId: req.targetId, inputData: req.data, data: res }; me.emitEvent(payload, eventNameBase, null); } // return the response that will go back to the calling client return res; }); }; }); // so essentially the service is the adapter with each method bulked up with some extra stuff return adapter; }
javascript
function putItAllTogether(serviceInfo, resource, adapter) { var me = this; var debug = this.injector.debug; // loop through the methods _.each(resource.methods[serviceInfo.adapterName], function (method) { if (!adapter[method]) { return; } // we are going to monkey patch the target method on the adapter, so save the original method var origMethod = adapter[method].bind(adapter); var eventNameBase = { resource: serviceInfo.resourceName, adapter: serviceInfo.adapterName, method: method }; // create the new service function adapter[method] = function (req) { req = req || {}; // clean out request _.each(req, function (value, name) { if (value && value === 'undefined') { delete req[name]; } }); // add event for data before anything happens (used only for debugging) if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); } // first validate the request return me.validateRequestParams(req, resource, method, serviceInfo.adapterName) .then(function () { // add event before calling the original method (used only for debugging) if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); } // call the original target method on the adapter return origMethod(req); }) .then(function (res) { // emit event after origin method called; this is what most // reactors key off of (can be disabled with noemit flag) if (!req.noemit && !req.multi && method !== 'find') { var payload = { caller: req.caller, inputId: req._id, targetId: req.targetId, inputData: req.data, data: res }; me.emitEvent(payload, eventNameBase, null); } // return the response that will go back to the calling client return res; }); }; }); // so essentially the service is the adapter with each method bulked up with some extra stuff return adapter; }
[ "function", "putItAllTogether", "(", "serviceInfo", ",", "resource", ",", "adapter", ")", "{", "var", "me", "=", "this", ";", "var", "debug", "=", "this", ".", "injector", ".", "debug", ";", "// loop through the methods", "_", ".", "each", "(", "resource", ...
Take all the objects involved with a service and put them all together. The final service is really just an instance of an adapter with each method enhanced to have various filters added @param serviceInfo @param resource @param adapter @returns {{}}
[ "Take", "all", "the", "objects", "involved", "with", "a", "service", "and", "put", "them", "all", "together", ".", "The", "final", "service", "is", "really", "just", "an", "instance", "of", "an", "adapter", "with", "each", "method", "enhanced", "to", "have...
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L196-L261
28,989
gethuman/pancakes
lib/factories/service.factory.js
emitEvent
function emitEvent(payload, eventNameBase, debugParams) { // create a copy of the payload so that nothing modifies the original object try { payload = JSON.parse(JSON.stringify(payload)); } catch (err) { /* eslint no-console:0 */ console.log('issue parsing during emit ' + JSON.stringify(eventNameBase)); } // we don't want to emit the potentially huge resource file if (payload && payload.resource) { delete payload.resource; } // create the event data and emit the event var name = _.extend({}, eventNameBase, debugParams); var eventData = { name: name, payload: payload }; var eventName = name.resource + '.' + name.adapter + '.' + name.method; eventName += debugParams ? '.' + name.type + '.' + name.timing : ''; eventBus.emit(eventName, eventData); }
javascript
function emitEvent(payload, eventNameBase, debugParams) { // create a copy of the payload so that nothing modifies the original object try { payload = JSON.parse(JSON.stringify(payload)); } catch (err) { /* eslint no-console:0 */ console.log('issue parsing during emit ' + JSON.stringify(eventNameBase)); } // we don't want to emit the potentially huge resource file if (payload && payload.resource) { delete payload.resource; } // create the event data and emit the event var name = _.extend({}, eventNameBase, debugParams); var eventData = { name: name, payload: payload }; var eventName = name.resource + '.' + name.adapter + '.' + name.method; eventName += debugParams ? '.' + name.type + '.' + name.timing : ''; eventBus.emit(eventName, eventData); }
[ "function", "emitEvent", "(", "payload", ",", "eventNameBase", ",", "debugParams", ")", "{", "// create a copy of the payload so that nothing modifies the original object", "try", "{", "payload", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "payload", ...
This is used to get an mock filter which will be sending out events @param payload @param eventNameBase @param debugParams
[ "This", "is", "used", "to", "get", "an", "mock", "filter", "which", "will", "be", "sending", "out", "events" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L269-L294
28,990
gethuman/pancakes
lib/factories/service.factory.js
validateRequestParams
function validateRequestParams(req, resource, method, adapter) { req = req || {}; var params = resource.params || {}; var methodParams = _.extend({}, params[method], params[adapter + '.' + method] ); var requiredParams = methodParams.required || []; var eitherorParams = methodParams.eitheror || []; var optional = methodParams.optional || []; var eitherorExists, param; var err, reqObj; // make sure all the required params are there for (var i = 0; i < requiredParams.length; i++) { param = requiredParams[i]; if (req[param] === undefined || req[param] === null) { reqObj = _.extend({}, req); delete reqObj.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = resource.name + ' ' + method + ' missing ' + param + '. Required params: ' + JSON.stringify(requiredParams) + ' req is: ' + JSON.stringify(reqObj); return Q.reject(err); } } // make sure at least one of the eitheror params are there if (eitherorParams.length) { eitherorExists = false; _.each(eitherorParams, function (eitherorParam) { if (req[eitherorParam]) { eitherorExists = true; } }); if (!eitherorExists) { delete req.caller; delete req.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = resource.name + ' ' + method + ' must have one of the following params: ' + JSON.stringify(eitherorParams) + ' request is ' + JSON.stringify(req); return Q.reject(err); } } // now loop through the values and error if invalid param in there; also do JSON parsing if an object var validParams = requiredParams.concat(eitherorParams, optional, ['lang', 'caller', 'resource', 'method', 'auth', 'noemit']); for (var key in req) { if (req.hasOwnProperty(key)) { if (validParams.indexOf(key) < 0) { delete req.caller; delete req.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = 'For ' + resource.name + ' ' + method + ' the key ' + key + ' is not allowed. Valid params: ' + JSON.stringify(validParams) + ' request is ' + JSON.stringify(req); return Q.reject(err); } } } // no errors, so return resolved promise return new Q(); }
javascript
function validateRequestParams(req, resource, method, adapter) { req = req || {}; var params = resource.params || {}; var methodParams = _.extend({}, params[method], params[adapter + '.' + method] ); var requiredParams = methodParams.required || []; var eitherorParams = methodParams.eitheror || []; var optional = methodParams.optional || []; var eitherorExists, param; var err, reqObj; // make sure all the required params are there for (var i = 0; i < requiredParams.length; i++) { param = requiredParams[i]; if (req[param] === undefined || req[param] === null) { reqObj = _.extend({}, req); delete reqObj.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = resource.name + ' ' + method + ' missing ' + param + '. Required params: ' + JSON.stringify(requiredParams) + ' req is: ' + JSON.stringify(reqObj); return Q.reject(err); } } // make sure at least one of the eitheror params are there if (eitherorParams.length) { eitherorExists = false; _.each(eitherorParams, function (eitherorParam) { if (req[eitherorParam]) { eitherorExists = true; } }); if (!eitherorExists) { delete req.caller; delete req.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = resource.name + ' ' + method + ' must have one of the following params: ' + JSON.stringify(eitherorParams) + ' request is ' + JSON.stringify(req); return Q.reject(err); } } // now loop through the values and error if invalid param in there; also do JSON parsing if an object var validParams = requiredParams.concat(eitherorParams, optional, ['lang', 'caller', 'resource', 'method', 'auth', 'noemit']); for (var key in req) { if (req.hasOwnProperty(key)) { if (validParams.indexOf(key) < 0) { delete req.caller; delete req.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = 'For ' + resource.name + ' ' + method + ' the key ' + key + ' is not allowed. Valid params: ' + JSON.stringify(validParams) + ' request is ' + JSON.stringify(req); return Q.reject(err); } } } // no errors, so return resolved promise return new Q(); }
[ "function", "validateRequestParams", "(", "req", ",", "resource", ",", "method", ",", "adapter", ")", "{", "req", "=", "req", "||", "{", "}", ";", "var", "params", "=", "resource", ".", "params", "||", "{", "}", ";", "var", "methodParams", "=", "_", ...
Used within a service to validate the input params @param req @param resource @param method @param adapter @returns {*}
[ "Used", "within", "a", "service", "to", "validate", "the", "input", "params" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L304-L371
28,991
telefonicaid/logops
lib/logops.js
logWrap
function logWrap(level) { return function log() { let context, message, args, trace, err; if (arguments[0] instanceof Error) { // log.<level>(err, ...) context = API.getContext(); args = Array.prototype.slice.call(arguments, 1); if (!args.length) { // log.<level>(err) err = arguments[0]; message = err.name + ': ' + err.message; } else { // log.<level>(err, "More %s", "things") // Use the err as context information err = arguments[0]; message = arguments[1]; args = Array.prototype.slice.call(args, 1); } } else if (arguments[0] == null || (typeof (arguments[0]) !== 'object' && arguments[0] !== null) || Array.isArray(arguments[0])) { // log.<level>(msg, ...) context = API.getContext(); message = arguments[0]; args = Array.prototype.slice.call(arguments, 1); } else { // log.<level>(fields, msg, ...) context = merge(API.getContext(), arguments[0]); message = arguments[1]; args = Array.prototype.slice.call(arguments, 2); } trace = API.format(level, context || {}, message, args, err); API.stream.write(trace + '\n'); }; }
javascript
function logWrap(level) { return function log() { let context, message, args, trace, err; if (arguments[0] instanceof Error) { // log.<level>(err, ...) context = API.getContext(); args = Array.prototype.slice.call(arguments, 1); if (!args.length) { // log.<level>(err) err = arguments[0]; message = err.name + ': ' + err.message; } else { // log.<level>(err, "More %s", "things") // Use the err as context information err = arguments[0]; message = arguments[1]; args = Array.prototype.slice.call(args, 1); } } else if (arguments[0] == null || (typeof (arguments[0]) !== 'object' && arguments[0] !== null) || Array.isArray(arguments[0])) { // log.<level>(msg, ...) context = API.getContext(); message = arguments[0]; args = Array.prototype.slice.call(arguments, 1); } else { // log.<level>(fields, msg, ...) context = merge(API.getContext(), arguments[0]); message = arguments[1]; args = Array.prototype.slice.call(arguments, 2); } trace = API.format(level, context || {}, message, args, err); API.stream.write(trace + '\n'); }; }
[ "function", "logWrap", "(", "level", ")", "{", "return", "function", "log", "(", ")", "{", "let", "context", ",", "message", ",", "args", ",", "trace", ",", "err", ";", "if", "(", "arguments", "[", "0", "]", "instanceof", "Error", ")", "{", "// log.<...
Internal private function that implements a decorator to all the level functions. @param {String} level one of ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL']
[ "Internal", "private", "function", "that", "implements", "a", "decorator", "to", "all", "the", "level", "functions", "." ]
6023d75b3531ed1bb3abe171679234f9519be082
https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/logops.js#L45-L80
28,992
telefonicaid/logops
lib/logops.js
setLevel
function setLevel(level) { opts.level = level; let logLevelIndex = levels.indexOf(opts.level.toUpperCase()); levels.forEach((logLevel) => { let fn; if (logLevelIndex <= levels.indexOf(logLevel)) { fn = logWrap(logLevel); } else { fn = noop; } API[logLevel.toLowerCase()] = fn; }); }
javascript
function setLevel(level) { opts.level = level; let logLevelIndex = levels.indexOf(opts.level.toUpperCase()); levels.forEach((logLevel) => { let fn; if (logLevelIndex <= levels.indexOf(logLevel)) { fn = logWrap(logLevel); } else { fn = noop; } API[logLevel.toLowerCase()] = fn; }); }
[ "function", "setLevel", "(", "level", ")", "{", "opts", ".", "level", "=", "level", ";", "let", "logLevelIndex", "=", "levels", ".", "indexOf", "(", "opts", ".", "level", ".", "toUpperCase", "(", ")", ")", ";", "levels", ".", "forEach", "(", "(", "lo...
Sets the enabled logging level. All the disabled logging methods are replaced by a noop, so there is not any performance penalty at production using an undesired level @param {String} level
[ "Sets", "the", "enabled", "logging", "level", ".", "All", "the", "disabled", "logging", "methods", "are", "replaced", "by", "a", "noop", "so", "there", "is", "not", "any", "performance", "penalty", "at", "production", "using", "an", "undesired", "level" ]
6023d75b3531ed1bb3abe171679234f9519be082
https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/logops.js#L89-L102
28,993
telefonicaid/logops
lib/logops.js
merge
function merge(obj1, obj2) { var res = {}, attrname; for (attrname in obj1) { res[attrname] = obj1[attrname]; } for (attrname in obj2) { res[attrname] = obj2[attrname]; } return res; }
javascript
function merge(obj1, obj2) { var res = {}, attrname; for (attrname in obj1) { res[attrname] = obj1[attrname]; } for (attrname in obj2) { res[attrname] = obj2[attrname]; } return res; }
[ "function", "merge", "(", "obj1", ",", "obj2", ")", "{", "var", "res", "=", "{", "}", ",", "attrname", ";", "for", "(", "attrname", "in", "obj1", ")", "{", "res", "[", "attrname", "]", "=", "obj1", "[", "attrname", "]", ";", "}", "for", "(", "a...
Merges accesible properties in two objects. obj2 takes precedence when common properties are found @param {Object} obj1 @param {Object} obj2 @returns {{}} The merged, new, object
[ "Merges", "accesible", "properties", "in", "two", "objects", ".", "obj2", "takes", "precedence", "when", "common", "properties", "are", "found" ]
6023d75b3531ed1bb3abe171679234f9519be082
https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/logops.js#L266-L276
28,994
gethuman/pancakes
lib/transformers/base.transformer.js
loadUIPart
function loadUIPart(appName, filePath) { var idx = filePath.indexOf(delim + appName + delim); var modulePath = filePath.substring(idx - 3); return this.pancakes.cook(modulePath); }
javascript
function loadUIPart(appName, filePath) { var idx = filePath.indexOf(delim + appName + delim); var modulePath = filePath.substring(idx - 3); return this.pancakes.cook(modulePath); }
[ "function", "loadUIPart", "(", "appName", ",", "filePath", ")", "{", "var", "idx", "=", "filePath", ".", "indexOf", "(", "delim", "+", "appName", "+", "delim", ")", ";", "var", "modulePath", "=", "filePath", ".", "substring", "(", "idx", "-", "3", ")",...
Load the UI part @param appName @param filePath @returns {injector.require|*|require}
[ "Load", "the", "UI", "part" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L24-L28
28,995
gethuman/pancakes
lib/transformers/base.transformer.js
setTemplate
function setTemplate(transformDir, templateName, clientType) { clientType = clientType ? (clientType + '.') : ''; if (templateCache[templateName]) { this.template = templateCache[templateName]; } else { var fileName = transformDir + '/' + clientType + templateName + '.template'; if (fs.existsSync(path.normalize(fileName))) { var file = fs.readFileSync(path.normalize(fileName)); this.template = templateCache[templateName] = dot.template(file); } else { throw new Error('No template at ' + fileName); } } }
javascript
function setTemplate(transformDir, templateName, clientType) { clientType = clientType ? (clientType + '.') : ''; if (templateCache[templateName]) { this.template = templateCache[templateName]; } else { var fileName = transformDir + '/' + clientType + templateName + '.template'; if (fs.existsSync(path.normalize(fileName))) { var file = fs.readFileSync(path.normalize(fileName)); this.template = templateCache[templateName] = dot.template(file); } else { throw new Error('No template at ' + fileName); } } }
[ "function", "setTemplate", "(", "transformDir", ",", "templateName", ",", "clientType", ")", "{", "clientType", "=", "clientType", "?", "(", "clientType", "+", "'.'", ")", ":", "''", ";", "if", "(", "templateCache", "[", "templateName", "]", ")", "{", "thi...
Get a dot template @param transformDir @param templateName @param clientType
[ "Get", "a", "dot", "template" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L65-L82
28,996
gethuman/pancakes
lib/transformers/base.transformer.js
getParamInfo
function getParamInfo(params, aliases) { var paramInfo = { converted: [], list: [], ngrefs: [] }; _.each(params, function (param) { var mappedVal = aliases[param] || param; if (mappedVal === 'angular') { paramInfo.ngrefs.push(param); } else { paramInfo.list.push(param); paramInfo.converted.push(mappedVal); } }); return paramInfo; }
javascript
function getParamInfo(params, aliases) { var paramInfo = { converted: [], list: [], ngrefs: [] }; _.each(params, function (param) { var mappedVal = aliases[param] || param; if (mappedVal === 'angular') { paramInfo.ngrefs.push(param); } else { paramInfo.list.push(param); paramInfo.converted.push(mappedVal); } }); return paramInfo; }
[ "function", "getParamInfo", "(", "params", ",", "aliases", ")", "{", "var", "paramInfo", "=", "{", "converted", ":", "[", "]", ",", "list", ":", "[", "]", ",", "ngrefs", ":", "[", "]", "}", ";", "_", ".", "each", "(", "params", ",", "function", "...
Take a list of params and create an object that contains the param list and converted values which will be used in templates @param params @param aliases @returns {{converted: Array, list: Array}}
[ "Take", "a", "list", "of", "params", "and", "create", "an", "object", "that", "contains", "the", "param", "list", "and", "converted", "values", "which", "will", "be", "used", "in", "templates" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L92-L107
28,997
gethuman/pancakes
lib/transformers/base.transformer.js
getFilteredParamInfo
function getFilteredParamInfo(flapjack, options) { if (!flapjack) { return {}; } var aliases = this.getClientAliases(flapjack, options); var params = this.getParameters(flapjack) || []; params = params.filter(function (param) { return ['$scope', 'defaults', 'initialModel'].indexOf(param) < 0; }); return this.getParamInfo(params, aliases) || {}; }
javascript
function getFilteredParamInfo(flapjack, options) { if (!flapjack) { return {}; } var aliases = this.getClientAliases(flapjack, options); var params = this.getParameters(flapjack) || []; params = params.filter(function (param) { return ['$scope', 'defaults', 'initialModel'].indexOf(param) < 0; }); return this.getParamInfo(params, aliases) || {}; }
[ "function", "getFilteredParamInfo", "(", "flapjack", ",", "options", ")", "{", "if", "(", "!", "flapjack", ")", "{", "return", "{", "}", ";", "}", "var", "aliases", "=", "this", ".", "getClientAliases", "(", "flapjack", ",", "options", ")", ";", "var", ...
Get the parameter info for a given flajack @param flapjack @param options @returns {*|{converted: Array, list: Array}|{}}
[ "Get", "the", "parameter", "info", "for", "a", "given", "flajack" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L115-L125
28,998
gethuman/pancakes
lib/transformers/base.transformer.js
getModuleBody
function getModuleBody(flapjack) { if (!flapjack) { return ''; } var str = flapjack.toString(); var openingCurly = str.indexOf('{'); var closingCurly = str.lastIndexOf('}'); // if can't find the opening or closing curly, just return the entire string if (openingCurly < 0 || closingCurly < 0) { return str; } var body = str.substring(openingCurly + 1, closingCurly); return body.replace(/\n/g, '\n\t'); }
javascript
function getModuleBody(flapjack) { if (!flapjack) { return ''; } var str = flapjack.toString(); var openingCurly = str.indexOf('{'); var closingCurly = str.lastIndexOf('}'); // if can't find the opening or closing curly, just return the entire string if (openingCurly < 0 || closingCurly < 0) { return str; } var body = str.substring(openingCurly + 1, closingCurly); return body.replace(/\n/g, '\n\t'); }
[ "function", "getModuleBody", "(", "flapjack", ")", "{", "if", "(", "!", "flapjack", ")", "{", "return", "''", ";", "}", "var", "str", "=", "flapjack", ".", "toString", "(", ")", ";", "var", "openingCurly", "=", "str", ".", "indexOf", "(", "'{'", ")",...
Get the core logic within a module without the function declaration, parameters, etc. Essentially everything inside the curly brackets. @param flapjack The pancakes module @return {String}
[ "Get", "the", "core", "logic", "within", "a", "module", "without", "the", "function", "declaration", "parameters", "etc", ".", "Essentially", "everything", "inside", "the", "curly", "brackets", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L133-L147
28,999
kartotherian/core
lib/sources.js
updateInfo
function updateInfo(info, override, source, sourceId) { if (source) { if (source.minzoom !== undefined) { // eslint-disable-next-line no-param-reassign info.minzoom = source.minzoom; } if (source.maxzoom !== undefined) { // eslint-disable-next-line no-param-reassign info.maxzoom = source.maxzoom; } } if (sourceId !== undefined) { // eslint-disable-next-line no-param-reassign info.name = sourceId; } if (override) { _.each(override, (v, k) => { if (v === null) { // When override.key == null, delete that key // eslint-disable-next-line no-param-reassign delete info[k]; } else { // override info of the parent // eslint-disable-next-line no-param-reassign info[k] = v; } }); } }
javascript
function updateInfo(info, override, source, sourceId) { if (source) { if (source.minzoom !== undefined) { // eslint-disable-next-line no-param-reassign info.minzoom = source.minzoom; } if (source.maxzoom !== undefined) { // eslint-disable-next-line no-param-reassign info.maxzoom = source.maxzoom; } } if (sourceId !== undefined) { // eslint-disable-next-line no-param-reassign info.name = sourceId; } if (override) { _.each(override, (v, k) => { if (v === null) { // When override.key == null, delete that key // eslint-disable-next-line no-param-reassign delete info[k]; } else { // override info of the parent // eslint-disable-next-line no-param-reassign info[k] = v; } }); } }
[ "function", "updateInfo", "(", "info", ",", "override", ",", "source", ",", "sourceId", ")", "{", "if", "(", "source", ")", "{", "if", "(", "source", ".", "minzoom", "!==", "undefined", ")", "{", "// eslint-disable-next-line no-param-reassign", "info", ".", ...
Override top-level values in the info object with the ones from override object, or delete on null @param {object} info @param {object} override @param {object} [source] if given, sets min/max zoom @param {string} [sourceId]
[ "Override", "top", "-", "level", "values", "in", "the", "info", "object", "with", "the", "ones", "from", "override", "object", "or", "delete", "on", "null" ]
fb9f696816a08d782f5444364432f1fd79f4d56f
https://github.com/kartotherian/core/blob/fb9f696816a08d782f5444364432f1fd79f4d56f/lib/sources.js#L116-L144