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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
52,800
gfax/junkyard-brawl
src/util.js
getPlayerPlays
function getPlayerPlays(player, game) { // Shuffle so that equal-weighted players aren't // always prioritized by their turn order return Util.shuffle(game.players) .reduce((plays, target) => { if (player === target) { return plays } return plays.concat( player.hand .map((card) => { return card.validPlays ? card.validPlays(player, target, game) : [] }) .reduce((acc, array) => { return acc.concat(array) }, []) ) }, []) .sort((playA, playB) => playB.weight - playA.weight) }
javascript
function getPlayerPlays(player, game) { // Shuffle so that equal-weighted players aren't // always prioritized by their turn order return Util.shuffle(game.players) .reduce((plays, target) => { if (player === target) { return plays } return plays.concat( player.hand .map((card) => { return card.validPlays ? card.validPlays(player, target, game) : [] }) .reduce((acc, array) => { return acc.concat(array) }, []) ) }, []) .sort((playA, playB) => playB.weight - playA.weight) }
[ "function", "getPlayerPlays", "(", "player", ",", "game", ")", "{", "// Shuffle so that equal-weighted players aren't", "// always prioritized by their turn order", "return", "Util", ".", "shuffle", "(", "game", ".", "players", ")", ".", "reduce", "(", "(", "plays", ",", "target", ")", "=>", "{", "if", "(", "player", "===", "target", ")", "{", "return", "plays", "}", "return", "plays", ".", "concat", "(", "player", ".", "hand", ".", "map", "(", "(", "card", ")", "=>", "{", "return", "card", ".", "validPlays", "?", "card", ".", "validPlays", "(", "player", ",", "target", ",", "game", ")", ":", "[", "]", "}", ")", ".", "reduce", "(", "(", "acc", ",", "array", ")", "=>", "{", "return", "acc", ".", "concat", "(", "array", ")", "}", ",", "[", "]", ")", ")", "}", ",", "[", "]", ")", ".", "sort", "(", "(", "playA", ",", "playB", ")", "=>", "playB", ".", "weight", "-", "playA", ".", "weight", ")", "}" ]
Get a list of possible moves a player can play, sorted by best option
[ "Get", "a", "list", "of", "possible", "moves", "a", "player", "can", "play", "sorted", "by", "best", "option" ]
5e1b9d3b622ffa6e602c7abe51995269a43423e1
https://github.com/gfax/junkyard-brawl/blob/5e1b9d3b622ffa6e602c7abe51995269a43423e1/src/util.js#L115-L134
52,801
gfax/junkyard-brawl
src/util.js
remove
function remove(array, fn) { const idx = array.findIndex(fn) if (idx !== -1) { array.splice(idx, 1) } }
javascript
function remove(array, fn) { const idx = array.findIndex(fn) if (idx !== -1) { array.splice(idx, 1) } }
[ "function", "remove", "(", "array", ",", "fn", ")", "{", "const", "idx", "=", "array", ".", "findIndex", "(", "fn", ")", "if", "(", "idx", "!==", "-", "1", ")", "{", "array", ".", "splice", "(", "idx", ",", "1", ")", "}", "}" ]
Remove one copy of a matched item from an array given a predicate function
[ "Remove", "one", "copy", "of", "a", "matched", "item", "from", "an", "array", "given", "a", "predicate", "function" ]
5e1b9d3b622ffa6e602c7abe51995269a43423e1
https://github.com/gfax/junkyard-brawl/blob/5e1b9d3b622ffa6e602c7abe51995269a43423e1/src/util.js#L137-L142
52,802
xsolon/spexplorerjs
webapi/src/components/string/funcs.js
function (arr, groupSize) { var groups = []; groupSize = groupSize || 100; arr.forEach(function (n, i) { var index = Math.trunc(i / groupSize); if (groups.length === index) { groups.push([]); } groups[index].push(n); }); return groups; }
javascript
function (arr, groupSize) { var groups = []; groupSize = groupSize || 100; arr.forEach(function (n, i) { var index = Math.trunc(i / groupSize); if (groups.length === index) { groups.push([]); } groups[index].push(n); }); return groups; }
[ "function", "(", "arr", ",", "groupSize", ")", "{", "var", "groups", "=", "[", "]", ";", "groupSize", "=", "groupSize", "||", "100", ";", "arr", ".", "forEach", "(", "function", "(", "n", ",", "i", ")", "{", "var", "index", "=", "Math", ".", "trunc", "(", "i", "/", "groupSize", ")", ";", "if", "(", "groups", ".", "length", "===", "index", ")", "{", "groups", ".", "push", "(", "[", "]", ")", ";", "}", "groups", "[", "index", "]", ".", "push", "(", "n", ")", ";", "}", ")", ";", "return", "groups", ";", "}" ]
Divide array into an array of arrays of size groupSize @param {Array} arr @param {integer} groupSize
[ "Divide", "array", "into", "an", "array", "of", "arrays", "of", "size", "groupSize" ]
4e9b410864afb731f88e84414984fa18ac5705f1
https://github.com/xsolon/spexplorerjs/blob/4e9b410864afb731f88e84414984fa18ac5705f1/webapi/src/components/string/funcs.js#L70-L81
52,803
tolokoban/ToloFrameWork
ker/mod/webgl.math.js
normalize
function normalize(arr) { const n = copy(arr); let len = 0; for (const v of n) len += v * v; if (len > 0) { const coeff = 1 / Math.sqrt(len); for (let k = 0; k < n.length; k++) { n[k] *= coeff; } } return n; }
javascript
function normalize(arr) { const n = copy(arr); let len = 0; for (const v of n) len += v * v; if (len > 0) { const coeff = 1 / Math.sqrt(len); for (let k = 0; k < n.length; k++) { n[k] *= coeff; } } return n; }
[ "function", "normalize", "(", "arr", ")", "{", "const", "n", "=", "copy", "(", "arr", ")", ";", "let", "len", "=", "0", ";", "for", "(", "const", "v", "of", "n", ")", "len", "+=", "v", "*", "v", ";", "if", "(", "len", ">", "0", ")", "{", "const", "coeff", "=", "1", "/", "Math", ".", "sqrt", "(", "len", ")", ";", "for", "(", "let", "k", "=", "0", ";", "k", "<", "n", ".", "length", ";", "k", "++", ")", "{", "n", "[", "k", "]", "*=", "coeff", ";", "}", "}", "return", "n", ";", "}" ]
Make a vector have a length of 1. @param {Float32Array} arr - Input vector. @returns {Float32Array} A new vector.
[ "Make", "a", "vector", "have", "a", "length", "of", "1", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/webgl.math.js#L71-L82
52,804
tolokoban/ToloFrameWork
ker/mod/webgl.math.js
perspective4
function perspective4(fieldAngle, aspect, near, far, result) { result = result || new Float32Array(16); var f = Math.tan(Math.PI * 0.5 - 0.5 * fieldAngle); var rangeInv = 1.0 / (near - far); result[0] = f / aspect; result[1] = 0; result[2] = 0; result[3] = 0; result[4] = 0; result[5] = f; result[6] = 0; result[7] = 0; result[8] = 0; result[9] = 0; result[10] = (near + far) * rangeInv; result[11] = -1; result[12] = 0; result[13] = 0; result[14] = near * far * rangeInv * 2; result[15] = 0; return result; }
javascript
function perspective4(fieldAngle, aspect, near, far, result) { result = result || new Float32Array(16); var f = Math.tan(Math.PI * 0.5 - 0.5 * fieldAngle); var rangeInv = 1.0 / (near - far); result[0] = f / aspect; result[1] = 0; result[2] = 0; result[3] = 0; result[4] = 0; result[5] = f; result[6] = 0; result[7] = 0; result[8] = 0; result[9] = 0; result[10] = (near + far) * rangeInv; result[11] = -1; result[12] = 0; result[13] = 0; result[14] = near * far * rangeInv * 2; result[15] = 0; return result; }
[ "function", "perspective4", "(", "fieldAngle", ",", "aspect", ",", "near", ",", "far", ",", "result", ")", "{", "result", "=", "result", "||", "new", "Float32Array", "(", "16", ")", ";", "var", "f", "=", "Math", ".", "tan", "(", "Math", ".", "PI", "*", "0.5", "-", "0.5", "*", "fieldAngle", ")", ";", "var", "rangeInv", "=", "1.0", "/", "(", "near", "-", "far", ")", ";", "result", "[", "0", "]", "=", "f", "/", "aspect", ";", "result", "[", "1", "]", "=", "0", ";", "result", "[", "2", "]", "=", "0", ";", "result", "[", "3", "]", "=", "0", ";", "result", "[", "4", "]", "=", "0", ";", "result", "[", "5", "]", "=", "f", ";", "result", "[", "6", "]", "=", "0", ";", "result", "[", "7", "]", "=", "0", ";", "result", "[", "8", "]", "=", "0", ";", "result", "[", "9", "]", "=", "0", ";", "result", "[", "10", "]", "=", "(", "near", "+", "far", ")", "*", "rangeInv", ";", "result", "[", "11", "]", "=", "-", "1", ";", "result", "[", "12", "]", "=", "0", ";", "result", "[", "13", "]", "=", "0", ";", "result", "[", "14", "]", "=", "near", "*", "far", "*", "rangeInv", "*", "2", ";", "result", "[", "15", "]", "=", "0", ";", "return", "result", ";", "}" ]
Define the `frustum`. @param {number} fieldAngle - View angle in radians. Maximum is PI. @param {number} aspect - (width / height) of the canvas. @param {number} near - Clip every Z lower than `near`. @param {number} far - Clip every Z greater than `far`.
[ "Define", "the", "frustum", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/webgl.math.js#L144-L170
52,805
wavesoft/gulp-jbb
index.js
streamOutput
function streamOutput( callback ) { return function(err, filenames) { if (err) { callback(err, null); } else { // Create read streams from each input var streams = [] for (var i=0; i<filenames.suffix.length; i++) streams.push([ fs.createReadStream( filenames.basename + filenames.suffix[i]), filenames.suffix[i] ]); // Callback with streams callback(err, streams); } } }
javascript
function streamOutput( callback ) { return function(err, filenames) { if (err) { callback(err, null); } else { // Create read streams from each input var streams = [] for (var i=0; i<filenames.suffix.length; i++) streams.push([ fs.createReadStream( filenames.basename + filenames.suffix[i]), filenames.suffix[i] ]); // Callback with streams callback(err, streams); } } }
[ "function", "streamOutput", "(", "callback", ")", "{", "return", "function", "(", "err", ",", "filenames", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "}", "else", "{", "// Create read streams from each input", "var", "streams", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "filenames", ".", "suffix", ".", "length", ";", "i", "++", ")", "streams", ".", "push", "(", "[", "fs", ".", "createReadStream", "(", "filenames", ".", "basename", "+", "filenames", ".", "suffix", "[", "i", "]", ")", ",", "filenames", ".", "suffix", "[", "i", "]", "]", ")", ";", "// Callback with streams", "callback", "(", "err", ",", "streams", ")", ";", "}", "}", "}" ]
Read resulting bundle and return a stream with it
[ "Read", "resulting", "bundle", "and", "return", "a", "stream", "with", "it" ]
d6a41efff91615d9a643c3b9332dadd3a4faa242
https://github.com/wavesoft/gulp-jbb/blob/d6a41efff91615d9a643c3b9332dadd3a4faa242/index.js#L34-L50
52,806
wavesoft/gulp-jbb
index.js
processAsBuffer
function processAsBuffer( file ) { return function( callback ) { var json = JSON.parse(file.contents); callback( json, path.dirname(file.path) ); } }
javascript
function processAsBuffer( file ) { return function( callback ) { var json = JSON.parse(file.contents); callback( json, path.dirname(file.path) ); } }
[ "function", "processAsBuffer", "(", "file", ")", "{", "return", "function", "(", "callback", ")", "{", "var", "json", "=", "JSON", ".", "parse", "(", "file", ".", "contents", ")", ";", "callback", "(", "json", ",", "path", ".", "dirname", "(", "file", ".", "path", ")", ")", ";", "}", "}" ]
Parse input file as buffer and return the JSON-parsed string
[ "Parse", "input", "file", "as", "buffer", "and", "return", "the", "JSON", "-", "parsed", "string" ]
d6a41efff91615d9a643c3b9332dadd3a4faa242
https://github.com/wavesoft/gulp-jbb/blob/d6a41efff91615d9a643c3b9332dadd3a4faa242/index.js#L55-L60
52,807
wavesoft/gulp-jbb
index.js
compileJBB
function compileJBB( config, parseCallback, resultCallback ) { // Continue compiling the JBB bundle var compile = function( bundleJSON, bundlePath, tempName ) { // Update path in config if (!config['path']) config['path'] = path.dirname(bundlePath); // Create the JBB bundle JBBCompiler.compile( bundleJSON, tempName, config, function() { // Check for sparse bundles if (config['sparse']) { resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbbp', '_b16.jbbp', '_b32.jbbp', '_b64.jbbp' ] }); } else { // Trigger callback resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbb' ] }); } } ); }; // Open a new temporary file (to be tracked by temp) temp.open({suffix: '_tmp'}, function(err, info) { // Handle errors if (err) { resultCallback(err, null); return; } fs.close(info.fd, function(err) { if (err) { resultCallback(err, null); return; } // We are ready, continue with compiling parseCallback(function( bundleJSON, baseName ) { compile( bundleJSON, baseName, info.path ); }); }); }); }
javascript
function compileJBB( config, parseCallback, resultCallback ) { // Continue compiling the JBB bundle var compile = function( bundleJSON, bundlePath, tempName ) { // Update path in config if (!config['path']) config['path'] = path.dirname(bundlePath); // Create the JBB bundle JBBCompiler.compile( bundleJSON, tempName, config, function() { // Check for sparse bundles if (config['sparse']) { resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbbp', '_b16.jbbp', '_b32.jbbp', '_b64.jbbp' ] }); } else { // Trigger callback resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbb' ] }); } } ); }; // Open a new temporary file (to be tracked by temp) temp.open({suffix: '_tmp'}, function(err, info) { // Handle errors if (err) { resultCallback(err, null); return; } fs.close(info.fd, function(err) { if (err) { resultCallback(err, null); return; } // We are ready, continue with compiling parseCallback(function( bundleJSON, baseName ) { compile( bundleJSON, baseName, info.path ); }); }); }); }
[ "function", "compileJBB", "(", "config", ",", "parseCallback", ",", "resultCallback", ")", "{", "// Continue compiling the JBB bundle", "var", "compile", "=", "function", "(", "bundleJSON", ",", "bundlePath", ",", "tempName", ")", "{", "// Update path in config", "if", "(", "!", "config", "[", "'path'", "]", ")", "config", "[", "'path'", "]", "=", "path", ".", "dirname", "(", "bundlePath", ")", ";", "// Create the JBB bundle", "JBBCompiler", ".", "compile", "(", "bundleJSON", ",", "tempName", ",", "config", ",", "function", "(", ")", "{", "// Check for sparse bundles", "if", "(", "config", "[", "'sparse'", "]", ")", "{", "resultCallback", "(", "null", ",", "{", "'basename'", ":", "tempName", ",", "'suffix'", ":", "[", "'.jbbp'", ",", "'_b16.jbbp'", ",", "'_b32.jbbp'", ",", "'_b64.jbbp'", "]", "}", ")", ";", "}", "else", "{", "// Trigger callback", "resultCallback", "(", "null", ",", "{", "'basename'", ":", "tempName", ",", "'suffix'", ":", "[", "'.jbb'", "]", "}", ")", ";", "}", "}", ")", ";", "}", ";", "// Open a new temporary file (to be tracked by temp)", "temp", ".", "open", "(", "{", "suffix", ":", "'_tmp'", "}", ",", "function", "(", "err", ",", "info", ")", "{", "// Handle errors", "if", "(", "err", ")", "{", "resultCallback", "(", "err", ",", "null", ")", ";", "return", ";", "}", "fs", ".", "close", "(", "info", ".", "fd", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "resultCallback", "(", "err", ",", "null", ")", ";", "return", ";", "}", "// We are ready, continue with compiling", "parseCallback", "(", "function", "(", "bundleJSON", ",", "baseName", ")", "{", "compile", "(", "bundleJSON", ",", "baseName", ",", "info", ".", "path", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Helper function to compile the JBB bundle according to the configuration options and return the temporary filename were the bundle was created.
[ "Helper", "function", "to", "compile", "the", "JBB", "bundle", "according", "to", "the", "configuration", "options", "and", "return", "the", "temporary", "filename", "were", "the", "bundle", "was", "created", "." ]
d6a41efff91615d9a643c3b9332dadd3a4faa242
https://github.com/wavesoft/gulp-jbb/blob/d6a41efff91615d9a643c3b9332dadd3a4faa242/index.js#L77-L137
52,808
wavesoft/gulp-jbb
index.js
function( bundleJSON, bundlePath, tempName ) { // Update path in config if (!config['path']) config['path'] = path.dirname(bundlePath); // Create the JBB bundle JBBCompiler.compile( bundleJSON, tempName, config, function() { // Check for sparse bundles if (config['sparse']) { resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbbp', '_b16.jbbp', '_b32.jbbp', '_b64.jbbp' ] }); } else { // Trigger callback resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbb' ] }); } } ); }
javascript
function( bundleJSON, bundlePath, tempName ) { // Update path in config if (!config['path']) config['path'] = path.dirname(bundlePath); // Create the JBB bundle JBBCompiler.compile( bundleJSON, tempName, config, function() { // Check for sparse bundles if (config['sparse']) { resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbbp', '_b16.jbbp', '_b32.jbbp', '_b64.jbbp' ] }); } else { // Trigger callback resultCallback( null, { 'basename': tempName, 'suffix': [ '.jbb' ] }); } } ); }
[ "function", "(", "bundleJSON", ",", "bundlePath", ",", "tempName", ")", "{", "// Update path in config", "if", "(", "!", "config", "[", "'path'", "]", ")", "config", "[", "'path'", "]", "=", "path", ".", "dirname", "(", "bundlePath", ")", ";", "// Create the JBB bundle", "JBBCompiler", ".", "compile", "(", "bundleJSON", ",", "tempName", ",", "config", ",", "function", "(", ")", "{", "// Check for sparse bundles", "if", "(", "config", "[", "'sparse'", "]", ")", "{", "resultCallback", "(", "null", ",", "{", "'basename'", ":", "tempName", ",", "'suffix'", ":", "[", "'.jbbp'", ",", "'_b16.jbbp'", ",", "'_b32.jbbp'", ",", "'_b64.jbbp'", "]", "}", ")", ";", "}", "else", "{", "// Trigger callback", "resultCallback", "(", "null", ",", "{", "'basename'", ":", "tempName", ",", "'suffix'", ":", "[", "'.jbb'", "]", "}", ")", ";", "}", "}", ")", ";", "}" ]
Continue compiling the JBB bundle
[ "Continue", "compiling", "the", "JBB", "bundle" ]
d6a41efff91615d9a643c3b9332dadd3a4faa242
https://github.com/wavesoft/gulp-jbb/blob/d6a41efff91615d9a643c3b9332dadd3a4faa242/index.js#L80-L113
52,809
wavesoft/gulp-jbb
index.js
function( err, streams ) { // Get base name var path = originalFile.path; var parts = path.split("."); parts.pop(); var baseName = parts.join("."); // Push each stream to output for (var i=0; i<streams.length; i++) { var f = originalFile.clone(); f.contents = streams[i][0]; // Content f.path = baseName + streams[i][1]; // Suffix self.push(f); } // We are done done(); return; }
javascript
function( err, streams ) { // Get base name var path = originalFile.path; var parts = path.split("."); parts.pop(); var baseName = parts.join("."); // Push each stream to output for (var i=0; i<streams.length; i++) { var f = originalFile.clone(); f.contents = streams[i][0]; // Content f.path = baseName + streams[i][1]; // Suffix self.push(f); } // We are done done(); return; }
[ "function", "(", "err", ",", "streams", ")", "{", "// Get base name", "var", "path", "=", "originalFile", ".", "path", ";", "var", "parts", "=", "path", ".", "split", "(", "\".\"", ")", ";", "parts", ".", "pop", "(", ")", ";", "var", "baseName", "=", "parts", ".", "join", "(", "\".\"", ")", ";", "// Push each stream to output", "for", "(", "var", "i", "=", "0", ";", "i", "<", "streams", ".", "length", ";", "i", "++", ")", "{", "var", "f", "=", "originalFile", ".", "clone", "(", ")", ";", "f", ".", "contents", "=", "streams", "[", "i", "]", "[", "0", "]", ";", "// Content", "f", ".", "path", "=", "baseName", "+", "streams", "[", "i", "]", "[", "1", "]", ";", "// Suffix", "self", ".", "push", "(", "f", ")", ";", "}", "// We are done", "done", "(", ")", ";", "return", ";", "}" ]
Call when finished with compression
[ "Call", "when", "finished", "with", "compression" ]
d6a41efff91615d9a643c3b9332dadd3a4faa242
https://github.com/wavesoft/gulp-jbb/blob/d6a41efff91615d9a643c3b9332dadd3a4faa242/index.js#L158-L176
52,810
redisjs/jsr-server
lib/signals.js
signals
function signals() { /** * Signal handler. */ function interrupt(signal) { this.log.notice('received %s, scheduling shutdown', signal); this.shutdown(0, process.exit); } interrupt = interrupt.bind(this); function iterate(signal) { /* test environment listener leak */ if(process.listeners(signal).length) return; process.once(signal, function() { interrupt(signal); }) } ['SIGINT', 'SIGTERM'].forEach(iterate.bind(this)); }
javascript
function signals() { /** * Signal handler. */ function interrupt(signal) { this.log.notice('received %s, scheduling shutdown', signal); this.shutdown(0, process.exit); } interrupt = interrupt.bind(this); function iterate(signal) { /* test environment listener leak */ if(process.listeners(signal).length) return; process.once(signal, function() { interrupt(signal); }) } ['SIGINT', 'SIGTERM'].forEach(iterate.bind(this)); }
[ "function", "signals", "(", ")", "{", "/**\n * Signal handler.\n */", "function", "interrupt", "(", "signal", ")", "{", "this", ".", "log", ".", "notice", "(", "'received %s, scheduling shutdown'", ",", "signal", ")", ";", "this", ".", "shutdown", "(", "0", ",", "process", ".", "exit", ")", ";", "}", "interrupt", "=", "interrupt", ".", "bind", "(", "this", ")", ";", "function", "iterate", "(", "signal", ")", "{", "/* test environment listener leak */", "if", "(", "process", ".", "listeners", "(", "signal", ")", ".", "length", ")", "return", ";", "process", ".", "once", "(", "signal", ",", "function", "(", ")", "{", "interrupt", "(", "signal", ")", ";", "}", ")", "}", "[", "'SIGINT'", ",", "'SIGTERM'", "]", ".", "forEach", "(", "iterate", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Register listeners for signals that trigger a shutdown.
[ "Register", "listeners", "for", "signals", "that", "trigger", "a", "shutdown", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/signals.js#L4-L27
52,811
StupidStudio/stupid-deferred
deferred.js
promiseThen
function promiseThen(success, reject, notify){ /** * @define {object} Return a new promise */ var def = Deferred(); /** * Resolved promise * @example example * @param {string} A string key for the event system * @param {function} A callback when event is triggered * @return {object} Returns promise object */ event.on('resolve', function(){ /** * If the success callback returns a promise * then resolve/reject/notify that returned promise */ var promise = success(); if(!promise) return; promise.success(function(){ /** handle the returned deferred object */ def.resolve(); }); promise.error(function(){ def.reject(); }); promise.notify(function(){ def.notify(); }); }); /** * If promise is rejected/notify trigger the callback */ event.on('reject', function(){ if(reject) reject(); }); event.on('notify', function(){ if(notify) notify(); }); /** * @return {object} Returns a promise object */ return def.promise; }
javascript
function promiseThen(success, reject, notify){ /** * @define {object} Return a new promise */ var def = Deferred(); /** * Resolved promise * @example example * @param {string} A string key for the event system * @param {function} A callback when event is triggered * @return {object} Returns promise object */ event.on('resolve', function(){ /** * If the success callback returns a promise * then resolve/reject/notify that returned promise */ var promise = success(); if(!promise) return; promise.success(function(){ /** handle the returned deferred object */ def.resolve(); }); promise.error(function(){ def.reject(); }); promise.notify(function(){ def.notify(); }); }); /** * If promise is rejected/notify trigger the callback */ event.on('reject', function(){ if(reject) reject(); }); event.on('notify', function(){ if(notify) notify(); }); /** * @return {object} Returns a promise object */ return def.promise; }
[ "function", "promiseThen", "(", "success", ",", "reject", ",", "notify", ")", "{", "/**\n\t\t * @define {object} Return a new promise\n\t\t */", "var", "def", "=", "Deferred", "(", ")", ";", "/**\n\t\t * Resolved promise\n\t\t * @example example\n\t\t * @param {string} A string key for the event system\n\t\t * @param {function} A callback when event is triggered\n\t\t * @return {object} Returns promise object\n\t\t */", "event", ".", "on", "(", "'resolve'", ",", "function", "(", ")", "{", "/**\n\t\t\t * If the success callback returns a promise\n\t\t\t * then resolve/reject/notify that returned promise\n\t\t\t */", "var", "promise", "=", "success", "(", ")", ";", "if", "(", "!", "promise", ")", "return", ";", "promise", ".", "success", "(", "function", "(", ")", "{", "/** handle the returned deferred object */", "def", ".", "resolve", "(", ")", ";", "}", ")", ";", "promise", ".", "error", "(", "function", "(", ")", "{", "def", ".", "reject", "(", ")", ";", "}", ")", ";", "promise", ".", "notify", "(", "function", "(", ")", "{", "def", ".", "notify", "(", ")", ";", "}", ")", ";", "}", ")", ";", "/**\n\t\t * If promise is rejected/notify trigger the callback\n\t\t */", "event", ".", "on", "(", "'reject'", ",", "function", "(", ")", "{", "if", "(", "reject", ")", "reject", "(", ")", ";", "}", ")", ";", "event", ".", "on", "(", "'notify'", ",", "function", "(", ")", "{", "if", "(", "notify", ")", "notify", "(", ")", ";", "}", ")", ";", "/**\n\t\t * @return {object} Returns a promise object\n\t\t */", "return", "def", ".", "promise", ";", "}" ]
Promise then method This is for chaining promis callbacks @example promiseFunction().then( function(){ // success }, function(){ // rejected }, function(){ // notify } ).then( ... ); @param {function} sucess Success callback @param {function} reject Reject callback @param {function} notify notify callback @return {object} Returns the promise object
[ "Promise", "then", "method", "This", "is", "for", "chaining", "promis", "callbacks" ]
d5e6aa8cf3b89e9faf58a811cd6e42df986ef0af
https://github.com/StupidStudio/stupid-deferred/blob/d5e6aa8cf3b89e9faf58a811cd6e42df986ef0af/deferred.js#L47-L94
52,812
StupidStudio/stupid-deferred
deferred.js
resolve
function resolve(){ var args = Array.prototype.slice.call(arguments); event.trigger('resolve', args); }
javascript
function resolve(){ var args = Array.prototype.slice.call(arguments); event.trigger('resolve', args); }
[ "function", "resolve", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "event", ".", "trigger", "(", "'resolve'", ",", "args", ")", ";", "}" ]
Deferred methods to trigger the promise @example def.resolve(args) @example def.reject(args) @example def.notify(args)
[ "Deferred", "methods", "to", "trigger", "the", "promise" ]
d5e6aa8cf3b89e9faf58a811cd6e42df986ef0af
https://github.com/StupidStudio/stupid-deferred/blob/d5e6aa8cf3b89e9faf58a811cd6e42df986ef0af/deferred.js#L124-L127
52,813
gethuman/pancakes-angular
lib/pancakes.angular.plugin.js
PancakesAngularPlugin
function PancakesAngularPlugin(opts) { this.templateDir = path.join(__dirname, 'transformers'); this.pancakes = opts.pluginOptions.pancakes; // initialize Jyt plugins this.registerJytPlugins(); // initialize all directives and load them into memory this.initDirectives(opts); // if mobile app then register mobile components if (this.isMobileApp()) { this.registerMobileComponents(); } // set all the transformation functions (used by the pancakes module transformation.factory this.transformers = { apiclient: apiTrans, app: appTrans, basic: basicTrans, routing: routingTrans, uipart: uipartTrans }; }
javascript
function PancakesAngularPlugin(opts) { this.templateDir = path.join(__dirname, 'transformers'); this.pancakes = opts.pluginOptions.pancakes; // initialize Jyt plugins this.registerJytPlugins(); // initialize all directives and load them into memory this.initDirectives(opts); // if mobile app then register mobile components if (this.isMobileApp()) { this.registerMobileComponents(); } // set all the transformation functions (used by the pancakes module transformation.factory this.transformers = { apiclient: apiTrans, app: appTrans, basic: basicTrans, routing: routingTrans, uipart: uipartTrans }; }
[ "function", "PancakesAngularPlugin", "(", "opts", ")", "{", "this", ".", "templateDir", "=", "path", ".", "join", "(", "__dirname", ",", "'transformers'", ")", ";", "this", ".", "pancakes", "=", "opts", ".", "pluginOptions", ".", "pancakes", ";", "// initialize Jyt plugins", "this", ".", "registerJytPlugins", "(", ")", ";", "// initialize all directives and load them into memory", "this", ".", "initDirectives", "(", "opts", ")", ";", "// if mobile app then register mobile components", "if", "(", "this", ".", "isMobileApp", "(", ")", ")", "{", "this", ".", "registerMobileComponents", "(", ")", ";", "}", "// set all the transformation functions (used by the pancakes module transformation.factory", "this", ".", "transformers", "=", "{", "apiclient", ":", "apiTrans", ",", "app", ":", "appTrans", ",", "basic", ":", "basicTrans", ",", "routing", ":", "routingTrans", ",", "uipart", ":", "uipartTrans", "}", ";", "}" ]
Constructor for the pancakes angular plugin @param opts @constructor
[ "Constructor", "for", "the", "pancakes", "angular", "plugin" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/pancakes.angular.plugin.js#L27-L50
52,814
mattstyles/octofish
lib/octofish.js
function( path, cb ) { // Set the content path octofish.setContentPath( path ); // Use the content path to retrieve content octofish.github.repos.getContent( octofish.config.contentOpts, function ( err, res ) { var data = null; // Handle any error if (err) { // Log the error - not a very useful log at the moment console.log( 'An error occured whilst getting content from github - this should be dealt with properly' ); console.log( 'It is most likely a URL error with the path' ); // Call the callback with a null value to denote an error cb( data ); return; } // Decode the data before sending on to the callback // Check for decoding an image if ( octofish.config.contentOpts.path.match(/img/) ) { data = octofish.decodeGithubImageData( res.content ); } else { data = octofish.decodeGithubData( res.content ); } // If the content was collected successfully then call the callback and remember to pass in the data cb( data ); }); }
javascript
function( path, cb ) { // Set the content path octofish.setContentPath( path ); // Use the content path to retrieve content octofish.github.repos.getContent( octofish.config.contentOpts, function ( err, res ) { var data = null; // Handle any error if (err) { // Log the error - not a very useful log at the moment console.log( 'An error occured whilst getting content from github - this should be dealt with properly' ); console.log( 'It is most likely a URL error with the path' ); // Call the callback with a null value to denote an error cb( data ); return; } // Decode the data before sending on to the callback // Check for decoding an image if ( octofish.config.contentOpts.path.match(/img/) ) { data = octofish.decodeGithubImageData( res.content ); } else { data = octofish.decodeGithubData( res.content ); } // If the content was collected successfully then call the callback and remember to pass in the data cb( data ); }); }
[ "function", "(", "path", ",", "cb", ")", "{", "// Set the content path", "octofish", ".", "setContentPath", "(", "path", ")", ";", "// Use the content path to retrieve content", "octofish", ".", "github", ".", "repos", ".", "getContent", "(", "octofish", ".", "config", ".", "contentOpts", ",", "function", "(", "err", ",", "res", ")", "{", "var", "data", "=", "null", ";", "// Handle any error", "if", "(", "err", ")", "{", "// Log the error - not a very useful log at the moment", "console", ".", "log", "(", "'An error occured whilst getting content from github - this should be dealt with properly'", ")", ";", "console", ".", "log", "(", "'It is most likely a URL error with the path'", ")", ";", "// Call the callback with a null value to denote an error", "cb", "(", "data", ")", ";", "return", ";", "}", "// Decode the data before sending on to the callback", "// Check for decoding an image", "if", "(", "octofish", ".", "config", ".", "contentOpts", ".", "path", ".", "match", "(", "/", "img", "/", ")", ")", "{", "data", "=", "octofish", ".", "decodeGithubImageData", "(", "res", ".", "content", ")", ";", "}", "else", "{", "data", "=", "octofish", ".", "decodeGithubData", "(", "res", ".", "content", ")", ";", "}", "// If the content was collected successfully then call the callback and remember to pass in the data", "cb", "(", "data", ")", ";", "}", ")", ";", "}" ]
getContent gets the content from github repo set up in config @param cb - the callback to fire on success - passes in the collected data
[ "getContent", "gets", "the", "content", "from", "github", "repo", "set", "up", "in", "config" ]
24e3d7e662a9551bcd5f158e94d56f05f75171ab
https://github.com/mattstyles/octofish/blob/24e3d7e662a9551bcd5f158e94d56f05f75171ab/lib/octofish.js#L79-L110
52,815
mattstyles/octofish
lib/octofish.js
function( authType ) { switch ( authType.toLowerCase() ) { case 'basic': console.log( 'Attempting to use basic authorisation' ); getBasicAuth() ? cb_success() : cb_failure(); break; case 'oauth': console.log( 'Using oAuth to authenticate' ); return getOAuth(); break; default: console.warn( 'Incorrect authorisation type passed to Octofish' ); console.warn( 'Authorisation to github will be unauthorised' ); cb_failure(); return false; } return true; }
javascript
function( authType ) { switch ( authType.toLowerCase() ) { case 'basic': console.log( 'Attempting to use basic authorisation' ); getBasicAuth() ? cb_success() : cb_failure(); break; case 'oauth': console.log( 'Using oAuth to authenticate' ); return getOAuth(); break; default: console.warn( 'Incorrect authorisation type passed to Octofish' ); console.warn( 'Authorisation to github will be unauthorised' ); cb_failure(); return false; } return true; }
[ "function", "(", "authType", ")", "{", "switch", "(", "authType", ".", "toLowerCase", "(", ")", ")", "{", "case", "'basic'", ":", "console", ".", "log", "(", "'Attempting to use basic authorisation'", ")", ";", "getBasicAuth", "(", ")", "?", "cb_success", "(", ")", ":", "cb_failure", "(", ")", ";", "break", ";", "case", "'oauth'", ":", "console", ".", "log", "(", "'Using oAuth to authenticate'", ")", ";", "return", "getOAuth", "(", ")", ";", "break", ";", "default", ":", "console", ".", "warn", "(", "'Incorrect authorisation type passed to Octofish'", ")", ";", "console", ".", "warn", "(", "'Authorisation to github will be unauthorised'", ")", ";", "cb_failure", "(", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Gets the correct method for building an authentication object to pass to github @param authType { basic || oauth } @return calls the correct function for building an auth object || null
[ "Gets", "the", "correct", "method", "for", "building", "an", "authentication", "object", "to", "pass", "to", "github" ]
24e3d7e662a9551bcd5f158e94d56f05f75171ab
https://github.com/mattstyles/octofish/blob/24e3d7e662a9551bcd5f158e94d56f05f75171ab/lib/octofish.js#L127-L148
52,816
mattstyles/octofish
lib/octofish.js
function() { auth.type = 'basic'; auth.username = process.env.GHusername || octofish.config.auth.username || null; auth.password = process.env.GHpassword || octofish.config.auth.password || null; if ( !auth.password || !auth.username ) { return false; } else { octofish.github.authenticate( auth ); return true; } }
javascript
function() { auth.type = 'basic'; auth.username = process.env.GHusername || octofish.config.auth.username || null; auth.password = process.env.GHpassword || octofish.config.auth.password || null; if ( !auth.password || !auth.username ) { return false; } else { octofish.github.authenticate( auth ); return true; } }
[ "function", "(", ")", "{", "auth", ".", "type", "=", "'basic'", ";", "auth", ".", "username", "=", "process", ".", "env", ".", "GHusername", "||", "octofish", ".", "config", ".", "auth", ".", "username", "||", "null", ";", "auth", ".", "password", "=", "process", ".", "env", ".", "GHpassword", "||", "octofish", ".", "config", ".", "auth", ".", "password", "||", "null", ";", "if", "(", "!", "auth", ".", "password", "||", "!", "auth", ".", "username", ")", "{", "return", "false", ";", "}", "else", "{", "octofish", ".", "github", ".", "authenticate", "(", "auth", ")", ";", "return", "true", ";", "}", "}" ]
Completes basic authorisation or returns false on failure @todo Currently only checks that a username and password have been specified, not that they have successfully completed authentication @return {Boolean}
[ "Completes", "basic", "authorisation", "or", "returns", "false", "on", "failure" ]
24e3d7e662a9551bcd5f158e94d56f05f75171ab
https://github.com/mattstyles/octofish/blob/24e3d7e662a9551bcd5f158e94d56f05f75171ab/lib/octofish.js#L163-L175
52,817
magicdawn/predator-kit
lib/index.js
Predator
function Predator(options) { if (!(this instanceof Predator)) { return new Predator(options); } if (!options || !options.app) { throw new Error('options.app is required'); } // 主目录 this.home = pathFn.resolve(options.home || '.'); // app this.app = options.app; // build 目录 this.buildDir = pathFn.resolve(options.buildDir || './public'); }
javascript
function Predator(options) { if (!(this instanceof Predator)) { return new Predator(options); } if (!options || !options.app) { throw new Error('options.app is required'); } // 主目录 this.home = pathFn.resolve(options.home || '.'); // app this.app = options.app; // build 目录 this.buildDir = pathFn.resolve(options.buildDir || './public'); }
[ "function", "Predator", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Predator", ")", ")", "{", "return", "new", "Predator", "(", "options", ")", ";", "}", "if", "(", "!", "options", "||", "!", "options", ".", "app", ")", "{", "throw", "new", "Error", "(", "'options.app is required'", ")", ";", "}", "// 主目录", "this", ".", "home", "=", "pathFn", ".", "resolve", "(", "options", ".", "home", "||", "'.'", ")", ";", "// app", "this", ".", "app", "=", "options", ".", "app", ";", "// build 目录", "this", ".", "buildDir", "=", "pathFn", ".", "resolve", "(", "options", ".", "buildDir", "||", "'./public'", ")", ";", "}" ]
Preadtor class def options - home: 主目录 - app: koa app - buildDir: build static files
[ "Preadtor", "class", "def" ]
aa6b7b3094a278a536a731639611556f76e5a8b9
https://github.com/magicdawn/predator-kit/blob/aa6b7b3094a278a536a731639611556f76e5a8b9/lib/index.js#L39-L56
52,818
node-neatly/neatly
lib/module.js
createQueuePusher
function createQueuePusher(providerName, method, insertMethod, queue) { return function() { let args = arguments; // Add provide method to invokeQueue to execute it on bootstrap. (queue || invokeQueue)[insertMethod || 'push'](function provide(injector) { // Get provider let provider = injector.get(providerName); // Execute method on provider provider[method].apply(provider, args); // Return name in case of provider, factory, service, value or constant if (providerName === '$provide') { return args[0]; } }); return that; }; }
javascript
function createQueuePusher(providerName, method, insertMethod, queue) { return function() { let args = arguments; // Add provide method to invokeQueue to execute it on bootstrap. (queue || invokeQueue)[insertMethod || 'push'](function provide(injector) { // Get provider let provider = injector.get(providerName); // Execute method on provider provider[method].apply(provider, args); // Return name in case of provider, factory, service, value or constant if (providerName === '$provide') { return args[0]; } }); return that; }; }
[ "function", "createQueuePusher", "(", "providerName", ",", "method", ",", "insertMethod", ",", "queue", ")", "{", "return", "function", "(", ")", "{", "let", "args", "=", "arguments", ";", "// Add provide method to invokeQueue to execute it on bootstrap.", "(", "queue", "||", "invokeQueue", ")", "[", "insertMethod", "||", "'push'", "]", "(", "function", "provide", "(", "injector", ")", "{", "// Get provider", "let", "provider", "=", "injector", ".", "get", "(", "providerName", ")", ";", "// Execute method on provider", "provider", "[", "method", "]", ".", "apply", "(", "provider", ",", "args", ")", ";", "// Return name in case of provider, factory, service, value or constant", "if", "(", "providerName", "===", "'$provide'", ")", "{", "return", "args", "[", "0", "]", ";", "}", "}", ")", ";", "return", "that", ";", "}", ";", "}" ]
Helper to create a function which adds a provide-method to invokeQueue. @param {String} providerName $provide | $injector @param {String} method method to execute on provider @param {String} insertMethod native array-methods (default: push) @return {Object} self
[ "Helper", "to", "create", "a", "function", "which", "adds", "a", "provide", "-", "method", "to", "invokeQueue", "." ]
732d9729bce84013b5516fe7c239dd672d138dd8
https://github.com/node-neatly/neatly/blob/732d9729bce84013b5516fe7c239dd672d138dd8/lib/module.js#L24-L46
52,819
sbyrnes/bloom.js
bloom.js
estimateFalsePositiveRate
function estimateFalsePositiveRate(numValues, numBuckets, numHashes) { // Formula for false positives is (1-e^(-kn/m))^k // k - number of hashes // n - number of set entries // m - number of buckets var expectedFalsePositivesRate = Math.pow((1 - Math.exp(-numHashes * numValues / numBuckets)), numHashes); return expectedFalsePositivesRate; }
javascript
function estimateFalsePositiveRate(numValues, numBuckets, numHashes) { // Formula for false positives is (1-e^(-kn/m))^k // k - number of hashes // n - number of set entries // m - number of buckets var expectedFalsePositivesRate = Math.pow((1 - Math.exp(-numHashes * numValues / numBuckets)), numHashes); return expectedFalsePositivesRate; }
[ "function", "estimateFalsePositiveRate", "(", "numValues", ",", "numBuckets", ",", "numHashes", ")", "{", "// Formula for false positives is (1-e^(-kn/m))^k", "// k - number of hashes", "// n - number of set entries", "// m - number of buckets", "var", "expectedFalsePositivesRate", "=", "Math", ".", "pow", "(", "(", "1", "-", "Math", ".", "exp", "(", "-", "numHashes", "*", "numValues", "/", "numBuckets", ")", ")", ",", "numHashes", ")", ";", "return", "expectedFalsePositivesRate", ";", "}" ]
Estimate the false positive rate for a given set of usage parameters @param numValues The number of unique values in the set to be added to the filter. @param numBuckets The number of unique buckets (bits) in the filter @param numHashes The number of hashes to use. @return Estimated false positive percentage as a float.
[ "Estimate", "the", "false", "positive", "rate", "for", "a", "given", "set", "of", "usage", "parameters" ]
e93fdbda2e1aabd7895c5625f3ad5f845f949aad
https://github.com/sbyrnes/bloom.js/blob/e93fdbda2e1aabd7895c5625f3ad5f845f949aad/bloom.js#L106-L115
52,820
redisjs/jsr-client
lib/multi.js
_reset
function _reset() { this._queue = []; this._commands = [{cmd: Constants.MAP.multi.name, args: []}]; this._multi = false; }
javascript
function _reset() { this._queue = []; this._commands = [{cmd: Constants.MAP.multi.name, args: []}]; this._multi = false; }
[ "function", "_reset", "(", ")", "{", "this", ".", "_queue", "=", "[", "]", ";", "this", ".", "_commands", "=", "[", "{", "cmd", ":", "Constants", ".", "MAP", ".", "multi", ".", "name", ",", "args", ":", "[", "]", "}", "]", ";", "this", ".", "_multi", "=", "false", ";", "}" ]
Reset the multi so that it may be used again.
[ "Reset", "the", "multi", "so", "that", "it", "may", "be", "used", "again", "." ]
be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b
https://github.com/redisjs/jsr-client/blob/be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b/lib/multi.js#L25-L29
52,821
redisjs/jsr-client
lib/multi.js
_abort
function _abort(err) { this._queue = null; this._commands = null; // listen for the event so we can clean reference function onError() { this._client = null; } this._client.once('error', onError.bind(this)); this._client.emit('error', err); }
javascript
function _abort(err) { this._queue = null; this._commands = null; // listen for the event so we can clean reference function onError() { this._client = null; } this._client.once('error', onError.bind(this)); this._client.emit('error', err); }
[ "function", "_abort", "(", "err", ")", "{", "this", ".", "_queue", "=", "null", ";", "this", ".", "_commands", "=", "null", ";", "// listen for the event so we can clean reference", "function", "onError", "(", ")", "{", "this", ".", "_client", "=", "null", ";", "}", "this", ".", "_client", ".", "once", "(", "'error'", ",", "onError", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "_client", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}" ]
Abort with an error.
[ "Abort", "with", "an", "error", "." ]
be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b
https://github.com/redisjs/jsr-client/blob/be90dd5c062e4efb38d5b7f91d3ad9f43174cb3b/lib/multi.js#L35-L44
52,822
ksmithut/confess
lib/load-file.js
loadFile
function loadFile(filepath, defaultObj) { defaultObj = defaultObj || {}; if (!isFile(filepath)) { return defaultObj; } var extension = path.extname(filepath).replace(/^\./, ''); var contents = supportedExtensions[extension](filepath); return assign({}, defaultObj, contents); }
javascript
function loadFile(filepath, defaultObj) { defaultObj = defaultObj || {}; if (!isFile(filepath)) { return defaultObj; } var extension = path.extname(filepath).replace(/^\./, ''); var contents = supportedExtensions[extension](filepath); return assign({}, defaultObj, contents); }
[ "function", "loadFile", "(", "filepath", ",", "defaultObj", ")", "{", "defaultObj", "=", "defaultObj", "||", "{", "}", ";", "if", "(", "!", "isFile", "(", "filepath", ")", ")", "{", "return", "defaultObj", ";", "}", "var", "extension", "=", "path", ".", "extname", "(", "filepath", ")", ".", "replace", "(", "/", "^\\.", "/", ",", "''", ")", ";", "var", "contents", "=", "supportedExtensions", "[", "extension", "]", "(", "filepath", ")", ";", "return", "assign", "(", "{", "}", ",", "defaultObj", ",", "contents", ")", ";", "}" ]
Loads a file, if it exists. If it doesn't, then return the default object or empty object
[ "Loads", "a", "file", "if", "it", "exists", ".", "If", "it", "doesn", "t", "then", "return", "the", "default", "object", "or", "empty", "object" ]
937976ebfb52aa2cc9a5b337be28ee790ce9c403
https://github.com/ksmithut/confess/blob/937976ebfb52aa2cc9a5b337be28ee790ce9c403/lib/load-file.js#L18-L27
52,823
jneurock/gulp-viking-posts
index.js
createPost
function createPost( file, options ) { resetDoc(); var _formatDate = options && typeof options.formatDate === 'function' ? options.formatDate : formatDate, post = new Post(); // Parse front matter to get as many post attributes as possible parseFrontMatter( file, post, options ); // Get category from path if not from front matter if ( !post.category ) { post.category = getCategoryFromPath( file ); } // Get creation date from file if not from front matter if ( !post.created ) { post.created = _formatDate( file.stat.ctime ); } // Get excerpt from first <p> tag if not from front matter if ( !post.excerpt ) { post.excerpt = getDefaultExcerpt( post.content ); } // Get title from file name if not from front matter if ( !post.title ) { post.title = getTitleFromPath( file ); } // Get updated date from file if not from front matter if ( !post.updated ) { post.updated = _formatDate( file.stat.mtime ); /* * If updated date from file system matches creation date, * assume udated date should be empty */ if ( post.updated === post.created ) { post.updated = ''; } } return JSON.stringify( post ); }
javascript
function createPost( file, options ) { resetDoc(); var _formatDate = options && typeof options.formatDate === 'function' ? options.formatDate : formatDate, post = new Post(); // Parse front matter to get as many post attributes as possible parseFrontMatter( file, post, options ); // Get category from path if not from front matter if ( !post.category ) { post.category = getCategoryFromPath( file ); } // Get creation date from file if not from front matter if ( !post.created ) { post.created = _formatDate( file.stat.ctime ); } // Get excerpt from first <p> tag if not from front matter if ( !post.excerpt ) { post.excerpt = getDefaultExcerpt( post.content ); } // Get title from file name if not from front matter if ( !post.title ) { post.title = getTitleFromPath( file ); } // Get updated date from file if not from front matter if ( !post.updated ) { post.updated = _formatDate( file.stat.mtime ); /* * If updated date from file system matches creation date, * assume udated date should be empty */ if ( post.updated === post.created ) { post.updated = ''; } } return JSON.stringify( post ); }
[ "function", "createPost", "(", "file", ",", "options", ")", "{", "resetDoc", "(", ")", ";", "var", "_formatDate", "=", "options", "&&", "typeof", "options", ".", "formatDate", "===", "'function'", "?", "options", ".", "formatDate", ":", "formatDate", ",", "post", "=", "new", "Post", "(", ")", ";", "// Parse front matter to get as many post attributes as possible", "parseFrontMatter", "(", "file", ",", "post", ",", "options", ")", ";", "// Get category from path if not from front matter", "if", "(", "!", "post", ".", "category", ")", "{", "post", ".", "category", "=", "getCategoryFromPath", "(", "file", ")", ";", "}", "// Get creation date from file if not from front matter", "if", "(", "!", "post", ".", "created", ")", "{", "post", ".", "created", "=", "_formatDate", "(", "file", ".", "stat", ".", "ctime", ")", ";", "}", "// Get excerpt from first <p> tag if not from front matter", "if", "(", "!", "post", ".", "excerpt", ")", "{", "post", ".", "excerpt", "=", "getDefaultExcerpt", "(", "post", ".", "content", ")", ";", "}", "// Get title from file name if not from front matter", "if", "(", "!", "post", ".", "title", ")", "{", "post", ".", "title", "=", "getTitleFromPath", "(", "file", ")", ";", "}", "// Get updated date from file if not from front matter", "if", "(", "!", "post", ".", "updated", ")", "{", "post", ".", "updated", "=", "_formatDate", "(", "file", ".", "stat", ".", "mtime", ")", ";", "/*\n\t\t * If updated date from file system matches creation date,\n\t\t * assume udated date should be empty\n\t\t */", "if", "(", "post", ".", "updated", "===", "post", ".", "created", ")", "{", "post", ".", "updated", "=", "''", ";", "}", "}", "return", "JSON", ".", "stringify", "(", "post", ")", ";", "}" ]
Create a post object @param {Object} file @param {Object} [options] @returns {string} post object as a string
[ "Create", "a", "post", "object" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L30-L81
52,824
jneurock/gulp-viking-posts
index.js
formatDate
function formatDate( date ) { var dateString = ''; date = new Date( date ); dateString = date.getMonth() + 1; dateString += '/'; dateString += date.getDate(); dateString += '/'; dateString += date.getFullYear(); return dateString; }
javascript
function formatDate( date ) { var dateString = ''; date = new Date( date ); dateString = date.getMonth() + 1; dateString += '/'; dateString += date.getDate(); dateString += '/'; dateString += date.getFullYear(); return dateString; }
[ "function", "formatDate", "(", "date", ")", "{", "var", "dateString", "=", "''", ";", "date", "=", "new", "Date", "(", "date", ")", ";", "dateString", "=", "date", ".", "getMonth", "(", ")", "+", "1", ";", "dateString", "+=", "'/'", ";", "dateString", "+=", "date", ".", "getDate", "(", ")", ";", "dateString", "+=", "'/'", ";", "dateString", "+=", "date", ".", "getFullYear", "(", ")", ";", "return", "dateString", ";", "}" ]
Format a date @param {(Object|string)} date The date object to format @returns {string}
[ "Format", "a", "date" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L89-L102
52,825
jneurock/gulp-viking-posts
index.js
getCategoryFromPath
function getCategoryFromPath( file ) { var category = '', i = 0, parts = file.path.split('/'), len = parts.length, last = len - 1; for ( ; i < len; i++ ) { /* * If previous path part is "posts" and the * current path part isn't the last path part */ if ( parts[i - 1] === 'posts' && i !== last ) { category = parts[i]; break; } } return category; }
javascript
function getCategoryFromPath( file ) { var category = '', i = 0, parts = file.path.split('/'), len = parts.length, last = len - 1; for ( ; i < len; i++ ) { /* * If previous path part is "posts" and the * current path part isn't the last path part */ if ( parts[i - 1] === 'posts' && i !== last ) { category = parts[i]; break; } } return category; }
[ "function", "getCategoryFromPath", "(", "file", ")", "{", "var", "category", "=", "''", ",", "i", "=", "0", ",", "parts", "=", "file", ".", "path", ".", "split", "(", "'/'", ")", ",", "len", "=", "parts", ".", "length", ",", "last", "=", "len", "-", "1", ";", "for", "(", ";", "i", "<", "len", ";", "i", "++", ")", "{", "/*\n\t\t * If previous path part is \"posts\" and the\n\t\t * current path part isn't the last path part\n\t\t */", "if", "(", "parts", "[", "i", "-", "1", "]", "===", "'posts'", "&&", "i", "!==", "last", ")", "{", "category", "=", "parts", "[", "i", "]", ";", "break", ";", "}", "}", "return", "category", ";", "}" ]
Get post category from file path @param {Object} file @returns {string}
[ "Get", "post", "category", "from", "file", "path" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L110-L133
52,826
jneurock/gulp-viking-posts
index.js
getTitleFromPath
function getTitleFromPath( file, options ) { var _titleSeparator = options && options.titleSeparator ? options.titleSeparator : titleSeparator, i = 0, parts = file.path.split('/'), fileParts = parts[parts.length - 1].split('.'), filename = fileParts[0], fileNameParts = filename.split( _titleSeparator ), len = fileNameParts.length, title = ''; for ( ; i < len; i++ ) { title += i ? ' ' : ''; title += fileNameParts[i]; } return titleCase( title ); }
javascript
function getTitleFromPath( file, options ) { var _titleSeparator = options && options.titleSeparator ? options.titleSeparator : titleSeparator, i = 0, parts = file.path.split('/'), fileParts = parts[parts.length - 1].split('.'), filename = fileParts[0], fileNameParts = filename.split( _titleSeparator ), len = fileNameParts.length, title = ''; for ( ; i < len; i++ ) { title += i ? ' ' : ''; title += fileNameParts[i]; } return titleCase( title ); }
[ "function", "getTitleFromPath", "(", "file", ",", "options", ")", "{", "var", "_titleSeparator", "=", "options", "&&", "options", ".", "titleSeparator", "?", "options", ".", "titleSeparator", ":", "titleSeparator", ",", "i", "=", "0", ",", "parts", "=", "file", ".", "path", ".", "split", "(", "'/'", ")", ",", "fileParts", "=", "parts", "[", "parts", ".", "length", "-", "1", "]", ".", "split", "(", "'.'", ")", ",", "filename", "=", "fileParts", "[", "0", "]", ",", "fileNameParts", "=", "filename", ".", "split", "(", "_titleSeparator", ")", ",", "len", "=", "fileNameParts", ".", "length", ",", "title", "=", "''", ";", "for", "(", ";", "i", "<", "len", ";", "i", "++", ")", "{", "title", "+=", "i", "?", "' '", ":", "''", ";", "title", "+=", "fileNameParts", "[", "i", "]", ";", "}", "return", "titleCase", "(", "title", ")", ";", "}" ]
Get post title from file path @param {Object} file @param {Object} [options] @returns {string}
[ "Get", "post", "title", "from", "file", "path" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L167-L186
52,827
jneurock/gulp-viking-posts
index.js
highlightPostSyntax
function highlightPostSyntax( post ) { var codeTags = [], i = 0, len = 0; doc = doc || createDom( post.content ); codeTags = doc.querySelectorAll('pre code'); len = codeTags.length; for ( ; i < len; i++ ) { // Replace class names beginning with "lang-" with "language-" for Highlight.js codeTags[i].className = codeTags[i].className.replace('lang-', 'language-'); hljs.highlightBlock( codeTags[i] ); } post.content = doc.body.innerHTML; }
javascript
function highlightPostSyntax( post ) { var codeTags = [], i = 0, len = 0; doc = doc || createDom( post.content ); codeTags = doc.querySelectorAll('pre code'); len = codeTags.length; for ( ; i < len; i++ ) { // Replace class names beginning with "lang-" with "language-" for Highlight.js codeTags[i].className = codeTags[i].className.replace('lang-', 'language-'); hljs.highlightBlock( codeTags[i] ); } post.content = doc.body.innerHTML; }
[ "function", "highlightPostSyntax", "(", "post", ")", "{", "var", "codeTags", "=", "[", "]", ",", "i", "=", "0", ",", "len", "=", "0", ";", "doc", "=", "doc", "||", "createDom", "(", "post", ".", "content", ")", ";", "codeTags", "=", "doc", ".", "querySelectorAll", "(", "'pre code'", ")", ";", "len", "=", "codeTags", ".", "length", ";", "for", "(", ";", "i", "<", "len", ";", "i", "++", ")", "{", "// Replace class names beginning with \"lang-\" with \"language-\" for Highlight.js", "codeTags", "[", "i", "]", ".", "className", "=", "codeTags", "[", "i", "]", ".", "className", ".", "replace", "(", "'lang-'", ",", "'language-'", ")", ";", "hljs", ".", "highlightBlock", "(", "codeTags", "[", "i", "]", ")", ";", "}", "post", ".", "content", "=", "doc", ".", "body", ".", "innerHTML", ";", "}" ]
Parse any code blocks in the post content and highlight syntax @param {Object} post
[ "Parse", "any", "code", "blocks", "in", "the", "post", "content", "and", "highlight", "syntax" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L193-L214
52,828
jneurock/gulp-viking-posts
index.js
isCustomFrontMatter
function isCustomFrontMatter( attr ) { if ( attr !== 'title' && attr !== 'category' && attr !== 'content' && attr !== 'created' && attr !== 'excerpt' && attr !== 'updated' ) { return true; } else { return false; } }
javascript
function isCustomFrontMatter( attr ) { if ( attr !== 'title' && attr !== 'category' && attr !== 'content' && attr !== 'created' && attr !== 'excerpt' && attr !== 'updated' ) { return true; } else { return false; } }
[ "function", "isCustomFrontMatter", "(", "attr", ")", "{", "if", "(", "attr", "!==", "'title'", "&&", "attr", "!==", "'category'", "&&", "attr", "!==", "'content'", "&&", "attr", "!==", "'created'", "&&", "attr", "!==", "'excerpt'", "&&", "attr", "!==", "'updated'", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Check if front matter attribute is custom or not @param {string} attr The attribute name @returns {boolean}
[ "Check", "if", "front", "matter", "attribute", "is", "custom", "or", "not" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L222-L233
52,829
jneurock/gulp-viking-posts
index.js
parseFrontMatter
function parseFrontMatter( file, post, options ) { var _formatDate = options && typeof options.formatDate === 'function' ? options.formatDate : formatDate, content = frontMatter( file.contents.toString() ), prop = ''; if ( content.attributes ) { post.category = content.attributes.category || ''; post.created = content.attributes.created ? _formatDate( content.attributes.created ) : ''; post.title = content.attributes.title || ''; post.updated = content.attributes.updated ? _formatDate( content.attributes.updated ) : ''; if ( content.attributes.excerpt ) { post.excerpt = markdown( content.attributes.excerpt ); } post.content = content.body ? markdown( content.body ) : ''; if ( post.content && highlightSyntax ) { highlightPostSyntax( post ); } // Look for custom front-matter for ( prop in content.attributes ) { if ( content.attributes.hasOwnProperty( prop ) && isCustomFrontMatter( prop ) ) { post[ prop ] = content.attributes[ prop ]; } } } }
javascript
function parseFrontMatter( file, post, options ) { var _formatDate = options && typeof options.formatDate === 'function' ? options.formatDate : formatDate, content = frontMatter( file.contents.toString() ), prop = ''; if ( content.attributes ) { post.category = content.attributes.category || ''; post.created = content.attributes.created ? _formatDate( content.attributes.created ) : ''; post.title = content.attributes.title || ''; post.updated = content.attributes.updated ? _formatDate( content.attributes.updated ) : ''; if ( content.attributes.excerpt ) { post.excerpt = markdown( content.attributes.excerpt ); } post.content = content.body ? markdown( content.body ) : ''; if ( post.content && highlightSyntax ) { highlightPostSyntax( post ); } // Look for custom front-matter for ( prop in content.attributes ) { if ( content.attributes.hasOwnProperty( prop ) && isCustomFrontMatter( prop ) ) { post[ prop ] = content.attributes[ prop ]; } } } }
[ "function", "parseFrontMatter", "(", "file", ",", "post", ",", "options", ")", "{", "var", "_formatDate", "=", "options", "&&", "typeof", "options", ".", "formatDate", "===", "'function'", "?", "options", ".", "formatDate", ":", "formatDate", ",", "content", "=", "frontMatter", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ",", "prop", "=", "''", ";", "if", "(", "content", ".", "attributes", ")", "{", "post", ".", "category", "=", "content", ".", "attributes", ".", "category", "||", "''", ";", "post", ".", "created", "=", "content", ".", "attributes", ".", "created", "?", "_formatDate", "(", "content", ".", "attributes", ".", "created", ")", ":", "''", ";", "post", ".", "title", "=", "content", ".", "attributes", ".", "title", "||", "''", ";", "post", ".", "updated", "=", "content", ".", "attributes", ".", "updated", "?", "_formatDate", "(", "content", ".", "attributes", ".", "updated", ")", ":", "''", ";", "if", "(", "content", ".", "attributes", ".", "excerpt", ")", "{", "post", ".", "excerpt", "=", "markdown", "(", "content", ".", "attributes", ".", "excerpt", ")", ";", "}", "post", ".", "content", "=", "content", ".", "body", "?", "markdown", "(", "content", ".", "body", ")", ":", "''", ";", "if", "(", "post", ".", "content", "&&", "highlightSyntax", ")", "{", "highlightPostSyntax", "(", "post", ")", ";", "}", "// Look for custom front-matter", "for", "(", "prop", "in", "content", ".", "attributes", ")", "{", "if", "(", "content", ".", "attributes", ".", "hasOwnProperty", "(", "prop", ")", "&&", "isCustomFrontMatter", "(", "prop", ")", ")", "{", "post", "[", "prop", "]", "=", "content", ".", "attributes", "[", "prop", "]", ";", "}", "}", "}", "}" ]
Parse YAML front matter from post @param {Object} file The post file object @param {Object} post The new post object we're working with @param {Object} [options]
[ "Parse", "YAML", "front", "matter", "from", "post" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L242-L277
52,830
jneurock/gulp-viking-posts
index.js
sortPosts
function sortPosts( a, b ) { var dateA = new Date( a.created ), dateB = new Date( b.created ); // See if dates match if ( dateB - dateA === 0 ) { // See if categories are the same if ( a.category === b.category ) { // Sort by title return a.title.localeCompare( b.title ); // Sort by category } else { return a.category.localeCompare( b.category ); } // Sort by date descending } else { return dateB - dateA; } }
javascript
function sortPosts( a, b ) { var dateA = new Date( a.created ), dateB = new Date( b.created ); // See if dates match if ( dateB - dateA === 0 ) { // See if categories are the same if ( a.category === b.category ) { // Sort by title return a.title.localeCompare( b.title ); // Sort by category } else { return a.category.localeCompare( b.category ); } // Sort by date descending } else { return dateB - dateA; } }
[ "function", "sortPosts", "(", "a", ",", "b", ")", "{", "var", "dateA", "=", "new", "Date", "(", "a", ".", "created", ")", ",", "dateB", "=", "new", "Date", "(", "b", ".", "created", ")", ";", "// See if dates match", "if", "(", "dateB", "-", "dateA", "===", "0", ")", "{", "// See if categories are the same", "if", "(", "a", ".", "category", "===", "b", ".", "category", ")", "{", "// Sort by title", "return", "a", ".", "title", ".", "localeCompare", "(", "b", ".", "title", ")", ";", "// Sort by category", "}", "else", "{", "return", "a", ".", "category", ".", "localeCompare", "(", "b", ".", "category", ")", ";", "}", "// Sort by date descending", "}", "else", "{", "return", "dateB", "-", "dateA", ";", "}", "}" ]
Sort posts. By default posts are sorted by date descending, category, title @param {Object} a @param {Object} b
[ "Sort", "posts", ".", "By", "default", "posts", "are", "sorted", "by", "date", "descending", "category", "title" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L341-L366
52,831
jneurock/gulp-viking-posts
index.js
removePostsContent
function removePostsContent( posts, options ) { var _sortPosts = options && typeof options.sortPosts === 'function' ? options.sortPosts : sortPosts, i = 0, len = 0; // Posts should be objects separated by commas but not wrapped in [] posts = JSON.parse( '[' + posts.contents.toString() + ']' ); len = posts.length; for ( i; i < len; i++ ) { delete posts[i].content; } // Sort posts by newest posts.sort( _sortPosts ); return JSON.stringify( posts ); }
javascript
function removePostsContent( posts, options ) { var _sortPosts = options && typeof options.sortPosts === 'function' ? options.sortPosts : sortPosts, i = 0, len = 0; // Posts should be objects separated by commas but not wrapped in [] posts = JSON.parse( '[' + posts.contents.toString() + ']' ); len = posts.length; for ( i; i < len; i++ ) { delete posts[i].content; } // Sort posts by newest posts.sort( _sortPosts ); return JSON.stringify( posts ); }
[ "function", "removePostsContent", "(", "posts", ",", "options", ")", "{", "var", "_sortPosts", "=", "options", "&&", "typeof", "options", ".", "sortPosts", "===", "'function'", "?", "options", ".", "sortPosts", ":", "sortPosts", ",", "i", "=", "0", ",", "len", "=", "0", ";", "// Posts should be objects separated by commas but not wrapped in []", "posts", "=", "JSON", ".", "parse", "(", "'['", "+", "posts", ".", "contents", ".", "toString", "(", ")", "+", "']'", ")", ";", "len", "=", "posts", ".", "length", ";", "for", "(", "i", ";", "i", "<", "len", ";", "i", "++", ")", "{", "delete", "posts", "[", "i", "]", ".", "content", ";", "}", "// Sort posts by newest", "posts", ".", "sort", "(", "_sortPosts", ")", ";", "return", "JSON", ".", "stringify", "(", "posts", ")", ";", "}" ]
Iterate over posts objects and delete the content property @param {string} posts @param {Object} [options] @returns {string}
[ "Iterate", "over", "posts", "objects", "and", "delete", "the", "content", "property" ]
e14b19a6fe743c9525af0448d8988589961f936a
https://github.com/jneurock/gulp-viking-posts/blob/e14b19a6fe743c9525af0448d8988589961f936a/index.js#L375-L396
52,832
geometryzen/generic-rbtree
build/module/RBTree.js
diamondLeftToVic
function diamondLeftToVic(lead) { var m = lead.p; var z = lead; var x = z.l; var y = x.r; var a = y.l; var b = y.r; x.flag = false; y.l = x; x.p = y; y.r = z; z.p = y; x.r = a; a.p = x; z.l = b; b.p = z; if (m.r === lead) { m.r = y; } else { m.l = y; } y.p = m; return y; }
javascript
function diamondLeftToVic(lead) { var m = lead.p; var z = lead; var x = z.l; var y = x.r; var a = y.l; var b = y.r; x.flag = false; y.l = x; x.p = y; y.r = z; z.p = y; x.r = a; a.p = x; z.l = b; b.p = z; if (m.r === lead) { m.r = y; } else { m.l = y; } y.p = m; return y; }
[ "function", "diamondLeftToVic", "(", "lead", ")", "{", "var", "m", "=", "lead", ".", "p", ";", "var", "z", "=", "lead", ";", "var", "x", "=", "z", ".", "l", ";", "var", "y", "=", "x", ".", "r", ";", "var", "a", "=", "y", ".", "l", ";", "var", "b", "=", "y", ".", "r", ";", "x", ".", "flag", "=", "false", ";", "y", ".", "l", "=", "x", ";", "x", ".", "p", "=", "y", ";", "y", ".", "r", "=", "z", ";", "z", ".", "p", "=", "y", ";", "x", ".", "r", "=", "a", ";", "a", ".", "p", "=", "x", ";", "z", ".", "l", "=", "b", ";", "b", ".", "p", "=", "z", ";", "if", "(", "m", ".", "r", "===", "lead", ")", "{", "m", ".", "r", "=", "y", ";", "}", "else", "{", "m", ".", "l", "=", "y", ";", "}", "y", ".", "p", "=", "m", ";", "return", "y", ";", "}" ]
z, x, y are in diamond-left formation. z is the initial leader and is black. x and y are initially red. z moves right and back. y takes the lead. children a,b of y are adopted by x and z. x becomes black. z y x => x z y a b a b
[ "z", "x", "y", "are", "in", "diamond", "-", "left", "formation", ".", "z", "is", "the", "initial", "leader", "and", "is", "black", ".", "x", "and", "y", "are", "initially", "red", "." ]
edac467bcf6bde1b8614926d846ce773ecddc7d9
https://github.com/geometryzen/generic-rbtree/blob/edac467bcf6bde1b8614926d846ce773ecddc7d9/build/module/RBTree.js#L252-L276
52,833
geometryzen/generic-rbtree
build/module/RBTree.js
rbInsertFixup
function rbInsertFixup(tree, n) { // When inserting the node (at any place other than the root), we always color it red. // This is so that we don't violate the height invariant. // However, this may violate the color invariant, which we address by recursing back up the tree. n.flag = true; if (!n.p.flag) { throw new Error("n.p must be red."); } while (n.flag) { /** * The parent of n. */ var p = n.p; if (n === tree.root) { tree.root.flag = false; return; } else if (p === tree.root) { tree.root.flag = false; return; } /** * The leader of the formation. */ var lead = p.p; // Establish the n = red, p = red, g = black condition for a transformation. if (p.flag && !lead.flag) { if (p === lead.l) { var aux = lead.r; if (aux.flag) { n = colorFlip(p, lead, aux); } else if (n === p.r) { n = diamondLeftToVic(lead); } else { n = echelonLeftToVic(lead); } } else { var aux = lead.l; if (aux.flag) { n = colorFlip(p, lead, aux); } else if (n === n.p.l) { n = diamondRightToVic(lead); } else { n = echelonRightToVic(lead); } } } else { break; } } tree.root.flag = false; }
javascript
function rbInsertFixup(tree, n) { // When inserting the node (at any place other than the root), we always color it red. // This is so that we don't violate the height invariant. // However, this may violate the color invariant, which we address by recursing back up the tree. n.flag = true; if (!n.p.flag) { throw new Error("n.p must be red."); } while (n.flag) { /** * The parent of n. */ var p = n.p; if (n === tree.root) { tree.root.flag = false; return; } else if (p === tree.root) { tree.root.flag = false; return; } /** * The leader of the formation. */ var lead = p.p; // Establish the n = red, p = red, g = black condition for a transformation. if (p.flag && !lead.flag) { if (p === lead.l) { var aux = lead.r; if (aux.flag) { n = colorFlip(p, lead, aux); } else if (n === p.r) { n = diamondLeftToVic(lead); } else { n = echelonLeftToVic(lead); } } else { var aux = lead.l; if (aux.flag) { n = colorFlip(p, lead, aux); } else if (n === n.p.l) { n = diamondRightToVic(lead); } else { n = echelonRightToVic(lead); } } } else { break; } } tree.root.flag = false; }
[ "function", "rbInsertFixup", "(", "tree", ",", "n", ")", "{", "// When inserting the node (at any place other than the root), we always color it red.", "// This is so that we don't violate the height invariant.", "// However, this may violate the color invariant, which we address by recursing back up the tree.", "n", ".", "flag", "=", "true", ";", "if", "(", "!", "n", ".", "p", ".", "flag", ")", "{", "throw", "new", "Error", "(", "\"n.p must be red.\"", ")", ";", "}", "while", "(", "n", ".", "flag", ")", "{", "/**\n * The parent of n.\n */", "var", "p", "=", "n", ".", "p", ";", "if", "(", "n", "===", "tree", ".", "root", ")", "{", "tree", ".", "root", ".", "flag", "=", "false", ";", "return", ";", "}", "else", "if", "(", "p", "===", "tree", ".", "root", ")", "{", "tree", ".", "root", ".", "flag", "=", "false", ";", "return", ";", "}", "/**\n * The leader of the formation.\n */", "var", "lead", "=", "p", ".", "p", ";", "// Establish the n = red, p = red, g = black condition for a transformation.", "if", "(", "p", ".", "flag", "&&", "!", "lead", ".", "flag", ")", "{", "if", "(", "p", "===", "lead", ".", "l", ")", "{", "var", "aux", "=", "lead", ".", "r", ";", "if", "(", "aux", ".", "flag", ")", "{", "n", "=", "colorFlip", "(", "p", ",", "lead", ",", "aux", ")", ";", "}", "else", "if", "(", "n", "===", "p", ".", "r", ")", "{", "n", "=", "diamondLeftToVic", "(", "lead", ")", ";", "}", "else", "{", "n", "=", "echelonLeftToVic", "(", "lead", ")", ";", "}", "}", "else", "{", "var", "aux", "=", "lead", ".", "l", ";", "if", "(", "aux", ".", "flag", ")", "{", "n", "=", "colorFlip", "(", "p", ",", "lead", ",", "aux", ")", ";", "}", "else", "if", "(", "n", "===", "n", ".", "p", ".", "l", ")", "{", "n", "=", "diamondRightToVic", "(", "lead", ")", ";", "}", "else", "{", "n", "=", "echelonRightToVic", "(", "lead", ")", ";", "}", "}", "}", "else", "{", "break", ";", "}", "}", "tree", ".", "root", ".", "flag", "=", "false", ";", "}" ]
In this algorithm we start with the node that has been inserted and make our way up the tree. This requires carefully maintaining parent pointers.
[ "In", "this", "algorithm", "we", "start", "with", "the", "node", "that", "has", "been", "inserted", "and", "make", "our", "way", "up", "the", "tree", ".", "This", "requires", "carefully", "maintaining", "parent", "pointers", "." ]
edac467bcf6bde1b8614926d846ce773ecddc7d9
https://github.com/geometryzen/generic-rbtree/blob/edac467bcf6bde1b8614926d846ce773ecddc7d9/build/module/RBTree.js#L425-L482
52,834
geometryzen/generic-rbtree
build/module/RBTree.js
glb
function glb(tree, node, key, comp, low) { if (node === tree.z) { return low; } else if (comp(key, node.key) >= 0) { // The node key is a valid lower bound, but may not be the greatest. // Take the right link in search of larger keys. return maxNode(node, glb(tree, node.r, key, comp, low), comp); } else { // Take the left link in search of smaller keys. return glb(tree, node.l, key, comp, low); } }
javascript
function glb(tree, node, key, comp, low) { if (node === tree.z) { return low; } else if (comp(key, node.key) >= 0) { // The node key is a valid lower bound, but may not be the greatest. // Take the right link in search of larger keys. return maxNode(node, glb(tree, node.r, key, comp, low), comp); } else { // Take the left link in search of smaller keys. return glb(tree, node.l, key, comp, low); } }
[ "function", "glb", "(", "tree", ",", "node", ",", "key", ",", "comp", ",", "low", ")", "{", "if", "(", "node", "===", "tree", ".", "z", ")", "{", "return", "low", ";", "}", "else", "if", "(", "comp", "(", "key", ",", "node", ".", "key", ")", ">=", "0", ")", "{", "// The node key is a valid lower bound, but may not be the greatest.", "// Take the right link in search of larger keys.", "return", "maxNode", "(", "node", ",", "glb", "(", "tree", ",", "node", ".", "r", ",", "key", ",", "comp", ",", "low", ")", ",", "comp", ")", ";", "}", "else", "{", "// Take the left link in search of smaller keys.", "return", "glb", "(", "tree", ",", "node", ".", "l", ",", "key", ",", "comp", ",", "low", ")", ";", "}", "}" ]
Recursive implementation to compute the Greatest Lower Bound. The largest key such that glb <= key.
[ "Recursive", "implementation", "to", "compute", "the", "Greatest", "Lower", "Bound", ".", "The", "largest", "key", "such", "that", "glb", "<", "=", "key", "." ]
edac467bcf6bde1b8614926d846ce773ecddc7d9
https://github.com/geometryzen/generic-rbtree/blob/edac467bcf6bde1b8614926d846ce773ecddc7d9/build/module/RBTree.js#L487-L500
52,835
geometryzen/generic-rbtree
build/module/RBTree.js
lub
function lub(tree, node, key, comp, high) { if (node === tree.z) { return high; } else if (comp(key, node.key) <= 0) { // The node key is a valid upper bound, but may not be the least. return minNode(node, lub(tree, node.l, key, comp, high), comp); } else { // Take the right link in search of bigger keys. return lub(tree, node.r, key, comp, high); } }
javascript
function lub(tree, node, key, comp, high) { if (node === tree.z) { return high; } else if (comp(key, node.key) <= 0) { // The node key is a valid upper bound, but may not be the least. return minNode(node, lub(tree, node.l, key, comp, high), comp); } else { // Take the right link in search of bigger keys. return lub(tree, node.r, key, comp, high); } }
[ "function", "lub", "(", "tree", ",", "node", ",", "key", ",", "comp", ",", "high", ")", "{", "if", "(", "node", "===", "tree", ".", "z", ")", "{", "return", "high", ";", "}", "else", "if", "(", "comp", "(", "key", ",", "node", ".", "key", ")", "<=", "0", ")", "{", "// The node key is a valid upper bound, but may not be the least.", "return", "minNode", "(", "node", ",", "lub", "(", "tree", ",", "node", ".", "l", ",", "key", ",", "comp", ",", "high", ")", ",", "comp", ")", ";", "}", "else", "{", "// Take the right link in search of bigger keys.", "return", "lub", "(", "tree", ",", "node", ".", "r", ",", "key", ",", "comp", ",", "high", ")", ";", "}", "}" ]
Recursive implementation to compute the Least Upper Bound. The smallest key such that key <= lub.
[ "Recursive", "implementation", "to", "compute", "the", "Least", "Upper", "Bound", ".", "The", "smallest", "key", "such", "that", "key", "<", "=", "lub", "." ]
edac467bcf6bde1b8614926d846ce773ecddc7d9
https://github.com/geometryzen/generic-rbtree/blob/edac467bcf6bde1b8614926d846ce773ecddc7d9/build/module/RBTree.js#L505-L517
52,836
byu-oit/sans-server-middleware
bin/middleware.js
Middleware
function Middleware(name) { if (!(this instanceof Middleware)) return new Middleware(name); this.name = name || ''; Object.defineProperty(this, '_', { enumerable: false, configurable: false, value: { length: 0, ordered: null, weights: new Map() } }); /** * Returns the length of the middleware. * @type {number} */ Object.defineProperty(this, 'length', { get: () => this._.length }); }
javascript
function Middleware(name) { if (!(this instanceof Middleware)) return new Middleware(name); this.name = name || ''; Object.defineProperty(this, '_', { enumerable: false, configurable: false, value: { length: 0, ordered: null, weights: new Map() } }); /** * Returns the length of the middleware. * @type {number} */ Object.defineProperty(this, 'length', { get: () => this._.length }); }
[ "function", "Middleware", "(", "name", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Middleware", ")", ")", "return", "new", "Middleware", "(", "name", ")", ";", "this", ".", "name", "=", "name", "||", "''", ";", "Object", ".", "defineProperty", "(", "this", ",", "'_'", ",", "{", "enumerable", ":", "false", ",", "configurable", ":", "false", ",", "value", ":", "{", "length", ":", "0", ",", "ordered", ":", "null", ",", "weights", ":", "new", "Map", "(", ")", "}", "}", ")", ";", "/**\n * Returns the length of the middleware.\n * @type {number}\n */", "Object", ".", "defineProperty", "(", "this", ",", "'length'", ",", "{", "get", ":", "(", ")", "=>", "this", ".", "_", ".", "length", "}", ")", ";", "}" ]
Create a new middleware instance. @params {string} [name=''] @returns {Middleware} @constructor
[ "Create", "a", "new", "middleware", "instance", "." ]
c42430aa558b4edee205bd9180d24d74022607ae
https://github.com/byu-oit/sans-server-middleware/blob/c42430aa558b4edee205bd9180d24d74022607ae/bin/middleware.js#L29-L50
52,837
byu-oit/sans-server-middleware
bin/middleware.js
function(err, req, res, next) { function done(error) { log(req, util.format('middleware-end %s', name)); next(error); } if (err && !errHandler) { log(req, util.format('skipped %s Hook is not for error handling', name)); next(err); } else if (!err && errHandler) { log(req, util.format('skipped %s Hook is for error handling', name)); next(); } else { try { log(req, util.format('middleware-start %s', name)); errHandler ? hook(err, req, res, done) : hook(req, res, done); } catch (err) { done(err); } } }
javascript
function(err, req, res, next) { function done(error) { log(req, util.format('middleware-end %s', name)); next(error); } if (err && !errHandler) { log(req, util.format('skipped %s Hook is not for error handling', name)); next(err); } else if (!err && errHandler) { log(req, util.format('skipped %s Hook is for error handling', name)); next(); } else { try { log(req, util.format('middleware-start %s', name)); errHandler ? hook(err, req, res, done) : hook(req, res, done); } catch (err) { done(err); } } }
[ "function", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "function", "done", "(", "error", ")", "{", "log", "(", "req", ",", "util", ".", "format", "(", "'middleware-end %s'", ",", "name", ")", ")", ";", "next", "(", "error", ")", ";", "}", "if", "(", "err", "&&", "!", "errHandler", ")", "{", "log", "(", "req", ",", "util", ".", "format", "(", "'skipped %s Hook is not for error handling'", ",", "name", ")", ")", ";", "next", "(", "err", ")", ";", "}", "else", "if", "(", "!", "err", "&&", "errHandler", ")", "{", "log", "(", "req", ",", "util", ".", "format", "(", "'skipped %s Hook is for error handling'", ",", "name", ")", ")", ";", "next", "(", ")", ";", "}", "else", "{", "try", "{", "log", "(", "req", ",", "util", ".", "format", "(", "'middleware-start %s'", ",", "name", ")", ")", ";", "errHandler", "?", "hook", "(", "err", ",", "req", ",", "res", ",", "done", ")", ":", "hook", "(", "req", ",", "res", ",", "done", ")", ";", "}", "catch", "(", "err", ")", "{", "done", "(", "err", ")", ";", "}", "}", "}" ]
create a wrapper around the middleware
[ "create", "a", "wrapper", "around", "the", "middleware" ]
c42430aa558b4edee205bd9180d24d74022607ae
https://github.com/byu-oit/sans-server-middleware/blob/c42430aa558b4edee205bd9180d24d74022607ae/bin/middleware.js#L79-L103
52,838
nfroidure/common-services
src/delay.js
create
function create(delay) { let timeoutId; let _reject; const promise = new Promise((resolve, reject) => { _reject = reject; timeoutId = setTimeout(() => { resolve(); pendingPromises.delete(promise); }, delay); }); pendingPromises.set(promise, { timeoutId, reject: _reject, }); log('debug', 'Created a delay:', delay); return promise; }
javascript
function create(delay) { let timeoutId; let _reject; const promise = new Promise((resolve, reject) => { _reject = reject; timeoutId = setTimeout(() => { resolve(); pendingPromises.delete(promise); }, delay); }); pendingPromises.set(promise, { timeoutId, reject: _reject, }); log('debug', 'Created a delay:', delay); return promise; }
[ "function", "create", "(", "delay", ")", "{", "let", "timeoutId", ";", "let", "_reject", ";", "const", "promise", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "_reject", "=", "reject", ";", "timeoutId", "=", "setTimeout", "(", "(", ")", "=>", "{", "resolve", "(", ")", ";", "pendingPromises", ".", "delete", "(", "promise", ")", ";", "}", ",", "delay", ")", ";", "}", ")", ";", "pendingPromises", ".", "set", "(", "promise", ",", "{", "timeoutId", ",", "reject", ":", "_reject", ",", "}", ")", ";", "log", "(", "'debug'", ",", "'Created a delay:'", ",", "delay", ")", ";", "return", "promise", ";", "}" ]
Create a new delay @param {Number} delay The delay in ms @return {Promise} A promise to be resolved after that delay or rejected if it is cancelled. @example await delay.create(1000); console.log('1000 ms elapsed!');
[ "Create", "a", "new", "delay" ]
09df32597fe798777abec0ef1f3a994e91046085
https://github.com/nfroidure/common-services/blob/09df32597fe798777abec0ef1f3a994e91046085/src/delay.js#L52-L69
52,839
nfroidure/common-services
src/delay.js
clear
async function clear(promise) { if (!pendingPromises.has(promise)) { return Promise.reject(new YError('E_BAD_DELAY')); } const { timeoutId, reject } = pendingPromises.get(promise); clearTimeout(timeoutId); reject(new YError('E_DELAY_CLEARED')); pendingPromises.delete(promise); log('debug', 'Cleared a delay'); }
javascript
async function clear(promise) { if (!pendingPromises.has(promise)) { return Promise.reject(new YError('E_BAD_DELAY')); } const { timeoutId, reject } = pendingPromises.get(promise); clearTimeout(timeoutId); reject(new YError('E_DELAY_CLEARED')); pendingPromises.delete(promise); log('debug', 'Cleared a delay'); }
[ "async", "function", "clear", "(", "promise", ")", "{", "if", "(", "!", "pendingPromises", ".", "has", "(", "promise", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "YError", "(", "'E_BAD_DELAY'", ")", ")", ";", "}", "const", "{", "timeoutId", ",", "reject", "}", "=", "pendingPromises", ".", "get", "(", "promise", ")", ";", "clearTimeout", "(", "timeoutId", ")", ";", "reject", "(", "new", "YError", "(", "'E_DELAY_CLEARED'", ")", ")", ";", "pendingPromises", ".", "delete", "(", "promise", ")", ";", "log", "(", "'debug'", ",", "'Cleared a delay'", ")", ";", "}" ]
Cancel an earlier created delay @param {Promise} promise The promise of the delay to cancel @return {Promise} A promise resolved when cancellation is done. @example try { const delayPromise = delay.create(1000); await Promise.all(delayPromise, delay.clear(delayPromise)); console.log('1000 ms elapsed!'); } catch (err) { if(err.code != 'E_DELAY_CLEARED') { trow err; } console.log('Cancelled!')); } // Prints: Cancelled!
[ "Cancel", "an", "earlier", "created", "delay" ]
09df32597fe798777abec0ef1f3a994e91046085
https://github.com/nfroidure/common-services/blob/09df32597fe798777abec0ef1f3a994e91046085/src/delay.js#L90-L100
52,840
bholloway/browserify-anonymous-labeler
lib/get-field.js
getField
function getField(field) { return function map(element) { if (element) { if (Array.isArray(element)) { return element.map(map).join(''); } else if (typeof element === 'string') { return element; } else if (typeof element === 'object') { return element[field]; } } return ''; }; }
javascript
function getField(field) { return function map(element) { if (element) { if (Array.isArray(element)) { return element.map(map).join(''); } else if (typeof element === 'string') { return element; } else if (typeof element === 'object') { return element[field]; } } return ''; }; }
[ "function", "getField", "(", "field", ")", "{", "return", "function", "map", "(", "element", ")", "{", "if", "(", "element", ")", "{", "if", "(", "Array", ".", "isArray", "(", "element", ")", ")", "{", "return", "element", ".", "map", "(", "map", ")", ".", "join", "(", "''", ")", ";", "}", "else", "if", "(", "typeof", "element", "===", "'string'", ")", "{", "return", "element", ";", "}", "else", "if", "(", "typeof", "element", "===", "'object'", ")", "{", "return", "element", "[", "field", "]", ";", "}", "}", "return", "''", ";", "}", ";", "}" ]
Get the string representation of the element from the given field where present, else the value itself. @param {string} field The field of the element to consider @returns {function} A method that performs the action on a given element
[ "Get", "the", "string", "representation", "of", "the", "element", "from", "the", "given", "field", "where", "present", "else", "the", "value", "itself", "." ]
651b124eefe8d1a567b2a03a0b8a3dfea87c2703
https://github.com/bholloway/browserify-anonymous-labeler/blob/651b124eefe8d1a567b2a03a0b8a3dfea87c2703/lib/get-field.js#L8-L23
52,841
redisjs/jsr-server
lib/command/server/command.js
getList
function getList() { if(!COMMAND_LIST) { COMMAND_LIST = []; for(var z in this.execs) { COMMAND_LIST.push(this.execs[z].definition.getDefinition()); } } return COMMAND_LIST; }
javascript
function getList() { if(!COMMAND_LIST) { COMMAND_LIST = []; for(var z in this.execs) { COMMAND_LIST.push(this.execs[z].definition.getDefinition()); } } return COMMAND_LIST; }
[ "function", "getList", "(", ")", "{", "if", "(", "!", "COMMAND_LIST", ")", "{", "COMMAND_LIST", "=", "[", "]", ";", "for", "(", "var", "z", "in", "this", ".", "execs", ")", "{", "COMMAND_LIST", ".", "push", "(", "this", ".", "execs", "[", "z", "]", ".", "definition", ".", "getDefinition", "(", ")", ")", ";", "}", "}", "return", "COMMAND_LIST", ";", "}" ]
Helper to lazily build the command list.
[ "Helper", "to", "lazily", "build", "the", "command", "list", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/server/command.js#L18-L26
52,842
redisjs/jsr-server
lib/command/server/command.js
info
function info(req, res) { var list = [] , i , exec; for(i = 0;i < req.args.length;i++) { exec = this.execs[req.args[i]]; list.push(exec ? exec.definition.getDefinition() : null); } res.send(null, list); }
javascript
function info(req, res) { var list = [] , i , exec; for(i = 0;i < req.args.length;i++) { exec = this.execs[req.args[i]]; list.push(exec ? exec.definition.getDefinition() : null); } res.send(null, list); }
[ "function", "info", "(", "req", ",", "res", ")", "{", "var", "list", "=", "[", "]", ",", "i", ",", "exec", ";", "for", "(", "i", "=", "0", ";", "i", "<", "req", ".", "args", ".", "length", ";", "i", "++", ")", "{", "exec", "=", "this", ".", "execs", "[", "req", ".", "args", "[", "i", "]", "]", ";", "list", ".", "push", "(", "exec", "?", "exec", ".", "definition", ".", "getDefinition", "(", ")", ":", "null", ")", ";", "}", "res", ".", "send", "(", "null", ",", "list", ")", ";", "}" ]
Respond to the INFO subcommand.
[ "Respond", "to", "the", "INFO", "subcommand", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/server/command.js#L31-L40
52,843
redisjs/jsr-server
lib/command/server/command.js
getkeys
function getkeys(req, res) { var keys = [] // target command , tcmd = req.args[0] , def = Constants.MAP[tcmd]; if(def) { keys = def.getKeys(req.args.slice(1)); } res.send(null, keys); }
javascript
function getkeys(req, res) { var keys = [] // target command , tcmd = req.args[0] , def = Constants.MAP[tcmd]; if(def) { keys = def.getKeys(req.args.slice(1)); } res.send(null, keys); }
[ "function", "getkeys", "(", "req", ",", "res", ")", "{", "var", "keys", "=", "[", "]", "// target command", ",", "tcmd", "=", "req", ".", "args", "[", "0", "]", ",", "def", "=", "Constants", ".", "MAP", "[", "tcmd", "]", ";", "if", "(", "def", ")", "{", "keys", "=", "def", ".", "getKeys", "(", "req", ".", "args", ".", "slice", "(", "1", ")", ")", ";", "}", "res", ".", "send", "(", "null", ",", "keys", ")", ";", "}" ]
Respond to the GETKEYS subcommand. Current version [email protected] does not actually appear to implement this: `command getkeys get key` results in an error. Therefore this implementation is a best guess as to the intended behaviour. This command cannot fail with an error so we just return an empty list for target commands that do not accept keys. Examples: command getkeys set key val // ['key'] command getkeys mset k1 v1 k2 v2 // ['k1', 'k2'] command getkeys hset hash field val // ['hash']
[ "Respond", "to", "the", "GETKEYS", "subcommand", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/server/command.js#L60-L69
52,844
redisjs/jsr-server
lib/command/server/command.js
count
function count(req, res) { var list = getList.call(this); return res.send(null, list.length); }
javascript
function count(req, res) { var list = getList.call(this); return res.send(null, list.length); }
[ "function", "count", "(", "req", ",", "res", ")", "{", "var", "list", "=", "getList", ".", "call", "(", "this", ")", ";", "return", "res", ".", "send", "(", "null", ",", "list", ".", "length", ")", ";", "}" ]
Respond to the COUNT subcommand.
[ "Respond", "to", "the", "COUNT", "subcommand", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/server/command.js#L74-L77
52,845
redisjs/jsr-server
lib/command/server/command.js
execute
function execute(req, res) { if(req.info.command.sub) { this.delegate(req, res); // no subcommand return command list }else{ var list = getList.call(this); return res.send(null, list); } }
javascript
function execute(req, res) { if(req.info.command.sub) { this.delegate(req, res); // no subcommand return command list }else{ var list = getList.call(this); return res.send(null, list); } }
[ "function", "execute", "(", "req", ",", "res", ")", "{", "if", "(", "req", ".", "info", ".", "command", ".", "sub", ")", "{", "this", ".", "delegate", "(", "req", ",", "res", ")", ";", "// no subcommand return command list", "}", "else", "{", "var", "list", "=", "getList", ".", "call", "(", "this", ")", ";", "return", "res", ".", "send", "(", "null", ",", "list", ")", ";", "}", "}" ]
Respond to the COMMAND command.
[ "Respond", "to", "the", "COMMAND", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/server/command.js#L82-L90
52,846
logashoff/grunt-uglify-amd
tasks/uglifyAMD.js
buildPaths
function buildPaths(file, arr) { if (!grunt.file.exists(file)) { grunt.log.warn('File "' + file + '" not found'); return null; } arr.unshift(file); var namespaces = pathTable[file]; if (namespaces && namespaces.length) { for (var i = namespaces.length, ns; i-- > 0;) { ns = namespaces[i]; if (!nsTable[ns]) { throw new Error( 'Required namespace "' + ns + '" not found in ' + file); } buildPaths(nsTable[ns], arr); } } return arr; }
javascript
function buildPaths(file, arr) { if (!grunt.file.exists(file)) { grunt.log.warn('File "' + file + '" not found'); return null; } arr.unshift(file); var namespaces = pathTable[file]; if (namespaces && namespaces.length) { for (var i = namespaces.length, ns; i-- > 0;) { ns = namespaces[i]; if (!nsTable[ns]) { throw new Error( 'Required namespace "' + ns + '" not found in ' + file); } buildPaths(nsTable[ns], arr); } } return arr; }
[ "function", "buildPaths", "(", "file", ",", "arr", ")", "{", "if", "(", "!", "grunt", ".", "file", ".", "exists", "(", "file", ")", ")", "{", "grunt", ".", "log", ".", "warn", "(", "'File \"'", "+", "file", "+", "'\" not found'", ")", ";", "return", "null", ";", "}", "arr", ".", "unshift", "(", "file", ")", ";", "var", "namespaces", "=", "pathTable", "[", "file", "]", ";", "if", "(", "namespaces", "&&", "namespaces", ".", "length", ")", "{", "for", "(", "var", "i", "=", "namespaces", ".", "length", ",", "ns", ";", "i", "--", ">", "0", ";", ")", "{", "ns", "=", "namespaces", "[", "i", "]", ";", "if", "(", "!", "nsTable", "[", "ns", "]", ")", "{", "throw", "new", "Error", "(", "'Required namespace \"'", "+", "ns", "+", "'\" not found in '", "+", "file", ")", ";", "}", "buildPaths", "(", "nsTable", "[", "ns", "]", ",", "arr", ")", ";", "}", "}", "return", "arr", ";", "}" ]
Recursively builds file paths array from specified file and assigns them to array parameter. Uses pathTable to look up namespace dependencies. @param {string} file File path. @param {Array} arr Array to store file paths. @returns {Array|null} Array of file paths.
[ "Recursively", "builds", "file", "paths", "array", "from", "specified", "file", "and", "assigns", "them", "to", "array", "parameter", ".", "Uses", "pathTable", "to", "look", "up", "namespace", "dependencies", "." ]
0bc68c42f7a555b6ac71b0e02ea5cda4860d0361
https://github.com/logashoff/grunt-uglify-amd/blob/0bc68c42f7a555b6ac71b0e02ea5cda4860d0361/tasks/uglifyAMD.js#L46-L64
52,847
vlad-zhukov/redux-status
src/promiseState.js
create
function create({ pending = false, // eslint-disable-line no-shadow refreshing = false, // eslint-disable-line no-shadow fulfilled = false, // eslint-disable-line no-shadow rejected = false, // eslint-disable-line no-shadow value = null, reason = null, }) { return { pending, refreshing, fulfilled, rejected, value, reason, }; }
javascript
function create({ pending = false, // eslint-disable-line no-shadow refreshing = false, // eslint-disable-line no-shadow fulfilled = false, // eslint-disable-line no-shadow rejected = false, // eslint-disable-line no-shadow value = null, reason = null, }) { return { pending, refreshing, fulfilled, rejected, value, reason, }; }
[ "function", "create", "(", "{", "pending", "=", "false", ",", "// eslint-disable-line no-shadow", "refreshing", "=", "false", ",", "// eslint-disable-line no-shadow", "fulfilled", "=", "false", ",", "// eslint-disable-line no-shadow", "rejected", "=", "false", ",", "// eslint-disable-line no-shadow", "value", "=", "null", ",", "reason", "=", "null", ",", "}", ")", "{", "return", "{", "pending", ",", "refreshing", ",", "fulfilled", ",", "rejected", ",", "value", ",", "reason", ",", "}", ";", "}" ]
Constructor for creating a new promiseState. @param [pending] {Boolean} @param [refreshing] {Boolean} @param [fulfilled] {Boolean} @param [rejected] {Boolean} @param [value] {*} @param [reason] {*} @returns {Object}
[ "Constructor", "for", "creating", "a", "new", "promiseState", "." ]
1f2108949b71f25d1c592501ed089a52a9fc61ec
https://github.com/vlad-zhukov/redux-status/blob/1f2108949b71f25d1c592501ed089a52a9fc61ec/src/promiseState.js#L13-L29
52,848
MostlyJS/mostly-feathers-mongoose
src/helpers/set-field.js
cloneById
function cloneById (v, k) { if (Array.isArray(v)) { let match = find(v, it => String(it[options.idField]) === String(k)); return match? cloneDeep(match) : (options.keepOrig? k : null); } else { return String(v[options.idField]) === String(k)? cloneDeep(v) : (options.keepOrig? k : null); } }
javascript
function cloneById (v, k) { if (Array.isArray(v)) { let match = find(v, it => String(it[options.idField]) === String(k)); return match? cloneDeep(match) : (options.keepOrig? k : null); } else { return String(v[options.idField]) === String(k)? cloneDeep(v) : (options.keepOrig? k : null); } }
[ "function", "cloneById", "(", "v", ",", "k", ")", "{", "if", "(", "Array", ".", "isArray", "(", "v", ")", ")", "{", "let", "match", "=", "find", "(", "v", ",", "it", "=>", "String", "(", "it", "[", "options", ".", "idField", "]", ")", "===", "String", "(", "k", ")", ")", ";", "return", "match", "?", "cloneDeep", "(", "match", ")", ":", "(", "options", ".", "keepOrig", "?", "k", ":", "null", ")", ";", "}", "else", "{", "return", "String", "(", "v", "[", "options", ".", "idField", "]", ")", "===", "String", "(", "k", ")", "?", "cloneDeep", "(", "v", ")", ":", "(", "options", ".", "keepOrig", "?", "k", ":", "null", ")", ";", "}", "}" ]
avoid duplicate setField
[ "avoid", "duplicate", "setField" ]
d20e150e054c784cc7db7c2487399e4f4eb730de
https://github.com/MostlyJS/mostly-feathers-mongoose/blob/d20e150e054c784cc7db7c2487399e4f4eb730de/src/helpers/set-field.js#L43-L50
52,849
ENOW-IJI/ENOW-console
start.js
function(req, topic, messages){ payloads[0]['topic'] = topic payloads[0]['messages']= JSON.stringify(messages); console.log(payloads[0]['messages']); setTimeout(function () { producer.send(payloads, function (err, data) { if(err){ console.log(err); } }); producer.on('error', function (err) { console.log(err); }); }, 1000); }
javascript
function(req, topic, messages){ payloads[0]['topic'] = topic payloads[0]['messages']= JSON.stringify(messages); console.log(payloads[0]['messages']); setTimeout(function () { producer.send(payloads, function (err, data) { if(err){ console.log(err); } }); producer.on('error', function (err) { console.log(err); }); }, 1000); }
[ "function", "(", "req", ",", "topic", ",", "messages", ")", "{", "payloads", "[", "0", "]", "[", "'topic'", "]", "=", "topic", "payloads", "[", "0", "]", "[", "'messages'", "]", "=", "JSON", ".", "stringify", "(", "messages", ")", ";", "console", ".", "log", "(", "payloads", "[", "0", "]", "[", "'messages'", "]", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "producer", ".", "send", "(", "payloads", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", "}", ")", ";", "producer", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", ")", ";", "}", ",", "1000", ")", ";", "}" ]
publish message to kafka.
[ "publish", "message", "to", "kafka", "." ]
f241ed4e645a7da0cd1a6ca86e896a5b73be53e5
https://github.com/ENOW-IJI/ENOW-console/blob/f241ed4e645a7da0cd1a6ca86e896a5b73be53e5/start.js#L71-L85
52,850
ENOW-IJI/ENOW-console
start.js
function(callback){ if(source['brokerId']!='null'){ db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){ mqttHost = result[0]['ipAddress']; mqttPort = result[0]['port']; console.log(result); }); }else{ mqttHost = mqttPort = null; } }
javascript
function(callback){ if(source['brokerId']!='null'){ db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){ mqttHost = result[0]['ipAddress']; mqttPort = result[0]['port']; console.log(result); }); }else{ mqttHost = mqttPort = null; } }
[ "function", "(", "callback", ")", "{", "if", "(", "source", "[", "'brokerId'", "]", "!=", "'null'", ")", "{", "db", ".", "db", "(", "dbName", ")", ".", "collection", "(", "collectionName", ")", ".", "find", "(", "{", "brokerId", ":", "source", "[", "'brokerId'", "]", "}", ")", ".", "toArray", "(", "function", "(", "err", ",", "result", ")", "{", "mqttHost", "=", "result", "[", "0", "]", "[", "'ipAddress'", "]", ";", "mqttPort", "=", "result", "[", "0", "]", "[", "'port'", "]", ";", "console", ".", "log", "(", "result", ")", ";", "}", ")", ";", "}", "else", "{", "mqttHost", "=", "mqttPort", "=", "null", ";", "}", "}" ]
find broker for get mqtt url.
[ "find", "broker", "for", "get", "mqtt", "url", "." ]
f241ed4e645a7da0cd1a6ca86e896a5b73be53e5
https://github.com/ENOW-IJI/ENOW-console/blob/f241ed4e645a7da0cd1a6ca86e896a5b73be53e5/start.js#L353-L363
52,851
ENOW-IJI/ENOW-console
start.js
function(callback){ var o_id = BSON.ObjectID.createFromHexString(source['_id']); db.db(dbName).collection(collectionName).find({_id:o_id}).toArray(function(err,result){ response.send(result); o_id = null; }); }
javascript
function(callback){ var o_id = BSON.ObjectID.createFromHexString(source['_id']); db.db(dbName).collection(collectionName).find({_id:o_id}).toArray(function(err,result){ response.send(result); o_id = null; }); }
[ "function", "(", "callback", ")", "{", "var", "o_id", "=", "BSON", ".", "ObjectID", ".", "createFromHexString", "(", "source", "[", "'_id'", "]", ")", ";", "db", ".", "db", "(", "dbName", ")", ".", "collection", "(", "collectionName", ")", ".", "find", "(", "{", "_id", ":", "o_id", "}", ")", ".", "toArray", "(", "function", "(", "err", ",", "result", ")", "{", "response", ".", "send", "(", "result", ")", ";", "o_id", "=", "null", ";", "}", ")", ";", "}" ]
find roadmap.
[ "find", "roadmap", "." ]
f241ed4e645a7da0cd1a6ca86e896a5b73be53e5
https://github.com/ENOW-IJI/ENOW-console/blob/f241ed4e645a7da0cd1a6ca86e896a5b73be53e5/start.js#L377-L383
52,852
ENOW-IJI/ENOW-console
start.js
function(callback){ var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){ if(result.length!=0){ roadmapNum = roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1; } else{ roadmapNum = roadMapIdTemp = 1; } db.db(dbName).collection(collectionName).insertOne({ "roadMapId" : roadMapIdTemp.toString(), "clientId" : source['clientId'], "orderNode" : source['orderNode'], "initNode" : source['initNode'], "lastNode" : source['lastNode'], "incomingNode" : source['incomingNode'], "outingNode" : source['outingNode'], "isInput" : source['isInput'], "isOutput" : source['isOutput'], "nodeIds" : source['nodeIds'] },function(err, result){ response.send(roadmapNum.toString()); }); }); }
javascript
function(callback){ var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){ if(result.length!=0){ roadmapNum = roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1; } else{ roadmapNum = roadMapIdTemp = 1; } db.db(dbName).collection(collectionName).insertOne({ "roadMapId" : roadMapIdTemp.toString(), "clientId" : source['clientId'], "orderNode" : source['orderNode'], "initNode" : source['initNode'], "lastNode" : source['lastNode'], "incomingNode" : source['incomingNode'], "outingNode" : source['outingNode'], "isInput" : source['isInput'], "isOutput" : source['isOutput'], "nodeIds" : source['nodeIds'] },function(err, result){ response.send(roadmapNum.toString()); }); }); }
[ "function", "(", "callback", ")", "{", "var", "cursor", "=", "db", ".", "db", "(", "dbName", ")", ".", "collection", "(", "collectionName", ")", ".", "find", "(", "{", "}", ")", ".", "toArray", "(", "function", "(", "err", ",", "result", ")", "{", "if", "(", "result", ".", "length", "!=", "0", ")", "{", "roadmapNum", "=", "roadMapIdTemp", "=", "parseInt", "(", "result", "[", "result", ".", "length", "-", "1", "]", "[", "'roadMapId'", "]", ")", "+", "1", ";", "}", "else", "{", "roadmapNum", "=", "roadMapIdTemp", "=", "1", ";", "}", "db", ".", "db", "(", "dbName", ")", ".", "collection", "(", "collectionName", ")", ".", "insertOne", "(", "{", "\"roadMapId\"", ":", "roadMapIdTemp", ".", "toString", "(", ")", ",", "\"clientId\"", ":", "source", "[", "'clientId'", "]", ",", "\"orderNode\"", ":", "source", "[", "'orderNode'", "]", ",", "\"initNode\"", ":", "source", "[", "'initNode'", "]", ",", "\"lastNode\"", ":", "source", "[", "'lastNode'", "]", ",", "\"incomingNode\"", ":", "source", "[", "'incomingNode'", "]", ",", "\"outingNode\"", ":", "source", "[", "'outingNode'", "]", ",", "\"isInput\"", ":", "source", "[", "'isInput'", "]", ",", "\"isOutput\"", ":", "source", "[", "'isOutput'", "]", ",", "\"nodeIds\"", ":", "source", "[", "'nodeIds'", "]", "}", ",", "function", "(", "err", ",", "result", ")", "{", "response", ".", "send", "(", "roadmapNum", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
run roadmap of save it to mongodb.
[ "run", "roadmap", "of", "save", "it", "to", "mongodb", "." ]
f241ed4e645a7da0cd1a6ca86e896a5b73be53e5
https://github.com/ENOW-IJI/ENOW-console/blob/f241ed4e645a7da0cd1a6ca86e896a5b73be53e5/start.js#L397-L421
52,853
redisjs/jsr-store
lib/type/list.js
lset
function lset(index, value) { if(index < 0) index = this._data.length + index; // command should validate the index if(index < 0 || index >= this._data.length) return null; this._data[index] = value; }
javascript
function lset(index, value) { if(index < 0) index = this._data.length + index; // command should validate the index if(index < 0 || index >= this._data.length) return null; this._data[index] = value; }
[ "function", "lset", "(", "index", ",", "value", ")", "{", "if", "(", "index", "<", "0", ")", "index", "=", "this", ".", "_data", ".", "length", "+", "index", ";", "// command should validate the index", "if", "(", "index", "<", "0", "||", "index", ">=", "this", ".", "_data", ".", "length", ")", "return", "null", ";", "this", ".", "_data", "[", "index", "]", "=", "value", ";", "}" ]
Sets the list element at index to value.
[ "Sets", "the", "list", "element", "at", "index", "to", "value", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/list.js#L17-L22
52,854
redisjs/jsr-store
lib/type/list.js
linsert
function linsert(beforeAfter, pivot, value) { //console.dir(pivot); //console.dir(this._data); var ind = this.indexOf(pivot); if(ind === -1) return ind; // note beforeAfter can be a buffer ind = (('' + beforeAfter) === BEFORE) ? ind : ind + 1; this._data.splice(ind, 0, value); return this._data.length; }
javascript
function linsert(beforeAfter, pivot, value) { //console.dir(pivot); //console.dir(this._data); var ind = this.indexOf(pivot); if(ind === -1) return ind; // note beforeAfter can be a buffer ind = (('' + beforeAfter) === BEFORE) ? ind : ind + 1; this._data.splice(ind, 0, value); return this._data.length; }
[ "function", "linsert", "(", "beforeAfter", ",", "pivot", ",", "value", ")", "{", "//console.dir(pivot);", "//console.dir(this._data);", "var", "ind", "=", "this", ".", "indexOf", "(", "pivot", ")", ";", "if", "(", "ind", "===", "-", "1", ")", "return", "ind", ";", "// note beforeAfter can be a buffer", "ind", "=", "(", "(", "''", "+", "beforeAfter", ")", "===", "BEFORE", ")", "?", "ind", ":", "ind", "+", "1", ";", "this", ".", "_data", ".", "splice", "(", "ind", ",", "0", ",", "value", ")", ";", "return", "this", ".", "_data", ".", "length", ";", "}" ]
Inserts value in the list either before or after the reference value pivot.
[ "Inserts", "value", "in", "the", "list", "either", "before", "or", "after", "the", "reference", "value", "pivot", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/list.js#L28-L37
52,855
redisjs/jsr-store
lib/type/list.js
lindex
function lindex(index) { if(index < 0) index = this._data.length + index; return this._data[index] || null; }
javascript
function lindex(index) { if(index < 0) index = this._data.length + index; return this._data[index] || null; }
[ "function", "lindex", "(", "index", ")", "{", "if", "(", "index", "<", "0", ")", "index", "=", "this", ".", "_data", ".", "length", "+", "index", ";", "return", "this", ".", "_data", "[", "index", "]", "||", "null", ";", "}" ]
Returns the element at index `index` in the list.
[ "Returns", "the", "element", "at", "index", "index", "in", "the", "list", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/list.js#L42-L45
52,856
redisjs/jsr-store
lib/type/list.js
lrem
function lrem(count, value) { var ind, deleted = 0; if(count === 0) { while((ind = this.indexOf(value)) !== -1) { this._data.splice(ind, 1); deleted++; } }else if(count > 0) { while((ind = this.indexOf(value)) !== -1 && (deleted < count)) { this._data.splice(ind, 1); deleted++; } }else{ count = Math.abs(count); while((ind = this.lastIndexOf(value)) !== -1 && (deleted < count)) { this._data.splice(ind, 1); deleted++; } } return deleted; }
javascript
function lrem(count, value) { var ind, deleted = 0; if(count === 0) { while((ind = this.indexOf(value)) !== -1) { this._data.splice(ind, 1); deleted++; } }else if(count > 0) { while((ind = this.indexOf(value)) !== -1 && (deleted < count)) { this._data.splice(ind, 1); deleted++; } }else{ count = Math.abs(count); while((ind = this.lastIndexOf(value)) !== -1 && (deleted < count)) { this._data.splice(ind, 1); deleted++; } } return deleted; }
[ "function", "lrem", "(", "count", ",", "value", ")", "{", "var", "ind", ",", "deleted", "=", "0", ";", "if", "(", "count", "===", "0", ")", "{", "while", "(", "(", "ind", "=", "this", ".", "indexOf", "(", "value", ")", ")", "!==", "-", "1", ")", "{", "this", ".", "_data", ".", "splice", "(", "ind", ",", "1", ")", ";", "deleted", "++", ";", "}", "}", "else", "if", "(", "count", ">", "0", ")", "{", "while", "(", "(", "ind", "=", "this", ".", "indexOf", "(", "value", ")", ")", "!==", "-", "1", "&&", "(", "deleted", "<", "count", ")", ")", "{", "this", ".", "_data", ".", "splice", "(", "ind", ",", "1", ")", ";", "deleted", "++", ";", "}", "}", "else", "{", "count", "=", "Math", ".", "abs", "(", "count", ")", ";", "while", "(", "(", "ind", "=", "this", ".", "lastIndexOf", "(", "value", ")", ")", "!==", "-", "1", "&&", "(", "deleted", "<", "count", ")", ")", "{", "this", ".", "_data", ".", "splice", "(", "ind", ",", "1", ")", ";", "deleted", "++", ";", "}", "}", "return", "deleted", ";", "}" ]
Removes elements from the list.
[ "Removes", "elements", "from", "the", "list", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/list.js#L82-L102
52,857
redisjs/jsr-store
lib/type/list.js
lrange
function lrange(start, stop) { if(start < 0) start = this._data.length + start; if(stop < 0) stop = this._data.length + stop; stop++; return this._data.slice(start, stop); }
javascript
function lrange(start, stop) { if(start < 0) start = this._data.length + start; if(stop < 0) stop = this._data.length + stop; stop++; return this._data.slice(start, stop); }
[ "function", "lrange", "(", "start", ",", "stop", ")", "{", "if", "(", "start", "<", "0", ")", "start", "=", "this", ".", "_data", ".", "length", "+", "start", ";", "if", "(", "stop", "<", "0", ")", "stop", "=", "this", ".", "_data", ".", "length", "+", "stop", ";", "stop", "++", ";", "return", "this", ".", "_data", ".", "slice", "(", "start", ",", "stop", ")", ";", "}" ]
Returns the specified elements of the list.
[ "Returns", "the", "specified", "elements", "of", "the", "list", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/list.js#L115-L120
52,858
redisjs/jsr-persistence
lib/save.js
iterateKeys
function iterateKeys() { var obj = getKeyObject(db, j); if(obj === null) return onKeysComplete(); encoder.write(obj, function onWrite() { j++; setImmediate(iterateKeys); }); }
javascript
function iterateKeys() { var obj = getKeyObject(db, j); if(obj === null) return onKeysComplete(); encoder.write(obj, function onWrite() { j++; setImmediate(iterateKeys); }); }
[ "function", "iterateKeys", "(", ")", "{", "var", "obj", "=", "getKeyObject", "(", "db", ",", "j", ")", ";", "if", "(", "obj", "===", "null", ")", "return", "onKeysComplete", "(", ")", ";", "encoder", ".", "write", "(", "obj", ",", "function", "onWrite", "(", ")", "{", "j", "++", ";", "setImmediate", "(", "iterateKeys", ")", ";", "}", ")", ";", "}" ]
iterate keys in a db
[ "iterate", "keys", "in", "a", "db" ]
77f3fc84ea7cbdb9f41a4dfa7ee1d89be61f7510
https://github.com/redisjs/jsr-persistence/blob/77f3fc84ea7cbdb9f41a4dfa7ee1d89be61f7510/lib/save.js#L163-L170
52,859
repetere/periodicjs.ext.login
controller/token_controller.js
function (user, req, cb) { CoreController.getPluginViewDefaultTemplate({ viewname: 'email/user/forgot_password_link', themefileext: appSettings.templatefileextension, }, function (err, templatepath) { if (err) { cb(err); } else { // console.log('emailForgotPasswordLink templatepath', templatepath); if (templatepath === 'email/user/forgot_password_link') { templatepath = path.resolve(process.cwd(), 'node_modules/periodicjs.ext.login/views', templatepath + '.' + appSettings.templatefileextension); } // console.log('user for forgot password', user); var coreMailerOptions = { appenvironment: appenvironment, to: user.email, from: appSettings.fromemail || appSettings.adminnotificationemail, replyTo: appSettings.fromemail || appSettings.adminnotificationemail, subject: loginExtSettings.settings.forgotPasswordEmailSubject || appSettings.name + ' - Reset your password', emailtemplatefilepath: templatepath, emailtemplatedata: { user: user, appname: appSettings.name, hostname: req.headers.host, filename: templatepath, adminPostRoute: req.adminPostRoute, }, }; if (loginExtSettings.settings.adminbccemail || appSettings.adminbccemail) { coreMailerOptions.bcc = loginExtSettings.settings.adminbccemail || appSettings.adminbccemail; } CoreMailer.sendEmail(coreMailerOptions, cb); } } ); // cb(null, options); }
javascript
function (user, req, cb) { CoreController.getPluginViewDefaultTemplate({ viewname: 'email/user/forgot_password_link', themefileext: appSettings.templatefileextension, }, function (err, templatepath) { if (err) { cb(err); } else { // console.log('emailForgotPasswordLink templatepath', templatepath); if (templatepath === 'email/user/forgot_password_link') { templatepath = path.resolve(process.cwd(), 'node_modules/periodicjs.ext.login/views', templatepath + '.' + appSettings.templatefileextension); } // console.log('user for forgot password', user); var coreMailerOptions = { appenvironment: appenvironment, to: user.email, from: appSettings.fromemail || appSettings.adminnotificationemail, replyTo: appSettings.fromemail || appSettings.adminnotificationemail, subject: loginExtSettings.settings.forgotPasswordEmailSubject || appSettings.name + ' - Reset your password', emailtemplatefilepath: templatepath, emailtemplatedata: { user: user, appname: appSettings.name, hostname: req.headers.host, filename: templatepath, adminPostRoute: req.adminPostRoute, }, }; if (loginExtSettings.settings.adminbccemail || appSettings.adminbccemail) { coreMailerOptions.bcc = loginExtSettings.settings.adminbccemail || appSettings.adminbccemail; } CoreMailer.sendEmail(coreMailerOptions, cb); } } ); // cb(null, options); }
[ "function", "(", "user", ",", "req", ",", "cb", ")", "{", "CoreController", ".", "getPluginViewDefaultTemplate", "(", "{", "viewname", ":", "'email/user/forgot_password_link'", ",", "themefileext", ":", "appSettings", ".", "templatefileextension", ",", "}", ",", "function", "(", "err", ",", "templatepath", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", "else", "{", "// console.log('emailForgotPasswordLink templatepath', templatepath);", "if", "(", "templatepath", "===", "'email/user/forgot_password_link'", ")", "{", "templatepath", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "'node_modules/periodicjs.ext.login/views'", ",", "templatepath", "+", "'.'", "+", "appSettings", ".", "templatefileextension", ")", ";", "}", "// console.log('user for forgot password', user);", "var", "coreMailerOptions", "=", "{", "appenvironment", ":", "appenvironment", ",", "to", ":", "user", ".", "email", ",", "from", ":", "appSettings", ".", "fromemail", "||", "appSettings", ".", "adminnotificationemail", ",", "replyTo", ":", "appSettings", ".", "fromemail", "||", "appSettings", ".", "adminnotificationemail", ",", "subject", ":", "loginExtSettings", ".", "settings", ".", "forgotPasswordEmailSubject", "||", "appSettings", ".", "name", "+", "' - Reset your password'", ",", "emailtemplatefilepath", ":", "templatepath", ",", "emailtemplatedata", ":", "{", "user", ":", "user", ",", "appname", ":", "appSettings", ".", "name", ",", "hostname", ":", "req", ".", "headers", ".", "host", ",", "filename", ":", "templatepath", ",", "adminPostRoute", ":", "req", ".", "adminPostRoute", ",", "}", ",", "}", ";", "if", "(", "loginExtSettings", ".", "settings", ".", "adminbccemail", "||", "appSettings", ".", "adminbccemail", ")", "{", "coreMailerOptions", ".", "bcc", "=", "loginExtSettings", ".", "settings", ".", "adminbccemail", "||", "appSettings", ".", "adminbccemail", ";", "}", "CoreMailer", ".", "sendEmail", "(", "coreMailerOptions", ",", "cb", ")", ";", "}", "}", ")", ";", "// cb(null, options);", "}" ]
create a func for the mail options
[ "create", "a", "func", "for", "the", "mail", "options" ]
f0e83fc0224242a841c013435c0f75d5f4ae15cd
https://github.com/repetere/periodicjs.ext.login/blob/f0e83fc0224242a841c013435c0f75d5f4ae15cd/controller/token_controller.js#L196-L233
52,860
repetere/periodicjs.ext.login
controller/token_controller.js
function (req, res, next) { if (periodic.app.controller.extension.reactadmin) { let reactadmin = periodic.app.controller.extension.reactadmin; // console.log({ reactadmin }); // console.log('ensureAuthenticated req.session', req.session); // console.log('ensureAuthenticated req.user', req.user); next(); } else { let adminPostRoute = res.locals.adminPostRoute || 'auth'; var token = req.controllerData.token, // current_user, decode_token; decode(token, function (err, decode) { if (err) { CoreController.handleDocumentQueryErrorResponse({ err: err, res: res, req: req, errorflash: err.message, }); } else { decode_token = decode; //Find the User by their token User.findOne({ 'attributes.reset_token': token, }, function (err, found_user) { if (err || !found_user) { req.flash('error', 'Password reset token is invalid.'); res.redirect(loginExtSettings.settings.authLoginPath); } // current_user = found_user; //Check to make sure token hasn't expired //Check to make sure token is valid and sign by us else if (found_user.email !== decode_token.email && found_user.api_key !== decode_token.api_key) { req.flash('error', 'This token is not valid please try again'); res.redirect(loginExtSettings.settings.authLoginPath); } else { CoreController.getPluginViewDefaultTemplate({ viewname: 'user/reset', themefileext: appSettings.templatefileextension, extname: 'periodicjs.ext.login', }, function (err, templatepath) { CoreController.handleDocumentQueryRender({ res: res, req: req, renderView: templatepath, responseData: { pagedata: { title: 'Reset Password', current_user: found_user, }, user: req.user, adminPostRoute: adminPostRoute, }, }); }); } }); } }); } }
javascript
function (req, res, next) { if (periodic.app.controller.extension.reactadmin) { let reactadmin = periodic.app.controller.extension.reactadmin; // console.log({ reactadmin }); // console.log('ensureAuthenticated req.session', req.session); // console.log('ensureAuthenticated req.user', req.user); next(); } else { let adminPostRoute = res.locals.adminPostRoute || 'auth'; var token = req.controllerData.token, // current_user, decode_token; decode(token, function (err, decode) { if (err) { CoreController.handleDocumentQueryErrorResponse({ err: err, res: res, req: req, errorflash: err.message, }); } else { decode_token = decode; //Find the User by their token User.findOne({ 'attributes.reset_token': token, }, function (err, found_user) { if (err || !found_user) { req.flash('error', 'Password reset token is invalid.'); res.redirect(loginExtSettings.settings.authLoginPath); } // current_user = found_user; //Check to make sure token hasn't expired //Check to make sure token is valid and sign by us else if (found_user.email !== decode_token.email && found_user.api_key !== decode_token.api_key) { req.flash('error', 'This token is not valid please try again'); res.redirect(loginExtSettings.settings.authLoginPath); } else { CoreController.getPluginViewDefaultTemplate({ viewname: 'user/reset', themefileext: appSettings.templatefileextension, extname: 'periodicjs.ext.login', }, function (err, templatepath) { CoreController.handleDocumentQueryRender({ res: res, req: req, renderView: templatepath, responseData: { pagedata: { title: 'Reset Password', current_user: found_user, }, user: req.user, adminPostRoute: adminPostRoute, }, }); }); } }); } }); } }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "periodic", ".", "app", ".", "controller", ".", "extension", ".", "reactadmin", ")", "{", "let", "reactadmin", "=", "periodic", ".", "app", ".", "controller", ".", "extension", ".", "reactadmin", ";", "// console.log({ reactadmin });", "// console.log('ensureAuthenticated req.session', req.session);", "// console.log('ensureAuthenticated req.user', req.user);", "next", "(", ")", ";", "}", "else", "{", "let", "adminPostRoute", "=", "res", ".", "locals", ".", "adminPostRoute", "||", "'auth'", ";", "var", "token", "=", "req", ".", "controllerData", ".", "token", ",", "// current_user,", "decode_token", ";", "decode", "(", "token", ",", "function", "(", "err", ",", "decode", ")", "{", "if", "(", "err", ")", "{", "CoreController", ".", "handleDocumentQueryErrorResponse", "(", "{", "err", ":", "err", ",", "res", ":", "res", ",", "req", ":", "req", ",", "errorflash", ":", "err", ".", "message", ",", "}", ")", ";", "}", "else", "{", "decode_token", "=", "decode", ";", "//Find the User by their token", "User", ".", "findOne", "(", "{", "'attributes.reset_token'", ":", "token", ",", "}", ",", "function", "(", "err", ",", "found_user", ")", "{", "if", "(", "err", "||", "!", "found_user", ")", "{", "req", ".", "flash", "(", "'error'", ",", "'Password reset token is invalid.'", ")", ";", "res", ".", "redirect", "(", "loginExtSettings", ".", "settings", ".", "authLoginPath", ")", ";", "}", "// current_user = found_user;", "//Check to make sure token hasn't expired", "//Check to make sure token is valid and sign by us", "else", "if", "(", "found_user", ".", "email", "!==", "decode_token", ".", "email", "&&", "found_user", ".", "api_key", "!==", "decode_token", ".", "api_key", ")", "{", "req", ".", "flash", "(", "'error'", ",", "'This token is not valid please try again'", ")", ";", "res", ".", "redirect", "(", "loginExtSettings", ".", "settings", ".", "authLoginPath", ")", ";", "}", "else", "{", "CoreController", ".", "getPluginViewDefaultTemplate", "(", "{", "viewname", ":", "'user/reset'", ",", "themefileext", ":", "appSettings", ".", "templatefileextension", ",", "extname", ":", "'periodicjs.ext.login'", ",", "}", ",", "function", "(", "err", ",", "templatepath", ")", "{", "CoreController", ".", "handleDocumentQueryRender", "(", "{", "res", ":", "res", ",", "req", ":", "req", ",", "renderView", ":", "templatepath", ",", "responseData", ":", "{", "pagedata", ":", "{", "title", ":", "'Reset Password'", ",", "current_user", ":", "found_user", ",", "}", ",", "user", ":", "req", ".", "user", ",", "adminPostRoute", ":", "adminPostRoute", ",", "}", ",", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "}" ]
GET if the user token is vaild show the change password page
[ "GET", "if", "the", "user", "token", "is", "vaild", "show", "the", "change", "password", "page" ]
f0e83fc0224242a841c013435c0f75d5f4ae15cd
https://github.com/repetere/periodicjs.ext.login/blob/f0e83fc0224242a841c013435c0f75d5f4ae15cd/controller/token_controller.js#L385-L449
52,861
repetere/periodicjs.ext.login
controller/token_controller.js
function (req, res, next) { // console.log('req.body', req.body); // console.log('req.params', req.params); var user_token = req.params.token || req.body.token; //req.controllerData.token; waterfall([ function (cb) { cb(null, req, res, next); }, invalidateUserToken, resetPassword, saveUser, emailResetPasswordNotification, ], function (err, results) { if (periodic.app.controller.extension.reactadmin) { let reactadmin = periodic.app.controller.extension.reactadmin; if (err) { res.status(400).send({ result: 'error', data: { error:err.toString(), }, }); } else { res.status(200).send({ result: 'success', data:'Password successfully changed', }); } } else { // console.log('These are the err', err); // console.log('These are the results', results); CoreController.respondInKind({ req: req, res: res, err: err, responseData: results || {}, callback: function (req, res /*,responseData*/ ) { // console.log('err',err,'/auth/reset/' + user_token); if (err) { // console.log('return to reset'); req.flash('error', err.message); res.redirect('/auth/reset/' + user_token); } else { // console.log('no return to x'); req.flash('success', 'Password Sucessfully Changed!'); res.redirect(loginExtSettings.settings.authLoginPath); } }, }); } }); }
javascript
function (req, res, next) { // console.log('req.body', req.body); // console.log('req.params', req.params); var user_token = req.params.token || req.body.token; //req.controllerData.token; waterfall([ function (cb) { cb(null, req, res, next); }, invalidateUserToken, resetPassword, saveUser, emailResetPasswordNotification, ], function (err, results) { if (periodic.app.controller.extension.reactadmin) { let reactadmin = periodic.app.controller.extension.reactadmin; if (err) { res.status(400).send({ result: 'error', data: { error:err.toString(), }, }); } else { res.status(200).send({ result: 'success', data:'Password successfully changed', }); } } else { // console.log('These are the err', err); // console.log('These are the results', results); CoreController.respondInKind({ req: req, res: res, err: err, responseData: results || {}, callback: function (req, res /*,responseData*/ ) { // console.log('err',err,'/auth/reset/' + user_token); if (err) { // console.log('return to reset'); req.flash('error', err.message); res.redirect('/auth/reset/' + user_token); } else { // console.log('no return to x'); req.flash('success', 'Password Sucessfully Changed!'); res.redirect(loginExtSettings.settings.authLoginPath); } }, }); } }); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "// console.log('req.body', req.body);", "// console.log('req.params', req.params);", "var", "user_token", "=", "req", ".", "params", ".", "token", "||", "req", ".", "body", ".", "token", ";", "//req.controllerData.token;", "waterfall", "(", "[", "function", "(", "cb", ")", "{", "cb", "(", "null", ",", "req", ",", "res", ",", "next", ")", ";", "}", ",", "invalidateUserToken", ",", "resetPassword", ",", "saveUser", ",", "emailResetPasswordNotification", ",", "]", ",", "function", "(", "err", ",", "results", ")", "{", "if", "(", "periodic", ".", "app", ".", "controller", ".", "extension", ".", "reactadmin", ")", "{", "let", "reactadmin", "=", "periodic", ".", "app", ".", "controller", ".", "extension", ".", "reactadmin", ";", "if", "(", "err", ")", "{", "res", ".", "status", "(", "400", ")", ".", "send", "(", "{", "result", ":", "'error'", ",", "data", ":", "{", "error", ":", "err", ".", "toString", "(", ")", ",", "}", ",", "}", ")", ";", "}", "else", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "{", "result", ":", "'success'", ",", "data", ":", "'Password successfully changed'", ",", "}", ")", ";", "}", "}", "else", "{", "// console.log('These are the err', err);", "// console.log('These are the results', results);", "CoreController", ".", "respondInKind", "(", "{", "req", ":", "req", ",", "res", ":", "res", ",", "err", ":", "err", ",", "responseData", ":", "results", "||", "{", "}", ",", "callback", ":", "function", "(", "req", ",", "res", "/*,responseData*/", ")", "{", "// console.log('err',err,'/auth/reset/' + user_token);", "if", "(", "err", ")", "{", "// console.log('return to reset');", "req", ".", "flash", "(", "'error'", ",", "err", ".", "message", ")", ";", "res", ".", "redirect", "(", "'/auth/reset/'", "+", "user_token", ")", ";", "}", "else", "{", "// console.log('no return to x');", "req", ".", "flash", "(", "'success'", ",", "'Password Sucessfully Changed!'", ")", ";", "res", ".", "redirect", "(", "loginExtSettings", ".", "settings", ".", "authLoginPath", ")", ";", "}", "}", ",", "}", ")", ";", "}", "}", ")", ";", "}" ]
POST change the users old password to the new password in the form
[ "POST", "change", "the", "users", "old", "password", "to", "the", "new", "password", "in", "the", "form" ]
f0e83fc0224242a841c013435c0f75d5f4ae15cd
https://github.com/repetere/periodicjs.ext.login/blob/f0e83fc0224242a841c013435c0f75d5f4ae15cd/controller/token_controller.js#L452-L504
52,862
michbuett/immutabilis
src/immutabilis.js
createSub
function createSub(value, computed) { if (isArray(value)) { return new List(value, computed); } else if (isObject(value)) { if (isImmutable(value)) { return value; } else if (value.constructor === Object) { return new Struct(value, computed); } return new Value(value, computed); } return new Value(value, computed); }
javascript
function createSub(value, computed) { if (isArray(value)) { return new List(value, computed); } else if (isObject(value)) { if (isImmutable(value)) { return value; } else if (value.constructor === Object) { return new Struct(value, computed); } return new Value(value, computed); } return new Value(value, computed); }
[ "function", "createSub", "(", "value", ",", "computed", ")", "{", "if", "(", "isArray", "(", "value", ")", ")", "{", "return", "new", "List", "(", "value", ",", "computed", ")", ";", "}", "else", "if", "(", "isObject", "(", "value", ")", ")", "{", "if", "(", "isImmutable", "(", "value", ")", ")", "{", "return", "value", ";", "}", "else", "if", "(", "value", ".", "constructor", "===", "Object", ")", "{", "return", "new", "Struct", "(", "value", ",", "computed", ")", ";", "}", "return", "new", "Value", "(", "value", ",", "computed", ")", ";", "}", "return", "new", "Value", "(", "value", ",", "computed", ")", ";", "}" ]
Helper to create an immutable data object depending on the type of the input @private
[ "Helper", "to", "create", "an", "immutable", "data", "object", "depending", "on", "the", "type", "of", "the", "input" ]
3b3b9eaa69e7a7d718a9804ca2d3f5d439716c79
https://github.com/michbuett/immutabilis/blob/3b3b9eaa69e7a7d718a9804ca2d3f5d439716c79/src/immutabilis.js#L39-L51
52,863
michbuett/immutabilis
src/immutabilis.js
Abstract
function Abstract(value, data, computed) { this.value = value; this.data = data && each(data, function (item) { return createSub(item); }); this.computedProps = computed; }
javascript
function Abstract(value, data, computed) { this.value = value; this.data = data && each(data, function (item) { return createSub(item); }); this.computedProps = computed; }
[ "function", "Abstract", "(", "value", ",", "data", ",", "computed", ")", "{", "this", ".", "value", "=", "value", ";", "this", ".", "data", "=", "data", "&&", "each", "(", "data", ",", "function", "(", "item", ")", "{", "return", "createSub", "(", "item", ")", ";", "}", ")", ";", "this", ".", "computedProps", "=", "computed", ";", "}" ]
The abstract base class for immutable values @class Abstract @private
[ "The", "abstract", "base", "class", "for", "immutable", "values" ]
3b3b9eaa69e7a7d718a9804ca2d3f5d439716c79
https://github.com/michbuett/immutabilis/blob/3b3b9eaa69e7a7d718a9804ca2d3f5d439716c79/src/immutabilis.js#L59-L65
52,864
koop-retired/koop-server
lib/SQLite.js
function(name, schema, callback){ var self = this; this.db.serialize(function() { self.db.run("CREATE TABLE IF NOT EXISTS\"" + name + "\" " + schema, callback); }); }
javascript
function(name, schema, callback){ var self = this; this.db.serialize(function() { self.db.run("CREATE TABLE IF NOT EXISTS\"" + name + "\" " + schema, callback); }); }
[ "function", "(", "name", ",", "schema", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "this", ".", "db", ".", "serialize", "(", "function", "(", ")", "{", "self", ".", "db", ".", "run", "(", "\"CREATE TABLE IF NOT EXISTS\\\"\"", "+", "name", "+", "\"\\\" \"", "+", "schema", ",", "callback", ")", ";", "}", ")", ";", "}" ]
checks to see in the info table exists, create it if not
[ "checks", "to", "see", "in", "the", "info", "table", "exists", "create", "it", "if", "not" ]
7b4404aa0db92023bfd59b475ad43aa36e02aee8
https://github.com/koop-retired/koop-server/blob/7b4404aa0db92023bfd59b475ad43aa36e02aee8/lib/SQLite.js#L349-L354
52,865
mdasberg/angular-test-setup
app/todo/todo.component.po.js
function () { this.el = element(by.tagName('todo')); this.available = function() { return this.el.element(by.binding('$ctrl.todos.length')).getText(); }; this.uncompleted = function() { return this.el.element(by.binding('$ctrl.uncompleted()')).getText(); }; this.todos = function() { return this.el.all(by.repeater('todo in $ctrl.todos')); }; this.todo = function (index) { return new Todo(this.todos().get(index)); }; this.error = function() { return this.el.element(by.binding('$ctrl.error')).getText(); }; // actions this.add = function (description) { return this.el.element(by.model('$ctrl.description')).clear().sendKeys(description, protractor.Key.ENTER); }; this.archive = function() { return this.el.element(by.css('[ng-click="$ctrl.archive()"]')).click(); }; }
javascript
function () { this.el = element(by.tagName('todo')); this.available = function() { return this.el.element(by.binding('$ctrl.todos.length')).getText(); }; this.uncompleted = function() { return this.el.element(by.binding('$ctrl.uncompleted()')).getText(); }; this.todos = function() { return this.el.all(by.repeater('todo in $ctrl.todos')); }; this.todo = function (index) { return new Todo(this.todos().get(index)); }; this.error = function() { return this.el.element(by.binding('$ctrl.error')).getText(); }; // actions this.add = function (description) { return this.el.element(by.model('$ctrl.description')).clear().sendKeys(description, protractor.Key.ENTER); }; this.archive = function() { return this.el.element(by.css('[ng-click="$ctrl.archive()"]')).click(); }; }
[ "function", "(", ")", "{", "this", ".", "el", "=", "element", "(", "by", ".", "tagName", "(", "'todo'", ")", ")", ";", "this", ".", "available", "=", "function", "(", ")", "{", "return", "this", ".", "el", ".", "element", "(", "by", ".", "binding", "(", "'$ctrl.todos.length'", ")", ")", ".", "getText", "(", ")", ";", "}", ";", "this", ".", "uncompleted", "=", "function", "(", ")", "{", "return", "this", ".", "el", ".", "element", "(", "by", ".", "binding", "(", "'$ctrl.uncompleted()'", ")", ")", ".", "getText", "(", ")", ";", "}", ";", "this", ".", "todos", "=", "function", "(", ")", "{", "return", "this", ".", "el", ".", "all", "(", "by", ".", "repeater", "(", "'todo in $ctrl.todos'", ")", ")", ";", "}", ";", "this", ".", "todo", "=", "function", "(", "index", ")", "{", "return", "new", "Todo", "(", "this", ".", "todos", "(", ")", ".", "get", "(", "index", ")", ")", ";", "}", ";", "this", ".", "error", "=", "function", "(", ")", "{", "return", "this", ".", "el", ".", "element", "(", "by", ".", "binding", "(", "'$ctrl.error'", ")", ")", ".", "getText", "(", ")", ";", "}", ";", "// actions", "this", ".", "add", "=", "function", "(", "description", ")", "{", "return", "this", ".", "el", ".", "element", "(", "by", ".", "model", "(", "'$ctrl.description'", ")", ")", ".", "clear", "(", ")", ".", "sendKeys", "(", "description", ",", "protractor", ".", "Key", ".", "ENTER", ")", ";", "}", ";", "this", ".", "archive", "=", "function", "(", ")", "{", "return", "this", ".", "el", ".", "element", "(", "by", ".", "css", "(", "'[ng-click=\"$ctrl.archive()\"]'", ")", ")", ".", "click", "(", ")", ";", "}", ";", "}" ]
PageObject is an API for the Todo. @constructor
[ "PageObject", "is", "an", "API", "for", "the", "Todo", "." ]
4a1ef0742bac233b94e7c3682e8158c00aa87552
https://github.com/mdasberg/angular-test-setup/blob/4a1ef0742bac233b94e7c3682e8158c00aa87552/app/todo/todo.component.po.js#L7-L32
52,866
xiamidaxia/xiami
meteor/mongo-livedata/oplog_observe_driver.js
function (id) { var self = this; self._unpublishedBuffer.remove(id); // To keep the contract "buffer is never empty in STEADY phase unless the // everything matching fits into published" true, we poll everything as soon // as we see the buffer becoming empty. if (! self._unpublishedBuffer.size() && ! self._safeAppendToBuffer) self._needToPollQuery(); }
javascript
function (id) { var self = this; self._unpublishedBuffer.remove(id); // To keep the contract "buffer is never empty in STEADY phase unless the // everything matching fits into published" true, we poll everything as soon // as we see the buffer becoming empty. if (! self._unpublishedBuffer.size() && ! self._safeAppendToBuffer) self._needToPollQuery(); }
[ "function", "(", "id", ")", "{", "var", "self", "=", "this", ";", "self", ".", "_unpublishedBuffer", ".", "remove", "(", "id", ")", ";", "// To keep the contract \"buffer is never empty in STEADY phase unless the", "// everything matching fits into published\" true, we poll everything as soon", "// as we see the buffer becoming empty.", "if", "(", "!", "self", ".", "_unpublishedBuffer", ".", "size", "(", ")", "&&", "!", "self", ".", "_safeAppendToBuffer", ")", "self", ".", "_needToPollQuery", "(", ")", ";", "}" ]
Is called either to remove the doc completely from matching set or to move it to the published set later.
[ "Is", "called", "either", "to", "remove", "the", "doc", "completely", "from", "matching", "set", "or", "to", "move", "it", "to", "the", "published", "set", "later", "." ]
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/mongo-livedata/oplog_observe_driver.js#L286-L294
52,867
xiamidaxia/xiami
meteor/mongo-livedata/oplog_observe_driver.js
function (doc) { var self = this; var id = doc._id; if (self._published.has(id)) throw Error("tried to add something already published " + id); if (self._limit && self._unpublishedBuffer.has(id)) throw Error("tried to add something already existed in buffer " + id); var limit = self._limit; var comparator = self._comparator; var maxPublished = (limit && self._published.size() > 0) ? self._published.get(self._published.maxElementId()) : null; var maxBuffered = (limit && self._unpublishedBuffer.size() > 0) ? self._unpublishedBuffer.get(self._unpublishedBuffer.maxElementId()) : null; // The query is unlimited or didn't publish enough documents yet or the new // document would fit into published set pushing the maximum element out, // then we need to publish the doc. var toPublish = ! limit || self._published.size() < limit || comparator(doc, maxPublished) < 0; // Otherwise we might need to buffer it (only in case of limited query). // Buffering is allowed if the buffer is not filled up yet and all matching // docs are either in the published set or in the buffer. var canAppendToBuffer = !toPublish && self._safeAppendToBuffer && self._unpublishedBuffer.size() < limit; // Or if it is small enough to be safely inserted to the middle or the // beginning of the buffer. var canInsertIntoBuffer = !toPublish && maxBuffered && comparator(doc, maxBuffered) <= 0; var toBuffer = canAppendToBuffer || canInsertIntoBuffer; if (toPublish) { self._addPublished(id, doc); } else if (toBuffer) { self._addBuffered(id, doc); } else { // dropping it and not saving to the cache self._safeAppendToBuffer = false; } }
javascript
function (doc) { var self = this; var id = doc._id; if (self._published.has(id)) throw Error("tried to add something already published " + id); if (self._limit && self._unpublishedBuffer.has(id)) throw Error("tried to add something already existed in buffer " + id); var limit = self._limit; var comparator = self._comparator; var maxPublished = (limit && self._published.size() > 0) ? self._published.get(self._published.maxElementId()) : null; var maxBuffered = (limit && self._unpublishedBuffer.size() > 0) ? self._unpublishedBuffer.get(self._unpublishedBuffer.maxElementId()) : null; // The query is unlimited or didn't publish enough documents yet or the new // document would fit into published set pushing the maximum element out, // then we need to publish the doc. var toPublish = ! limit || self._published.size() < limit || comparator(doc, maxPublished) < 0; // Otherwise we might need to buffer it (only in case of limited query). // Buffering is allowed if the buffer is not filled up yet and all matching // docs are either in the published set or in the buffer. var canAppendToBuffer = !toPublish && self._safeAppendToBuffer && self._unpublishedBuffer.size() < limit; // Or if it is small enough to be safely inserted to the middle or the // beginning of the buffer. var canInsertIntoBuffer = !toPublish && maxBuffered && comparator(doc, maxBuffered) <= 0; var toBuffer = canAppendToBuffer || canInsertIntoBuffer; if (toPublish) { self._addPublished(id, doc); } else if (toBuffer) { self._addBuffered(id, doc); } else { // dropping it and not saving to the cache self._safeAppendToBuffer = false; } }
[ "function", "(", "doc", ")", "{", "var", "self", "=", "this", ";", "var", "id", "=", "doc", ".", "_id", ";", "if", "(", "self", ".", "_published", ".", "has", "(", "id", ")", ")", "throw", "Error", "(", "\"tried to add something already published \"", "+", "id", ")", ";", "if", "(", "self", ".", "_limit", "&&", "self", ".", "_unpublishedBuffer", ".", "has", "(", "id", ")", ")", "throw", "Error", "(", "\"tried to add something already existed in buffer \"", "+", "id", ")", ";", "var", "limit", "=", "self", ".", "_limit", ";", "var", "comparator", "=", "self", ".", "_comparator", ";", "var", "maxPublished", "=", "(", "limit", "&&", "self", ".", "_published", ".", "size", "(", ")", ">", "0", ")", "?", "self", ".", "_published", ".", "get", "(", "self", ".", "_published", ".", "maxElementId", "(", ")", ")", ":", "null", ";", "var", "maxBuffered", "=", "(", "limit", "&&", "self", ".", "_unpublishedBuffer", ".", "size", "(", ")", ">", "0", ")", "?", "self", ".", "_unpublishedBuffer", ".", "get", "(", "self", ".", "_unpublishedBuffer", ".", "maxElementId", "(", ")", ")", ":", "null", ";", "// The query is unlimited or didn't publish enough documents yet or the new", "// document would fit into published set pushing the maximum element out,", "// then we need to publish the doc.", "var", "toPublish", "=", "!", "limit", "||", "self", ".", "_published", ".", "size", "(", ")", "<", "limit", "||", "comparator", "(", "doc", ",", "maxPublished", ")", "<", "0", ";", "// Otherwise we might need to buffer it (only in case of limited query).", "// Buffering is allowed if the buffer is not filled up yet and all matching", "// docs are either in the published set or in the buffer.", "var", "canAppendToBuffer", "=", "!", "toPublish", "&&", "self", ".", "_safeAppendToBuffer", "&&", "self", ".", "_unpublishedBuffer", ".", "size", "(", ")", "<", "limit", ";", "// Or if it is small enough to be safely inserted to the middle or the", "// beginning of the buffer.", "var", "canInsertIntoBuffer", "=", "!", "toPublish", "&&", "maxBuffered", "&&", "comparator", "(", "doc", ",", "maxBuffered", ")", "<=", "0", ";", "var", "toBuffer", "=", "canAppendToBuffer", "||", "canInsertIntoBuffer", ";", "if", "(", "toPublish", ")", "{", "self", ".", "_addPublished", "(", "id", ",", "doc", ")", ";", "}", "else", "if", "(", "toBuffer", ")", "{", "self", ".", "_addBuffered", "(", "id", ",", "doc", ")", ";", "}", "else", "{", "// dropping it and not saving to the cache", "self", ".", "_safeAppendToBuffer", "=", "false", ";", "}", "}" ]
Called when a document has joined the "Matching" results set. Takes responsibility of keeping _unpublishedBuffer in sync with _published and the effect of limit enforced.
[ "Called", "when", "a", "document", "has", "joined", "the", "Matching", "results", "set", ".", "Takes", "responsibility", "of", "keeping", "_unpublishedBuffer", "in", "sync", "with", "_published", "and", "the", "effect", "of", "limit", "enforced", "." ]
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/mongo-livedata/oplog_observe_driver.js#L298-L339
52,868
xiamidaxia/xiami
meteor/mongo-livedata/oplog_observe_driver.js
function (id) { var self = this; if (! self._published.has(id) && ! self._limit) throw Error("tried to remove something matching but not cached " + id); if (self._published.has(id)) { self._removePublished(id); } else if (self._unpublishedBuffer.has(id)) { self._removeBuffered(id); } }
javascript
function (id) { var self = this; if (! self._published.has(id) && ! self._limit) throw Error("tried to remove something matching but not cached " + id); if (self._published.has(id)) { self._removePublished(id); } else if (self._unpublishedBuffer.has(id)) { self._removeBuffered(id); } }
[ "function", "(", "id", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "self", ".", "_published", ".", "has", "(", "id", ")", "&&", "!", "self", ".", "_limit", ")", "throw", "Error", "(", "\"tried to remove something matching but not cached \"", "+", "id", ")", ";", "if", "(", "self", ".", "_published", ".", "has", "(", "id", ")", ")", "{", "self", ".", "_removePublished", "(", "id", ")", ";", "}", "else", "if", "(", "self", ".", "_unpublishedBuffer", ".", "has", "(", "id", ")", ")", "{", "self", ".", "_removeBuffered", "(", "id", ")", ";", "}", "}" ]
Called when a document leaves the "Matching" results set. Takes responsibility of keeping _unpublishedBuffer in sync with _published and the effect of limit enforced.
[ "Called", "when", "a", "document", "leaves", "the", "Matching", "results", "set", ".", "Takes", "responsibility", "of", "keeping", "_unpublishedBuffer", "in", "sync", "with", "_published", "and", "the", "effect", "of", "limit", "enforced", "." ]
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/mongo-livedata/oplog_observe_driver.js#L343-L353
52,869
xiamidaxia/xiami
meteor/mongo-livedata/oplog_observe_driver.js
function () { var self = this; if (self._stopped) return; self._stopped = true; _.each(self._stopHandles, function (handle) { handle.stop(); }); // Note: we *don't* use multiplexer.onFlush here because this stop // callback is actually invoked by the multiplexer itself when it has // determined that there are no handles left. So nothing is actually going // to get flushed (and it's probably not valid to call methods on the // dying multiplexer). _.each(self._writesToCommitWhenWeReachSteady, function (w) { w.committed(); }); self._writesToCommitWhenWeReachSteady = null; // Proactively drop references to potentially big things. self._published = null; self._unpublishedBuffer = null; self._needToFetch = null; self._currentlyFetching = null; self._oplogEntryHandle = null; self._listenersHandle = null; Package.facts && Package.facts.Facts.incrementServerFact( "mongo-livedata", "observe-drivers-oplog", -1); }
javascript
function () { var self = this; if (self._stopped) return; self._stopped = true; _.each(self._stopHandles, function (handle) { handle.stop(); }); // Note: we *don't* use multiplexer.onFlush here because this stop // callback is actually invoked by the multiplexer itself when it has // determined that there are no handles left. So nothing is actually going // to get flushed (and it's probably not valid to call methods on the // dying multiplexer). _.each(self._writesToCommitWhenWeReachSteady, function (w) { w.committed(); }); self._writesToCommitWhenWeReachSteady = null; // Proactively drop references to potentially big things. self._published = null; self._unpublishedBuffer = null; self._needToFetch = null; self._currentlyFetching = null; self._oplogEntryHandle = null; self._listenersHandle = null; Package.facts && Package.facts.Facts.incrementServerFact( "mongo-livedata", "observe-drivers-oplog", -1); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "if", "(", "self", ".", "_stopped", ")", "return", ";", "self", ".", "_stopped", "=", "true", ";", "_", ".", "each", "(", "self", ".", "_stopHandles", ",", "function", "(", "handle", ")", "{", "handle", ".", "stop", "(", ")", ";", "}", ")", ";", "// Note: we *don't* use multiplexer.onFlush here because this stop", "// callback is actually invoked by the multiplexer itself when it has", "// determined that there are no handles left. So nothing is actually going", "// to get flushed (and it's probably not valid to call methods on the", "// dying multiplexer).", "_", ".", "each", "(", "self", ".", "_writesToCommitWhenWeReachSteady", ",", "function", "(", "w", ")", "{", "w", ".", "committed", "(", ")", ";", "}", ")", ";", "self", ".", "_writesToCommitWhenWeReachSteady", "=", "null", ";", "// Proactively drop references to potentially big things.", "self", ".", "_published", "=", "null", ";", "self", ".", "_unpublishedBuffer", "=", "null", ";", "self", ".", "_needToFetch", "=", "null", ";", "self", ".", "_currentlyFetching", "=", "null", ";", "self", ".", "_oplogEntryHandle", "=", "null", ";", "self", ".", "_listenersHandle", "=", "null", ";", "Package", ".", "facts", "&&", "Package", ".", "facts", ".", "Facts", ".", "incrementServerFact", "(", "\"mongo-livedata\"", ",", "\"observe-drivers-oplog\"", ",", "-", "1", ")", ";", "}" ]
This stop function is invoked from the onStop of the ObserveMultiplexer, so it shouldn't actually be possible to call it until the multiplexer is ready.
[ "This", "stop", "function", "is", "invoked", "from", "the", "onStop", "of", "the", "ObserveMultiplexer", "so", "it", "shouldn", "t", "actually", "be", "possible", "to", "call", "it", "until", "the", "multiplexer", "is", "ready", "." ]
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/mongo-livedata/oplog_observe_driver.js#L797-L826
52,870
gameclosure/jash
src/jash.js
addBinaries
function addBinaries(binaries) { var SLICE = Array.prototype.slice; //iterate backwards to mimic normal resolution order for (var i = binaries.length-1; i >= 0; i--) { var parts = binaries[i].split('/'); (function() {var name = parts[parts.length-1]; exports[name] = function() { //grab the last argument, which might be a callback var cbs = SLICE.call(arguments, 3); //assume none of the args we got were handlers var args = SLICE.call(arguments); var argLength = args.length; var cb, stdoutHandler, stderrHandler, options; if (args[argLength-3] instanceof Function) { //we have all 3 stderrHandler = args.pop(); stdoutHandler = args.pop(); cb = args.pop(); } else if (arguments[argLength-2] instanceof Function) { //we have cb and stdout stdoutHandler = args.pop(); cb = args.pop(); } else if (arguments[argLength-1] instanceof Function) { //we have cb only cb = args.pop(); } //if the last arg is an object, it's the options object var lastArg = args[args.length-1]; if (typeof lastArg == 'object' && !lastArg.length) { options = args.pop(); } //if the first argument was an array, the args were passed as //an array if (args[0] instanceof Array) { args = args[0]; } return runCommand(name, args, options, cb, stdoutHandler, stderrHandler); };})(); } }
javascript
function addBinaries(binaries) { var SLICE = Array.prototype.slice; //iterate backwards to mimic normal resolution order for (var i = binaries.length-1; i >= 0; i--) { var parts = binaries[i].split('/'); (function() {var name = parts[parts.length-1]; exports[name] = function() { //grab the last argument, which might be a callback var cbs = SLICE.call(arguments, 3); //assume none of the args we got were handlers var args = SLICE.call(arguments); var argLength = args.length; var cb, stdoutHandler, stderrHandler, options; if (args[argLength-3] instanceof Function) { //we have all 3 stderrHandler = args.pop(); stdoutHandler = args.pop(); cb = args.pop(); } else if (arguments[argLength-2] instanceof Function) { //we have cb and stdout stdoutHandler = args.pop(); cb = args.pop(); } else if (arguments[argLength-1] instanceof Function) { //we have cb only cb = args.pop(); } //if the last arg is an object, it's the options object var lastArg = args[args.length-1]; if (typeof lastArg == 'object' && !lastArg.length) { options = args.pop(); } //if the first argument was an array, the args were passed as //an array if (args[0] instanceof Array) { args = args[0]; } return runCommand(name, args, options, cb, stdoutHandler, stderrHandler); };})(); } }
[ "function", "addBinaries", "(", "binaries", ")", "{", "var", "SLICE", "=", "Array", ".", "prototype", ".", "slice", ";", "//iterate backwards to mimic normal resolution order", "for", "(", "var", "i", "=", "binaries", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "parts", "=", "binaries", "[", "i", "]", ".", "split", "(", "'/'", ")", ";", "(", "function", "(", ")", "{", "var", "name", "=", "parts", "[", "parts", ".", "length", "-", "1", "]", ";", "exports", "[", "name", "]", "=", "function", "(", ")", "{", "//grab the last argument, which might be a callback", "var", "cbs", "=", "SLICE", ".", "call", "(", "arguments", ",", "3", ")", ";", "//assume none of the args we got were handlers", "var", "args", "=", "SLICE", ".", "call", "(", "arguments", ")", ";", "var", "argLength", "=", "args", ".", "length", ";", "var", "cb", ",", "stdoutHandler", ",", "stderrHandler", ",", "options", ";", "if", "(", "args", "[", "argLength", "-", "3", "]", "instanceof", "Function", ")", "{", "//we have all 3", "stderrHandler", "=", "args", ".", "pop", "(", ")", ";", "stdoutHandler", "=", "args", ".", "pop", "(", ")", ";", "cb", "=", "args", ".", "pop", "(", ")", ";", "}", "else", "if", "(", "arguments", "[", "argLength", "-", "2", "]", "instanceof", "Function", ")", "{", "//we have cb and stdout ", "stdoutHandler", "=", "args", ".", "pop", "(", ")", ";", "cb", "=", "args", ".", "pop", "(", ")", ";", "}", "else", "if", "(", "arguments", "[", "argLength", "-", "1", "]", "instanceof", "Function", ")", "{", "//we have cb only", "cb", "=", "args", ".", "pop", "(", ")", ";", "}", "//if the last arg is an object, it's the options object", "var", "lastArg", "=", "args", "[", "args", ".", "length", "-", "1", "]", ";", "if", "(", "typeof", "lastArg", "==", "'object'", "&&", "!", "lastArg", ".", "length", ")", "{", "options", "=", "args", ".", "pop", "(", ")", ";", "}", "//if the first argument was an array, the args were passed as", "//an array", "if", "(", "args", "[", "0", "]", "instanceof", "Array", ")", "{", "args", "=", "args", "[", "0", "]", ";", "}", "return", "runCommand", "(", "name", ",", "args", ",", "options", ",", "cb", ",", "stdoutHandler", ",", "stderrHandler", ")", ";", "}", ";", "}", ")", "(", ")", ";", "}", "}" ]
for all the binaries in the path, setup a proxy function with the binary's name that will execute it.
[ "for", "all", "the", "binaries", "in", "the", "path", "setup", "a", "proxy", "function", "with", "the", "binary", "s", "name", "that", "will", "execute", "it", "." ]
93bcffcc2392b168538834ec8d01b172121a8c09
https://github.com/gameclosure/jash/blob/93bcffcc2392b168538834ec8d01b172121a8c09/src/jash.js#L115-L160
52,871
lordfpx/AB
index.js
function() { var extended = {}, deep = false, i = 0, length = arguments.length; if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]'){ deep = arguments[0]; i++; } var merge = function(obj) { for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') { extended[prop] = window.AB.extend(true, extended[prop], obj[prop]); } else { extended[prop] = obj[prop]; } } } }; for (; i < length; i++) { merge(arguments[i]); } return extended; }
javascript
function() { var extended = {}, deep = false, i = 0, length = arguments.length; if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]'){ deep = arguments[0]; i++; } var merge = function(obj) { for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') { extended[prop] = window.AB.extend(true, extended[prop], obj[prop]); } else { extended[prop] = obj[prop]; } } } }; for (; i < length; i++) { merge(arguments[i]); } return extended; }
[ "function", "(", ")", "{", "var", "extended", "=", "{", "}", ",", "deep", "=", "false", ",", "i", "=", "0", ",", "length", "=", "arguments", ".", "length", ";", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "arguments", "[", "0", "]", ")", "===", "'[object Boolean]'", ")", "{", "deep", "=", "arguments", "[", "0", "]", ";", "i", "++", ";", "}", "var", "merge", "=", "function", "(", "obj", ")", "{", "for", "(", "var", "prop", "in", "obj", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "prop", ")", ")", "{", "if", "(", "deep", "&&", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "obj", "[", "prop", "]", ")", "===", "'[object Object]'", ")", "{", "extended", "[", "prop", "]", "=", "window", ".", "AB", ".", "extend", "(", "true", ",", "extended", "[", "prop", "]", ",", "obj", "[", "prop", "]", ")", ";", "}", "else", "{", "extended", "[", "prop", "]", "=", "obj", "[", "prop", "]", ";", "}", "}", "}", "}", ";", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "merge", "(", "arguments", "[", "i", "]", ")", ";", "}", "return", "extended", ";", "}" ]
deep extend function
[ "deep", "extend", "function" ]
05efbec0758b77dd1e146805437f132d1398c7d9
https://github.com/lordfpx/AB/blob/05efbec0758b77dd1e146805437f132d1398c7d9/index.js#L17-L45
52,872
idiocc/core
build/lib/start-app.js
createApp
async function createApp(middlewareConfig) { const app = new Koa() const middleware = await setupMiddleware(middlewareConfig, app) if (app.env == 'production') { app.proxy = true } return { app, middleware, } }
javascript
async function createApp(middlewareConfig) { const app = new Koa() const middleware = await setupMiddleware(middlewareConfig, app) if (app.env == 'production') { app.proxy = true } return { app, middleware, } }
[ "async", "function", "createApp", "(", "middlewareConfig", ")", "{", "const", "app", "=", "new", "Koa", "(", ")", "const", "middleware", "=", "await", "setupMiddleware", "(", "middlewareConfig", ",", "app", ")", "if", "(", "app", ".", "env", "==", "'production'", ")", "{", "app", ".", "proxy", "=", "true", "}", "return", "{", "app", ",", "middleware", ",", "}", "}" ]
Create an application and setup middleware. @param {MiddlewareConfig} middlewareConfig
[ "Create", "an", "application", "and", "setup", "middleware", "." ]
27aa14cf339b783777b6523670629ea40955bf3c
https://github.com/idiocc/core/blob/27aa14cf339b783777b6523670629ea40955bf3c/build/lib/start-app.js#L12-L25
52,873
alexander-heimbuch/utterson
pipe/plumber.js
function (defaults, attr, custom) { var resolvedPath; if (defaults === undefined || defaults[attr] === undefined) { throw new Error('Missing Parameter', 'Expect a given defaults object'); } if (attr === undefined) { throw new Error('Missing Parameter', 'Expect a given attribute'); } if (custom === undefined || custom[attr] === undefined) { resolvedPath = path.resolve(defaults[attr]); } else { resolvedPath = path.resolve(custom[attr]); } return resolvedPath; }
javascript
function (defaults, attr, custom) { var resolvedPath; if (defaults === undefined || defaults[attr] === undefined) { throw new Error('Missing Parameter', 'Expect a given defaults object'); } if (attr === undefined) { throw new Error('Missing Parameter', 'Expect a given attribute'); } if (custom === undefined || custom[attr] === undefined) { resolvedPath = path.resolve(defaults[attr]); } else { resolvedPath = path.resolve(custom[attr]); } return resolvedPath; }
[ "function", "(", "defaults", ",", "attr", ",", "custom", ")", "{", "var", "resolvedPath", ";", "if", "(", "defaults", "===", "undefined", "||", "defaults", "[", "attr", "]", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'Missing Parameter'", ",", "'Expect a given defaults object'", ")", ";", "}", "if", "(", "attr", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'Missing Parameter'", ",", "'Expect a given attribute'", ")", ";", "}", "if", "(", "custom", "===", "undefined", "||", "custom", "[", "attr", "]", "===", "undefined", ")", "{", "resolvedPath", "=", "path", ".", "resolve", "(", "defaults", "[", "attr", "]", ")", ";", "}", "else", "{", "resolvedPath", "=", "path", ".", "resolve", "(", "custom", "[", "attr", "]", ")", ";", "}", "return", "resolvedPath", ";", "}" ]
Retrieving a resolved path from defaults or custom options @param {Object} defaults Fallback options @param {String} attr Attribute to be resolved @param {Object} custom Custom options @return {String} Resolved path from custom options or default if undefined
[ "Retrieving", "a", "resolved", "path", "from", "defaults", "or", "custom", "options" ]
e4c03f48c50c656990774d55494db966d3f8992f
https://github.com/alexander-heimbuch/utterson/blob/e4c03f48c50c656990774d55494db966d3f8992f/pipe/plumber.js#L21-L39
52,874
alexander-heimbuch/utterson
pipe/plumber.js
function (content, type) { var results = {}; if (content === undefined) { return results; } _.forEach(content, function (element, key) { if (element === undefined || element.type === undefined || element.type !== type) { return; } results[key] = element; }); return results; }
javascript
function (content, type) { var results = {}; if (content === undefined) { return results; } _.forEach(content, function (element, key) { if (element === undefined || element.type === undefined || element.type !== type) { return; } results[key] = element; }); return results; }
[ "function", "(", "content", ",", "type", ")", "{", "var", "results", "=", "{", "}", ";", "if", "(", "content", "===", "undefined", ")", "{", "return", "results", ";", "}", "_", ".", "forEach", "(", "content", ",", "function", "(", "element", ",", "key", ")", "{", "if", "(", "element", "===", "undefined", "||", "element", ".", "type", "===", "undefined", "||", "element", ".", "type", "!==", "type", ")", "{", "return", ";", "}", "results", "[", "key", "]", "=", "element", ";", "}", ")", ";", "return", "results", ";", "}" ]
Sorts out a given type of content containers from the pipe @param {Object} content Pipe content @param {String} type Type of content to sort out (e.g. Pages, Posts or Statics) @return {Object} Object containing only content containers from a given type
[ "Sorts", "out", "a", "given", "type", "of", "content", "containers", "from", "the", "pipe" ]
e4c03f48c50c656990774d55494db966d3f8992f
https://github.com/alexander-heimbuch/utterson/blob/e4c03f48c50c656990774d55494db966d3f8992f/pipe/plumber.js#L47-L63
52,875
alexander-heimbuch/utterson
pipe/plumber.js
function (content, type) { var results = []; if (content === undefined) { return results; } _.forEach(content, function (element) { if (element === undefined || element.type === undefined || element.type !== type) { return; } _.forEach(element.files, function (file) { var fragment = element[file]; // filter collection of posts, these are commonly category fragments if (fragment === undefined || fragment.posts !== undefined) { return; } results.push(fragment); }); }); return results; }
javascript
function (content, type) { var results = []; if (content === undefined) { return results; } _.forEach(content, function (element) { if (element === undefined || element.type === undefined || element.type !== type) { return; } _.forEach(element.files, function (file) { var fragment = element[file]; // filter collection of posts, these are commonly category fragments if (fragment === undefined || fragment.posts !== undefined) { return; } results.push(fragment); }); }); return results; }
[ "function", "(", "content", ",", "type", ")", "{", "var", "results", "=", "[", "]", ";", "if", "(", "content", "===", "undefined", ")", "{", "return", "results", ";", "}", "_", ".", "forEach", "(", "content", ",", "function", "(", "element", ")", "{", "if", "(", "element", "===", "undefined", "||", "element", ".", "type", "===", "undefined", "||", "element", ".", "type", "!==", "type", ")", "{", "return", ";", "}", "_", ".", "forEach", "(", "element", ".", "files", ",", "function", "(", "file", ")", "{", "var", "fragment", "=", "element", "[", "file", "]", ";", "// filter collection of posts, these are commonly category fragments", "if", "(", "fragment", "===", "undefined", "||", "fragment", ".", "posts", "!==", "undefined", ")", "{", "return", ";", "}", "results", ".", "push", "(", "fragment", ")", ";", "}", ")", ";", "}", ")", ";", "return", "results", ";", "}" ]
Filters a given type of content files from the pipe @param {Object} content Pipe content @param {String} type Type of content to sort out (e.g. Pages, Posts or Statics) @return {Array} Object containing single content files from a given type
[ "Filters", "a", "given", "type", "of", "content", "files", "from", "the", "pipe" ]
e4c03f48c50c656990774d55494db966d3f8992f
https://github.com/alexander-heimbuch/utterson/blob/e4c03f48c50c656990774d55494db966d3f8992f/pipe/plumber.js#L71-L95
52,876
alexander-heimbuch/utterson
pipe/plumber.js
function (file, parent, type) { var fileDetails = path.parse(file), filePath = (type === 'static') ? path.join(fileDetails.dir, fileDetails.name + fileDetails.ext) : path.join(fileDetails.dir, fileDetails.name); return { name: filePath, parentDir: parent, href: parent + filePath }; }
javascript
function (file, parent, type) { var fileDetails = path.parse(file), filePath = (type === 'static') ? path.join(fileDetails.dir, fileDetails.name + fileDetails.ext) : path.join(fileDetails.dir, fileDetails.name); return { name: filePath, parentDir: parent, href: parent + filePath }; }
[ "function", "(", "file", ",", "parent", ",", "type", ")", "{", "var", "fileDetails", "=", "path", ".", "parse", "(", "file", ")", ",", "filePath", "=", "(", "type", "===", "'static'", ")", "?", "path", ".", "join", "(", "fileDetails", ".", "dir", ",", "fileDetails", ".", "name", "+", "fileDetails", ".", "ext", ")", ":", "path", ".", "join", "(", "fileDetails", ".", "dir", ",", "fileDetails", ".", "name", ")", ";", "return", "{", "name", ":", "filePath", ",", "parentDir", ":", "parent", ",", "href", ":", "parent", "+", "filePath", "}", ";", "}" ]
Resolves relative parent and own name of a specific file @param {String} file Path to corresponding file @param {String} parent Parent relative to the corresponding file @param {String} type Type of the corresponding file [post, page, static] @return {Object} Object containing single content files from a given type
[ "Resolves", "relative", "parent", "and", "own", "name", "of", "a", "specific", "file" ]
e4c03f48c50c656990774d55494db966d3f8992f
https://github.com/alexander-heimbuch/utterson/blob/e4c03f48c50c656990774d55494db966d3f8992f/pipe/plumber.js#L104-L115
52,877
meltmedia/node-usher
lib/decider/tasks/accumulator.js
Accumulator
function Accumulator(name, deps, fragment, resultsFn, options) { if (!(this instanceof Accumulator)) { return new Accumulator(name, deps, fragment, resultsFn, options); } Task.apply(this, Array.prototype.slice.call(arguments)); this.fragment = fragment; if (!_.isFunction(resultsFn)) { throw new Error('You must provide a function to indicate when the accumulator is complete'); } this.resultsFn = resultsFn; this.options = options || {}; }
javascript
function Accumulator(name, deps, fragment, resultsFn, options) { if (!(this instanceof Accumulator)) { return new Accumulator(name, deps, fragment, resultsFn, options); } Task.apply(this, Array.prototype.slice.call(arguments)); this.fragment = fragment; if (!_.isFunction(resultsFn)) { throw new Error('You must provide a function to indicate when the accumulator is complete'); } this.resultsFn = resultsFn; this.options = options || {}; }
[ "function", "Accumulator", "(", "name", ",", "deps", ",", "fragment", ",", "resultsFn", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Accumulator", ")", ")", "{", "return", "new", "Accumulator", "(", "name", ",", "deps", ",", "fragment", ",", "resultsFn", ",", "options", ")", ";", "}", "Task", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "this", ".", "fragment", "=", "fragment", ";", "if", "(", "!", "_", ".", "isFunction", "(", "resultsFn", ")", ")", "{", "throw", "new", "Error", "(", "'You must provide a function to indicate when the accumulator is complete'", ")", ";", "}", "this", ".", "resultsFn", "=", "resultsFn", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "}" ]
The Accumulator loop executes the `fragment` until the `resultsFn` returns an empty array, the results of each execution are then pushed into an array via the `resultsFn` for use by other tasks. @constructor
[ "The", "Accumulator", "loop", "executes", "the", "fragment", "until", "the", "resultsFn", "returns", "an", "empty", "array", "the", "results", "of", "each", "execution", "are", "then", "pushed", "into", "an", "array", "via", "the", "resultsFn", "for", "use", "by", "other", "tasks", "." ]
fe6183bf7097f84bef935e8d9c19463accc08ad6
https://github.com/meltmedia/node-usher/blob/fe6183bf7097f84bef935e8d9c19463accc08ad6/lib/decider/tasks/accumulator.js#L26-L41
52,878
bigpipe/500-pagelet
index.js
constructor
function constructor(options, error, name) { Pagelet.prototype.constructor.call(this, options); if (name) this.name = name; this.data = error instanceof Error ? error : {}; }
javascript
function constructor(options, error, name) { Pagelet.prototype.constructor.call(this, options); if (name) this.name = name; this.data = error instanceof Error ? error : {}; }
[ "function", "constructor", "(", "options", ",", "error", ",", "name", ")", "{", "Pagelet", ".", "prototype", ".", "constructor", ".", "call", "(", "this", ",", "options", ")", ";", "if", "(", "name", ")", "this", ".", "name", "=", "name", ";", "this", ".", "data", "=", "error", "instanceof", "Error", "?", "error", ":", "{", "}", ";", "}" ]
Extend the default constructor to allow second data parameter. @param {Object} options Optional options. @param {Error} error Error data and stack. @param {String} name Pagelet name that the Error pagelet replaces. @api public
[ "Extend", "the", "default", "constructor", "to", "allow", "second", "data", "parameter", "." ]
cf0b3c46603064df50a16d86d6e78237d6f1f345
https://github.com/bigpipe/500-pagelet/blob/cf0b3c46603064df50a16d86d6e78237d6f1f345/index.js#L25-L30
52,879
bigpipe/500-pagelet
index.js
get
function get(render) { render(null, { env: this.env, message: this.data.message, stack: this.env !== 'production' ? this.data.stack : '' }); }
javascript
function get(render) { render(null, { env: this.env, message: this.data.message, stack: this.env !== 'production' ? this.data.stack : '' }); }
[ "function", "get", "(", "render", ")", "{", "render", "(", "null", ",", "{", "env", ":", "this", ".", "env", ",", "message", ":", "this", ".", "data", ".", "message", ",", "stack", ":", "this", ".", "env", "!==", "'production'", "?", "this", ".", "data", ".", "stack", ":", "''", "}", ")", ";", "}" ]
Return available data depending on environment settings. @param {Function} render Completion callback. @api private
[ "Return", "available", "data", "depending", "on", "environment", "settings", "." ]
cf0b3c46603064df50a16d86d6e78237d6f1f345
https://github.com/bigpipe/500-pagelet/blob/cf0b3c46603064df50a16d86d6e78237d6f1f345/index.js#L38-L44
52,880
damsonjs/damson-server-core
index.js
pushTask
function pushTask(client, task) { /*jshint validthis: true */ if (!this.tasks[client]) { this.tasks[client] = []; } this.tasks[client].push(task); }
javascript
function pushTask(client, task) { /*jshint validthis: true */ if (!this.tasks[client]) { this.tasks[client] = []; } this.tasks[client].push(task); }
[ "function", "pushTask", "(", "client", ",", "task", ")", "{", "/*jshint validthis: true */", "if", "(", "!", "this", ".", "tasks", "[", "client", "]", ")", "{", "this", ".", "tasks", "[", "client", "]", "=", "[", "]", ";", "}", "this", ".", "tasks", "[", "client", "]", ".", "push", "(", "task", ")", ";", "}" ]
Pushes task for client. @param {string} client Client identificator @param {object} task Task information @param {string} task.task_name Damson task name @param {object} task.options Damson task arguments @param {string} task.driver_name Damson driver name
[ "Pushes", "task", "for", "client", "." ]
4490d8140dc585b0e55b1beb8d6db013445bbc94
https://github.com/damsonjs/damson-server-core/blob/4490d8140dc585b0e55b1beb8d6db013445bbc94/index.js#L11-L17
52,881
sendanor/nor-nopg
src/Cache.js
Cache
function Cache(opts) { //debug.log('new Cache'); opts = opts || {}; debug.assert(opts).is('object'); /** {boolean} True if this cache is using cursors */ this._has_cursors = opts.cursors ? true : false; // All cursors in a VariableStore if(this._has_cursors) { this._cursors = new VariableStore(); this._parents = new VariableStore(); this._cursor_map = {}; } /** Store for all objects */ this.objects = new VariableStore(); /** Array of current parents of the element which we are scanning -- this is used to find circular references */ this._current_parents = []; /** Array of cursors pointing to circular references */ this.circulars = []; }
javascript
function Cache(opts) { //debug.log('new Cache'); opts = opts || {}; debug.assert(opts).is('object'); /** {boolean} True if this cache is using cursors */ this._has_cursors = opts.cursors ? true : false; // All cursors in a VariableStore if(this._has_cursors) { this._cursors = new VariableStore(); this._parents = new VariableStore(); this._cursor_map = {}; } /** Store for all objects */ this.objects = new VariableStore(); /** Array of current parents of the element which we are scanning -- this is used to find circular references */ this._current_parents = []; /** Array of cursors pointing to circular references */ this.circulars = []; }
[ "function", "Cache", "(", "opts", ")", "{", "//debug.log('new Cache');", "opts", "=", "opts", "||", "{", "}", ";", "debug", ".", "assert", "(", "opts", ")", ".", "is", "(", "'object'", ")", ";", "/** {boolean} True if this cache is using cursors */", "this", ".", "_has_cursors", "=", "opts", ".", "cursors", "?", "true", ":", "false", ";", "// All cursors in a VariableStore", "if", "(", "this", ".", "_has_cursors", ")", "{", "this", ".", "_cursors", "=", "new", "VariableStore", "(", ")", ";", "this", ".", "_parents", "=", "new", "VariableStore", "(", ")", ";", "this", ".", "_cursor_map", "=", "{", "}", ";", "}", "/** Store for all objects */", "this", ".", "objects", "=", "new", "VariableStore", "(", ")", ";", "/** Array of current parents of the element which we are scanning -- this is used to find circular references */", "this", ".", "_current_parents", "=", "[", "]", ";", "/** Array of cursors pointing to circular references */", "this", ".", "circulars", "=", "[", "]", ";", "}" ]
The cache object
[ "The", "cache", "object" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/Cache.js#L11-L36
52,882
vkiding/judpack-lib
src/plugman/platforms/common.js
function(plugin_dir, src, project_dir, dest, link) { var target_path = common.resolveTargetPath(project_dir, dest); if (fs.existsSync(target_path)) throw new Error('"' + target_path + '" already exists!'); common.copyFile(plugin_dir, src, project_dir, dest, !!link); }
javascript
function(plugin_dir, src, project_dir, dest, link) { var target_path = common.resolveTargetPath(project_dir, dest); if (fs.existsSync(target_path)) throw new Error('"' + target_path + '" already exists!'); common.copyFile(plugin_dir, src, project_dir, dest, !!link); }
[ "function", "(", "plugin_dir", ",", "src", ",", "project_dir", ",", "dest", ",", "link", ")", "{", "var", "target_path", "=", "common", ".", "resolveTargetPath", "(", "project_dir", ",", "dest", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "target_path", ")", ")", "throw", "new", "Error", "(", "'\"'", "+", "target_path", "+", "'\" already exists!'", ")", ";", "common", ".", "copyFile", "(", "plugin_dir", ",", "src", ",", "project_dir", ",", "dest", ",", "!", "!", "link", ")", ";", "}" ]
Same as copy file but throws error if target exists
[ "Same", "as", "copy", "file", "but", "throws", "error", "if", "target", "exists" ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/plugman/platforms/common.js#L96-L102
52,883
manvalls/iku-hub
server.js
Peer
function Peer(internalPeer){ Emitter.Target.call(this,emitter); this[rooms] = {}; this[pids] = {}; this[ip] = internalPeer; plugins.give('peer',this); }
javascript
function Peer(internalPeer){ Emitter.Target.call(this,emitter); this[rooms] = {}; this[pids] = {}; this[ip] = internalPeer; plugins.give('peer',this); }
[ "function", "Peer", "(", "internalPeer", ")", "{", "Emitter", ".", "Target", ".", "call", "(", "this", ",", "emitter", ")", ";", "this", "[", "rooms", "]", "=", "{", "}", ";", "this", "[", "pids", "]", "=", "{", "}", ";", "this", "[", "ip", "]", "=", "internalPeer", ";", "plugins", ".", "give", "(", "'peer'", ",", "this", ")", ";", "}" ]
External Peer object
[ "External", "Peer", "object" ]
ce7bf254e05f9e901b61bb0370cfa0b8f21a56aa
https://github.com/manvalls/iku-hub/blob/ce7bf254e05f9e901b61bb0370cfa0b8f21a56aa/server.js#L484-L492
52,884
redisjs/jsr-server
lib/info.js
Info
function Info(state) { this.state = state; this.conf = state.conf; this.stats = state.stats; this.name = pkg.name; this.version = pkg.version; }
javascript
function Info(state) { this.state = state; this.conf = state.conf; this.stats = state.stats; this.name = pkg.name; this.version = pkg.version; }
[ "function", "Info", "(", "state", ")", "{", "this", ".", "state", "=", "state", ";", "this", ".", "conf", "=", "state", ".", "conf", ";", "this", ".", "stats", "=", "state", ".", "stats", ";", "this", ".", "name", "=", "pkg", ".", "name", ";", "this", ".", "version", "=", "pkg", ".", "version", ";", "}" ]
Encapsulates server information.
[ "Encapsulates", "server", "information", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/info.js#L32-L38
52,885
redisjs/jsr-server
lib/info.js
getServer
function getServer() { var o = {} , uptime = process.uptime() o.version = this.version; o.os = process.platform; o.arch = process.arch; o.process_id = process.pid; o.tcp_port = this.state.addr && this.state.addr.port ? this.state.addr.port : NA; o.uptime_in_seconds = uptime; o.uptime_in_days = Math.floor(uptime / DAY_SECS); o.hz = this.conf.get(ConfigKey.HZ); o.config_file = this.conf.isDefault() ? '' : this.conf.getFile(); return o; }
javascript
function getServer() { var o = {} , uptime = process.uptime() o.version = this.version; o.os = process.platform; o.arch = process.arch; o.process_id = process.pid; o.tcp_port = this.state.addr && this.state.addr.port ? this.state.addr.port : NA; o.uptime_in_seconds = uptime; o.uptime_in_days = Math.floor(uptime / DAY_SECS); o.hz = this.conf.get(ConfigKey.HZ); o.config_file = this.conf.isDefault() ? '' : this.conf.getFile(); return o; }
[ "function", "getServer", "(", ")", "{", "var", "o", "=", "{", "}", ",", "uptime", "=", "process", ".", "uptime", "(", ")", "o", ".", "version", "=", "this", ".", "version", ";", "o", ".", "os", "=", "process", ".", "platform", ";", "o", ".", "arch", "=", "process", ".", "arch", ";", "o", ".", "process_id", "=", "process", ".", "pid", ";", "o", ".", "tcp_port", "=", "this", ".", "state", ".", "addr", "&&", "this", ".", "state", ".", "addr", ".", "port", "?", "this", ".", "state", ".", "addr", ".", "port", ":", "NA", ";", "o", ".", "uptime_in_seconds", "=", "uptime", ";", "o", ".", "uptime_in_days", "=", "Math", ".", "floor", "(", "uptime", "/", "DAY_SECS", ")", ";", "o", ".", "hz", "=", "this", ".", "conf", ".", "get", "(", "ConfigKey", ".", "HZ", ")", ";", "o", ".", "config_file", "=", "this", ".", "conf", ".", "isDefault", "(", ")", "?", "''", ":", "this", ".", "conf", ".", "getFile", "(", ")", ";", "return", "o", ";", "}" ]
Get server info section.
[ "Get", "server", "info", "section", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/info.js#L57-L73
52,886
redisjs/jsr-server
lib/info.js
getMemory
function getMemory(rusage) { var o = {}, mem = process.memoryUsage(); o.used_memory = mem.heapUsed; o.used_memory_human = bytes.humanize(mem.heapUsed, 2, true); o.used_memory_rss = mem.rss; o.used_memory_peak = rusage.maxrss; o.used_memory_peak_human = bytes.humanize(rusage.maxrss, 2, true); return o; }
javascript
function getMemory(rusage) { var o = {}, mem = process.memoryUsage(); o.used_memory = mem.heapUsed; o.used_memory_human = bytes.humanize(mem.heapUsed, 2, true); o.used_memory_rss = mem.rss; o.used_memory_peak = rusage.maxrss; o.used_memory_peak_human = bytes.humanize(rusage.maxrss, 2, true); return o; }
[ "function", "getMemory", "(", "rusage", ")", "{", "var", "o", "=", "{", "}", ",", "mem", "=", "process", ".", "memoryUsage", "(", ")", ";", "o", ".", "used_memory", "=", "mem", ".", "heapUsed", ";", "o", ".", "used_memory_human", "=", "bytes", ".", "humanize", "(", "mem", ".", "heapUsed", ",", "2", ",", "true", ")", ";", "o", ".", "used_memory_rss", "=", "mem", ".", "rss", ";", "o", ".", "used_memory_peak", "=", "rusage", ".", "maxrss", ";", "o", ".", "used_memory_peak_human", "=", "bytes", ".", "humanize", "(", "rusage", ".", "maxrss", ",", "2", ",", "true", ")", ";", "return", "o", ";", "}" ]
Get memory info section.
[ "Get", "memory", "info", "section", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/info.js#L87-L95
52,887
redisjs/jsr-server
lib/info.js
getStats
function getStats() { var o = {}; o.total_connections_received = this.stats.connections; o.total_commands_processed = this.stats.commands; o.total_net_input_bytes = this.stats.ibytes; o.total_net_output_bytes = this.stats.obytes; o.rejected_connections = this.stats.rejected; o.expired_keys = this.stats.expired; o.keyspace_hits = this.stats.hits; o.keyspace_misses = this.stats.misses; o.pubsub_channels = this.stats.pubsub_channels; o.pubsub_patterns = this.stats.pubsub_patterns; return o; }
javascript
function getStats() { var o = {}; o.total_connections_received = this.stats.connections; o.total_commands_processed = this.stats.commands; o.total_net_input_bytes = this.stats.ibytes; o.total_net_output_bytes = this.stats.obytes; o.rejected_connections = this.stats.rejected; o.expired_keys = this.stats.expired; o.keyspace_hits = this.stats.hits; o.keyspace_misses = this.stats.misses; o.pubsub_channels = this.stats.pubsub_channels; o.pubsub_patterns = this.stats.pubsub_patterns; return o; }
[ "function", "getStats", "(", ")", "{", "var", "o", "=", "{", "}", ";", "o", ".", "total_connections_received", "=", "this", ".", "stats", ".", "connections", ";", "o", ".", "total_commands_processed", "=", "this", ".", "stats", ".", "commands", ";", "o", ".", "total_net_input_bytes", "=", "this", ".", "stats", ".", "ibytes", ";", "o", ".", "total_net_output_bytes", "=", "this", ".", "stats", ".", "obytes", ";", "o", ".", "rejected_connections", "=", "this", ".", "stats", ".", "rejected", ";", "o", ".", "expired_keys", "=", "this", ".", "stats", ".", "expired", ";", "o", ".", "keyspace_hits", "=", "this", ".", "stats", ".", "hits", ";", "o", ".", "keyspace_misses", "=", "this", ".", "stats", ".", "misses", ";", "o", ".", "pubsub_channels", "=", "this", ".", "stats", ".", "pubsub_channels", ";", "o", ".", "pubsub_patterns", "=", "this", ".", "stats", ".", "pubsub_patterns", ";", "return", "o", ";", "}" ]
Get stats info section.
[ "Get", "stats", "info", "section", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/info.js#L108-L125
52,888
redisjs/jsr-server
lib/info.js
getCpu
function getCpu(rusage) { var o = {}; //console.dir(rusage); o.used_cpu_sys = rusage.stime.toFixed(2); o.used_cpu_user = rusage.utime.toFixed(2); return o; }
javascript
function getCpu(rusage) { var o = {}; //console.dir(rusage); o.used_cpu_sys = rusage.stime.toFixed(2); o.used_cpu_user = rusage.utime.toFixed(2); return o; }
[ "function", "getCpu", "(", "rusage", ")", "{", "var", "o", "=", "{", "}", ";", "//console.dir(rusage);", "o", ".", "used_cpu_sys", "=", "rusage", ".", "stime", ".", "toFixed", "(", "2", ")", ";", "o", ".", "used_cpu_user", "=", "rusage", ".", "utime", ".", "toFixed", "(", "2", ")", ";", "return", "o", ";", "}" ]
Get cpu info section.
[ "Get", "cpu", "info", "section", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/info.js#L138-L144
52,889
redisjs/jsr-server
lib/info.js
getKeyspace
function getKeyspace() { var o = {} , i , db , size; for(i in this.state.store.databases) { db = this.state.store.databases[i]; size = db.dbsize(); if(size) { o['db' + i] = util.format('keys=%s,expires=%s', size, db.expiring); } } return o; }
javascript
function getKeyspace() { var o = {} , i , db , size; for(i in this.state.store.databases) { db = this.state.store.databases[i]; size = db.dbsize(); if(size) { o['db' + i] = util.format('keys=%s,expires=%s', size, db.expiring); } } return o; }
[ "function", "getKeyspace", "(", ")", "{", "var", "o", "=", "{", "}", ",", "i", ",", "db", ",", "size", ";", "for", "(", "i", "in", "this", ".", "state", ".", "store", ".", "databases", ")", "{", "db", "=", "this", ".", "state", ".", "store", ".", "databases", "[", "i", "]", ";", "size", "=", "db", ".", "dbsize", "(", ")", ";", "if", "(", "size", ")", "{", "o", "[", "'db'", "+", "i", "]", "=", "util", ".", "format", "(", "'keys=%s,expires=%s'", ",", "size", ",", "db", ".", "expiring", ")", ";", "}", "}", "return", "o", ";", "}" ]
Get keyspace info section.
[ "Get", "keyspace", "info", "section", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/info.js#L149-L162
52,890
redisjs/jsr-server
lib/info.js
getObject
function getObject(section) { var o = {} , i , k , name , method , sections = section ? [section] : keys , rusage = proc.usage(); for(i = 0;i < sections.length;i++) { k = sections[i]; name = k.charAt(0).toUpperCase() + k.substr(1); method = 'get' + name o[k] = { header: name, data: this[method](rusage) } } return o; }
javascript
function getObject(section) { var o = {} , i , k , name , method , sections = section ? [section] : keys , rusage = proc.usage(); for(i = 0;i < sections.length;i++) { k = sections[i]; name = k.charAt(0).toUpperCase() + k.substr(1); method = 'get' + name o[k] = { header: name, data: this[method](rusage) } } return o; }
[ "function", "getObject", "(", "section", ")", "{", "var", "o", "=", "{", "}", ",", "i", ",", "k", ",", "name", ",", "method", ",", "sections", "=", "section", "?", "[", "section", "]", ":", "keys", ",", "rusage", "=", "proc", ".", "usage", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "sections", ".", "length", ";", "i", "++", ")", "{", "k", "=", "sections", "[", "i", "]", ";", "name", "=", "k", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "k", ".", "substr", "(", "1", ")", ";", "method", "=", "'get'", "+", "name", "o", "[", "k", "]", "=", "{", "header", ":", "name", ",", "data", ":", "this", "[", "method", "]", "(", "rusage", ")", "}", "}", "return", "o", ";", "}" ]
Get an info object.
[ "Get", "an", "info", "object", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/info.js#L174-L193
52,891
redisjs/jsr-server
lib/command/server/time.js
execute
function execute(req, res) { var t = systime(); res.send(null, [t.s, t.m]); }
javascript
function execute(req, res) { var t = systime(); res.send(null, [t.s, t.m]); }
[ "function", "execute", "(", "req", ",", "res", ")", "{", "var", "t", "=", "systime", "(", ")", ";", "res", ".", "send", "(", "null", ",", "[", "t", ".", "s", ",", "t", ".", "m", "]", ")", ";", "}" ]
Respond to the TIME command.
[ "Respond", "to", "the", "TIME", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/server/time.js#L18-L21
52,892
Becklyn/becklyn-gulp
lib/path-helper.js
function (filePath) { if (0 === filePath.indexOf(process.cwd())) { filePath = path.relative(process.cwd(), filePath); } if (0 !== filePath.indexOf("./") && 0 !== filePath.indexOf("/")) { filePath = "./" + filePath; } return filePath; }
javascript
function (filePath) { if (0 === filePath.indexOf(process.cwd())) { filePath = path.relative(process.cwd(), filePath); } if (0 !== filePath.indexOf("./") && 0 !== filePath.indexOf("/")) { filePath = "./" + filePath; } return filePath; }
[ "function", "(", "filePath", ")", "{", "if", "(", "0", "===", "filePath", ".", "indexOf", "(", "process", ".", "cwd", "(", ")", ")", ")", "{", "filePath", "=", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "filePath", ")", ";", "}", "if", "(", "0", "!==", "filePath", ".", "indexOf", "(", "\"./\"", ")", "&&", "0", "!==", "filePath", ".", "indexOf", "(", "\"/\"", ")", ")", "{", "filePath", "=", "\"./\"", "+", "filePath", ";", "}", "return", "filePath", ";", "}" ]
Makes the file path relative @param {string} filePath @returns {string}
[ "Makes", "the", "file", "path", "relative" ]
1c633378d561f07101f9db19ccd153617b8e0252
https://github.com/Becklyn/becklyn-gulp/blob/1c633378d561f07101f9db19ccd153617b8e0252/lib/path-helper.js#L13-L26
52,893
Chieze-Franklin/bolt-internal-utils
utils-cov.js
function(body, error, code, errorTraceId, errorUserTitle, errorUserMessage) { _$jscmd("utils.js", "line", 104); //TODO: support errorTraceId //TODO: errorUserTitle and errorUserMessage should be change from strings to ints (==code) to support localization var response = {}; //set code if (_$jscmd("utils.js", "cond", "107_7_26", !__isNullOrUndefined(code))) { _$jscmd("utils.js", "line", 108); response.code = code; } else { if (_$jscmd("utils.js", "cond", "111_8_26", !__isNullOrUndefined(body))) response.code = 0; else //if (!__isNullOrUndefined(error)) response.code = 1e3; } //set body if (_$jscmd("utils.js", "cond", "118_7_26", !__isNullOrUndefined(body))) response.body = body; //set error if (_$jscmd("utils.js", "cond", "122_7_27", !__isNullOrUndefined(error))) { _$jscmd("utils.js", "line", 123); response.error = error; //set errorTraceId if (_$jscmd("utils.js", "cond", "126_8_34", !__isNullOrUndefined(errorTraceId))) response.errorTraceId = errorTraceId; //set errorUserTitle if (_$jscmd("utils.js", "cond", "130_8_36", !__isNullOrUndefined(errorUserTitle))) response.errorUserTitle = errorUserTitle; else { _$jscmd("utils.js", "line", 134); //TODO: this is not the real implementation response.errorUserTitle = "Bolt Error " + response.code.toString(); } //set errorUserMessage if (_$jscmd("utils.js", "cond", "138_8_38", !__isNullOrUndefined(errorUserMessage))) response.errorUserMessage = errorUserMessage; else { _$jscmd("utils.js", "line", 142); //TODO: this is not the real implementation response.errorUserMessage = errors[response.code]; } } _$jscmd("utils.js", "line", 146); return JSON.stringify(response); }
javascript
function(body, error, code, errorTraceId, errorUserTitle, errorUserMessage) { _$jscmd("utils.js", "line", 104); //TODO: support errorTraceId //TODO: errorUserTitle and errorUserMessage should be change from strings to ints (==code) to support localization var response = {}; //set code if (_$jscmd("utils.js", "cond", "107_7_26", !__isNullOrUndefined(code))) { _$jscmd("utils.js", "line", 108); response.code = code; } else { if (_$jscmd("utils.js", "cond", "111_8_26", !__isNullOrUndefined(body))) response.code = 0; else //if (!__isNullOrUndefined(error)) response.code = 1e3; } //set body if (_$jscmd("utils.js", "cond", "118_7_26", !__isNullOrUndefined(body))) response.body = body; //set error if (_$jscmd("utils.js", "cond", "122_7_27", !__isNullOrUndefined(error))) { _$jscmd("utils.js", "line", 123); response.error = error; //set errorTraceId if (_$jscmd("utils.js", "cond", "126_8_34", !__isNullOrUndefined(errorTraceId))) response.errorTraceId = errorTraceId; //set errorUserTitle if (_$jscmd("utils.js", "cond", "130_8_36", !__isNullOrUndefined(errorUserTitle))) response.errorUserTitle = errorUserTitle; else { _$jscmd("utils.js", "line", 134); //TODO: this is not the real implementation response.errorUserTitle = "Bolt Error " + response.code.toString(); } //set errorUserMessage if (_$jscmd("utils.js", "cond", "138_8_38", !__isNullOrUndefined(errorUserMessage))) response.errorUserMessage = errorUserMessage; else { _$jscmd("utils.js", "line", 142); //TODO: this is not the real implementation response.errorUserMessage = errors[response.code]; } } _$jscmd("utils.js", "line", 146); return JSON.stringify(response); }
[ "function", "(", "body", ",", "error", ",", "code", ",", "errorTraceId", ",", "errorUserTitle", ",", "errorUserMessage", ")", "{", "_$jscmd", "(", "\"utils.js\"", ",", "\"line\"", ",", "104", ")", ";", "//TODO: support errorTraceId", "//TODO: errorUserTitle and errorUserMessage should be change from strings to ints (==code) to support localization", "var", "response", "=", "{", "}", ";", "//set code", "if", "(", "_$jscmd", "(", "\"utils.js\"", ",", "\"cond\"", ",", "\"107_7_26\"", ",", "!", "__isNullOrUndefined", "(", "code", ")", ")", ")", "{", "_$jscmd", "(", "\"utils.js\"", ",", "\"line\"", ",", "108", ")", ";", "response", ".", "code", "=", "code", ";", "}", "else", "{", "if", "(", "_$jscmd", "(", "\"utils.js\"", ",", "\"cond\"", ",", "\"111_8_26\"", ",", "!", "__isNullOrUndefined", "(", "body", ")", ")", ")", "response", ".", "code", "=", "0", ";", "else", "//if (!__isNullOrUndefined(error))", "response", ".", "code", "=", "1e3", ";", "}", "//set body", "if", "(", "_$jscmd", "(", "\"utils.js\"", ",", "\"cond\"", ",", "\"118_7_26\"", ",", "!", "__isNullOrUndefined", "(", "body", ")", ")", ")", "response", ".", "body", "=", "body", ";", "//set error", "if", "(", "_$jscmd", "(", "\"utils.js\"", ",", "\"cond\"", ",", "\"122_7_27\"", ",", "!", "__isNullOrUndefined", "(", "error", ")", ")", ")", "{", "_$jscmd", "(", "\"utils.js\"", ",", "\"line\"", ",", "123", ")", ";", "response", ".", "error", "=", "error", ";", "//set errorTraceId", "if", "(", "_$jscmd", "(", "\"utils.js\"", ",", "\"cond\"", ",", "\"126_8_34\"", ",", "!", "__isNullOrUndefined", "(", "errorTraceId", ")", ")", ")", "response", ".", "errorTraceId", "=", "errorTraceId", ";", "//set errorUserTitle", "if", "(", "_$jscmd", "(", "\"utils.js\"", ",", "\"cond\"", ",", "\"130_8_36\"", ",", "!", "__isNullOrUndefined", "(", "errorUserTitle", ")", ")", ")", "response", ".", "errorUserTitle", "=", "errorUserTitle", ";", "else", "{", "_$jscmd", "(", "\"utils.js\"", ",", "\"line\"", ",", "134", ")", ";", "//TODO: this is not the real implementation", "response", ".", "errorUserTitle", "=", "\"Bolt Error \"", "+", "response", ".", "code", ".", "toString", "(", ")", ";", "}", "//set errorUserMessage", "if", "(", "_$jscmd", "(", "\"utils.js\"", ",", "\"cond\"", ",", "\"138_8_38\"", ",", "!", "__isNullOrUndefined", "(", "errorUserMessage", ")", ")", ")", "response", ".", "errorUserMessage", "=", "errorUserMessage", ";", "else", "{", "_$jscmd", "(", "\"utils.js\"", ",", "\"line\"", ",", "142", ")", ";", "//TODO: this is not the real implementation", "response", ".", "errorUserMessage", "=", "errors", "[", "response", ".", "code", "]", ";", "}", "}", "_$jscmd", "(", "\"utils.js\"", ",", "\"line\"", ",", "146", ")", ";", "return", "JSON", ".", "stringify", "(", "response", ")", ";", "}" ]
constructs an appropriate response object
[ "constructs", "an", "appropriate", "response", "object" ]
4d250d2384f1a02ac0b9994e5341f0829bf4c683
https://github.com/Chieze-Franklin/bolt-internal-utils/blob/4d250d2384f1a02ac0b9994e5341f0829bf4c683/utils-cov.js#L201-L237
52,894
ottojs/otto-errors
lib/not_found.error.js
ErrorNotFound
function ErrorNotFound (message, data) { Error.call(this); // Add Information this.name = 'ErrorNotFound'; this.type = 'client'; this.status = 404; if (message) { this.message = message; } if (data) { this.data = {}; if (data.method) { this.data.method = data.method; } if (data.path) { this.data.path = data.path; } } }
javascript
function ErrorNotFound (message, data) { Error.call(this); // Add Information this.name = 'ErrorNotFound'; this.type = 'client'; this.status = 404; if (message) { this.message = message; } if (data) { this.data = {}; if (data.method) { this.data.method = data.method; } if (data.path) { this.data.path = data.path; } } }
[ "function", "ErrorNotFound", "(", "message", ",", "data", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "// Add Information", "this", ".", "name", "=", "'ErrorNotFound'", ";", "this", ".", "type", "=", "'client'", ";", "this", ".", "status", "=", "404", ";", "if", "(", "message", ")", "{", "this", ".", "message", "=", "message", ";", "}", "if", "(", "data", ")", "{", "this", ".", "data", "=", "{", "}", ";", "if", "(", "data", ".", "method", ")", "{", "this", ".", "data", ".", "method", "=", "data", ".", "method", ";", "}", "if", "(", "data", ".", "path", ")", "{", "this", ".", "data", ".", "path", "=", "data", ".", "path", ";", "}", "}", "}" ]
Error - ErrorNotFound
[ "Error", "-", "ErrorNotFound" ]
a3c6d98fd5d35ce3c136ed7e1edd2f800af268d9
https://github.com/ottojs/otto-errors/blob/a3c6d98fd5d35ce3c136ed7e1edd2f800af268d9/lib/not_found.error.js#L8-L27
52,895
andrewscwei/requiem
src/dom/hasChild.js
hasChild
function hasChild(child, element) { assert(child !== undefined, 'Child is undefined'); assertType(element, Node, true, 'Parameter \'element\', if specified, must be a Node'); if (typeof child === 'string') { return !noval(getChild(element, child, true)); } else { if (!element || element === window || element === document) element = document.body; if (element.shadowRoot) element = element.shadowRoot; while (!noval(child) && child !== document) { child = child.parentNode; if (child === element) return true; } return false; } }
javascript
function hasChild(child, element) { assert(child !== undefined, 'Child is undefined'); assertType(element, Node, true, 'Parameter \'element\', if specified, must be a Node'); if (typeof child === 'string') { return !noval(getChild(element, child, true)); } else { if (!element || element === window || element === document) element = document.body; if (element.shadowRoot) element = element.shadowRoot; while (!noval(child) && child !== document) { child = child.parentNode; if (child === element) return true; } return false; } }
[ "function", "hasChild", "(", "child", ",", "element", ")", "{", "assert", "(", "child", "!==", "undefined", ",", "'Child is undefined'", ")", ";", "assertType", "(", "element", ",", "Node", ",", "true", ",", "'Parameter \\'element\\', if specified, must be a Node'", ")", ";", "if", "(", "typeof", "child", "===", "'string'", ")", "{", "return", "!", "noval", "(", "getChild", "(", "element", ",", "child", ",", "true", ")", ")", ";", "}", "else", "{", "if", "(", "!", "element", "||", "element", "===", "window", "||", "element", "===", "document", ")", "element", "=", "document", ".", "body", ";", "if", "(", "element", ".", "shadowRoot", ")", "element", "=", "element", ".", "shadowRoot", ";", "while", "(", "!", "noval", "(", "child", ")", "&&", "child", "!==", "document", ")", "{", "child", "=", "child", ".", "parentNode", ";", "if", "(", "child", "===", "element", ")", "return", "true", ";", "}", "return", "false", ";", "}", "}" ]
Determines if an element contains the specified child. @param {Node|string} child - A child is a Node. It can also be a string of child name(s) separated by '.'. @param {Node} [element] - Specifies the parent Node to fetch the child from. @return {boolean} True if this element has the specified child, false otherwise. @alias module:requiem~dom.hasChild
[ "Determines", "if", "an", "element", "contains", "the", "specified", "child", "." ]
c4182bfffc9841c6de5718f689ad3c2060511777
https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/dom/hasChild.js#L22-L40
52,896
9fv/node-is-port-reachable
.gulp/tasks/lint.js
lint
function lint(p) { return () => { gulp.src(p).pipe(g.eslint()) .pipe(g.eslint.format()) .pipe(g.eslint.failOnError()); }; }
javascript
function lint(p) { return () => { gulp.src(p).pipe(g.eslint()) .pipe(g.eslint.format()) .pipe(g.eslint.failOnError()); }; }
[ "function", "lint", "(", "p", ")", "{", "return", "(", ")", "=>", "{", "gulp", ".", "src", "(", "p", ")", ".", "pipe", "(", "g", ".", "eslint", "(", ")", ")", ".", "pipe", "(", "g", ".", "eslint", ".", "format", "(", ")", ")", ".", "pipe", "(", "g", ".", "eslint", ".", "failOnError", "(", ")", ")", ";", "}", ";", "}" ]
Lint source. @param p {string} - Path and pattern. @returns {void|*}
[ "Lint", "source", "." ]
5c0c325b2f10255616603ee85900faa83bfb7834
https://github.com/9fv/node-is-port-reachable/blob/5c0c325b2f10255616603ee85900faa83bfb7834/.gulp/tasks/lint.js#L13-L19
52,897
rkamradt/meta-app-mongo
index.js
function(data, done) { if(!this._key) { done('no key found for metadata'); return; } var key = data[this._key]; var self = this; this._getCollection(function(err) { if(err) { done(err); } var kobj = {}; kobj[self._key.getName()] = key; self._collection.find(kobj).toArray(function(err, docs) { if(docs.length > 0) { data._id = docs[0]._id; } self._collection.save(data, function(err, count) { self._db.close(); done(err); }); }); }); }
javascript
function(data, done) { if(!this._key) { done('no key found for metadata'); return; } var key = data[this._key]; var self = this; this._getCollection(function(err) { if(err) { done(err); } var kobj = {}; kobj[self._key.getName()] = key; self._collection.find(kobj).toArray(function(err, docs) { if(docs.length > 0) { data._id = docs[0]._id; } self._collection.save(data, function(err, count) { self._db.close(); done(err); }); }); }); }
[ "function", "(", "data", ",", "done", ")", "{", "if", "(", "!", "this", ".", "_key", ")", "{", "done", "(", "'no key found for metadata'", ")", ";", "return", ";", "}", "var", "key", "=", "data", "[", "this", ".", "_key", "]", ";", "var", "self", "=", "this", ";", "this", ".", "_getCollection", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "done", "(", "err", ")", ";", "}", "var", "kobj", "=", "{", "}", ";", "kobj", "[", "self", ".", "_key", ".", "getName", "(", ")", "]", "=", "key", ";", "self", ".", "_collection", ".", "find", "(", "kobj", ")", ".", "toArray", "(", "function", "(", "err", ",", "docs", ")", "{", "if", "(", "docs", ".", "length", ">", "0", ")", "{", "data", ".", "_id", "=", "docs", "[", "0", "]", ".", "_id", ";", "}", "self", ".", "_collection", ".", "save", "(", "data", ",", "function", "(", "err", ",", "count", ")", "{", "self", ".", "_db", ".", "close", "(", ")", ";", "done", "(", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
update an item by id @param {String} data The new data @param {Function} done The callback when done
[ "update", "an", "item", "by", "id" ]
330cc805e1547b59e228e179ef0962def7d9f32c
https://github.com/rkamradt/meta-app-mongo/blob/330cc805e1547b59e228e179ef0962def7d9f32c/index.js#L135-L158
52,898
rkamradt/meta-app-mongo
index.js
function(key, done) { if(!this._key) { done('no key found for metadata'); return; } var self = this; this._getCollection(function(err) { if(err) { done(err); } var kobj = {}; kobj[self._key.getName()] = key; self._collection.find(kobj).toArray(function(err, docs) { var ret; if(!err && docs.length !== 0) { ret = docs[0]; } self._collection.remove(kobj, function(err, result) { self._db.close(); done(err, ret); }); }); }); }
javascript
function(key, done) { if(!this._key) { done('no key found for metadata'); return; } var self = this; this._getCollection(function(err) { if(err) { done(err); } var kobj = {}; kobj[self._key.getName()] = key; self._collection.find(kobj).toArray(function(err, docs) { var ret; if(!err && docs.length !== 0) { ret = docs[0]; } self._collection.remove(kobj, function(err, result) { self._db.close(); done(err, ret); }); }); }); }
[ "function", "(", "key", ",", "done", ")", "{", "if", "(", "!", "this", ".", "_key", ")", "{", "done", "(", "'no key found for metadata'", ")", ";", "return", ";", "}", "var", "self", "=", "this", ";", "this", ".", "_getCollection", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "done", "(", "err", ")", ";", "}", "var", "kobj", "=", "{", "}", ";", "kobj", "[", "self", ".", "_key", ".", "getName", "(", ")", "]", "=", "key", ";", "self", ".", "_collection", ".", "find", "(", "kobj", ")", ".", "toArray", "(", "function", "(", "err", ",", "docs", ")", "{", "var", "ret", ";", "if", "(", "!", "err", "&&", "docs", ".", "length", "!==", "0", ")", "{", "ret", "=", "docs", "[", "0", "]", ";", "}", "self", ".", "_collection", ".", "remove", "(", "kobj", ",", "function", "(", "err", ",", "result", ")", "{", "self", ".", "_db", ".", "close", "(", ")", ";", "done", "(", "err", ",", "ret", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Remove an item by key @param {String} key The key value @param {Function} done The callback when done
[ "Remove", "an", "item", "by", "key" ]
330cc805e1547b59e228e179ef0962def7d9f32c
https://github.com/rkamradt/meta-app-mongo/blob/330cc805e1547b59e228e179ef0962def7d9f32c/index.js#L164-L187
52,899
tx4x/git-module
lib/modules.js
addRepository
function addRepository(name, rep, directory, gitOptions, options) { var userConfig = options || {}; REPOSITORIES.push(_.extend({ name: name, options: _.extend({ repository: rep, directory: directory || name }, gitOptions || {}) }, userConfig)); }
javascript
function addRepository(name, rep, directory, gitOptions, options) { var userConfig = options || {}; REPOSITORIES.push(_.extend({ name: name, options: _.extend({ repository: rep, directory: directory || name }, gitOptions || {}) }, userConfig)); }
[ "function", "addRepository", "(", "name", ",", "rep", ",", "directory", ",", "gitOptions", ",", "options", ")", "{", "var", "userConfig", "=", "options", "||", "{", "}", ";", "REPOSITORIES", ".", "push", "(", "_", ".", "extend", "(", "{", "name", ":", "name", ",", "options", ":", "_", ".", "extend", "(", "{", "repository", ":", "rep", ",", "directory", ":", "directory", "||", "name", "}", ",", "gitOptions", "||", "{", "}", ")", "}", ",", "userConfig", ")", ")", ";", "}" ]
Helper function to add a new repo to our module list. @param name {string} That is the unique name of the module. @param rep {string} The repository url. @param directory {null|string} The target directory to clone the module into. @param gitOptions {null|object} A mixin to override default git options for the module added. @param options {null|object} A mixin to override default options for the module added.
[ "Helper", "function", "to", "add", "a", "new", "repo", "to", "our", "module", "list", "." ]
93ff14eecb00c5c140f3e6413bd43404cc1dd021
https://github.com/tx4x/git-module/blob/93ff14eecb00c5c140f3e6413bd43404cc1dd021/lib/modules.js#L44-L54