id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
31,000
observing/square
lib/watch.js
getPath
function getPath(path, callback) { fs.lstat(path, function(err, stats) { if(err) return callback(err); // Check if it's a link if(stats.isSymbolicLink()) fs.readlink(path, callback); callback(err, path); }); }
javascript
function getPath(path, callback) { fs.lstat(path, function(err, stats) { if(err) return callback(err); // Check if it's a link if(stats.isSymbolicLink()) fs.readlink(path, callback); callback(err, path); }); }
[ "function", "getPath", "(", "path", ",", "callback", ")", "{", "fs", ".", "lstat", "(", "path", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "// Check if it's a link", "if", "...
Helper for finder to also handle symlinks. @param {String} path @param {Function} callback @api private
[ "Helper", "for", "finder", "to", "also", "handle", "symlinks", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/watch.js#L48-L57
31,001
observing/square
lib/watch.js
filter
function filter(location) { var file = path.basename(location) , vim = file.charAt(file.length - 1) === '~' , extension = path.extname(location).slice(1); // filter out the duplicates if (~changes.indexOf(location) || vim) return; changes.push(location); process.nextTick(limited); }
javascript
function filter(location) { var file = path.basename(location) , vim = file.charAt(file.length - 1) === '~' , extension = path.extname(location).slice(1); // filter out the duplicates if (~changes.indexOf(location) || vim) return; changes.push(location); process.nextTick(limited); }
[ "function", "filter", "(", "location", ")", "{", "var", "file", "=", "path", ".", "basename", "(", "location", ")", ",", "vim", "=", "file", ".", "charAt", "(", "file", ".", "length", "-", "1", ")", "===", "'~'", ",", "extension", "=", "path", ".",...
Filter out the bad files and try to remove some noise. For example vim generates some silly swap files in directories or other silly thumb files The this context of this file will be set the current directory that we are watching. @param {String} file @api private
[ "Filter", "out", "the", "bad", "files", "and", "try", "to", "remove", "some", "noise", ".", "For", "example", "vim", "generates", "some", "silly", "swap", "files", "in", "directories", "or", "other", "silly", "thumb", "files" ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/lib/watch.js#L195-L205
31,002
observing/square
plugins/update.js
done
function done(err, content) { if (err) return cb(err); var code = JSON.parse(self.square.package.source) , current = bundle.version || self.version(bundle.meta.content) , source; code.bundle[key].version = version; bundle.version = version; bundle.content = content; // now that we have updated the shizzle, we can write a new file // also update the old source with the new version source = JSON.stringify(code, null, 2); self.square.package.source = source; try { async.parallel([ async.apply(fs.writeFile, self.square.package.location, source) , async.apply(fs.writeFile, bundle.meta.location, content) ], function (err, results) { self.square.logger.notice( 'sucessfully updated %s from version %s to %s' , key , current.grey , version.green ); cb(err); }); } catch (e) { err = e; } }
javascript
function done(err, content) { if (err) return cb(err); var code = JSON.parse(self.square.package.source) , current = bundle.version || self.version(bundle.meta.content) , source; code.bundle[key].version = version; bundle.version = version; bundle.content = content; // now that we have updated the shizzle, we can write a new file // also update the old source with the new version source = JSON.stringify(code, null, 2); self.square.package.source = source; try { async.parallel([ async.apply(fs.writeFile, self.square.package.location, source) , async.apply(fs.writeFile, bundle.meta.location, content) ], function (err, results) { self.square.logger.notice( 'sucessfully updated %s from version %s to %s' , key , current.grey , version.green ); cb(err); }); } catch (e) { err = e; } }
[ "function", "done", "(", "err", ",", "content", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "var", "code", "=", "JSON", ".", "parse", "(", "self", ".", "square", ".", "package", ".", "source", ")", ",", "current", "=", ...
Handle file upgrades. @param {Mixed} err @param {String} content @api private
[ "Handle", "file", "upgrades", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/update.js#L156-L187
31,003
observing/square
plugins/lib/child.js
compile
function compile (extension, content, options, fn) { // allow optional options argument if (_.isFunction(options)) { fn = options; options = {}; } var config = _.clone(compile.configuration) , args = flags.slice(0) , buffer = '' , errors = '' , compressor; if (compile.configuration.type) { config.type = extension; } // generate the --key value options, both the key and the value should added // seperately to the `args` array or the child_process will chocke. Object.keys(config).filter(function filter (option) { return config[option]; }).forEach(function format (option) { var bool = _.isBoolean(config[option]); if (!bool || config[option]) { args.push('--' + option); if (!bool) args.push(config[option]); } }); // apply the configuration _.extend(config, options); // spawn the shit and set the correct encoding compressor = spawn(type, args); compressor.stdout.setEncoding('utf8'); compressor.stderr.setEncoding('utf8'); /** * Buffer up the results so we can concat them once the compression is * finished. * * @param {Buffer} chunk * @api private */ compressor.stdout.on('data', function data (chunk) { buffer += chunk; }); compressor.stderr.on('data', function data (err) { errors += err; }); /** * The compressor has finished can we now process the data and see if it was * a success. * * @param {Number} code * @api private */ compressor.on('close', function close (code) { // invalid states if (errors.length) return fn(new Error(errors)); if (code !== 0) return fn(new Error('process exited with code ' + code)); if (!buffer.length) return fn(new Error('no data returned ' + type + args)); // correctly processed the data fn(null, buffer); }); // write out the content that needs to be minified compressor.stdin.end(content); }
javascript
function compile (extension, content, options, fn) { // allow optional options argument if (_.isFunction(options)) { fn = options; options = {}; } var config = _.clone(compile.configuration) , args = flags.slice(0) , buffer = '' , errors = '' , compressor; if (compile.configuration.type) { config.type = extension; } // generate the --key value options, both the key and the value should added // seperately to the `args` array or the child_process will chocke. Object.keys(config).filter(function filter (option) { return config[option]; }).forEach(function format (option) { var bool = _.isBoolean(config[option]); if (!bool || config[option]) { args.push('--' + option); if (!bool) args.push(config[option]); } }); // apply the configuration _.extend(config, options); // spawn the shit and set the correct encoding compressor = spawn(type, args); compressor.stdout.setEncoding('utf8'); compressor.stderr.setEncoding('utf8'); /** * Buffer up the results so we can concat them once the compression is * finished. * * @param {Buffer} chunk * @api private */ compressor.stdout.on('data', function data (chunk) { buffer += chunk; }); compressor.stderr.on('data', function data (err) { errors += err; }); /** * The compressor has finished can we now process the data and see if it was * a success. * * @param {Number} code * @api private */ compressor.on('close', function close (code) { // invalid states if (errors.length) return fn(new Error(errors)); if (code !== 0) return fn(new Error('process exited with code ' + code)); if (!buffer.length) return fn(new Error('no data returned ' + type + args)); // correctly processed the data fn(null, buffer); }); // write out the content that needs to be minified compressor.stdin.end(content); }
[ "function", "compile", "(", "extension", ",", "content", ",", "options", ",", "fn", ")", "{", "// allow optional options argument", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "fn", "=", "options", ";", "options", "=", "{", "}", ";"...
Delegrate all the hard core processing to the vendor file. @param {String} extension file extenstion @param {String} content file contents @param {Object} options options @param {Function} fn error first callback @api public
[ "Delegrate", "all", "the", "hard", "core", "processing", "to", "the", "vendor", "file", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lib/child.js#L31-L105
31,004
observing/square
plugins/lib/crusher.js
message
function message(worker, task) { var callback = worker.queue[task.id] , err; // Rebuild the Error object so we can pass it to our callbacks if (task.err) { err = new Error(task.err.message); err.stack = task.err.stack; } // Kill the whole fucking system, we are in a fucked up state and should die // badly, so just throw something and have the process.uncaughtException // handle it. if (!callback) { if (err) console.error(err); console.error(task); throw new Error('Unable to process message from worker, can\'t locate the callback!'); } callback(err, task); delete worker.queue[task.id]; }
javascript
function message(worker, task) { var callback = worker.queue[task.id] , err; // Rebuild the Error object so we can pass it to our callbacks if (task.err) { err = new Error(task.err.message); err.stack = task.err.stack; } // Kill the whole fucking system, we are in a fucked up state and should die // badly, so just throw something and have the process.uncaughtException // handle it. if (!callback) { if (err) console.error(err); console.error(task); throw new Error('Unable to process message from worker, can\'t locate the callback!'); } callback(err, task); delete worker.queue[task.id]; }
[ "function", "message", "(", "worker", ",", "task", ")", "{", "var", "callback", "=", "worker", ".", "queue", "[", "task", ".", "id", "]", ",", "err", ";", "// Rebuild the Error object so we can pass it to our callbacks", "if", "(", "task", ".", "err", ")", "...
Message handler for the workers. @param {Worker} worker @param {Error} err @param {Object} task the updated task @api private
[ "Message", "handler", "for", "the", "workers", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lib/crusher.js#L264-L285
31,005
observing/square
plugin.js
Plugin
function Plugin(square, collection) { if (!(this instanceof Plugin)) return new Plugin(square, collection); if (!square) throw new Error('Missing square instance'); if (!collection) throw new Error('Missing collection'); var self = this; this.square = square; // Reference to the current square instance. this.async = async; // Handle async operation. this._ = _; // Utilities. this.logger = {}; // Our logging utility. this.collection = collection; // Reference to the original collection. // Provide a default namespace to the logging method, we are going to prefix // it with the plugin's name which will help with the debug ability of this // module. Object.keys(square.logger.levels).forEach(function generate(level) { self.logger[level] = square.logger[level].bind( square.logger , '[plugin::'+ self.id +']' ); }); // Merge the given collection with the plugin, but don't override the default // values. Object.keys(collection).forEach(function each(key) { self[key] = collection[key]; }); // Force an async nature of the plugin interface, this also allows us to // attach or listen to methods after we have constructed the plugin. process.nextTick(this.configure.bind(this)); }
javascript
function Plugin(square, collection) { if (!(this instanceof Plugin)) return new Plugin(square, collection); if (!square) throw new Error('Missing square instance'); if (!collection) throw new Error('Missing collection'); var self = this; this.square = square; // Reference to the current square instance. this.async = async; // Handle async operation. this._ = _; // Utilities. this.logger = {}; // Our logging utility. this.collection = collection; // Reference to the original collection. // Provide a default namespace to the logging method, we are going to prefix // it with the plugin's name which will help with the debug ability of this // module. Object.keys(square.logger.levels).forEach(function generate(level) { self.logger[level] = square.logger[level].bind( square.logger , '[plugin::'+ self.id +']' ); }); // Merge the given collection with the plugin, but don't override the default // values. Object.keys(collection).forEach(function each(key) { self[key] = collection[key]; }); // Force an async nature of the plugin interface, this also allows us to // attach or listen to methods after we have constructed the plugin. process.nextTick(this.configure.bind(this)); }
[ "function", "Plugin", "(", "square", ",", "collection", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Plugin", ")", ")", "return", "new", "Plugin", "(", "square", ",", "collection", ")", ";", "if", "(", "!", "square", ")", "throw", "new", "Er...
Plugin interface for square. @constructor @param {Square} square @param {Object} collection @api public
[ "Plugin", "interface", "for", "square", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugin.js#L32-L64
31,006
observing/square
plugin.js
configure
function configure() { var pkg = this.square.package , configuration = pkg.configuration , type = this.type || Plugin.modifier , self = this , load = []; // Check for the distribution and if it should accept the given extension, // extend self with the context of the plugin. if (!~type.indexOf('once') && (!this.distributable() || !this.accepted())) { this.logger.debug( 'disregarding this plugin for extension: '+ this.extension +', distribution: '+ this.distribution ); return this.emit('disregard'); } // Check if there are any configuration options in the package. if (_.isObject(pkg.plugins) && this.id in pkg.plugins) { this.merge(this, pkg.plugins[this.id]); } // Merge in the plugin configuration. if ( configuration && _.isObject(configuration.plugins) && this.id in configuration.plugins ) { this.merge(this, configuration.plugins[this.id]); } // Check if the bundle it self also had specific configurations for this // plugin. if (this.id in this && _.isObject(this[this.id])) { this.merge(this, this[this.id]); } // Ensure that our requires is an array, before we continue if (!Array.isArray(this.requires)) this.requires = [this.requires]; // Check if we need to lazy load any dependencies if (this.requires && this.requires.length) { load = this.requires.map(function (file) { if (typeof file !== 'object') return file; if (!('extension' in file)) return file.name || file; if (file.extension === self.extension) return file.name || file; return undefined; }).filter(Boolean); // Only get existing files // Only fetch shizzle when we actually have shizzle to fetch here if (load.length) return canihaz.apply(canihaz, load.concat(function canihaz(err) { if (err) return self.emit('error', err); // Add all the libraries to the context, the `canihaz#all` returns an // error first, and then all libraries it installed or required in the // order as given to it, which is in our case the `this.requires` order. Array.prototype.slice.call(arguments, 1).forEach(function (lib, index) { self[load[index]] = lib; }); // We are now fully initialized. if (self.initialize) self.initialize(); })); } // We are now fully initialized. if (self.initialize) self.initialize(); }
javascript
function configure() { var pkg = this.square.package , configuration = pkg.configuration , type = this.type || Plugin.modifier , self = this , load = []; // Check for the distribution and if it should accept the given extension, // extend self with the context of the plugin. if (!~type.indexOf('once') && (!this.distributable() || !this.accepted())) { this.logger.debug( 'disregarding this plugin for extension: '+ this.extension +', distribution: '+ this.distribution ); return this.emit('disregard'); } // Check if there are any configuration options in the package. if (_.isObject(pkg.plugins) && this.id in pkg.plugins) { this.merge(this, pkg.plugins[this.id]); } // Merge in the plugin configuration. if ( configuration && _.isObject(configuration.plugins) && this.id in configuration.plugins ) { this.merge(this, configuration.plugins[this.id]); } // Check if the bundle it self also had specific configurations for this // plugin. if (this.id in this && _.isObject(this[this.id])) { this.merge(this, this[this.id]); } // Ensure that our requires is an array, before we continue if (!Array.isArray(this.requires)) this.requires = [this.requires]; // Check if we need to lazy load any dependencies if (this.requires && this.requires.length) { load = this.requires.map(function (file) { if (typeof file !== 'object') return file; if (!('extension' in file)) return file.name || file; if (file.extension === self.extension) return file.name || file; return undefined; }).filter(Boolean); // Only get existing files // Only fetch shizzle when we actually have shizzle to fetch here if (load.length) return canihaz.apply(canihaz, load.concat(function canihaz(err) { if (err) return self.emit('error', err); // Add all the libraries to the context, the `canihaz#all` returns an // error first, and then all libraries it installed or required in the // order as given to it, which is in our case the `this.requires` order. Array.prototype.slice.call(arguments, 1).forEach(function (lib, index) { self[load[index]] = lib; }); // We are now fully initialized. if (self.initialize) self.initialize(); })); } // We are now fully initialized. if (self.initialize) self.initialize(); }
[ "function", "configure", "(", ")", "{", "var", "pkg", "=", "this", ".", "square", ".", "package", ",", "configuration", "=", "pkg", ".", "configuration", ",", "type", "=", "this", ".", "type", "||", "Plugin", ".", "modifier", ",", "self", "=", "this", ...
Configure the plugin, prepare all the things. @api private
[ "Configure", "the", "plugin", "prepare", "all", "the", "things", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugin.js#L128-L196
31,007
observing/square
plugins/lint.js
parser
function parser (content, options, fn) { var jshintrc = path.join(process.env.HOME || process.env.USERPROFILE, '.jshintrc') , jshintninja = configurator(jshintrc) , config = options.jshint; // extend all the things config = _.extend(config, jshintninja); canihaz.jshint(function lazyload (err, jshint) { if (err) return fn(err); var validates = jshint.JSHINT(content, config) , errors; if (!validates) errors = formatters.js(jshint.JSHINT.errors); fn(null, errors); }); }
javascript
function parser (content, options, fn) { var jshintrc = path.join(process.env.HOME || process.env.USERPROFILE, '.jshintrc') , jshintninja = configurator(jshintrc) , config = options.jshint; // extend all the things config = _.extend(config, jshintninja); canihaz.jshint(function lazyload (err, jshint) { if (err) return fn(err); var validates = jshint.JSHINT(content, config) , errors; if (!validates) errors = formatters.js(jshint.JSHINT.errors); fn(null, errors); }); }
[ "function", "parser", "(", "content", ",", "options", ",", "fn", ")", "{", "var", "jshintrc", "=", "path", ".", "join", "(", "process", ".", "env", ".", "HOME", "||", "process", ".", "env", ".", "USERPROFILE", ",", "'.jshintrc'", ")", ",", "jshintninja...
JSHint the content @param {String} content @param {Object} options @param {Function} fn @api private
[ "JSHint", "the", "content" ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lint.js#L127-L144
31,008
observing/square
plugins/lint.js
formatter
function formatter (fail) { return fail.map(function oops (err) { return { line: err.line , column: err.character , message: err.reason , ref: err }; }); }
javascript
function formatter (fail) { return fail.map(function oops (err) { return { line: err.line , column: err.character , message: err.reason , ref: err }; }); }
[ "function", "formatter", "(", "fail", ")", "{", "return", "fail", ".", "map", "(", "function", "oops", "(", "err", ")", "{", "return", "{", "line", ":", "err", ".", "line", ",", "column", ":", "err", ".", "character", ",", "message", ":", "err", "....
Format the output of the jshint tool. @param {Array} fail @returns {Array} @api private
[ "Format", "the", "output", "of", "the", "jshint", "tool", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lint.js#L192-L201
31,009
observing/square
plugins/lint.js
function (file, errors, options) { var reports = [] , content = file.content.split('\n'); errors.forEach(function error (err) { // some linters don't return the location -_- if (!err.line) return reports.push(err.message.grey, ''); var start = err.line > 3 ? err.line - 3 : 0 , stop = err.line + 2 , range = content.slice(start, stop) , numbers = _.range(start + 1, stop + 1) , len = stop.toString().length; reports.push('Lint error: ' + err.line + ' col ' + err.column); range.map(function reformat (line) { var lineno = numbers.shift() , offender = lineno === err.line , inline = /\'[^\']+?\'/ , slice; // this is the actual line with the error, so we should start finding // what the error is and how we could highlight it in the output if (offender) { if (line.length < err.column) { // we are missing something at the end of the line.. so add a red // square line += ' '.inverse.red; } else { // we have a direct match on a statement if (inline.test(err.message)) { slice = err.message.match(inline)[0].replace(/\'/g, ''); } else { // it's happening in the center of things, so we can start // coloring inside the shizzle slice = line.slice(err.column - 1); } line = line.replace(slice, slice.inverse.red); } } reports.push(' ' + pad(lineno, len) + ' | ' + line); }); reports.push(''); reports.push(err.message.grey); reports.push(''); }); // output the shizzle reports.forEach(function output (line) { this.logger.error(line); }.bind(this)); }
javascript
function (file, errors, options) { var reports = [] , content = file.content.split('\n'); errors.forEach(function error (err) { // some linters don't return the location -_- if (!err.line) return reports.push(err.message.grey, ''); var start = err.line > 3 ? err.line - 3 : 0 , stop = err.line + 2 , range = content.slice(start, stop) , numbers = _.range(start + 1, stop + 1) , len = stop.toString().length; reports.push('Lint error: ' + err.line + ' col ' + err.column); range.map(function reformat (line) { var lineno = numbers.shift() , offender = lineno === err.line , inline = /\'[^\']+?\'/ , slice; // this is the actual line with the error, so we should start finding // what the error is and how we could highlight it in the output if (offender) { if (line.length < err.column) { // we are missing something at the end of the line.. so add a red // square line += ' '.inverse.red; } else { // we have a direct match on a statement if (inline.test(err.message)) { slice = err.message.match(inline)[0].replace(/\'/g, ''); } else { // it's happening in the center of things, so we can start // coloring inside the shizzle slice = line.slice(err.column - 1); } line = line.replace(slice, slice.inverse.red); } } reports.push(' ' + pad(lineno, len) + ' | ' + line); }); reports.push(''); reports.push(err.message.grey); reports.push(''); }); // output the shizzle reports.forEach(function output (line) { this.logger.error(line); }.bind(this)); }
[ "function", "(", "file", ",", "errors", ",", "options", ")", "{", "var", "reports", "=", "[", "]", ",", "content", "=", "file", ".", "content", ".", "split", "(", "'\\n'", ")", ";", "errors", ".", "forEach", "(", "function", "error", "(", "err", ")...
Simple output of the errors in a human readable fashion. @param {Object} file @param {Array} errors @api pprivate
[ "Simple", "output", "of", "the", "errors", "in", "a", "human", "readable", "fashion", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lint.js#L238-L293
31,010
observing/square
plugins/lint.js
configurator
function configurator (location) { return !(location && fs.existsSync(location)) ? {} : JSON.parse( fs.readFileSync(location, 'UTF-8') .replace(/\/\*[\s\S]*(?:\*\/)/g, '') // removes /* comments */ .replace(/\/\/[^\n\r]*/g, '') // removes // comments ); }
javascript
function configurator (location) { return !(location && fs.existsSync(location)) ? {} : JSON.parse( fs.readFileSync(location, 'UTF-8') .replace(/\/\*[\s\S]*(?:\*\/)/g, '') // removes /* comments */ .replace(/\/\/[^\n\r]*/g, '') // removes // comments ); }
[ "function", "configurator", "(", "location", ")", "{", "return", "!", "(", "location", "&&", "fs", ".", "existsSync", "(", "location", ")", ")", "?", "{", "}", ":", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "location", ",", "'UTF-8'", ...
Simple configuration parser, which is less strict then a regular JSON parser. @param {String} path @returns {Object}
[ "Simple", "configuration", "parser", "which", "is", "less", "strict", "then", "a", "regular", "JSON", "parser", "." ]
0a801de3815526d0d5231976f666e97674312de2
https://github.com/observing/square/blob/0a801de3815526d0d5231976f666e97674312de2/plugins/lint.js#L317-L325
31,011
SilentCicero/ipfs-mini
src/index.js
createBoundary
function createBoundary(data) { while (true) { var boundary = `----IPFSMini${Math.random() * 100000}.${Math.random() * 100000}`; if (data.indexOf(boundary) === -1) { return boundary; } } }
javascript
function createBoundary(data) { while (true) { var boundary = `----IPFSMini${Math.random() * 100000}.${Math.random() * 100000}`; if (data.indexOf(boundary) === -1) { return boundary; } } }
[ "function", "createBoundary", "(", "data", ")", "{", "while", "(", "true", ")", "{", "var", "boundary", "=", "`", "${", "Math", ".", "random", "(", ")", "*", "100000", "}", "${", "Math", ".", "random", "(", ")", "*", "100000", "}", "`", ";", "if"...
creates a boundary that isn't part of the payload
[ "creates", "a", "boundary", "that", "isn", "t", "part", "of", "the", "payload" ]
8a007116995ec84e26901b6bd3eb119c6b06aca7
https://github.com/SilentCicero/ipfs-mini/blob/8a007116995ec84e26901b6bd3eb119c6b06aca7/src/index.js#L102-L109
31,012
larvit/larvitimages
index.js
returnFile
function returnFile(cb) { fs.readFile(fileToLoad, function (err, fileBuf) { if (err || ! fileBuf) { createFile(function (err) { if (err) return cb(err); returnFile(cb); }); return; } cb(null, fileBuf, fileToLoad); }); }
javascript
function returnFile(cb) { fs.readFile(fileToLoad, function (err, fileBuf) { if (err || ! fileBuf) { createFile(function (err) { if (err) return cb(err); returnFile(cb); }); return; } cb(null, fileBuf, fileToLoad); }); }
[ "function", "returnFile", "(", "cb", ")", "{", "fs", ".", "readFile", "(", "fileToLoad", ",", "function", "(", "err", ",", "fileBuf", ")", "{", "if", "(", "err", "||", "!", "fileBuf", ")", "{", "createFile", "(", "function", "(", "err", ")", "{", "...
Check if cached file exists, and if so, return it
[ "Check", "if", "cached", "file", "exists", "and", "if", "so", "return", "it" ]
6f918fc7d6e6e932fb177d9d42106fd6c3daffa1
https://github.com/larvit/larvitimages/blob/6f918fc7d6e6e932fb177d9d42106fd6c3daffa1/index.js#L340-L351
31,013
nico3333fr/van11y-accessible-modal-window-aria
dist/van11y-accessible-modal-window-aria.js
createOverlay
function createOverlay(config) { var id = MODAL_OVERLAY_ID; var overlayText = config.text || MODAL_OVERLAY_TXT; var overlayClass = config.prefixClass + MODAL_OVERLAY_CLASS_SUFFIX; var overlayBackgroundEnabled = config.backgroundEnabled === 'disabled' ? 'disabled' : 'enabled'; return '<span\n id="' + id + '"\n class="' + overlayClass + '"\n ' + MODAL_OVERLAY_BG_ENABLED_ATTR + '="' + overlayBackgroundEnabled + '"\n title="' + overlayText + '"\n >\n <span class="' + VISUALLY_HIDDEN_CLASS + '">' + overlayText + '</span>\n </span>'; }
javascript
function createOverlay(config) { var id = MODAL_OVERLAY_ID; var overlayText = config.text || MODAL_OVERLAY_TXT; var overlayClass = config.prefixClass + MODAL_OVERLAY_CLASS_SUFFIX; var overlayBackgroundEnabled = config.backgroundEnabled === 'disabled' ? 'disabled' : 'enabled'; return '<span\n id="' + id + '"\n class="' + overlayClass + '"\n ' + MODAL_OVERLAY_BG_ENABLED_ATTR + '="' + overlayBackgroundEnabled + '"\n title="' + overlayText + '"\n >\n <span class="' + VISUALLY_HIDDEN_CLASS + '">' + overlayText + '</span>\n </span>'; }
[ "function", "createOverlay", "(", "config", ")", "{", "var", "id", "=", "MODAL_OVERLAY_ID", ";", "var", "overlayText", "=", "config", ".", "text", "||", "MODAL_OVERLAY_TXT", ";", "var", "overlayClass", "=", "config", ".", "prefixClass", "+", "MODAL_OVERLAY_CLASS...
Create the template for an overlay @param {Object} config @return {String}
[ "Create", "the", "template", "for", "an", "overlay" ]
77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9
https://github.com/nico3333fr/van11y-accessible-modal-window-aria/blob/77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9/dist/van11y-accessible-modal-window-aria.js#L133-L141
31,014
nico3333fr/van11y-accessible-modal-window-aria
dist/van11y-accessible-modal-window-aria.js
createModal
function createModal(config) { var id = MODAL_JS_ID; var modalClassName = config.modalPrefixClass + MODAL_CLASS_SUFFIX; var modalClassWrapper = config.modalPrefixClass + MODAL_WRAPPER_CLASS_SUFFIX; var buttonCloseClassName = config.modalPrefixClass + MODAL_BUTTON_CLASS_SUFFIX; var buttonCloseInner = config.modalCloseImgPath ? '<img src="' + config.modalCloseImgPath + '" alt="' + config.modalCloseText + '" class="' + config.modalPrefixClass + MODAL_CLOSE_IMG_CLASS_SUFFIX + '" />' : '<span class="' + config.modalPrefixClass + MODAL_CLOSE_TEXT_CLASS_SUFFIX + '">\n ' + config.modalCloseText + '\n </span>'; var contentClassName = config.modalPrefixClass + MODAL_CONTENT_CLASS_SUFFIX; var titleClassName = config.modalPrefixClass + MODAL_TITLE_CLASS_SUFFIX; var title = config.modalTitle !== '' ? '<h1 id="' + MODAL_TITLE_ID + '" class="' + titleClassName + '">\n ' + config.modalTitle + '\n </h1>' : ''; var button_close = '<button type="button" class="' + MODAL_BUTTON_JS_CLASS + ' ' + buttonCloseClassName + '" id="' + MODAL_BUTTON_JS_ID + '" title="' + config.modalCloseTitle + '" ' + MODAL_BUTTON_CONTENT_BACK_ID + '="' + config.modalContentId + '" ' + MODAL_BUTTON_FOCUS_BACK_ID + '="' + config.modalFocusBackId + '">\n ' + buttonCloseInner + '\n </button>'; var content = config.modalText; var describedById = config.modalDescribedById !== '' ? ATTR_DESCRIBEDBY + '="' + config.modalDescribedById + '"' : ''; // If there is no content but an id we try to fetch content id if (content === '' && config.modalContentId) { var contentFromId = findById(config.modalContentId); if (contentFromId) { content = '<div id="' + MODAL_CONTENT_JS_ID + '">\n ' + contentFromId.innerHTML + '\n </div'; // we remove content from its source to avoid id duplicates, etc. contentFromId.innerHTML = ''; } } return '<dialog id="' + id + '" class="' + modalClassName + '" ' + ATTR_ROLE + '="' + MODAL_ROLE + '" ' + describedById + ' ' + ATTR_OPEN + ' ' + ATTR_LABELLEDBY + '="' + MODAL_TITLE_ID + '">\n <div role="document" class="' + modalClassWrapper + '">\n ' + button_close + '\n <div class="' + contentClassName + '">\n ' + title + '\n ' + content + '\n </div>\n </div>\n </dialog>'; }
javascript
function createModal(config) { var id = MODAL_JS_ID; var modalClassName = config.modalPrefixClass + MODAL_CLASS_SUFFIX; var modalClassWrapper = config.modalPrefixClass + MODAL_WRAPPER_CLASS_SUFFIX; var buttonCloseClassName = config.modalPrefixClass + MODAL_BUTTON_CLASS_SUFFIX; var buttonCloseInner = config.modalCloseImgPath ? '<img src="' + config.modalCloseImgPath + '" alt="' + config.modalCloseText + '" class="' + config.modalPrefixClass + MODAL_CLOSE_IMG_CLASS_SUFFIX + '" />' : '<span class="' + config.modalPrefixClass + MODAL_CLOSE_TEXT_CLASS_SUFFIX + '">\n ' + config.modalCloseText + '\n </span>'; var contentClassName = config.modalPrefixClass + MODAL_CONTENT_CLASS_SUFFIX; var titleClassName = config.modalPrefixClass + MODAL_TITLE_CLASS_SUFFIX; var title = config.modalTitle !== '' ? '<h1 id="' + MODAL_TITLE_ID + '" class="' + titleClassName + '">\n ' + config.modalTitle + '\n </h1>' : ''; var button_close = '<button type="button" class="' + MODAL_BUTTON_JS_CLASS + ' ' + buttonCloseClassName + '" id="' + MODAL_BUTTON_JS_ID + '" title="' + config.modalCloseTitle + '" ' + MODAL_BUTTON_CONTENT_BACK_ID + '="' + config.modalContentId + '" ' + MODAL_BUTTON_FOCUS_BACK_ID + '="' + config.modalFocusBackId + '">\n ' + buttonCloseInner + '\n </button>'; var content = config.modalText; var describedById = config.modalDescribedById !== '' ? ATTR_DESCRIBEDBY + '="' + config.modalDescribedById + '"' : ''; // If there is no content but an id we try to fetch content id if (content === '' && config.modalContentId) { var contentFromId = findById(config.modalContentId); if (contentFromId) { content = '<div id="' + MODAL_CONTENT_JS_ID + '">\n ' + contentFromId.innerHTML + '\n </div'; // we remove content from its source to avoid id duplicates, etc. contentFromId.innerHTML = ''; } } return '<dialog id="' + id + '" class="' + modalClassName + '" ' + ATTR_ROLE + '="' + MODAL_ROLE + '" ' + describedById + ' ' + ATTR_OPEN + ' ' + ATTR_LABELLEDBY + '="' + MODAL_TITLE_ID + '">\n <div role="document" class="' + modalClassWrapper + '">\n ' + button_close + '\n <div class="' + contentClassName + '">\n ' + title + '\n ' + content + '\n </div>\n </div>\n </dialog>'; }
[ "function", "createModal", "(", "config", ")", "{", "var", "id", "=", "MODAL_JS_ID", ";", "var", "modalClassName", "=", "config", ".", "modalPrefixClass", "+", "MODAL_CLASS_SUFFIX", ";", "var", "modalClassWrapper", "=", "config", ".", "modalPrefixClass", "+", "M...
Create the template for a modal @param {Object} config @return {String}
[ "Create", "the", "template", "for", "a", "modal" ]
77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9
https://github.com/nico3333fr/van11y-accessible-modal-window-aria/blob/77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9/dist/van11y-accessible-modal-window-aria.js#L148-L173
31,015
nico3333fr/van11y-accessible-modal-window-aria
dist/van11y-accessible-modal-window-aria.js
$listModals
function $listModals() { var node = arguments.length <= 0 || arguments[0] === undefined ? doc : arguments[0]; return [].slice.call(node.querySelectorAll('.' + MODAL_JS_CLASS)); }
javascript
function $listModals() { var node = arguments.length <= 0 || arguments[0] === undefined ? doc : arguments[0]; return [].slice.call(node.querySelectorAll('.' + MODAL_JS_CLASS)); }
[ "function", "$listModals", "(", ")", "{", "var", "node", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "doc", ":", "arguments", "[", "0", "]", ";", "return", "[", "]", ".", "slice", ".", "cal...
Find all modals inside a container @param {Node} node Default document @return {Array}
[ "Find", "all", "modals", "inside", "a", "container" ]
77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9
https://github.com/nico3333fr/van11y-accessible-modal-window-aria/blob/77b6075aa50fde0ddd41f2c59d4c0b79fb01dcd9/dist/van11y-accessible-modal-window-aria.js#L199-L202
31,016
dcodeIO/MetaScript
MetaScript.js
function(sourceOrProgram, filename) { if (!(this instanceof MetaScript)) { __version = Array.prototype.join.call(arguments, '.'); return; } // Whether constructing from a meta program or, otherwise, a source var isProgram = (sourceOrProgram+="").substring(0, 11) === 'MetaScript('; /** * Original source. * @type {?string} */ this.source = isProgram ? null : sourceOrProgram; /** * Original source file name. * @type {string} */ this.filename = filename || "main"; /** * The compiled meta program's source. * @type {string} */ this.program = isProgram ? sourceOrProgram : MetaScript.compile(sourceOrProgram); }
javascript
function(sourceOrProgram, filename) { if (!(this instanceof MetaScript)) { __version = Array.prototype.join.call(arguments, '.'); return; } // Whether constructing from a meta program or, otherwise, a source var isProgram = (sourceOrProgram+="").substring(0, 11) === 'MetaScript('; /** * Original source. * @type {?string} */ this.source = isProgram ? null : sourceOrProgram; /** * Original source file name. * @type {string} */ this.filename = filename || "main"; /** * The compiled meta program's source. * @type {string} */ this.program = isProgram ? sourceOrProgram : MetaScript.compile(sourceOrProgram); }
[ "function", "(", "sourceOrProgram", ",", "filename", ")", "{", "if", "(", "!", "(", "this", "instanceof", "MetaScript", ")", ")", "{", "__version", "=", "Array", ".", "prototype", ".", "join", ".", "call", "(", "arguments", ",", "'.'", ")", ";", "retur...
Constructs a new MetaScript instance. @exports MetaScript @param {string} sourceOrProgram Source to compile or meta program to run @param {string=} filename Source file name if known, defaults to `"main"`. @constructor
[ "Constructs", "a", "new", "MetaScript", "instance", "." ]
dc7caf5eae2f2b2467f6c6467203dbcd05f23549
https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L38-L65
31,017
dcodeIO/MetaScript
MetaScript.js
evaluate
function evaluate(expr) { if (expr.substring(0, 2) === '==') { return 'write(JSON.stringify('+expr.substring(2).trim()+'));\n'; } else if (expr.substring(0, 1) === '=') { return 'write('+expr.substring(1).trim()+');\n'; } else if (expr.substring(0, 3) === '...') { expr = '//...\n'+expr.substring(3).trim()+'\n//.'; } if (expr !== '') { return expr+'\n'; } return ''; }
javascript
function evaluate(expr) { if (expr.substring(0, 2) === '==') { return 'write(JSON.stringify('+expr.substring(2).trim()+'));\n'; } else if (expr.substring(0, 1) === '=') { return 'write('+expr.substring(1).trim()+');\n'; } else if (expr.substring(0, 3) === '...') { expr = '//...\n'+expr.substring(3).trim()+'\n//.'; } if (expr !== '') { return expr+'\n'; } return ''; }
[ "function", "evaluate", "(", "expr", ")", "{", "if", "(", "expr", ".", "substring", "(", "0", ",", "2", ")", "===", "'=='", ")", "{", "return", "'write(JSON.stringify('", "+", "expr", ".", "substring", "(", "2", ")", ".", "trim", "(", ")", "+", "')...
Evaluates a meta expression
[ "Evaluates", "a", "meta", "expression" ]
dc7caf5eae2f2b2467f6c6467203dbcd05f23549
https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L103-L115
31,018
dcodeIO/MetaScript
MetaScript.js
append
function append(source) { if (s === '') return; var index = 0, expr = /\n/g, s, match; while (match = expr.exec(source)) { s = source.substring(index, match.index+1); if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n'); index = match.index+1; } s = source.substring(index, source.length); if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n'); }
javascript
function append(source) { if (s === '') return; var index = 0, expr = /\n/g, s, match; while (match = expr.exec(source)) { s = source.substring(index, match.index+1); if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n'); index = match.index+1; } s = source.substring(index, source.length); if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n'); }
[ "function", "append", "(", "source", ")", "{", "if", "(", "s", "===", "''", ")", "return", ";", "var", "index", "=", "0", ",", "expr", "=", "/", "\\n", "/", "g", ",", "s", ",", "match", ";", "while", "(", "match", "=", "expr", ".", "exec", "(...
Appends additional content to the program, if not empty
[ "Appends", "additional", "content", "to", "the", "program", "if", "not", "empty" ]
dc7caf5eae2f2b2467f6c6467203dbcd05f23549
https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L118-L131
31,019
dcodeIO/MetaScript
MetaScript.js
indent
function indent(str, indent) { if (typeof indent === 'number') { var indent_str = ''; while (indent_str.length < indent) indent_str += ' '; indent = indent_str; } var lines = str.split(/\n/); for (var i=0; i<lines.length; i++) { if (lines[i].trim() !== '') lines[i] = indent + lines[i]; } return lines.join("\n"); }
javascript
function indent(str, indent) { if (typeof indent === 'number') { var indent_str = ''; while (indent_str.length < indent) indent_str += ' '; indent = indent_str; } var lines = str.split(/\n/); for (var i=0; i<lines.length; i++) { if (lines[i].trim() !== '') lines[i] = indent + lines[i]; } return lines.join("\n"); }
[ "function", "indent", "(", "str", ",", "indent", ")", "{", "if", "(", "typeof", "indent", "===", "'number'", ")", "{", "var", "indent_str", "=", "''", ";", "while", "(", "indent_str", ".", "length", "<", "indent", ")", "indent_str", "+=", "' '", ";", ...
Indents a block of text. @function indent @param {string} str Text to indent @param {string|number} indent Whitespace text to use for indentation or the number of whitespaces to use @returns {string} Indented text
[ "Indents", "a", "block", "of", "text", "." ]
dc7caf5eae2f2b2467f6c6467203dbcd05f23549
https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L317-L329
31,020
dcodeIO/MetaScript
MetaScript.js
include
function include(filename, absolute) { filename = absolute ? filename : __dirname + '/' + filename; var _program = __program, // Previous meta program _source = __source, // Previous source _filename = __filename, // Previous source file _dirname = __dirname, // Previous source directory _indent = __; // Previous indentation level var files; if (/(?:^|[^\\])\*/.test(filename)) { files = require("glob").sync(filename, { cwd : __dirname, nosort: true }); files.sort(naturalCompare); // Sort these naturally (e.g. int8 < int16) } else { files = [filename]; } files.forEach(function(file) { var source = require("fs").readFileSync(file)+""; __program = MetaScript.compile(indent(source, __)); __source = source; __filename = file; __dirname = dirname(__filename); __runProgram(); __program = _program; __source = _source; __filename = _filename; __dirname = _dirname; __ = _indent; }); }
javascript
function include(filename, absolute) { filename = absolute ? filename : __dirname + '/' + filename; var _program = __program, // Previous meta program _source = __source, // Previous source _filename = __filename, // Previous source file _dirname = __dirname, // Previous source directory _indent = __; // Previous indentation level var files; if (/(?:^|[^\\])\*/.test(filename)) { files = require("glob").sync(filename, { cwd : __dirname, nosort: true }); files.sort(naturalCompare); // Sort these naturally (e.g. int8 < int16) } else { files = [filename]; } files.forEach(function(file) { var source = require("fs").readFileSync(file)+""; __program = MetaScript.compile(indent(source, __)); __source = source; __filename = file; __dirname = dirname(__filename); __runProgram(); __program = _program; __source = _source; __filename = _filename; __dirname = _dirname; __ = _indent; }); }
[ "function", "include", "(", "filename", ",", "absolute", ")", "{", "filename", "=", "absolute", "?", "filename", ":", "__dirname", "+", "'/'", "+", "filename", ";", "var", "_program", "=", "__program", ",", "// Previous meta program", "_source", "=", "__source...
Includes another source file. @function include @param {string} filename File to include. May be a glob expression on node.js. @param {boolean} absolute Whether the path is absolute, defaults to `false` for a relative path
[ "Includes", "another", "source", "file", "." ]
dc7caf5eae2f2b2467f6c6467203dbcd05f23549
https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L337-L366
31,021
dcodeIO/MetaScript
MetaScript.js
escapestr
function escapestr(s) { return s.replace(/\\/g, '\\\\') .replace(/'/g, '\\\'') .replace(/"/g, '\\"') .replace(/\r/g, '\\r') .replace(/\n/g, '\\n'); }
javascript
function escapestr(s) { return s.replace(/\\/g, '\\\\') .replace(/'/g, '\\\'') .replace(/"/g, '\\"') .replace(/\r/g, '\\r') .replace(/\n/g, '\\n'); }
[ "function", "escapestr", "(", "s", ")", "{", "return", "s", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'\\\\\\\\'", ")", ".", "replace", "(", "/", "'", "/", "g", ",", "'\\\\\\''", ")", ".", "replace", "(", "/", "\"", "/", "g", ",", "'\\\...
Escaoes a string to be used inside of a single or double quote enclosed JavaScript string. @function escapestr @param {string} s String to escape @returns {string} Escaped string
[ "Escaoes", "a", "string", "to", "be", "used", "inside", "of", "a", "single", "or", "double", "quote", "enclosed", "JavaScript", "string", "." ]
dc7caf5eae2f2b2467f6c6467203dbcd05f23549
https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L374-L380
31,022
dcodeIO/MetaScript
MetaScript.js
__err2code
function __err2code(program, err) { if (typeof err.stack !== 'string') return indent(program, 4); var match = /<anonymous>:(\d+):(\d+)\)/.exec(err.stack); if (!match) { return indent(program, 4); } var line = parseInt(match[1], 10)-1, start = line - 3, end = line + 4, lines = program.split("\n"); if (start < 0) start = 0; if (end > lines.length) end = lines.length; var code = []; start = 0; end = lines.length; while (start < end) { code.push(start === line ? "--> "+lines[start] : " "+lines[start]); start++; } return indent(code.join('\n'), 4); }
javascript
function __err2code(program, err) { if (typeof err.stack !== 'string') return indent(program, 4); var match = /<anonymous>:(\d+):(\d+)\)/.exec(err.stack); if (!match) { return indent(program, 4); } var line = parseInt(match[1], 10)-1, start = line - 3, end = line + 4, lines = program.split("\n"); if (start < 0) start = 0; if (end > lines.length) end = lines.length; var code = []; start = 0; end = lines.length; while (start < end) { code.push(start === line ? "--> "+lines[start] : " "+lines[start]); start++; } return indent(code.join('\n'), 4); }
[ "function", "__err2code", "(", "program", ",", "err", ")", "{", "if", "(", "typeof", "err", ".", "stack", "!==", "'string'", ")", "return", "indent", "(", "program", ",", "4", ")", ";", "var", "match", "=", "/", "<anonymous>:(\\d+):(\\d+)\\)", "/", ".", ...
Generates a code view of eval'ed code from an Error. @param {string} program Failed program @param {!Error} err Error caught @returns {string} Code view @inner @private
[ "Generates", "a", "code", "view", "of", "eval", "ed", "code", "from", "an", "Error", "." ]
dc7caf5eae2f2b2467f6c6467203dbcd05f23549
https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L408-L428
31,023
ExpressenAB/exp-amqp-connection
index.js
function(callback) { bootstrap(behaviour, (bootstrapErr, bootstrapRes) => { if (bootstrapErr) api.emit("error", bootstrapErr); if (bootstrapRes && bootstrapRes.virgin) { bootstrapRes.connection.on("error", (err) => api.emit("error", err)); bootstrapRes.connection.on("close", (why) => api.emit("error", why)); api.emit("connected"); bootstrapRes.pubChannel.on("error", (err) => api.emit("error", err)); bootstrapRes.subChannel.on("error", (err) => api.emit("error", err)); bootstrapRes.pubChannel.assertExchange(behaviour.exchange, "topic"); } callback(bootstrapErr, bootstrapRes); }); }
javascript
function(callback) { bootstrap(behaviour, (bootstrapErr, bootstrapRes) => { if (bootstrapErr) api.emit("error", bootstrapErr); if (bootstrapRes && bootstrapRes.virgin) { bootstrapRes.connection.on("error", (err) => api.emit("error", err)); bootstrapRes.connection.on("close", (why) => api.emit("error", why)); api.emit("connected"); bootstrapRes.pubChannel.on("error", (err) => api.emit("error", err)); bootstrapRes.subChannel.on("error", (err) => api.emit("error", err)); bootstrapRes.pubChannel.assertExchange(behaviour.exchange, "topic"); } callback(bootstrapErr, bootstrapRes); }); }
[ "function", "(", "callback", ")", "{", "bootstrap", "(", "behaviour", ",", "(", "bootstrapErr", ",", "bootstrapRes", ")", "=>", "{", "if", "(", "bootstrapErr", ")", "api", ".", "emit", "(", "\"error\"", ",", "bootstrapErr", ")", ";", "if", "(", "bootstra...
get connnection and add event listeners if it's brand new.
[ "get", "connnection", "and", "add", "event", "listeners", "if", "it", "s", "brand", "new", "." ]
999240feee6f0861ddd7404b58b3e6600bd36062
https://github.com/ExpressenAB/exp-amqp-connection/blob/999240feee6f0861ddd7404b58b3e6600bd36062/index.js#L35-L48
31,024
healthsparq/ember-fountainhead
lib/create-dirs.js
mkdirSync
function mkdirSync(dirPath) { // Get relative path to output const relativePath = dirPath.replace(`${CWD}${pathSep}`, ''); const dirs = relativePath.split(pathSep); let currentDir = CWD; // Check if each dir exists, and if not, create it dirs.forEach(dir => { currentDir = path.resolve(currentDir, dir); if(!fs.existsSync(currentDir)) { fs.mkdirSync(currentDir); } }); }
javascript
function mkdirSync(dirPath) { // Get relative path to output const relativePath = dirPath.replace(`${CWD}${pathSep}`, ''); const dirs = relativePath.split(pathSep); let currentDir = CWD; // Check if each dir exists, and if not, create it dirs.forEach(dir => { currentDir = path.resolve(currentDir, dir); if(!fs.existsSync(currentDir)) { fs.mkdirSync(currentDir); } }); }
[ "function", "mkdirSync", "(", "dirPath", ")", "{", "// Get relative path to output", "const", "relativePath", "=", "dirPath", ".", "replace", "(", "`", "${", "CWD", "}", "${", "pathSep", "}", "`", ",", "''", ")", ";", "const", "dirs", "=", "relativePath", ...
Synchronous mkdir that handles creating a potentially nested directory @method mkdirSync @param {string} dirPath Directory path to create, can be nested @return {undefined}
[ "Synchronous", "mkdir", "that", "handles", "creating", "a", "potentially", "nested", "directory" ]
3577546719b251385ca1093f812889590459205a
https://github.com/healthsparq/ember-fountainhead/blob/3577546719b251385ca1093f812889590459205a/lib/create-dirs.js#L26-L39
31,025
mia-js/mia-js-core
lib/baseModel/lib/baseModel.js
function (values, options, callback) { var deferred = Q.defer(); var args = ArgumentHelpers.prepareArguments(options, callback) , wrapper = {}; options = args.options; callback = Qext.makeNodeResolver(deferred, args.callback); //Check for mongo's another possible syntax with '$' operators, e.g. '$set', '$setOnInsert' and set wrapper values = values || {}; for (var element in values) { if (element.match(/\$/i)) { wrapper[element] = values[element]; options.flat = options.flat != undefined ? options.flat : true } } // If nothing to wrap just validate values if (_.isEmpty(wrapper)) { ModelValidator.validate(values, this.prototype, options, function (err, validatedValues) { callback(err, validatedValues); }); } else { // If wrapping elements like $set, $inc etc found, validate each and rewrite to values values = {}; var errors = {}; var wrapperOptions = {}; for (var wrapperElem in wrapper) { wrapperOptions = _.clone(options); if (options && options.partial && _.isObject(options.partial)) { if (options.partial[wrapperElem] !== undefined) { wrapperOptions['partial'] = options.partial[wrapperElem]; } } if (options && options.validate && _.isObject(options.validate)) { if (options.validate[wrapperElem] !== undefined) { wrapperOptions['validate'] = options.validate[wrapperElem]; } } if (options.validate && options.validate[wrapperElem] === false) { values[wrapperElem] = wrapper[wrapperElem]; } else { ModelValidator.validate(wrapper[wrapperElem], this.prototype, wrapperOptions, function (err, validatedValues) { if (err) { errors = err; } values[wrapperElem] = validatedValues; }); } } if (_.isEmpty(errors)) { errors = null; } callback(errors, values); } return deferred.promise; }
javascript
function (values, options, callback) { var deferred = Q.defer(); var args = ArgumentHelpers.prepareArguments(options, callback) , wrapper = {}; options = args.options; callback = Qext.makeNodeResolver(deferred, args.callback); //Check for mongo's another possible syntax with '$' operators, e.g. '$set', '$setOnInsert' and set wrapper values = values || {}; for (var element in values) { if (element.match(/\$/i)) { wrapper[element] = values[element]; options.flat = options.flat != undefined ? options.flat : true } } // If nothing to wrap just validate values if (_.isEmpty(wrapper)) { ModelValidator.validate(values, this.prototype, options, function (err, validatedValues) { callback(err, validatedValues); }); } else { // If wrapping elements like $set, $inc etc found, validate each and rewrite to values values = {}; var errors = {}; var wrapperOptions = {}; for (var wrapperElem in wrapper) { wrapperOptions = _.clone(options); if (options && options.partial && _.isObject(options.partial)) { if (options.partial[wrapperElem] !== undefined) { wrapperOptions['partial'] = options.partial[wrapperElem]; } } if (options && options.validate && _.isObject(options.validate)) { if (options.validate[wrapperElem] !== undefined) { wrapperOptions['validate'] = options.validate[wrapperElem]; } } if (options.validate && options.validate[wrapperElem] === false) { values[wrapperElem] = wrapper[wrapperElem]; } else { ModelValidator.validate(wrapper[wrapperElem], this.prototype, wrapperOptions, function (err, validatedValues) { if (err) { errors = err; } values[wrapperElem] = validatedValues; }); } } if (_.isEmpty(errors)) { errors = null; } callback(errors, values); } return deferred.promise; }
[ "function", "(", "values", ",", "options", ",", "callback", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "args", "=", "ArgumentHelpers", ".", "prepareArguments", "(", "options", ",", "callback", ")", ",", "wrapper", "=", "...
Validates provided 'values' against this model. @param values @param callback
[ "Validates", "provided", "values", "against", "this", "model", "." ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L202-L265
31,026
mia-js/mia-js-core
lib/baseModel/lib/baseModel.js
function (callback) { var self = this; var deferred = Q.defer(); callback = Qext.makeNodeResolver(deferred, callback); var breakExec = {}; Async.waterfall([ function (next) { if (!self.collectionName) { next({ name: 'InternalError', err: "collectionName property is not set for model " + self.identity }); } else { var dbName = self.dbName || Shared.config("environment.defaultMongoDatabase"); var db = self.db(dbName); if (db) { next(null, db); } else { next({ name: 'InternalError', err: "No connection to database " + self.identity }); } } }, function (db, next) { if (!db || _.isEmpty(db)) { Logger.error("No db connection"); next("No db connection"); } else { //try to get exiting collection db.collection(self.collectionName, {strict: true}, function (err, collection) { if (!err) { //collection exists already self._collection = collection; //do not apply indexes to exiting collection, since this operation is time consuming next(breakExec, collection); } else { var collectionOptions = self.collectionOptions || {}; db.createCollection(self.collectionName, collectionOptions, function (err, collection) { if (!err) { next(null, collection); } else { db.collection(self.collectionName, {strict: true}, function (err, collection) { if (!err) { //collection exists already self._collection = collection; //do not apply indexes to exiting collection, since this operation is time consuming next(breakExec, collection); } else { Logger.error(err); next(err); } }); } }); } }); } }, function (collection, next) { //store new collection self._collection = collection; if (_skipDatabaseIndexingOnNewCollections()) { return next(null, collection); } //apply all indexes on collection self.ensureAllIndexes(function (err) { next(err, collection); }); }, function (collection, next) { //return collection next(null, collection); } ], function (err, collection) { if (!err || err === breakExec) { callback(null, collection); } else { callback(err); } }); return deferred.promise; }
javascript
function (callback) { var self = this; var deferred = Q.defer(); callback = Qext.makeNodeResolver(deferred, callback); var breakExec = {}; Async.waterfall([ function (next) { if (!self.collectionName) { next({ name: 'InternalError', err: "collectionName property is not set for model " + self.identity }); } else { var dbName = self.dbName || Shared.config("environment.defaultMongoDatabase"); var db = self.db(dbName); if (db) { next(null, db); } else { next({ name: 'InternalError', err: "No connection to database " + self.identity }); } } }, function (db, next) { if (!db || _.isEmpty(db)) { Logger.error("No db connection"); next("No db connection"); } else { //try to get exiting collection db.collection(self.collectionName, {strict: true}, function (err, collection) { if (!err) { //collection exists already self._collection = collection; //do not apply indexes to exiting collection, since this operation is time consuming next(breakExec, collection); } else { var collectionOptions = self.collectionOptions || {}; db.createCollection(self.collectionName, collectionOptions, function (err, collection) { if (!err) { next(null, collection); } else { db.collection(self.collectionName, {strict: true}, function (err, collection) { if (!err) { //collection exists already self._collection = collection; //do not apply indexes to exiting collection, since this operation is time consuming next(breakExec, collection); } else { Logger.error(err); next(err); } }); } }); } }); } }, function (collection, next) { //store new collection self._collection = collection; if (_skipDatabaseIndexingOnNewCollections()) { return next(null, collection); } //apply all indexes on collection self.ensureAllIndexes(function (err) { next(err, collection); }); }, function (collection, next) { //return collection next(null, collection); } ], function (err, collection) { if (!err || err === breakExec) { callback(null, collection); } else { callback(err); } }); return deferred.promise; }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "callback", "=", "Qext", ".", "makeNodeResolver", "(", "deferred", ",", "callback", ")", ";", "var", "breakExec", "=", "...
Gets the collection of this model. Collection is specified in the 'collectionName' property of the model.
[ "Gets", "the", "collection", "of", "this", "model", ".", "Collection", "is", "specified", "in", "the", "collectionName", "property", "of", "the", "model", "." ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L286-L381
31,027
mia-js/mia-js-core
lib/baseModel/lib/baseModel.js
function (arguments) { var argData = ArgumentHelpers.prepareCallback(arguments); var callback = argData.callback; var args = argData.arguments; if (callback) { args.pop(); } return args; }
javascript
function (arguments) { var argData = ArgumentHelpers.prepareCallback(arguments); var callback = argData.callback; var args = argData.arguments; if (callback) { args.pop(); } return args; }
[ "function", "(", "arguments", ")", "{", "var", "argData", "=", "ArgumentHelpers", ".", "prepareCallback", "(", "arguments", ")", ";", "var", "callback", "=", "argData", ".", "callback", ";", "var", "args", "=", "argData", ".", "arguments", ";", "if", "(", ...
Removes callback function from arguments and returns the arguments @param {Object} arguments @returns {Array} @private
[ "Removes", "callback", "function", "from", "arguments", "and", "returns", "the", "arguments" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L389-L397
31,028
mia-js/mia-js-core
lib/baseModel/lib/baseModel.js
function (functionName, arguments) { var self = this; var args = self._getArgs(arguments); var callback = self._getCallback(arguments); return self._generic(functionName, args) .nodeify(callback); }
javascript
function (functionName, arguments) { var self = this; var args = self._getArgs(arguments); var callback = self._getCallback(arguments); return self._generic(functionName, args) .nodeify(callback); }
[ "function", "(", "functionName", ",", "arguments", ")", "{", "var", "self", "=", "this", ";", "var", "args", "=", "self", ".", "_getArgs", "(", "arguments", ")", ";", "var", "callback", "=", "self", ".", "_getCallback", "(", "arguments", ")", ";", "ret...
Calls generic driver functions @param {String} functionName @param {Object} arguments @returns {*} @private
[ "Calls", "generic", "driver", "functions" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L417-L424
31,029
mia-js/mia-js-core
lib/baseModel/lib/baseModel.js
function (args) { var shardKey = this.prototype.shardKey; var query = !_.isUndefined(args[0]) ? args[0] : {}; var options = !_.isUndefined(args[1]) ? args[1] : {}; var ignoreShardKey = MemberHelpers.getPathPropertyValue(options, 'ignoreShardKey') ? true : false; var missingFields = []; if (!_.isUndefined(shardKey) && !_.isUndefined(query) && !ignoreShardKey) { for (let shardKeyField in shardKey) { if (!query.hasOwnProperty(shardKeyField)) { missingFields.push(shardKeyField); } } } return new Q.Promise(function (resolve, reject) { if (!_.isEmpty(missingFields)) { return reject("Query doesn't contain the shard key or parts of it. Missing fields: " + missingFields.join(', ')); } return resolve(); }); }
javascript
function (args) { var shardKey = this.prototype.shardKey; var query = !_.isUndefined(args[0]) ? args[0] : {}; var options = !_.isUndefined(args[1]) ? args[1] : {}; var ignoreShardKey = MemberHelpers.getPathPropertyValue(options, 'ignoreShardKey') ? true : false; var missingFields = []; if (!_.isUndefined(shardKey) && !_.isUndefined(query) && !ignoreShardKey) { for (let shardKeyField in shardKey) { if (!query.hasOwnProperty(shardKeyField)) { missingFields.push(shardKeyField); } } } return new Q.Promise(function (resolve, reject) { if (!_.isEmpty(missingFields)) { return reject("Query doesn't contain the shard key or parts of it. Missing fields: " + missingFields.join(', ')); } return resolve(); }); }
[ "function", "(", "args", ")", "{", "var", "shardKey", "=", "this", ".", "prototype", ".", "shardKey", ";", "var", "query", "=", "!", "_", ".", "isUndefined", "(", "args", "[", "0", "]", ")", "?", "args", "[", "0", "]", ":", "{", "}", ";", "var"...
Checks whether there is a shard key and if it is in the query @param {Object} args @returns {*} @private
[ "Checks", "whether", "there", "is", "a", "shard", "key", "and", "if", "it", "is", "in", "the", "query" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L469-L491
31,030
jbaicoianu/elation
components/utils/scripts/events.js
function(event) { if (typeof event.touches != 'undefined' && event.touches.length > 0) { var c = { x: event.touches[0].pageX, y: event.touches[0].pageY }; } else { var c = { x: (event.pageX || (event.clientX + document.body.scrollLeft)), y: (event.pageY || (event.clientY + document.body.scrollTop)) }; } return c; }
javascript
function(event) { if (typeof event.touches != 'undefined' && event.touches.length > 0) { var c = { x: event.touches[0].pageX, y: event.touches[0].pageY }; } else { var c = { x: (event.pageX || (event.clientX + document.body.scrollLeft)), y: (event.pageY || (event.clientY + document.body.scrollTop)) }; } return c; }
[ "function", "(", "event", ")", "{", "if", "(", "typeof", "event", ".", "touches", "!=", "'undefined'", "&&", "event", ".", "touches", ".", "length", ">", "0", ")", "{", "var", "c", "=", "{", "x", ":", "event", ".", "touches", "[", "0", "]", ".", ...
returns mouse or all finger touch coords
[ "returns", "mouse", "or", "all", "finger", "touch", "coords" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/events.js#L397-L411
31,031
mia-js/mia-js-core
lib/routesHandler/lib/swaggerDocs.js
function (bodySchemaModels, defName) { for (var i in bodySchemaModels) { if (bodySchemaModels[i]["name"] == defName) { return bodySchemaModels[i]; } } return null; }
javascript
function (bodySchemaModels, defName) { for (var i in bodySchemaModels) { if (bodySchemaModels[i]["name"] == defName) { return bodySchemaModels[i]; } } return null; }
[ "function", "(", "bodySchemaModels", ",", "defName", ")", "{", "for", "(", "var", "i", "in", "bodySchemaModels", ")", "{", "if", "(", "bodySchemaModels", "[", "i", "]", "[", "\"name\"", "]", "==", "defName", ")", "{", "return", "bodySchemaModels", "[", "...
Create swagger compatible schema for body parameters @param bodySchemaModels @param obj @param defName @returns {{bodySchemaModels: *, attributes: {}}} @private
[ "Create", "swagger", "compatible", "schema", "for", "body", "parameters" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/swaggerDocs.js#L20-L27
31,032
mia-js/mia-js-core
lib/modelValidator/lib/modelValidator.js
function (values, schema) { var publicList = find(schema, 'public') , arrElem; for (var value in values) { if (publicList[value]) { if (_.isArray(publicList[value])) { for (var thisArrayElem in publicList[value]) { if (!_.isArray(values[value])) { // Delete values due to it should be an array defined in schema delete(values[value]); } else { for (var thisValue in values[value]) { values[value][thisValue] = unsetPublicSet(values[value][thisValue], publicList[value][thisArrayElem]); if (_.isEmpty(values[value][thisValue])) { (values[value]).splice(thisValue); } } if (_.isEmpty(values[value])) { delete(values[value]); } } } } else { if (publicList[value].public) { if (publicList[value].public == false || (publicList[value].public.hasOwnProperty('set') && publicList[value].public.set != true)) { delete(values[value]); } } } } } return values; }
javascript
function (values, schema) { var publicList = find(schema, 'public') , arrElem; for (var value in values) { if (publicList[value]) { if (_.isArray(publicList[value])) { for (var thisArrayElem in publicList[value]) { if (!_.isArray(values[value])) { // Delete values due to it should be an array defined in schema delete(values[value]); } else { for (var thisValue in values[value]) { values[value][thisValue] = unsetPublicSet(values[value][thisValue], publicList[value][thisArrayElem]); if (_.isEmpty(values[value][thisValue])) { (values[value]).splice(thisValue); } } if (_.isEmpty(values[value])) { delete(values[value]); } } } } else { if (publicList[value].public) { if (publicList[value].public == false || (publicList[value].public.hasOwnProperty('set') && publicList[value].public.set != true)) { delete(values[value]); } } } } } return values; }
[ "function", "(", "values", ",", "schema", ")", "{", "var", "publicList", "=", "find", "(", "schema", ",", "'public'", ")", ",", "arrElem", ";", "for", "(", "var", "value", "in", "values", ")", "{", "if", "(", "publicList", "[", "value", "]", ")", "...
Remove values where schema setting public.set false @param values @param schema @returns {*}
[ "Remove", "values", "where", "schema", "setting", "public", ".", "set", "false" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/modelValidator/lib/modelValidator.js#L724-L763
31,033
mia-js/mia-js-core
lib/modelValidator/lib/modelValidator.js
function (values, schema, options) { var virtualList = find(schema, 'virtual'); //Set default value for virtual if not exists in values if (options && options.query === true) { } else { for (var virtual in virtualList) { if (_.isArray(virtualList[virtual])) { for (var thisVirtual in virtualList[virtual]) { if (_.isArray(values[virtual])) { for (var thisValue in values[virtual]) { setVirtuals(values[virtual][thisValue], virtualList[virtual][thisVirtual], options); } } } } else { if (values[virtual] === undefined && virtualList[virtual] && virtualList[virtual].hasOwnProperty('default') && options && options.partial !== true) { values[virtual] = (virtualList[virtual]).default; } } } } for (var value in values) { if (virtualList[value] && virtualList[value].virtual) { var setFunction = virtualList[value].virtual; //Check for setter and getter if (virtualList[value].virtual.set) { setFunction = virtualList[value].virtual.set; } //Check conditions and apply virtual rulesMatch(value, values[value], setFunction, null, function (err, data) { if (!err) { if (_.isFunction(setFunction)) { var virtualResult = setFunction(values[value]); if (_.isObject(virtualResult) && !_.isEmpty(virtualResult)) { //Check if virtual values does not exists in given values list. Do not overwrite given for (var vValue in virtualResult) { { if (vValue == 'this') { virtualResult[value] = virtualResult[vValue]; delete(virtualResult[vValue]); } else { // Prevent overwrite of given values if (values[vValue] !== undefined) { delete(virtualResult[vValue]); } } } } values = _.assign(values, virtualResult); } } } }); } } return values; }
javascript
function (values, schema, options) { var virtualList = find(schema, 'virtual'); //Set default value for virtual if not exists in values if (options && options.query === true) { } else { for (var virtual in virtualList) { if (_.isArray(virtualList[virtual])) { for (var thisVirtual in virtualList[virtual]) { if (_.isArray(values[virtual])) { for (var thisValue in values[virtual]) { setVirtuals(values[virtual][thisValue], virtualList[virtual][thisVirtual], options); } } } } else { if (values[virtual] === undefined && virtualList[virtual] && virtualList[virtual].hasOwnProperty('default') && options && options.partial !== true) { values[virtual] = (virtualList[virtual]).default; } } } } for (var value in values) { if (virtualList[value] && virtualList[value].virtual) { var setFunction = virtualList[value].virtual; //Check for setter and getter if (virtualList[value].virtual.set) { setFunction = virtualList[value].virtual.set; } //Check conditions and apply virtual rulesMatch(value, values[value], setFunction, null, function (err, data) { if (!err) { if (_.isFunction(setFunction)) { var virtualResult = setFunction(values[value]); if (_.isObject(virtualResult) && !_.isEmpty(virtualResult)) { //Check if virtual values does not exists in given values list. Do not overwrite given for (var vValue in virtualResult) { { if (vValue == 'this') { virtualResult[value] = virtualResult[vValue]; delete(virtualResult[vValue]); } else { // Prevent overwrite of given values if (values[vValue] !== undefined) { delete(virtualResult[vValue]); } } } } values = _.assign(values, virtualResult); } } } }); } } return values; }
[ "function", "(", "values", ",", "schema", ",", "options", ")", "{", "var", "virtualList", "=", "find", "(", "schema", ",", "'virtual'", ")", ";", "//Set default value for virtual if not exists in values", "if", "(", "options", "&&", "options", ".", "query", "===...
Apply virtual functions defined in schema @param values @param model @param options @returns {*}
[ "Apply", "virtual", "functions", "defined", "in", "schema" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/modelValidator/lib/modelValidator.js#L772-L840
31,034
mia-js/mia-js-core
lib/modelValidator/lib/modelValidator.js
function (model, filter, value) { if (!_.isString(filter)) { return null; } if (model.data) { var list = findKeys(model.data, filter) , values = []; for (var res in list) { if (value === undefined || list[res][filter] === value) { values.push(res); } } } //return _.isEmpty(values) ? undefined : values; //Changed to return empty array instead of 'undefined'. Do not change back, otherwise some functions working with arrays do not work properly. return values; }
javascript
function (model, filter, value) { if (!_.isString(filter)) { return null; } if (model.data) { var list = findKeys(model.data, filter) , values = []; for (var res in list) { if (value === undefined || list[res][filter] === value) { values.push(res); } } } //return _.isEmpty(values) ? undefined : values; //Changed to return empty array instead of 'undefined'. Do not change back, otherwise some functions working with arrays do not work properly. return values; }
[ "function", "(", "model", ",", "filter", ",", "value", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "filter", ")", ")", "{", "return", "null", ";", "}", "if", "(", "model", ".", "data", ")", "{", "var", "list", "=", "findKeys", "(", "mo...
Finds all nodes with filter property in given model and returns array list of nodes @param model @param filter @returns {*}
[ "Finds", "all", "nodes", "with", "filter", "property", "in", "given", "model", "and", "returns", "array", "list", "of", "nodes" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/modelValidator/lib/modelValidator.js#L977-L997
31,035
mia-js/mia-js-core
lib/modelValidator/lib/modelValidator.js
function (schema) { var extendList = find(schema, 'extend'); for (var extendElem in extendList) { if (extendList[extendElem] && extendList[extendElem].extend && _.isFunction(extendList[extendElem].extend)) { schema[extendElem] = extendList[extendElem].extend(); } } return schema; }
javascript
function (schema) { var extendList = find(schema, 'extend'); for (var extendElem in extendList) { if (extendList[extendElem] && extendList[extendElem].extend && _.isFunction(extendList[extendElem].extend)) { schema[extendElem] = extendList[extendElem].extend(); } } return schema; }
[ "function", "(", "schema", ")", "{", "var", "extendList", "=", "find", "(", "schema", ",", "'extend'", ")", ";", "for", "(", "var", "extendElem", "in", "extendList", ")", "{", "if", "(", "extendList", "[", "extendElem", "]", "&&", "extendList", "[", "e...
Extend schema by dynamic functions. Write a function that defined the schema settings for a node @param schema @returns {*}
[ "Extend", "schema", "by", "dynamic", "functions", ".", "Write", "a", "function", "that", "defined", "the", "schema", "settings", "for", "a", "node" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/modelValidator/lib/modelValidator.js#L1004-L1013
31,036
jonschlinkert/plasma
index.js
name
function name(fp, options) { var opts = options || {}; if (typeof opts.namespace === 'function') { return opts.namespace(fp, opts); } if (typeof opts.namespace === false) { return fp; } var ext = path.extname(fp); return path.basename(fp, ext); }
javascript
function name(fp, options) { var opts = options || {}; if (typeof opts.namespace === 'function') { return opts.namespace(fp, opts); } if (typeof opts.namespace === false) { return fp; } var ext = path.extname(fp); return path.basename(fp, ext); }
[ "function", "name", "(", "fp", ",", "options", ")", "{", "var", "opts", "=", "options", "||", "{", "}", ";", "if", "(", "typeof", "opts", ".", "namespace", "===", "'function'", ")", "{", "return", "opts", ".", "namespace", "(", "fp", ",", "opts", "...
Default `namespace` function. Pass a function on `options.namespace` to customize. @param {String} `fp` @param {Object} `opts` @return {String} @api private
[ "Default", "namespace", "function", ".", "Pass", "a", "function", "on", "options", ".", "namespace", "to", "customize", "." ]
573027b52817ceb2f1295779bc2b3bceefa74d11
https://github.com/jonschlinkert/plasma/blob/573027b52817ceb2f1295779bc2b3bceefa74d11/index.js#L229-L239
31,037
jonschlinkert/plasma
index.js
read
function read(fp, opts) { if (opts && opts.read) { return opts.read(fp, opts); } return readData.call(this, fp, opts); }
javascript
function read(fp, opts) { if (opts && opts.read) { return opts.read(fp, opts); } return readData.call(this, fp, opts); }
[ "function", "read", "(", "fp", ",", "opts", ")", "{", "if", "(", "opts", "&&", "opts", ".", "read", ")", "{", "return", "opts", ".", "read", "(", "fp", ",", "opts", ")", ";", "}", "return", "readData", ".", "call", "(", "this", ",", "fp", ",", ...
Default `read` function. Pass a function on `options.read` to customize. @param {String} `fp` @param {Object} `opts` @return {String} @api private
[ "Default", "read", "function", ".", "Pass", "a", "function", "on", "options", ".", "read", "to", "customize", "." ]
573027b52817ceb2f1295779bc2b3bceefa74d11
https://github.com/jonschlinkert/plasma/blob/573027b52817ceb2f1295779bc2b3bceefa74d11/index.js#L251-L256
31,038
jonschlinkert/plasma
index.js
readData
function readData(fp, options) { // shallow clone options var opts = utils.extend({}, options); // get the loader for this file. var ext = opts.lang || path.extname(fp); if (ext && ext.charAt(0) !== '.') { ext = '.' + ext; } if (!this.dataLoaders.hasOwnProperty(ext)) { return this.dataLoader('read')(fp, opts); } return this.dataLoader(ext)(fp, opts); }
javascript
function readData(fp, options) { // shallow clone options var opts = utils.extend({}, options); // get the loader for this file. var ext = opts.lang || path.extname(fp); if (ext && ext.charAt(0) !== '.') { ext = '.' + ext; } if (!this.dataLoaders.hasOwnProperty(ext)) { return this.dataLoader('read')(fp, opts); } return this.dataLoader(ext)(fp, opts); }
[ "function", "readData", "(", "fp", ",", "options", ")", "{", "// shallow clone options", "var", "opts", "=", "utils", ".", "extend", "(", "{", "}", ",", "options", ")", ";", "// get the loader for this file.", "var", "ext", "=", "opts", ".", "lang", "||", ...
Utility for reading data files. @param {String} `fp` Filepath to read. @param {Object} `options` Options to pass to [js-yaml] @api private
[ "Utility", "for", "reading", "data", "files", "." ]
573027b52817ceb2f1295779bc2b3bceefa74d11
https://github.com/jonschlinkert/plasma/blob/573027b52817ceb2f1295779bc2b3bceefa74d11/index.js#L266-L278
31,039
jbaicoianu/elation
components/utils/scripts/ajaxlib.js
function() { if (common.inlinescripts.length > 0) { var script_text = ''; for (var i = 0; i < common.inlinescripts.length; i++) { if (!common.inlinescripts[i] || typeof common.inlinescripts[i] == 'undefined') continue; else script_text += common.inlinescripts[i] + '\n'; } try { eval(script_text); } catch(e) { batch.callback(script_text); } } }
javascript
function() { if (common.inlinescripts.length > 0) { var script_text = ''; for (var i = 0; i < common.inlinescripts.length; i++) { if (!common.inlinescripts[i] || typeof common.inlinescripts[i] == 'undefined') continue; else script_text += common.inlinescripts[i] + '\n'; } try { eval(script_text); } catch(e) { batch.callback(script_text); } } }
[ "function", "(", ")", "{", "if", "(", "common", ".", "inlinescripts", ".", "length", ">", "0", ")", "{", "var", "script_text", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "common", ".", "inlinescripts", ".", "length", ";", "i...
Execute all inline scripts
[ "Execute", "all", "inline", "scripts" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/ajaxlib.js#L229-L244
31,040
healthsparq/ember-fountainhead
lib/generate-fountainhead-data.js
saveObjectToJSON
function saveObjectToJSON(filePath, data) { try { data = JSON.stringify(data, null, 2); writeFileSync(filePath, data, { encoding: 'utf8' }); return true; } catch(ex) { console.warn('Unable to save class JSON'); return false; } // NOTE: ASYNC REQUIRES PROMISIFYING ALL OPERATIONS // fs.writeFile(filePath, data, err => { // if (err) { console.warn(`Unable to save ${filePath}`); } // }); }
javascript
function saveObjectToJSON(filePath, data) { try { data = JSON.stringify(data, null, 2); writeFileSync(filePath, data, { encoding: 'utf8' }); return true; } catch(ex) { console.warn('Unable to save class JSON'); return false; } // NOTE: ASYNC REQUIRES PROMISIFYING ALL OPERATIONS // fs.writeFile(filePath, data, err => { // if (err) { console.warn(`Unable to save ${filePath}`); } // }); }
[ "function", "saveObjectToJSON", "(", "filePath", ",", "data", ")", "{", "try", "{", "data", "=", "JSON", ".", "stringify", "(", "data", ",", "null", ",", "2", ")", ";", "writeFileSync", "(", "filePath", ",", "data", ",", "{", "encoding", ":", "'utf8'",...
Call to handle saving data to a file. Requires a file path and data to save. If data is not a string, it will be stringified @method saveObjectToJSON @param {string} filePath Path to save file at @param {Object|string} data Data to save in file @return {boolean} True for successful operation, false for failures
[ "Call", "to", "handle", "saving", "data", "to", "a", "file", ".", "Requires", "a", "file", "path", "and", "data", "to", "save", ".", "If", "data", "is", "not", "a", "string", "it", "will", "be", "stringified" ]
3577546719b251385ca1093f812889590459205a
https://github.com/healthsparq/ember-fountainhead/blob/3577546719b251385ca1093f812889590459205a/lib/generate-fountainhead-data.js#L58-L72
31,041
kuzzleio/kuzzle-common-objects
lib/utils/assertType.js
assertObject
function assertObject(attr, data) { if (data === null || data === undefined) { return null; } if (typeof data !== 'object' || Array.isArray(data)) { throw new ParseError(`Attribute ${attr} must be of type "object"`); } return data; }
javascript
function assertObject(attr, data) { if (data === null || data === undefined) { return null; } if (typeof data !== 'object' || Array.isArray(data)) { throw new ParseError(`Attribute ${attr} must be of type "object"`); } return data; }
[ "function", "assertObject", "(", "attr", ",", "data", ")", "{", "if", "(", "data", "===", "null", "||", "data", "===", "undefined", ")", "{", "return", "null", ";", "}", "if", "(", "typeof", "data", "!==", "'object'", "||", "Array", ".", "isArray", "...
Throws if the provided data is not an object. Returns the unmodified data if validated @throws @param {string} attr - tested attribute name @param {*} data @return {object}
[ "Throws", "if", "the", "provided", "data", "is", "not", "an", "object", ".", "Returns", "the", "unmodified", "data", "if", "validated" ]
7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2
https://github.com/kuzzleio/kuzzle-common-objects/blob/7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2/lib/utils/assertType.js#L14-L24
31,042
kuzzleio/kuzzle-common-objects
lib/utils/assertType.js
assertArray
function assertArray(attr, data, type) { if (data === null || data === undefined) { return []; } if (!Array.isArray(data)) { throw new ParseError(`Attribute ${attr} must be of type "array"`); } const clone = []; for (const d of data) { if (d !== undefined && d !== null) { if (typeof d !== type) { throw new ParseError(`Attribute ${attr} must contain only values of type "${type}"`); } clone.push(d); } } return clone; }
javascript
function assertArray(attr, data, type) { if (data === null || data === undefined) { return []; } if (!Array.isArray(data)) { throw new ParseError(`Attribute ${attr} must be of type "array"`); } const clone = []; for (const d of data) { if (d !== undefined && d !== null) { if (typeof d !== type) { throw new ParseError(`Attribute ${attr} must contain only values of type "${type}"`); } clone.push(d); } } return clone; }
[ "function", "assertArray", "(", "attr", ",", "data", ",", "type", ")", "{", "if", "(", "data", "===", "null", "||", "data", "===", "undefined", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "data", ")", ")"...
Throws if the provided data is not an array containing exclusively values of the specified "type" Returns a clone of the provided array if valid @throws @param {string} attr - tested attribute name @param {*} data @return {array}
[ "Throws", "if", "the", "provided", "data", "is", "not", "an", "array", "containing", "exclusively", "values", "of", "the", "specified", "type", "Returns", "a", "clone", "of", "the", "provided", "array", "if", "valid" ]
7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2
https://github.com/kuzzleio/kuzzle-common-objects/blob/7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2/lib/utils/assertType.js#L36-L58
31,043
kuzzleio/kuzzle-common-objects
lib/utils/assertType.js
assertUniTypeObject
function assertUniTypeObject(attr, data, type) { data = assertObject(attr, data); if (data === null) { return null; } Object.keys(data).forEach(key => { if (type === undefined) { type = typeof data[key]; } type = type.toLowerCase(); let msg = `Attribute ${attr} must be of type "object" and have all its properties of type ${type}.` + `\nExpected "${attr}.${key}" to be of type "${type}", but go "${typeof data[key]}".`; switch (type) { case 'array': if (!Array.isArray(data[key])) { throw new ParseError(msg); } break; default: if (typeof data[key] !== type) { throw new ParseError(msg); } break; } }); return data; }
javascript
function assertUniTypeObject(attr, data, type) { data = assertObject(attr, data); if (data === null) { return null; } Object.keys(data).forEach(key => { if (type === undefined) { type = typeof data[key]; } type = type.toLowerCase(); let msg = `Attribute ${attr} must be of type "object" and have all its properties of type ${type}.` + `\nExpected "${attr}.${key}" to be of type "${type}", but go "${typeof data[key]}".`; switch (type) { case 'array': if (!Array.isArray(data[key])) { throw new ParseError(msg); } break; default: if (typeof data[key] !== type) { throw new ParseError(msg); } break; } }); return data; }
[ "function", "assertUniTypeObject", "(", "attr", ",", "data", ",", "type", ")", "{", "data", "=", "assertObject", "(", "attr", ",", "data", ")", ";", "if", "(", "data", "===", "null", ")", "{", "return", "null", ";", "}", "Object", ".", "keys", "(", ...
Throws if the provided object is not an object or if it contains heterogeaous typed properties. Returns the unmodified data if validated. @throws {ParseError} @param {string} attr - tested attribute name @param {*} data @param {string} [type] - expected type for data properties @returns {object|null}
[ "Throws", "if", "the", "provided", "object", "is", "not", "an", "object", "or", "if", "it", "contains", "heterogeaous", "typed", "properties", ".", "Returns", "the", "unmodified", "data", "if", "validated", "." ]
7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2
https://github.com/kuzzleio/kuzzle-common-objects/blob/7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2/lib/utils/assertType.js#L70-L102
31,044
kuzzleio/kuzzle-common-objects
lib/utils/assertType.js
assertString
function assertString(attr, data) { if (data === null || data === undefined) { return null; } if (typeof data !== 'string') { throw new ParseError(`Attribute ${attr} must be of type "string"`); } return data; }
javascript
function assertString(attr, data) { if (data === null || data === undefined) { return null; } if (typeof data !== 'string') { throw new ParseError(`Attribute ${attr} must be of type "string"`); } return data; }
[ "function", "assertString", "(", "attr", ",", "data", ")", "{", "if", "(", "data", "===", "null", "||", "data", "===", "undefined", ")", "{", "return", "null", ";", "}", "if", "(", "typeof", "data", "!==", "'string'", ")", "{", "throw", "new", "Parse...
Throws if the provided data is not a string Returns the unmodified data if validated @throws @param {string} attr - tested attribute name @param {*} data @return {null|string}
[ "Throws", "if", "the", "provided", "data", "is", "not", "a", "string", "Returns", "the", "unmodified", "data", "if", "validated" ]
7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2
https://github.com/kuzzleio/kuzzle-common-objects/blob/7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2/lib/utils/assertType.js#L114-L124
31,045
mia-js/mia-js-core
lib/routesHandler/lib/preconditionsCheck.js
function (values, model, type) { var deferred = Q.defer(); var modelData = {data: model}; ModelValidator.validate(values, modelData, function (err, data) { deferred.resolve({data: data, err: err, type: type}); }); return deferred.promise; }
javascript
function (values, model, type) { var deferred = Q.defer(); var modelData = {data: model}; ModelValidator.validate(values, modelData, function (err, data) { deferred.resolve({data: data, err: err, type: type}); }); return deferred.promise; }
[ "function", "(", "values", ",", "model", ",", "type", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "modelData", "=", "{", "data", ":", "model", "}", ";", "ModelValidator", ".", "validate", "(", "values", ",", "modelData"...
Validate given values using given model @param values @param model @param type @returns {*} @private
[ "Validate", "given", "values", "using", "given", "model" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/preconditionsCheck.js#L82-L90
31,046
mia-js/mia-js-core
lib/routesHandler/lib/preconditionsCheck.js
function (req, controller) { var parameters = []; if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.header) { parameters.push(_checkValues(req.headers, controller.conditions.parameters.header, "header")) } if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.query) { parameters.push(_checkValues(req.query, controller.conditions.parameters.query, "query")) } if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.body) { parameters.push(_checkValues(req.body, controller.conditions.parameters.body, "body")) } if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.path) { parameters.push(_checkValues(req.params, controller.conditions.parameters.path, "path")) } return Q.all(parameters).then(function (results) { var validatedData = []; var errors = []; results.forEach(function (result) { if (result.data) { if (!validatedData[result.type]) { validatedData[result.type] = {}; } validatedData[result.type] = result.data; } // Collect validation errors if (result.err && result.err.err && result.err.name == "ValidationError") { var resultErrors = result.err.err; resultErrors.forEach(function (error) { error.in = result.type; errors.push(error); }); } }); return Q({ validatedData: { name: controller.name, version: controller.version, method: controller.method, function: controller.function, data: validatedData }, errors: errors }); }); }
javascript
function (req, controller) { var parameters = []; if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.header) { parameters.push(_checkValues(req.headers, controller.conditions.parameters.header, "header")) } if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.query) { parameters.push(_checkValues(req.query, controller.conditions.parameters.query, "query")) } if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.body) { parameters.push(_checkValues(req.body, controller.conditions.parameters.body, "body")) } if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.path) { parameters.push(_checkValues(req.params, controller.conditions.parameters.path, "path")) } return Q.all(parameters).then(function (results) { var validatedData = []; var errors = []; results.forEach(function (result) { if (result.data) { if (!validatedData[result.type]) { validatedData[result.type] = {}; } validatedData[result.type] = result.data; } // Collect validation errors if (result.err && result.err.err && result.err.name == "ValidationError") { var resultErrors = result.err.err; resultErrors.forEach(function (error) { error.in = result.type; errors.push(error); }); } }); return Q({ validatedData: { name: controller.name, version: controller.version, method: controller.method, function: controller.function, data: validatedData }, errors: errors }); }); }
[ "function", "(", "req", ",", "controller", ")", "{", "var", "parameters", "=", "[", "]", ";", "if", "(", "controller", ".", "conditions", "&&", "controller", ".", "conditions", ".", "parameters", "&&", "controller", ".", "conditions", ".", "parameters", "....
Parse parameter model of controller and validate all request parameters for header,query and body @param req @param controller @returns {*} @private
[ "Parse", "parameter", "model", "of", "controller", "and", "validate", "all", "request", "parameters", "for", "header", "query", "and", "body" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/preconditionsCheck.js#L99-L149
31,047
mia-js/mia-js-core
lib/routesHandler/lib/preconditionsCheck.js
function (req, res, next) { var hostId = req.miajs.route.hostId; var url = req.miajs.route.url; var prefix = req.miajs.route.prefix; var method = req.miajs.route.method; var group = req.miajs.route.group; var version = req.miajs.route.version; var registeredServices = Shared.registeredServices(); var errors = []; var routeFound = false; req.miajs = req.miajs || {}; //console.log('checkPreconditions: url: ' + url + ', method: ' + method + ', body: ' + JSON.stringify(req.body)); for (var index in registeredServices) { if (registeredServices[index].group == group && registeredServices[index].hostId == hostId && registeredServices[index].version == version && registeredServices[index].prefix == prefix && registeredServices[index].method == method && registeredServices[index].url == url ) { routeFound = true; if (registeredServices[index].preconditions) { var service = registeredServices[index]; var preconditionsList = service.preconditions; var qfunctions = []; for (var cIndex in preconditionsList) { qfunctions.push(_checkControllerConditions(req, preconditionsList[cIndex])); } Q.all(qfunctions).then(function (results) { req.miajs.commonValidatedParameters = []; results.forEach(function (result) { if (result) { if (result.validatedData) { req.miajs.commonValidatedParameters.push(result.validatedData); } var controllerErrors = result.errors; controllerErrors.forEach(function (error) { var inList = false; // Check for error duplicates for (var eIndex in errors) { if (errors[eIndex].code == error.code && errors[eIndex].id == error.id && errors[eIndex].in == error.in) { inList = true; } } if (inList == false) { errors.push(error); } }); } }); }).then(function () { if (!_.isEmpty(errors)) { next({'status': 400, err: errors}) return; } else { next(); return; } }).catch(function (err) { next({'status': 400, err: err}); return; }); } else { next(); return; } } } if (routeFound == false) { Logger.error('Can not find controller file in preconditionsCheck to perform parameter validation. Request canceled due to security reasons'); next({status: 500}); return; } }
javascript
function (req, res, next) { var hostId = req.miajs.route.hostId; var url = req.miajs.route.url; var prefix = req.miajs.route.prefix; var method = req.miajs.route.method; var group = req.miajs.route.group; var version = req.miajs.route.version; var registeredServices = Shared.registeredServices(); var errors = []; var routeFound = false; req.miajs = req.miajs || {}; //console.log('checkPreconditions: url: ' + url + ', method: ' + method + ', body: ' + JSON.stringify(req.body)); for (var index in registeredServices) { if (registeredServices[index].group == group && registeredServices[index].hostId == hostId && registeredServices[index].version == version && registeredServices[index].prefix == prefix && registeredServices[index].method == method && registeredServices[index].url == url ) { routeFound = true; if (registeredServices[index].preconditions) { var service = registeredServices[index]; var preconditionsList = service.preconditions; var qfunctions = []; for (var cIndex in preconditionsList) { qfunctions.push(_checkControllerConditions(req, preconditionsList[cIndex])); } Q.all(qfunctions).then(function (results) { req.miajs.commonValidatedParameters = []; results.forEach(function (result) { if (result) { if (result.validatedData) { req.miajs.commonValidatedParameters.push(result.validatedData); } var controllerErrors = result.errors; controllerErrors.forEach(function (error) { var inList = false; // Check for error duplicates for (var eIndex in errors) { if (errors[eIndex].code == error.code && errors[eIndex].id == error.id && errors[eIndex].in == error.in) { inList = true; } } if (inList == false) { errors.push(error); } }); } }); }).then(function () { if (!_.isEmpty(errors)) { next({'status': 400, err: errors}) return; } else { next(); return; } }).catch(function (err) { next({'status': 400, err: err}); return; }); } else { next(); return; } } } if (routeFound == false) { Logger.error('Can not find controller file in preconditionsCheck to perform parameter validation. Request canceled due to security reasons'); next({status: 500}); return; } }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "hostId", "=", "req", ".", "miajs", ".", "route", ".", "hostId", ";", "var", "url", "=", "req", ".", "miajs", ".", "route", ".", "url", ";", "var", "prefix", "=", "req", ".", "mi...
Apply all preconditions defined in all controllers of this route. Try to find preconditions in registeredServices matching url, prefix, method, group and version @param req @param res @param next
[ "Apply", "all", "preconditions", "defined", "in", "all", "controllers", "of", "this", "route", ".", "Try", "to", "find", "preconditions", "in", "registeredServices", "matching", "url", "prefix", "method", "group", "and", "version" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/preconditionsCheck.js#L158-L245
31,048
mia-js/mia-js-core
lib/mia-js.js
function () { Shared.initialize('/config', process.argv[2]); Shared.setAppHttp(appHttp); Shared.setAppHttps(appHttps); Shared.setExpress(express); // Init memcached var memcached = Shared.memcached(); // Init redis cache var redis = Shared.redis(true); //Enable gzip compression appHttp.use(compression()); appHttp.disable('x-powered-by'); appHttps.use(compression()); appHttps.disable('x-powered-by'); var env = Shared.config("environment"); var maxLag = env.maxLag; if (maxLag) { toobusy.maxLag(maxLag); } appHttp.use(function (req, res, next) { if (maxLag && toobusy()) { Logger.error("Server is busy, rejected request"); res.status(503).send("I'm busy right now, sorry."); } else { next(); } }); appHttps.use(function (req, res, next) { if (maxLag && toobusy()) { Logger.error("Server is busy, rejected request"); res.status(503).send("I'm busy right now, sorry."); } else { next(); } }); return Q(); }
javascript
function () { Shared.initialize('/config', process.argv[2]); Shared.setAppHttp(appHttp); Shared.setAppHttps(appHttps); Shared.setExpress(express); // Init memcached var memcached = Shared.memcached(); // Init redis cache var redis = Shared.redis(true); //Enable gzip compression appHttp.use(compression()); appHttp.disable('x-powered-by'); appHttps.use(compression()); appHttps.disable('x-powered-by'); var env = Shared.config("environment"); var maxLag = env.maxLag; if (maxLag) { toobusy.maxLag(maxLag); } appHttp.use(function (req, res, next) { if (maxLag && toobusy()) { Logger.error("Server is busy, rejected request"); res.status(503).send("I'm busy right now, sorry."); } else { next(); } }); appHttps.use(function (req, res, next) { if (maxLag && toobusy()) { Logger.error("Server is busy, rejected request"); res.status(503).send("I'm busy right now, sorry."); } else { next(); } }); return Q(); }
[ "function", "(", ")", "{", "Shared", ".", "initialize", "(", "'/config'", ",", "process", ".", "argv", "[", "2", "]", ")", ";", "Shared", ".", "setAppHttp", "(", "appHttp", ")", ";", "Shared", ".", "setAppHttps", "(", "appHttps", ")", ";", "Shared", ...
Set initialize functions @returns {*} @private
[ "Set", "initialize", "functions" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L52-L95
31,049
mia-js/mia-js-core
lib/mia-js.js
function (initFunction) { if (_.isFunction(initFunction)) { Logger.info("Run init function"); _customInitFuncton = initFunction; return initFunction(appHttp) .then(function () { return initFunction(appHttps); }); } return Q(); }
javascript
function (initFunction) { if (_.isFunction(initFunction)) { Logger.info("Run init function"); _customInitFuncton = initFunction; return initFunction(appHttp) .then(function () { return initFunction(appHttps); }); } return Q(); }
[ "function", "(", "initFunction", ")", "{", "if", "(", "_", ".", "isFunction", "(", "initFunction", ")", ")", "{", "Logger", ".", "info", "(", "\"Run init function\"", ")", ";", "_customInitFuncton", "=", "initFunction", ";", "return", "initFunction", "(", "a...
Call and set custom init function to global @param initFunction @returns {*} @private
[ "Call", "and", "set", "custom", "init", "function", "to", "global" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L110-L120
31,050
mia-js/mia-js-core
lib/mia-js.js
function () { //set logger if (!module.parent) { appHttp.use(morgan({format: 'dev'})); appHttps.use(morgan({format: 'dev'})); } return Q(); }
javascript
function () { //set logger if (!module.parent) { appHttp.use(morgan({format: 'dev'})); appHttps.use(morgan({format: 'dev'})); } return Q(); }
[ "function", "(", ")", "{", "//set logger", "if", "(", "!", "module", ".", "parent", ")", "{", "appHttp", ".", "use", "(", "morgan", "(", "{", "format", ":", "'dev'", "}", ")", ")", ";", "appHttps", ".", "use", "(", "morgan", "(", "{", "format", "...
Set morgan logger @returns {*} @private
[ "Set", "morgan", "logger" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L174-L181
31,051
mia-js/mia-js-core
lib/mia-js.js
function (host, reInit) { if (_.isEmpty(host.id) || !_.isString(host.id)) { throw new Error("Host configuration is invalid. Host id is missing or not a string"); } if (_.isEmpty(host.host)) { throw new Error("Host configuration is invalid. Host is missing"); } if (_.isString(host.host)) { host.host = [host.host]; } if (!_.isArray(host.host)) { throw new Error("Host configuration is invalid. Host should be array or string"); } var router = new express.Router(); if (reInit === false) { // Check if host is already defined. Use same router instance to merge routes for (var index in _vhosts) { for (var vh in _vhosts[index]["host"]) { if (_vhosts[index]["host"][vh] == host.host) { router = _vhosts[index]["router"]; } } } } _vhosts[host.id] = { host: host.host, router: router, http: !host.listener ? true : host.listener && host.listener.http || null, https: !host.listener ? true : host.listener && host.listener.https || null }; _applyRouterConfig(_vhosts[host.id]["router"]); _customInitFuncton(_vhosts[host.id]["router"]); }
javascript
function (host, reInit) { if (_.isEmpty(host.id) || !_.isString(host.id)) { throw new Error("Host configuration is invalid. Host id is missing or not a string"); } if (_.isEmpty(host.host)) { throw new Error("Host configuration is invalid. Host is missing"); } if (_.isString(host.host)) { host.host = [host.host]; } if (!_.isArray(host.host)) { throw new Error("Host configuration is invalid. Host should be array or string"); } var router = new express.Router(); if (reInit === false) { // Check if host is already defined. Use same router instance to merge routes for (var index in _vhosts) { for (var vh in _vhosts[index]["host"]) { if (_vhosts[index]["host"][vh] == host.host) { router = _vhosts[index]["router"]; } } } } _vhosts[host.id] = { host: host.host, router: router, http: !host.listener ? true : host.listener && host.listener.http || null, https: !host.listener ? true : host.listener && host.listener.https || null }; _applyRouterConfig(_vhosts[host.id]["router"]); _customInitFuncton(_vhosts[host.id]["router"]); }
[ "function", "(", "host", ",", "reInit", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "host", ".", "id", ")", "||", "!", "_", ".", "isString", "(", "host", ".", "id", ")", ")", "{", "throw", "new", "Error", "(", "\"Host configuration is invalid. Hos...
Parse virtual host definition from mia.js global environment configuration @param {Object} host @param {Boolean} reInit @private
[ "Parse", "virtual", "host", "definition", "from", "mia", ".", "js", "global", "environment", "configuration" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L189-L227
31,052
mia-js/mia-js-core
lib/mia-js.js
function (reInit = false) { //load routes var environment = Shared.config("environment"); var hosts = environment.hosts; if (hosts) { if (!_.isArray(hosts)) { hosts = [hosts]; } for (var host in hosts) { _parseHosts(hosts[host], reInit); } } _vhosts["*"] = { host: '*', router: new express.Router() }; _applyRouterConfig(_vhosts["*"]["router"]); _customInitFuncton(_vhosts["*"]["router"]); return RoutesHandler.initializeRoutes(_vhosts, reInit === false); }
javascript
function (reInit = false) { //load routes var environment = Shared.config("environment"); var hosts = environment.hosts; if (hosts) { if (!_.isArray(hosts)) { hosts = [hosts]; } for (var host in hosts) { _parseHosts(hosts[host], reInit); } } _vhosts["*"] = { host: '*', router: new express.Router() }; _applyRouterConfig(_vhosts["*"]["router"]); _customInitFuncton(_vhosts["*"]["router"]); return RoutesHandler.initializeRoutes(_vhosts, reInit === false); }
[ "function", "(", "reInit", "=", "false", ")", "{", "//load routes", "var", "environment", "=", "Shared", ".", "config", "(", "\"environment\"", ")", ";", "var", "hosts", "=", "environment", ".", "hosts", ";", "if", "(", "hosts", ")", "{", "if", "(", "!...
Register all routes defined in routes definition of projects and apply to virtual hosts @param {Boolean} reInit @returns {*} @private
[ "Register", "all", "routes", "defined", "in", "routes", "definition", "of", "projects", "and", "apply", "to", "virtual", "hosts" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L245-L266
31,053
mia-js/mia-js-core
lib/mia-js.js
function () { const cronJobsToStart = _getNamesOfCronJobsToStart(); if (!cronJobsToStart && _shouldStartCrons() && Shared.isDbConnectionAvailable() === true) { return CronJobManagerJob.startListening().then(function () { Logger.tag('Cron').info('Cron Job Manager is started. Starting all available cron jobs'); return Q(); }, function (err) { Logger.tag('Cron').error('Error starting Cron Job Manager '); return Q.reject(err); }); } else if (cronJobsToStart && _shouldStartCrons()) { Logger.tag('Cron').info('Starting specific cron jobs "' + cronJobsToStart.join(', ') + '"'); try { const cronJobs = Shared.cronModules(cronJobsToStart); let promises = []; for (let cron of cronJobs) { // Set force run config cron.forceRun = true; promises.push(cron.worker(cron, cron)); } return Q.all(promises) .then(() => process.exit()) .catch(() => process.exit(1)); } catch (err) { process.exit(1); } } else { Logger.tag('Cron').warn('Cron Manager is disabled for this environment.'); return Q(); } }
javascript
function () { const cronJobsToStart = _getNamesOfCronJobsToStart(); if (!cronJobsToStart && _shouldStartCrons() && Shared.isDbConnectionAvailable() === true) { return CronJobManagerJob.startListening().then(function () { Logger.tag('Cron').info('Cron Job Manager is started. Starting all available cron jobs'); return Q(); }, function (err) { Logger.tag('Cron').error('Error starting Cron Job Manager '); return Q.reject(err); }); } else if (cronJobsToStart && _shouldStartCrons()) { Logger.tag('Cron').info('Starting specific cron jobs "' + cronJobsToStart.join(', ') + '"'); try { const cronJobs = Shared.cronModules(cronJobsToStart); let promises = []; for (let cron of cronJobs) { // Set force run config cron.forceRun = true; promises.push(cron.worker(cron, cron)); } return Q.all(promises) .then(() => process.exit()) .catch(() => process.exit(1)); } catch (err) { process.exit(1); } } else { Logger.tag('Cron').warn('Cron Manager is disabled for this environment.'); return Q(); } }
[ "function", "(", ")", "{", "const", "cronJobsToStart", "=", "_getNamesOfCronJobsToStart", "(", ")", ";", "if", "(", "!", "cronJobsToStart", "&&", "_shouldStartCrons", "(", ")", "&&", "Shared", ".", "isDbConnectionAvailable", "(", ")", "===", "true", ")", "{", ...
Start cron manager @returns {*} @private
[ "Start", "cron", "manager" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L284-L316
31,054
mia-js/mia-js-core
lib/mia-js.js
function () { const crons = _.get(Shared, 'runtimeArgs.cron') || _.get(Shared, 'runtimeArgs.crons'); if (crons) { const cronTasks = crons.replace(/\s/g, '').split(','); return cronTasks.length > 0 ? cronTasks : undefined; } return undefined; }
javascript
function () { const crons = _.get(Shared, 'runtimeArgs.cron') || _.get(Shared, 'runtimeArgs.crons'); if (crons) { const cronTasks = crons.replace(/\s/g, '').split(','); return cronTasks.length > 0 ? cronTasks : undefined; } return undefined; }
[ "function", "(", ")", "{", "const", "crons", "=", "_", ".", "get", "(", "Shared", ",", "'runtimeArgs.cron'", ")", "||", "_", ".", "get", "(", "Shared", ",", "'runtimeArgs.crons'", ")", ";", "if", "(", "crons", ")", "{", "const", "cronTasks", "=", "cr...
Checks process arguments if specific cron jobs should be started immediately. That's the case if there is a third argument like "cron=NameOfCronjobToStart,NameOfAnotherCronjobToStart" @returns {Array} Names of cron jobs to start @private
[ "Checks", "process", "arguments", "if", "specific", "cron", "jobs", "should", "be", "started", "immediately", ".", "That", "s", "the", "case", "if", "there", "is", "a", "third", "argument", "like", "cron", "=", "NameOfCronjobToStart", "NameOfAnotherCronjobToStart"...
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L324-L331
31,055
rapid7/rism
lib/rism.js
setResponsive
function setResponsive(name) { if (name) { setResponsiveComponents.call(this, name); } else { _utils2["default"].forEach(Object.keys(this._component), (function (name) { setResponsiveComponents.call(this, name); }).bind(this)); } if (_utils2["default"].isUndefined(name)) { _utils2["default"].forEach(this._matchMedias._orders, (function (query) { if (this._matchMedias[query].matches) { _utils2["default"].forIn(this._responsiveStyles[query], (function (style, key) { if (!this._styles[key]) { this._styles[key] = {}; } this[key] = _utils2["default"].merge(this._styles[key], (0, _reactPrefixer2["default"])(style)); }).bind(this)); } }).bind(this)); } }
javascript
function setResponsive(name) { if (name) { setResponsiveComponents.call(this, name); } else { _utils2["default"].forEach(Object.keys(this._component), (function (name) { setResponsiveComponents.call(this, name); }).bind(this)); } if (_utils2["default"].isUndefined(name)) { _utils2["default"].forEach(this._matchMedias._orders, (function (query) { if (this._matchMedias[query].matches) { _utils2["default"].forIn(this._responsiveStyles[query], (function (style, key) { if (!this._styles[key]) { this._styles[key] = {}; } this[key] = _utils2["default"].merge(this._styles[key], (0, _reactPrefixer2["default"])(style)); }).bind(this)); } }).bind(this)); } }
[ "function", "setResponsive", "(", "name", ")", "{", "if", "(", "name", ")", "{", "setResponsiveComponents", ".", "call", "(", "this", ",", "name", ")", ";", "}", "else", "{", "_utils2", "[", "\"default\"", "]", ".", "forEach", "(", "Object", ".", "keys...
set responsive values
[ "set", "responsive", "values" ]
cc1b8dd05175b0df375c0892edc4b1fefdf72b0f
https://github.com/rapid7/rism/blob/cc1b8dd05175b0df375c0892edc4b1fefdf72b0f/lib/rism.js#L154-L176
31,056
playmedia/http-cli
lib/config.js
loadDefault
function loadDefault() { return { port: 8000, host: '127.0.0.1', root: './', logFormat: 'combined', middlewares: [ { name: 'cors', cfg: { origin: true } }, { name: 'morgan', cfg: {} }, { name: 'serveStatic', cfg: {} }, { name: 'serveIndex', cfg: { icons: true } } ] } }
javascript
function loadDefault() { return { port: 8000, host: '127.0.0.1', root: './', logFormat: 'combined', middlewares: [ { name: 'cors', cfg: { origin: true } }, { name: 'morgan', cfg: {} }, { name: 'serveStatic', cfg: {} }, { name: 'serveIndex', cfg: { icons: true } } ] } }
[ "function", "loadDefault", "(", ")", "{", "return", "{", "port", ":", "8000", ",", "host", ":", "'127.0.0.1'", ",", "root", ":", "'./'", ",", "logFormat", ":", "'combined'", ",", "middlewares", ":", "[", "{", "name", ":", "'cors'", ",", "cfg", ":", "...
Get default HTTP server configuration. @return {Object} The HTTP server configuration.
[ "Get", "default", "HTTP", "server", "configuration", "." ]
81862084ef50cf9db6530b0da48cbe721355378f
https://github.com/playmedia/http-cli/blob/81862084ef50cf9db6530b0da48cbe721355378f/lib/config.js#L8-L37
31,057
playmedia/http-cli
lib/config.js
loadFromFile
function loadFromFile(filename) { var cfg = {} Object.assign( cfg, loadDefault(), JSON.parse(fs.readFileSync(filename)) ) return cfg }
javascript
function loadFromFile(filename) { var cfg = {} Object.assign( cfg, loadDefault(), JSON.parse(fs.readFileSync(filename)) ) return cfg }
[ "function", "loadFromFile", "(", "filename", ")", "{", "var", "cfg", "=", "{", "}", "Object", ".", "assign", "(", "cfg", ",", "loadDefault", "(", ")", ",", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "filename", ")", ")", ")", "return"...
Get HTTP server configuration from JSON file. @param {string} filename - The JSON filename. @throws Will throw an error if invalid filename or JSON. @return {Object} The HTTP server configuration.
[ "Get", "HTTP", "server", "configuration", "from", "JSON", "file", "." ]
81862084ef50cf9db6530b0da48cbe721355378f
https://github.com/playmedia/http-cli/blob/81862084ef50cf9db6530b0da48cbe721355378f/lib/config.js#L45-L54
31,058
playmedia/http-cli
lib/config.js
saveToFile
function saveToFile(filename, cfg) { // Use 'wx' flag to fails if filename exists fs.writeFileSync(filename, JSON.stringify(cfg, null, 2), {flag: 'wx'}) }
javascript
function saveToFile(filename, cfg) { // Use 'wx' flag to fails if filename exists fs.writeFileSync(filename, JSON.stringify(cfg, null, 2), {flag: 'wx'}) }
[ "function", "saveToFile", "(", "filename", ",", "cfg", ")", "{", "// Use 'wx' flag to fails if filename exists", "fs", ".", "writeFileSync", "(", "filename", ",", "JSON", ".", "stringify", "(", "cfg", ",", "null", ",", "2", ")", ",", "{", "flag", ":", "'wx'"...
Save HTTP server configuration to JSON file. @param {string} filename - The JSON filename. @param {Object} cfg - The HTTP server configuration. @throws Will throw an error if filename exists.
[ "Save", "HTTP", "server", "configuration", "to", "JSON", "file", "." ]
81862084ef50cf9db6530b0da48cbe721355378f
https://github.com/playmedia/http-cli/blob/81862084ef50cf9db6530b0da48cbe721355378f/lib/config.js#L62-L65
31,059
playmedia/http-cli
lib/config.js
loadFromOptions
function loadFromOptions(opts) { var defCfg = loadDefault() var cfg = opts.config ? loadFromFile(opts.config) : loadDefault() // Command line config override file loaded config for (var k in opts) { defCfg.hasOwnProperty(k) && (defCfg[k] !== opts[k] && (cfg[k] = opts[k])) } return cfg }
javascript
function loadFromOptions(opts) { var defCfg = loadDefault() var cfg = opts.config ? loadFromFile(opts.config) : loadDefault() // Command line config override file loaded config for (var k in opts) { defCfg.hasOwnProperty(k) && (defCfg[k] !== opts[k] && (cfg[k] = opts[k])) } return cfg }
[ "function", "loadFromOptions", "(", "opts", ")", "{", "var", "defCfg", "=", "loadDefault", "(", ")", "var", "cfg", "=", "opts", ".", "config", "?", "loadFromFile", "(", "opts", ".", "config", ")", ":", "loadDefault", "(", ")", "// Command line config overrid...
Get HTTP server configuration from command line options. @param {Object} opts - The command line options. @return {Object} The HTTP server configuration.
[ "Get", "HTTP", "server", "configuration", "from", "command", "line", "options", "." ]
81862084ef50cf9db6530b0da48cbe721355378f
https://github.com/playmedia/http-cli/blob/81862084ef50cf9db6530b0da48cbe721355378f/lib/config.js#L72-L82
31,060
mia-js/mia-js-core
lib/moduleLoader/lib/requireAll.js
function (options, iterationInfo) { var files; var modules = {}; var result = {}; // remember the starting directory try { files = fs.readdirSync(iterationInfo.dirName); } catch (e) { if (options.optional) return {}; else throw new Error('Directory not found: ' + iterationInfo.dirName); } // iterate through files in the current directory files.forEach(function (fileName) { iterationInfo.dirName = iterationInfo.initialDirName + '/' + fileName + '/' + options.moduleDir; iterationInfo.projectDir = iterationInfo.initialDirName + '/' + fileName; result = _.assign(doInterations(options, iterationInfo), result); }); return result; }
javascript
function (options, iterationInfo) { var files; var modules = {}; var result = {}; // remember the starting directory try { files = fs.readdirSync(iterationInfo.dirName); } catch (e) { if (options.optional) return {}; else throw new Error('Directory not found: ' + iterationInfo.dirName); } // iterate through files in the current directory files.forEach(function (fileName) { iterationInfo.dirName = iterationInfo.initialDirName + '/' + fileName + '/' + options.moduleDir; iterationInfo.projectDir = iterationInfo.initialDirName + '/' + fileName; result = _.assign(doInterations(options, iterationInfo), result); }); return result; }
[ "function", "(", "options", ",", "iterationInfo", ")", "{", "var", "files", ";", "var", "modules", "=", "{", "}", ";", "var", "result", "=", "{", "}", ";", "// remember the starting directory", "try", "{", "files", "=", "fs", ".", "readdirSync", "(", "it...
Parses a directory and searches for options.module subdir. If found subdir is searched for required files @param options @param iterationInfo @returns {{}}
[ "Parses", "a", "directory", "and", "searches", "for", "options", ".", "module", "subdir", ".", "If", "found", "subdir", "is", "searched", "for", "required", "files" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L100-L123
31,061
mia-js/mia-js-core
lib/moduleLoader/lib/requireAll.js
function (options, iterationInfo, modules) { // filename filter if (options.fileNameFilter) { var match = iterationInfo.fileName.match(options.fileNameFilter); if (!match) { return; } } // Filter spec.js files var match = iterationInfo.fileName.match(/.spec.js/i); if (match) { return; } // relative path filter if (options.relativePathFilter) { var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter); if (!pathMatch) return; } //load module loadModule(modules, options, iterationInfo); }
javascript
function (options, iterationInfo, modules) { // filename filter if (options.fileNameFilter) { var match = iterationInfo.fileName.match(options.fileNameFilter); if (!match) { return; } } // Filter spec.js files var match = iterationInfo.fileName.match(/.spec.js/i); if (match) { return; } // relative path filter if (options.relativePathFilter) { var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter); if (!pathMatch) return; } //load module loadModule(modules, options, iterationInfo); }
[ "function", "(", "options", ",", "iterationInfo", ",", "modules", ")", "{", "// filename filter", "if", "(", "options", ".", "fileNameFilter", ")", "{", "var", "match", "=", "iterationInfo", ".", "fileName", ".", "match", "(", "options", ".", "fileNameFilter",...
Process single file to module dictionary @param options @param fileName @param modules
[ "Process", "single", "file", "to", "module", "dictionary" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L181-L205
31,062
mia-js/mia-js-core
lib/moduleLoader/lib/requireAll.js
function (modules, options, iterationInfo) { // load module into memory (unless `dontLoad` is true) var module = true; //default is options.dontLoad === false if (options.dontLoad !== true) { //if module is to be loaded module = require(iterationInfo.absoluteFullPath); // If a module is found but was loaded as 'undefined', don't include it (since it's probably unusable) if (typeof module === 'undefined') { throw new Error('Invalid module:' + iterationInfo.absoluteFullPath); } var identity; //var name; var version; if (options.useVersions === true) { if (module.version) { version = module.version; } else { version = '1.0'; } } if (module.identity) { identity = module.identity; //name = identity; } else { identity = generateIdentity(options, iterationInfo); //name = identity; } //consider default options.injectIdentity === true if (options.injectIdentity !== false) { module.fileName = iterationInfo.fileName; module.projectDir = iterationInfo.projectDir; module.relativePath = iterationInfo.relativePath; module.relativeFullPath = iterationInfo.relativeFullPath; module.absolutePath = iterationInfo.absolutePath; module.absoluteFullPath = iterationInfo.absoluteFullPath; module.identity = identity; //module.name = name; if (options.useVersions === true) { module.version = version; } } else { identity = generateIdentity(options, iterationInfo); } //check if identity is unique within the collection and add to dictionary if (options.useVersions === true) { if (modules[identity] && modules[identity][version]) { var anotherModule = modules[identity][version]; throw new Error("Identity '" + identity + "' with version '" + version + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'"); } modules[identity] = modules[identity] || {}; modules[identity][version] = module; } else { var anotherModule = modules[identity]; if (anotherModule) { throw new Error("Identity '" + identity + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'"); } modules[identity] = module; } } }
javascript
function (modules, options, iterationInfo) { // load module into memory (unless `dontLoad` is true) var module = true; //default is options.dontLoad === false if (options.dontLoad !== true) { //if module is to be loaded module = require(iterationInfo.absoluteFullPath); // If a module is found but was loaded as 'undefined', don't include it (since it's probably unusable) if (typeof module === 'undefined') { throw new Error('Invalid module:' + iterationInfo.absoluteFullPath); } var identity; //var name; var version; if (options.useVersions === true) { if (module.version) { version = module.version; } else { version = '1.0'; } } if (module.identity) { identity = module.identity; //name = identity; } else { identity = generateIdentity(options, iterationInfo); //name = identity; } //consider default options.injectIdentity === true if (options.injectIdentity !== false) { module.fileName = iterationInfo.fileName; module.projectDir = iterationInfo.projectDir; module.relativePath = iterationInfo.relativePath; module.relativeFullPath = iterationInfo.relativeFullPath; module.absolutePath = iterationInfo.absolutePath; module.absoluteFullPath = iterationInfo.absoluteFullPath; module.identity = identity; //module.name = name; if (options.useVersions === true) { module.version = version; } } else { identity = generateIdentity(options, iterationInfo); } //check if identity is unique within the collection and add to dictionary if (options.useVersions === true) { if (modules[identity] && modules[identity][version]) { var anotherModule = modules[identity][version]; throw new Error("Identity '" + identity + "' with version '" + version + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'"); } modules[identity] = modules[identity] || {}; modules[identity][version] = module; } else { var anotherModule = modules[identity]; if (anotherModule) { throw new Error("Identity '" + identity + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'"); } modules[identity] = module; } } }
[ "function", "(", "modules", ",", "options", ",", "iterationInfo", ")", "{", "// load module into memory (unless `dontLoad` is true)", "var", "module", "=", "true", ";", "//default is options.dontLoad === false", "if", "(", "options", ".", "dontLoad", "!==", "true", ")",...
Load single module @param modules @param options @param iterationInfo
[ "Load", "single", "module" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L213-L285
31,063
mia-js/mia-js-core
lib/moduleLoader/lib/requireAll.js
function (options, iterationInfo) { // Use the identity for the key name var identity; if (options.mode === 'list') { identity = iterationInfo.relativeFullPath; //identity = identity.toLowerCase(); //find and replace all containments of '/', ':' and '\' within the string identity = identity.replace(/\/|\\|:/g, ''); } else if (options.mode === 'tree') { identity = iterationInfo.fileName; //identity = identity.toLowerCase(); } else throw new Error('Unknown mode'); //remove extention identity = identity.substr(0, identity.lastIndexOf('.')) || identity; return identity; }
javascript
function (options, iterationInfo) { // Use the identity for the key name var identity; if (options.mode === 'list') { identity = iterationInfo.relativeFullPath; //identity = identity.toLowerCase(); //find and replace all containments of '/', ':' and '\' within the string identity = identity.replace(/\/|\\|:/g, ''); } else if (options.mode === 'tree') { identity = iterationInfo.fileName; //identity = identity.toLowerCase(); } else throw new Error('Unknown mode'); //remove extention identity = identity.substr(0, identity.lastIndexOf('.')) || identity; return identity; }
[ "function", "(", "options", ",", "iterationInfo", ")", "{", "// Use the identity for the key name", "var", "identity", ";", "if", "(", "options", ".", "mode", "===", "'list'", ")", "{", "identity", "=", "iterationInfo", ".", "relativeFullPath", ";", "//identity = ...
Generates identity for a module @param options @param iterationInfo @returns {string}
[ "Generates", "identity", "for", "a", "module" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L293-L313
31,064
mia-js/mia-js-core
lib/moduleLoader/lib/requireAll.js
function (options, iterationInfo, modules) { // Ignore explicitly excluded directories if (options.excludeDirs) { var match = iterationInfo.fileName.match(options.excludeDirs); if (match) return; } // Recursively call requireAll on each child directory var subIterationInfo = _.clone(iterationInfo); ++subIterationInfo.depth; subIterationInfo.dirName = iterationInfo.absoluteFullPath; //process subtree recursively var subTreeResult = doInterations(options, subIterationInfo); //omit empty dirs if (_.isEmpty(subTreeResult)) return; //add to the list or to the subtree if (options.mode === 'list') { //check uniqueness _.forEach(subTreeResult, function (value, index) { if (options.useVersions === true) { modules[index] = modules[index] || {}; _.forEach(value, function (versionValue, versionIndex) { if (modules[index][versionIndex]) throw new Error("Identity '" + index + "' with version '" + versionIndex + "' is already registered by module at '" + modules[index][versionIndex].absoluteFullPath + "'"); modules[index][versionIndex] = versionValue; }); } else { if (modules[index]) throw new Error("Identity '" + index + "' is already registered by module at '" + modules[index].absoluteFullPath + "'"); modules[index] = value; } }) } else if (options.mode === 'tree') { if (options.markDirectories !== false) { subTreeResult.isDirectory = true; } var identity = generateIdentity(options, iterationInfo); modules[identity] = subTreeResult; } else throw new Error('Unknown mode'); }
javascript
function (options, iterationInfo, modules) { // Ignore explicitly excluded directories if (options.excludeDirs) { var match = iterationInfo.fileName.match(options.excludeDirs); if (match) return; } // Recursively call requireAll on each child directory var subIterationInfo = _.clone(iterationInfo); ++subIterationInfo.depth; subIterationInfo.dirName = iterationInfo.absoluteFullPath; //process subtree recursively var subTreeResult = doInterations(options, subIterationInfo); //omit empty dirs if (_.isEmpty(subTreeResult)) return; //add to the list or to the subtree if (options.mode === 'list') { //check uniqueness _.forEach(subTreeResult, function (value, index) { if (options.useVersions === true) { modules[index] = modules[index] || {}; _.forEach(value, function (versionValue, versionIndex) { if (modules[index][versionIndex]) throw new Error("Identity '" + index + "' with version '" + versionIndex + "' is already registered by module at '" + modules[index][versionIndex].absoluteFullPath + "'"); modules[index][versionIndex] = versionValue; }); } else { if (modules[index]) throw new Error("Identity '" + index + "' is already registered by module at '" + modules[index].absoluteFullPath + "'"); modules[index] = value; } }) } else if (options.mode === 'tree') { if (options.markDirectories !== false) { subTreeResult.isDirectory = true; } var identity = generateIdentity(options, iterationInfo); modules[identity] = subTreeResult; } else throw new Error('Unknown mode'); }
[ "function", "(", "options", ",", "iterationInfo", ",", "modules", ")", "{", "// Ignore explicitly excluded directories", "if", "(", "options", ".", "excludeDirs", ")", "{", "var", "match", "=", "iterationInfo", ".", "fileName", ".", "match", "(", "options", ".",...
Processes one directory level @param options :: general options @param iterationInfo :: iteration options @param modules :: object in which output will be loaded
[ "Processes", "one", "directory", "level" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L321-L371
31,065
mia-js/mia-js-core
lib/logger/lib/logger.js
function (level, message, tag, data) { var env = Shared.config('environment'); var levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace']; var logLevelConfig = env.logLevel || "info"; if (logLevelConfig == "none") { return; } var logLevel = levels.indexOf(logLevelConfig) >= 0 ? logLevelConfig : 'info'; // Set default error logging if (_.isObject(message) && _.isEmpty(data)) { if (message.message && _.isString(message.message)) { data = message.stack || ""; message = message.message; } else { data = message; message = null; } } //Output if (levels.indexOf(level) <= levels.indexOf(logLevel)) { var logString = ""; if (env.logFormat === 'json') { logString = JSON.stringify({ timestamp: new Date().toISOString(), level, tag, message, data, hostname: Shared.getCurrentHostId(), pid: process.pid, mode: env.mode }); } else { if (_.isObject(data)) { data = Util.inspect(data, {showHidden: false, depth: null}); } logString += new Date().toISOString() + ' '; logString += '[' + level + ']'; logString += tag == "default" ? "" : ' [' + tag + ']'; logString += !_.isString(message) ? "" : ': ' + message; logString += data ? ' --> ' + data : ""; } if (["error", "fatal"].indexOf(level) >= 0) { _outputLog("error", logString); } else if (level == "warn") { _outputLog("warn", logString); } else { _outputLog("info", logString); } } }
javascript
function (level, message, tag, data) { var env = Shared.config('environment'); var levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace']; var logLevelConfig = env.logLevel || "info"; if (logLevelConfig == "none") { return; } var logLevel = levels.indexOf(logLevelConfig) >= 0 ? logLevelConfig : 'info'; // Set default error logging if (_.isObject(message) && _.isEmpty(data)) { if (message.message && _.isString(message.message)) { data = message.stack || ""; message = message.message; } else { data = message; message = null; } } //Output if (levels.indexOf(level) <= levels.indexOf(logLevel)) { var logString = ""; if (env.logFormat === 'json') { logString = JSON.stringify({ timestamp: new Date().toISOString(), level, tag, message, data, hostname: Shared.getCurrentHostId(), pid: process.pid, mode: env.mode }); } else { if (_.isObject(data)) { data = Util.inspect(data, {showHidden: false, depth: null}); } logString += new Date().toISOString() + ' '; logString += '[' + level + ']'; logString += tag == "default" ? "" : ' [' + tag + ']'; logString += !_.isString(message) ? "" : ': ' + message; logString += data ? ' --> ' + data : ""; } if (["error", "fatal"].indexOf(level) >= 0) { _outputLog("error", logString); } else if (level == "warn") { _outputLog("warn", logString); } else { _outputLog("info", logString); } } }
[ "function", "(", "level", ",", "message", ",", "tag", ",", "data", ")", "{", "var", "env", "=", "Shared", ".", "config", "(", "'environment'", ")", ";", "var", "levels", "=", "[", "'fatal'", ",", "'error'", ",", "'warn'", ",", "'info'", ",", "'debug'...
Write logging information @param level => 'none', 'fatal', 'error', 'warn', 'info', 'debug', 'trace' @param message = >Error message @param tag => Tags of log info i.e. database, request. Default is 'default' or empty @param data => Any data object @private
[ "Write", "logging", "information" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/logger/lib/logger.js#L23-L82
31,066
mia-js/mia-js-core
lib/logger/lib/logger.js
function (obj, tag) { tag = _.isArray(tag) ? tag.join(',') : tag; tag = !_.isEmpty(tag) ? tag.toLowerCase() : 'default'; obj.trace = function (message, data) { _logEvent("trace", message, tag, data); }; obj.debug = function (message, data) { _logEvent("debug", message, tag, data); }; obj.info = function (message, data) { _logEvent("info", message, tag, data); }; obj.warn = function (message, data) { _logEvent("warn", message, tag, data); }; obj.error = function (message, data) { _logEvent("error", message, tag, data); }; obj.fatal = function (message, data) { _logEvent("fatal", message, tag, data); }; return obj; }
javascript
function (obj, tag) { tag = _.isArray(tag) ? tag.join(',') : tag; tag = !_.isEmpty(tag) ? tag.toLowerCase() : 'default'; obj.trace = function (message, data) { _logEvent("trace", message, tag, data); }; obj.debug = function (message, data) { _logEvent("debug", message, tag, data); }; obj.info = function (message, data) { _logEvent("info", message, tag, data); }; obj.warn = function (message, data) { _logEvent("warn", message, tag, data); }; obj.error = function (message, data) { _logEvent("error", message, tag, data); }; obj.fatal = function (message, data) { _logEvent("fatal", message, tag, data); }; return obj; }
[ "function", "(", "obj", ",", "tag", ")", "{", "tag", "=", "_", ".", "isArray", "(", "tag", ")", "?", "tag", ".", "join", "(", "','", ")", ":", "tag", ";", "tag", "=", "!", "_", ".", "isEmpty", "(", "tag", ")", "?", "tag", ".", "toLowerCase", ...
Provide log methods @param obj @param tag @returns {*}
[ "Provide", "log", "methods" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/logger/lib/logger.js#L100-L129
31,067
AndreasPizsa/grunt-update-json
tasks/lib/update_json.js
expandField
function expandField(input, grunt){ var get = pointer(input); return function(memo, fin, fout){ if(_.isString(fin)){ var match = fin.match(re.PATH_POINT); // matched ...with a `$.` ...but not with a `\` if(match && match[3] === '$.' && !match[1]){ // field name, starts with an unescaped `$`, treat as JSON Path memo[fout] = jsonPath(input, match[2]); }else if(match && match[3] === '/' && !match[1]){ // field name, treat as a JSON pointer memo[fout] = get(match[2]); }else{ memo[fout] = input[match[2]]; } }else if(_.isFunction(fin)){ // call a function memo[fout] = fin(input); }else if(_.isArray(fin)){ // pick out the values memo[fout] = _.map(fin, function(value){ return expandField(input)({}, value, "dummy")["dummy"]; }); }else if(_.isObject(fin)){ // build up an object of something else memo[fout] = _.reduce(fin, expandField(input, grunt), {}); }else if(_.isNull(fin)){ // copy the value memo[fout] = input[fout]; }else{ grunt.fail.warn('Could not map `' + JSON.stringify(fin) + '` to `' + JSON.stringify(fout) + '`'); } return memo; }; }
javascript
function expandField(input, grunt){ var get = pointer(input); return function(memo, fin, fout){ if(_.isString(fin)){ var match = fin.match(re.PATH_POINT); // matched ...with a `$.` ...but not with a `\` if(match && match[3] === '$.' && !match[1]){ // field name, starts with an unescaped `$`, treat as JSON Path memo[fout] = jsonPath(input, match[2]); }else if(match && match[3] === '/' && !match[1]){ // field name, treat as a JSON pointer memo[fout] = get(match[2]); }else{ memo[fout] = input[match[2]]; } }else if(_.isFunction(fin)){ // call a function memo[fout] = fin(input); }else if(_.isArray(fin)){ // pick out the values memo[fout] = _.map(fin, function(value){ return expandField(input)({}, value, "dummy")["dummy"]; }); }else if(_.isObject(fin)){ // build up an object of something else memo[fout] = _.reduce(fin, expandField(input, grunt), {}); }else if(_.isNull(fin)){ // copy the value memo[fout] = input[fout]; }else{ grunt.fail.warn('Could not map `' + JSON.stringify(fin) + '` to `' + JSON.stringify(fout) + '`'); } return memo; }; }
[ "function", "expandField", "(", "input", ",", "grunt", ")", "{", "var", "get", "=", "pointer", "(", "input", ")", ";", "return", "function", "(", "memo", ",", "fin", ",", "fout", ")", "{", "if", "(", "_", ".", "isString", "(", "fin", ")", ")", "{...
factory for a reduce function, bound to the input, that can get the value out of the input
[ "factory", "for", "a", "reduce", "function", "bound", "to", "the", "input", "that", "can", "get", "the", "value", "out", "of", "the", "input" ]
c85f6575a039c665371ce411f0d47e2a264bb3b6
https://github.com/AndreasPizsa/grunt-update-json/blob/c85f6575a039c665371ce411f0d47e2a264bb3b6/tasks/lib/update_json.js#L46-L82
31,068
voxgig/seneca-hapi
hapi.js
action_handler
async function action_handler(req, h) { const data = req.payload const json = 'string' === typeof data ? tu.parseJSON(data) : data if (json instanceof Error) { throw json } const seneca = prepare_seneca(req, json) const msg = tu.internalize_msg(seneca, json) return await new Promise(resolve => { var out = null for (var i = 0; i < modify_action.length; i++) { out = modify_action[i].call(seneca, msg, req) if (out) { return resolve(out) } } seneca.act(msg, function(err, out, meta) { if (err && !options.debug) { err.stack = null } resolve(tu.externalize_reply(this, err, out, meta)) }) }) }
javascript
async function action_handler(req, h) { const data = req.payload const json = 'string' === typeof data ? tu.parseJSON(data) : data if (json instanceof Error) { throw json } const seneca = prepare_seneca(req, json) const msg = tu.internalize_msg(seneca, json) return await new Promise(resolve => { var out = null for (var i = 0; i < modify_action.length; i++) { out = modify_action[i].call(seneca, msg, req) if (out) { return resolve(out) } } seneca.act(msg, function(err, out, meta) { if (err && !options.debug) { err.stack = null } resolve(tu.externalize_reply(this, err, out, meta)) }) }) }
[ "async", "function", "action_handler", "(", "req", ",", "h", ")", "{", "const", "data", "=", "req", ".", "payload", "const", "json", "=", "'string'", "===", "typeof", "data", "?", "tu", ".", "parseJSON", "(", "data", ")", ":", "data", "if", "(", "jso...
Convenience handler to call a seneca action directly from inbound POST JSON.
[ "Convenience", "handler", "to", "call", "a", "seneca", "action", "directly", "from", "inbound", "POST", "JSON", "." ]
377c0e8c38bc2703686fcffa85a5999c93f9ef1c
https://github.com/voxgig/seneca-hapi/blob/377c0e8c38bc2703686fcffa85a5999c93f9ef1c/hapi.js#L64-L91
31,069
mia-js/mia-js-core
lib/cronJobs/lib/jobManagementDbConnector.js
function () { return ServerHeartbeatModel.find({ status: _statusActive }).then(function (cursor) { return Q.ninvoke(cursor, 'toArray').then(function (servers) { var serverIds = []; servers.map(function (value) { serverIds.push(value._id); }); return _removeAllJobsOfUnknownServer(serverIds); }); }); }
javascript
function () { return ServerHeartbeatModel.find({ status: _statusActive }).then(function (cursor) { return Q.ninvoke(cursor, 'toArray').then(function (servers) { var serverIds = []; servers.map(function (value) { serverIds.push(value._id); }); return _removeAllJobsOfUnknownServer(serverIds); }); }); }
[ "function", "(", ")", "{", "return", "ServerHeartbeatModel", ".", "find", "(", "{", "status", ":", "_statusActive", "}", ")", ".", "then", "(", "function", "(", "cursor", ")", "{", "return", "Q", ".", "ninvoke", "(", "cursor", ",", "'toArray'", ")", "....
Remove unknown serverIds from jobslist, can happen while server restart
[ "Remove", "unknown", "serverIds", "from", "jobslist", "can", "happen", "while", "server", "restart" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/cronJobs/lib/jobManagementDbConnector.js#L301-L313
31,070
jbaicoianu/elation
components/utils/scripts/dust.js
function( input, chunk, context ){ // return given input if there is no dust reference to resolve var output = input; // dust compiles a string to function, if there are references if( typeof input === "function"){ if( ( typeof input.isReference !== "undefined" ) && ( input.isReference === true ) ){ // just a plain function, not a dust `body` function output = input(); } else { output = ''; chunk.tap(function(data){ output += data; return ''; }).render(input, context).untap(); if( output === '' ){ output = false; } } } return output; }
javascript
function( input, chunk, context ){ // return given input if there is no dust reference to resolve var output = input; // dust compiles a string to function, if there are references if( typeof input === "function"){ if( ( typeof input.isReference !== "undefined" ) && ( input.isReference === true ) ){ // just a plain function, not a dust `body` function output = input(); } else { output = ''; chunk.tap(function(data){ output += data; return ''; }).render(input, context).untap(); if( output === '' ){ output = false; } } } return output; }
[ "function", "(", "input", ",", "chunk", ",", "context", ")", "{", "// return given input if there is no dust reference to resolve", "var", "output", "=", "input", ";", "// dust compiles a string to function, if there are references", "if", "(", "typeof", "input", "===", "\"...
Utility helping to resolve dust references in the given chunk
[ "Utility", "helping", "to", "resolve", "dust", "references", "in", "the", "given", "chunk" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/dust.js#L655-L674
31,071
jbaicoianu/elation
components/utils/scripts/dust.js
compactBuffers
function compactBuffers(context, node) { var out = [node[0]], memo; for (var i=1, len=node.length; i<len; i++) { var res = dust.filterNode(context, node[i]); if (res) { if (res[0] === 'buffer') { if (memo) { memo[1] += res[1]; } else { memo = res; out.push(res); } } else { memo = null; out.push(res); } } } return out; }
javascript
function compactBuffers(context, node) { var out = [node[0]], memo; for (var i=1, len=node.length; i<len; i++) { var res = dust.filterNode(context, node[i]); if (res) { if (res[0] === 'buffer') { if (memo) { memo[1] += res[1]; } else { memo = res; out.push(res); } } else { memo = null; out.push(res); } } } return out; }
[ "function", "compactBuffers", "(", "context", ",", "node", ")", "{", "var", "out", "=", "[", "node", "[", "0", "]", "]", ",", "memo", ";", "for", "(", "var", "i", "=", "1", ",", "len", "=", "node", ".", "length", ";", "i", "<", "len", ";", "i...
Compacts consecutive buffer nodes into a single node
[ "Compacts", "consecutive", "buffer", "nodes", "into", "a", "single", "node" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/dust.js#L838-L857
31,072
mia-js/mia-js-core
lib/utils/lib/ipAddressHelper.js
thisModule
function thisModule() { var self = this; /** * Generate random hash value * @returns {*} */ self.getClientIP = function (req) { req = req || {}; req.connection = req.connection || {}; req.socket = req.socket || {}; req.client = req.client || {}; var ipString = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.client.remoteAddress || req.ip || ""; var ips = ipString.split(","); if (ips.length > 0) { return ips[0]; } else { return; } }; return self; }
javascript
function thisModule() { var self = this; /** * Generate random hash value * @returns {*} */ self.getClientIP = function (req) { req = req || {}; req.connection = req.connection || {}; req.socket = req.socket || {}; req.client = req.client || {}; var ipString = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.client.remoteAddress || req.ip || ""; var ips = ipString.split(","); if (ips.length > 0) { return ips[0]; } else { return; } }; return self; }
[ "function", "thisModule", "(", ")", "{", "var", "self", "=", "this", ";", "/**\n * Generate random hash value\n * @returns {*}\n */", "self", ".", "getClientIP", "=", "function", "(", "req", ")", "{", "req", "=", "req", "||", "{", "}", ";", "req", ...
Determine Clients IP Address @param err @returns {*}
[ "Determine", "Clients", "IP", "Address" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/utils/lib/ipAddressHelper.js#L7-L31
31,073
AmpersandJS/ampersand-dom
ampersand-dom.js
function (el, cls) { cls = getString(cls); if (!cls) return; if (Array.isArray(cls)) { cls.forEach(function(c) { dom.addClass(el, c); }); } else if (el.classList) { el.classList.add(cls); } else { if (!hasClass(el, cls)) { if (el.classList) { el.classList.add(cls); } else { el.className += ' ' + cls; } } } }
javascript
function (el, cls) { cls = getString(cls); if (!cls) return; if (Array.isArray(cls)) { cls.forEach(function(c) { dom.addClass(el, c); }); } else if (el.classList) { el.classList.add(cls); } else { if (!hasClass(el, cls)) { if (el.classList) { el.classList.add(cls); } else { el.className += ' ' + cls; } } } }
[ "function", "(", "el", ",", "cls", ")", "{", "cls", "=", "getString", "(", "cls", ")", ";", "if", "(", "!", "cls", ")", "return", ";", "if", "(", "Array", ".", "isArray", "(", "cls", ")", ")", "{", "cls", ".", "forEach", "(", "function", "(", ...
optimize if we have classList
[ "optimize", "if", "we", "have", "classList" ]
7a79f8a2a6c0bba16eb6d9f5e81295c0286aafa9
https://github.com/AmpersandJS/ampersand-dom/blob/7a79f8a2a6c0bba16eb6d9f5e81295c0286aafa9/ampersand-dom.js#L7-L25
31,074
jbaicoianu/elation
components/utils/scripts/elation.js
function(name, container, args, events) { /* handling for any default values if args are not specified */ var mergeDefaults = function(args, defaults) { var args = args || {}; if (typeof defaults == 'object') { for (var key in defaults) { if (elation.utils.isNull(args[key])) { args[key] = defaults[key]; } } } return args; }; var realname = name; if (elation.utils.isObject(name)) { // Simple syntax just takes an object with all arguments args = name; realname = elation.utils.any(args.id, args.name, null); container = (!elation.utils.isNull(args.container) ? args.container : null); events = (!elation.utils.isNull(args.events) ? args.events : null); } // If no args were passed in, we're probably being used as the base for another // component's prototype, so there's no need to go through full init if (elation.utils.isNull(realname) && !container && !args) { var obj = new component.base(type); // apply default args obj.args = mergeDefaults(obj.args, elation.utils.clone(obj.defaults)); return obj; } // If no name was passed, use the current object count as a name instead ("anonymous" components) if (elation.utils.isNull(realname) || realname === "") { realname = component.objcount; } if (!component.obj[realname] && !elation.utils.isEmpty(args)) { component.obj[realname] = obj = new component.base(type); component.objcount++; //} // TODO - I think combining this logic would let us use components without needing HTML elements for the container //if (component.obj[realname] && container !== undefined) { component.obj[realname].componentinit(type, realname, container, args, events); /* if (component.extendclass) { component.obj[realname].initSuperClass(component.extendclass); } */ // fix handling for append component infinite recursion issue if (args.append instanceof elation.component.base) args.append = args.append.container; if (args.before instanceof elation.component.base) args.before = args.before.container; // apply default args try { if (typeof obj.defaults == 'object') args = mergeDefaults(args, elation.utils.clone(obj.defaults)); var parentclass = component.extendclass; // recursively apply inherited defaults while (parentclass) { if (typeof parentclass.defaults == 'object') elation.utils.merge(mergeDefaults(args, elation.utils.clone(parentclass.defaults)),args); parentclass = parentclass.extendclass; } } catch (e) { console.log('-!- Error merging component args', e.msg); } if (typeof obj.init == 'function') { obj.init(realname, container, args, events); } } return component.obj[realname]; }
javascript
function(name, container, args, events) { /* handling for any default values if args are not specified */ var mergeDefaults = function(args, defaults) { var args = args || {}; if (typeof defaults == 'object') { for (var key in defaults) { if (elation.utils.isNull(args[key])) { args[key] = defaults[key]; } } } return args; }; var realname = name; if (elation.utils.isObject(name)) { // Simple syntax just takes an object with all arguments args = name; realname = elation.utils.any(args.id, args.name, null); container = (!elation.utils.isNull(args.container) ? args.container : null); events = (!elation.utils.isNull(args.events) ? args.events : null); } // If no args were passed in, we're probably being used as the base for another // component's prototype, so there's no need to go through full init if (elation.utils.isNull(realname) && !container && !args) { var obj = new component.base(type); // apply default args obj.args = mergeDefaults(obj.args, elation.utils.clone(obj.defaults)); return obj; } // If no name was passed, use the current object count as a name instead ("anonymous" components) if (elation.utils.isNull(realname) || realname === "") { realname = component.objcount; } if (!component.obj[realname] && !elation.utils.isEmpty(args)) { component.obj[realname] = obj = new component.base(type); component.objcount++; //} // TODO - I think combining this logic would let us use components without needing HTML elements for the container //if (component.obj[realname] && container !== undefined) { component.obj[realname].componentinit(type, realname, container, args, events); /* if (component.extendclass) { component.obj[realname].initSuperClass(component.extendclass); } */ // fix handling for append component infinite recursion issue if (args.append instanceof elation.component.base) args.append = args.append.container; if (args.before instanceof elation.component.base) args.before = args.before.container; // apply default args try { if (typeof obj.defaults == 'object') args = mergeDefaults(args, elation.utils.clone(obj.defaults)); var parentclass = component.extendclass; // recursively apply inherited defaults while (parentclass) { if (typeof parentclass.defaults == 'object') elation.utils.merge(mergeDefaults(args, elation.utils.clone(parentclass.defaults)),args); parentclass = parentclass.extendclass; } } catch (e) { console.log('-!- Error merging component args', e.msg); } if (typeof obj.init == 'function') { obj.init(realname, container, args, events); } } return component.obj[realname]; }
[ "function", "(", "name", ",", "container", ",", "args", ",", "events", ")", "{", "/* handling for any default values if args are not specified */", "var", "mergeDefaults", "=", "function", "(", "args", ",", "defaults", ")", "{", "var", "args", "=", "args", "||", ...
At the top level, a component is just a function which checks to see if an instance with the given name exists already. If it doesn't we create it, and then we return a reference to the specified instance.
[ "At", "the", "top", "level", "a", "component", "is", "just", "a", "function", "which", "checks", "to", "see", "if", "an", "instance", "with", "the", "given", "name", "exists", "already", ".", "If", "it", "doesn", "t", "we", "create", "it", "and", "then...
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/elation.js#L238-L322
31,075
healthsparq/ember-fountainhead
lib/parse-markdown.js
function(description) { // Look for triple backtick code blocks flagged as `glimmer`; // define end of block as triple backticks followed by a newline let matches = description.match(/(```glimmer)(.|\n)*?```/gi); if (matches && matches.length) { matches.map(codeBlock => { let blockEnd = codeBlock.length + description.indexOf(codeBlock); let plainCode = codeBlock.replace(/(```glimmer|```)/gi, ''); description = `${description.slice(0, (blockEnd))}${plainCode}${ description.slice(blockEnd)}`; }); } return description; }
javascript
function(description) { // Look for triple backtick code blocks flagged as `glimmer`; // define end of block as triple backticks followed by a newline let matches = description.match(/(```glimmer)(.|\n)*?```/gi); if (matches && matches.length) { matches.map(codeBlock => { let blockEnd = codeBlock.length + description.indexOf(codeBlock); let plainCode = codeBlock.replace(/(```glimmer|```)/gi, ''); description = `${description.slice(0, (blockEnd))}${plainCode}${ description.slice(blockEnd)}`; }); } return description; }
[ "function", "(", "description", ")", "{", "// Look for triple backtick code blocks flagged as `glimmer`;", "// define end of block as triple backticks followed by a newline", "let", "matches", "=", "description", ".", "match", "(", "/", "(```glimmer)(.|\\n)*?```", "/", "gi", ")",...
Scans the description text for instances of markdown code blocks flagged as `"glimmer"` syntax. If any such instances are found, they are copied, stripped of their triple backticks and re-inserted into the `templateString` immediately after the original declaration. This allows for functional copies of your code examples to be automatically rendered into the description, without having to duplicate the code block itself. If your functional code needs to have different setup to work correctly in the Fountainhead context (for example, if you need to use `core-state` to set up sandboxed state and controls), simply use `"handlebars"` or no syntax flag, and manually add the code block you want Fountainhead to render after your example. Neato! @method _renderCodeBlocks @param {String} description The description text to scan for code blocks @return {String}
[ "Scans", "the", "description", "text", "for", "instances", "of", "markdown", "code", "blocks", "flagged", "as", "glimmer", "syntax", ".", "If", "any", "such", "instances", "are", "found", "they", "are", "copied", "stripped", "of", "their", "triple", "backticks...
3577546719b251385ca1093f812889590459205a
https://github.com/healthsparq/ember-fountainhead/blob/3577546719b251385ca1093f812889590459205a/lib/parse-markdown.js#L101-L115
31,076
jbaicoianu/elation
components/utils/htdocs/scripts/jsmart.js
obMerge
function obMerge(prefix, ob1, ob2 /*, ...*/) { for (var i=2; i<arguments.length; ++i) { for (var nm in arguments[i]) { if (arguments[i].hasOwnProperty(nm) || typeof arguments[i][nm] == 'function') { if (typeof(arguments[i][nm]) == 'object' && arguments[i][nm] != null) { ob1[prefix+nm] = (arguments[i][nm] instanceof Array) ? new Array : new Object; obMerge('', ob1[prefix+nm], arguments[i][nm]); } else { ob1[prefix+nm] = arguments[i][nm]; } } } } return ob1; }
javascript
function obMerge(prefix, ob1, ob2 /*, ...*/) { for (var i=2; i<arguments.length; ++i) { for (var nm in arguments[i]) { if (arguments[i].hasOwnProperty(nm) || typeof arguments[i][nm] == 'function') { if (typeof(arguments[i][nm]) == 'object' && arguments[i][nm] != null) { ob1[prefix+nm] = (arguments[i][nm] instanceof Array) ? new Array : new Object; obMerge('', ob1[prefix+nm], arguments[i][nm]); } else { ob1[prefix+nm] = arguments[i][nm]; } } } } return ob1; }
[ "function", "obMerge", "(", "prefix", ",", "ob1", ",", "ob2", "/*, ...*/", ")", "{", "for", "(", "var", "i", "=", "2", ";", "i", "<", "arguments", ".", "length", ";", "++", "i", ")", "{", "for", "(", "var", "nm", "in", "arguments", "[", "i", "]...
merges two or more objects into one and add prefix at the beginning of every property name at the top level objects type is lost, only own properties copied
[ "merges", "two", "or", "more", "objects", "into", "one", "and", "add", "prefix", "at", "the", "beginning", "of", "every", "property", "name", "at", "the", "top", "level", "objects", "type", "is", "lost", "only", "own", "properties", "copied" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/htdocs/scripts/jsmart.js#L17-L38
31,077
jbaicoianu/elation
components/utils/htdocs/scripts/jsmart.js
function(e, s) { var parens = []; e.tree.push(parens); parens.parent = e.tree; e.tree = parens; }
javascript
function(e, s) { var parens = []; e.tree.push(parens); parens.parent = e.tree; e.tree = parens; }
[ "function", "(", "e", ",", "s", ")", "{", "var", "parens", "=", "[", "]", ";", "e", ".", "tree", ".", "push", "(", "parens", ")", ";", "parens", ".", "parent", "=", "e", ".", "tree", ";", "e", ".", "tree", "=", "parens", ";", "}" ]
expression in parentheses
[ "expression", "in", "parentheses" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/htdocs/scripts/jsmart.js#L1093-L1099
31,078
mongodb-js/storage-mixin
lib/backends/errback.js
function(done) { return { success: function(res) { done(null, res); }, error: function(res, err) { done(err); } }; }
javascript
function(done) { return { success: function(res) { done(null, res); }, error: function(res, err) { done(err); } }; }
[ "function", "(", "done", ")", "{", "return", "{", "success", ":", "function", "(", "res", ")", "{", "done", "(", "null", ",", "res", ")", ";", "}", ",", "error", ":", "function", "(", "res", ",", "err", ")", "{", "done", "(", "err", ")", ";", ...
The opposite of wrapOptions, this helper wraps an errback and returns an options object that calls the errback appropriately. @param {Function} done @return {Object}
[ "The", "opposite", "of", "wrapOptions", "this", "helper", "wraps", "an", "errback", "and", "returns", "an", "options", "object", "that", "calls", "the", "errback", "appropriately", "." ]
1f8c26e6db4738f6f502a9a3286d114364fe9ed8
https://github.com/mongodb-js/storage-mixin/blob/1f8c26e6db4738f6f502a9a3286d114364fe9ed8/lib/backends/errback.js#L34-L43
31,079
knownasilya/interval
lib/interval.js
add
function add(base, addend) { if (util.isDate(base)) { return new Date(base.getTime() + interval(addend)); } return interval(base) + interval(addend); }
javascript
function add(base, addend) { if (util.isDate(base)) { return new Date(base.getTime() + interval(addend)); } return interval(base) + interval(addend); }
[ "function", "add", "(", "base", ",", "addend", ")", "{", "if", "(", "util", ".", "isDate", "(", "base", ")", ")", "{", "return", "new", "Date", "(", "base", ".", "getTime", "(", ")", "+", "interval", "(", "addend", ")", ")", ";", "}", "return", ...
first parmater can be a date or an interval, second parameter has to be an interval returns the same type as the first parameter
[ "first", "parmater", "can", "be", "a", "date", "or", "an", "interval", "second", "parameter", "has", "to", "be", "an", "interval", "returns", "the", "same", "type", "as", "the", "first", "parameter" ]
d8dd395944dc202f79031adeb3defe9296c5a7f8
https://github.com/knownasilya/interval/blob/d8dd395944dc202f79031adeb3defe9296c5a7f8/lib/interval.js#L95-L100
31,080
faucet-pipeline/faucet-pipeline-sass
lib/make-sass-renderer.js
renderSass
function renderSass(options) { return new Promise((resolve, reject) => { try { // using synchronous rendering because it is faster let result = sass.renderSync(options); result.css = fixEOF(result.css); resolve(result); } catch(err) { reject(err); } }); }
javascript
function renderSass(options) { return new Promise((resolve, reject) => { try { // using synchronous rendering because it is faster let result = sass.renderSync(options); result.css = fixEOF(result.css); resolve(result); } catch(err) { reject(err); } }); }
[ "function", "renderSass", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "// using synchronous rendering because it is faster", "let", "result", "=", "sass", ".", "renderSync", "(", "options"...
promisified version of sass.render
[ "promisified", "version", "of", "sass", ".", "render" ]
a9c1e40671237abdef4939dfb07e8717bb187622
https://github.com/faucet-pipeline/faucet-pipeline-sass/blob/a9c1e40671237abdef4939dfb07e8717bb187622/lib/make-sass-renderer.js#L29-L40
31,081
jbaicoianu/elation
components/utils/scripts/sylvester.js
function(obj) { if (obj.anchor) { // obj is a plane or line var P = this.elements.slice(); var C = obj.pointClosestTo(P).elements; return Vector.create([C[0] + (C[0] - P[0]), C[1] + (C[1] - P[1]), C[2] + (C[2] - (P[2] || 0))]); } else { // obj is a point var Q = obj.elements || obj; if (this.elements.length != Q.length) { return null; } return this.map(function(x, i) { return Q[i-1] + (Q[i-1] - x); }); } }
javascript
function(obj) { if (obj.anchor) { // obj is a plane or line var P = this.elements.slice(); var C = obj.pointClosestTo(P).elements; return Vector.create([C[0] + (C[0] - P[0]), C[1] + (C[1] - P[1]), C[2] + (C[2] - (P[2] || 0))]); } else { // obj is a point var Q = obj.elements || obj; if (this.elements.length != Q.length) { return null; } return this.map(function(x, i) { return Q[i-1] + (Q[i-1] - x); }); } }
[ "function", "(", "obj", ")", "{", "if", "(", "obj", ".", "anchor", ")", "{", "// obj is a plane or line\r", "var", "P", "=", "this", ".", "elements", ".", "slice", "(", ")", ";", "var", "C", "=", "obj", ".", "pointClosestTo", "(", "P", ")", ".", "e...
Returns the result of reflecting the point in the given point, line or plane
[ "Returns", "the", "result", "of", "reflecting", "the", "point", "in", "the", "given", "point", "line", "or", "plane" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/sylvester.js#L264-L276
31,082
jbaicoianu/elation
components/utils/scripts/sylvester.js
function(obj) { if (obj.normal) { // obj is a plane var A = this.anchor.elements, D = this.direction.elements; var A1 = A[0], A2 = A[1], A3 = A[2], D1 = D[0], D2 = D[1], D3 = D[2]; var newA = this.anchor.reflectionIn(obj).elements; // Add the line's direction vector to its anchor, then mirror that in the plane var AD1 = A1 + D1, AD2 = A2 + D2, AD3 = A3 + D3; var Q = obj.pointClosestTo([AD1, AD2, AD3]).elements; var newD = [Q[0] + (Q[0] - AD1) - newA[0], Q[1] + (Q[1] - AD2) - newA[1], Q[2] + (Q[2] - AD3) - newA[2]]; return Line.create(newA, newD); } else if (obj.direction) { // obj is a line - reflection obtained by rotating PI radians about obj return this.rotate(Math.PI, obj); } else { // obj is a point - just reflect the line's anchor in it var P = obj.elements || obj; return Line.create(this.anchor.reflectionIn([P[0], P[1], (P[2] || 0)]), this.direction); } }
javascript
function(obj) { if (obj.normal) { // obj is a plane var A = this.anchor.elements, D = this.direction.elements; var A1 = A[0], A2 = A[1], A3 = A[2], D1 = D[0], D2 = D[1], D3 = D[2]; var newA = this.anchor.reflectionIn(obj).elements; // Add the line's direction vector to its anchor, then mirror that in the plane var AD1 = A1 + D1, AD2 = A2 + D2, AD3 = A3 + D3; var Q = obj.pointClosestTo([AD1, AD2, AD3]).elements; var newD = [Q[0] + (Q[0] - AD1) - newA[0], Q[1] + (Q[1] - AD2) - newA[1], Q[2] + (Q[2] - AD3) - newA[2]]; return Line.create(newA, newD); } else if (obj.direction) { // obj is a line - reflection obtained by rotating PI radians about obj return this.rotate(Math.PI, obj); } else { // obj is a point - just reflect the line's anchor in it var P = obj.elements || obj; return Line.create(this.anchor.reflectionIn([P[0], P[1], (P[2] || 0)]), this.direction); } }
[ "function", "(", "obj", ")", "{", "if", "(", "obj", ".", "normal", ")", "{", "// obj is a plane\r", "var", "A", "=", "this", ".", "anchor", ".", "elements", ",", "D", "=", "this", ".", "direction", ".", "elements", ";", "var", "A1", "=", "A", "[", ...
Returns the line's reflection in the given point or line
[ "Returns", "the", "line", "s", "reflection", "in", "the", "given", "point", "or", "line" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/sylvester.js#L973-L992
31,083
ericmatthys/grunt-changelog
tasks/changelog.js
getChanges
function getChanges(log, regex) { var changes = []; var match; while ((match = regex.exec(log))) { var change = ''; for (var i = 1, len = match.length; i < len; i++) { change += match[i]; } changes.push(change.trim()); } return changes; }
javascript
function getChanges(log, regex) { var changes = []; var match; while ((match = regex.exec(log))) { var change = ''; for (var i = 1, len = match.length; i < len; i++) { change += match[i]; } changes.push(change.trim()); } return changes; }
[ "function", "getChanges", "(", "log", ",", "regex", ")", "{", "var", "changes", "=", "[", "]", ";", "var", "match", ";", "while", "(", "(", "match", "=", "regex", ".", "exec", "(", "log", ")", ")", ")", "{", "var", "change", "=", "''", ";", "fo...
Loop through each match and build the array of changes that will be passed to the template.
[ "Loop", "through", "each", "match", "and", "build", "the", "array", "of", "changes", "that", "will", "be", "passed", "to", "the", "template", "." ]
24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6
https://github.com/ericmatthys/grunt-changelog/blob/24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6/tasks/changelog.js#L76-L91
31,084
ericmatthys/grunt-changelog
tasks/changelog.js
getChangelog
function getChangelog(log) { var data = { date: moment().format('YYYY-MM-DD'), features: getChanges(log, options.featureRegex), fixes: getChanges(log, options.fixRegex) }; return template(data); }
javascript
function getChangelog(log) { var data = { date: moment().format('YYYY-MM-DD'), features: getChanges(log, options.featureRegex), fixes: getChanges(log, options.fixRegex) }; return template(data); }
[ "function", "getChangelog", "(", "log", ")", "{", "var", "data", "=", "{", "date", ":", "moment", "(", ")", ".", "format", "(", "'YYYY-MM-DD'", ")", ",", "features", ":", "getChanges", "(", "log", ",", "options", ".", "featureRegex", ")", ",", "fixes",...
Generate the changelog using the templates defined in options.
[ "Generate", "the", "changelog", "using", "the", "templates", "defined", "in", "options", "." ]
24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6
https://github.com/ericmatthys/grunt-changelog/blob/24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6/tasks/changelog.js#L94-L102
31,085
ericmatthys/grunt-changelog
tasks/changelog.js
writeChangelog
function writeChangelog(changelog) { var fileContents = null; var firstLineFile = null; var firstLineFileHeader = null; var regex = null; if (options.insertType && grunt.file.exists(options.dest)) { fileContents = grunt.file.read(options.dest); firstLineFile = fileContents.split('\n')[0]; grunt.log.debug('firstLineFile = ' + firstLineFile); switch (options.insertType) { case 'prepend': changelog = changelog + '\n' + fileContents; break; case 'append': changelog = fileContents + '\n' + changelog; break; default: grunt.fatal('"' + options.insertType + '" is not a valid insertType. Please use "append" or "prepend".'); return false; } } if (options.fileHeader) { firstLineFileHeader = options.fileHeader.split('\n')[0]; grunt.log.debug('firstLineFileHeader = ' + firstLineFileHeader); if (options.insertType === 'prepend') { if (firstLineFile !== firstLineFileHeader) { changelog = options.fileHeader + '\n\n' + changelog; } else { regex = new RegExp(options.fileHeader+'\n\n','m'); changelog = options.fileHeader + '\n\n' + changelog.replace(regex, ''); } // insertType === 'append' || undefined } else { if (firstLineFile !== firstLineFileHeader) { changelog = options.fileHeader + '\n\n' + changelog; } } } grunt.file.write(options.dest, changelog); // Log the results. grunt.log.ok(changelog); grunt.log.writeln(); grunt.log.writeln('Changelog created at '+ options.dest.toString().cyan + '.'); }
javascript
function writeChangelog(changelog) { var fileContents = null; var firstLineFile = null; var firstLineFileHeader = null; var regex = null; if (options.insertType && grunt.file.exists(options.dest)) { fileContents = grunt.file.read(options.dest); firstLineFile = fileContents.split('\n')[0]; grunt.log.debug('firstLineFile = ' + firstLineFile); switch (options.insertType) { case 'prepend': changelog = changelog + '\n' + fileContents; break; case 'append': changelog = fileContents + '\n' + changelog; break; default: grunt.fatal('"' + options.insertType + '" is not a valid insertType. Please use "append" or "prepend".'); return false; } } if (options.fileHeader) { firstLineFileHeader = options.fileHeader.split('\n')[0]; grunt.log.debug('firstLineFileHeader = ' + firstLineFileHeader); if (options.insertType === 'prepend') { if (firstLineFile !== firstLineFileHeader) { changelog = options.fileHeader + '\n\n' + changelog; } else { regex = new RegExp(options.fileHeader+'\n\n','m'); changelog = options.fileHeader + '\n\n' + changelog.replace(regex, ''); } // insertType === 'append' || undefined } else { if (firstLineFile !== firstLineFileHeader) { changelog = options.fileHeader + '\n\n' + changelog; } } } grunt.file.write(options.dest, changelog); // Log the results. grunt.log.ok(changelog); grunt.log.writeln(); grunt.log.writeln('Changelog created at '+ options.dest.toString().cyan + '.'); }
[ "function", "writeChangelog", "(", "changelog", ")", "{", "var", "fileContents", "=", "null", ";", "var", "firstLineFile", "=", "null", ";", "var", "firstLineFileHeader", "=", "null", ";", "var", "regex", "=", "null", ";", "if", "(", "options", ".", "inser...
Write the changelog to the destination file.
[ "Write", "the", "changelog", "to", "the", "destination", "file", "." ]
24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6
https://github.com/ericmatthys/grunt-changelog/blob/24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6/tasks/changelog.js#L105-L157
31,086
mia-js/mia-js-core
lib/routesHandler/lib/initializeRoutes.js
function (preconditions) { var errorCodesList = { "500": ["InternalServerError"], "400": [ "UnexpectedDefaultValue", "UnexpectedType", "MinLengthUnderachieved", "MaxLengthExceeded", "MinValueUnderachived", "MaxValueExceeded", "ValueNotAllowed", "PatternMismatch", "MissingRequiredParameter"], "429": ["RateLimitExceeded"], }; for (var index in preconditions) { if (preconditions[index].conditions && preconditions[index].conditions.responses) { for (var code in preconditions[index].conditions.responses) { if (errorCodesList[code]) { if (_.isArray(preconditions[index].conditions.responses[code])) { for (var ecode in preconditions[index].conditions.responses[code]) { if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code][ecode]) == -1) { errorCodesList[code].push(preconditions[index].conditions.responses[code][ecode]); } } } else { if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code]) == -1) { errorCodesList[code].push(preconditions[index].conditions.responses[code]); } } } else { if (_.isArray(preconditions[index].conditions.responses[code])) { errorCodesList[code] = _.clone(preconditions[index].conditions.responses[code]); } else { errorCodesList[code] = [_.clone(preconditions[index].conditions.responses[code])]; } } } } } return errorCodesList; }
javascript
function (preconditions) { var errorCodesList = { "500": ["InternalServerError"], "400": [ "UnexpectedDefaultValue", "UnexpectedType", "MinLengthUnderachieved", "MaxLengthExceeded", "MinValueUnderachived", "MaxValueExceeded", "ValueNotAllowed", "PatternMismatch", "MissingRequiredParameter"], "429": ["RateLimitExceeded"], }; for (var index in preconditions) { if (preconditions[index].conditions && preconditions[index].conditions.responses) { for (var code in preconditions[index].conditions.responses) { if (errorCodesList[code]) { if (_.isArray(preconditions[index].conditions.responses[code])) { for (var ecode in preconditions[index].conditions.responses[code]) { if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code][ecode]) == -1) { errorCodesList[code].push(preconditions[index].conditions.responses[code][ecode]); } } } else { if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code]) == -1) { errorCodesList[code].push(preconditions[index].conditions.responses[code]); } } } else { if (_.isArray(preconditions[index].conditions.responses[code])) { errorCodesList[code] = _.clone(preconditions[index].conditions.responses[code]); } else { errorCodesList[code] = [_.clone(preconditions[index].conditions.responses[code])]; } } } } } return errorCodesList; }
[ "function", "(", "preconditions", ")", "{", "var", "errorCodesList", "=", "{", "\"500\"", ":", "[", "\"InternalServerError\"", "]", ",", "\"400\"", ":", "[", "\"UnexpectedDefaultValue\"", ",", "\"UnexpectedType\"", ",", "\"MinLengthUnderachieved\"", ",", "\"MaxLengthE...
Returns a list of http codes defined in preconditions section in controller
[ "Returns", "a", "list", "of", "http", "codes", "defined", "in", "preconditions", "section", "in", "controller" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L88-L132
31,087
mia-js/mia-js-core
lib/routesHandler/lib/initializeRoutes.js
function (attr, attrName) { if (_.isObject(attr) && !_.isDate(attr) && !_.isBoolean(attr) && !_.isString(attr) && !_.isNumber(attr) && !_.isFunction(attr) && !_.isRegExp(attr) && !_.isArray(attr)) { //attr = _removeAttributes(); for (var aIndex in attr) { attr[aIndex] = _removeAttributes(attr[aIndex], aIndex); } return attr; } else { if (_.indexOf(allowedAttributes, attrName) != -1) { if (_.isFunction(attr)) { attr = _functionName(attr); } return attr; } else { return; } } }
javascript
function (attr, attrName) { if (_.isObject(attr) && !_.isDate(attr) && !_.isBoolean(attr) && !_.isString(attr) && !_.isNumber(attr) && !_.isFunction(attr) && !_.isRegExp(attr) && !_.isArray(attr)) { //attr = _removeAttributes(); for (var aIndex in attr) { attr[aIndex] = _removeAttributes(attr[aIndex], aIndex); } return attr; } else { if (_.indexOf(allowedAttributes, attrName) != -1) { if (_.isFunction(attr)) { attr = _functionName(attr); } return attr; } else { return; } } }
[ "function", "(", "attr", ",", "attrName", ")", "{", "if", "(", "_", ".", "isObject", "(", "attr", ")", "&&", "!", "_", ".", "isDate", "(", "attr", ")", "&&", "!", "_", ".", "isBoolean", "(", "attr", ")", "&&", "!", "_", ".", "isString", "(", ...
Remove attributes recursively
[ "Remove", "attributes", "recursively" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L148-L168
31,088
mia-js/mia-js-core
lib/routesHandler/lib/initializeRoutes.js
function (parametersList, parameters, section) { if (parameters[section]) { for (var name in parameters[section]) { var addCondition = parameters[section][name]; if (parametersList[section] && parametersList[section][name]) { // Merge parameters attributes for (var attr in addCondition) { if (_.has(parametersList, [section, name, attr]) === false) { // Attribute does not exists -> add to list parametersList[section][name][attr] = addCondition[attr]; } else { // Attribute already exists compare values if (_.isFunction(addCondition[attr])) { addCondition[attr] = _functionName(addCondition[attr]); } if (JSON.stringify(parametersList[section][name][attr]) != JSON.stringify(addCondition[attr])) { throw new Error("Precondition conflict: " + preconditions[index].name + ' -> ' + preconditions[index].version + ' -> ' + preconditions[index].method + ' -> ' + attr + ':' + addCondition[attr] + ' -> already defined in previous controller and value is mismatching'); } else { parametersList[section][name][attr] = addCondition[attr]; } } } } else { parametersList[section] = parametersList[section] ? parametersList[section] : {}; parametersList[section][name] = addCondition; } // Filter parameter attributes by allowedAttributes var validatedParameterAttributes = {}; if (_.has(parametersList, [section, name])) { for (var attr in parametersList[section][name]) { validatedParameterAttributes[attr] = _removeAttributes(parametersList[section][name][attr], attr); } } if (!_.isEmpty(validatedParameterAttributes)) { parametersList[section][name] = validatedParameterAttributes; } } } return parametersList; }
javascript
function (parametersList, parameters, section) { if (parameters[section]) { for (var name in parameters[section]) { var addCondition = parameters[section][name]; if (parametersList[section] && parametersList[section][name]) { // Merge parameters attributes for (var attr in addCondition) { if (_.has(parametersList, [section, name, attr]) === false) { // Attribute does not exists -> add to list parametersList[section][name][attr] = addCondition[attr]; } else { // Attribute already exists compare values if (_.isFunction(addCondition[attr])) { addCondition[attr] = _functionName(addCondition[attr]); } if (JSON.stringify(parametersList[section][name][attr]) != JSON.stringify(addCondition[attr])) { throw new Error("Precondition conflict: " + preconditions[index].name + ' -> ' + preconditions[index].version + ' -> ' + preconditions[index].method + ' -> ' + attr + ':' + addCondition[attr] + ' -> already defined in previous controller and value is mismatching'); } else { parametersList[section][name][attr] = addCondition[attr]; } } } } else { parametersList[section] = parametersList[section] ? parametersList[section] : {}; parametersList[section][name] = addCondition; } // Filter parameter attributes by allowedAttributes var validatedParameterAttributes = {}; if (_.has(parametersList, [section, name])) { for (var attr in parametersList[section][name]) { validatedParameterAttributes[attr] = _removeAttributes(parametersList[section][name][attr], attr); } } if (!_.isEmpty(validatedParameterAttributes)) { parametersList[section][name] = validatedParameterAttributes; } } } return parametersList; }
[ "function", "(", "parametersList", ",", "parameters", ",", "section", ")", "{", "if", "(", "parameters", "[", "section", "]", ")", "{", "for", "(", "var", "name", "in", "parameters", "[", "section", "]", ")", "{", "var", "addCondition", "=", "parameters"...
Parse preconditions parameters in section header, query, body
[ "Parse", "preconditions", "parameters", "in", "section", "header", "query", "body" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L171-L215
31,089
mia-js/mia-js-core
lib/routesHandler/lib/initializeRoutes.js
function (req, res, next) { if (!req.miajs.controllerDebugInfo) { req.miajs.controllerDebugInfo = {}; } if (controller.name && controller.version) { req.miajs.controllerDebugInfo[controller.name + '_' + controller.version] = {'runtime': Date.now() - req.miajs.controllerStart}; } next(); }
javascript
function (req, res, next) { if (!req.miajs.controllerDebugInfo) { req.miajs.controllerDebugInfo = {}; } if (controller.name && controller.version) { req.miajs.controllerDebugInfo[controller.name + '_' + controller.version] = {'runtime': Date.now() - req.miajs.controllerStart}; } next(); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "!", "req", ".", "miajs", ".", "controllerDebugInfo", ")", "{", "req", ".", "miajs", ".", "controllerDebugInfo", "=", "{", "}", ";", "}", "if", "(", "controller", ".", "name", "&...
Measure runtime of controller
[ "Measure", "runtime", "of", "controller" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L381-L389
31,090
mia-js/mia-js-core
lib/routesHandler/lib/initializeRoutes.js
function (routeConfig, methodValue) { var rateLimits = []; var environment = Shared.config("environment"); var globalRateLimit = environment.rateLimit; if (globalRateLimit) { if (globalRateLimit.interval && _.isNumber(globalRateLimit.interval) && parseInt(globalRateLimit.interval) > 0 && globalRateLimit.maxRequests && _.isNumber(globalRateLimit.maxRequests) && parseInt(globalRateLimit.maxRequests) > 0) { rateLimits.push(globalRateLimit); } else { throw new Error('Global rate limit config invalid' + ". Provide parameters 'interval' and 'maxRequests' with Int value"); } } if (routeConfig && routeConfig.rateLimit) { if (routeConfig.rateLimit.interval && _.isNumber(routeConfig.rateLimit.interval) && parseInt(routeConfig.rateLimit.interval) > 0 && routeConfig.rateLimit.maxRequests && _.isNumber(routeConfig.rateLimit.maxRequests) && parseInt(routeConfig.rateLimit.maxRequests) > 0) { rateLimits.push(routeConfig.rateLimit); } else { throw new Error('Rate limit config invalid for route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value"); } } if (methodValue && methodValue.rateLimit) { if (methodValue.rateLimit.interval && _.isNumber(methodValue.rateLimit.interval) && parseInt(methodValue.rateLimit.interval) > 0 && methodValue.rateLimit.maxRequests && _.isNumber(methodValue.rateLimit.maxRequests) && parseInt(methodValue.rateLimit.maxRequests) > 0) { rateLimits.push(methodValue.rateLimit); } else { throw new Error('Rate limit config invalid for route ' + methodValue.identity + ' in route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value"); } } if (!_.isEmpty(rateLimits) && !Shared.memcached()) { throw new Error("Rate limits set but memcached not configured. Provide settings for memcached in environment config file"); } return rateLimits; }
javascript
function (routeConfig, methodValue) { var rateLimits = []; var environment = Shared.config("environment"); var globalRateLimit = environment.rateLimit; if (globalRateLimit) { if (globalRateLimit.interval && _.isNumber(globalRateLimit.interval) && parseInt(globalRateLimit.interval) > 0 && globalRateLimit.maxRequests && _.isNumber(globalRateLimit.maxRequests) && parseInt(globalRateLimit.maxRequests) > 0) { rateLimits.push(globalRateLimit); } else { throw new Error('Global rate limit config invalid' + ". Provide parameters 'interval' and 'maxRequests' with Int value"); } } if (routeConfig && routeConfig.rateLimit) { if (routeConfig.rateLimit.interval && _.isNumber(routeConfig.rateLimit.interval) && parseInt(routeConfig.rateLimit.interval) > 0 && routeConfig.rateLimit.maxRequests && _.isNumber(routeConfig.rateLimit.maxRequests) && parseInt(routeConfig.rateLimit.maxRequests) > 0) { rateLimits.push(routeConfig.rateLimit); } else { throw new Error('Rate limit config invalid for route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value"); } } if (methodValue && methodValue.rateLimit) { if (methodValue.rateLimit.interval && _.isNumber(methodValue.rateLimit.interval) && parseInt(methodValue.rateLimit.interval) > 0 && methodValue.rateLimit.maxRequests && _.isNumber(methodValue.rateLimit.maxRequests) && parseInt(methodValue.rateLimit.maxRequests) > 0) { rateLimits.push(methodValue.rateLimit); } else { throw new Error('Rate limit config invalid for route ' + methodValue.identity + ' in route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value"); } } if (!_.isEmpty(rateLimits) && !Shared.memcached()) { throw new Error("Rate limits set but memcached not configured. Provide settings for memcached in environment config file"); } return rateLimits; }
[ "function", "(", "routeConfig", ",", "methodValue", ")", "{", "var", "rateLimits", "=", "[", "]", ";", "var", "environment", "=", "Shared", ".", "config", "(", "\"environment\"", ")", ";", "var", "globalRateLimit", "=", "environment", ".", "rateLimit", ";", ...
Validate rate limits settings
[ "Validate", "rate", "limits", "settings" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L459-L493
31,091
mia-js/mia-js-core
lib/routesHandler/lib/initializeRoutes.js
function (req, res, next) { var ip = IPAddressHelper.getClientIP(req) , route = req.miajs.route , key = ip + route.path + route.method; if (_.isEmpty(route.rateLimits)) { next(); return; } RateLimiter.checkRateLimitsByKey(key, route.rateLimits).then(function (rateLimiterResult) { if (rateLimiterResult.remaining == -1) { _logInfo("Rate limit of " + rateLimiterResult.limit + "req/" + rateLimiterResult.timeInterval + "min requests exceeded " + route.requestmethod.toUpperCase() + " " + route.url + " for " + ip); res.header("X-Rate-Limit-Limit", rateLimiterResult.limit); res.header("X-Rate-Limit-Remaining", 0); res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset); next(new MiaError({ status: 429, err: { 'code': 'RateLimitExceeded', 'msg': Translator('system', 'RateLimitExceeded') } })); } else { res.header("X-Rate-Limit-Limit", rateLimiterResult.limit); res.header("X-Rate-Limit-Remaining", rateLimiterResult.remaining); res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset); next(); } }).catch(function () { next(); }); }
javascript
function (req, res, next) { var ip = IPAddressHelper.getClientIP(req) , route = req.miajs.route , key = ip + route.path + route.method; if (_.isEmpty(route.rateLimits)) { next(); return; } RateLimiter.checkRateLimitsByKey(key, route.rateLimits).then(function (rateLimiterResult) { if (rateLimiterResult.remaining == -1) { _logInfo("Rate limit of " + rateLimiterResult.limit + "req/" + rateLimiterResult.timeInterval + "min requests exceeded " + route.requestmethod.toUpperCase() + " " + route.url + " for " + ip); res.header("X-Rate-Limit-Limit", rateLimiterResult.limit); res.header("X-Rate-Limit-Remaining", 0); res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset); next(new MiaError({ status: 429, err: { 'code': 'RateLimitExceeded', 'msg': Translator('system', 'RateLimitExceeded') } })); } else { res.header("X-Rate-Limit-Limit", rateLimiterResult.limit); res.header("X-Rate-Limit-Remaining", rateLimiterResult.remaining); res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset); next(); } }).catch(function () { next(); }); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "ip", "=", "IPAddressHelper", ".", "getClientIP", "(", "req", ")", ",", "route", "=", "req", ".", "miajs", ".", "route", ",", "key", "=", "ip", "+", "route", ".", "path", "+", "rou...
Route for rate limits check
[ "Route", "for", "rate", "limits", "check" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L497-L530
31,092
mia-js/mia-js-core
lib/rateLimiter/lib/rateLimiter.js
function (range) { var coeff = 1000 * 60 * range; return new Date(Math.ceil(new Date(Date.now()).getTime() / coeff) * coeff).getTime() / 1000; }
javascript
function (range) { var coeff = 1000 * 60 * range; return new Date(Math.ceil(new Date(Date.now()).getTime() / coeff) * coeff).getTime() / 1000; }
[ "function", "(", "range", ")", "{", "var", "coeff", "=", "1000", "*", "60", "*", "range", ";", "return", "new", "Date", "(", "Math", ".", "ceil", "(", "new", "Date", "(", "Date", ".", "now", "(", ")", ")", ".", "getTime", "(", ")", "/", "coeff"...
Calculate current time interval slot
[ "Calculate", "current", "time", "interval", "slot" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/rateLimiter/lib/rateLimiter.js#L21-L24
31,093
mia-js/mia-js-core
lib/rateLimiter/lib/rateLimiter.js
function (key, timeInterval, limit) { //Validate rate limiter settings if (!_.isNumber(timeInterval) || parseInt(timeInterval) <= 0 || !_.isNumber(limit) || parseInt(limit) <= 0) { return Q.reject(); } var cacheKey = Encryption.md5("MiaJSRateLimit" + key + _calculateCurrentTimeInterval(timeInterval)); return _validateRateLimit(cacheKey, timeInterval, limit).then(function (value) { return Q({ limit: limit, remaining: limit - value, timeInterval: timeInterval, timeTillReset: _getTimeLeftTillReset(timeInterval) }); }); }
javascript
function (key, timeInterval, limit) { //Validate rate limiter settings if (!_.isNumber(timeInterval) || parseInt(timeInterval) <= 0 || !_.isNumber(limit) || parseInt(limit) <= 0) { return Q.reject(); } var cacheKey = Encryption.md5("MiaJSRateLimit" + key + _calculateCurrentTimeInterval(timeInterval)); return _validateRateLimit(cacheKey, timeInterval, limit).then(function (value) { return Q({ limit: limit, remaining: limit - value, timeInterval: timeInterval, timeTillReset: _getTimeLeftTillReset(timeInterval) }); }); }
[ "function", "(", "key", ",", "timeInterval", ",", "limit", ")", "{", "//Validate rate limiter settings", "if", "(", "!", "_", ".", "isNumber", "(", "timeInterval", ")", "||", "parseInt", "(", "timeInterval", ")", "<=", "0", "||", "!", "_", ".", "isNumber",...
Check global rate limits per ip
[ "Check", "global", "rate", "limits", "per", "ip" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/rateLimiter/lib/rateLimiter.js#L27-L41
31,094
mia-js/mia-js-core
lib/rateLimiter/lib/rateLimiter.js
function (key, intervalSize, limit) { var deferred = Q.defer() , memcached = Shared.memcached(); if (!memcached) { deferred.reject(); } else { //Get current rate for ip memcached.get(key, function (err, value) { if (err) { //Allow access as failover Logger.warn("Rate limit set but memcached error, allow access without limit", err); deferred.reject(); } else if (_.isUndefined(value)) { memcached.set(key, 1, 60 * intervalSize, function (err) { if (err) { Logger.warn("Rate limit set but memcached error, allow access without limit", err); } }); deferred.resolve(1); } else { //Do not increase rate counter if exceeded anyway if (value < limit) { // Increase rate counter by 1 memcached.incr(key, 1, function (err) { if (err) { Logger.warn("Rate limit set but memcached error, allow access without limit", err); } }); } deferred.resolve(value + 1); } }); } return deferred.promise; }
javascript
function (key, intervalSize, limit) { var deferred = Q.defer() , memcached = Shared.memcached(); if (!memcached) { deferred.reject(); } else { //Get current rate for ip memcached.get(key, function (err, value) { if (err) { //Allow access as failover Logger.warn("Rate limit set but memcached error, allow access without limit", err); deferred.reject(); } else if (_.isUndefined(value)) { memcached.set(key, 1, 60 * intervalSize, function (err) { if (err) { Logger.warn("Rate limit set but memcached error, allow access without limit", err); } }); deferred.resolve(1); } else { //Do not increase rate counter if exceeded anyway if (value < limit) { // Increase rate counter by 1 memcached.incr(key, 1, function (err) { if (err) { Logger.warn("Rate limit set but memcached error, allow access without limit", err); } }); } deferred.resolve(value + 1); } }); } return deferred.promise; }
[ "function", "(", "key", ",", "intervalSize", ",", "limit", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ",", "memcached", "=", "Shared", ".", "memcached", "(", ")", ";", "if", "(", "!", "memcached", ")", "{", "deferred", ".", "rej...
Validate and increase current rate limit in memcache
[ "Validate", "and", "increase", "current", "rate", "limit", "in", "memcache" ]
77c976a72382fd0edef1144f9bea47d8c175c26b
https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/rateLimiter/lib/rateLimiter.js#L44-L81
31,095
jbaicoianu/elation
components/utils/scripts/jit.js
function(e, win) { var event = $.event.get(e, win); var wheel = $.event.getWheel(event); that.handleEvent('MouseWheel', e, win, wheel); }
javascript
function(e, win) { var event = $.event.get(e, win); var wheel = $.event.getWheel(event); that.handleEvent('MouseWheel', e, win, wheel); }
[ "function", "(", "e", ",", "win", ")", "{", "var", "event", "=", "$", ".", "event", ".", "get", "(", "e", ",", "win", ")", ";", "var", "wheel", "=", "$", ".", "event", ".", "getWheel", "(", "event", ")", ";", "that", ".", "handleEvent", "(", ...
attach mousewheel event
[ "attach", "mousewheel", "event" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/jit.js#L2037-L2041
31,096
jbaicoianu/elation
components/utils/scripts/jit.js
$E
function $E(tag, props) { var elem = document.createElement(tag); for(var p in props) { if(typeof props[p] == "object") { $.extend(elem[p], props[p]); } else { elem[p] = props[p]; } } if (tag == "canvas" && !supportsCanvas && G_vmlCanvasManager) { elem = G_vmlCanvasManager.initElement(document.body.appendChild(elem)); } return elem; }
javascript
function $E(tag, props) { var elem = document.createElement(tag); for(var p in props) { if(typeof props[p] == "object") { $.extend(elem[p], props[p]); } else { elem[p] = props[p]; } } if (tag == "canvas" && !supportsCanvas && G_vmlCanvasManager) { elem = G_vmlCanvasManager.initElement(document.body.appendChild(elem)); } return elem; }
[ "function", "$E", "(", "tag", ",", "props", ")", "{", "var", "elem", "=", "document", ".", "createElement", "(", "tag", ")", ";", "for", "(", "var", "p", "in", "props", ")", "{", "if", "(", "typeof", "props", "[", "p", "]", "==", "\"object\"", ")...
create element function
[ "create", "element", "function" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/jit.js#L2719-L2732
31,097
jbaicoianu/elation
components/utils/scripts/jit.js
getNodesToHide
function getNodesToHide(node) { node = node || this.clickedNode; if(!this.config.constrained) { return []; } var Geom = this.geom; var graph = this.graph; var canvas = this.canvas; var level = node._depth, nodeArray = []; graph.eachNode(function(n) { if(n.exist && !n.selected) { if(n.isDescendantOf(node.id)) { if(n._depth <= level) nodeArray.push(n); } else { nodeArray.push(n); } } }); var leafLevel = Geom.getRightLevelToShow(node, canvas); node.eachLevel(leafLevel, leafLevel, function(n) { if(n.exist && !n.selected) nodeArray.push(n); }); for (var i = 0; i < nodesInPath.length; i++) { var n = this.graph.getNode(nodesInPath[i]); if(!n.isDescendantOf(node.id)) { nodeArray.push(n); } } return nodeArray; }
javascript
function getNodesToHide(node) { node = node || this.clickedNode; if(!this.config.constrained) { return []; } var Geom = this.geom; var graph = this.graph; var canvas = this.canvas; var level = node._depth, nodeArray = []; graph.eachNode(function(n) { if(n.exist && !n.selected) { if(n.isDescendantOf(node.id)) { if(n._depth <= level) nodeArray.push(n); } else { nodeArray.push(n); } } }); var leafLevel = Geom.getRightLevelToShow(node, canvas); node.eachLevel(leafLevel, leafLevel, function(n) { if(n.exist && !n.selected) nodeArray.push(n); }); for (var i = 0; i < nodesInPath.length; i++) { var n = this.graph.getNode(nodesInPath[i]); if(!n.isDescendantOf(node.id)) { nodeArray.push(n); } } return nodeArray; }
[ "function", "getNodesToHide", "(", "node", ")", "{", "node", "=", "node", "||", "this", ".", "clickedNode", ";", "if", "(", "!", "this", ".", "config", ".", "constrained", ")", "{", "return", "[", "]", ";", "}", "var", "Geom", "=", "this", ".", "ge...
Nodes to contract
[ "Nodes", "to", "contract" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/jit.js#L8113-L8143
31,098
jbaicoianu/elation
components/utils/scripts/jit.js
getNodesToShow
function getNodesToShow(node) { var nodeArray = [], config = this.config; node = node || this.clickedNode; this.clickedNode.eachLevel(0, config.levelsToShow, function(n) { if(config.multitree && !('$orn' in n.data) && n.anySubnode(function(ch){ return ch.exist && !ch.drawn; })) { nodeArray.push(n); } else if(n.drawn && !n.anySubnode("drawn")) { nodeArray.push(n); } }); return nodeArray; }
javascript
function getNodesToShow(node) { var nodeArray = [], config = this.config; node = node || this.clickedNode; this.clickedNode.eachLevel(0, config.levelsToShow, function(n) { if(config.multitree && !('$orn' in n.data) && n.anySubnode(function(ch){ return ch.exist && !ch.drawn; })) { nodeArray.push(n); } else if(n.drawn && !n.anySubnode("drawn")) { nodeArray.push(n); } }); return nodeArray; }
[ "function", "getNodesToShow", "(", "node", ")", "{", "var", "nodeArray", "=", "[", "]", ",", "config", "=", "this", ".", "config", ";", "node", "=", "node", "||", "this", ".", "clickedNode", ";", "this", ".", "clickedNode", ".", "eachLevel", "(", "0", ...
Nodes to expand
[ "Nodes", "to", "expand" ]
5fb8824d8b7150c463daf2fe99c31716c6e8812f
https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/jit.js#L8145-L8157
31,099
primus/substream
substream.js
SubStream
function SubStream(stream, name, options) { if (!(this instanceof SubStream)) return new SubStream(stream, name, options); options = options || {}; this.readyState = stream.readyState; // Copy the current readyState. this.stream = stream; // The underlaying stream. this.name = name; // The stream namespace/name. this.primus = options.primus; // Primus reference. // // Register the SubStream on the socket. // if (!stream.streams) stream.streams = {}; if (!stream.streams[name]) stream.streams[name] = this; Stream.call(this); // // No need to continue with the execution if we don't have any events that // need to be proxied. // if (!options.proxy) return; for (var i = 0, l = options.proxy.length, event; i < l; i++) { event = options.proxy[i]; this.stream.on(event, this.emits(event)); } }
javascript
function SubStream(stream, name, options) { if (!(this instanceof SubStream)) return new SubStream(stream, name, options); options = options || {}; this.readyState = stream.readyState; // Copy the current readyState. this.stream = stream; // The underlaying stream. this.name = name; // The stream namespace/name. this.primus = options.primus; // Primus reference. // // Register the SubStream on the socket. // if (!stream.streams) stream.streams = {}; if (!stream.streams[name]) stream.streams[name] = this; Stream.call(this); // // No need to continue with the execution if we don't have any events that // need to be proxied. // if (!options.proxy) return; for (var i = 0, l = options.proxy.length, event; i < l; i++) { event = options.proxy[i]; this.stream.on(event, this.emits(event)); } }
[ "function", "SubStream", "(", "stream", ",", "name", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "SubStream", ")", ")", "return", "new", "SubStream", "(", "stream", ",", "name", ",", "options", ")", ";", "options", "=", "option...
Streams provides a streaming, namespaced interface on top of a regular stream. Options: - proxy: Array of addition events that need to be re-emitted. @constructor @param {Stream} stream The stream that needs we're streaming over. @param {String} name The name of our stream. @param {object} options SubStream configuration. @api public
[ "Streams", "provides", "a", "streaming", "namespaced", "interface", "on", "top", "of", "a", "regular", "stream", "." ]
626792b746e1dc90b67a81045f442ee1f584c0ec
https://github.com/primus/substream/blob/626792b746e1dc90b67a81045f442ee1f584c0ec/substream.js#L25-L53