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
partition
stringclasses
1 value
logikum/md-site-engine
source/models/search-result-list.js
function( text2search, noSearchPhrase, noSearchResult ) { Array.call( this ); /** * Gets the text to search. * @type {string|null} */ this.text2search = text2search || null; /** * Gets a message to display when search phrase is missing. * @type {string} */ this.noSearchPhrase = noSearchPhrase; /** * Gets a message to display when search did not found the text in the contents. * @type {string} */ this.noSearchResult = noSearchResult; }
javascript
function( text2search, noSearchPhrase, noSearchResult ) { Array.call( this ); /** * Gets the text to search. * @type {string|null} */ this.text2search = text2search || null; /** * Gets a message to display when search phrase is missing. * @type {string} */ this.noSearchPhrase = noSearchPhrase; /** * Gets a message to display when search did not found the text in the contents. * @type {string} */ this.noSearchResult = noSearchResult; }
[ "function", "(", "text2search", ",", "noSearchPhrase", ",", "noSearchResult", ")", "{", "Array", ".", "call", "(", "this", ")", ";", "this", ".", "text2search", "=", "text2search", "||", "null", ";", "this", ".", "noSearchPhrase", "=", "noSearchPhrase", ";", "this", ".", "noSearchResult", "=", "noSearchResult", ";", "}" ]
Represents a search result collection. @param {string} text2search - The text to search. @param {string} noSearchPhrase - The message when search phrase is missing. @param {string} noSearchResult - The message when search has no result. @constructor
[ "Represents", "a", "search", "result", "collection", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/models/search-result-list.js#L12-L33
train
xcambar/node-dbdeploy
index.js
function (files, latestMigrationFile) { if (direction === 'do') { return files .sort() .filter(function () { var _mustBeApplied = (latestMigrationFile === null); return function (name) { if (latestMigrationFile === name) { _mustBeApplied = !_mustBeApplied; return false; } return _mustBeApplied; }; }() ); } else { return files.sort().reverse().filter(function (name) { return latestMigrationFile === name; }); } }
javascript
function (files, latestMigrationFile) { if (direction === 'do') { return files .sort() .filter(function () { var _mustBeApplied = (latestMigrationFile === null); return function (name) { if (latestMigrationFile === name) { _mustBeApplied = !_mustBeApplied; return false; } return _mustBeApplied; }; }() ); } else { return files.sort().reverse().filter(function (name) { return latestMigrationFile === name; }); } }
[ "function", "(", "files", ",", "latestMigrationFile", ")", "{", "if", "(", "direction", "===", "'do'", ")", "{", "return", "files", ".", "sort", "(", ")", ".", "filter", "(", "function", "(", ")", "{", "var", "_mustBeApplied", "=", "(", "latestMigrationFile", "===", "null", ")", ";", "return", "function", "(", "name", ")", "{", "if", "(", "latestMigrationFile", "===", "name", ")", "{", "_mustBeApplied", "=", "!", "_mustBeApplied", ";", "return", "false", ";", "}", "return", "_mustBeApplied", ";", "}", ";", "}", "(", ")", ")", ";", "}", "else", "{", "return", "files", ".", "sort", "(", ")", ".", "reverse", "(", ")", ".", "filter", "(", "function", "(", "name", ")", "{", "return", "latestMigrationFile", "===", "name", ";", "}", ")", ";", "}", "}" ]
Filters through the files in the migration folder and finds the statements that need to be applied to the database
[ "Filters", "through", "the", "files", "in", "the", "migration", "folder", "and", "finds", "the", "statements", "that", "need", "to", "be", "applied", "to", "the", "database" ]
09408f070764032e45502ec67ee532d12bee7ae3
https://github.com/xcambar/node-dbdeploy/blob/09408f070764032e45502ec67ee532d12bee7ae3/index.js#L103-L123
train
xcambar/node-dbdeploy
index.js
function (order, unorderedObj) { var orderedObj = []; for (var i = 0; i < order.length; i++) { orderedObj.push(unorderedObj[order[i]]); } return orderedObj; }
javascript
function (order, unorderedObj) { var orderedObj = []; for (var i = 0; i < order.length; i++) { orderedObj.push(unorderedObj[order[i]]); } return orderedObj; }
[ "function", "(", "order", ",", "unorderedObj", ")", "{", "var", "orderedObj", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "order", ".", "length", ";", "i", "++", ")", "{", "orderedObj", ".", "push", "(", "unorderedObj", "[", "order", "[", "i", "]", "]", ")", ";", "}", "return", "orderedObj", ";", "}" ]
Orders the migrations statements to the specified order, so they can be applied in the right place, at the right time
[ "Orders", "the", "migrations", "statements", "to", "the", "specified", "order", "so", "they", "can", "be", "applied", "in", "the", "right", "place", "at", "the", "right", "time" ]
09408f070764032e45502ec67ee532d12bee7ae3
https://github.com/xcambar/node-dbdeploy/blob/09408f070764032e45502ec67ee532d12bee7ae3/index.js#L127-L133
train
xcambar/node-dbdeploy
index.js
function (latestMigrationFile) { return function (err, files) { if (err) { throw err; } files = _getApplicableMigrations(files, latestMigrationFile); var filesRemaining = files.length; var parsedMigrations = {}; console.log('* Number of migration scripts to apply:', filesRemaining); if (filesRemaining === 0) { // me.client; // TODO : what is this ? } for (var file in files) { if (files.hasOwnProperty(file)) { var filename = files[file]; var filepath = _config.migrationFolder + '/' + filename; var parser = new migrationParser(filepath, me.client); parser.on('ready', function () { filesRemaining--; parsedMigrations[basename(this.file)] = this; if (filesRemaining === 0) { var orderedMigrations = _orderMigrations(files, parsedMigrations); // Here is where the migration really takes place me.changelog.apply(orderedMigrations, direction); } }); } } } }
javascript
function (latestMigrationFile) { return function (err, files) { if (err) { throw err; } files = _getApplicableMigrations(files, latestMigrationFile); var filesRemaining = files.length; var parsedMigrations = {}; console.log('* Number of migration scripts to apply:', filesRemaining); if (filesRemaining === 0) { // me.client; // TODO : what is this ? } for (var file in files) { if (files.hasOwnProperty(file)) { var filename = files[file]; var filepath = _config.migrationFolder + '/' + filename; var parser = new migrationParser(filepath, me.client); parser.on('ready', function () { filesRemaining--; parsedMigrations[basename(this.file)] = this; if (filesRemaining === 0) { var orderedMigrations = _orderMigrations(files, parsedMigrations); // Here is where the migration really takes place me.changelog.apply(orderedMigrations, direction); } }); } } } }
[ "function", "(", "latestMigrationFile", ")", "{", "return", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "files", "=", "_getApplicableMigrations", "(", "files", ",", "latestMigrationFile", ")", ";", "var", "filesRemaining", "=", "files", ".", "length", ";", "var", "parsedMigrations", "=", "{", "}", ";", "console", ".", "log", "(", "'* Number of migration scripts to apply:'", ",", "filesRemaining", ")", ";", "if", "(", "filesRemaining", "===", "0", ")", "{", "}", "for", "(", "var", "file", "in", "files", ")", "{", "if", "(", "files", ".", "hasOwnProperty", "(", "file", ")", ")", "{", "var", "filename", "=", "files", "[", "file", "]", ";", "var", "filepath", "=", "_config", ".", "migrationFolder", "+", "'/'", "+", "filename", ";", "var", "parser", "=", "new", "migrationParser", "(", "filepath", ",", "me", ".", "client", ")", ";", "parser", ".", "on", "(", "'ready'", ",", "function", "(", ")", "{", "filesRemaining", "--", ";", "parsedMigrations", "[", "basename", "(", "this", ".", "file", ")", "]", "=", "this", ";", "if", "(", "filesRemaining", "===", "0", ")", "{", "var", "orderedMigrations", "=", "_orderMigrations", "(", "files", ",", "parsedMigrations", ")", ";", "me", ".", "changelog", ".", "apply", "(", "orderedMigrations", ",", "direction", ")", ";", "}", "}", ")", ";", "}", "}", "}", "}" ]
Returns a function that, once run, will return the statements to be applied
[ "Returns", "a", "function", "that", "once", "run", "will", "return", "the", "statements", "to", "be", "applied" ]
09408f070764032e45502ec67ee532d12bee7ae3
https://github.com/xcambar/node-dbdeploy/blob/09408f070764032e45502ec67ee532d12bee7ae3/index.js#L137-L170
train
cnnlabs/generator-cnn-base
generators/app/index.js
validateFilename
function validateFilename(input) { let isValidCharacterString = validateCharacterString(input); if (isValidCharacterString !== true) { return isValidCharacterString; } return (input.search(/ /) === -1) ? true : 'Must be a valid POSIX.1-2013 3.170 Filename!'; }
javascript
function validateFilename(input) { let isValidCharacterString = validateCharacterString(input); if (isValidCharacterString !== true) { return isValidCharacterString; } return (input.search(/ /) === -1) ? true : 'Must be a valid POSIX.1-2013 3.170 Filename!'; }
[ "function", "validateFilename", "(", "input", ")", "{", "let", "isValidCharacterString", "=", "validateCharacterString", "(", "input", ")", ";", "if", "(", "isValidCharacterString", "!==", "true", ")", "{", "return", "isValidCharacterString", ";", "}", "return", "(", "input", ".", "search", "(", "/", " ", "/", ")", "===", "-", "1", ")", "?", "true", ":", "'Must be a valid POSIX.1-2013 3.170 Filename!'", ";", "}" ]
Validates that a string is a valid POSIX.1-2013 3.170 filename. @see http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_170 @param {?string} input The string to validate. @return {boolean|string} Will either be true, or a string. If it is a string, validation failed.
[ "Validates", "that", "a", "string", "is", "a", "valid", "POSIX", ".", "1", "-", "2013", "3", ".", "170", "filename", "." ]
63a973ba1ab20824a87332cf8ddb1d058d2b4552
https://github.com/cnnlabs/generator-cnn-base/blob/63a973ba1ab20824a87332cf8ddb1d058d2b4552/generators/app/index.js#L49-L57
train
pashky/connect-fastcgi
index.js
makeHeaders
function makeHeaders(headers, params) { if (headers.length <= 0) { return params; } for (var prop in headers) { var head = headers[prop]; prop = prop.replace(/-/, '_').toUpperCase(); if (prop.indexOf('CONTENT_') < 0) { // Quick hack for PHP, might be more or less headers. prop = 'HTTP_' + prop; } params[params.length] = [prop, head] } return params; }
javascript
function makeHeaders(headers, params) { if (headers.length <= 0) { return params; } for (var prop in headers) { var head = headers[prop]; prop = prop.replace(/-/, '_').toUpperCase(); if (prop.indexOf('CONTENT_') < 0) { // Quick hack for PHP, might be more or less headers. prop = 'HTTP_' + prop; } params[params.length] = [prop, head] } return params; }
[ "function", "makeHeaders", "(", "headers", ",", "params", ")", "{", "if", "(", "headers", ".", "length", "<=", "0", ")", "{", "return", "params", ";", "}", "for", "(", "var", "prop", "in", "headers", ")", "{", "var", "head", "=", "headers", "[", "prop", "]", ";", "prop", "=", "prop", ".", "replace", "(", "/", "-", "/", ",", "'_'", ")", ".", "toUpperCase", "(", ")", ";", "if", "(", "prop", ".", "indexOf", "(", "'CONTENT_'", ")", "<", "0", ")", "{", "prop", "=", "'HTTP_'", "+", "prop", ";", "}", "params", "[", "params", ".", "length", "]", "=", "[", "prop", ",", "head", "]", "}", "return", "params", ";", "}" ]
Make headers for FPM Some headers have to be modified to fit the FPM handler and some others don't. For instance, the Content-Type header, when received, has to be made upper-case and the hyphen has to be made into an underscore. However, the Accept header has to be made uppercase, hyphens turned into underscores and the string "HTTP_" has to be appended to the header. @param array headers An array of existing user headers from Node.js @param array params An array of pre-built headers set in serveFpm @return array An array of complete headers.
[ "Make", "headers", "for", "FPM" ]
b8390f85163aec533a5725a8fd9279900d48192e
https://github.com/pashky/connect-fastcgi/blob/b8390f85163aec533a5725a8fd9279900d48192e/index.js#L34-L51
train
logikum/md-site-engine
source/readers/read-contents.js
readContents
function readContents( contentPath, submenuFile, filingCabinet, renderer ) { var typeName = 'Content'; logger.showInfo( '*** Reading contents...' ); // Read directory items in the content store. var items = fs.readdirSync( path.join( process.cwd(), contentPath ) ); items.forEach( function ( item ) { var itemPath = path.join( contentPath, item ); // Get item info. var stats = fs.statSync( path.join( process.cwd(), itemPath ) ); if (stats.isDirectory()) { // Create new stores for the language. var contentStock = filingCabinet.contents.create( item ); var menuStock = filingCabinet.menus.create( item ); // Save the language for the menu. filingCabinet.languages.push( item ); logger.localeFound( typeName, item ); // Find and add contents for the language. processContents( itemPath, // content directory '', // content root submenuFile, // submenu filename contentStock, // content stock menuStock, // menu stock filingCabinet.references, // reference drawer item, // language renderer // markdown renderer ); } else // Unused file. logger.fileSkipped( typeName, itemPath ); } ) }
javascript
function readContents( contentPath, submenuFile, filingCabinet, renderer ) { var typeName = 'Content'; logger.showInfo( '*** Reading contents...' ); // Read directory items in the content store. var items = fs.readdirSync( path.join( process.cwd(), contentPath ) ); items.forEach( function ( item ) { var itemPath = path.join( contentPath, item ); // Get item info. var stats = fs.statSync( path.join( process.cwd(), itemPath ) ); if (stats.isDirectory()) { // Create new stores for the language. var contentStock = filingCabinet.contents.create( item ); var menuStock = filingCabinet.menus.create( item ); // Save the language for the menu. filingCabinet.languages.push( item ); logger.localeFound( typeName, item ); // Find and add contents for the language. processContents( itemPath, // content directory '', // content root submenuFile, // submenu filename contentStock, // content stock menuStock, // menu stock filingCabinet.references, // reference drawer item, // language renderer // markdown renderer ); } else // Unused file. logger.fileSkipped( typeName, itemPath ); } ) }
[ "function", "readContents", "(", "contentPath", ",", "submenuFile", ",", "filingCabinet", ",", "renderer", ")", "{", "var", "typeName", "=", "'Content'", ";", "logger", ".", "showInfo", "(", "'*** Reading contents...'", ")", ";", "var", "items", "=", "fs", ".", "readdirSync", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "contentPath", ")", ")", ";", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "itemPath", "=", "path", ".", "join", "(", "contentPath", ",", "item", ")", ";", "var", "stats", "=", "fs", ".", "statSync", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "itemPath", ")", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "var", "contentStock", "=", "filingCabinet", ".", "contents", ".", "create", "(", "item", ")", ";", "var", "menuStock", "=", "filingCabinet", ".", "menus", ".", "create", "(", "item", ")", ";", "filingCabinet", ".", "languages", ".", "push", "(", "item", ")", ";", "logger", ".", "localeFound", "(", "typeName", ",", "item", ")", ";", "processContents", "(", "itemPath", ",", "''", ",", "submenuFile", ",", "contentStock", ",", "menuStock", ",", "filingCabinet", ".", "references", ",", "item", ",", "renderer", ")", ";", "}", "else", "logger", ".", "fileSkipped", "(", "typeName", ",", "itemPath", ")", ";", "}", ")", "}" ]
Read all contents. @param {string} contentPath - The path of the contents directory. @param {string} submenuFile - The path of the menu level file (__submenu.txt). @param {FilingCabinet} filingCabinet - The file manager object. @param {marked.Renderer} renderer - The custom markdown renderer.
[ "Read", "all", "contents", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/read-contents.js#L15-L55
train
FormidableLabs/gulp-mdox
mdox.js
function (tmplPath) { var text = fs.readFileSync(tmplPath) .toString() .replace(/^\s*|\s*$/g, ""); return ejs.compile(text); }
javascript
function (tmplPath) { var text = fs.readFileSync(tmplPath) .toString() .replace(/^\s*|\s*$/g, ""); return ejs.compile(text); }
[ "function", "(", "tmplPath", ")", "{", "var", "text", "=", "fs", ".", "readFileSync", "(", "tmplPath", ")", ".", "toString", "(", ")", ".", "replace", "(", "/", "^\\s*|\\s*$", "/", "g", ",", "\"\"", ")", ";", "return", "ejs", ".", "compile", "(", "text", ")", ";", "}" ]
Read and process a single template.
[ "Read", "and", "process", "a", "single", "template", "." ]
77f4c2b101a39c949649f722a4a44bccb36cd6aa
https://github.com/FormidableLabs/gulp-mdox/blob/77f4c2b101a39c949649f722a4a44bccb36cd6aa/mdox.js#L14-L20
train
FormidableLabs/gulp-mdox
mdox.js
function (obj, opts) { var toc = []; // Finesse comment markdown data. // Also, statefully create TOC. var sections = _.chain(obj) .map(function (data) { return new Section(data, opts); }) .filter(function (s) { return s.isPublic(); }) .map(function (s) { toc.push(s.renderToc()); // Add to TOC. return s.renderSection(); // Render section. }) .value() .join("\n"); // No Output if not sections. if (!sections) { return ""; } return "\n" + toc.join("") + "\n" + sections; }
javascript
function (obj, opts) { var toc = []; // Finesse comment markdown data. // Also, statefully create TOC. var sections = _.chain(obj) .map(function (data) { return new Section(data, opts); }) .filter(function (s) { return s.isPublic(); }) .map(function (s) { toc.push(s.renderToc()); // Add to TOC. return s.renderSection(); // Render section. }) .value() .join("\n"); // No Output if not sections. if (!sections) { return ""; } return "\n" + toc.join("") + "\n" + sections; }
[ "function", "(", "obj", ",", "opts", ")", "{", "var", "toc", "=", "[", "]", ";", "var", "sections", "=", "_", ".", "chain", "(", "obj", ")", ".", "map", "(", "function", "(", "data", ")", "{", "return", "new", "Section", "(", "data", ",", "opts", ")", ";", "}", ")", ".", "filter", "(", "function", "(", "s", ")", "{", "return", "s", ".", "isPublic", "(", ")", ";", "}", ")", ".", "map", "(", "function", "(", "s", ")", "{", "toc", ".", "push", "(", "s", ".", "renderToc", "(", ")", ")", ";", "return", "s", ".", "renderSection", "(", ")", ";", "}", ")", ".", "value", "(", ")", ".", "join", "(", "\"\\n\"", ")", ";", "\\n", "if", "(", "!", "sections", ")", "{", "return", "\"\"", ";", "}", "}" ]
Generate MD API from `dox` object.
[ "Generate", "MD", "API", "from", "dox", "object", "." ]
77f4c2b101a39c949649f722a4a44bccb36cd6aa
https://github.com/FormidableLabs/gulp-mdox/blob/77f4c2b101a39c949649f722a4a44bccb36cd6aa/mdox.js#L106-L127
train
FormidableLabs/gulp-mdox
mdox.js
function (text) { var inApiSection = false; return fs.createReadStream(opts.src) .pipe(es.split("\n")) .pipe(es.through(function (line) { // Hit the start marker. if (line === opts.start) { // Emit our line (it **is** included). this.emit("data", line); // Emit our the processed API data. this.emit("data", text); // Mark that we are **within** API section. inApiSection = true; } // End marker. if (line === opts.end) { // Mark that we have **exited** API section. inApiSection = false; } // Re-emit lines only if we are not within API section. if (!inApiSection) { this.emit("data", line); } })) .pipe(es.join("\n")) .pipe(es.wait()); }
javascript
function (text) { var inApiSection = false; return fs.createReadStream(opts.src) .pipe(es.split("\n")) .pipe(es.through(function (line) { // Hit the start marker. if (line === opts.start) { // Emit our line (it **is** included). this.emit("data", line); // Emit our the processed API data. this.emit("data", text); // Mark that we are **within** API section. inApiSection = true; } // End marker. if (line === opts.end) { // Mark that we have **exited** API section. inApiSection = false; } // Re-emit lines only if we are not within API section. if (!inApiSection) { this.emit("data", line); } })) .pipe(es.join("\n")) .pipe(es.wait()); }
[ "function", "(", "text", ")", "{", "var", "inApiSection", "=", "false", ";", "return", "fs", ".", "createReadStream", "(", "opts", ".", "src", ")", ".", "pipe", "(", "es", ".", "split", "(", "\"\\n\"", ")", ")", ".", "\\n", "pipe", ".", "(", "es", ".", "through", "(", "function", "(", "line", ")", "{", "if", "(", "line", "===", "opts", ".", "start", ")", "{", "this", ".", "emit", "(", "\"data\"", ",", "line", ")", ";", "this", ".", "emit", "(", "\"data\"", ",", "text", ")", ";", "inApiSection", "=", "true", ";", "}", "if", "(", "line", "===", "opts", ".", "end", ")", "{", "inApiSection", "=", "false", ";", "}", "if", "(", "!", "inApiSection", ")", "{", "this", ".", "emit", "(", "\"data\"", ",", "line", ")", ";", "}", "}", ")", ")", "pipe", ".", "(", "es", ".", "join", "(", "\"\\n\"", ")", ")", "\\n", ";", "}" ]
Create stream for destination and insert text appropriately.
[ "Create", "stream", "for", "destination", "and", "insert", "text", "appropriately", "." ]
77f4c2b101a39c949649f722a4a44bccb36cd6aa
https://github.com/FormidableLabs/gulp-mdox/blob/77f4c2b101a39c949649f722a4a44bccb36cd6aa/mdox.js#L190-L221
train
juttle/juttle-viz
src/lib/charts/table.js
function(element, options) { _.extend(this, Backbone.Events); var defaults = require('../utils/default-options')(); // set to be an object in case // it's undefined options = options || {}; // extend the defaults options = _.extend(defaults, options); this.options = options; this._currentColumns = []; this.container = element; this.innerContainer = document.createElement('div'); this.innerContainer.classList.add('inner-container'); this.innerContainer.classList.add('hide-overflow'); this.el = document.createElement('table'); this.el.classList.add('table'); this.el.classList.add('table-striped'); this.container.classList.add('table-sink-container'); this.innerContainer.appendChild(this.el); this.container.appendChild(this.innerContainer); this.innerContainer.style.maxHeight = options.height + 'px'; this.resize(); // create some scaffolding this.table = d3.select(this.el); this.thead = this.table.append('thead'); this.tbody = this.table.append('tbody'); // set if we should append to the existing table data // and not reset on batch_end this._append = options._append; this._markdownFields = this.options.markdownFields || []; this._bindScrollBlocker(); // We don't need a fully-fledged data target here, // so we just add functions as per feedback from @demmer var self = this; this.dataTarget = { _data: [], push: function(data) { // clear the table if we've done batch_end / stream_end before if (this._data.length === 0) { self.clearTable(); } // limit the data to avoid crashing the browser. If limit // is zero, then it is ignored. If the limit has been reached, // we return early and don't display the new data // check that we aren't already over the limit if (this._data.length >= self.options.limit) { // display the message and don't do anything else self._sendRowLimitReachedMessage(); return; // check that the new data won't make us go over the limit } else if ((this._data.length + data.length) > self.options.limit) { self._sendRowLimitReachedMessage(); // just add from new data until we get to the limit var i = 0; while (this._data.length < self.options.limit) { this._data.push(data[i++]); } } // we're fine. else { self._clearRowLimitReachedMessage(); this._data = this._data.concat(data); } // if you got here, draw the table self.onData(this._data); }, batch_end: function() { if (self.options.update === 'replace') { this._data = []; } }, stream_end: function() { } }; }
javascript
function(element, options) { _.extend(this, Backbone.Events); var defaults = require('../utils/default-options')(); // set to be an object in case // it's undefined options = options || {}; // extend the defaults options = _.extend(defaults, options); this.options = options; this._currentColumns = []; this.container = element; this.innerContainer = document.createElement('div'); this.innerContainer.classList.add('inner-container'); this.innerContainer.classList.add('hide-overflow'); this.el = document.createElement('table'); this.el.classList.add('table'); this.el.classList.add('table-striped'); this.container.classList.add('table-sink-container'); this.innerContainer.appendChild(this.el); this.container.appendChild(this.innerContainer); this.innerContainer.style.maxHeight = options.height + 'px'; this.resize(); // create some scaffolding this.table = d3.select(this.el); this.thead = this.table.append('thead'); this.tbody = this.table.append('tbody'); // set if we should append to the existing table data // and not reset on batch_end this._append = options._append; this._markdownFields = this.options.markdownFields || []; this._bindScrollBlocker(); // We don't need a fully-fledged data target here, // so we just add functions as per feedback from @demmer var self = this; this.dataTarget = { _data: [], push: function(data) { // clear the table if we've done batch_end / stream_end before if (this._data.length === 0) { self.clearTable(); } // limit the data to avoid crashing the browser. If limit // is zero, then it is ignored. If the limit has been reached, // we return early and don't display the new data // check that we aren't already over the limit if (this._data.length >= self.options.limit) { // display the message and don't do anything else self._sendRowLimitReachedMessage(); return; // check that the new data won't make us go over the limit } else if ((this._data.length + data.length) > self.options.limit) { self._sendRowLimitReachedMessage(); // just add from new data until we get to the limit var i = 0; while (this._data.length < self.options.limit) { this._data.push(data[i++]); } } // we're fine. else { self._clearRowLimitReachedMessage(); this._data = this._data.concat(data); } // if you got here, draw the table self.onData(this._data); }, batch_end: function() { if (self.options.update === 'replace') { this._data = []; } }, stream_end: function() { } }; }
[ "function", "(", "element", ",", "options", ")", "{", "_", ".", "extend", "(", "this", ",", "Backbone", ".", "Events", ")", ";", "var", "defaults", "=", "require", "(", "'../utils/default-options'", ")", "(", ")", ";", "options", "=", "options", "||", "{", "}", ";", "options", "=", "_", ".", "extend", "(", "defaults", ",", "options", ")", ";", "this", ".", "options", "=", "options", ";", "this", ".", "_currentColumns", "=", "[", "]", ";", "this", ".", "container", "=", "element", ";", "this", ".", "innerContainer", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "this", ".", "innerContainer", ".", "classList", ".", "add", "(", "'inner-container'", ")", ";", "this", ".", "innerContainer", ".", "classList", ".", "add", "(", "'hide-overflow'", ")", ";", "this", ".", "el", "=", "document", ".", "createElement", "(", "'table'", ")", ";", "this", ".", "el", ".", "classList", ".", "add", "(", "'table'", ")", ";", "this", ".", "el", ".", "classList", ".", "add", "(", "'table-striped'", ")", ";", "this", ".", "container", ".", "classList", ".", "add", "(", "'table-sink-container'", ")", ";", "this", ".", "innerContainer", ".", "appendChild", "(", "this", ".", "el", ")", ";", "this", ".", "container", ".", "appendChild", "(", "this", ".", "innerContainer", ")", ";", "this", ".", "innerContainer", ".", "style", ".", "maxHeight", "=", "options", ".", "height", "+", "'px'", ";", "this", ".", "resize", "(", ")", ";", "this", ".", "table", "=", "d3", ".", "select", "(", "this", ".", "el", ")", ";", "this", ".", "thead", "=", "this", ".", "table", ".", "append", "(", "'thead'", ")", ";", "this", ".", "tbody", "=", "this", ".", "table", ".", "append", "(", "'tbody'", ")", ";", "this", ".", "_append", "=", "options", ".", "_append", ";", "this", ".", "_markdownFields", "=", "this", ".", "options", ".", "markdownFields", "||", "[", "]", ";", "this", ".", "_bindScrollBlocker", "(", ")", ";", "var", "self", "=", "this", ";", "this", ".", "dataTarget", "=", "{", "_data", ":", "[", "]", ",", "push", ":", "function", "(", "data", ")", "{", "if", "(", "this", ".", "_data", ".", "length", "===", "0", ")", "{", "self", ".", "clearTable", "(", ")", ";", "}", "if", "(", "this", ".", "_data", ".", "length", ">=", "self", ".", "options", ".", "limit", ")", "{", "self", ".", "_sendRowLimitReachedMessage", "(", ")", ";", "return", ";", "}", "else", "if", "(", "(", "this", ".", "_data", ".", "length", "+", "data", ".", "length", ")", ">", "self", ".", "options", ".", "limit", ")", "{", "self", ".", "_sendRowLimitReachedMessage", "(", ")", ";", "var", "i", "=", "0", ";", "while", "(", "this", ".", "_data", ".", "length", "<", "self", ".", "options", ".", "limit", ")", "{", "this", ".", "_data", ".", "push", "(", "data", "[", "i", "++", "]", ")", ";", "}", "}", "else", "{", "self", ".", "_clearRowLimitReachedMessage", "(", ")", ";", "this", ".", "_data", "=", "this", ".", "_data", ".", "concat", "(", "data", ")", ";", "}", "self", ".", "onData", "(", "this", ".", "_data", ")", ";", "}", ",", "batch_end", ":", "function", "(", ")", "{", "if", "(", "self", ".", "options", ".", "update", "===", "'replace'", ")", "{", "this", ".", "_data", "=", "[", "]", ";", "}", "}", ",", "stream_end", ":", "function", "(", ")", "{", "}", "}", ";", "}" ]
initialise the table and create some scaffolding
[ "initialise", "the", "table", "and", "create", "some", "scaffolding" ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/lib/charts/table.js#L11-L108
train
IonicaBizau/node-git-repos
lib/index.js
GitRepos
function GitRepos (path, callback) { var ev = FindIt(Abs(path)); ev.on("directory", function (dir, stat, stop) { var cDir = Path.dirname(dir) , base = Path.basename(dir) ; if (base === ".git") { callback(null, cDir, stat); stop(); } }); ev.on("error", function (err) { callback(err); }); return ev; }
javascript
function GitRepos (path, callback) { var ev = FindIt(Abs(path)); ev.on("directory", function (dir, stat, stop) { var cDir = Path.dirname(dir) , base = Path.basename(dir) ; if (base === ".git") { callback(null, cDir, stat); stop(); } }); ev.on("error", function (err) { callback(err); }); return ev; }
[ "function", "GitRepos", "(", "path", ",", "callback", ")", "{", "var", "ev", "=", "FindIt", "(", "Abs", "(", "path", ")", ")", ";", "ev", ".", "on", "(", "\"directory\"", ",", "function", "(", "dir", ",", "stat", ",", "stop", ")", "{", "var", "cDir", "=", "Path", ".", "dirname", "(", "dir", ")", ",", "base", "=", "Path", ".", "basename", "(", "dir", ")", ";", "if", "(", "base", "===", "\".git\"", ")", "{", "callback", "(", "null", ",", "cDir", ",", "stat", ")", ";", "stop", "(", ")", ";", "}", "}", ")", ";", "ev", ".", "on", "(", "\"error\"", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", ")", ";", "return", "ev", ";", "}" ]
GitRepos Finds the git repositories paths in the provided path. @name GitRepos @function @param {String} path The path where to search recursively the git repositories. @param {Function} callback The callback function. @return {EventEmitter} The `FindIt` event emitter.
[ "GitRepos", "Finds", "the", "git", "repositories", "paths", "in", "the", "provided", "path", "." ]
2d9e9dee2c7fdaa93e28cbfd7744e48f82371f28
https://github.com/IonicaBizau/node-git-repos/blob/2d9e9dee2c7fdaa93e28cbfd7744e48f82371f28/lib/index.js#L17-L37
train
suguru/cql-client
lib/protocol/resultset.js
Row
function Row(columnSpecs, row) { var i, col, type, val, cols = []; for (i = 0; i < columnSpecs.length; i++) { col = columnSpecs[i]; type = types.fromType(col.type); if (col.subtype) { type = type(col.subtype); } else if (col.keytype) { type = type(col.keytype, col.valuetype); } val = type.deserialize(row[i]); this[col.name] = val; cols.push(val); } Object.defineProperty(this, 'columns', { value: cols, enumerable: false }); }
javascript
function Row(columnSpecs, row) { var i, col, type, val, cols = []; for (i = 0; i < columnSpecs.length; i++) { col = columnSpecs[i]; type = types.fromType(col.type); if (col.subtype) { type = type(col.subtype); } else if (col.keytype) { type = type(col.keytype, col.valuetype); } val = type.deserialize(row[i]); this[col.name] = val; cols.push(val); } Object.defineProperty(this, 'columns', { value: cols, enumerable: false }); }
[ "function", "Row", "(", "columnSpecs", ",", "row", ")", "{", "var", "i", ",", "col", ",", "type", ",", "val", ",", "cols", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "columnSpecs", ".", "length", ";", "i", "++", ")", "{", "col", "=", "columnSpecs", "[", "i", "]", ";", "type", "=", "types", ".", "fromType", "(", "col", ".", "type", ")", ";", "if", "(", "col", ".", "subtype", ")", "{", "type", "=", "type", "(", "col", ".", "subtype", ")", ";", "}", "else", "if", "(", "col", ".", "keytype", ")", "{", "type", "=", "type", "(", "col", ".", "keytype", ",", "col", ".", "valuetype", ")", ";", "}", "val", "=", "type", ".", "deserialize", "(", "row", "[", "i", "]", ")", ";", "this", "[", "col", ".", "name", "]", "=", "val", ";", "cols", ".", "push", "(", "val", ")", ";", "}", "Object", ".", "defineProperty", "(", "this", ",", "'columns'", ",", "{", "value", ":", "cols", ",", "enumerable", ":", "false", "}", ")", ";", "}" ]
A row. @constructor
[ "A", "row", "." ]
c80563526827d13505e4821f7091d4db75e556c1
https://github.com/suguru/cql-client/blob/c80563526827d13505e4821f7091d4db75e556c1/lib/protocol/resultset.js#L13-L31
train
wedeploy/wedeploy-middleware
auth.js
awaitFunction
function awaitFunction(fn) { return (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; }
javascript
function awaitFunction(fn) { return (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; }
[ "function", "awaitFunction", "(", "fn", ")", "{", "return", "(", "req", ",", "res", ",", "next", ")", "=>", "{", "Promise", ".", "resolve", "(", "fn", "(", "req", ",", "res", ",", "next", ")", ")", ".", "catch", "(", "next", ")", ";", "}", ";", "}" ]
Turn async function into regular function @param {Function} fn @return {Function}
[ "Turn", "async", "function", "into", "regular", "function" ]
d6c98f8f0da7ce3b3b4539cc1b4264166a715369
https://github.com/wedeploy/wedeploy-middleware/blob/d6c98f8f0da7ce3b3b4539cc1b4264166a715369/auth.js#L12-L16
train
wedeploy/wedeploy-middleware
auth.js
prepareConfig
function prepareConfig(config) { if (!('authorizationError' in config)) { config.authorizationError = {status: 401, message: 'Unauthorized'}; } if (!('unauthorizedOnly' in config)) { config.unauthorizedOnly = false; } }
javascript
function prepareConfig(config) { if (!('authorizationError' in config)) { config.authorizationError = {status: 401, message: 'Unauthorized'}; } if (!('unauthorizedOnly' in config)) { config.unauthorizedOnly = false; } }
[ "function", "prepareConfig", "(", "config", ")", "{", "if", "(", "!", "(", "'authorizationError'", "in", "config", ")", ")", "{", "config", ".", "authorizationError", "=", "{", "status", ":", "401", ",", "message", ":", "'Unauthorized'", "}", ";", "}", "if", "(", "!", "(", "'unauthorizedOnly'", "in", "config", ")", ")", "{", "config", ".", "unauthorizedOnly", "=", "false", ";", "}", "}" ]
Prepare configuration values. @param {Object} config
[ "Prepare", "configuration", "values", "." ]
d6c98f8f0da7ce3b3b4539cc1b4264166a715369
https://github.com/wedeploy/wedeploy-middleware/blob/d6c98f8f0da7ce3b3b4539cc1b4264166a715369/auth.js#L131-L138
train
wedeploy/wedeploy-middleware
auth.js
retrieveUserFromRedis
async function retrieveUserFromRedis(res, auth, tokenOrEmail, config) { if (config.redisClient) { const getFromRedis = util .promisify(config.redisClient.get) .bind(config.redisClient); const cachedUserData = await getFromRedis(`${ns}:${tokenOrEmail}`); if (cachedUserData) { const data = JSON.parse(cachedUserData); const user = auth.createAuthFromData(data); auth.currentUser = user; res.locals = res.locals || {}; res.locals.auth = auth; return user; } } }
javascript
async function retrieveUserFromRedis(res, auth, tokenOrEmail, config) { if (config.redisClient) { const getFromRedis = util .promisify(config.redisClient.get) .bind(config.redisClient); const cachedUserData = await getFromRedis(`${ns}:${tokenOrEmail}`); if (cachedUserData) { const data = JSON.parse(cachedUserData); const user = auth.createAuthFromData(data); auth.currentUser = user; res.locals = res.locals || {}; res.locals.auth = auth; return user; } } }
[ "async", "function", "retrieveUserFromRedis", "(", "res", ",", "auth", ",", "tokenOrEmail", ",", "config", ")", "{", "if", "(", "config", ".", "redisClient", ")", "{", "const", "getFromRedis", "=", "util", ".", "promisify", "(", "config", ".", "redisClient", ".", "get", ")", ".", "bind", "(", "config", ".", "redisClient", ")", ";", "const", "cachedUserData", "=", "await", "getFromRedis", "(", "`", "${", "ns", "}", "${", "tokenOrEmail", "}", "`", ")", ";", "if", "(", "cachedUserData", ")", "{", "const", "data", "=", "JSON", ".", "parse", "(", "cachedUserData", ")", ";", "const", "user", "=", "auth", ".", "createAuthFromData", "(", "data", ")", ";", "auth", ".", "currentUser", "=", "user", ";", "res", ".", "locals", "=", "res", ".", "locals", "||", "{", "}", ";", "res", ".", "locals", ".", "auth", "=", "auth", ";", "return", "user", ";", "}", "}", "}" ]
Get User from Redis Client @param {!Response} res @param {!Auth} auth @param {!string} tokenOrEmail @param {!Object} config @return {Auth}
[ "Get", "User", "from", "Redis", "Client" ]
d6c98f8f0da7ce3b3b4539cc1b4264166a715369
https://github.com/wedeploy/wedeploy-middleware/blob/d6c98f8f0da7ce3b3b4539cc1b4264166a715369/auth.js#L148-L163
train
wedeploy/wedeploy-middleware
auth.js
saveUserInRedis
function saveUserInRedis(user, tokenOrEmail, config) { if (config.redisClient) { const key = `${ns}:${tokenOrEmail}`; config.redisClient.set(key, JSON.stringify(user.data_), 'EX', 10); } }
javascript
function saveUserInRedis(user, tokenOrEmail, config) { if (config.redisClient) { const key = `${ns}:${tokenOrEmail}`; config.redisClient.set(key, JSON.stringify(user.data_), 'EX', 10); } }
[ "function", "saveUserInRedis", "(", "user", ",", "tokenOrEmail", ",", "config", ")", "{", "if", "(", "config", ".", "redisClient", ")", "{", "const", "key", "=", "`", "${", "ns", "}", "${", "tokenOrEmail", "}", "`", ";", "config", ".", "redisClient", ".", "set", "(", "key", ",", "JSON", ".", "stringify", "(", "user", ".", "data_", ")", ",", "'EX'", ",", "10", ")", ";", "}", "}" ]
Save user in Redis Client @param {!Auth} user @param {!String} tokenOrEmail @param {!Object} config
[ "Save", "user", "in", "Redis", "Client" ]
d6c98f8f0da7ce3b3b4539cc1b4264166a715369
https://github.com/wedeploy/wedeploy-middleware/blob/d6c98f8f0da7ce3b3b4539cc1b4264166a715369/auth.js#L171-L176
train
leftshifters/azimuth
lib/azimuth.js
locationToPoint
function locationToPoint(loc) { var lat, lng, radius, cosLat, sinLat, cosLng, sinLng, x, y, z; lat = loc.lat * Math.PI / 180.0; lng = loc.lng * Math.PI / 180.0; radius = loc.elv + getRadius(lat); cosLng = Math.cos(lng); sinLng = Math.sin(lng); cosLat = Math.cos(lat); sinLat = Math.sin(lat); x = cosLng * cosLat * radius; y = sinLng * cosLat * radius; z = sinLat * radius; return { x: x, y: y, z: z, radius: radius }; }
javascript
function locationToPoint(loc) { var lat, lng, radius, cosLat, sinLat, cosLng, sinLng, x, y, z; lat = loc.lat * Math.PI / 180.0; lng = loc.lng * Math.PI / 180.0; radius = loc.elv + getRadius(lat); cosLng = Math.cos(lng); sinLng = Math.sin(lng); cosLat = Math.cos(lat); sinLat = Math.sin(lat); x = cosLng * cosLat * radius; y = sinLng * cosLat * radius; z = sinLat * radius; return { x: x, y: y, z: z, radius: radius }; }
[ "function", "locationToPoint", "(", "loc", ")", "{", "var", "lat", ",", "lng", ",", "radius", ",", "cosLat", ",", "sinLat", ",", "cosLng", ",", "sinLng", ",", "x", ",", "y", ",", "z", ";", "lat", "=", "loc", ".", "lat", "*", "Math", ".", "PI", "/", "180.0", ";", "lng", "=", "loc", ".", "lng", "*", "Math", ".", "PI", "/", "180.0", ";", "radius", "=", "loc", ".", "elv", "+", "getRadius", "(", "lat", ")", ";", "cosLng", "=", "Math", ".", "cos", "(", "lng", ")", ";", "sinLng", "=", "Math", ".", "sin", "(", "lng", ")", ";", "cosLat", "=", "Math", ".", "cos", "(", "lat", ")", ";", "sinLat", "=", "Math", ".", "sin", "(", "lat", ")", ";", "x", "=", "cosLng", "*", "cosLat", "*", "radius", ";", "y", "=", "sinLng", "*", "cosLat", "*", "radius", ";", "z", "=", "sinLat", "*", "radius", ";", "return", "{", "x", ":", "x", ",", "y", ":", "y", ",", "z", ":", "z", ",", "radius", ":", "radius", "}", ";", "}" ]
Converts lat, lng, elv to x, y, z @param {Object} loc @returns {Object}
[ "Converts", "lat", "lng", "elv", "to", "x", "y", "z" ]
75f0ad5c4c714fb0f937689ddb638c7567a6d38f
https://github.com/leftshifters/azimuth/blob/75f0ad5c4c714fb0f937689ddb638c7567a6d38f/lib/azimuth.js#L89-L104
train
leftshifters/azimuth
lib/azimuth.js
distance
function distance(ap, bp) { var dx, dy, dz; dx = ap.x - bp.x; dy = ap.y - bp.y; dz = ap.z - bp.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); }
javascript
function distance(ap, bp) { var dx, dy, dz; dx = ap.x - bp.x; dy = ap.y - bp.y; dz = ap.z - bp.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); }
[ "function", "distance", "(", "ap", ",", "bp", ")", "{", "var", "dx", ",", "dy", ",", "dz", ";", "dx", "=", "ap", ".", "x", "-", "bp", ".", "x", ";", "dy", "=", "ap", ".", "y", "-", "bp", ".", "y", ";", "dz", "=", "ap", ".", "z", "-", "bp", ".", "z", ";", "return", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", "+", "dz", "*", "dz", ")", ";", "}" ]
Calculates distance between two points in 3d space @param {Object} ap @param {Object} bp @returns {Number}
[ "Calculates", "distance", "between", "two", "points", "in", "3d", "space" ]
75f0ad5c4c714fb0f937689ddb638c7567a6d38f
https://github.com/leftshifters/azimuth/blob/75f0ad5c4c714fb0f937689ddb638c7567a6d38f/lib/azimuth.js#L113-L121
train
leftshifters/azimuth
lib/azimuth.js
rotateGlobe
function rotateGlobe(b, a, bRadius) { var br, brp, alat, acos, asin, bx, by, bz; // Get modified coordinates of 'b' by rotating the globe so // that 'a' is at lat=0, lng=0 br = { lat: b.lat, lng: (b.lng - a.lng), elv:b.elv }; brp = locationToPoint(br); // scale all the coordinates based on the original, correct geoid radius brp.x *= (bRadius / brp.radius); brp.y *= (bRadius / brp.radius); brp.z *= (bRadius / brp.radius); // restore actual geoid-based radius calculation brp.radius = bRadius; // Rotate brp cartesian coordinates around the z-axis by a.lng degrees, // then around the y-axis by a.lat degrees. // Though we are decreasing by a.lat degrees, as seen above the y-axis, // this is a positive (counterclockwise) rotation // (if B's longitude is east of A's). // However, from this point of view the x-axis is pointing left. // So we will look the other way making the x-axis pointing right, the z-axis // pointing up, and the rotation treated as negative. alat = -a.lat * Math.PI / 180.0; acos = Math.cos(alat); asin = Math.sin(alat); bx = (brp.x * acos) - (brp.z * asin); by = brp.y; bz = (brp.x * asin) + (brp.z * acos); return { x: bx, y: by, z: bz }; }
javascript
function rotateGlobe(b, a, bRadius) { var br, brp, alat, acos, asin, bx, by, bz; // Get modified coordinates of 'b' by rotating the globe so // that 'a' is at lat=0, lng=0 br = { lat: b.lat, lng: (b.lng - a.lng), elv:b.elv }; brp = locationToPoint(br); // scale all the coordinates based on the original, correct geoid radius brp.x *= (bRadius / brp.radius); brp.y *= (bRadius / brp.radius); brp.z *= (bRadius / brp.radius); // restore actual geoid-based radius calculation brp.radius = bRadius; // Rotate brp cartesian coordinates around the z-axis by a.lng degrees, // then around the y-axis by a.lat degrees. // Though we are decreasing by a.lat degrees, as seen above the y-axis, // this is a positive (counterclockwise) rotation // (if B's longitude is east of A's). // However, from this point of view the x-axis is pointing left. // So we will look the other way making the x-axis pointing right, the z-axis // pointing up, and the rotation treated as negative. alat = -a.lat * Math.PI / 180.0; acos = Math.cos(alat); asin = Math.sin(alat); bx = (brp.x * acos) - (brp.z * asin); by = brp.y; bz = (brp.x * asin) + (brp.z * acos); return { x: bx, y: by, z: bz }; }
[ "function", "rotateGlobe", "(", "b", ",", "a", ",", "bRadius", ")", "{", "var", "br", ",", "brp", ",", "alat", ",", "acos", ",", "asin", ",", "bx", ",", "by", ",", "bz", ";", "br", "=", "{", "lat", ":", "b", ".", "lat", ",", "lng", ":", "(", "b", ".", "lng", "-", "a", ".", "lng", ")", ",", "elv", ":", "b", ".", "elv", "}", ";", "brp", "=", "locationToPoint", "(", "br", ")", ";", "brp", ".", "x", "*=", "(", "bRadius", "/", "brp", ".", "radius", ")", ";", "brp", ".", "y", "*=", "(", "bRadius", "/", "brp", ".", "radius", ")", ";", "brp", ".", "z", "*=", "(", "bRadius", "/", "brp", ".", "radius", ")", ";", "brp", ".", "radius", "=", "bRadius", ";", "alat", "=", "-", "a", ".", "lat", "*", "Math", ".", "PI", "/", "180.0", ";", "acos", "=", "Math", ".", "cos", "(", "alat", ")", ";", "asin", "=", "Math", ".", "sin", "(", "alat", ")", ";", "bx", "=", "(", "brp", ".", "x", "*", "acos", ")", "-", "(", "brp", ".", "z", "*", "asin", ")", ";", "by", "=", "brp", ".", "y", ";", "bz", "=", "(", "brp", ".", "x", "*", "asin", ")", "+", "(", "brp", ".", "z", "*", "acos", ")", ";", "return", "{", "x", ":", "bx", ",", "y", ":", "by", ",", "z", ":", "bz", "}", ";", "}" ]
Gets rotated point @param {Object} b @param {Object} a @param {Number} bRadius @returns {Object}
[ "Gets", "rotated", "point" ]
75f0ad5c4c714fb0f937689ddb638c7567a6d38f
https://github.com/leftshifters/azimuth/blob/75f0ad5c4c714fb0f937689ddb638c7567a6d38f/lib/azimuth.js#L131-L164
train
dbushell/dbushell-grunt-mustatic
tasks/mustatic.js
function(path, partials) { var templates = { }; grunt.file.recurse(path, function (absPath, rootDir, subDir, filename) { // ignore non-template files if (!filename.match(matcher)) { return; } // read template source and data var relPath = absPath.substr(rootDir.length + 1), tmpData = absPath.replace(matcher, '.json'), tmpSrc = grunt.file.read(absPath), // template name based on path (e.g. "index", "guide/index", etc) name = relPath.replace(matcher, ''), // set-up template specific locals locals = mustatic.merge({}, globals); // add template URL to locals locals.url = name + '.html'; // load template data and merge into locals if (grunt.file.exists(tmpData)) { locals = mustatic.merge(locals, JSON.parse(grunt.file.read(tmpData))); } // store locals data[name] = locals; templates[name] = hogan.compile(tmpSrc); }); return templates; }
javascript
function(path, partials) { var templates = { }; grunt.file.recurse(path, function (absPath, rootDir, subDir, filename) { // ignore non-template files if (!filename.match(matcher)) { return; } // read template source and data var relPath = absPath.substr(rootDir.length + 1), tmpData = absPath.replace(matcher, '.json'), tmpSrc = grunt.file.read(absPath), // template name based on path (e.g. "index", "guide/index", etc) name = relPath.replace(matcher, ''), // set-up template specific locals locals = mustatic.merge({}, globals); // add template URL to locals locals.url = name + '.html'; // load template data and merge into locals if (grunt.file.exists(tmpData)) { locals = mustatic.merge(locals, JSON.parse(grunt.file.read(tmpData))); } // store locals data[name] = locals; templates[name] = hogan.compile(tmpSrc); }); return templates; }
[ "function", "(", "path", ",", "partials", ")", "{", "var", "templates", "=", "{", "}", ";", "grunt", ".", "file", ".", "recurse", "(", "path", ",", "function", "(", "absPath", ",", "rootDir", ",", "subDir", ",", "filename", ")", "{", "if", "(", "!", "filename", ".", "match", "(", "matcher", ")", ")", "{", "return", ";", "}", "var", "relPath", "=", "absPath", ".", "substr", "(", "rootDir", ".", "length", "+", "1", ")", ",", "tmpData", "=", "absPath", ".", "replace", "(", "matcher", ",", "'.json'", ")", ",", "tmpSrc", "=", "grunt", ".", "file", ".", "read", "(", "absPath", ")", ",", "name", "=", "relPath", ".", "replace", "(", "matcher", ",", "''", ")", ",", "locals", "=", "mustatic", ".", "merge", "(", "{", "}", ",", "globals", ")", ";", "locals", ".", "url", "=", "name", "+", "'.html'", ";", "if", "(", "grunt", ".", "file", ".", "exists", "(", "tmpData", ")", ")", "{", "locals", "=", "mustatic", ".", "merge", "(", "locals", ",", "JSON", ".", "parse", "(", "grunt", ".", "file", ".", "read", "(", "tmpData", ")", ")", ")", ";", "}", "data", "[", "name", "]", "=", "locals", ";", "templates", "[", "name", "]", "=", "hogan", ".", "compile", "(", "tmpSrc", ")", ";", "}", ")", ";", "return", "templates", ";", "}" ]
compile templates from a given directory
[ "compile", "templates", "from", "a", "given", "directory" ]
01a8c9517aa4dd50c2de53a61c907c98a960f6aa
https://github.com/dbushell/dbushell-grunt-mustatic/blob/01a8c9517aa4dd50c2de53a61c907c98a960f6aa/tasks/mustatic.js#L53-L90
train
juttle/juttle-viz
src/lib/generators/axis-label.js
function(el, options) { if (typeof options === 'undefined') { options = {}; } // apply defaults options = _.defaults(options, defaults, { orientation : 'left', labelText: '', // true to position the axis-label // when chart uses layout positioning of axis-labels is handled by layout position: true }); this._labelText = options.labelText; this._animDuration = options.duration; this._orientation = options.orientation; this._margin = options.margin; this._width = options.width; this._height = options.height; this._isPositioned = options.position; this._container = d3.select(el); this._g = null; this._text = null; }
javascript
function(el, options) { if (typeof options === 'undefined') { options = {}; } // apply defaults options = _.defaults(options, defaults, { orientation : 'left', labelText: '', // true to position the axis-label // when chart uses layout positioning of axis-labels is handled by layout position: true }); this._labelText = options.labelText; this._animDuration = options.duration; this._orientation = options.orientation; this._margin = options.margin; this._width = options.width; this._height = options.height; this._isPositioned = options.position; this._container = d3.select(el); this._g = null; this._text = null; }
[ "function", "(", "el", ",", "options", ")", "{", "if", "(", "typeof", "options", "===", "'undefined'", ")", "{", "options", "=", "{", "}", ";", "}", "options", "=", "_", ".", "defaults", "(", "options", ",", "defaults", ",", "{", "orientation", ":", "'left'", ",", "labelText", ":", "''", ",", "position", ":", "true", "}", ")", ";", "this", ".", "_labelText", "=", "options", ".", "labelText", ";", "this", ".", "_animDuration", "=", "options", ".", "duration", ";", "this", ".", "_orientation", "=", "options", ".", "orientation", ";", "this", ".", "_margin", "=", "options", ".", "margin", ";", "this", ".", "_width", "=", "options", ".", "width", ";", "this", ".", "_height", "=", "options", ".", "height", ";", "this", ".", "_isPositioned", "=", "options", ".", "position", ";", "this", ".", "_container", "=", "d3", ".", "select", "(", "el", ")", ";", "this", ".", "_g", "=", "null", ";", "this", ".", "_text", "=", "null", ";", "}" ]
Axis label component that can be used for x or y axis @param {Object} el - the HTML element @param {string} options.labelText - the label text @param {string} options.orientation - supported values 'left', 'right', 'bottom'
[ "Axis", "label", "component", "that", "can", "be", "used", "for", "x", "or", "y", "axis" ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/lib/generators/axis-label.js#L11-L38
train
emmetio/css-abbreviation
lib/numeric-value.js
eatNumber
function eatNumber(stream) { const start = stream.pos; const negative = stream.eat(DASH); const afterNegative = stream.pos; stream.eatWhile(isNumber); const prevPos = stream.pos; if (stream.eat(DOT) && !stream.eatWhile(isNumber)) { // Number followed by a dot, but then no number stream.pos = prevPos; } // Edge case: consumed dash only: not a number, bail-out if (stream.pos === afterNegative) { stream.pos = start; } return stream.pos !== start; }
javascript
function eatNumber(stream) { const start = stream.pos; const negative = stream.eat(DASH); const afterNegative = stream.pos; stream.eatWhile(isNumber); const prevPos = stream.pos; if (stream.eat(DOT) && !stream.eatWhile(isNumber)) { // Number followed by a dot, but then no number stream.pos = prevPos; } // Edge case: consumed dash only: not a number, bail-out if (stream.pos === afterNegative) { stream.pos = start; } return stream.pos !== start; }
[ "function", "eatNumber", "(", "stream", ")", "{", "const", "start", "=", "stream", ".", "pos", ";", "const", "negative", "=", "stream", ".", "eat", "(", "DASH", ")", ";", "const", "afterNegative", "=", "stream", ".", "pos", ";", "stream", ".", "eatWhile", "(", "isNumber", ")", ";", "const", "prevPos", "=", "stream", ".", "pos", ";", "if", "(", "stream", ".", "eat", "(", "DOT", ")", "&&", "!", "stream", ".", "eatWhile", "(", "isNumber", ")", ")", "{", "stream", ".", "pos", "=", "prevPos", ";", "}", "if", "(", "stream", ".", "pos", "===", "afterNegative", ")", "{", "stream", ".", "pos", "=", "start", ";", "}", "return", "stream", ".", "pos", "!==", "start", ";", "}" ]
Eats number value from given stream @param {StreamReader} stream @return {Boolean} Returns `true` if number was consumed
[ "Eats", "number", "value", "from", "given", "stream" ]
af922be7317caba3662162ee271f01ae63849e14
https://github.com/emmetio/css-abbreviation/blob/af922be7317caba3662162ee271f01ae63849e14/lib/numeric-value.js#L48-L67
train
mangonel/mangonel
src/lib/mangonel.js
Mangonel
function Mangonel (modules = []) { const getLaunchersByName = (modules, name) => modules.filter(m => m.name === name) const getFirstLauncher = (...args) => modules.filter(m => m.platforms.filter(p => p === args[1]).length > 0)[0] return { /** * * * @param {function} emulator launcher modules * @param {Object} [launcher={}] launcher object * @param {Object} [options={}] options object * @returns {int} processId */ launch (software, launcher = {}, settings = {}, options = {}) { const command = getFirstLauncher(modules, software.platform).buildCommand( software.file, launcher, settings ) return execute(command, options) }, modules } }
javascript
function Mangonel (modules = []) { const getLaunchersByName = (modules, name) => modules.filter(m => m.name === name) const getFirstLauncher = (...args) => modules.filter(m => m.platforms.filter(p => p === args[1]).length > 0)[0] return { /** * * * @param {function} emulator launcher modules * @param {Object} [launcher={}] launcher object * @param {Object} [options={}] options object * @returns {int} processId */ launch (software, launcher = {}, settings = {}, options = {}) { const command = getFirstLauncher(modules, software.platform).buildCommand( software.file, launcher, settings ) return execute(command, options) }, modules } }
[ "function", "Mangonel", "(", "modules", "=", "[", "]", ")", "{", "const", "getLaunchersByName", "=", "(", "modules", ",", "name", ")", "=>", "modules", ".", "filter", "(", "m", "=>", "m", ".", "name", "===", "name", ")", "const", "getFirstLauncher", "=", "(", "...", "args", ")", "=>", "modules", ".", "filter", "(", "m", "=>", "m", ".", "platforms", ".", "filter", "(", "p", "=>", "p", "===", "args", "[", "1", "]", ")", ".", "length", ">", "0", ")", "[", "0", "]", "return", "{", "launch", "(", "software", ",", "launcher", "=", "{", "}", ",", "settings", "=", "{", "}", ",", "options", "=", "{", "}", ")", "{", "const", "command", "=", "getFirstLauncher", "(", "modules", ",", "software", ".", "platform", ")", ".", "buildCommand", "(", "software", ".", "file", ",", "launcher", ",", "settings", ")", "return", "execute", "(", "command", ",", "options", ")", "}", ",", "modules", "}", "}" ]
mangonel - Main constructor for the application @param {array} [modules=[]]
[ "mangonel", "-", "Main", "constructor", "for", "the", "application" ]
f41ec456dca21326750cde5bd66bce948060beb8
https://github.com/mangonel/mangonel/blob/f41ec456dca21326750cde5bd66bce948060beb8/src/lib/mangonel.js#L8-L35
train
codekirei/columnize-array
index.js
columnizeArray
function columnizeArray(array, opts) { // conditionally sort array //---------------------------------------------------------- const ar = opts && opts.sort ? typeof opts.sort === 'boolean' ? array.sort() : opts.sort(array) : array // build and freeze props //---------------------------------------------------------- const props = freeze(merge( { gap: { len: 2 , ch: ' ' } , maxRowLen: 80 } , opts , { ar , arLen: ar.length , initState: { i: 0 , strs: [] , indices: [] , widths: [] } } )) // columnize and return //---------------------------------------------------------- const columns = new Columns(props) return { strs: columns.state.strs , indices: columns.state.indices } }
javascript
function columnizeArray(array, opts) { // conditionally sort array //---------------------------------------------------------- const ar = opts && opts.sort ? typeof opts.sort === 'boolean' ? array.sort() : opts.sort(array) : array // build and freeze props //---------------------------------------------------------- const props = freeze(merge( { gap: { len: 2 , ch: ' ' } , maxRowLen: 80 } , opts , { ar , arLen: ar.length , initState: { i: 0 , strs: [] , indices: [] , widths: [] } } )) // columnize and return //---------------------------------------------------------- const columns = new Columns(props) return { strs: columns.state.strs , indices: columns.state.indices } }
[ "function", "columnizeArray", "(", "array", ",", "opts", ")", "{", "const", "ar", "=", "opts", "&&", "opts", ".", "sort", "?", "typeof", "opts", ".", "sort", "===", "'boolean'", "?", "array", ".", "sort", "(", ")", ":", "opts", ".", "sort", "(", "array", ")", ":", "array", "const", "props", "=", "freeze", "(", "merge", "(", "{", "gap", ":", "{", "len", ":", "2", ",", "ch", ":", "' '", "}", ",", "maxRowLen", ":", "80", "}", ",", "opts", ",", "{", "ar", ",", "arLen", ":", "ar", ".", "length", ",", "initState", ":", "{", "i", ":", "0", ",", "strs", ":", "[", "]", ",", "indices", ":", "[", "]", ",", "widths", ":", "[", "]", "}", "}", ")", ")", "const", "columns", "=", "new", "Columns", "(", "props", ")", "return", "{", "strs", ":", "columns", ".", "state", ".", "strs", ",", "indices", ":", "columns", ".", "state", ".", "indices", "}", "}" ]
Columnize an array of strings. @param {String[]} array - array of strs to columnize @param {Object} opts - configurable options @returns {Object} strs: array of strings; indices: array of index arrays
[ "Columnize", "an", "array", "of", "strings", "." ]
ba100d1d9cf707fa249a58fa177d6b26ec131278
https://github.com/codekirei/columnize-array/blob/ba100d1d9cf707fa249a58fa177d6b26ec131278/index.js#L16-L54
train
Evo-Forge/Crux
lib/core/application.js
getComponentConfiguration
function getComponentConfiguration(name) { var config = {}; if (typeof projectConfig[name] === 'object') { config = projectConfig[name]; } if (typeof componentConfig[name] === 'object') { if (config == null) config = {}; config = util.extend(true, config, componentConfig[name]); } if (typeof appConfig[name] === 'object') { if (config == null) config = {}; config = util.extend(true, config, appConfig[name]); } function ref(obj, str) { return str.split(".").reduce(function(o, x) { return o[x] }, obj); } if (config == null) { // if it's null, we search for inner dotted configs. try { config = ref(projectConfig, name); } catch (e) { } try { config = util.extend(true, config || {}, ref(appConfig, name)); } catch (e) { } } return config; }
javascript
function getComponentConfiguration(name) { var config = {}; if (typeof projectConfig[name] === 'object') { config = projectConfig[name]; } if (typeof componentConfig[name] === 'object') { if (config == null) config = {}; config = util.extend(true, config, componentConfig[name]); } if (typeof appConfig[name] === 'object') { if (config == null) config = {}; config = util.extend(true, config, appConfig[name]); } function ref(obj, str) { return str.split(".").reduce(function(o, x) { return o[x] }, obj); } if (config == null) { // if it's null, we search for inner dotted configs. try { config = ref(projectConfig, name); } catch (e) { } try { config = util.extend(true, config || {}, ref(appConfig, name)); } catch (e) { } } return config; }
[ "function", "getComponentConfiguration", "(", "name", ")", "{", "var", "config", "=", "{", "}", ";", "if", "(", "typeof", "projectConfig", "[", "name", "]", "===", "'object'", ")", "{", "config", "=", "projectConfig", "[", "name", "]", ";", "}", "if", "(", "typeof", "componentConfig", "[", "name", "]", "===", "'object'", ")", "{", "if", "(", "config", "==", "null", ")", "config", "=", "{", "}", ";", "config", "=", "util", ".", "extend", "(", "true", ",", "config", ",", "componentConfig", "[", "name", "]", ")", ";", "}", "if", "(", "typeof", "appConfig", "[", "name", "]", "===", "'object'", ")", "{", "if", "(", "config", "==", "null", ")", "config", "=", "{", "}", ";", "config", "=", "util", ".", "extend", "(", "true", ",", "config", ",", "appConfig", "[", "name", "]", ")", ";", "}", "function", "ref", "(", "obj", ",", "str", ")", "{", "return", "str", ".", "split", "(", "\".\"", ")", ".", "reduce", "(", "function", "(", "o", ",", "x", ")", "{", "return", "o", "[", "x", "]", "}", ",", "obj", ")", ";", "}", "if", "(", "config", "==", "null", ")", "{", "try", "{", "config", "=", "ref", "(", "projectConfig", ",", "name", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "try", "{", "config", "=", "util", ".", "extend", "(", "true", ",", "config", "||", "{", "}", ",", "ref", "(", "appConfig", ",", "name", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "return", "config", ";", "}" ]
Returns the configuration object of a previously registered component or null if either the componet was found or it has no configuration attached. @function @memberof crux.Applicationlication @param {string} name - the component name.
[ "Returns", "the", "configuration", "object", "of", "a", "previously", "registered", "component", "or", "null", "if", "either", "the", "componet", "was", "found", "or", "it", "has", "no", "configuration", "attached", "." ]
f5264fbc2eb053e3170cf2b7b38d46d08f779feb
https://github.com/Evo-Forge/Crux/blob/f5264fbc2eb053e3170cf2b7b38d46d08f779feb/lib/core/application.js#L174-L204
train
avigoldman/fuse-email
lib/transports/sparkpost.js
toInboundMessage
function toInboundMessage(relayMessage, mail) { let inboundMessage = transport.defaultInboundMessage({ to: { email: relayMessage.rcpt_to, name: '' }, from: mail.from[0], subject: mail.subject, text: mail.text, html: mail.html, recipients: mail.to, cc: mail.cc, bcc: mail.bcc, headers: mail.headers, attachments: mail.attachments, _raw: relayMessage }); inboundMessage.id = transport.defaultMessageId(inboundMessage); return inboundMessage; }
javascript
function toInboundMessage(relayMessage, mail) { let inboundMessage = transport.defaultInboundMessage({ to: { email: relayMessage.rcpt_to, name: '' }, from: mail.from[0], subject: mail.subject, text: mail.text, html: mail.html, recipients: mail.to, cc: mail.cc, bcc: mail.bcc, headers: mail.headers, attachments: mail.attachments, _raw: relayMessage }); inboundMessage.id = transport.defaultMessageId(inboundMessage); return inboundMessage; }
[ "function", "toInboundMessage", "(", "relayMessage", ",", "mail", ")", "{", "let", "inboundMessage", "=", "transport", ".", "defaultInboundMessage", "(", "{", "to", ":", "{", "email", ":", "relayMessage", ".", "rcpt_to", ",", "name", ":", "''", "}", ",", "from", ":", "mail", ".", "from", "[", "0", "]", ",", "subject", ":", "mail", ".", "subject", ",", "text", ":", "mail", ".", "text", ",", "html", ":", "mail", ".", "html", ",", "recipients", ":", "mail", ".", "to", ",", "cc", ":", "mail", ".", "cc", ",", "bcc", ":", "mail", ".", "bcc", ",", "headers", ":", "mail", ".", "headers", ",", "attachments", ":", "mail", ".", "attachments", ",", "_raw", ":", "relayMessage", "}", ")", ";", "inboundMessage", ".", "id", "=", "transport", ".", "defaultMessageId", "(", "inboundMessage", ")", ";", "return", "inboundMessage", ";", "}" ]
Takes a relay message from sparkpost and converts it to an inboundMessage @param {Object} relayMessage @param {Object} mail - from MailParser @returns {InboundMessage} inboundMessage
[ "Takes", "a", "relay", "message", "from", "sparkpost", "and", "converts", "it", "to", "an", "inboundMessage" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/transports/sparkpost.js#L268-L289
train
avigoldman/fuse-email
lib/transports/sparkpost.js
handleReply
function handleReply(inboundMessage, data) { if (data.reply) { _.merge(data.content.headers, Transport.getReplyHeaders(inboundMessage)); data.content.subject = Transport.getReplySubject(inboundMessage); delete data.reply; } return data; }
javascript
function handleReply(inboundMessage, data) { if (data.reply) { _.merge(data.content.headers, Transport.getReplyHeaders(inboundMessage)); data.content.subject = Transport.getReplySubject(inboundMessage); delete data.reply; } return data; }
[ "function", "handleReply", "(", "inboundMessage", ",", "data", ")", "{", "if", "(", "data", ".", "reply", ")", "{", "_", ".", "merge", "(", "data", ".", "content", ".", "headers", ",", "Transport", ".", "getReplyHeaders", "(", "inboundMessage", ")", ")", ";", "data", ".", "content", ".", "subject", "=", "Transport", ".", "getReplySubject", "(", "inboundMessage", ")", ";", "delete", "data", ".", "reply", ";", "}", "return", "data", ";", "}" ]
Modifies the data to be in reply if in reply @param {inboundMessage} inboundMessage @param {Object} data - the data for the SparkPost API @returns {Object} data
[ "Modifies", "the", "data", "to", "be", "in", "reply", "if", "in", "reply" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/transports/sparkpost.js#L301-L311
train
avigoldman/fuse-email
lib/transports/sparkpost.js
throwUpError
function throwUpError(err) { if (err.name === 'SparkPostError') console.log(JSON.stringify(err.errors, null, 2)); setTimeout(function() { throw err; }); }
javascript
function throwUpError(err) { if (err.name === 'SparkPostError') console.log(JSON.stringify(err.errors, null, 2)); setTimeout(function() { throw err; }); }
[ "function", "throwUpError", "(", "err", ")", "{", "if", "(", "err", ".", "name", "===", "'SparkPostError'", ")", "console", ".", "log", "(", "JSON", ".", "stringify", "(", "err", ".", "errors", ",", "null", ",", "2", ")", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "throw", "err", ";", "}", ")", ";", "}" ]
Logs error for sparkpost reponse @param {Error} err
[ "Logs", "error", "for", "sparkpost", "reponse" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/transports/sparkpost.js#L318-L323
train
troven/meta4apis
src/plugins/crud.js
function(model) { model.can = _.extend({create: true, read: true, update: true, delete: true}, model.can, feature.can); }
javascript
function(model) { model.can = _.extend({create: true, read: true, update: true, delete: true}, model.can, feature.can); }
[ "function", "(", "model", ")", "{", "model", ".", "can", "=", "_", ".", "extend", "(", "{", "create", ":", "true", ",", "read", ":", "true", ",", "update", ":", "true", ",", "delete", ":", "true", "}", ",", "model", ".", "can", ",", "feature", ".", "can", ")", ";", "}" ]
ensure CRUD permissions - feature permissions take precedence
[ "ensure", "CRUD", "permissions", "-", "feature", "permissions", "take", "precedence" ]
853524c7df10a6a4e297d56e1814936342b48650
https://github.com/troven/meta4apis/blob/853524c7df10a6a4e297d56e1814936342b48650/src/plugins/crud.js#L125-L127
train
boilerplates/snippet
index.js
Snippets
function Snippets(options) { this.options = options || {}; this.store = store(this.options); this.snippets = {}; this.presets = {}; this.cache = {}; this.cache.data = {}; var FetchFiles = lazy.FetchFiles(); this.downloader = new FetchFiles(this.options); this.presets = this.downloader.presets; if (typeof this.options.templates === 'object') { this.visit('set', this.options.templates); } }
javascript
function Snippets(options) { this.options = options || {}; this.store = store(this.options); this.snippets = {}; this.presets = {}; this.cache = {}; this.cache.data = {}; var FetchFiles = lazy.FetchFiles(); this.downloader = new FetchFiles(this.options); this.presets = this.downloader.presets; if (typeof this.options.templates === 'object') { this.visit('set', this.options.templates); } }
[ "function", "Snippets", "(", "options", ")", "{", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "store", "=", "store", "(", "this", ".", "options", ")", ";", "this", ".", "snippets", "=", "{", "}", ";", "this", ".", "presets", "=", "{", "}", ";", "this", ".", "cache", "=", "{", "}", ";", "this", ".", "cache", ".", "data", "=", "{", "}", ";", "var", "FetchFiles", "=", "lazy", ".", "FetchFiles", "(", ")", ";", "this", ".", "downloader", "=", "new", "FetchFiles", "(", "this", ".", "options", ")", ";", "this", ".", "presets", "=", "this", ".", "downloader", ".", "presets", ";", "if", "(", "typeof", "this", ".", "options", ".", "templates", "===", "'object'", ")", "{", "this", ".", "visit", "(", "'set'", ",", "this", ".", "options", ".", "templates", ")", ";", "}", "}" ]
Create an instance of `Snippets` with the given options. ```js var Snippets = require('snippets'); var snippets = new Snippets(); ``` @param {Object} `options` @api public
[ "Create", "an", "instance", "of", "Snippets", "with", "the", "given", "options", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/index.js#L43-L59
train
boilerplates/snippet
index.js
function (name, val) { if (typeof name === 'object') { return this.visit('set', name); } utils.set(this.snippets, name, val); return this; }
javascript
function (name, val) { if (typeof name === 'object') { return this.visit('set', name); } utils.set(this.snippets, name, val); return this; }
[ "function", "(", "name", ",", "val", ")", "{", "if", "(", "typeof", "name", "===", "'object'", ")", "{", "return", "this", ".", "visit", "(", "'set'", ",", "name", ")", ";", "}", "utils", ".", "set", "(", "this", ".", "snippets", ",", "name", ",", "val", ")", ";", "return", "this", ";", "}" ]
Cache a snippet or arbitrary value in memory. @param {String} `name` The snippet name @param {any} `val` @return {Object} Returns the `Snippet` instance for chaining @name .set @api public
[ "Cache", "a", "snippet", "or", "arbitrary", "value", "in", "memory", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/index.js#L78-L84
train
boilerplates/snippet
index.js
function (name, preset) { if(typeof name !== 'string') { throw new TypeError('snippets#get expects `name` to be a string.'); } if (utils.startsWith(name, './')) { return this.read(name); } // ex: `http(s)://api.github.com/...` if (/^\w+:\/\//.test(name) || preset) { var snippet = this.downloader .fetch(name, preset) .download(); var parsed = url.parse(name); this.set(parsed.pathname, snippet); return new Snippet(snippet); } var res = this.snippets[name] || this.store.get(name) || utils.get(this.snippets, name); return new Snippet(res); }
javascript
function (name, preset) { if(typeof name !== 'string') { throw new TypeError('snippets#get expects `name` to be a string.'); } if (utils.startsWith(name, './')) { return this.read(name); } // ex: `http(s)://api.github.com/...` if (/^\w+:\/\//.test(name) || preset) { var snippet = this.downloader .fetch(name, preset) .download(); var parsed = url.parse(name); this.set(parsed.pathname, snippet); return new Snippet(snippet); } var res = this.snippets[name] || this.store.get(name) || utils.get(this.snippets, name); return new Snippet(res); }
[ "function", "(", "name", ",", "preset", ")", "{", "if", "(", "typeof", "name", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'snippets#get expects `name` to be a string.'", ")", ";", "}", "if", "(", "utils", ".", "startsWith", "(", "name", ",", "'./'", ")", ")", "{", "return", "this", ".", "read", "(", "name", ")", ";", "}", "if", "(", "/", "^\\w+:\\/\\/", "/", ".", "test", "(", "name", ")", "||", "preset", ")", "{", "var", "snippet", "=", "this", ".", "downloader", ".", "fetch", "(", "name", ",", "preset", ")", ".", "download", "(", ")", ";", "var", "parsed", "=", "url", ".", "parse", "(", "name", ")", ";", "this", ".", "set", "(", "parsed", ".", "pathname", ",", "snippet", ")", ";", "return", "new", "Snippet", "(", "snippet", ")", ";", "}", "var", "res", "=", "this", ".", "snippets", "[", "name", "]", "||", "this", ".", "store", ".", "get", "(", "name", ")", "||", "utils", ".", "get", "(", "this", ".", "snippets", ",", "name", ")", ";", "return", "new", "Snippet", "(", "res", ")", ";", "}" ]
Get a snippet or arbitrary value by `name`. Cached, local, or remote. @param {String} `name` @param {Object} `preset` Preset to use if a URL is passed. @return {Object} Returns the requested snippet. @name .get @api public
[ "Get", "a", "snippet", "or", "arbitrary", "value", "by", "name", ".", "Cached", "local", "or", "remote", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/index.js#L149-L172
train
boilerplates/snippet
index.js
function (snippets, options) { if (typeof snippets === 'string') { var glob = lazy.glob(); var files = glob.sync(snippets, options); files.forEach(function (fp) { var key = fp.split('.').join('\\.'); this.set(key, {path: fp}); }.bind(this)); } return this; }
javascript
function (snippets, options) { if (typeof snippets === 'string') { var glob = lazy.glob(); var files = glob.sync(snippets, options); files.forEach(function (fp) { var key = fp.split('.').join('\\.'); this.set(key, {path: fp}); }.bind(this)); } return this; }
[ "function", "(", "snippets", ",", "options", ")", "{", "if", "(", "typeof", "snippets", "===", "'string'", ")", "{", "var", "glob", "=", "lazy", ".", "glob", "(", ")", ";", "var", "files", "=", "glob", ".", "sync", "(", "snippets", ",", "options", ")", ";", "files", ".", "forEach", "(", "function", "(", "fp", ")", "{", "var", "key", "=", "fp", ".", "split", "(", "'.'", ")", ".", "join", "(", "'\\\\.'", ")", ";", "\\\\", "}", ".", "this", ".", "set", "(", "key", ",", "{", "path", ":", "fp", "}", ")", ";", "bind", ")", ";", "}", "(", "this", ")", "}" ]
Load a glob of snippets. @param {String|Array} `snippets @param {Object} `options` @return {Object} `Snippets` for chaining @name .load @api public
[ "Load", "a", "glob", "of", "snippets", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/index.js#L200-L210
train
juttle/juttle-viz
src/views/timechart.js
function(options) { var userOptions = options; var series = userOptions.series; if (!series) { return userOptions; } series.forEach(function(value, index) { if (Object.keys(userOptions.yScales).length < 2 && Object.keys(userOptions.yScales).indexOf(value.yScale) === -1 && value.yScale === 'secondary') { userOptions.yScales[value.yScale] = { scaling: 'linear', minValue: 'auto', maxValue: 'auto', displayOnAxis: 'right' }; } }); return userOptions; }
javascript
function(options) { var userOptions = options; var series = userOptions.series; if (!series) { return userOptions; } series.forEach(function(value, index) { if (Object.keys(userOptions.yScales).length < 2 && Object.keys(userOptions.yScales).indexOf(value.yScale) === -1 && value.yScale === 'secondary') { userOptions.yScales[value.yScale] = { scaling: 'linear', minValue: 'auto', maxValue: 'auto', displayOnAxis: 'right' }; } }); return userOptions; }
[ "function", "(", "options", ")", "{", "var", "userOptions", "=", "options", ";", "var", "series", "=", "userOptions", ".", "series", ";", "if", "(", "!", "series", ")", "{", "return", "userOptions", ";", "}", "series", ".", "forEach", "(", "function", "(", "value", ",", "index", ")", "{", "if", "(", "Object", ".", "keys", "(", "userOptions", ".", "yScales", ")", ".", "length", "<", "2", "&&", "Object", ".", "keys", "(", "userOptions", ".", "yScales", ")", ".", "indexOf", "(", "value", ".", "yScale", ")", "===", "-", "1", "&&", "value", ".", "yScale", "===", "'secondary'", ")", "{", "userOptions", ".", "yScales", "[", "value", ".", "yScale", "]", "=", "{", "scaling", ":", "'linear'", ",", "minValue", ":", "'auto'", ",", "maxValue", ":", "'auto'", ",", "displayOnAxis", ":", "'right'", "}", ";", "}", "}", ")", ";", "return", "userOptions", ";", "}" ]
adds secondary scale if necessary
[ "adds", "secondary", "scale", "if", "necessary" ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/views/timechart.js#L433-L450
train
juttle/juttle-viz
src/views/timechart.js
function(seriesKeys) { var fieldValues = _.values(seriesKeys), matchingSeriesDef = _.find(this._attributes.series, function(seriesDef) { return _.contains(fieldValues, seriesDef.name); }); if (!matchingSeriesDef) { return _.find(this._attributes.series, function(seriesDef) { return !seriesDef.name; }); } return matchingSeriesDef; }
javascript
function(seriesKeys) { var fieldValues = _.values(seriesKeys), matchingSeriesDef = _.find(this._attributes.series, function(seriesDef) { return _.contains(fieldValues, seriesDef.name); }); if (!matchingSeriesDef) { return _.find(this._attributes.series, function(seriesDef) { return !seriesDef.name; }); } return matchingSeriesDef; }
[ "function", "(", "seriesKeys", ")", "{", "var", "fieldValues", "=", "_", ".", "values", "(", "seriesKeys", ")", ",", "matchingSeriesDef", "=", "_", ".", "find", "(", "this", ".", "_attributes", ".", "series", ",", "function", "(", "seriesDef", ")", "{", "return", "_", ".", "contains", "(", "fieldValues", ",", "seriesDef", ".", "name", ")", ";", "}", ")", ";", "if", "(", "!", "matchingSeriesDef", ")", "{", "return", "_", ".", "find", "(", "this", ".", "_attributes", ".", "series", ",", "function", "(", "seriesDef", ")", "{", "return", "!", "seriesDef", ".", "name", ";", "}", ")", ";", "}", "return", "matchingSeriesDef", ";", "}" ]
returns a series def if the series def has a name value that matches one of the series keys.
[ "returns", "a", "series", "def", "if", "the", "series", "def", "has", "a", "name", "value", "that", "matches", "one", "of", "the", "series", "keys", "." ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/views/timechart.js#L713-L724
train
juttle/juttle-viz
src/views/timechart.js
function() { this._setTimeRangeTo(this._jut_time_bounds, this._juttleNow); if (this._hasReceivedData && this.contextChart) { $(this.sinkBodyEl).append(this.contextChart.el); this.chart.toggleAnimations(false); } }
javascript
function() { this._setTimeRangeTo(this._jut_time_bounds, this._juttleNow); if (this._hasReceivedData && this.contextChart) { $(this.sinkBodyEl).append(this.contextChart.el); this.chart.toggleAnimations(false); } }
[ "function", "(", ")", "{", "this", ".", "_setTimeRangeTo", "(", "this", ".", "_jut_time_bounds", ",", "this", ".", "_juttleNow", ")", ";", "if", "(", "this", ".", "_hasReceivedData", "&&", "this", ".", "contextChart", ")", "{", "$", "(", "this", ".", "sinkBodyEl", ")", ".", "append", "(", "this", ".", "contextChart", ".", "el", ")", ";", "this", ".", "chart", ".", "toggleAnimations", "(", "false", ")", ";", "}", "}" ]
gets called when a stream finishes
[ "gets", "called", "when", "a", "stream", "finishes" ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/views/timechart.js#L1187-L1194
train
Andrinoid/showtime.js
src/showtime.js
tick
function tick() { currentTime += 1 / 60; var p = currentTime / time; var t = easingEquations[easing](p); if (p < 1) { requestAnimationFrame(tick); window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t)); } else { window.scrollTo(0, scrollTargetY); } }
javascript
function tick() { currentTime += 1 / 60; var p = currentTime / time; var t = easingEquations[easing](p); if (p < 1) { requestAnimationFrame(tick); window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t)); } else { window.scrollTo(0, scrollTargetY); } }
[ "function", "tick", "(", ")", "{", "currentTime", "+=", "1", "/", "60", ";", "var", "p", "=", "currentTime", "/", "time", ";", "var", "t", "=", "easingEquations", "[", "easing", "]", "(", "p", ")", ";", "if", "(", "p", "<", "1", ")", "{", "requestAnimationFrame", "(", "tick", ")", ";", "window", ".", "scrollTo", "(", "0", ",", "scrollY", "+", "(", "(", "scrollTargetY", "-", "scrollY", ")", "*", "t", ")", ")", ";", "}", "else", "{", "window", ".", "scrollTo", "(", "0", ",", "scrollTargetY", ")", ";", "}", "}" ]
add animation loop
[ "add", "animation", "loop" ]
992eb9ee5020807b83ac0b24c44f9c4f75b629ed
https://github.com/Andrinoid/showtime.js/blob/992eb9ee5020807b83ac0b24c44f9c4f75b629ed/src/showtime.js#L369-L381
train
hobbyquaker/obj-ease
index.js
chunk
function chunk(start, end) { // Slice, unescape and push onto result array. res.push(str.slice(start, end).replace(/\\\\/g, '\\').replace(/\\\./g, '.')); // Set starting position of next chunk. pos = end + 1; }
javascript
function chunk(start, end) { // Slice, unescape and push onto result array. res.push(str.slice(start, end).replace(/\\\\/g, '\\').replace(/\\\./g, '.')); // Set starting position of next chunk. pos = end + 1; }
[ "function", "chunk", "(", "start", ",", "end", ")", "{", "res", ".", "push", "(", "str", ".", "slice", "(", "start", ",", "end", ")", ".", "replace", "(", "/", "\\\\\\\\", "/", "g", ",", "'\\\\'", ")", ".", "\\\\", "replace", ")", ";", "(", "/", "\\\\\\.", "/", "g", ",", "'.'", ")", "}" ]
Starting position of current chunk
[ "Starting", "position", "of", "current", "chunk" ]
edfd6e4b7edb9e645912fac566ac34d31e8cd928
https://github.com/hobbyquaker/obj-ease/blob/edfd6e4b7edb9e645912fac566ac34d31e8cd928/index.js#L79-L84
train
suguru/cql-client
lib/protocol/buffer.js
Buf
function Buf(buffer) { this._initialSize = 64 * 1024; this._stepSize = this._initialSize; this._pos = 0; if (typeof buffer === 'number') { this._initialSize = buffer; } if (buffer instanceof Buffer) { this._buf = buffer; } else { this._buf = new Buffer(this._initialSize); } }
javascript
function Buf(buffer) { this._initialSize = 64 * 1024; this._stepSize = this._initialSize; this._pos = 0; if (typeof buffer === 'number') { this._initialSize = buffer; } if (buffer instanceof Buffer) { this._buf = buffer; } else { this._buf = new Buffer(this._initialSize); } }
[ "function", "Buf", "(", "buffer", ")", "{", "this", ".", "_initialSize", "=", "64", "*", "1024", ";", "this", ".", "_stepSize", "=", "this", ".", "_initialSize", ";", "this", ".", "_pos", "=", "0", ";", "if", "(", "typeof", "buffer", "===", "'number'", ")", "{", "this", ".", "_initialSize", "=", "buffer", ";", "}", "if", "(", "buffer", "instanceof", "Buffer", ")", "{", "this", ".", "_buf", "=", "buffer", ";", "}", "else", "{", "this", ".", "_buf", "=", "new", "Buffer", "(", "this", ".", "_initialSize", ")", ";", "}", "}" ]
Helper class to read and write from Buffer object. @constructor
[ "Helper", "class", "to", "read", "and", "write", "from", "Buffer", "object", "." ]
c80563526827d13505e4821f7091d4db75e556c1
https://github.com/suguru/cql-client/blob/c80563526827d13505e4821f7091d4db75e556c1/lib/protocol/buffer.js#L9-L22
train
avigoldman/fuse-email
lib/conversation.js
runTheHandler
function runTheHandler(inboundMessage) { let handler = convo.handler; convo.handler = null; let result = handler.apply(convo, [convo, inboundMessage]); if (result === IS_WAIT_FUNCTION) { // reset the handler to wait again convo.handler = handler; } // this was a real interaction so reset the timeout and wait count else { fuse.logger.verbose('Ran handler'); resetTimeout(); convo.wait_count = 0; } }
javascript
function runTheHandler(inboundMessage) { let handler = convo.handler; convo.handler = null; let result = handler.apply(convo, [convo, inboundMessage]); if (result === IS_WAIT_FUNCTION) { // reset the handler to wait again convo.handler = handler; } // this was a real interaction so reset the timeout and wait count else { fuse.logger.verbose('Ran handler'); resetTimeout(); convo.wait_count = 0; } }
[ "function", "runTheHandler", "(", "inboundMessage", ")", "{", "let", "handler", "=", "convo", ".", "handler", ";", "convo", ".", "handler", "=", "null", ";", "let", "result", "=", "handler", ".", "apply", "(", "convo", ",", "[", "convo", ",", "inboundMessage", "]", ")", ";", "if", "(", "result", "===", "IS_WAIT_FUNCTION", ")", "{", "convo", ".", "handler", "=", "handler", ";", "}", "else", "{", "fuse", ".", "logger", ".", "verbose", "(", "'Ran handler'", ")", ";", "resetTimeout", "(", ")", ";", "convo", ".", "wait_count", "=", "0", ";", "}", "}" ]
runs the handler with the inboundMessage @param {InboundMessage} inboundMessage
[ "runs", "the", "handler", "with", "the", "inboundMessage" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/conversation.js#L193-L210
train
avigoldman/fuse-email
lib/conversation.js
addInboundMessageToConvo
function addInboundMessageToConvo(inboundMessage) { if (_.last(convo.inboundMessages) !== inboundMessage) { fuse.logger.debug(`Add ${inboundMessage.id} to transcript`); convo.inboundMessages.push(inboundMessage); convo.transcript.push(inboundMessage); } }
javascript
function addInboundMessageToConvo(inboundMessage) { if (_.last(convo.inboundMessages) !== inboundMessage) { fuse.logger.debug(`Add ${inboundMessage.id} to transcript`); convo.inboundMessages.push(inboundMessage); convo.transcript.push(inboundMessage); } }
[ "function", "addInboundMessageToConvo", "(", "inboundMessage", ")", "{", "if", "(", "_", ".", "last", "(", "convo", ".", "inboundMessages", ")", "!==", "inboundMessage", ")", "{", "fuse", ".", "logger", ".", "debug", "(", "`", "${", "inboundMessage", ".", "id", "}", "`", ")", ";", "convo", ".", "inboundMessages", ".", "push", "(", "inboundMessage", ")", ";", "convo", ".", "transcript", ".", "push", "(", "inboundMessage", ")", ";", "}", "}" ]
adds new received messages to the transcript and inboundMessages list @param {InboundMessage} inboundMessage
[ "adds", "new", "received", "messages", "to", "the", "transcript", "and", "inboundMessages", "list" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/conversation.js#L226-L232
train
avigoldman/fuse-email
lib/conversation.js
resetTimeout
function resetTimeout() { clearTimeout(convo.timeout_function); convo.timeout_function = setTimeout(function() { convo.timeout(); }, convo.timeout_after); }
javascript
function resetTimeout() { clearTimeout(convo.timeout_function); convo.timeout_function = setTimeout(function() { convo.timeout(); }, convo.timeout_after); }
[ "function", "resetTimeout", "(", ")", "{", "clearTimeout", "(", "convo", ".", "timeout_function", ")", ";", "convo", ".", "timeout_function", "=", "setTimeout", "(", "function", "(", ")", "{", "convo", ".", "timeout", "(", ")", ";", "}", ",", "convo", ".", "timeout_after", ")", ";", "}" ]
starts timer for timeout from 0
[ "starts", "timer", "for", "timeout", "from", "0" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/conversation.js#L237-L243
train
jonschlinkert/expand-files
index.js
ExpandFiles
function ExpandFiles(options) { if (!(this instanceof ExpandFiles)) { return new ExpandFiles(options); } Base.call(this, {}, options); this.use(utils.plugins()); this.is('Files'); this.options = options || {}; if (util.isFiles(options) || arguments.length > 1) { this.options = {}; this.expand.apply(this, arguments); return this; } }
javascript
function ExpandFiles(options) { if (!(this instanceof ExpandFiles)) { return new ExpandFiles(options); } Base.call(this, {}, options); this.use(utils.plugins()); this.is('Files'); this.options = options || {}; if (util.isFiles(options) || arguments.length > 1) { this.options = {}; this.expand.apply(this, arguments); return this; } }
[ "function", "ExpandFiles", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "ExpandFiles", ")", ")", "{", "return", "new", "ExpandFiles", "(", "options", ")", ";", "}", "Base", ".", "call", "(", "this", ",", "{", "}", ",", "options", ")", ";", "this", ".", "use", "(", "utils", ".", "plugins", "(", ")", ")", ";", "this", ".", "is", "(", "'Files'", ")", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "if", "(", "util", ".", "isFiles", "(", "options", ")", "||", "arguments", ".", "length", ">", "1", ")", "{", "this", ".", "options", "=", "{", "}", ";", "this", ".", "expand", ".", "apply", "(", "this", ",", "arguments", ")", ";", "return", "this", ";", "}", "}" ]
Create an instance of `ExpandFiles` with `options`. ```js var config = new ExpandFiles({cwd: 'src'}); ``` @param {Object} `options` @api public
[ "Create", "an", "instance", "of", "ExpandFiles", "with", "options", "." ]
023185d6394a82738d0bec6c026f645267e0c365
https://github.com/jonschlinkert/expand-files/blob/023185d6394a82738d0bec6c026f645267e0c365/index.js#L18-L33
train
jonschlinkert/expand-files
index.js
expandMapping
function expandMapping(config, options) { var len = config.files.length, i = -1; var res = []; while (++i < len) { var raw = config.files[i]; var node = new RawNode(raw, config, this); this.emit('files', 'rawNode', node); this.emit('rawNode', node); if (node.files.length) { res.push.apply(res, node.files); } } config.files = res; return config; }
javascript
function expandMapping(config, options) { var len = config.files.length, i = -1; var res = []; while (++i < len) { var raw = config.files[i]; var node = new RawNode(raw, config, this); this.emit('files', 'rawNode', node); this.emit('rawNode', node); if (node.files.length) { res.push.apply(res, node.files); } } config.files = res; return config; }
[ "function", "expandMapping", "(", "config", ",", "options", ")", "{", "var", "len", "=", "config", ".", "files", ".", "length", ",", "i", "=", "-", "1", ";", "var", "res", "=", "[", "]", ";", "while", "(", "++", "i", "<", "len", ")", "{", "var", "raw", "=", "config", ".", "files", "[", "i", "]", ";", "var", "node", "=", "new", "RawNode", "(", "raw", ",", "config", ",", "this", ")", ";", "this", ".", "emit", "(", "'files'", ",", "'rawNode'", ",", "node", ")", ";", "this", ".", "emit", "(", "'rawNode'", ",", "node", ")", ";", "if", "(", "node", ".", "files", ".", "length", ")", "{", "res", ".", "push", ".", "apply", "(", "res", ",", "node", ".", "files", ")", ";", "}", "}", "config", ".", "files", "=", "res", ";", "return", "config", ";", "}" ]
Iterate over a files array and expand src-dest mappings ```js { files: [ { src: [ '*.js' ], dest: 'dist/' } ] } ``` @param {Object} `config` @param {Object} `options` @return {Object}
[ "Iterate", "over", "a", "files", "array", "and", "expand", "src", "-", "dest", "mappings" ]
023185d6394a82738d0bec6c026f645267e0c365
https://github.com/jonschlinkert/expand-files/blob/023185d6394a82738d0bec6c026f645267e0c365/index.js#L84-L99
train
jonschlinkert/expand-files
index.js
RawNode
function RawNode(raw, config, app) { utils.define(this, 'isRawNode', true); util.run(config, 'rawNode', raw); this.files = []; var paths = {}; raw.options = utils.extend({}, config.options, raw.options); var opts = resolvePaths(raw.options); var filter = filterFiles(opts); var srcFiles = utils.arrayify(raw.src); if (opts.glob !== false && utils.hasGlob(raw.src)) { srcFiles = utils.glob.sync(raw.src, opts); } srcFiles = srcFiles.filter(filter); if (config.options.mapDest) { var len = srcFiles.length, i = -1; while (++i < len) { var node = new FilesNode(srcFiles[i], raw, config); app.emit('files', 'filesNode', node); app.emit('filesNode', node); var dest = node.dest; if (!node.src && !node.path) { continue; } var src = resolveArray(node.src, opts); if (paths[dest]) { paths[dest].src = paths[dest].src.concat(src); } else { node.src = utils.arrayify(src); this.files.push(node); paths[dest] = node; } } if (!this.files.length) { node = raw; raw.src = []; this.files.push(raw); } } else { createNode(srcFiles, raw, this.files, config); } }
javascript
function RawNode(raw, config, app) { utils.define(this, 'isRawNode', true); util.run(config, 'rawNode', raw); this.files = []; var paths = {}; raw.options = utils.extend({}, config.options, raw.options); var opts = resolvePaths(raw.options); var filter = filterFiles(opts); var srcFiles = utils.arrayify(raw.src); if (opts.glob !== false && utils.hasGlob(raw.src)) { srcFiles = utils.glob.sync(raw.src, opts); } srcFiles = srcFiles.filter(filter); if (config.options.mapDest) { var len = srcFiles.length, i = -1; while (++i < len) { var node = new FilesNode(srcFiles[i], raw, config); app.emit('files', 'filesNode', node); app.emit('filesNode', node); var dest = node.dest; if (!node.src && !node.path) { continue; } var src = resolveArray(node.src, opts); if (paths[dest]) { paths[dest].src = paths[dest].src.concat(src); } else { node.src = utils.arrayify(src); this.files.push(node); paths[dest] = node; } } if (!this.files.length) { node = raw; raw.src = []; this.files.push(raw); } } else { createNode(srcFiles, raw, this.files, config); } }
[ "function", "RawNode", "(", "raw", ",", "config", ",", "app", ")", "{", "utils", ".", "define", "(", "this", ",", "'isRawNode'", ",", "true", ")", ";", "util", ".", "run", "(", "config", ",", "'rawNode'", ",", "raw", ")", ";", "this", ".", "files", "=", "[", "]", ";", "var", "paths", "=", "{", "}", ";", "raw", ".", "options", "=", "utils", ".", "extend", "(", "{", "}", ",", "config", ".", "options", ",", "raw", ".", "options", ")", ";", "var", "opts", "=", "resolvePaths", "(", "raw", ".", "options", ")", ";", "var", "filter", "=", "filterFiles", "(", "opts", ")", ";", "var", "srcFiles", "=", "utils", ".", "arrayify", "(", "raw", ".", "src", ")", ";", "if", "(", "opts", ".", "glob", "!==", "false", "&&", "utils", ".", "hasGlob", "(", "raw", ".", "src", ")", ")", "{", "srcFiles", "=", "utils", ".", "glob", ".", "sync", "(", "raw", ".", "src", ",", "opts", ")", ";", "}", "srcFiles", "=", "srcFiles", ".", "filter", "(", "filter", ")", ";", "if", "(", "config", ".", "options", ".", "mapDest", ")", "{", "var", "len", "=", "srcFiles", ".", "length", ",", "i", "=", "-", "1", ";", "while", "(", "++", "i", "<", "len", ")", "{", "var", "node", "=", "new", "FilesNode", "(", "srcFiles", "[", "i", "]", ",", "raw", ",", "config", ")", ";", "app", ".", "emit", "(", "'files'", ",", "'filesNode'", ",", "node", ")", ";", "app", ".", "emit", "(", "'filesNode'", ",", "node", ")", ";", "var", "dest", "=", "node", ".", "dest", ";", "if", "(", "!", "node", ".", "src", "&&", "!", "node", ".", "path", ")", "{", "continue", ";", "}", "var", "src", "=", "resolveArray", "(", "node", ".", "src", ",", "opts", ")", ";", "if", "(", "paths", "[", "dest", "]", ")", "{", "paths", "[", "dest", "]", ".", "src", "=", "paths", "[", "dest", "]", ".", "src", ".", "concat", "(", "src", ")", ";", "}", "else", "{", "node", ".", "src", "=", "utils", ".", "arrayify", "(", "src", ")", ";", "this", ".", "files", ".", "push", "(", "node", ")", ";", "paths", "[", "dest", "]", "=", "node", ";", "}", "}", "if", "(", "!", "this", ".", "files", ".", "length", ")", "{", "node", "=", "raw", ";", "raw", ".", "src", "=", "[", "]", ";", "this", ".", "files", ".", "push", "(", "raw", ")", ";", "}", "}", "else", "{", "createNode", "(", "srcFiles", ",", "raw", ",", "this", ".", "files", ",", "config", ")", ";", "}", "}" ]
Create a `raw` node. A node represents a single element in a `files` array, and "raw" means that `src` glob patterns have not been expanded. @param {Object} `raw` @param {Object} `config` @return {Object}
[ "Create", "a", "raw", "node", ".", "A", "node", "represents", "a", "single", "element", "in", "a", "files", "array", "and", "raw", "means", "that", "src", "glob", "patterns", "have", "not", "been", "expanded", "." ]
023185d6394a82738d0bec6c026f645267e0c365
https://github.com/jonschlinkert/expand-files/blob/023185d6394a82738d0bec6c026f645267e0c365/index.js#L111-L159
train
jonschlinkert/expand-files
index.js
FilesNode
function FilesNode(src, raw, config) { utils.define(this, 'isFilesNode', true); this.options = utils.omit(raw.options, ['mapDest', 'flatten', 'rename', 'filter']); this.src = utils.arrayify(src); if (this.options.resolve) { var cwd = path.resolve(this.options.cwd || process.cwd()); this.src = this.src.map(function(fp) { return path.resolve(cwd, fp); }); } if (raw.options.mapDest) { this.dest = mapDest(raw.dest, src, raw); } else { this.dest = rewriteDest(raw.dest, src, raw.options); } // copy properties to the new node for (var key in raw) { if (key !== 'src' && key !== 'dest' && key !== 'options') { this[key] = raw[key]; } } util.run(config, 'filesNode', this); }
javascript
function FilesNode(src, raw, config) { utils.define(this, 'isFilesNode', true); this.options = utils.omit(raw.options, ['mapDest', 'flatten', 'rename', 'filter']); this.src = utils.arrayify(src); if (this.options.resolve) { var cwd = path.resolve(this.options.cwd || process.cwd()); this.src = this.src.map(function(fp) { return path.resolve(cwd, fp); }); } if (raw.options.mapDest) { this.dest = mapDest(raw.dest, src, raw); } else { this.dest = rewriteDest(raw.dest, src, raw.options); } // copy properties to the new node for (var key in raw) { if (key !== 'src' && key !== 'dest' && key !== 'options') { this[key] = raw[key]; } } util.run(config, 'filesNode', this); }
[ "function", "FilesNode", "(", "src", ",", "raw", ",", "config", ")", "{", "utils", ".", "define", "(", "this", ",", "'isFilesNode'", ",", "true", ")", ";", "this", ".", "options", "=", "utils", ".", "omit", "(", "raw", ".", "options", ",", "[", "'mapDest'", ",", "'flatten'", ",", "'rename'", ",", "'filter'", "]", ")", ";", "this", ".", "src", "=", "utils", ".", "arrayify", "(", "src", ")", ";", "if", "(", "this", ".", "options", ".", "resolve", ")", "{", "var", "cwd", "=", "path", ".", "resolve", "(", "this", ".", "options", ".", "cwd", "||", "process", ".", "cwd", "(", ")", ")", ";", "this", ".", "src", "=", "this", ".", "src", ".", "map", "(", "function", "(", "fp", ")", "{", "return", "path", ".", "resolve", "(", "cwd", ",", "fp", ")", ";", "}", ")", ";", "}", "if", "(", "raw", ".", "options", ".", "mapDest", ")", "{", "this", ".", "dest", "=", "mapDest", "(", "raw", ".", "dest", ",", "src", ",", "raw", ")", ";", "}", "else", "{", "this", ".", "dest", "=", "rewriteDest", "(", "raw", ".", "dest", ",", "src", ",", "raw", ".", "options", ")", ";", "}", "for", "(", "var", "key", "in", "raw", ")", "{", "if", "(", "key", "!==", "'src'", "&&", "key", "!==", "'dest'", "&&", "key", "!==", "'options'", ")", "{", "this", "[", "key", "]", "=", "raw", "[", "key", "]", ";", "}", "}", "util", ".", "run", "(", "config", ",", "'filesNode'", ",", "this", ")", ";", "}" ]
Create a new `Node` with the given `src`, `raw` node and `config` object. @param {String|Array} `src` Glob patterns @param {Object} `raw` FilesNode with un-expanded glob patterns. @param {Object} `config` @return {Object}
[ "Create", "a", "new", "Node", "with", "the", "given", "src", "raw", "node", "and", "config", "object", "." ]
023185d6394a82738d0bec6c026f645267e0c365
https://github.com/jonschlinkert/expand-files/blob/023185d6394a82738d0bec6c026f645267e0c365/index.js#L171-L196
train
jonschlinkert/expand-files
index.js
rewriteDest
function rewriteDest(dest, src, opts) { dest = utils.resolve(dest); if (opts.destBase) { dest = path.join(opts.destBase, dest); } if (opts.extDot || opts.hasOwnProperty('ext')) { dest = rewriteExt(dest, opts); } if (typeof opts.rename === 'function') { return opts.rename(dest, src, opts); } return dest; }
javascript
function rewriteDest(dest, src, opts) { dest = utils.resolve(dest); if (opts.destBase) { dest = path.join(opts.destBase, dest); } if (opts.extDot || opts.hasOwnProperty('ext')) { dest = rewriteExt(dest, opts); } if (typeof opts.rename === 'function') { return opts.rename(dest, src, opts); } return dest; }
[ "function", "rewriteDest", "(", "dest", ",", "src", ",", "opts", ")", "{", "dest", "=", "utils", ".", "resolve", "(", "dest", ")", ";", "if", "(", "opts", ".", "destBase", ")", "{", "dest", "=", "path", ".", "join", "(", "opts", ".", "destBase", ",", "dest", ")", ";", "}", "if", "(", "opts", ".", "extDot", "||", "opts", ".", "hasOwnProperty", "(", "'ext'", ")", ")", "{", "dest", "=", "rewriteExt", "(", "dest", ",", "opts", ")", ";", "}", "if", "(", "typeof", "opts", ".", "rename", "===", "'function'", ")", "{", "return", "opts", ".", "rename", "(", "dest", ",", "src", ",", "opts", ")", ";", "}", "return", "dest", ";", "}" ]
Used when `mapDest` is not true
[ "Used", "when", "mapDest", "is", "not", "true" ]
023185d6394a82738d0bec6c026f645267e0c365
https://github.com/jonschlinkert/expand-files/blob/023185d6394a82738d0bec6c026f645267e0c365/index.js#L254-L266
train
vulcan-estudios/vulcanval
bundle/js/convertMapTo.js
toNested
function toNested(map) { var split, first, last; utils.walkObject(map, function (val, prop1) { split = prop1.split('.'); if (!utils.validateFieldName(prop1)) { log.error('map field name "' + prop1 + '" is invalid'); } last = split[split.length - 1]; first = prop1.replace('.' + last, ''); utils.walkObject(map, function (val2, prop2) { if (prop1 !== prop2 && first === prop2) { log.error('map field name "' + prop2 + '" is invalid'); } }); }); var form = {}; var names = []; utils.walkObject(map, function (val, prop) { names.push({ keys: prop.split('.'), value: val }); }); var obj; names.forEach(function (name) { obj = form; name.keys.forEach(function (key, index) { if (index === name.keys.length - 1) { obj[key] = name.value; } else { if (!obj[key]) { obj[key] = {}; } obj = obj[key]; } }); }); return form; }
javascript
function toNested(map) { var split, first, last; utils.walkObject(map, function (val, prop1) { split = prop1.split('.'); if (!utils.validateFieldName(prop1)) { log.error('map field name "' + prop1 + '" is invalid'); } last = split[split.length - 1]; first = prop1.replace('.' + last, ''); utils.walkObject(map, function (val2, prop2) { if (prop1 !== prop2 && first === prop2) { log.error('map field name "' + prop2 + '" is invalid'); } }); }); var form = {}; var names = []; utils.walkObject(map, function (val, prop) { names.push({ keys: prop.split('.'), value: val }); }); var obj; names.forEach(function (name) { obj = form; name.keys.forEach(function (key, index) { if (index === name.keys.length - 1) { obj[key] = name.value; } else { if (!obj[key]) { obj[key] = {}; } obj = obj[key]; } }); }); return form; }
[ "function", "toNested", "(", "map", ")", "{", "var", "split", ",", "first", ",", "last", ";", "utils", ".", "walkObject", "(", "map", ",", "function", "(", "val", ",", "prop1", ")", "{", "split", "=", "prop1", ".", "split", "(", "'.'", ")", ";", "if", "(", "!", "utils", ".", "validateFieldName", "(", "prop1", ")", ")", "{", "log", ".", "error", "(", "'map field name \"'", "+", "prop1", "+", "'\" is invalid'", ")", ";", "}", "last", "=", "split", "[", "split", ".", "length", "-", "1", "]", ";", "first", "=", "prop1", ".", "replace", "(", "'.'", "+", "last", ",", "''", ")", ";", "utils", ".", "walkObject", "(", "map", ",", "function", "(", "val2", ",", "prop2", ")", "{", "if", "(", "prop1", "!==", "prop2", "&&", "first", "===", "prop2", ")", "{", "log", ".", "error", "(", "'map field name \"'", "+", "prop2", "+", "'\" is invalid'", ")", ";", "}", "}", ")", ";", "}", ")", ";", "var", "form", "=", "{", "}", ";", "var", "names", "=", "[", "]", ";", "utils", ".", "walkObject", "(", "map", ",", "function", "(", "val", ",", "prop", ")", "{", "names", ".", "push", "(", "{", "keys", ":", "prop", ".", "split", "(", "'.'", ")", ",", "value", ":", "val", "}", ")", ";", "}", ")", ";", "var", "obj", ";", "names", ".", "forEach", "(", "function", "(", "name", ")", "{", "obj", "=", "form", ";", "name", ".", "keys", ".", "forEach", "(", "function", "(", "key", ",", "index", ")", "{", "if", "(", "index", "===", "name", ".", "keys", ".", "length", "-", "1", ")", "{", "obj", "[", "key", "]", "=", "name", ".", "value", ";", "}", "else", "{", "if", "(", "!", "obj", "[", "key", "]", ")", "{", "obj", "[", "key", "]", "=", "{", "}", ";", "}", "obj", "=", "obj", "[", "key", "]", ";", "}", "}", ")", ";", "}", ")", ";", "return", "form", ";", "}" ]
Plain to nested.
[ "Plain", "to", "nested", "." ]
b8478debdbdea7f3645f10a57564fbf2cda639c7
https://github.com/vulcan-estudios/vulcanval/blob/b8478debdbdea7f3645f10a57564fbf2cda639c7/bundle/js/convertMapTo.js#L9-L53
train
vulcan-estudios/vulcanval
bundle/js/convertMapTo.js
toPlain
function toPlain(map) { var split; var form = {}; var throwErr = function throwErr(key) { return log.error('map field name "' + key + '" is invalid'); }; var isInvalidKey = function isInvalidKey(str) { return str.split('.').length > 1; }; var run = function run(n, o, p) { if (o.hasOwnProperty(p)) { n += '.' + p; if (typeof o[p] === 'string' || typeof o[p] === 'number' || typeof o[p] === 'boolean' || o[p] === undefined || o[p] === null) { n = n.substring(1); form[n] = o[p]; } else { for (var k in o[p]) { if (isInvalidKey(k)) throwErr(k); run(n, o[p], k); } } } }; for (var p in map) { if (isInvalidKey(p)) throwErr(p); run('', map, p); } return form; }
javascript
function toPlain(map) { var split; var form = {}; var throwErr = function throwErr(key) { return log.error('map field name "' + key + '" is invalid'); }; var isInvalidKey = function isInvalidKey(str) { return str.split('.').length > 1; }; var run = function run(n, o, p) { if (o.hasOwnProperty(p)) { n += '.' + p; if (typeof o[p] === 'string' || typeof o[p] === 'number' || typeof o[p] === 'boolean' || o[p] === undefined || o[p] === null) { n = n.substring(1); form[n] = o[p]; } else { for (var k in o[p]) { if (isInvalidKey(k)) throwErr(k); run(n, o[p], k); } } } }; for (var p in map) { if (isInvalidKey(p)) throwErr(p); run('', map, p); } return form; }
[ "function", "toPlain", "(", "map", ")", "{", "var", "split", ";", "var", "form", "=", "{", "}", ";", "var", "throwErr", "=", "function", "throwErr", "(", "key", ")", "{", "return", "log", ".", "error", "(", "'map field name \"'", "+", "key", "+", "'\" is invalid'", ")", ";", "}", ";", "var", "isInvalidKey", "=", "function", "isInvalidKey", "(", "str", ")", "{", "return", "str", ".", "split", "(", "'.'", ")", ".", "length", ">", "1", ";", "}", ";", "var", "run", "=", "function", "run", "(", "n", ",", "o", ",", "p", ")", "{", "if", "(", "o", ".", "hasOwnProperty", "(", "p", ")", ")", "{", "n", "+=", "'.'", "+", "p", ";", "if", "(", "typeof", "o", "[", "p", "]", "===", "'string'", "||", "typeof", "o", "[", "p", "]", "===", "'number'", "||", "typeof", "o", "[", "p", "]", "===", "'boolean'", "||", "o", "[", "p", "]", "===", "undefined", "||", "o", "[", "p", "]", "===", "null", ")", "{", "n", "=", "n", ".", "substring", "(", "1", ")", ";", "form", "[", "n", "]", "=", "o", "[", "p", "]", ";", "}", "else", "{", "for", "(", "var", "k", "in", "o", "[", "p", "]", ")", "{", "if", "(", "isInvalidKey", "(", "k", ")", ")", "throwErr", "(", "k", ")", ";", "run", "(", "n", ",", "o", "[", "p", "]", ",", "k", ")", ";", "}", "}", "}", "}", ";", "for", "(", "var", "p", "in", "map", ")", "{", "if", "(", "isInvalidKey", "(", "p", ")", ")", "throwErr", "(", "p", ")", ";", "run", "(", "''", ",", "map", ",", "p", ")", ";", "}", "return", "form", ";", "}" ]
Nested to plain.
[ "Nested", "to", "plain", "." ]
b8478debdbdea7f3645f10a57564fbf2cda639c7
https://github.com/vulcan-estudios/vulcanval/blob/b8478debdbdea7f3645f10a57564fbf2cda639c7/bundle/js/convertMapTo.js#L56-L88
train
Andreyco/react-native-conditional-stylesheet
module.js
iterateStyleRules
function iterateStyleRules(argument) { if (typeof argument === 'string') { checkStyleExistence(styleDefinitions, argument); collectedStyles.push(styleDefinitions[argument]); return; } if (typeof argument === 'object') { Object.keys(argument).forEach(function(styleName) { checkStyleExistence(styleDefinitions, styleName); if (argument[styleName]) { collectedStyles.push(styleDefinitions[styleName]) } }) } }
javascript
function iterateStyleRules(argument) { if (typeof argument === 'string') { checkStyleExistence(styleDefinitions, argument); collectedStyles.push(styleDefinitions[argument]); return; } if (typeof argument === 'object') { Object.keys(argument).forEach(function(styleName) { checkStyleExistence(styleDefinitions, styleName); if (argument[styleName]) { collectedStyles.push(styleDefinitions[styleName]) } }) } }
[ "function", "iterateStyleRules", "(", "argument", ")", "{", "if", "(", "typeof", "argument", "===", "'string'", ")", "{", "checkStyleExistence", "(", "styleDefinitions", ",", "argument", ")", ";", "collectedStyles", ".", "push", "(", "styleDefinitions", "[", "argument", "]", ")", ";", "return", ";", "}", "if", "(", "typeof", "argument", "===", "'object'", ")", "{", "Object", ".", "keys", "(", "argument", ")", ".", "forEach", "(", "function", "(", "styleName", ")", "{", "checkStyleExistence", "(", "styleDefinitions", ",", "styleName", ")", ";", "if", "(", "argument", "[", "styleName", "]", ")", "{", "collectedStyles", ".", "push", "(", "styleDefinitions", "[", "styleName", "]", ")", "}", "}", ")", "}", "}" ]
Iterate passed style rules and build style collection based on it.
[ "Iterate", "passed", "style", "rules", "and", "build", "style", "collection", "based", "on", "it", "." ]
d6a76c299972a5a84e1a137ee539c5f3fcad1da4
https://github.com/Andreyco/react-native-conditional-stylesheet/blob/d6a76c299972a5a84e1a137ee539c5f3fcad1da4/module.js#L18-L35
train
suguru/cql-client
lib/protocol/protocol.js
NativeProtocol
function NativeProtocol(protocolVersion) { var _protocolVersion = protocolVersion || DEFAULT_PROTOCOL_VERSION; if (!(this instanceof NativeProtocol)) return new NativeProtocol(); stream.Duplex.call(this); Object.defineProperties(this, { 'protocolVersion': { set: function(val) { if (typeof val !== 'number' || val < 1 || val > DEFAULT_PROTOCOL_VERSION) { throw new Error('Invalid protocol version is set: ' + val); } _protocolVersion = val; }, get: function() { return _protocolVersion; } } }); this._messageQueue = []; this._readBuf = new Buffer(8); // for header this.lastRead = 0; }
javascript
function NativeProtocol(protocolVersion) { var _protocolVersion = protocolVersion || DEFAULT_PROTOCOL_VERSION; if (!(this instanceof NativeProtocol)) return new NativeProtocol(); stream.Duplex.call(this); Object.defineProperties(this, { 'protocolVersion': { set: function(val) { if (typeof val !== 'number' || val < 1 || val > DEFAULT_PROTOCOL_VERSION) { throw new Error('Invalid protocol version is set: ' + val); } _protocolVersion = val; }, get: function() { return _protocolVersion; } } }); this._messageQueue = []; this._readBuf = new Buffer(8); // for header this.lastRead = 0; }
[ "function", "NativeProtocol", "(", "protocolVersion", ")", "{", "var", "_protocolVersion", "=", "protocolVersion", "||", "DEFAULT_PROTOCOL_VERSION", ";", "if", "(", "!", "(", "this", "instanceof", "NativeProtocol", ")", ")", "return", "new", "NativeProtocol", "(", ")", ";", "stream", ".", "Duplex", ".", "call", "(", "this", ")", ";", "Object", ".", "defineProperties", "(", "this", ",", "{", "'protocolVersion'", ":", "{", "set", ":", "function", "(", "val", ")", "{", "if", "(", "typeof", "val", "!==", "'number'", "||", "val", "<", "1", "||", "val", ">", "DEFAULT_PROTOCOL_VERSION", ")", "{", "throw", "new", "Error", "(", "'Invalid protocol version is set: '", "+", "val", ")", ";", "}", "_protocolVersion", "=", "val", ";", "}", ",", "get", ":", "function", "(", ")", "{", "return", "_protocolVersion", ";", "}", "}", "}", ")", ";", "this", ".", "_messageQueue", "=", "[", "]", ";", "this", ".", "_readBuf", "=", "new", "Buffer", "(", "8", ")", ";", "this", ".", "lastRead", "=", "0", ";", "}" ]
NativeProtocol class. Protocol is implemented as node.js' stream.Duplex, so piping with socket like: <code> var conn = net.connect(..); conn.pipe(protocol).pipe(conn); </code> to hook up to network connection. @constructor @param {object} options - options to configure protocol
[ "NativeProtocol", "class", "." ]
c80563526827d13505e4821f7091d4db75e556c1
https://github.com/suguru/cql-client/blob/c80563526827d13505e4821f7091d4db75e556c1/lib/protocol/protocol.js#L41-L64
train
suguru/cql-client
lib/protocol/protocol.js
ErrorMessage
function ErrorMessage(errorCode, errorMessage, details) { Response.call(this, 0x00); Object.defineProperties(this, { 'errorCode': { value: errorCode || 0, enumerable: true }, 'errorMessage': { value: errorMessage || '', enumerable: true }, 'details': { value: details || {}, enumerable: true } }); }
javascript
function ErrorMessage(errorCode, errorMessage, details) { Response.call(this, 0x00); Object.defineProperties(this, { 'errorCode': { value: errorCode || 0, enumerable: true }, 'errorMessage': { value: errorMessage || '', enumerable: true }, 'details': { value: details || {}, enumerable: true } }); }
[ "function", "ErrorMessage", "(", "errorCode", ",", "errorMessage", ",", "details", ")", "{", "Response", ".", "call", "(", "this", ",", "0x00", ")", ";", "Object", ".", "defineProperties", "(", "this", ",", "{", "'errorCode'", ":", "{", "value", ":", "errorCode", "||", "0", ",", "enumerable", ":", "true", "}", ",", "'errorMessage'", ":", "{", "value", ":", "errorMessage", "||", "''", ",", "enumerable", ":", "true", "}", ",", "'details'", ":", "{", "value", ":", "details", "||", "{", "}", ",", "enumerable", ":", "true", "}", "}", ")", ";", "}" ]
ERROR message. @constructor
[ "ERROR", "message", "." ]
c80563526827d13505e4821f7091d4db75e556c1
https://github.com/suguru/cql-client/blob/c80563526827d13505e4821f7091d4db75e556c1/lib/protocol/protocol.js#L314-L331
train
suguru/cql-client
lib/protocol/protocol.js
AuthChallengeMessage
function AuthChallengeMessage(token) { var _token = token || new Buffer(0); Response.call(this, 0x0E); Object.defineProperty(this, 'token', { set: function(val) { _token = val; }, get: function() { return _token; } }); }
javascript
function AuthChallengeMessage(token) { var _token = token || new Buffer(0); Response.call(this, 0x0E); Object.defineProperty(this, 'token', { set: function(val) { _token = val; }, get: function() { return _token; } }); }
[ "function", "AuthChallengeMessage", "(", "token", ")", "{", "var", "_token", "=", "token", "||", "new", "Buffer", "(", "0", ")", ";", "Response", ".", "call", "(", "this", ",", "0x0E", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'token'", ",", "{", "set", ":", "function", "(", "val", ")", "{", "_token", "=", "val", ";", "}", ",", "get", ":", "function", "(", ")", "{", "return", "_token", ";", "}", "}", ")", ";", "}" ]
AUTH_CHALLENGE message. @constructor @since protocol version 2
[ "AUTH_CHALLENGE", "message", "." ]
c80563526827d13505e4821f7091d4db75e556c1
https://github.com/suguru/cql-client/blob/c80563526827d13505e4821f7091d4db75e556c1/lib/protocol/protocol.js#L943-L952
train
logikum/md-site-engine
source/index.js
Engine
function Engine() { // The content manager object. var contents = null; /** * Gets the configuration object. * @param {string} configPath - The path of the configuration JSON file. * @returns {Configuration} The configuration object. */ this.getConfiguration = function( configPath ) { logger.showInfo( '>>> Getting configuration: %s', configPath ); var data = require( path.join( process.cwd(), configPath ) ); var config = new Configuration( data ); Object.freeze( config ); logger.showInfo( '>>> Configuration is ready: %j', config ); return config; }; /** * Sets up the content manager object. * @param {Configuration} config - The configuration object. */ this.getContents = function( config ) { logger.showInfo( '>>> Getting contents...' ); contents = new ContentManager( config ); logger.showInfo( '>>> Contents are ready.' ); }; /** * Sets all routes used by te application. * @param {Express.Application} app - The express.js application. * @param {object} actions - An object containing the URLs and paths of the actions. * @param {string} mode - The current Node.js environment. */ this.setRoutes = function( app, actions, mode ) { logger.showInfo( '>>> Setting routes...' ); // Set engine middlewares. contents.setMiddlewares( app ); // Set action routes. contents.setActions( app, actions || { } ); // Set engine routes. contents.setRoutes( app, mode === 'development' ); logger.showInfo( '>>> Routes are ready.' ); }; }
javascript
function Engine() { // The content manager object. var contents = null; /** * Gets the configuration object. * @param {string} configPath - The path of the configuration JSON file. * @returns {Configuration} The configuration object. */ this.getConfiguration = function( configPath ) { logger.showInfo( '>>> Getting configuration: %s', configPath ); var data = require( path.join( process.cwd(), configPath ) ); var config = new Configuration( data ); Object.freeze( config ); logger.showInfo( '>>> Configuration is ready: %j', config ); return config; }; /** * Sets up the content manager object. * @param {Configuration} config - The configuration object. */ this.getContents = function( config ) { logger.showInfo( '>>> Getting contents...' ); contents = new ContentManager( config ); logger.showInfo( '>>> Contents are ready.' ); }; /** * Sets all routes used by te application. * @param {Express.Application} app - The express.js application. * @param {object} actions - An object containing the URLs and paths of the actions. * @param {string} mode - The current Node.js environment. */ this.setRoutes = function( app, actions, mode ) { logger.showInfo( '>>> Setting routes...' ); // Set engine middlewares. contents.setMiddlewares( app ); // Set action routes. contents.setActions( app, actions || { } ); // Set engine routes. contents.setRoutes( app, mode === 'development' ); logger.showInfo( '>>> Routes are ready.' ); }; }
[ "function", "Engine", "(", ")", "{", "var", "contents", "=", "null", ";", "this", ".", "getConfiguration", "=", "function", "(", "configPath", ")", "{", "logger", ".", "showInfo", "(", "'>>> Getting configuration: %s'", ",", "configPath", ")", ";", "var", "data", "=", "require", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "configPath", ")", ")", ";", "var", "config", "=", "new", "Configuration", "(", "data", ")", ";", "Object", ".", "freeze", "(", "config", ")", ";", "logger", ".", "showInfo", "(", "'>>> Configuration is ready: %j'", ",", "config", ")", ";", "return", "config", ";", "}", ";", "this", ".", "getContents", "=", "function", "(", "config", ")", "{", "logger", ".", "showInfo", "(", "'>>> Getting contents...'", ")", ";", "contents", "=", "new", "ContentManager", "(", "config", ")", ";", "logger", ".", "showInfo", "(", "'>>> Contents are ready.'", ")", ";", "}", ";", "this", ".", "setRoutes", "=", "function", "(", "app", ",", "actions", ",", "mode", ")", "{", "logger", ".", "showInfo", "(", "'>>> Setting routes...'", ")", ";", "contents", ".", "setMiddlewares", "(", "app", ")", ";", "contents", ".", "setActions", "(", "app", ",", "actions", "||", "{", "}", ")", ";", "contents", ".", "setRoutes", "(", "app", ",", "mode", "===", "'development'", ")", ";", "logger", ".", "showInfo", "(", "'>>> Routes are ready.'", ")", ";", "}", ";", "}" ]
Represents the markdown site engine. @constructor
[ "Represents", "the", "markdown", "site", "engine", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/index.js#L15-L67
train
gyselroth/balloon-node-sync
lib/delta/local-delta.js
createNode
function createNode(name, parent, stat, parentNodeId, callback) { if(utility.hasInvalidChars(name)) { logger.info('Ignoring file \'' + name + '\' because filename contains invalid chars'); return callback(undefined); } var newNode = { directory: stat.isDirectory(), name: name, parent: parent, localActions: {create: {immediate: false, actionInitialized: new Date()}}, localParent: parentNodeId, ino: stat.ino } syncDb.create(newNode, (err, createdNode) => { callback(createdNode._id, undefined); }); }
javascript
function createNode(name, parent, stat, parentNodeId, callback) { if(utility.hasInvalidChars(name)) { logger.info('Ignoring file \'' + name + '\' because filename contains invalid chars'); return callback(undefined); } var newNode = { directory: stat.isDirectory(), name: name, parent: parent, localActions: {create: {immediate: false, actionInitialized: new Date()}}, localParent: parentNodeId, ino: stat.ino } syncDb.create(newNode, (err, createdNode) => { callback(createdNode._id, undefined); }); }
[ "function", "createNode", "(", "name", ",", "parent", ",", "stat", ",", "parentNodeId", ",", "callback", ")", "{", "if", "(", "utility", ".", "hasInvalidChars", "(", "name", ")", ")", "{", "logger", ".", "info", "(", "'Ignoring file \\''", "+", "\\'", "+", "name", ")", ";", "'\\' because filename contains invalid chars'", "}", "\\'", "return", "callback", "(", "undefined", ")", ";", "}" ]
Creates a node in the database @param {string} name - name of the node @param {string} parent - parent path of the node @param {Object} stat - fs.lstat result for the node @param {string} parentNodeId - local parent id @param {Function} callback - callback function @returns {void} - no return value
[ "Creates", "a", "node", "in", "the", "database" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/local-delta.js#L20-L38
train
gyselroth/balloon-node-sync
lib/delta/local-delta.js
deleteNode
function deleteNode(node, immediate, callback) { node.localActions = {delete: { remoteId: node.remoteId, actionInitialized: new Date(), immediate }}; syncDb.update(node._id, node, callback); }
javascript
function deleteNode(node, immediate, callback) { node.localActions = {delete: { remoteId: node.remoteId, actionInitialized: new Date(), immediate }}; syncDb.update(node._id, node, callback); }
[ "function", "deleteNode", "(", "node", ",", "immediate", ",", "callback", ")", "{", "node", ".", "localActions", "=", "{", "delete", ":", "{", "remoteId", ":", "node", ".", "remoteId", ",", "actionInitialized", ":", "new", "Date", "(", ")", ",", "immediate", "}", "}", ";", "syncDb", ".", "update", "(", "node", ".", "_id", ",", "node", ",", "callback", ")", ";", "}" ]
Sets the local action to delete for a given node @param {Object} node - node from database @param {Function} callback - callback function @returns {void} - no return value
[ "Sets", "the", "local", "action", "to", "delete", "for", "a", "given", "node" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/local-delta.js#L47-L55
train
gyselroth/balloon-node-sync
lib/delta/local-delta.js
function(dirPath, callback) { logger.info('getDelta start', {category: 'sync-local-delta'}); async.series([ (cb) => { logger.debug('findDeletedNodes start', {category: 'sync-local-delta'}); this.findDeletedNodes(cb) }, (cb) => { logger.debug('findChanges start', {category: 'sync-local-delta'}); this.findChanges(dirPath, undefined, null, cb); }, (cb) => { logger.debug('resolveConflicts start', {category: 'sync-local-delta'}); this.resolveConflicts(cb); } ], (err, resuls) => { logger.info('getDelta end', {category: 'sync-local-delta'}); return callback(null); }); }
javascript
function(dirPath, callback) { logger.info('getDelta start', {category: 'sync-local-delta'}); async.series([ (cb) => { logger.debug('findDeletedNodes start', {category: 'sync-local-delta'}); this.findDeletedNodes(cb) }, (cb) => { logger.debug('findChanges start', {category: 'sync-local-delta'}); this.findChanges(dirPath, undefined, null, cb); }, (cb) => { logger.debug('resolveConflicts start', {category: 'sync-local-delta'}); this.resolveConflicts(cb); } ], (err, resuls) => { logger.info('getDelta end', {category: 'sync-local-delta'}); return callback(null); }); }
[ "function", "(", "dirPath", ",", "callback", ")", "{", "logger", ".", "info", "(", "'getDelta start'", ",", "{", "category", ":", "'sync-local-delta'", "}", ")", ";", "async", ".", "series", "(", "[", "(", "cb", ")", "=>", "{", "logger", ".", "debug", "(", "'findDeletedNodes start'", ",", "{", "category", ":", "'sync-local-delta'", "}", ")", ";", "this", ".", "findDeletedNodes", "(", "cb", ")", "}", ",", "(", "cb", ")", "=>", "{", "logger", ".", "debug", "(", "'findChanges start'", ",", "{", "category", ":", "'sync-local-delta'", "}", ")", ";", "this", ".", "findChanges", "(", "dirPath", ",", "undefined", ",", "null", ",", "cb", ")", ";", "}", ",", "(", "cb", ")", "=>", "{", "logger", ".", "debug", "(", "'resolveConflicts start'", ",", "{", "category", ":", "'sync-local-delta'", "}", ")", ";", "this", ".", "resolveConflicts", "(", "cb", ")", ";", "}", "]", ",", "(", "err", ",", "resuls", ")", "=>", "{", "logger", ".", "info", "(", "'getDelta end'", ",", "{", "category", ":", "'sync-local-delta'", "}", ")", ";", "return", "callback", "(", "null", ")", ";", "}", ")", ";", "}" ]
Scans the given directory for new, changed and deleted nodes. Sets the necessary localActions in the database. @param {string} dirPath - root directory to get delta for @param {Function} callback - callback function @returns {void} - no return value
[ "Scans", "the", "given", "directory", "for", "new", "changed", "and", "deleted", "nodes", ".", "Sets", "the", "necessary", "localActions", "in", "the", "database", "." ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/local-delta.js#L66-L90
train
gyselroth/balloon-node-sync
lib/delta/local-delta.js
function(dirPath, oldDirPath, parentNodeId, callback) { fsWrap.readdir(dirPath, (err, nodes) => { //if it is not possible to read dir abort sync if(err) { logger.warning('Error while reading dir', {category: 'sync-local-delta', dirPath, err}); throw new BlnDeltaError(err.message); } async.eachSeries(nodes, (node, cb) => { var nodePath = utility.joinPath(dirPath, node); try { var stat = fsWrap.lstatSync(nodePath); } catch(e) { logger.warning('findChanges got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code}); throw new BlnDeltaError(e.message); } if(utility.isExcludeFile(node)) { logger.info('LOCAL DELTA: ignoring file \'' + nodePath + '\' matching exclude pattern'); return cb(null); } if(utility.hasInvalidChars(node)) { logger.info('LOCAL DELTA: ignoring file \'' + name + '\' because filename contains invalid chars'); return cb(undefined); } if(stat.isSymbolicLink()) { logger.info('LOCAL DELTA: ignoring symlink \'' + nodePath + '\''); return cb(null); } syncDb.findByIno(stat.ino, (err, syncedNode) => { if(stat.isDirectory()) { let query = {path: nodePath}; if(syncedNode && syncedNode.remoteId) { query.remoteId = syncedNode.remoteId; } ignoreDb.isIgnoredNode(query, (err, isIgnored) => { if(err) return cb(err); if(isIgnored) { logger.info('ignoring directory \'' + nodePath + '\' because it is ignored by ignoredNodes', {category: 'sync-local-delta'}); return cb(null); } this.analyzeNodeForChanges(node, dirPath, oldDirPath, parentNodeId, stat, syncedNode, cb); }); } else { this.analyzeNodeForChanges(node, dirPath, oldDirPath, parentNodeId, stat, syncedNode, cb); } }); }, callback); }); }
javascript
function(dirPath, oldDirPath, parentNodeId, callback) { fsWrap.readdir(dirPath, (err, nodes) => { //if it is not possible to read dir abort sync if(err) { logger.warning('Error while reading dir', {category: 'sync-local-delta', dirPath, err}); throw new BlnDeltaError(err.message); } async.eachSeries(nodes, (node, cb) => { var nodePath = utility.joinPath(dirPath, node); try { var stat = fsWrap.lstatSync(nodePath); } catch(e) { logger.warning('findChanges got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code}); throw new BlnDeltaError(e.message); } if(utility.isExcludeFile(node)) { logger.info('LOCAL DELTA: ignoring file \'' + nodePath + '\' matching exclude pattern'); return cb(null); } if(utility.hasInvalidChars(node)) { logger.info('LOCAL DELTA: ignoring file \'' + name + '\' because filename contains invalid chars'); return cb(undefined); } if(stat.isSymbolicLink()) { logger.info('LOCAL DELTA: ignoring symlink \'' + nodePath + '\''); return cb(null); } syncDb.findByIno(stat.ino, (err, syncedNode) => { if(stat.isDirectory()) { let query = {path: nodePath}; if(syncedNode && syncedNode.remoteId) { query.remoteId = syncedNode.remoteId; } ignoreDb.isIgnoredNode(query, (err, isIgnored) => { if(err) return cb(err); if(isIgnored) { logger.info('ignoring directory \'' + nodePath + '\' because it is ignored by ignoredNodes', {category: 'sync-local-delta'}); return cb(null); } this.analyzeNodeForChanges(node, dirPath, oldDirPath, parentNodeId, stat, syncedNode, cb); }); } else { this.analyzeNodeForChanges(node, dirPath, oldDirPath, parentNodeId, stat, syncedNode, cb); } }); }, callback); }); }
[ "function", "(", "dirPath", ",", "oldDirPath", ",", "parentNodeId", ",", "callback", ")", "{", "fsWrap", ".", "readdir", "(", "dirPath", ",", "(", "err", ",", "nodes", ")", "=>", "{", "if", "(", "err", ")", "{", "logger", ".", "warning", "(", "'Error while reading dir'", ",", "{", "category", ":", "'sync-local-delta'", ",", "dirPath", ",", "err", "}", ")", ";", "throw", "new", "BlnDeltaError", "(", "err", ".", "message", ")", ";", "}", "async", ".", "eachSeries", "(", "nodes", ",", "(", "node", ",", "cb", ")", "=>", "{", "var", "nodePath", "=", "utility", ".", "joinPath", "(", "dirPath", ",", "node", ")", ";", "try", "{", "var", "stat", "=", "fsWrap", ".", "lstatSync", "(", "nodePath", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "warning", "(", "'findChanges got lstat error on node'", ",", "{", "category", ":", "'sync-local-delta'", ",", "nodePath", ",", "code", ":", "e", ".", "code", "}", ")", ";", "throw", "new", "BlnDeltaError", "(", "e", ".", "message", ")", ";", "}", "if", "(", "utility", ".", "isExcludeFile", "(", "node", ")", ")", "{", "logger", ".", "info", "(", "'LOCAL DELTA: ignoring file \\''", "+", "\\'", "+", "nodePath", ")", ";", "'\\' matching exclude pattern'", "}", "\\'", "return", "cb", "(", "null", ")", ";", "if", "(", "utility", ".", "hasInvalidChars", "(", "node", ")", ")", "{", "logger", ".", "info", "(", "'LOCAL DELTA: ignoring file \\''", "+", "\\'", "+", "name", ")", ";", "'\\' because filename contains invalid chars'", "}", "}", ",", "\\'", ")", ";", "}", ")", ";", "}" ]
Recursively scans the given directory for new and changed nodes. Sets the necessary localActions in the database. Paths found in ignoreDb are ignored @param {string} dirPath - root directory to get delta for @param {string|undefined} oldDirPath - path of this directory after the last sync. undefined for root node @param {string|null} parentNodeId - the id of the parent node. null for root node @param {Function} callback - callback function @returns {void} - no return value
[ "Recursively", "scans", "the", "given", "directory", "for", "new", "and", "changed", "nodes", ".", "Sets", "the", "necessary", "localActions", "in", "the", "database", ".", "Paths", "found", "in", "ignoreDb", "are", "ignored" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/local-delta.js#L103-L161
train
gyselroth/balloon-node-sync
lib/delta/local-delta.js
function(callback) { //process first all directories and then all files. async.mapSeries(['getDirectories', 'getFiles'], (nodeSource, cbMap) => { syncDb[nodeSource]((err, nodes) => { async.eachSeries(nodes, (node, cb) => { // If a node has to be redownloaded do not delete it remotely // See: https://github.com/gyselroth/balloon-node-sync/issues/17 if(node.downloadOriginal) return cb(); var nodePath = utility.joinPath(node.parent, node.name); process.nextTick(() => { var nodePath = utility.joinPath(node.parent, node.name); if(fsWrap.existsSync(nodePath) === false) { //Node doesn't exist localy -> delete it remotely deleteNode(node, false, cb); } else { try { var stat = fsWrap.lstatSync(nodePath); } catch(e) { logger.warning('findDeletedNodes got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code}); throw new BlnDeltaError(e.message); } if(stat.ino === node.ino) { //node still exists at given path return cb(); } else { deleteNode(node, true, cb); } } }); }, cbMap); }); }, callback); }
javascript
function(callback) { //process first all directories and then all files. async.mapSeries(['getDirectories', 'getFiles'], (nodeSource, cbMap) => { syncDb[nodeSource]((err, nodes) => { async.eachSeries(nodes, (node, cb) => { // If a node has to be redownloaded do not delete it remotely // See: https://github.com/gyselroth/balloon-node-sync/issues/17 if(node.downloadOriginal) return cb(); var nodePath = utility.joinPath(node.parent, node.name); process.nextTick(() => { var nodePath = utility.joinPath(node.parent, node.name); if(fsWrap.existsSync(nodePath) === false) { //Node doesn't exist localy -> delete it remotely deleteNode(node, false, cb); } else { try { var stat = fsWrap.lstatSync(nodePath); } catch(e) { logger.warning('findDeletedNodes got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code}); throw new BlnDeltaError(e.message); } if(stat.ino === node.ino) { //node still exists at given path return cb(); } else { deleteNode(node, true, cb); } } }); }, cbMap); }); }, callback); }
[ "function", "(", "callback", ")", "{", "async", ".", "mapSeries", "(", "[", "'getDirectories'", ",", "'getFiles'", "]", ",", "(", "nodeSource", ",", "cbMap", ")", "=>", "{", "syncDb", "[", "nodeSource", "]", "(", "(", "err", ",", "nodes", ")", "=>", "{", "async", ".", "eachSeries", "(", "nodes", ",", "(", "node", ",", "cb", ")", "=>", "{", "if", "(", "node", ".", "downloadOriginal", ")", "return", "cb", "(", ")", ";", "var", "nodePath", "=", "utility", ".", "joinPath", "(", "node", ".", "parent", ",", "node", ".", "name", ")", ";", "process", ".", "nextTick", "(", "(", ")", "=>", "{", "var", "nodePath", "=", "utility", ".", "joinPath", "(", "node", ".", "parent", ",", "node", ".", "name", ")", ";", "if", "(", "fsWrap", ".", "existsSync", "(", "nodePath", ")", "===", "false", ")", "{", "deleteNode", "(", "node", ",", "false", ",", "cb", ")", ";", "}", "else", "{", "try", "{", "var", "stat", "=", "fsWrap", ".", "lstatSync", "(", "nodePath", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "warning", "(", "'findDeletedNodes got lstat error on node'", ",", "{", "category", ":", "'sync-local-delta'", ",", "nodePath", ",", "code", ":", "e", ".", "code", "}", ")", ";", "throw", "new", "BlnDeltaError", "(", "e", ".", "message", ")", ";", "}", "if", "(", "stat", ".", "ino", "===", "node", ".", "ino", ")", "{", "return", "cb", "(", ")", ";", "}", "else", "{", "deleteNode", "(", "node", ",", "true", ",", "cb", ")", ";", "}", "}", "}", ")", ";", "}", ",", "cbMap", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}" ]
Scans the database and checks for deleted nodes. Sets the necessary localActions in the database. @param {Function} callback - callback function @returns {void} - no return value
[ "Scans", "the", "database", "and", "checks", "for", "deleted", "nodes", ".", "Sets", "the", "necessary", "localActions", "in", "the", "database", "." ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/local-delta.js#L279-L316
train
JS-MF/jsmf-core
src/Model.js
Model
function Model(name, referenceModel, modellingElements, transitive) { /** @memberOf Model * @member {string} name - The name of the model */ this.__name = name _.set(this, ['__jsmf__','conformsTo'], Model) _.set(this, ['__jsmf__','uuid'], generateId()) /** @memberof Model * @member {Model} referenceModel - The referenceModel (an empty object if undefined) */ this.referenceModel = referenceModel || {} /** @memberof Model * @member {Object} modellingElements - The objects of the model, classified by their class name */ this.modellingElements = {} /** @memberOf Model * @member {Object} classes - classes and enums of the model, classified by their name */ this.classes = {} if (modellingElements !== undefined) { modellingElements = _.isArray(modellingElements) ? modellingElements : [modellingElements] if (transitive) { modellingElements = crawlElements(modellingElements) } _.forEach(modellingElements, e => this.addModellingElement(e)) } }
javascript
function Model(name, referenceModel, modellingElements, transitive) { /** @memberOf Model * @member {string} name - The name of the model */ this.__name = name _.set(this, ['__jsmf__','conformsTo'], Model) _.set(this, ['__jsmf__','uuid'], generateId()) /** @memberof Model * @member {Model} referenceModel - The referenceModel (an empty object if undefined) */ this.referenceModel = referenceModel || {} /** @memberof Model * @member {Object} modellingElements - The objects of the model, classified by their class name */ this.modellingElements = {} /** @memberOf Model * @member {Object} classes - classes and enums of the model, classified by their name */ this.classes = {} if (modellingElements !== undefined) { modellingElements = _.isArray(modellingElements) ? modellingElements : [modellingElements] if (transitive) { modellingElements = crawlElements(modellingElements) } _.forEach(modellingElements, e => this.addModellingElement(e)) } }
[ "function", "Model", "(", "name", ",", "referenceModel", ",", "modellingElements", ",", "transitive", ")", "{", "this", ".", "__name", "=", "name", "_", ".", "set", "(", "this", ",", "[", "'__jsmf__'", ",", "'conformsTo'", "]", ",", "Model", ")", "_", ".", "set", "(", "this", ",", "[", "'__jsmf__'", ",", "'uuid'", "]", ",", "generateId", "(", ")", ")", "this", ".", "referenceModel", "=", "referenceModel", "||", "{", "}", "this", ".", "modellingElements", "=", "{", "}", "this", ".", "classes", "=", "{", "}", "if", "(", "modellingElements", "!==", "undefined", ")", "{", "modellingElements", "=", "_", ".", "isArray", "(", "modellingElements", ")", "?", "modellingElements", ":", "[", "modellingElements", "]", "if", "(", "transitive", ")", "{", "modellingElements", "=", "crawlElements", "(", "modellingElements", ")", "}", "_", ".", "forEach", "(", "modellingElements", ",", "e", "=>", "this", ".", "addModellingElement", "(", "e", ")", ")", "}", "}" ]
A Model is basically a set of elements @constructor @param {string} name - The model name @param {Model} referenceModel - The reference model (indicative and used for conformance) @param {Class~ClassInstance[]} modellingElements - Either an element or an array of elements that should be included in the model @param {boolean} transitive - If false, only the elements in modellingElements will be in the model, otherwise all theelements that can be reach from modellingElements references are included in the model
[ "A", "Model", "is", "basically", "a", "set", "of", "elements" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Model.js#L54-L80
train
JS-MF/jsmf-core
src/Model.js
modelExport
function modelExport(m) { const result = _.mapValues(m.classes, _.head) result[m.__name] = m return result }
javascript
function modelExport(m) { const result = _.mapValues(m.classes, _.head) result[m.__name] = m return result }
[ "function", "modelExport", "(", "m", ")", "{", "const", "result", "=", "_", ".", "mapValues", "(", "m", ".", "classes", ",", "_", ".", "head", ")", "result", "[", "m", ".", "__name", "]", "=", "m", "return", "result", "}" ]
A helper to export a model and all its classes in a npm module.
[ "A", "helper", "to", "export", "a", "model", "and", "all", "its", "classes", "in", "a", "npm", "module", "." ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Model.js#L84-L88
train
xcambar/node-dbdeploy
lib/changelog.js
function (client, migrationFolder) { events.EventEmitter.call(this); if (client === undefined) { throw new Error('no client provided'); } _client = client; this.__defineGetter__('migrationFolder', function () { return migrationFolder; }); this.__defineSetter__('migrationFolder', function () { }); }
javascript
function (client, migrationFolder) { events.EventEmitter.call(this); if (client === undefined) { throw new Error('no client provided'); } _client = client; this.__defineGetter__('migrationFolder', function () { return migrationFolder; }); this.__defineSetter__('migrationFolder', function () { }); }
[ "function", "(", "client", ",", "migrationFolder", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "if", "(", "client", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'no client provided'", ")", ";", "}", "_client", "=", "client", ";", "this", ".", "__defineGetter__", "(", "'migrationFolder'", ",", "function", "(", ")", "{", "return", "migrationFolder", ";", "}", ")", ";", "this", ".", "__defineSetter__", "(", "'migrationFolder'", ",", "function", "(", ")", "{", "}", ")", ";", "}" ]
Changelog is in charge of checking the existence of the migrations reference table, creating the migrations reference table if not available and applying the migrations @param client inject the client used to perform SQL requests @param migrationFolder string The path to the migration files
[ "Changelog", "is", "in", "charge", "of", "checking", "the", "existence", "of", "the", "migrations", "reference", "table", "creating", "the", "migrations", "reference", "table", "if", "not", "available", "and", "applying", "the", "migrations" ]
09408f070764032e45502ec67ee532d12bee7ae3
https://github.com/xcambar/node-dbdeploy/blob/09408f070764032e45502ec67ee532d12bee7ae3/lib/changelog.js#L22-L34
train
Evo-Forge/Crux
lib/util/log.js
CruxLogger
function CruxLogger(_type, _level) { if (this instanceof CruxLogger) { Component.apply(this, arguments); this.name = 'log'; var hasColors = this.config.colors; delete this.config.colors; if (!hasColors) { for (var i = 0; i < this.config.appenders.length; i++) { this.config.appenders[i].layout = { type: 'basic' } } } log4js.configure(this.config); this.__logger = log4js.getLogger(); this.__logger.setLevel(this.config.level.toUpperCase()); global['log'] = this.__logger; } else { // In case we just called crux.Log(), we just want to return an instance of log4js this.__logger = log4js.getLogger(_type || 'default'); if (typeof _level === 'string') { this.__logger.setLevel(_level); } return this.__logger; } }
javascript
function CruxLogger(_type, _level) { if (this instanceof CruxLogger) { Component.apply(this, arguments); this.name = 'log'; var hasColors = this.config.colors; delete this.config.colors; if (!hasColors) { for (var i = 0; i < this.config.appenders.length; i++) { this.config.appenders[i].layout = { type: 'basic' } } } log4js.configure(this.config); this.__logger = log4js.getLogger(); this.__logger.setLevel(this.config.level.toUpperCase()); global['log'] = this.__logger; } else { // In case we just called crux.Log(), we just want to return an instance of log4js this.__logger = log4js.getLogger(_type || 'default'); if (typeof _level === 'string') { this.__logger.setLevel(_level); } return this.__logger; } }
[ "function", "CruxLogger", "(", "_type", ",", "_level", ")", "{", "if", "(", "this", "instanceof", "CruxLogger", ")", "{", "Component", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "name", "=", "'log'", ";", "var", "hasColors", "=", "this", ".", "config", ".", "colors", ";", "delete", "this", ".", "config", ".", "colors", ";", "if", "(", "!", "hasColors", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "config", ".", "appenders", ".", "length", ";", "i", "++", ")", "{", "this", ".", "config", ".", "appenders", "[", "i", "]", ".", "layout", "=", "{", "type", ":", "'basic'", "}", "}", "}", "log4js", ".", "configure", "(", "this", ".", "config", ")", ";", "this", ".", "__logger", "=", "log4js", ".", "getLogger", "(", ")", ";", "this", ".", "__logger", ".", "setLevel", "(", "this", ".", "config", ".", "level", ".", "toUpperCase", "(", ")", ")", ";", "global", "[", "'log'", "]", "=", "this", ".", "__logger", ";", "}", "else", "{", "this", ".", "__logger", "=", "log4js", ".", "getLogger", "(", "_type", "||", "'default'", ")", ";", "if", "(", "typeof", "_level", "===", "'string'", ")", "{", "this", ".", "__logger", ".", "setLevel", "(", "_level", ")", ";", "}", "return", "this", ".", "__logger", ";", "}", "}" ]
We may want to just attach log in the global scope.
[ "We", "may", "want", "to", "just", "attach", "log", "in", "the", "global", "scope", "." ]
f5264fbc2eb053e3170cf2b7b38d46d08f779feb
https://github.com/Evo-Forge/Crux/blob/f5264fbc2eb053e3170cf2b7b38d46d08f779feb/lib/util/log.js#L35-L59
train
gyselroth/balloon-node-sync
lib/delta/remote-delta.js
groupDelta
function groupDelta(nodes, callback) { async.eachLimit(nodes, 10, (node, cb) => { if(node.path === null) { // if node.path is null we have to skip the node logger.info('Remote Delta: Got node with path equal null', {node}); return cb(null); } const query = {remoteId: node.id, path: node.path}; ignoreDb.isIgnoredNode(query, (err, isIgnored) => { if(err) return cb(err); if(isIgnored) return cb(null); groupNode(node); cb(null); }); }, callback); }
javascript
function groupDelta(nodes, callback) { async.eachLimit(nodes, 10, (node, cb) => { if(node.path === null) { // if node.path is null we have to skip the node logger.info('Remote Delta: Got node with path equal null', {node}); return cb(null); } const query = {remoteId: node.id, path: node.path}; ignoreDb.isIgnoredNode(query, (err, isIgnored) => { if(err) return cb(err); if(isIgnored) return cb(null); groupNode(node); cb(null); }); }, callback); }
[ "function", "groupDelta", "(", "nodes", ",", "callback", ")", "{", "async", ".", "eachLimit", "(", "nodes", ",", "10", ",", "(", "node", ",", "cb", ")", "=>", "{", "if", "(", "node", ".", "path", "===", "null", ")", "{", "logger", ".", "info", "(", "'Remote Delta: Got node with path equal null'", ",", "{", "node", "}", ")", ";", "return", "cb", "(", "null", ")", ";", "}", "const", "query", "=", "{", "remoteId", ":", "node", ".", "id", ",", "path", ":", "node", ".", "path", "}", ";", "ignoreDb", ".", "isIgnoredNode", "(", "query", ",", "(", "err", ",", "isIgnored", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "isIgnored", ")", "return", "cb", "(", "null", ")", ";", "groupNode", "(", "node", ")", ";", "cb", "(", "null", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}" ]
groups the delta by node id, ignores paths found in ignoreDb @param {Array} nodes - array of node actions (data.nodes from api call) @param {Function} callback - callback function @returns {void} - no return value
[ "groups", "the", "delta", "by", "node", "id", "ignores", "paths", "found", "in", "ignoreDb" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/remote-delta.js#L64-L81
train
gyselroth/balloon-node-sync
lib/delta/remote-delta.js
groupNode
function groupNode(node) { node.parent = node.parent || ''; if(groupedDelta[node.id] === undefined) { groupedDelta[node.id] = { id: node.id, directory: node.directory, actions: {} }; } else if(groupedDelta[node.id].directory === undefined && node.directory !== undefined) { // Since balloon v2.1.0 action: directory is undefined for delete actions groupedDelta[node.id].directory = node.directory; } var groupedNode = groupedDelta[node.id]; if(node.deleted !==false && node.deleted !== undefined) { //in rare cases node.deleted might be a timestamp groupedNode.actions.delete = node; } else { groupedNode.actions.create = node; groupedNode.parent = node.parent; if(node.directory === false) { groupedNode.version = node.version; groupedNode.hash = node.hash; groupedNode.size = node.size; } } }
javascript
function groupNode(node) { node.parent = node.parent || ''; if(groupedDelta[node.id] === undefined) { groupedDelta[node.id] = { id: node.id, directory: node.directory, actions: {} }; } else if(groupedDelta[node.id].directory === undefined && node.directory !== undefined) { // Since balloon v2.1.0 action: directory is undefined for delete actions groupedDelta[node.id].directory = node.directory; } var groupedNode = groupedDelta[node.id]; if(node.deleted !==false && node.deleted !== undefined) { //in rare cases node.deleted might be a timestamp groupedNode.actions.delete = node; } else { groupedNode.actions.create = node; groupedNode.parent = node.parent; if(node.directory === false) { groupedNode.version = node.version; groupedNode.hash = node.hash; groupedNode.size = node.size; } } }
[ "function", "groupNode", "(", "node", ")", "{", "node", ".", "parent", "=", "node", ".", "parent", "||", "''", ";", "if", "(", "groupedDelta", "[", "node", ".", "id", "]", "===", "undefined", ")", "{", "groupedDelta", "[", "node", ".", "id", "]", "=", "{", "id", ":", "node", ".", "id", ",", "directory", ":", "node", ".", "directory", ",", "actions", ":", "{", "}", "}", ";", "}", "else", "if", "(", "groupedDelta", "[", "node", ".", "id", "]", ".", "directory", "===", "undefined", "&&", "node", ".", "directory", "!==", "undefined", ")", "{", "groupedDelta", "[", "node", ".", "id", "]", ".", "directory", "=", "node", ".", "directory", ";", "}", "var", "groupedNode", "=", "groupedDelta", "[", "node", ".", "id", "]", ";", "if", "(", "node", ".", "deleted", "!==", "false", "&&", "node", ".", "deleted", "!==", "undefined", ")", "{", "groupedNode", ".", "actions", ".", "delete", "=", "node", ";", "}", "else", "{", "groupedNode", ".", "actions", ".", "create", "=", "node", ";", "groupedNode", ".", "parent", "=", "node", ".", "parent", ";", "if", "(", "node", ".", "directory", "===", "false", ")", "{", "groupedNode", ".", "version", "=", "node", ".", "version", ";", "groupedNode", ".", "hash", "=", "node", ".", "hash", ";", "groupedNode", ".", "size", "=", "node", ".", "size", ";", "}", "}", "}" ]
groups a single node @param {Object} node - node action from remote delta @returns {void} - no return value
[ "groups", "a", "single", "node" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/remote-delta.js#L89-L117
train
gyselroth/balloon-node-sync
lib/delta/remote-delta.js
function(cursor, callback) { groupedDelta = {}; async.series([ (cb) => { logger.info('Fetching delta', {category: 'sync-remote-delta'}); fetchDelta({cursor}, (err, newCursor) => { if(err) return cb(err); cb(null, newCursor); }); }, (cb) => { logger.info('Applying collections which need to be redownloaded', {category: 'sync-remote-delta'}); syncDb.find({$and: [{directory: true}, {downloadOriginal: true}]}, (err, syncedNodes) => { if(err) return cb(err); if(!syncedNodes) return cb(null); async.map(syncedNodes, (syncedNode, mapCb) => { if(!syncedNode.remoteId) mapCb(null); fetchDelta({id: syncedNode.remoteId}, mapCb); }, cb); }); } ], (err, results) => { logger.info('getDelta ended', {category: 'sync-remote-delta'}); callback(err, results[0]); }); }
javascript
function(cursor, callback) { groupedDelta = {}; async.series([ (cb) => { logger.info('Fetching delta', {category: 'sync-remote-delta'}); fetchDelta({cursor}, (err, newCursor) => { if(err) return cb(err); cb(null, newCursor); }); }, (cb) => { logger.info('Applying collections which need to be redownloaded', {category: 'sync-remote-delta'}); syncDb.find({$and: [{directory: true}, {downloadOriginal: true}]}, (err, syncedNodes) => { if(err) return cb(err); if(!syncedNodes) return cb(null); async.map(syncedNodes, (syncedNode, mapCb) => { if(!syncedNode.remoteId) mapCb(null); fetchDelta({id: syncedNode.remoteId}, mapCb); }, cb); }); } ], (err, results) => { logger.info('getDelta ended', {category: 'sync-remote-delta'}); callback(err, results[0]); }); }
[ "function", "(", "cursor", ",", "callback", ")", "{", "groupedDelta", "=", "{", "}", ";", "async", ".", "series", "(", "[", "(", "cb", ")", "=>", "{", "logger", ".", "info", "(", "'Fetching delta'", ",", "{", "category", ":", "'sync-remote-delta'", "}", ")", ";", "fetchDelta", "(", "{", "cursor", "}", ",", "(", "err", ",", "newCursor", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "cb", "(", "null", ",", "newCursor", ")", ";", "}", ")", ";", "}", ",", "(", "cb", ")", "=>", "{", "logger", ".", "info", "(", "'Applying collections which need to be redownloaded'", ",", "{", "category", ":", "'sync-remote-delta'", "}", ")", ";", "syncDb", ".", "find", "(", "{", "$and", ":", "[", "{", "directory", ":", "true", "}", ",", "{", "downloadOriginal", ":", "true", "}", "]", "}", ",", "(", "err", ",", "syncedNodes", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "!", "syncedNodes", ")", "return", "cb", "(", "null", ")", ";", "async", ".", "map", "(", "syncedNodes", ",", "(", "syncedNode", ",", "mapCb", ")", "=>", "{", "if", "(", "!", "syncedNode", ".", "remoteId", ")", "mapCb", "(", "null", ")", ";", "fetchDelta", "(", "{", "id", ":", "syncedNode", ".", "remoteId", "}", ",", "mapCb", ")", ";", "}", ",", "cb", ")", ";", "}", ")", ";", "}", "]", ",", "(", "err", ",", "results", ")", "=>", "{", "logger", ".", "info", "(", "'getDelta ended'", ",", "{", "category", ":", "'sync-remote-delta'", "}", ")", ";", "callback", "(", "err", ",", "results", "[", "0", "]", ")", ";", "}", ")", ";", "}" ]
fetches the delta from the server, @param {string|undefined} cursor - the cursor to get the delta from @param {Function} callback - callback function @returns {void} - no return value
[ "fetches", "the", "delta", "from", "the", "server" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/remote-delta.js#L128-L160
train
base/base-plugins
index.js
use
function use(type, fn, options) { if (typeof type === 'string' || Array.isArray(type)) { fn = wrap(type, fn); } else { options = fn; fn = type; } var val = fn.call(this, this, this.base || {}, options || {}, this.env || {}); if (typeof val === 'function') { this.fns.push(val); } if (typeof this.emit === 'function') { this.emit('use', val, this); } return this; }
javascript
function use(type, fn, options) { if (typeof type === 'string' || Array.isArray(type)) { fn = wrap(type, fn); } else { options = fn; fn = type; } var val = fn.call(this, this, this.base || {}, options || {}, this.env || {}); if (typeof val === 'function') { this.fns.push(val); } if (typeof this.emit === 'function') { this.emit('use', val, this); } return this; }
[ "function", "use", "(", "type", ",", "fn", ",", "options", ")", "{", "if", "(", "typeof", "type", "===", "'string'", "||", "Array", ".", "isArray", "(", "type", ")", ")", "{", "fn", "=", "wrap", "(", "type", ",", "fn", ")", ";", "}", "else", "{", "options", "=", "fn", ";", "fn", "=", "type", ";", "}", "var", "val", "=", "fn", ".", "call", "(", "this", ",", "this", ",", "this", ".", "base", "||", "{", "}", ",", "options", "||", "{", "}", ",", "this", ".", "env", "||", "{", "}", ")", ";", "if", "(", "typeof", "val", "===", "'function'", ")", "{", "this", ".", "fns", ".", "push", "(", "val", ")", ";", "}", "if", "(", "typeof", "this", ".", "emit", "===", "'function'", ")", "{", "this", ".", "emit", "(", "'use'", ",", "val", ",", "this", ")", ";", "}", "return", "this", ";", "}" ]
Call plugin `fn`. If a function is returned push it into the `fns` array to be called by the `run` method.
[ "Call", "plugin", "fn", ".", "If", "a", "function", "is", "returned", "push", "it", "into", "the", "fns", "array", "to", "be", "called", "by", "the", "run", "method", "." ]
89ddd3f772aa0c376b8035b941d13018d0c66102
https://github.com/base/base-plugins/blob/89ddd3f772aa0c376b8035b941d13018d0c66102/index.js#L97-L114
train
angelozerr/tern-node-mongoose
generator/dox2tern.js
function(entry, options) { if (options.isClass) return options.isClass(entry); var tags = entry.tags; for(var k = 0; k < tags.length; k++) { if(tags[k].type == 'class') return true; } return false; }
javascript
function(entry, options) { if (options.isClass) return options.isClass(entry); var tags = entry.tags; for(var k = 0; k < tags.length; k++) { if(tags[k].type == 'class') return true; } return false; }
[ "function", "(", "entry", ",", "options", ")", "{", "if", "(", "options", ".", "isClass", ")", "return", "options", ".", "isClass", "(", "entry", ")", ";", "var", "tags", "=", "entry", ".", "tags", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "tags", ".", "length", ";", "k", "++", ")", "{", "if", "(", "tags", "[", "k", "]", ".", "type", "==", "'class'", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Helper methods used in the rendering
[ "Helper", "methods", "used", "in", "the", "rendering" ]
c0ddc30bb1383d6f9550352ca5cf31a2bf9d9ce0
https://github.com/angelozerr/tern-node-mongoose/blob/c0ddc30bb1383d6f9550352ca5cf31a2bf9d9ce0/generator/dox2tern.js#L188-L195
train
agco/elastic-harvesterjs
Util.js
assertAsDefined
function assertAsDefined(obj, errorMsg) { if (_.isUndefined(obj) || _.isNull(obj)) { throw new Error(errorMsg); } }
javascript
function assertAsDefined(obj, errorMsg) { if (_.isUndefined(obj) || _.isNull(obj)) { throw new Error(errorMsg); } }
[ "function", "assertAsDefined", "(", "obj", ",", "errorMsg", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "obj", ")", "||", "_", ".", "isNull", "(", "obj", ")", ")", "{", "throw", "new", "Error", "(", "errorMsg", ")", ";", "}", "}" ]
Throws error if objValue is undefined
[ "Throws", "error", "if", "objValue", "is", "undefined" ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/Util.js#L74-L78
train
agco/elastic-harvesterjs
Util.js
hasDotNesting
function hasDotNesting(string) { const loc = string.indexOf('.'); return (loc !== -1) && (loc !== 0) && (loc !== string.length - 1); }
javascript
function hasDotNesting(string) { const loc = string.indexOf('.'); return (loc !== -1) && (loc !== 0) && (loc !== string.length - 1); }
[ "function", "hasDotNesting", "(", "string", ")", "{", "const", "loc", "=", "string", ".", "indexOf", "(", "'.'", ")", ";", "return", "(", "loc", "!==", "-", "1", ")", "&&", "(", "loc", "!==", "0", ")", "&&", "(", "loc", "!==", "string", ".", "length", "-", "1", ")", ";", "}" ]
Returns true if string a dot in it at any position other than the first and last ones.
[ "Returns", "true", "if", "string", "a", "dot", "in", "it", "at", "any", "position", "other", "than", "the", "first", "and", "last", "ones", "." ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/Util.js#L88-L91
train
agco/elastic-harvesterjs
Util.js
substrAtNthOccurence
function substrAtNthOccurence(string, start, delimiter) { const _delimiter = getValueWithDefault(delimiter, '.'); const _start = getValueWithDefault(start, 1); const tokens = string.split(_delimiter).slice(_start); return tokens.join(_delimiter); }
javascript
function substrAtNthOccurence(string, start, delimiter) { const _delimiter = getValueWithDefault(delimiter, '.'); const _start = getValueWithDefault(start, 1); const tokens = string.split(_delimiter).slice(_start); return tokens.join(_delimiter); }
[ "function", "substrAtNthOccurence", "(", "string", ",", "start", ",", "delimiter", ")", "{", "const", "_delimiter", "=", "getValueWithDefault", "(", "delimiter", ",", "'.'", ")", ";", "const", "_start", "=", "getValueWithDefault", "(", "start", ",", "1", ")", ";", "const", "tokens", "=", "string", ".", "split", "(", "_delimiter", ")", ".", "slice", "(", "_start", ")", ";", "return", "tokens", ".", "join", "(", "_delimiter", ")", ";", "}" ]
Takes a string like "links.equipment.id",2,"." and returns "id"
[ "Takes", "a", "string", "like", "links", ".", "equipment", ".", "id", "2", ".", "and", "returns", "id" ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/Util.js#L104-L109
train
pnicorelli/nodejs-chinese-remainder
chinese_remainder_bignum.js
chineseRemainder_bignum
function chineseRemainder_bignum(a, n){ var p = bignum(1); var p1 = bignum(1); var prod = bignum(1); var i = 1; var sm = bignum(0); for(i=0; i< n.length; i++){ prod = prod.mul( n[i] ); //prod = prod * n[i]; } for(i=0; i< n.length; i++){ p = prod.div( n[i] ); //sm = sm + ( a[i] * mul_inv(p, n[i]) * p); p1 = mul_inv( p, n[i] ); p1 = p1.mul( a[i] ); p1 = p1.mul( p ); sm = sm.add( p1 ); } return sm.mod(prod); }
javascript
function chineseRemainder_bignum(a, n){ var p = bignum(1); var p1 = bignum(1); var prod = bignum(1); var i = 1; var sm = bignum(0); for(i=0; i< n.length; i++){ prod = prod.mul( n[i] ); //prod = prod * n[i]; } for(i=0; i< n.length; i++){ p = prod.div( n[i] ); //sm = sm + ( a[i] * mul_inv(p, n[i]) * p); p1 = mul_inv( p, n[i] ); p1 = p1.mul( a[i] ); p1 = p1.mul( p ); sm = sm.add( p1 ); } return sm.mod(prod); }
[ "function", "chineseRemainder_bignum", "(", "a", ",", "n", ")", "{", "var", "p", "=", "bignum", "(", "1", ")", ";", "var", "p1", "=", "bignum", "(", "1", ")", ";", "var", "prod", "=", "bignum", "(", "1", ")", ";", "var", "i", "=", "1", ";", "var", "sm", "=", "bignum", "(", "0", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "n", ".", "length", ";", "i", "++", ")", "{", "prod", "=", "prod", ".", "mul", "(", "n", "[", "i", "]", ")", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "n", ".", "length", ";", "i", "++", ")", "{", "p", "=", "prod", ".", "div", "(", "n", "[", "i", "]", ")", ";", "p1", "=", "mul_inv", "(", "p", ",", "n", "[", "i", "]", ")", ";", "p1", "=", "p1", ".", "mul", "(", "a", "[", "i", "]", ")", ";", "p1", "=", "p1", ".", "mul", "(", "p", ")", ";", "sm", "=", "sm", ".", "add", "(", "p1", ")", ";", "}", "return", "sm", ".", "mod", "(", "prod", ")", ";", "}" ]
a, n are array of bignum instances
[ "a", "n", "are", "array", "of", "bignum", "instances" ]
ad617a2d76751d69d19a4338a98923b45324a198
https://github.com/pnicorelli/nodejs-chinese-remainder/blob/ad617a2d76751d69d19a4338a98923b45324a198/chinese_remainder_bignum.js#L41-L61
train
socialtables/geometry-utils
lib/arc.js
Arc
function Arc(start, end, height) { this.start = start; this.end = end; this.height = height; }
javascript
function Arc(start, end, height) { this.start = start; this.end = end; this.height = height; }
[ "function", "Arc", "(", "start", ",", "end", ",", "height", ")", "{", "this", ".", "start", "=", "start", ";", "this", ".", "end", "=", "end", ";", "this", ".", "height", "=", "height", ";", "}" ]
Define a simple Arc object
[ "Define", "a", "simple", "Arc", "object" ]
4dc13529696a52dbe2d2cfcad3204dd39fca2f88
https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/arc.js#L6-L10
train
techpush/es6-readability
src/helpers.js
cleanStyles
function cleanStyles(e) { if (!e) return; // Remove any root styles, if we're able. if (typeof e.removeAttribute == 'function' && e.className != 'readability-styled') e.removeAttribute('style'); // Go until there are no more child nodes var cur = e.firstChild; while (cur) { if (cur.nodeType == 1) { // Remove style attribute(s) : if (cur.className != "readability-styled") { cur.removeAttribute("style"); } cleanStyles(cur); } cur = cur.nextSibling; } }
javascript
function cleanStyles(e) { if (!e) return; // Remove any root styles, if we're able. if (typeof e.removeAttribute == 'function' && e.className != 'readability-styled') e.removeAttribute('style'); // Go until there are no more child nodes var cur = e.firstChild; while (cur) { if (cur.nodeType == 1) { // Remove style attribute(s) : if (cur.className != "readability-styled") { cur.removeAttribute("style"); } cleanStyles(cur); } cur = cur.nextSibling; } }
[ "function", "cleanStyles", "(", "e", ")", "{", "if", "(", "!", "e", ")", "return", ";", "if", "(", "typeof", "e", ".", "removeAttribute", "==", "'function'", "&&", "e", ".", "className", "!=", "'readability-styled'", ")", "e", ".", "removeAttribute", "(", "'style'", ")", ";", "var", "cur", "=", "e", ".", "firstChild", ";", "while", "(", "cur", ")", "{", "if", "(", "cur", ".", "nodeType", "==", "1", ")", "{", "if", "(", "cur", ".", "className", "!=", "\"readability-styled\"", ")", "{", "cur", ".", "removeAttribute", "(", "\"style\"", ")", ";", "}", "cleanStyles", "(", "cur", ")", ";", "}", "cur", "=", "cur", ".", "nextSibling", ";", "}", "}" ]
Remove the style attribute on every e and under. @param Element @return void
[ "Remove", "the", "style", "attribute", "on", "every", "e", "and", "under", "." ]
cda873af030bf3db110a40906c6b3052d11ccecd
https://github.com/techpush/es6-readability/blob/cda873af030bf3db110a40906c6b3052d11ccecd/src/helpers.js#L265-L284
train
techpush/es6-readability
src/helpers.js
getCharCount
function getCharCount(e, s) { s = s || ","; return getInnerText(e).split(s).length; }
javascript
function getCharCount(e, s) { s = s || ","; return getInnerText(e).split(s).length; }
[ "function", "getCharCount", "(", "e", ",", "s", ")", "{", "s", "=", "s", "||", "\",\"", ";", "return", "getInnerText", "(", "e", ")", ".", "split", "(", "s", ")", ".", "length", ";", "}" ]
Get the number of times a string s appears in the node e. @param Element @param string - what to split on. Default is "," @return number (integer)
[ "Get", "the", "number", "of", "times", "a", "string", "s", "appears", "in", "the", "node", "e", "." ]
cda873af030bf3db110a40906c6b3052d11ccecd
https://github.com/techpush/es6-readability/blob/cda873af030bf3db110a40906c6b3052d11ccecd/src/helpers.js#L322-L325
train
techpush/es6-readability
src/helpers.js
fixLinks
function fixLinks(e) { if (!e.ownerDocument.originalURL) { return; } function fixLink(link) { var fixed = url.resolve(e.ownerDocument.originalURL, link); return fixed; } var i; var imgs = e.getElementsByTagName('img'); for (i = imgs.length - 1; i >= 0; --i) { var src = imgs[i].getAttribute('src'); if (src) { imgs[i].setAttribute('src', fixLink(src)); } } var as = e.getElementsByTagName('a'); for (i = as.length - 1; i >= 0; --i) { var href = as[i].getAttribute('href'); if (href) { as[i].setAttribute('href', fixLink(href)); } } }
javascript
function fixLinks(e) { if (!e.ownerDocument.originalURL) { return; } function fixLink(link) { var fixed = url.resolve(e.ownerDocument.originalURL, link); return fixed; } var i; var imgs = e.getElementsByTagName('img'); for (i = imgs.length - 1; i >= 0; --i) { var src = imgs[i].getAttribute('src'); if (src) { imgs[i].setAttribute('src', fixLink(src)); } } var as = e.getElementsByTagName('a'); for (i = as.length - 1; i >= 0; --i) { var href = as[i].getAttribute('href'); if (href) { as[i].setAttribute('href', fixLink(href)); } } }
[ "function", "fixLinks", "(", "e", ")", "{", "if", "(", "!", "e", ".", "ownerDocument", ".", "originalURL", ")", "{", "return", ";", "}", "function", "fixLink", "(", "link", ")", "{", "var", "fixed", "=", "url", ".", "resolve", "(", "e", ".", "ownerDocument", ".", "originalURL", ",", "link", ")", ";", "return", "fixed", ";", "}", "var", "i", ";", "var", "imgs", "=", "e", ".", "getElementsByTagName", "(", "'img'", ")", ";", "for", "(", "i", "=", "imgs", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "var", "src", "=", "imgs", "[", "i", "]", ".", "getAttribute", "(", "'src'", ")", ";", "if", "(", "src", ")", "{", "imgs", "[", "i", "]", ".", "setAttribute", "(", "'src'", ",", "fixLink", "(", "src", ")", ")", ";", "}", "}", "var", "as", "=", "e", ".", "getElementsByTagName", "(", "'a'", ")", ";", "for", "(", "i", "=", "as", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "var", "href", "=", "as", "[", "i", "]", ".", "getAttribute", "(", "'href'", ")", ";", "if", "(", "href", ")", "{", "as", "[", "i", "]", ".", "setAttribute", "(", "'href'", ",", "fixLink", "(", "href", ")", ")", ";", "}", "}", "}" ]
Converts relative urls to absolute for images and links
[ "Converts", "relative", "urls", "to", "absolute", "for", "images", "and", "links" ]
cda873af030bf3db110a40906c6b3052d11ccecd
https://github.com/techpush/es6-readability/blob/cda873af030bf3db110a40906c6b3052d11ccecd/src/helpers.js#L488-L514
train
techpush/es6-readability
src/helpers.js
cleanSingleHeader
function cleanSingleHeader(e) { for (var headerIndex = 1; headerIndex < 7; headerIndex++) { var headers = e.getElementsByTagName('h' + headerIndex); for (var i = headers.length - 1; i >= 0; --i) { if (headers[i].nextSibling === null) { headers[i].parentNode.removeChild(headers[i]); } } } }
javascript
function cleanSingleHeader(e) { for (var headerIndex = 1; headerIndex < 7; headerIndex++) { var headers = e.getElementsByTagName('h' + headerIndex); for (var i = headers.length - 1; i >= 0; --i) { if (headers[i].nextSibling === null) { headers[i].parentNode.removeChild(headers[i]); } } } }
[ "function", "cleanSingleHeader", "(", "e", ")", "{", "for", "(", "var", "headerIndex", "=", "1", ";", "headerIndex", "<", "7", ";", "headerIndex", "++", ")", "{", "var", "headers", "=", "e", ".", "getElementsByTagName", "(", "'h'", "+", "headerIndex", ")", ";", "for", "(", "var", "i", "=", "headers", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "if", "(", "headers", "[", "i", "]", ".", "nextSibling", "===", "null", ")", "{", "headers", "[", "i", "]", ".", "parentNode", ".", "removeChild", "(", "headers", "[", "i", "]", ")", ";", "}", "}", "}", "}" ]
Remove the header that doesn't have next sibling. @param Element @return void
[ "Remove", "the", "header", "that", "doesn", "t", "have", "next", "sibling", "." ]
cda873af030bf3db110a40906c6b3052d11ccecd
https://github.com/techpush/es6-readability/blob/cda873af030bf3db110a40906c6b3052d11ccecd/src/helpers.js#L540-L550
train
boilerplates/snippet
lib/snippet.js
Snippet
function Snippet(file) { if (!(this instanceof Snippet)) { return new Snippet(file); } if (typeof file === 'string') { file = {path: file}; } this.history = []; if (typeof file === 'object') { this.visit('set', file); } this.cwd = this.cwd || process.cwd(); this.content = this.content || null; this.options = this.options || {}; }
javascript
function Snippet(file) { if (!(this instanceof Snippet)) { return new Snippet(file); } if (typeof file === 'string') { file = {path: file}; } this.history = []; if (typeof file === 'object') { this.visit('set', file); } this.cwd = this.cwd || process.cwd(); this.content = this.content || null; this.options = this.options || {}; }
[ "function", "Snippet", "(", "file", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Snippet", ")", ")", "{", "return", "new", "Snippet", "(", "file", ")", ";", "}", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "file", "=", "{", "path", ":", "file", "}", ";", "}", "this", ".", "history", "=", "[", "]", ";", "if", "(", "typeof", "file", "===", "'object'", ")", "{", "this", ".", "visit", "(", "'set'", ",", "file", ")", ";", "}", "this", ".", "cwd", "=", "this", ".", "cwd", "||", "process", ".", "cwd", "(", ")", ";", "this", ".", "content", "=", "this", ".", "content", "||", "null", ";", "this", ".", "options", "=", "this", ".", "options", "||", "{", "}", ";", "}" ]
Create a new `Snippet`, optionally passing a `file` object to start with. @param {Object} `file` @api public
[ "Create", "a", "new", "Snippet", "optionally", "passing", "a", "file", "object", "to", "start", "with", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/lib/snippet.js#L18-L35
train
boilerplates/snippet
lib/snippet.js
function (prop, val) { if (arguments.length === 1) { if (typeof prop === 'string') { return utils.get(this.options, prop); } if (typeof prop === 'object') { return this.visit('option', prop); } } utils.set(this.options, prop, val); return this; }
javascript
function (prop, val) { if (arguments.length === 1) { if (typeof prop === 'string') { return utils.get(this.options, prop); } if (typeof prop === 'object') { return this.visit('option', prop); } } utils.set(this.options, prop, val); return this; }
[ "function", "(", "prop", ",", "val", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "if", "(", "typeof", "prop", "===", "'string'", ")", "{", "return", "utils", ".", "get", "(", "this", ".", "options", ",", "prop", ")", ";", "}", "if", "(", "typeof", "prop", "===", "'object'", ")", "{", "return", "this", ".", "visit", "(", "'option'", ",", "prop", ")", ";", "}", "}", "utils", ".", "set", "(", "this", ".", "options", ",", "prop", ",", "val", ")", ";", "return", "this", ";", "}" ]
Set or get an option on the snippet. Dot notation may be used. @name .option @param {String} `prop` The property to get. @api public
[ "Set", "or", "get", "an", "option", "on", "the", "snippet", ".", "Dot", "notation", "may", "be", "used", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/lib/snippet.js#L52-L63
train
boilerplates/snippet
lib/snippet.js
function (fp) { if (this.content) return this; fp = path.resolve(this.cwd, fp || this.path); this.content = utils.tryRead(fp); return this; }
javascript
function (fp) { if (this.content) return this; fp = path.resolve(this.cwd, fp || this.path); this.content = utils.tryRead(fp); return this; }
[ "function", "(", "fp", ")", "{", "if", "(", "this", ".", "content", ")", "return", "this", ";", "fp", "=", "path", ".", "resolve", "(", "this", ".", "cwd", ",", "fp", "||", "this", ".", "path", ")", ";", "this", ".", "content", "=", "utils", ".", "tryRead", "(", "fp", ")", ";", "return", "this", ";", "}" ]
Read a utf8 string from the file system, or return if `content` is already a string. @name .read @param {String} `fp` Filepath @api public
[ "Read", "a", "utf8", "string", "from", "the", "file", "system", "or", "return", "if", "content", "is", "already", "a", "string", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/lib/snippet.js#L102-L107
train
boilerplates/snippet
lib/snippet.js
function (val, opts) { if (typeof val === 'function') { return new Snippet(val(this)); } if (typeof val === 'string') { var str = utils.tryRead(val); var res = {content: null, options: opts || {}}; if (str) { res.path = val; res.content = str.toString(); } else { res.content = val; } return new Snippet(res); } if (val instanceof Snippet) { val.option(opts); return val; } if (typeof val === 'object') { val.options = extend({}, val.options, opts); return new Snippet(val); } }
javascript
function (val, opts) { if (typeof val === 'function') { return new Snippet(val(this)); } if (typeof val === 'string') { var str = utils.tryRead(val); var res = {content: null, options: opts || {}}; if (str) { res.path = val; res.content = str.toString(); } else { res.content = val; } return new Snippet(res); } if (val instanceof Snippet) { val.option(opts); return val; } if (typeof val === 'object') { val.options = extend({}, val.options, opts); return new Snippet(val); } }
[ "function", "(", "val", ",", "opts", ")", "{", "if", "(", "typeof", "val", "===", "'function'", ")", "{", "return", "new", "Snippet", "(", "val", "(", "this", ")", ")", ";", "}", "if", "(", "typeof", "val", "===", "'string'", ")", "{", "var", "str", "=", "utils", ".", "tryRead", "(", "val", ")", ";", "var", "res", "=", "{", "content", ":", "null", ",", "options", ":", "opts", "||", "{", "}", "}", ";", "if", "(", "str", ")", "{", "res", ".", "path", "=", "val", ";", "res", ".", "content", "=", "str", ".", "toString", "(", ")", ";", "}", "else", "{", "res", ".", "content", "=", "val", ";", "}", "return", "new", "Snippet", "(", "res", ")", ";", "}", "if", "(", "val", "instanceof", "Snippet", ")", "{", "val", ".", "option", "(", "opts", ")", ";", "return", "val", ";", "}", "if", "(", "typeof", "val", "===", "'object'", ")", "{", "val", ".", "options", "=", "extend", "(", "{", "}", ",", "val", ".", "options", ",", "opts", ")", ";", "return", "new", "Snippet", "(", "val", ")", ";", "}", "}" ]
Attempts to return a snippet object from the given `value`. @name .toSnippet @param {String|Object} `val` Can be a filepath, content string, object or instance of `Snippet`. @param {Object} `opts` @api public
[ "Attempts", "to", "return", "a", "snippet", "object", "from", "the", "given", "value", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/lib/snippet.js#L118-L141
train
boilerplates/snippet
lib/snippet.js
function (fp, options) { if (typeof fp === 'function') { return fp.call(this, this.path); } var opts = extend({}, this.options, options); if (typeof fp === 'object') { opts = extend({}, opts, fp); } if (typeof fp === 'string' && ~fp.indexOf(':')) { fp = fp.replace(/:(\w+)/g, function (m, prop) { return opts[prop] || this[prop] || m; }.bind(this)); } this.path = this.path || fp; var base = opts.base || this.base || path.dirname(fp); var name = opts.basename || this.relative || this.basename; var ext = opts.ext || this.extname || path.extname(fp); if (typeof fp === 'string' && fp[fp.length - 1] === '/') { base = fp; } var dest = path.join(base, utils.rewrite(name, ext)); if (dest.slice(-1) === '.') { dest = dest.slice(0, dest.length - 1) + ext; } return dest; }
javascript
function (fp, options) { if (typeof fp === 'function') { return fp.call(this, this.path); } var opts = extend({}, this.options, options); if (typeof fp === 'object') { opts = extend({}, opts, fp); } if (typeof fp === 'string' && ~fp.indexOf(':')) { fp = fp.replace(/:(\w+)/g, function (m, prop) { return opts[prop] || this[prop] || m; }.bind(this)); } this.path = this.path || fp; var base = opts.base || this.base || path.dirname(fp); var name = opts.basename || this.relative || this.basename; var ext = opts.ext || this.extname || path.extname(fp); if (typeof fp === 'string' && fp[fp.length - 1] === '/') { base = fp; } var dest = path.join(base, utils.rewrite(name, ext)); if (dest.slice(-1) === '.') { dest = dest.slice(0, dest.length - 1) + ext; } return dest; }
[ "function", "(", "fp", ",", "options", ")", "{", "if", "(", "typeof", "fp", "===", "'function'", ")", "{", "return", "fp", ".", "call", "(", "this", ",", "this", ".", "path", ")", ";", "}", "var", "opts", "=", "extend", "(", "{", "}", ",", "this", ".", "options", ",", "options", ")", ";", "if", "(", "typeof", "fp", "===", "'object'", ")", "{", "opts", "=", "extend", "(", "{", "}", ",", "opts", ",", "fp", ")", ";", "}", "if", "(", "typeof", "fp", "===", "'string'", "&&", "~", "fp", ".", "indexOf", "(", "':'", ")", ")", "{", "fp", "=", "fp", ".", "replace", "(", "/", ":(\\w+)", "/", "g", ",", "function", "(", "m", ",", "prop", ")", "{", "return", "opts", "[", "prop", "]", "||", "this", "[", "prop", "]", "||", "m", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "this", ".", "path", "=", "this", ".", "path", "||", "fp", ";", "var", "base", "=", "opts", ".", "base", "||", "this", ".", "base", "||", "path", ".", "dirname", "(", "fp", ")", ";", "var", "name", "=", "opts", ".", "basename", "||", "this", ".", "relative", "||", "this", ".", "basename", ";", "var", "ext", "=", "opts", ".", "ext", "||", "this", ".", "extname", "||", "path", ".", "extname", "(", "fp", ")", ";", "if", "(", "typeof", "fp", "===", "'string'", "&&", "fp", "[", "fp", ".", "length", "-", "1", "]", "===", "'/'", ")", "{", "base", "=", "fp", ";", "}", "var", "dest", "=", "path", ".", "join", "(", "base", ",", "utils", ".", "rewrite", "(", "name", ",", "ext", ")", ")", ";", "if", "(", "dest", ".", "slice", "(", "-", "1", ")", "===", "'.'", ")", "{", "dest", "=", "dest", ".", "slice", "(", "0", ",", "dest", ".", "length", "-", "1", ")", "+", "ext", ";", "}", "return", "dest", ";", "}" ]
Calculate the destination path based on the given function or `filepath`. @name .dest @param {String|Function} `fp` @return {String} Returns the destination path. @api public
[ "Calculate", "the", "destination", "path", "based", "on", "the", "given", "function", "or", "filepath", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/lib/snippet.js#L199-L229
train
boilerplates/snippet
lib/snippet.js
function (fp, opts, cb) { if (typeof fp !== 'string') { cb = opts; opts = fp; fp = null; } if (typeof opts === 'function') { cb = opts; opts = {}; } if (typeof cb !== 'function') { throw new Error('expected a callback function.'); } var dest = this.dest(fp || this.path, opts); var file = { contents: this.content, path: dest }; opts = extend({ ask: true }, this.options, opts); utils.detect(file, opts, function (err) { if (file.contents) { utils.write(dest, file.contents, cb); } else { this.copy(dest, cb); } return this; }.bind(this)); return this; }
javascript
function (fp, opts, cb) { if (typeof fp !== 'string') { cb = opts; opts = fp; fp = null; } if (typeof opts === 'function') { cb = opts; opts = {}; } if (typeof cb !== 'function') { throw new Error('expected a callback function.'); } var dest = this.dest(fp || this.path, opts); var file = { contents: this.content, path: dest }; opts = extend({ ask: true }, this.options, opts); utils.detect(file, opts, function (err) { if (file.contents) { utils.write(dest, file.contents, cb); } else { this.copy(dest, cb); } return this; }.bind(this)); return this; }
[ "function", "(", "fp", ",", "opts", ",", "cb", ")", "{", "if", "(", "typeof", "fp", "!==", "'string'", ")", "{", "cb", "=", "opts", ";", "opts", "=", "fp", ";", "fp", "=", "null", ";", "}", "if", "(", "typeof", "opts", "===", "'function'", ")", "{", "cb", "=", "opts", ";", "opts", "=", "{", "}", ";", "}", "if", "(", "typeof", "cb", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'expected a callback function.'", ")", ";", "}", "var", "dest", "=", "this", ".", "dest", "(", "fp", "||", "this", ".", "path", ",", "opts", ")", ";", "var", "file", "=", "{", "contents", ":", "this", ".", "content", ",", "path", ":", "dest", "}", ";", "opts", "=", "extend", "(", "{", "ask", ":", "true", "}", ",", "this", ".", "options", ",", "opts", ")", ";", "utils", ".", "detect", "(", "file", ",", "opts", ",", "function", "(", "err", ")", "{", "if", "(", "file", ".", "contents", ")", "{", "utils", ".", "write", "(", "dest", ",", "file", ".", "contents", ",", "cb", ")", ";", "}", "else", "{", "this", ".", "copy", "(", "dest", ",", "cb", ")", ";", "}", "return", "this", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "this", ";", "}" ]
Asynchronously write the snippet to disk. @name .write @param {String} `fp` Destination filepath. @param {Function} `cb` Callback function @returns {Object} Returns the instance for chaining. @api public
[ "Asynchronously", "write", "the", "snippet", "to", "disk", "." ]
894e3951359fb83957d7d8fa319a9482b425fd46
https://github.com/boilerplates/snippet/blob/894e3951359fb83957d7d8fa319a9482b425fd46/lib/snippet.js#L241-L267
train
wangtao0101/parse-import-es6
src/parseImportClause.js
splitImportsList
function splitImportsList(text) { const list = []; list.push(...text .split(',') .map(s => s.trim()) .filter(s => s !== '') ); return list; }
javascript
function splitImportsList(text) { const list = []; list.push(...text .split(',') .map(s => s.trim()) .filter(s => s !== '') ); return list; }
[ "function", "splitImportsList", "(", "text", ")", "{", "const", "list", "=", "[", "]", ";", "list", ".", "push", "(", "...", "text", ".", "split", "(", "','", ")", ".", "map", "(", "s", "=>", "s", ".", "trim", "(", ")", ")", ".", "filter", "(", "s", "=>", "s", "!==", "''", ")", ")", ";", "return", "list", ";", "}" ]
split ImportsList by ',' here wo do not check the correctness of ImportSpecifiers in ImportsList, just tolerate it @param {*} text
[ "split", "ImportsList", "by", "here", "wo", "do", "not", "check", "the", "correctness", "of", "ImportSpecifiers", "in", "ImportsList", "just", "tolerate", "it" ]
c0ada33342b07e58cba83c27b6f1d92e522f35ac
https://github.com/wangtao0101/parse-import-es6/blob/c0ada33342b07e58cba83c27b6f1d92e522f35ac/src/parseImportClause.js#L6-L14
train
nodenica/grunt-loopback-auto
tasks/loopback_auto.js
goToNext
function goToNext() { count++; if (count === _.size(config)) { grunt.log.writeln(''); // line break grunt.log.ok('Ignored: %d', countIgnored); grunt.log.ok('Excluded: %d', countExcluded); grunt.log.ok('Processed: %d', countProcessed); done(); } }
javascript
function goToNext() { count++; if (count === _.size(config)) { grunt.log.writeln(''); // line break grunt.log.ok('Ignored: %d', countIgnored); grunt.log.ok('Excluded: %d', countExcluded); grunt.log.ok('Processed: %d', countProcessed); done(); } }
[ "function", "goToNext", "(", ")", "{", "count", "++", ";", "if", "(", "count", "===", "_", ".", "size", "(", "config", ")", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "''", ")", ";", "grunt", ".", "log", ".", "ok", "(", "'Ignored: %d'", ",", "countIgnored", ")", ";", "grunt", ".", "log", ".", "ok", "(", "'Excluded: %d'", ",", "countExcluded", ")", ";", "grunt", ".", "log", ".", "ok", "(", "'Processed: %d'", ",", "countProcessed", ")", ";", "done", "(", ")", ";", "}", "}" ]
Check if all models has been processed
[ "Check", "if", "all", "models", "has", "been", "processed" ]
840c5df889d35a0122ce233cf60eec5eb398298d
https://github.com/nodenica/grunt-loopback-auto/blob/840c5df889d35a0122ce233cf60eec5eb398298d/tasks/loopback_auto.js#L76-L85
train
ksanaforge/tibetan
wylie.js
function() { this.top = '' this.stack = [] this.caret = false this.vowels = [] this.finals = [] this.finals_found = newHashMap() this.visarga = false this.cons_str = '' this.single_cons = '' this.prefix = false this.suffix = false this.suff2 = false this.dot = false this.tokens_used = 0 this.warns = [] return this }
javascript
function() { this.top = '' this.stack = [] this.caret = false this.vowels = [] this.finals = [] this.finals_found = newHashMap() this.visarga = false this.cons_str = '' this.single_cons = '' this.prefix = false this.suffix = false this.suff2 = false this.dot = false this.tokens_used = 0 this.warns = [] return this }
[ "function", "(", ")", "{", "this", ".", "top", "=", "''", "this", ".", "stack", "=", "[", "]", "this", ".", "caret", "=", "false", "this", ".", "vowels", "=", "[", "]", "this", ".", "finals", "=", "[", "]", "this", ".", "finals_found", "=", "newHashMap", "(", ")", "this", ".", "visarga", "=", "false", "this", ".", "cons_str", "=", "''", "this", ".", "single_cons", "=", "''", "this", ".", "prefix", "=", "false", "this", ".", "suffix", "=", "false", "this", ".", "suff2", "=", "false", "this", ".", "dot", "=", "false", "this", ".", "tokens_used", "=", "0", "this", ".", "warns", "=", "[", "]", "return", "this", "}" ]
A class to encapsulate an analyzed tibetan stack, while converting Unicode to Wylie.
[ "A", "class", "to", "encapsulate", "an", "analyzed", "tibetan", "stack", "while", "converting", "Unicode", "to", "Wylie", "." ]
c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a
https://github.com/ksanaforge/tibetan/blob/c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a/wylie.js#L946-L963
train
ksanaforge/tibetan
wylie.js
function(str) { var tokens = [] // size = str.length + 2 var i = 0; var maxlen = str.length; TOKEN: while (i < maxlen) { var c = str.charAt(i); var mlo = m_tokens_start.get(c); // if there are multi-char tokens starting with this char, try them if (mlo != null) { for (var len = mlo; len > 1; len--) { if (i <= maxlen - len) { var tr = str.substring(i, i + len); if (m_tokens.contains(tr)) { tokens.push(tr); i += len; continue TOKEN; } } } } // things starting with backslash are special if (c == '\\' && i <= maxlen - 2) { if (str.charAt(i + 1) == 'u' && i <= maxlen - 6) { tokens.push(str.substring(i, i + 6)); // \\uxxxx i += 6; } else if (str.charAt(i + 1) == 'U' && i <= maxlen - 10) { tokens.push(str.substring(i, i + 10)); // \\Uxxxxxxxx i += 10; } else { tokens.push(str.substring(i, i + 2)); // \\x i += 2; } continue TOKEN; } // otherwise just take one char tokens.push(c.toString()); i += 1; } return tokens; }
javascript
function(str) { var tokens = [] // size = str.length + 2 var i = 0; var maxlen = str.length; TOKEN: while (i < maxlen) { var c = str.charAt(i); var mlo = m_tokens_start.get(c); // if there are multi-char tokens starting with this char, try them if (mlo != null) { for (var len = mlo; len > 1; len--) { if (i <= maxlen - len) { var tr = str.substring(i, i + len); if (m_tokens.contains(tr)) { tokens.push(tr); i += len; continue TOKEN; } } } } // things starting with backslash are special if (c == '\\' && i <= maxlen - 2) { if (str.charAt(i + 1) == 'u' && i <= maxlen - 6) { tokens.push(str.substring(i, i + 6)); // \\uxxxx i += 6; } else if (str.charAt(i + 1) == 'U' && i <= maxlen - 10) { tokens.push(str.substring(i, i + 10)); // \\Uxxxxxxxx i += 10; } else { tokens.push(str.substring(i, i + 2)); // \\x i += 2; } continue TOKEN; } // otherwise just take one char tokens.push(c.toString()); i += 1; } return tokens; }
[ "function", "(", "str", ")", "{", "var", "tokens", "=", "[", "]", "var", "i", "=", "0", ";", "var", "maxlen", "=", "str", ".", "length", ";", "TOKEN", ":", "while", "(", "i", "<", "maxlen", ")", "{", "var", "c", "=", "str", ".", "charAt", "(", "i", ")", ";", "var", "mlo", "=", "m_tokens_start", ".", "get", "(", "c", ")", ";", "if", "(", "mlo", "!=", "null", ")", "{", "for", "(", "var", "len", "=", "mlo", ";", "len", ">", "1", ";", "len", "--", ")", "{", "if", "(", "i", "<=", "maxlen", "-", "len", ")", "{", "var", "tr", "=", "str", ".", "substring", "(", "i", ",", "i", "+", "len", ")", ";", "if", "(", "m_tokens", ".", "contains", "(", "tr", ")", ")", "{", "tokens", ".", "push", "(", "tr", ")", ";", "i", "+=", "len", ";", "continue", "TOKEN", ";", "}", "}", "}", "}", "if", "(", "c", "==", "'\\\\'", "&&", "\\\\", ")", "i", "<=", "maxlen", "-", "2", "{", "if", "(", "str", ".", "charAt", "(", "i", "+", "1", ")", "==", "'u'", "&&", "i", "<=", "maxlen", "-", "6", ")", "{", "tokens", ".", "push", "(", "str", ".", "substring", "(", "i", ",", "i", "+", "6", ")", ")", ";", "i", "+=", "6", ";", "}", "else", "if", "(", "str", ".", "charAt", "(", "i", "+", "1", ")", "==", "'U'", "&&", "i", "<=", "maxlen", "-", "10", ")", "{", "tokens", ".", "push", "(", "str", ".", "substring", "(", "i", ",", "i", "+", "10", ")", ")", ";", "i", "+=", "10", ";", "}", "else", "{", "tokens", ".", "push", "(", "str", ".", "substring", "(", "i", ",", "i", "+", "2", ")", ")", ";", "i", "+=", "2", ";", "}", "continue", "TOKEN", ";", "}", "tokens", ".", "push", "(", "c", ".", "toString", "(", ")", ")", ";", "}", "i", "+=", "1", ";", "}" ]
split a string into Wylie tokens; make sure there is room for at least one null element at the end of the array
[ "split", "a", "string", "into", "Wylie", "tokens", ";", "make", "sure", "there", "is", "room", "for", "at", "least", "one", "null", "element", "at", "the", "end", "of", "the", "array" ]
c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a
https://github.com/ksanaforge/tibetan/blob/c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a/wylie.js#L982-L1022
train
ksanaforge/tibetan
wylie.js
validHex
function validHex(t) { for (var i = 0; i < t.length; i++) { var c = t.charAt(i); if (!((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'))) return false; } return true; }
javascript
function validHex(t) { for (var i = 0; i < t.length; i++) { var c = t.charAt(i); if (!((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'))) return false; } return true; }
[ "function", "validHex", "(", "t", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "t", ".", "length", ";", "i", "++", ")", "{", "var", "c", "=", "t", ".", "charAt", "(", "i", ")", ";", "if", "(", "!", "(", "(", "c", ">=", "'a'", "&&", "c", "<=", "'f'", ")", "||", "(", "c", ">=", "'0'", "&&", "c", "<=", "'9'", ")", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
does this string consist of only hexadecimal digits?
[ "does", "this", "string", "consist", "of", "only", "hexadecimal", "digits?" ]
c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a
https://github.com/ksanaforge/tibetan/blob/c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a/wylie.js#L1070-L1076
train
ksanaforge/tibetan
wylie.js
unicodeEscape
function unicodeEscape (warns, line, t) { // [], int, str var hex = t.substring(2); if (hex == '') return null; if (!validHex(hex)) { warnl(warns, line, "\"" + t + "\": invalid hex code."); return ""; } return String.fromCharCode(parseInt(hex, 16)) }
javascript
function unicodeEscape (warns, line, t) { // [], int, str var hex = t.substring(2); if (hex == '') return null; if (!validHex(hex)) { warnl(warns, line, "\"" + t + "\": invalid hex code."); return ""; } return String.fromCharCode(parseInt(hex, 16)) }
[ "function", "unicodeEscape", "(", "warns", ",", "line", ",", "t", ")", "{", "var", "hex", "=", "t", ".", "substring", "(", "2", ")", ";", "if", "(", "hex", "==", "''", ")", "return", "null", ";", "if", "(", "!", "validHex", "(", "hex", ")", ")", "{", "warnl", "(", "warns", ",", "line", ",", "\"\\\"\"", "+", "\\\"", "+", "t", ")", ";", "\"\\\": invalid hex code.\"", "}", "\\\"", "}" ]
generate a warning if we are keeping them; prints it out if we were asked to handle a Wylie unicode escape, \\uxxxx or \\Uxxxxxxxx
[ "generate", "a", "warning", "if", "we", "are", "keeping", "them", ";", "prints", "it", "out", "if", "we", "were", "asked", "to", "handle", "a", "Wylie", "unicode", "escape", "\\\\", "uxxxx", "or", "\\\\", "Uxxxxxxxx" ]
c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a
https://github.com/ksanaforge/tibetan/blob/c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a/wylie.js#L1080-L1088
train
ksanaforge/tibetan
wylie.js
formatHex
function formatHex(t) { //char // not compatible with GWT... // return String.format("\\u%04x", (int)t); var sb = ''; sb += '\\u'; var s = t.charCodeAt(0).toString(16); for (var i = s.length; i < 4; i++) sb += '0'; sb += s; return sb; }
javascript
function formatHex(t) { //char // not compatible with GWT... // return String.format("\\u%04x", (int)t); var sb = ''; sb += '\\u'; var s = t.charCodeAt(0).toString(16); for (var i = s.length; i < 4; i++) sb += '0'; sb += s; return sb; }
[ "function", "formatHex", "(", "t", ")", "{", "var", "sb", "=", "''", ";", "sb", "+=", "'\\\\u'", ";", "\\\\", "var", "s", "=", "t", ".", "charCodeAt", "(", "0", ")", ".", "toString", "(", "16", ")", ";", "for", "(", "var", "i", "=", "s", ".", "length", ";", "i", "<", "4", ";", "i", "++", ")", "sb", "+=", "'0'", ";", "sb", "+=", "s", ";", "}" ]
given a character, return a string like "\\uxxxx", with its code in hex
[ "given", "a", "character", "return", "a", "string", "like", "\\\\", "uxxxx", "with", "its", "code", "in", "hex" ]
c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a
https://github.com/ksanaforge/tibetan/blob/c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a/wylie.js#L1533-L1542
train
ksanaforge/tibetan
wylie.js
putStackTogether
function putStackTogether(st) { var out = ''; // put the main elements together... stacked with "+" unless it's a regular stack if (tib_stack(st.cons_str)) { out += st.stack.join(""); } else out += (st.cons_str); // caret (tsa-phru) goes here as per some (halfway broken) Unicode specs... if (st.caret) out += ("^"); // vowels... if (st.vowels.length > 0) { out += st.vowels.join("+"); } else if (!st.prefix && !st.suffix && !st.suff2 && (st.cons_str.length == 0 || st.cons_str.charAt(st.cons_str.length - 1) != 'a')) { out += "a" } // final stuff out += st.finals.join(""); if (st.dot) out += "."; return out; }
javascript
function putStackTogether(st) { var out = ''; // put the main elements together... stacked with "+" unless it's a regular stack if (tib_stack(st.cons_str)) { out += st.stack.join(""); } else out += (st.cons_str); // caret (tsa-phru) goes here as per some (halfway broken) Unicode specs... if (st.caret) out += ("^"); // vowels... if (st.vowels.length > 0) { out += st.vowels.join("+"); } else if (!st.prefix && !st.suffix && !st.suff2 && (st.cons_str.length == 0 || st.cons_str.charAt(st.cons_str.length - 1) != 'a')) { out += "a" } // final stuff out += st.finals.join(""); if (st.dot) out += "."; return out; }
[ "function", "putStackTogether", "(", "st", ")", "{", "var", "out", "=", "''", ";", "if", "(", "tib_stack", "(", "st", ".", "cons_str", ")", ")", "{", "out", "+=", "st", ".", "stack", ".", "join", "(", "\"\"", ")", ";", "}", "else", "out", "+=", "(", "st", ".", "cons_str", ")", ";", "if", "(", "st", ".", "caret", ")", "out", "+=", "(", "\"^\"", ")", ";", "if", "(", "st", ".", "vowels", ".", "length", ">", "0", ")", "{", "out", "+=", "st", ".", "vowels", ".", "join", "(", "\"+\"", ")", ";", "}", "else", "if", "(", "!", "st", ".", "prefix", "&&", "!", "st", ".", "suffix", "&&", "!", "st", ".", "suff2", "&&", "(", "st", ".", "cons_str", ".", "length", "==", "0", "||", "st", ".", "cons_str", ".", "charAt", "(", "st", ".", "cons_str", ".", "length", "-", "1", ")", "!=", "'a'", ")", ")", "{", "out", "+=", "\"a\"", "}", "out", "+=", "st", ".", "finals", ".", "join", "(", "\"\"", ")", ";", "if", "(", "st", ".", "dot", ")", "out", "+=", "\".\"", ";", "return", "out", ";", "}" ]
Puts an analyzed stack together into Wylie output, adding an implicit "a" if needed.
[ "Puts", "an", "analyzed", "stack", "together", "into", "Wylie", "output", "adding", "an", "implicit", "a", "if", "needed", "." ]
c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a
https://github.com/ksanaforge/tibetan/blob/c7bfd70c9e83d9a1f1a57bd545f353a43a0a226a/wylie.js#L1722-L1741
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.js
error
function error(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown); throw new Error(msg); }
javascript
function error(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown); throw new Error(msg); }
[ "function", "error", "(", "msg", ")", "{", "if", "(", "PDFJS", ".", "verbosity", ">=", "PDFJS", ".", "VERBOSITY_LEVELS", ".", "errors", ")", "{", "console", ".", "log", "(", "'Error: '", "+", "msg", ")", ";", "console", ".", "log", "(", "backtrace", "(", ")", ")", ";", "}", "UnsupportedManager", ".", "notify", "(", "UNSUPPORTED_FEATURES", ".", "unknown", ")", ";", "throw", "new", "Error", "(", "msg", ")", ";", "}" ]
Fatal errors that should trigger the fallback UI and halt execution by throwing an exception.
[ "Fatal", "errors", "that", "should", "trigger", "the", "fallback", "UI", "and", "halt", "execution", "by", "throwing", "an", "exception", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.js#L241-L248
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.js
PDFPageProxy_render
function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingDestroy = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingDestroy) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingDestroy = true; } self._tryDestroy(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }
javascript
function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingDestroy = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingDestroy) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingDestroy = true; } self._tryDestroy(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }
[ "function", "PDFPageProxy_render", "(", "params", ")", "{", "var", "stats", "=", "this", ".", "stats", ";", "stats", ".", "time", "(", "'Overall'", ")", ";", "this", ".", "pendingDestroy", "=", "false", ";", "var", "renderingIntent", "=", "(", "params", ".", "intent", "===", "'print'", "?", "'print'", ":", "'display'", ")", ";", "if", "(", "!", "this", ".", "intentStates", "[", "renderingIntent", "]", ")", "{", "this", ".", "intentStates", "[", "renderingIntent", "]", "=", "{", "}", ";", "}", "var", "intentState", "=", "this", ".", "intentStates", "[", "renderingIntent", "]", ";", "if", "(", "!", "intentState", ".", "displayReadyCapability", ")", "{", "intentState", ".", "receivingOperatorList", "=", "true", ";", "intentState", ".", "displayReadyCapability", "=", "createPromiseCapability", "(", ")", ";", "intentState", ".", "operatorList", "=", "{", "fnArray", ":", "[", "]", ",", "argsArray", ":", "[", "]", ",", "lastChunk", ":", "false", "}", ";", "this", ".", "stats", ".", "time", "(", "'Page Request'", ")", ";", "this", ".", "transport", ".", "messageHandler", ".", "send", "(", "'RenderPageRequest'", ",", "{", "pageIndex", ":", "this", ".", "pageNumber", "-", "1", ",", "intent", ":", "renderingIntent", "}", ")", ";", "}", "var", "internalRenderTask", "=", "new", "InternalRenderTask", "(", "complete", ",", "params", ",", "this", ".", "objs", ",", "this", ".", "commonObjs", ",", "intentState", ".", "operatorList", ",", "this", ".", "pageNumber", ")", ";", "internalRenderTask", ".", "useRequestAnimationFrame", "=", "renderingIntent", "!==", "'print'", ";", "if", "(", "!", "intentState", ".", "renderTasks", ")", "{", "intentState", ".", "renderTasks", "=", "[", "]", ";", "}", "intentState", ".", "renderTasks", ".", "push", "(", "internalRenderTask", ")", ";", "var", "renderTask", "=", "internalRenderTask", ".", "task", ";", "if", "(", "params", ".", "continueCallback", ")", "{", "renderTask", ".", "onContinue", "=", "params", ".", "continueCallback", ";", "}", "var", "self", "=", "this", ";", "intentState", ".", "displayReadyCapability", ".", "promise", ".", "then", "(", "function", "pageDisplayReadyPromise", "(", "transparency", ")", "{", "if", "(", "self", ".", "pendingDestroy", ")", "{", "complete", "(", ")", ";", "return", ";", "}", "stats", ".", "time", "(", "'Rendering'", ")", ";", "internalRenderTask", ".", "initalizeGraphics", "(", "transparency", ")", ";", "internalRenderTask", ".", "operatorListChanged", "(", ")", ";", "}", ",", "function", "pageDisplayReadPromiseError", "(", "reason", ")", "{", "complete", "(", "reason", ")", ";", "}", ")", ";", "function", "complete", "(", "error", ")", "{", "var", "i", "=", "intentState", ".", "renderTasks", ".", "indexOf", "(", "internalRenderTask", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "intentState", ".", "renderTasks", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "if", "(", "self", ".", "cleanupAfterRender", ")", "{", "self", ".", "pendingDestroy", "=", "true", ";", "}", "self", ".", "_tryDestroy", "(", ")", ";", "if", "(", "error", ")", "{", "internalRenderTask", ".", "capability", ".", "reject", "(", "error", ")", ";", "}", "else", "{", "internalRenderTask", ".", "capability", ".", "resolve", "(", ")", ";", "}", "stats", ".", "timeEnd", "(", "'Rendering'", ")", ";", "stats", ".", "timeEnd", "(", "'Overall'", ")", ";", "}", "return", "renderTask", ";", "}" ]
Begins the process of rendering a page to the desired context. @param {RenderParameters} params Page render parameters. @return {RenderTask} An object that contains the promise, which is resolved when the page finishes rendering.
[ "Begins", "the", "process", "of", "rendering", "a", "page", "to", "the", "desired", "context", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.js#L2291-L2378
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.js
PDFPageProxy__destroy
function PDFPageProxy__destroy() { if (!this.pendingDestroy || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingDestroy = false; }
javascript
function PDFPageProxy__destroy() { if (!this.pendingDestroy || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingDestroy = false; }
[ "function", "PDFPageProxy__destroy", "(", ")", "{", "if", "(", "!", "this", ".", "pendingDestroy", "||", "Object", ".", "keys", "(", "this", ".", "intentStates", ")", ".", "some", "(", "function", "(", "intent", ")", "{", "var", "intentState", "=", "this", ".", "intentStates", "[", "intent", "]", ";", "return", "(", "intentState", ".", "renderTasks", ".", "length", "!==", "0", "||", "intentState", ".", "receivingOperatorList", ")", ";", "}", ",", "this", ")", ")", "{", "return", ";", "}", "Object", ".", "keys", "(", "this", ".", "intentStates", ")", ".", "forEach", "(", "function", "(", "intent", ")", "{", "delete", "this", ".", "intentStates", "[", "intent", "]", ";", "}", ",", "this", ")", ";", "this", ".", "objs", ".", "clear", "(", ")", ";", "this", ".", "annotationsPromise", "=", "null", ";", "this", ".", "pendingDestroy", "=", "false", ";", "}" ]
For internal use only. Attempts to clean up if rendering is in a state where that's possible. @ignore
[ "For", "internal", "use", "only", ".", "Attempts", "to", "clean", "up", "if", "rendering", "is", "in", "a", "state", "where", "that", "s", "possible", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.js#L2439-L2455
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.js
PDFPageProxy_renderPageChunk
function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryDestroy(); } }
javascript
function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryDestroy(); } }
[ "function", "PDFPageProxy_renderPageChunk", "(", "operatorListChunk", ",", "intent", ")", "{", "var", "intentState", "=", "this", ".", "intentStates", "[", "intent", "]", ";", "var", "i", ",", "ii", ";", "for", "(", "i", "=", "0", ",", "ii", "=", "operatorListChunk", ".", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "{", "intentState", ".", "operatorList", ".", "fnArray", ".", "push", "(", "operatorListChunk", ".", "fnArray", "[", "i", "]", ")", ";", "intentState", ".", "operatorList", ".", "argsArray", ".", "push", "(", "operatorListChunk", ".", "argsArray", "[", "i", "]", ")", ";", "}", "intentState", ".", "operatorList", ".", "lastChunk", "=", "operatorListChunk", ".", "lastChunk", ";", "for", "(", "i", "=", "0", ";", "i", "<", "intentState", ".", "renderTasks", ".", "length", ";", "i", "++", ")", "{", "intentState", ".", "renderTasks", "[", "i", "]", ".", "operatorListChanged", "(", ")", ";", "}", "if", "(", "operatorListChunk", ".", "lastChunk", ")", "{", "intentState", ".", "receivingOperatorList", "=", "false", ";", "this", ".", "_tryDestroy", "(", ")", ";", "}", "}" ]
For internal use only. @ignore
[ "For", "internal", "use", "only", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.js#L2473-L2494
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.js
PDFObjects_getData
function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }
javascript
function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }
[ "function", "PDFObjects_getData", "(", "objId", ")", "{", "var", "objs", "=", "this", ".", "objs", ";", "if", "(", "!", "objs", "[", "objId", "]", "||", "!", "objs", "[", "objId", "]", ".", "resolved", ")", "{", "return", "null", ";", "}", "else", "{", "return", "objs", "[", "objId", "]", ".", "data", ";", "}", "}" ]
Returns the data of `objId` if object exists, null otherwise.
[ "Returns", "the", "data", "of", "objId", "if", "object", "exists", "null", "otherwise", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.js#L3050-L3057
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.js
pf
function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); }
javascript
function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); }
[ "function", "pf", "(", "value", ")", "{", "if", "(", "value", "===", "(", "value", "|", "0", ")", ")", "{", "return", "value", ".", "toString", "(", ")", ";", "}", "var", "s", "=", "value", ".", "toFixed", "(", "10", ")", ";", "var", "i", "=", "s", ".", "length", "-", "1", ";", "if", "(", "s", "[", "i", "]", "!==", "'0'", ")", "{", "return", "s", ";", "}", "do", "{", "i", "--", ";", "}", "while", "(", "s", "[", "i", "]", "===", "'0'", ")", ";", "return", "s", ".", "substr", "(", "0", ",", "s", "[", "i", "]", "===", "'.'", "?", "i", ":", "i", "+", "1", ")", ";", "}" ]
Formats float number. @param value {number} number to format. @returns {string}
[ "Formats", "float", "number", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.js#L7131-L7145
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.js
pm
function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; }
javascript
function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; }
[ "function", "pm", "(", "m", ")", "{", "if", "(", "m", "[", "4", "]", "===", "0", "&&", "m", "[", "5", "]", "===", "0", ")", "{", "if", "(", "m", "[", "1", "]", "===", "0", "&&", "m", "[", "2", "]", "===", "0", ")", "{", "if", "(", "m", "[", "0", "]", "===", "1", "&&", "m", "[", "3", "]", "===", "1", ")", "{", "return", "''", ";", "}", "return", "'scale('", "+", "pf", "(", "m", "[", "0", "]", ")", "+", "' '", "+", "pf", "(", "m", "[", "3", "]", ")", "+", "')'", ";", "}", "if", "(", "m", "[", "0", "]", "===", "m", "[", "3", "]", "&&", "m", "[", "1", "]", "===", "-", "m", "[", "2", "]", ")", "{", "var", "a", "=", "Math", ".", "acos", "(", "m", "[", "0", "]", ")", "*", "180", "/", "Math", ".", "PI", ";", "return", "'rotate('", "+", "pf", "(", "a", ")", "+", "')'", ";", "}", "}", "else", "{", "if", "(", "m", "[", "0", "]", "===", "1", "&&", "m", "[", "1", "]", "===", "0", "&&", "m", "[", "2", "]", "===", "0", "&&", "m", "[", "3", "]", "===", "1", ")", "{", "return", "'translate('", "+", "pf", "(", "m", "[", "4", "]", ")", "+", "' '", "+", "pf", "(", "m", "[", "5", "]", ")", "+", "')'", ";", "}", "}", "return", "'matrix('", "+", "pf", "(", "m", "[", "0", "]", ")", "+", "' '", "+", "pf", "(", "m", "[", "1", "]", ")", "+", "' '", "+", "pf", "(", "m", "[", "2", "]", ")", "+", "' '", "+", "pf", "(", "m", "[", "3", "]", ")", "+", "' '", "+", "pf", "(", "m", "[", "4", "]", ")", "+", "' '", "+", "pf", "(", "m", "[", "5", "]", ")", "+", "')'", ";", "}" ]
Formats transform matrix. The standard rotation, scale and translate matrices are replaced by their shorter forms, and for identity matrix returns empty string to save the memory. @param m {Array} matrix to format. @returns {string}
[ "Formats", "transform", "matrix", ".", "The", "standard", "rotation", "scale", "and", "translate", "matrices", "are", "replaced", "by", "their", "shorter", "forms", "and", "for", "identity", "matrix", "returns", "empty", "string", "to", "save", "the", "memory", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.js#L7154-L7173
train
taskcluster/taskcluster-client
bin/update-apis.js
function() { // Path to apis.js file var apis_js = path.join(__dirname, '../src', 'apis.js'); // Create content // Use json-stable-stringify rather than JSON.stringify to guarantee // consistent ordering (see http://bugzil.la/1200519) var content = "/* eslint-disable */\nmodule.exports = " + stringify(apis, { space: ' ' }) + ";"; fs.writeFileSync(apis_js, content, {encoding: 'utf-8'}); }
javascript
function() { // Path to apis.js file var apis_js = path.join(__dirname, '../src', 'apis.js'); // Create content // Use json-stable-stringify rather than JSON.stringify to guarantee // consistent ordering (see http://bugzil.la/1200519) var content = "/* eslint-disable */\nmodule.exports = " + stringify(apis, { space: ' ' }) + ";"; fs.writeFileSync(apis_js, content, {encoding: 'utf-8'}); }
[ "function", "(", ")", "{", "var", "apis_js", "=", "path", ".", "join", "(", "__dirname", ",", "'../src'", ",", "'apis.js'", ")", ";", "var", "content", "=", "\"/* eslint-disable */\\nmodule.exports = \"", "+", "\\n", "+", "stringify", "(", "apis", ",", "{", "space", ":", "' '", "}", ")", ";", "\";\"", "}" ]
Save APIs to apis.js
[ "Save", "APIs", "to", "apis", ".", "js" ]
02d3efff9fdd046daa75b95e0f6a8f957c1abb09
https://github.com/taskcluster/taskcluster-client/blob/02d3efff9fdd046daa75b95e0f6a8f957c1abb09/bin/update-apis.js#L19-L29
train