repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
angular/gulp-clang-format
index.js
checkFormat
function checkFormat(opt_clangOptions, opt_clangFormat, opt_gulpOptions) { var optsStr = getOptsString(opt_clangOptions); var actualClangFormat = opt_clangFormat || clangFormat; opt_gulpOptions = opt_gulpOptions || {}; var filePaths = []; var pipe = combine.obj(format(opt_clangOptions, opt_clangFormat), diff()); if (opt_gulpOptions.verbose) { pipe = combine.obj(pipe, diff.reporter({fail: false})); } pipe = combine.obj( pipe, through2({objectMode: true}, function(f, enc, done) { if (f.diff && Object.keys(f.diff).length) filePaths.push(path.relative(process.cwd(), f.path)); done(null, f); }, function(done) { if (filePaths.length) { var clangFormatBin = path.relative(process.cwd(), actualClangFormat.location); log('WARNING: Files are not properly formatted. Please run'); log(' ' + clangFormatBin + ' -i -style="' + optsStr + '" ' + filePaths.join(' ')); log(' (using clang-format version ' + actualClangFormat.version + ')'); var level = opt_gulpOptions.fail ? 'error' : 'warning'; pipe.emit(level, new PluginError('gulp-clang-format', 'files not formatted')); } done(); })); return pipe; }
javascript
function checkFormat(opt_clangOptions, opt_clangFormat, opt_gulpOptions) { var optsStr = getOptsString(opt_clangOptions); var actualClangFormat = opt_clangFormat || clangFormat; opt_gulpOptions = opt_gulpOptions || {}; var filePaths = []; var pipe = combine.obj(format(opt_clangOptions, opt_clangFormat), diff()); if (opt_gulpOptions.verbose) { pipe = combine.obj(pipe, diff.reporter({fail: false})); } pipe = combine.obj( pipe, through2({objectMode: true}, function(f, enc, done) { if (f.diff && Object.keys(f.diff).length) filePaths.push(path.relative(process.cwd(), f.path)); done(null, f); }, function(done) { if (filePaths.length) { var clangFormatBin = path.relative(process.cwd(), actualClangFormat.location); log('WARNING: Files are not properly formatted. Please run'); log(' ' + clangFormatBin + ' -i -style="' + optsStr + '" ' + filePaths.join(' ')); log(' (using clang-format version ' + actualClangFormat.version + ')'); var level = opt_gulpOptions.fail ? 'error' : 'warning'; pipe.emit(level, new PluginError('gulp-clang-format', 'files not formatted')); } done(); })); return pipe; }
[ "function", "checkFormat", "(", "opt_clangOptions", ",", "opt_clangFormat", ",", "opt_gulpOptions", ")", "{", "var", "optsStr", "=", "getOptsString", "(", "opt_clangOptions", ")", ";", "var", "actualClangFormat", "=", "opt_clangFormat", "||", "clangFormat", ";", "opt_gulpOptions", "=", "opt_gulpOptions", "||", "{", "}", ";", "var", "filePaths", "=", "[", "]", ";", "var", "pipe", "=", "combine", ".", "obj", "(", "format", "(", "opt_clangOptions", ",", "opt_clangFormat", ")", ",", "diff", "(", ")", ")", ";", "if", "(", "opt_gulpOptions", ".", "verbose", ")", "{", "pipe", "=", "combine", ".", "obj", "(", "pipe", ",", "diff", ".", "reporter", "(", "{", "fail", ":", "false", "}", ")", ")", ";", "}", "pipe", "=", "combine", ".", "obj", "(", "pipe", ",", "through2", "(", "{", "objectMode", ":", "true", "}", ",", "function", "(", "f", ",", "enc", ",", "done", ")", "{", "if", "(", "f", ".", "diff", "&&", "Object", ".", "keys", "(", "f", ".", "diff", ")", ".", "length", ")", "filePaths", ".", "push", "(", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "f", ".", "path", ")", ")", ";", "done", "(", "null", ",", "f", ")", ";", "}", ",", "function", "(", "done", ")", "{", "if", "(", "filePaths", ".", "length", ")", "{", "var", "clangFormatBin", "=", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "actualClangFormat", ".", "location", ")", ";", "log", "(", "'WARNING: Files are not properly formatted. Please run'", ")", ";", "log", "(", "' '", "+", "clangFormatBin", "+", "' -i -style=\"'", "+", "optsStr", "+", "'\" '", "+", "filePaths", ".", "join", "(", "' '", ")", ")", ";", "log", "(", "' (using clang-format version '", "+", "actualClangFormat", ".", "version", "+", "')'", ")", ";", "var", "level", "=", "opt_gulpOptions", ".", "fail", "?", "'error'", ":", "'warning'", ";", "pipe", ".", "emit", "(", "level", ",", "new", "PluginError", "(", "'gulp-clang-format'", ",", "'files not formatted'", ")", ")", ";", "}", "done", "(", ")", ";", "}", ")", ")", ";", "return", "pipe", ";", "}" ]
Verifies that files are already in the format produced by clang-format. Prints a warning to the console for any file which isn't formatted. @param {(string|Object)=} opt_clangOptions the string 'file' to search for a '.clang-format' file, or an object literal containing clang-format options http://clang.llvm.org/docs/ClangFormatStyleOptions.html#configurable-format-style-options @param {Object=} opt_clangFormat A clang-format module to optionally use. @param {Object=} opt_gulpOptions Options for the gulp process. Options are 'verbose', which toggles a verbose diff report. 'fail', whether to fail in case of a diff.
[ "Verifies", "that", "files", "are", "already", "in", "the", "format", "produced", "by", "clang", "-", "format", ".", "Prints", "a", "warning", "to", "the", "console", "for", "any", "file", "which", "isn", "t", "formatted", "." ]
585c281cdd7788e6dee8082d6c9e5f53830baa4a
https://github.com/angular/gulp-clang-format/blob/585c281cdd7788e6dee8082d6c9e5f53830baa4a/index.js#L49-L80
train
wavesjs/waves-lfo
src/common/operator/Dct.js
getDctWeights
function getDctWeights(order, N, type = 'htk') { const weights = new Float32Array(N * order); const piOverN = PI / N; const scale0 = 1 / sqrt(2); const scale = sqrt(2 / N); for (let k = 0; k < order; k++) { const s = (k === 0) ? (scale0 * scale) : scale; // const s = scale; // rta doesn't apply k=0 scaling for (let n = 0; n < N; n++) weights[k * N + n] = s * cos(k * (n + 0.5) * piOverN); } return weights; }
javascript
function getDctWeights(order, N, type = 'htk') { const weights = new Float32Array(N * order); const piOverN = PI / N; const scale0 = 1 / sqrt(2); const scale = sqrt(2 / N); for (let k = 0; k < order; k++) { const s = (k === 0) ? (scale0 * scale) : scale; // const s = scale; // rta doesn't apply k=0 scaling for (let n = 0; n < N; n++) weights[k * N + n] = s * cos(k * (n + 0.5) * piOverN); } return weights; }
[ "function", "getDctWeights", "(", "order", ",", "N", ",", "type", "=", "'htk'", ")", "{", "const", "weights", "=", "new", "Float32Array", "(", "N", "*", "order", ")", ";", "const", "piOverN", "=", "PI", "/", "N", ";", "const", "scale0", "=", "1", "/", "sqrt", "(", "2", ")", ";", "const", "scale", "=", "sqrt", "(", "2", "/", "N", ")", ";", "for", "(", "let", "k", "=", "0", ";", "k", "<", "order", ";", "k", "++", ")", "{", "const", "s", "=", "(", "k", "===", "0", ")", "?", "(", "scale0", "*", "scale", ")", ":", "scale", ";", "for", "(", "let", "n", "=", "0", ";", "n", "<", "N", ";", "n", "++", ")", "weights", "[", "k", "*", "N", "+", "n", "]", "=", "s", "*", "cos", "(", "k", "*", "(", "n", "+", "0.5", ")", "*", "piOverN", ")", ";", "}", "return", "weights", ";", "}" ]
Dct Type 2 - orthogonal matrix scaling
[ "Dct", "Type", "2", "-", "orthogonal", "matrix", "scaling" ]
4353a8ef55b7921755fe182cb09b0df566696bc8
https://github.com/wavesjs/waves-lfo/blob/4353a8ef55b7921755fe182cb09b0df566696bc8/src/common/operator/Dct.js#L8-L23
train
nodebox/g.js
src/libraries/img/canvasrenderer.js
transformLayer
function transformLayer(ctx, iCanvas, layer) { var m = layer.transform.matrix(); ctx.translate(iCanvas.width / 2, iCanvas.height / 2); ctx.transform(m[0], m[1], m[3], m[4], m[6], m[7]); if (layer.flip_h || layer.flip_v) { ctx.scale(layer.flip_h ? -1 : 1, layer.flip_v ? -1 : 1); } ctx.translate(-layer.img.width / 2, -layer.img.height / 2); }
javascript
function transformLayer(ctx, iCanvas, layer) { var m = layer.transform.matrix(); ctx.translate(iCanvas.width / 2, iCanvas.height / 2); ctx.transform(m[0], m[1], m[3], m[4], m[6], m[7]); if (layer.flip_h || layer.flip_v) { ctx.scale(layer.flip_h ? -1 : 1, layer.flip_v ? -1 : 1); } ctx.translate(-layer.img.width / 2, -layer.img.height / 2); }
[ "function", "transformLayer", "(", "ctx", ",", "iCanvas", ",", "layer", ")", "{", "var", "m", "=", "layer", ".", "transform", ".", "matrix", "(", ")", ";", "ctx", ".", "translate", "(", "iCanvas", ".", "width", "/", "2", ",", "iCanvas", ".", "height", "/", "2", ")", ";", "ctx", ".", "transform", "(", "m", "[", "0", "]", ",", "m", "[", "1", "]", ",", "m", "[", "3", "]", ",", "m", "[", "4", "]", ",", "m", "[", "6", "]", ",", "m", "[", "7", "]", ")", ";", "if", "(", "layer", ".", "flip_h", "||", "layer", ".", "flip_v", ")", "{", "ctx", ".", "scale", "(", "layer", ".", "flip_h", "?", "-", "1", ":", "1", ",", "layer", ".", "flip_v", "?", "-", "1", ":", "1", ")", ";", "}", "ctx", ".", "translate", "(", "-", "layer", ".", "img", ".", "width", "/", "2", ",", "-", "layer", ".", "img", ".", "height", "/", "2", ")", ";", "}" ]
LAYER TRANFORMATIONS. Transforms the 2d context that acts upon this layer's image. Utility function. -> Rename this?
[ "LAYER", "TRANFORMATIONS", ".", "Transforms", "the", "2d", "context", "that", "acts", "upon", "this", "layer", "s", "image", ".", "Utility", "function", ".", "-", ">", "Rename", "this?" ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/canvasrenderer.js#L204-L213
train
nodebox/g.js
src/libraries/img/canvasrenderer.js
rectIntersect
function rectIntersect(r1, r2) { var right1 = r1.x + r1.width; var bottom1 = r1.y + r1.height; var right2 = r2.x + r2.width; var bottom2 = r2.y + r2.height; var x = Math.max(r1.x, r2.x); var y = Math.max(r1.y, r2.y); var w = Math.max(Math.min(right1, right2) - x, 0); var h = Math.max(Math.min(bottom1, bottom2) - y, 0); return {x: x, y: y, width: w, height: h}; }
javascript
function rectIntersect(r1, r2) { var right1 = r1.x + r1.width; var bottom1 = r1.y + r1.height; var right2 = r2.x + r2.width; var bottom2 = r2.y + r2.height; var x = Math.max(r1.x, r2.x); var y = Math.max(r1.y, r2.y); var w = Math.max(Math.min(right1, right2) - x, 0); var h = Math.max(Math.min(bottom1, bottom2) - y, 0); return {x: x, y: y, width: w, height: h}; }
[ "function", "rectIntersect", "(", "r1", ",", "r2", ")", "{", "var", "right1", "=", "r1", ".", "x", "+", "r1", ".", "width", ";", "var", "bottom1", "=", "r1", ".", "y", "+", "r1", ".", "height", ";", "var", "right2", "=", "r2", ".", "x", "+", "r2", ".", "width", ";", "var", "bottom2", "=", "r2", ".", "y", "+", "r2", ".", "height", ";", "var", "x", "=", "Math", ".", "max", "(", "r1", ".", "x", ",", "r2", ".", "x", ")", ";", "var", "y", "=", "Math", ".", "max", "(", "r1", ".", "y", ",", "r2", ".", "y", ")", ";", "var", "w", "=", "Math", ".", "max", "(", "Math", ".", "min", "(", "right1", ",", "right2", ")", "-", "x", ",", "0", ")", ";", "var", "h", "=", "Math", ".", "max", "(", "Math", ".", "min", "(", "bottom1", ",", "bottom2", ")", "-", "y", ",", "0", ")", ";", "return", "{", "x", ":", "x", ",", "y", ":", "y", ",", "width", ":", "w", ",", "height", ":", "h", "}", ";", "}" ]
Calculates the intersecting rectangle of two input rectangles.
[ "Calculates", "the", "intersecting", "rectangle", "of", "two", "input", "rectangles", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/canvasrenderer.js#L256-L267
train
nodebox/g.js
src/libraries/img/canvasrenderer.js
calcLayerRect
function calcLayerRect(iCanvas, layer) { var rect = transformRect(iCanvas, layer); rect = rectIntersect(rect, {x: 0, y: 0, width: iCanvas.width, height: iCanvas.height}); return { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.ceil(rect.width), height: Math.ceil(rect.height)}; }
javascript
function calcLayerRect(iCanvas, layer) { var rect = transformRect(iCanvas, layer); rect = rectIntersect(rect, {x: 0, y: 0, width: iCanvas.width, height: iCanvas.height}); return { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.ceil(rect.width), height: Math.ceil(rect.height)}; }
[ "function", "calcLayerRect", "(", "iCanvas", ",", "layer", ")", "{", "var", "rect", "=", "transformRect", "(", "iCanvas", ",", "layer", ")", ";", "rect", "=", "rectIntersect", "(", "rect", ",", "{", "x", ":", "0", ",", "y", ":", "0", ",", "width", ":", "iCanvas", ".", "width", ",", "height", ":", "iCanvas", ".", "height", "}", ")", ";", "return", "{", "x", ":", "Math", ".", "round", "(", "rect", ".", "x", ")", ",", "y", ":", "Math", ".", "round", "(", "rect", ".", "y", ")", ",", "width", ":", "Math", ".", "ceil", "(", "rect", ".", "width", ")", ",", "height", ":", "Math", ".", "ceil", "(", "rect", ".", "height", ")", "}", ";", "}" ]
Calculates the mimimal area that a transformed layer needs so that it can still be drawn on the canvas. Returns a rectangle.
[ "Calculates", "the", "mimimal", "area", "that", "a", "transformed", "layer", "needs", "so", "that", "it", "can", "still", "be", "drawn", "on", "the", "canvas", ".", "Returns", "a", "rectangle", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/canvasrenderer.js#L271-L278
train
nodebox/g.js
src/libraries/img/canvasrenderer.js
getTransformedLayerData
function getTransformedLayerData(iCanvas, layer, rect) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = rect.width; canvas.height = rect.height; ctx.translate(-rect.x, -rect.y); transformLayer(ctx, iCanvas, layer); ctx.drawImage(layer.img, 0, 0); return ctx.getImageData(0, 0, rect.width, rect.height); }
javascript
function getTransformedLayerData(iCanvas, layer, rect) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = rect.width; canvas.height = rect.height; ctx.translate(-rect.x, -rect.y); transformLayer(ctx, iCanvas, layer); ctx.drawImage(layer.img, 0, 0); return ctx.getImageData(0, 0, rect.width, rect.height); }
[ "function", "getTransformedLayerData", "(", "iCanvas", ",", "layer", ",", "rect", ")", "{", "var", "canvas", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "var", "ctx", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "canvas", ".", "width", "=", "rect", ".", "width", ";", "canvas", ".", "height", "=", "rect", ".", "height", ";", "ctx", ".", "translate", "(", "-", "rect", ".", "x", ",", "-", "rect", ".", "y", ")", ";", "transformLayer", "(", "ctx", ",", "iCanvas", ",", "layer", ")", ";", "ctx", ".", "drawImage", "(", "layer", ".", "img", ",", "0", ",", "0", ")", ";", "return", "ctx", ".", "getImageData", "(", "0", ",", "0", ",", "rect", ".", "width", ",", "rect", ".", "height", ")", ";", "}" ]
Transforms a layer and returns the resulting pixel data.
[ "Transforms", "a", "layer", "and", "returns", "the", "resulting", "pixel", "data", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/canvasrenderer.js#L281-L290
train
nodebox/g.js
src/libraries/vg/objects/matrix4.js
function (m) { if (m !== undefined) { // TODO Check for type and length this.m = m; } else { m = new Float32Array(16); m[0] = 1.0; m[1] = 0.0; m[2] = 0.0; m[3] = 0.0; m[4] = 0.0; m[5] = 1.0; m[6] = 0.0; m[7] = 0.0; m[8] = 0.0; m[9] = 0.0; m[10] = 1.0; m[11] = 0.0; m[12] = 0.0; m[13] = 0.0; m[14] = 0.0; m[15] = 1.0; this.m = m; } }
javascript
function (m) { if (m !== undefined) { // TODO Check for type and length this.m = m; } else { m = new Float32Array(16); m[0] = 1.0; m[1] = 0.0; m[2] = 0.0; m[3] = 0.0; m[4] = 0.0; m[5] = 1.0; m[6] = 0.0; m[7] = 0.0; m[8] = 0.0; m[9] = 0.0; m[10] = 1.0; m[11] = 0.0; m[12] = 0.0; m[13] = 0.0; m[14] = 0.0; m[15] = 1.0; this.m = m; } }
[ "function", "(", "m", ")", "{", "if", "(", "m", "!==", "undefined", ")", "{", "this", ".", "m", "=", "m", ";", "}", "else", "{", "m", "=", "new", "Float32Array", "(", "16", ")", ";", "m", "[", "0", "]", "=", "1.0", ";", "m", "[", "1", "]", "=", "0.0", ";", "m", "[", "2", "]", "=", "0.0", ";", "m", "[", "3", "]", "=", "0.0", ";", "m", "[", "4", "]", "=", "0.0", ";", "m", "[", "5", "]", "=", "1.0", ";", "m", "[", "6", "]", "=", "0.0", ";", "m", "[", "7", "]", "=", "0.0", ";", "m", "[", "8", "]", "=", "0.0", ";", "m", "[", "9", "]", "=", "0.0", ";", "m", "[", "10", "]", "=", "1.0", ";", "m", "[", "11", "]", "=", "0.0", ";", "m", "[", "12", "]", "=", "0.0", ";", "m", "[", "13", "]", "=", "0.0", ";", "m", "[", "14", "]", "=", "0.0", ";", "m", "[", "15", "]", "=", "1.0", ";", "this", ".", "m", "=", "m", ";", "}", "}" ]
Construct a 4x4 matrix.
[ "Construct", "a", "4x4", "matrix", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/vg/objects/matrix4.js#L8-L32
train
solderjs/rrecurjs
rrecur.js
parse
function parse(str) { str = str.replace(/\n/, ';'); str = str.replace(/RRULE:/, ''); str = str.replace(/DTSTART;/, 'DTSTART__SEMI__'); var pairs = str.split(';') , obj = {} ; pairs.forEach(function (pair) { pair = pair.replace(/DTSTART__SEMI__/, 'DTSTART;'); var parts = pair.split('=') , k = parts[0] , ks , param , tzid , vstr = parts[1] , v ; // Handle case of DTSTART;TZID=US-Eastern:{{yyyymmddThhmmss}} // NO Z ALLOWED ks = k.split(';'); k = ks[0]; // TZID exists if ('TZID' === ks[1]) { param = ks[1].split(':'); tzid = param[0]; obj.tzid = tzid; v = param[1]; } // Handle case of DTSTART;LOCALE=GMT-0600 (MDT):{{yyyymmddThhmmss}} // NO Z ALLOWED // obj.locale = obj.locale || stringifyGmtZone(obj.dtstart); if ('LOCALE' === ks[1]) { if (localeWarn2) { console.warn('[parse] falling back to non-standard locale definition for timezone'); localeWarn2 = false; } param = vstr.split(':'); obj.locale = param[0]; // Continue with DTSTART k = ks[0]; vstr = v = param[1]; } switch (k) { case 'DTSTART': case 'UNTIL': v = Rrecur.toRruleDateString(vstr); break; case 'FREQ': case 'WKST': v = vstr.toLowerCase(); break; case 'INTERVAL': case 'COUNT': v = vstr; break; case 'BYWEEKDAY': console.warn('converting rrule.js BYWEEKDAY to rrule rfc BYDAY'); k = 'BYDAY'; /* fall through */ case 'BYSETPOS': case 'BYYEARDAY': case 'BYMONTH': case 'BYWEEKNO': case 'BYDAY': case 'BYMONTHDAY': case 'BYHOUR': case 'BYMINUTE': case 'BYSECOND': case 'BYEASTER': v = vstr.split(','); v.forEach(function (val, i) { v[i] = val.toLowerCase(); }); break; } obj[k.toLowerCase()] = v; }); return obj; }
javascript
function parse(str) { str = str.replace(/\n/, ';'); str = str.replace(/RRULE:/, ''); str = str.replace(/DTSTART;/, 'DTSTART__SEMI__'); var pairs = str.split(';') , obj = {} ; pairs.forEach(function (pair) { pair = pair.replace(/DTSTART__SEMI__/, 'DTSTART;'); var parts = pair.split('=') , k = parts[0] , ks , param , tzid , vstr = parts[1] , v ; // Handle case of DTSTART;TZID=US-Eastern:{{yyyymmddThhmmss}} // NO Z ALLOWED ks = k.split(';'); k = ks[0]; // TZID exists if ('TZID' === ks[1]) { param = ks[1].split(':'); tzid = param[0]; obj.tzid = tzid; v = param[1]; } // Handle case of DTSTART;LOCALE=GMT-0600 (MDT):{{yyyymmddThhmmss}} // NO Z ALLOWED // obj.locale = obj.locale || stringifyGmtZone(obj.dtstart); if ('LOCALE' === ks[1]) { if (localeWarn2) { console.warn('[parse] falling back to non-standard locale definition for timezone'); localeWarn2 = false; } param = vstr.split(':'); obj.locale = param[0]; // Continue with DTSTART k = ks[0]; vstr = v = param[1]; } switch (k) { case 'DTSTART': case 'UNTIL': v = Rrecur.toRruleDateString(vstr); break; case 'FREQ': case 'WKST': v = vstr.toLowerCase(); break; case 'INTERVAL': case 'COUNT': v = vstr; break; case 'BYWEEKDAY': console.warn('converting rrule.js BYWEEKDAY to rrule rfc BYDAY'); k = 'BYDAY'; /* fall through */ case 'BYSETPOS': case 'BYYEARDAY': case 'BYMONTH': case 'BYWEEKNO': case 'BYDAY': case 'BYMONTHDAY': case 'BYHOUR': case 'BYMINUTE': case 'BYSECOND': case 'BYEASTER': v = vstr.split(','); v.forEach(function (val, i) { v[i] = val.toLowerCase(); }); break; } obj[k.toLowerCase()] = v; }); return obj; }
[ "function", "parse", "(", "str", ")", "{", "str", "=", "str", ".", "replace", "(", "/", "\\n", "/", ",", "';'", ")", ";", "str", "=", "str", ".", "replace", "(", "/", "RRULE:", "/", ",", "''", ")", ";", "str", "=", "str", ".", "replace", "(", "/", "DTSTART;", "/", ",", "'DTSTART__SEMI__'", ")", ";", "var", "pairs", "=", "str", ".", "split", "(", "';'", ")", ",", "obj", "=", "{", "}", ";", "pairs", ".", "forEach", "(", "function", "(", "pair", ")", "{", "pair", "=", "pair", ".", "replace", "(", "/", "DTSTART__SEMI__", "/", ",", "'DTSTART;'", ")", ";", "var", "parts", "=", "pair", ".", "split", "(", "'='", ")", ",", "k", "=", "parts", "[", "0", "]", ",", "ks", ",", "param", ",", "tzid", ",", "vstr", "=", "parts", "[", "1", "]", ",", "v", ";", "ks", "=", "k", ".", "split", "(", "';'", ")", ";", "k", "=", "ks", "[", "0", "]", ";", "if", "(", "'TZID'", "===", "ks", "[", "1", "]", ")", "{", "param", "=", "ks", "[", "1", "]", ".", "split", "(", "':'", ")", ";", "tzid", "=", "param", "[", "0", "]", ";", "obj", ".", "tzid", "=", "tzid", ";", "v", "=", "param", "[", "1", "]", ";", "}", "if", "(", "'LOCALE'", "===", "ks", "[", "1", "]", ")", "{", "if", "(", "localeWarn2", ")", "{", "console", ".", "warn", "(", "'[parse] falling back to non-standard locale definition for timezone'", ")", ";", "localeWarn2", "=", "false", ";", "}", "param", "=", "vstr", ".", "split", "(", "':'", ")", ";", "obj", ".", "locale", "=", "param", "[", "0", "]", ";", "k", "=", "ks", "[", "0", "]", ";", "vstr", "=", "v", "=", "param", "[", "1", "]", ";", "}", "switch", "(", "k", ")", "{", "case", "'DTSTART'", ":", "case", "'UNTIL'", ":", "v", "=", "Rrecur", ".", "toRruleDateString", "(", "vstr", ")", ";", "break", ";", "case", "'FREQ'", ":", "case", "'WKST'", ":", "v", "=", "vstr", ".", "toLowerCase", "(", ")", ";", "break", ";", "case", "'INTERVAL'", ":", "case", "'COUNT'", ":", "v", "=", "vstr", ";", "break", ";", "case", "'BYWEEKDAY'", ":", "console", ".", "warn", "(", "'converting rrule.js BYWEEKDAY to rrule rfc BYDAY'", ")", ";", "k", "=", "'BYDAY'", ";", "case", "'BYSETPOS'", ":", "case", "'BYYEARDAY'", ":", "case", "'BYMONTH'", ":", "case", "'BYWEEKNO'", ":", "case", "'BYDAY'", ":", "case", "'BYMONTHDAY'", ":", "case", "'BYHOUR'", ":", "case", "'BYMINUTE'", ":", "case", "'BYSECOND'", ":", "case", "'BYEASTER'", ":", "v", "=", "vstr", ".", "split", "(", "','", ")", ";", "v", ".", "forEach", "(", "function", "(", "val", ",", "i", ")", "{", "v", "[", "i", "]", "=", "val", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "break", ";", "}", "obj", "[", "k", ".", "toLowerCase", "(", ")", "]", "=", "v", ";", "}", ")", ";", "return", "obj", ";", "}" ]
DTSTART is not part of RRULE
[ "DTSTART", "is", "not", "part", "of", "RRULE" ]
3c2f27df921878eec1f14509e661a13a06514de8
https://github.com/solderjs/rrecurjs/blob/3c2f27df921878eec1f14509e661a13a06514de8/rrecur.js#L142-L226
train
WebReflection/polpetta
src/function/readdir.js
readDir
function readDir(err, files) { if (err) { internalServerError.call(this, err); } else { var dirName = decodeURIComponent( getCurrentPathName(this) ); this.output.push( "<!doctype html>", "<html>", "<head>", "<title>Index of ", dirName, "</title>", '<meta name="viewport" content="', 'width=device-width,', 'initial-scale=1.0,', 'maximum-scale=1.0,', 'user-scalable=no', '"/>', '<meta name="generator" content="polpetta" />', "</head>", "<body>", "<strong>Index of " + dirName + "</strong>", "<ul>" ); if (dirName != WEB_SEP) { this.output.push( '<li><a href="..">..</a></li>' ); } files.forEach(readDir.forEach, this.output); this.output.push( "</ul>", "</body>", "</html>" ); this.output.flush(200, "text/html", "utf-8"); } }
javascript
function readDir(err, files) { if (err) { internalServerError.call(this, err); } else { var dirName = decodeURIComponent( getCurrentPathName(this) ); this.output.push( "<!doctype html>", "<html>", "<head>", "<title>Index of ", dirName, "</title>", '<meta name="viewport" content="', 'width=device-width,', 'initial-scale=1.0,', 'maximum-scale=1.0,', 'user-scalable=no', '"/>', '<meta name="generator" content="polpetta" />', "</head>", "<body>", "<strong>Index of " + dirName + "</strong>", "<ul>" ); if (dirName != WEB_SEP) { this.output.push( '<li><a href="..">..</a></li>' ); } files.forEach(readDir.forEach, this.output); this.output.push( "</ul>", "</body>", "</html>" ); this.output.flush(200, "text/html", "utf-8"); } }
[ "function", "readDir", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "internalServerError", ".", "call", "(", "this", ",", "err", ")", ";", "}", "else", "{", "var", "dirName", "=", "decodeURIComponent", "(", "getCurrentPathName", "(", "this", ")", ")", ";", "this", ".", "output", ".", "push", "(", "\"<!doctype html>\"", ",", "\"<html>\"", ",", "\"<head>\"", ",", "\"<title>Index of \"", ",", "dirName", ",", "\"</title>\"", ",", "'<meta name=\"viewport\" content=\"'", ",", "'width=device-width,'", ",", "'initial-scale=1.0,'", ",", "'maximum-scale=1.0,'", ",", "'user-scalable=no'", ",", "'\"/>'", ",", "'<meta name=\"generator\" content=\"polpetta\" />'", ",", "\"</head>\"", ",", "\"<body>\"", ",", "\"<strong>Index of \"", "+", "dirName", "+", "\"</strong>\"", ",", "\"<ul>\"", ")", ";", "if", "(", "dirName", "!=", "WEB_SEP", ")", "{", "this", ".", "output", ".", "push", "(", "'<li><a href=\"..\">..</a></li>'", ")", ";", "}", "files", ".", "forEach", "(", "readDir", ".", "forEach", ",", "this", ".", "output", ")", ";", "this", ".", "output", ".", "push", "(", "\"</ul>\"", ",", "\"</body>\"", ",", "\"</html>\"", ")", ";", "this", ".", "output", ".", "flush", "(", "200", ",", "\"text/html\"", ",", "\"utf-8\"", ")", ";", "}", "}" ]
used to show a directory content
[ "used", "to", "show", "a", "directory", "content" ]
edaa23518db9c9dcde30fb8501ecd86f130ca5c3
https://github.com/WebReflection/polpetta/blob/edaa23518db9c9dcde30fb8501ecd86f130ca5c3/src/function/readdir.js#L3-L40
train
haroldiedema/joii
src/InterfaceBuilder.js
function(prop, prefix) { if (prop.isAbstract()) { throw 'An interface may not contain abstract definitions. ' + prefix + ' ' + prop.getName() + ' is abstract in interface ' + definition.__interface__.name + '.'; } if (prop.isFinal()) { throw 'An interface may not contain final definitions. ' + prefix + ' ' + prop.getName() + ' is final in interface ' + definition.__interface__.name + '.'; } }
javascript
function(prop, prefix) { if (prop.isAbstract()) { throw 'An interface may not contain abstract definitions. ' + prefix + ' ' + prop.getName() + ' is abstract in interface ' + definition.__interface__.name + '.'; } if (prop.isFinal()) { throw 'An interface may not contain final definitions. ' + prefix + ' ' + prop.getName() + ' is final in interface ' + definition.__interface__.name + '.'; } }
[ "function", "(", "prop", ",", "prefix", ")", "{", "if", "(", "prop", ".", "isAbstract", "(", ")", ")", "{", "throw", "'An interface may not contain abstract definitions. '", "+", "prefix", "+", "' '", "+", "prop", ".", "getName", "(", ")", "+", "' is abstract in interface '", "+", "definition", ".", "__interface__", ".", "name", "+", "'.'", ";", "}", "if", "(", "prop", ".", "isFinal", "(", ")", ")", "{", "throw", "'An interface may not contain final definitions. '", "+", "prefix", "+", "' '", "+", "prop", ".", "getName", "(", ")", "+", "' is final in interface '", "+", "definition", ".", "__interface__", ".", "name", "+", "'.'", ";", "}", "}" ]
Properties and methods may ever be declared as abstract or final in an interface definition, because that wouldn't make any sense in this context.
[ "Properties", "and", "methods", "may", "ever", "be", "declared", "as", "abstract", "or", "final", "in", "an", "interface", "definition", "because", "that", "wouldn", "t", "make", "any", "sense", "in", "this", "context", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/InterfaceBuilder.js#L147-L154
train
nimndata/nimnjs-schema-builder
builder.js
buildSchema
function buildSchema(jsObj, key) { if (jsObj === undefined) return null; var type = typeOf(jsObj); switch (type) { case "array": { let schema = { type: "list", detail: buildSchema(jsObj[0]) }; key && (schema.name = key); return schema; } case "object": { let schema = { type: "map", detail: [] }; key && (schema.name = key); let keys = Object.keys(jsObj); for (var i in keys) { let key = keys[i]; if (jsObj[key] !== undefined) { schema.detail.push(buildSchema(jsObj[key], key)); } } return schema; } case "null": case "string": case "number": case "date": case "boolean": { let schema = { type: type }; key && (schema.name = key); return schema; } default: throw Error("Unacceptable type : " + type); } }
javascript
function buildSchema(jsObj, key) { if (jsObj === undefined) return null; var type = typeOf(jsObj); switch (type) { case "array": { let schema = { type: "list", detail: buildSchema(jsObj[0]) }; key && (schema.name = key); return schema; } case "object": { let schema = { type: "map", detail: [] }; key && (schema.name = key); let keys = Object.keys(jsObj); for (var i in keys) { let key = keys[i]; if (jsObj[key] !== undefined) { schema.detail.push(buildSchema(jsObj[key], key)); } } return schema; } case "null": case "string": case "number": case "date": case "boolean": { let schema = { type: type }; key && (schema.name = key); return schema; } default: throw Error("Unacceptable type : " + type); } }
[ "function", "buildSchema", "(", "jsObj", ",", "key", ")", "{", "if", "(", "jsObj", "===", "undefined", ")", "return", "null", ";", "var", "type", "=", "typeOf", "(", "jsObj", ")", ";", "switch", "(", "type", ")", "{", "case", "\"array\"", ":", "{", "let", "schema", "=", "{", "type", ":", "\"list\"", ",", "detail", ":", "buildSchema", "(", "jsObj", "[", "0", "]", ")", "}", ";", "key", "&&", "(", "schema", ".", "name", "=", "key", ")", ";", "return", "schema", ";", "}", "case", "\"object\"", ":", "{", "let", "schema", "=", "{", "type", ":", "\"map\"", ",", "detail", ":", "[", "]", "}", ";", "key", "&&", "(", "schema", ".", "name", "=", "key", ")", ";", "let", "keys", "=", "Object", ".", "keys", "(", "jsObj", ")", ";", "for", "(", "var", "i", "in", "keys", ")", "{", "let", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "jsObj", "[", "key", "]", "!==", "undefined", ")", "{", "schema", ".", "detail", ".", "push", "(", "buildSchema", "(", "jsObj", "[", "key", "]", ",", "key", ")", ")", ";", "}", "}", "return", "schema", ";", "}", "case", "\"null\"", ":", "case", "\"string\"", ":", "case", "\"number\"", ":", "case", "\"date\"", ":", "case", "\"boolean\"", ":", "{", "let", "schema", "=", "{", "type", ":", "type", "}", ";", "key", "&&", "(", "schema", ".", "name", "=", "key", ")", ";", "return", "schema", ";", "}", "default", ":", "throw", "Error", "(", "\"Unacceptable type : \"", "+", "type", ")", ";", "}", "}" ]
Build Schema for nimnification of JSON data @param {*} jsObj
[ "Build", "Schema", "for", "nimnification", "of", "JSON", "data" ]
658a5f282b62450b9dc9485d540e70dfd811b094
https://github.com/nimndata/nimnjs-schema-builder/blob/658a5f282b62450b9dc9485d540e70dfd811b094/builder.js#L5-L50
train
WebReflection/polpetta
src/function/requireNJS.js
requireNJS
function requireNJS() { try { var module = ru(this.path); } catch(o_O) { console.error(o_O); return internalServerError.call(this, o_O); } module.onload( this.request, this.response, this ); }
javascript
function requireNJS() { try { var module = ru(this.path); } catch(o_O) { console.error(o_O); return internalServerError.call(this, o_O); } module.onload( this.request, this.response, this ); }
[ "function", "requireNJS", "(", ")", "{", "try", "{", "var", "module", "=", "ru", "(", "this", ".", "path", ")", ";", "}", "catch", "(", "o_O", ")", "{", "console", ".", "error", "(", "o_O", ")", ";", "return", "internalServerError", ".", "call", "(", "this", ",", "o_O", ")", ";", "}", "module", ".", "onload", "(", "this", ".", "request", ",", "this", ".", "response", ",", "this", ")", ";", "}" ]
used to require .njs files
[ "used", "to", "require", ".", "njs", "files" ]
edaa23518db9c9dcde30fb8501ecd86f130ca5c3
https://github.com/WebReflection/polpetta/blob/edaa23518db9c9dcde30fb8501ecd86f130ca5c3/src/function/requireNJS.js#L3-L15
train
jonschlinkert/fs-exists-sync
index.js
tryReaddir
function tryReaddir(filepath) { var ctx = { path: filepath, files: [] }; try { ctx.files = fs.readdirSync(filepath); return ctx; } catch (err) {} try { ctx.path = path.dirname(filepath); ctx.files = fs.readdirSync(ctx.path); return ctx; } catch (err) {} return null; }
javascript
function tryReaddir(filepath) { var ctx = { path: filepath, files: [] }; try { ctx.files = fs.readdirSync(filepath); return ctx; } catch (err) {} try { ctx.path = path.dirname(filepath); ctx.files = fs.readdirSync(ctx.path); return ctx; } catch (err) {} return null; }
[ "function", "tryReaddir", "(", "filepath", ")", "{", "var", "ctx", "=", "{", "path", ":", "filepath", ",", "files", ":", "[", "]", "}", ";", "try", "{", "ctx", ".", "files", "=", "fs", ".", "readdirSync", "(", "filepath", ")", ";", "return", "ctx", ";", "}", "catch", "(", "err", ")", "{", "}", "try", "{", "ctx", ".", "path", "=", "path", ".", "dirname", "(", "filepath", ")", ";", "ctx", ".", "files", "=", "fs", ".", "readdirSync", "(", "ctx", ".", "path", ")", ";", "return", "ctx", ";", "}", "catch", "(", "err", ")", "{", "}", "return", "null", ";", "}" ]
Try to read the filepath as a directory first, then fallback to the filepath's dirname. @param {String} `filepath` path of the directory to read. @return {Object} Object containing `path` and `files` if successful. Otherwise, null.
[ "Try", "to", "read", "the", "filepath", "as", "a", "directory", "first", "then", "fallback", "to", "the", "filepath", "s", "dirname", "." ]
2270e575660896c92d8f4a0cbbdbcf6b3b8a9f20
https://github.com/jonschlinkert/fs-exists-sync/blob/2270e575660896c92d8f4a0cbbdbcf6b3b8a9f20/index.js#L95-L107
train
haroldiedema/joii
src/ClassBuilder.js
function(bool_return_object) { var obj = { __joii_type: this.__joii__.name }; for (var key in this.__joii__.metadata) { var val = this.__joii__.metadata[key]; if (val.serializable) { var getter_name = JOII.GenerateGetterName(val); var currentValue = null; if (typeof (this[getter_name]) === 'function') { // use getter if it exists. This allows custom getters to translate the data properly if needed. currentValue = this[getter_name](); } else { currentValue = this[val.name]; } if (!val.is_enum && typeof (currentValue) === 'object' && currentValue !== null) { if ('serialize' in currentValue) { obj[val.name] = currentValue.serialize(true); } else { obj[val.name] = JOII.Compat.flattenObject(currentValue); } } else { obj[val.name] = currentValue; } } } return obj; }
javascript
function(bool_return_object) { var obj = { __joii_type: this.__joii__.name }; for (var key in this.__joii__.metadata) { var val = this.__joii__.metadata[key]; if (val.serializable) { var getter_name = JOII.GenerateGetterName(val); var currentValue = null; if (typeof (this[getter_name]) === 'function') { // use getter if it exists. This allows custom getters to translate the data properly if needed. currentValue = this[getter_name](); } else { currentValue = this[val.name]; } if (!val.is_enum && typeof (currentValue) === 'object' && currentValue !== null) { if ('serialize' in currentValue) { obj[val.name] = currentValue.serialize(true); } else { obj[val.name] = JOII.Compat.flattenObject(currentValue); } } else { obj[val.name] = currentValue; } } } return obj; }
[ "function", "(", "bool_return_object", ")", "{", "var", "obj", "=", "{", "__joii_type", ":", "this", ".", "__joii__", ".", "name", "}", ";", "for", "(", "var", "key", "in", "this", ".", "__joii__", ".", "metadata", ")", "{", "var", "val", "=", "this", ".", "__joii__", ".", "metadata", "[", "key", "]", ";", "if", "(", "val", ".", "serializable", ")", "{", "var", "getter_name", "=", "JOII", ".", "GenerateGetterName", "(", "val", ")", ";", "var", "currentValue", "=", "null", ";", "if", "(", "typeof", "(", "this", "[", "getter_name", "]", ")", "===", "'function'", ")", "{", "currentValue", "=", "this", "[", "getter_name", "]", "(", ")", ";", "}", "else", "{", "currentValue", "=", "this", "[", "val", ".", "name", "]", ";", "}", "if", "(", "!", "val", ".", "is_enum", "&&", "typeof", "(", "currentValue", ")", "===", "'object'", "&&", "currentValue", "!==", "null", ")", "{", "if", "(", "'serialize'", "in", "currentValue", ")", "{", "obj", "[", "val", ".", "name", "]", "=", "currentValue", ".", "serialize", "(", "true", ")", ";", "}", "else", "{", "obj", "[", "val", ".", "name", "]", "=", "JOII", ".", "Compat", ".", "flattenObject", "(", "currentValue", ")", ";", "}", "}", "else", "{", "obj", "[", "val", ".", "name", "]", "=", "currentValue", ";", "}", "}", "}", "return", "obj", ";", "}" ]
Serializes all serializable properties of an object. Public members are serializable by default. @return {Object}
[ "Serializes", "all", "serializable", "properties", "of", "an", "object", ".", "Public", "members", "are", "serializable", "by", "default", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/ClassBuilder.js#L369-L399
train
keik/merge-source-map
index.js
merge
function merge(oldMap, newMap) { if (!oldMap) return newMap if (!newMap) return oldMap var oldMapConsumer = new SourceMapConsumer(oldMap) var newMapConsumer = new SourceMapConsumer(newMap) var mergedMapGenerator = new SourceMapGenerator() // iterate on new map and overwrite original position of new map with one of old map newMapConsumer.eachMapping(function(m) { // pass when `originalLine` is null. // It occurs in case that the node does not have origin in original code. if (m.originalLine == null) return var origPosInOldMap = oldMapConsumer.originalPositionFor({ line: m.originalLine, column: m.originalColumn }) if (origPosInOldMap.source == null) return mergedMapGenerator.addMapping({ original: { line: origPosInOldMap.line, column: origPosInOldMap.column }, generated: { line: m.generatedLine, column: m.generatedColumn }, source: origPosInOldMap.source, name: origPosInOldMap.name }) }) var consumers = [oldMapConsumer, newMapConsumer] consumers.forEach(function(consumer) { consumer.sources.forEach(function(sourceFile) { mergedMapGenerator._sources.add(sourceFile) var sourceContent = consumer.sourceContentFor(sourceFile) if (sourceContent != null) { mergedMapGenerator.setSourceContent(sourceFile, sourceContent) } }) }) mergedMapGenerator._sourceRoot = oldMap.sourceRoot mergedMapGenerator._file = oldMap.file return JSON.parse(mergedMapGenerator.toString()) }
javascript
function merge(oldMap, newMap) { if (!oldMap) return newMap if (!newMap) return oldMap var oldMapConsumer = new SourceMapConsumer(oldMap) var newMapConsumer = new SourceMapConsumer(newMap) var mergedMapGenerator = new SourceMapGenerator() // iterate on new map and overwrite original position of new map with one of old map newMapConsumer.eachMapping(function(m) { // pass when `originalLine` is null. // It occurs in case that the node does not have origin in original code. if (m.originalLine == null) return var origPosInOldMap = oldMapConsumer.originalPositionFor({ line: m.originalLine, column: m.originalColumn }) if (origPosInOldMap.source == null) return mergedMapGenerator.addMapping({ original: { line: origPosInOldMap.line, column: origPosInOldMap.column }, generated: { line: m.generatedLine, column: m.generatedColumn }, source: origPosInOldMap.source, name: origPosInOldMap.name }) }) var consumers = [oldMapConsumer, newMapConsumer] consumers.forEach(function(consumer) { consumer.sources.forEach(function(sourceFile) { mergedMapGenerator._sources.add(sourceFile) var sourceContent = consumer.sourceContentFor(sourceFile) if (sourceContent != null) { mergedMapGenerator.setSourceContent(sourceFile, sourceContent) } }) }) mergedMapGenerator._sourceRoot = oldMap.sourceRoot mergedMapGenerator._file = oldMap.file return JSON.parse(mergedMapGenerator.toString()) }
[ "function", "merge", "(", "oldMap", ",", "newMap", ")", "{", "if", "(", "!", "oldMap", ")", "return", "newMap", "if", "(", "!", "newMap", ")", "return", "oldMap", "var", "oldMapConsumer", "=", "new", "SourceMapConsumer", "(", "oldMap", ")", "var", "newMapConsumer", "=", "new", "SourceMapConsumer", "(", "newMap", ")", "var", "mergedMapGenerator", "=", "new", "SourceMapGenerator", "(", ")", "newMapConsumer", ".", "eachMapping", "(", "function", "(", "m", ")", "{", "if", "(", "m", ".", "originalLine", "==", "null", ")", "return", "var", "origPosInOldMap", "=", "oldMapConsumer", ".", "originalPositionFor", "(", "{", "line", ":", "m", ".", "originalLine", ",", "column", ":", "m", ".", "originalColumn", "}", ")", "if", "(", "origPosInOldMap", ".", "source", "==", "null", ")", "return", "mergedMapGenerator", ".", "addMapping", "(", "{", "original", ":", "{", "line", ":", "origPosInOldMap", ".", "line", ",", "column", ":", "origPosInOldMap", ".", "column", "}", ",", "generated", ":", "{", "line", ":", "m", ".", "generatedLine", ",", "column", ":", "m", ".", "generatedColumn", "}", ",", "source", ":", "origPosInOldMap", ".", "source", ",", "name", ":", "origPosInOldMap", ".", "name", "}", ")", "}", ")", "var", "consumers", "=", "[", "oldMapConsumer", ",", "newMapConsumer", "]", "consumers", ".", "forEach", "(", "function", "(", "consumer", ")", "{", "consumer", ".", "sources", ".", "forEach", "(", "function", "(", "sourceFile", ")", "{", "mergedMapGenerator", ".", "_sources", ".", "add", "(", "sourceFile", ")", "var", "sourceContent", "=", "consumer", ".", "sourceContentFor", "(", "sourceFile", ")", "if", "(", "sourceContent", "!=", "null", ")", "{", "mergedMapGenerator", ".", "setSourceContent", "(", "sourceFile", ",", "sourceContent", ")", "}", "}", ")", "}", ")", "mergedMapGenerator", ".", "_sourceRoot", "=", "oldMap", ".", "sourceRoot", "mergedMapGenerator", ".", "_file", "=", "oldMap", ".", "file", "return", "JSON", ".", "parse", "(", "mergedMapGenerator", ".", "toString", "(", ")", ")", "}" ]
Merge old source map and new source map and return merged. If old or new source map value is falsy, return another one as it is. @param {object|string} [oldMap] old source map object @param {object|string} [newmap] new source map object @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
[ "Merge", "old", "source", "map", "and", "new", "source", "map", "and", "return", "merged", ".", "If", "old", "or", "new", "source", "map", "value", "is", "falsy", "return", "another", "one", "as", "it", "is", "." ]
987790721c7e3a36175f39de32bf060987200cc4
https://github.com/keik/merge-source-map/blob/987790721c7e3a36175f39de32bf060987200cc4/index.js#L15-L65
train
wavesjs/waves-lfo
src/common/utils/windows.js
initHannWindow
function initHannWindow(buffer, size, normCoefs) { let linSum = 0; let powSum = 0; const step = 2 * PI / size; for (let i = 0; i < size; i++) { const phi = i * step; const value = 0.5 - 0.5 * cos(phi); buffer[i] = value; linSum += value; powSum += value * value; } normCoefs.linear = size / linSum; normCoefs.power = sqrt(size / powSum); }
javascript
function initHannWindow(buffer, size, normCoefs) { let linSum = 0; let powSum = 0; const step = 2 * PI / size; for (let i = 0; i < size; i++) { const phi = i * step; const value = 0.5 - 0.5 * cos(phi); buffer[i] = value; linSum += value; powSum += value * value; } normCoefs.linear = size / linSum; normCoefs.power = sqrt(size / powSum); }
[ "function", "initHannWindow", "(", "buffer", ",", "size", ",", "normCoefs", ")", "{", "let", "linSum", "=", "0", ";", "let", "powSum", "=", "0", ";", "const", "step", "=", "2", "*", "PI", "/", "size", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "const", "phi", "=", "i", "*", "step", ";", "const", "value", "=", "0.5", "-", "0.5", "*", "cos", "(", "phi", ")", ";", "buffer", "[", "i", "]", "=", "value", ";", "linSum", "+=", "value", ";", "powSum", "+=", "value", "*", "value", ";", "}", "normCoefs", ".", "linear", "=", "size", "/", "linSum", ";", "normCoefs", ".", "power", "=", "sqrt", "(", "size", "/", "powSum", ")", ";", "}" ]
window creation functions
[ "window", "creation", "functions" ]
4353a8ef55b7921755fe182cb09b0df566696bc8
https://github.com/wavesjs/waves-lfo/blob/4353a8ef55b7921755fe182cb09b0df566696bc8/src/common/utils/windows.js#L9-L26
train
wavesjs/waves-lfo
src/common/utils/windows.js
initWindow
function initWindow(name, buffer, size, normCoefs) { name = name.toLowerCase(); switch (name) { case 'hann': case 'hanning': initHannWindow(buffer, size, normCoefs); break; case 'hamming': initHammingWindow(buffer, size, normCoefs); break; case 'blackman': initBlackmanWindow(buffer, size, normCoefs); break; case 'blackmanharris': initBlackmanHarrisWindow(buffer, size, normCoefs); break; case 'sine': initSineWindow(buffer, size, normCoefs); break; case 'rectangle': initRectangleWindow(buffer, size, normCoefs); break; } }
javascript
function initWindow(name, buffer, size, normCoefs) { name = name.toLowerCase(); switch (name) { case 'hann': case 'hanning': initHannWindow(buffer, size, normCoefs); break; case 'hamming': initHammingWindow(buffer, size, normCoefs); break; case 'blackman': initBlackmanWindow(buffer, size, normCoefs); break; case 'blackmanharris': initBlackmanHarrisWindow(buffer, size, normCoefs); break; case 'sine': initSineWindow(buffer, size, normCoefs); break; case 'rectangle': initRectangleWindow(buffer, size, normCoefs); break; } }
[ "function", "initWindow", "(", "name", ",", "buffer", ",", "size", ",", "normCoefs", ")", "{", "name", "=", "name", ".", "toLowerCase", "(", ")", ";", "switch", "(", "name", ")", "{", "case", "'hann'", ":", "case", "'hanning'", ":", "initHannWindow", "(", "buffer", ",", "size", ",", "normCoefs", ")", ";", "break", ";", "case", "'hamming'", ":", "initHammingWindow", "(", "buffer", ",", "size", ",", "normCoefs", ")", ";", "break", ";", "case", "'blackman'", ":", "initBlackmanWindow", "(", "buffer", ",", "size", ",", "normCoefs", ")", ";", "break", ";", "case", "'blackmanharris'", ":", "initBlackmanHarrisWindow", "(", "buffer", ",", "size", ",", "normCoefs", ")", ";", "break", ";", "case", "'sine'", ":", "initSineWindow", "(", "buffer", ",", "size", ",", "normCoefs", ")", ";", "break", ";", "case", "'rectangle'", ":", "initRectangleWindow", "(", "buffer", ",", "size", ",", "normCoefs", ")", ";", "break", ";", "}", "}" ]
Create a buffer with window signal. @memberof module:common.utils @param {String} name - Name of the window. @param {Float32Array} buffer - Buffer to be populated with the window signal. @param {Number} size - Size of the buffer. @param {Object} normCoefs - Object to be populated with the normailzation coefficients.
[ "Create", "a", "buffer", "with", "window", "signal", "." ]
4353a8ef55b7921755fe182cb09b0df566696bc8
https://github.com/wavesjs/waves-lfo/blob/4353a8ef55b7921755fe182cb09b0df566696bc8/src/common/utils/windows.js#L128-L152
train
nyxtom/dive
scuba-dive.js
plan
function plan(buhlmannTable, absPressure, isFreshWater, temperatureInCelcius) { this.isFreshWater = isFreshWater; this.bottomGasses = {}; this.decoGasses = {}; this.segments = []; }
javascript
function plan(buhlmannTable, absPressure, isFreshWater, temperatureInCelcius) { this.isFreshWater = isFreshWater; this.bottomGasses = {}; this.decoGasses = {}; this.segments = []; }
[ "function", "plan", "(", "buhlmannTable", ",", "absPressure", ",", "isFreshWater", ",", "temperatureInCelcius", ")", "{", "this", ".", "isFreshWater", "=", "isFreshWater", ";", "this", ".", "bottomGasses", "=", "{", "}", ";", "this", ".", "decoGasses", "=", "{", "}", ";", "this", ".", "segments", "=", "[", "]", ";", "}" ]
kept for interface compatibility
[ "kept", "for", "interface", "compatibility" ]
db6c75d4610a8610a8aa3be637f74cce4cd3ee7d
https://github.com/nyxtom/dive/blob/db6c75d4610a8610a8aa3be637f74cce4cd3ee7d/scuba-dive.js#L2494-L2499
train
WebReflection/polpetta
src/function/endOfChunks.js
endOfChunks
function endOfChunks() { this.callback = fsStat.bind(this.polpetta); if (this.boundary) { this.i = 0; this.received = {}; this.posted = []; this.join("").split(this.boundary).forEach( endOfChunks.forEach, this ); this.i || endOfChunks.done(this, this.posted.join("&")); } else { endOfChunks.done(this, this.join("")); } }
javascript
function endOfChunks() { this.callback = fsStat.bind(this.polpetta); if (this.boundary) { this.i = 0; this.received = {}; this.posted = []; this.join("").split(this.boundary).forEach( endOfChunks.forEach, this ); this.i || endOfChunks.done(this, this.posted.join("&")); } else { endOfChunks.done(this, this.join("")); } }
[ "function", "endOfChunks", "(", ")", "{", "this", ".", "callback", "=", "fsStat", ".", "bind", "(", "this", ".", "polpetta", ")", ";", "if", "(", "this", ".", "boundary", ")", "{", "this", ".", "i", "=", "0", ";", "this", ".", "received", "=", "{", "}", ";", "this", ".", "posted", "=", "[", "]", ";", "this", ".", "join", "(", "\"\"", ")", ".", "split", "(", "this", ".", "boundary", ")", ".", "forEach", "(", "endOfChunks", ".", "forEach", ",", "this", ")", ";", "this", ".", "i", "||", "endOfChunks", ".", "done", "(", "this", ",", "this", ".", "posted", ".", "join", "(", "\"&\"", ")", ")", ";", "}", "else", "{", "endOfChunks", ".", "done", "(", "this", ",", "this", ".", "join", "(", "\"\"", ")", ")", ";", "}", "}" ]
remove received, chunks, and i, after
[ "remove", "received", "chunks", "and", "i", "after" ]
edaa23518db9c9dcde30fb8501ecd86f130ca5c3
https://github.com/WebReflection/polpetta/blob/edaa23518db9c9dcde30fb8501ecd86f130ca5c3/src/function/endOfChunks.js#L3-L16
train
nodebox/g.js
src/libraries/img/util.js
_mmult
function _mmult(a, m) { m = m.slice(); var m0 = m[0]; var m1 = m[1]; var m2 = m[2]; var m3 = m[3]; var m4 = m[4]; var m5 = m[5]; var m6 = m[6]; var m7 = m[7]; var m8 = m[8]; m[0] = a[0] * m0 + a[1] * m3; m[1] = a[0] * m1 + a[1] * m4; m[3] = a[3] * m0 + a[4] * m3; m[4] = a[3] * m1 + a[4] * m4; m[6] = a[6] * m0 + a[7] * m3 + m6; m[7] = a[6] * m1 + a[7] * m4 + m7; return transform(m); }
javascript
function _mmult(a, m) { m = m.slice(); var m0 = m[0]; var m1 = m[1]; var m2 = m[2]; var m3 = m[3]; var m4 = m[4]; var m5 = m[5]; var m6 = m[6]; var m7 = m[7]; var m8 = m[8]; m[0] = a[0] * m0 + a[1] * m3; m[1] = a[0] * m1 + a[1] * m4; m[3] = a[3] * m0 + a[4] * m3; m[4] = a[3] * m1 + a[4] * m4; m[6] = a[6] * m0 + a[7] * m3 + m6; m[7] = a[6] * m1 + a[7] * m4 + m7; return transform(m); }
[ "function", "_mmult", "(", "a", ",", "m", ")", "{", "m", "=", "m", ".", "slice", "(", ")", ";", "var", "m0", "=", "m", "[", "0", "]", ";", "var", "m1", "=", "m", "[", "1", "]", ";", "var", "m2", "=", "m", "[", "2", "]", ";", "var", "m3", "=", "m", "[", "3", "]", ";", "var", "m4", "=", "m", "[", "4", "]", ";", "var", "m5", "=", "m", "[", "5", "]", ";", "var", "m6", "=", "m", "[", "6", "]", ";", "var", "m7", "=", "m", "[", "7", "]", ";", "var", "m8", "=", "m", "[", "8", "]", ";", "m", "[", "0", "]", "=", "a", "[", "0", "]", "*", "m0", "+", "a", "[", "1", "]", "*", "m3", ";", "m", "[", "1", "]", "=", "a", "[", "0", "]", "*", "m1", "+", "a", "[", "1", "]", "*", "m4", ";", "m", "[", "3", "]", "=", "a", "[", "3", "]", "*", "m0", "+", "a", "[", "4", "]", "*", "m3", ";", "m", "[", "4", "]", "=", "a", "[", "3", "]", "*", "m1", "+", "a", "[", "4", "]", "*", "m4", ";", "m", "[", "6", "]", "=", "a", "[", "6", "]", "*", "m0", "+", "a", "[", "7", "]", "*", "m3", "+", "m6", ";", "m", "[", "7", "]", "=", "a", "[", "6", "]", "*", "m1", "+", "a", "[", "7", "]", "*", "m4", "+", "m7", ";", "return", "transform", "(", "m", ")", ";", "}" ]
Performs the 3x3 matrix multiplication of the current matrix with the input matrix a.
[ "Performs", "the", "3x3", "matrix", "multiplication", "of", "the", "current", "matrix", "with", "the", "input", "matrix", "a", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/util.js#L31-L52
train
colthreepv/express-raml-store
api.js
getFn
function getFn (req, res, next) { var reqPath = req.params[0]; debug('getFn', 'reqPath', reqPath); stat(reqPath) .then(function (content) { if (!!content.type && content.type === 'file') { return res.sendFile(reqPath, { root: ramlPath }); } res.status(200).json(content); }, function (err) { if (err === 'ENOENT') { return res.sendStatus(404); } next(err); }); }
javascript
function getFn (req, res, next) { var reqPath = req.params[0]; debug('getFn', 'reqPath', reqPath); stat(reqPath) .then(function (content) { if (!!content.type && content.type === 'file') { return res.sendFile(reqPath, { root: ramlPath }); } res.status(200).json(content); }, function (err) { if (err === 'ENOENT') { return res.sendStatus(404); } next(err); }); }
[ "function", "getFn", "(", "req", ",", "res", ",", "next", ")", "{", "var", "reqPath", "=", "req", ".", "params", "[", "0", "]", ";", "debug", "(", "'getFn'", ",", "'reqPath'", ",", "reqPath", ")", ";", "stat", "(", "reqPath", ")", ".", "then", "(", "function", "(", "content", ")", "{", "if", "(", "!", "!", "content", ".", "type", "&&", "content", ".", "type", "===", "'file'", ")", "{", "return", "res", ".", "sendFile", "(", "reqPath", ",", "{", "root", ":", "ramlPath", "}", ")", ";", "}", "res", ".", "status", "(", "200", ")", ".", "json", "(", "content", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", "===", "'ENOENT'", ")", "{", "return", "res", ".", "sendStatus", "(", "404", ")", ";", "}", "next", "(", "err", ")", ";", "}", ")", ";", "}" ]
manages file and directory retrieval
[ "manages", "file", "and", "directory", "retrieval" ]
0ae9a5cd535c1a1956544745c314b408352d7dc9
https://github.com/colthreepv/express-raml-store/blob/0ae9a5cd535c1a1956544745c314b408352d7dc9/api.js#L99-L115
train
IonicaBizau/abs
lib/index.js
abs
function abs(input) { if (!input) { return process.cwd(); } if (input.charAt(0) === "/") { return input; } if (input.charAt(0) === "~" && input.charAt(1) === "/") { input = ul.HOME_DIR + input.substr(1); } return path.resolve(input); }
javascript
function abs(input) { if (!input) { return process.cwd(); } if (input.charAt(0) === "/") { return input; } if (input.charAt(0) === "~" && input.charAt(1) === "/") { input = ul.HOME_DIR + input.substr(1); } return path.resolve(input); }
[ "function", "abs", "(", "input", ")", "{", "if", "(", "!", "input", ")", "{", "return", "process", ".", "cwd", "(", ")", ";", "}", "if", "(", "input", ".", "charAt", "(", "0", ")", "===", "\"/\"", ")", "{", "return", "input", ";", "}", "if", "(", "input", ".", "charAt", "(", "0", ")", "===", "\"~\"", "&&", "input", ".", "charAt", "(", "1", ")", "===", "\"/\"", ")", "{", "input", "=", "ul", ".", "HOME_DIR", "+", "input", ".", "substr", "(", "1", ")", ";", "}", "return", "path", ".", "resolve", "(", "input", ")", ";", "}" ]
abs Computes the absolute path of an input. @name abs @function @param {String} input The input path (if not provided, the current working directory will be returned). @return {String} The absolute path.
[ "abs", "Computes", "the", "absolute", "path", "of", "an", "input", "." ]
9b570aa5f0a6ca5580a0d93cb7cffad9be618daf
https://github.com/IonicaBizau/abs/blob/9b570aa5f0a6ca5580a0d93cb7cffad9be618daf/lib/index.js#L17-L24
train
Innovailable/node-libnice
src/module.js
inject
function inject(target, source) { for (var k in source.prototype) { target.prototype[k] = source.prototype[k]; } }
javascript
function inject(target, source) { for (var k in source.prototype) { target.prototype[k] = source.prototype[k]; } }
[ "function", "inject", "(", "target", ",", "source", ")", "{", "for", "(", "var", "k", "in", "source", ".", "prototype", ")", "{", "target", ".", "prototype", "[", "k", "]", "=", "source", ".", "prototype", "[", "k", "]", ";", "}", "}" ]
turn the stream into an event emitter
[ "turn", "the", "stream", "into", "an", "event", "emitter" ]
f0eb491bab6314cb5bc019a1a229c8d45de5c5a0
https://github.com/Innovailable/node-libnice/blob/f0eb491bab6314cb5bc019a1a229c8d45de5c5a0/src/module.js#L7-L11
train
toolbuddy/docoGen
lib/docogen-latex-engine.js
append_nested
function append_nested(concater,items){ concater += `\\begin{enumerate}\n`; for(var index in items){ concater += `\\item ${items[index].name}\n`; // doing append job if(items[index].subitems != undefined){ concater = append_nested(concater,items[index].subitems); } } concater += `\\end{enumerate}\n`; return concater; }
javascript
function append_nested(concater,items){ concater += `\\begin{enumerate}\n`; for(var index in items){ concater += `\\item ${items[index].name}\n`; // doing append job if(items[index].subitems != undefined){ concater = append_nested(concater,items[index].subitems); } } concater += `\\end{enumerate}\n`; return concater; }
[ "function", "append_nested", "(", "concater", ",", "items", ")", "{", "concater", "+=", "`", "\\\\", "\\n", "`", ";", "for", "(", "var", "index", "in", "items", ")", "{", "concater", "+=", "`", "\\\\", "${", "items", "[", "index", "]", ".", "name", "}", "\\n", "`", ";", "if", "(", "items", "[", "index", "]", ".", "subitems", "!=", "undefined", ")", "{", "concater", "=", "append_nested", "(", "concater", ",", "items", "[", "index", "]", ".", "subitems", ")", ";", "}", "}", "concater", "+=", "`", "\\\\", "\\n", "`", ";", "return", "concater", ";", "}" ]
list structure operation
[ "list", "structure", "operation" ]
712d268e1c91a091da0a09b3a017e12b864d9f5d
https://github.com/toolbuddy/docoGen/blob/712d268e1c91a091da0a09b3a017e12b864d9f5d/lib/docogen-latex-engine.js#L373-L384
train
azendal/neon
stdlib/widget.js
_destroy
function _destroy() { var childrenLength; if (this.element) { this.element.remove(); } if (this.children !== null){ childrenLength = this.children.length; while(childrenLength > 0){ this.children[0].destroy(); if (this.children.length === childrenLength) { this.children.shift(); } childrenLength--; } } if (this.parent) { this.parent.removeChild(this); } this.children = null; this.element = null; }
javascript
function _destroy() { var childrenLength; if (this.element) { this.element.remove(); } if (this.children !== null){ childrenLength = this.children.length; while(childrenLength > 0){ this.children[0].destroy(); if (this.children.length === childrenLength) { this.children.shift(); } childrenLength--; } } if (this.parent) { this.parent.removeChild(this); } this.children = null; this.element = null; }
[ "function", "_destroy", "(", ")", "{", "var", "childrenLength", ";", "if", "(", "this", ".", "element", ")", "{", "this", ".", "element", ".", "remove", "(", ")", ";", "}", "if", "(", "this", ".", "children", "!==", "null", ")", "{", "childrenLength", "=", "this", ".", "children", ".", "length", ";", "while", "(", "childrenLength", ">", "0", ")", "{", "this", ".", "children", "[", "0", "]", ".", "destroy", "(", ")", ";", "if", "(", "this", ".", "children", ".", "length", "===", "childrenLength", ")", "{", "this", ".", "children", ".", "shift", "(", ")", ";", "}", "childrenLength", "--", ";", "}", "}", "if", "(", "this", ".", "parent", ")", "{", "this", ".", "parent", ".", "removeChild", "(", "this", ")", ";", "}", "this", ".", "children", "=", "null", ";", "this", ".", "element", "=", "null", ";", "}" ]
Destroy implementation. Its main responsabilities are cleaning all references to other objects so garbage collector can collect the memory used by this and the other objects @property _destroy <private> [Function] @method @return undefined [undefined]
[ "Destroy", "implementation", ".", "Its", "main", "responsabilities", "are", "cleaning", "all", "references", "to", "other", "objects", "so", "garbage", "collector", "can", "collect", "the", "memory", "used", "by", "this", "and", "the", "other", "objects" ]
01d05ded3fb6ab1d849d441ed7550a37df5365d8
https://github.com/azendal/neon/blob/01d05ded3fb6ab1d849d441ed7550a37df5365d8/stdlib/widget.js#L246-L270
train
azendal/neon
stdlib/widget.js
destroy
function destroy() { if (this.__destroyed === true) { console.warn('calling on destroyed object'); } this.dispatch('beforeDestroy'); this._destroy(); this.dispatch('destroy'); this.eventListeners = null; this.__destroyed = true; return null; }
javascript
function destroy() { if (this.__destroyed === true) { console.warn('calling on destroyed object'); } this.dispatch('beforeDestroy'); this._destroy(); this.dispatch('destroy'); this.eventListeners = null; this.__destroyed = true; return null; }
[ "function", "destroy", "(", ")", "{", "if", "(", "this", ".", "__destroyed", "===", "true", ")", "{", "console", ".", "warn", "(", "'calling on destroyed object'", ")", ";", "}", "this", ".", "dispatch", "(", "'beforeDestroy'", ")", ";", "this", ".", "_destroy", "(", ")", ";", "this", ".", "dispatch", "(", "'destroy'", ")", ";", "this", ".", "eventListeners", "=", "null", ";", "this", ".", "__destroyed", "=", "true", ";", "return", "null", ";", "}" ]
Destroy public method, this one should not be replaced @property destroy <public> [Function] @method @return null [null]
[ "Destroy", "public", "method", "this", "one", "should", "not", "be", "replaced" ]
01d05ded3fb6ab1d849d441ed7550a37df5365d8
https://github.com/azendal/neon/blob/01d05ded3fb6ab1d849d441ed7550a37df5365d8/stdlib/widget.js#L278-L291
train
azendal/neon
stdlib/widget.js
render
function render(element, beforeElement) { if (this.__destroyed === true) { console.warn('calling on destroyed object'); } this.dispatch('beforeRender', { element : element, beforeElement : beforeElement }); if (beforeElement) { this.element.insertBefore(beforeElement); } else { this.element.appendTo(element); } this.dispatch('render'); return this; }
javascript
function render(element, beforeElement) { if (this.__destroyed === true) { console.warn('calling on destroyed object'); } this.dispatch('beforeRender', { element : element, beforeElement : beforeElement }); if (beforeElement) { this.element.insertBefore(beforeElement); } else { this.element.appendTo(element); } this.dispatch('render'); return this; }
[ "function", "render", "(", "element", ",", "beforeElement", ")", "{", "if", "(", "this", ".", "__destroyed", "===", "true", ")", "{", "console", ".", "warn", "(", "'calling on destroyed object'", ")", ";", "}", "this", ".", "dispatch", "(", "'beforeRender'", ",", "{", "element", ":", "element", ",", "beforeElement", ":", "beforeElement", "}", ")", ";", "if", "(", "beforeElement", ")", "{", "this", ".", "element", ".", "insertBefore", "(", "beforeElement", ")", ";", "}", "else", "{", "this", ".", "element", ".", "appendTo", "(", "element", ")", ";", "}", "this", ".", "dispatch", "(", "'render'", ")", ";", "return", "this", ";", "}" ]
The render method is the mechanism by which you pass a widget from living only on memory to get into the DOM and with this into the application flow. The recomendation is that render is the last method of the setup of a widget, including appending its children. this is because once a widget gets renderer, further operations cause browser reflows, and DOM operations are slower than memory operations. This method should not be replaced by its children. @property render <public> [Function] @method @argument element <required> [JQuery] (undefined) This is the element into which the widget will be appended. @argument beforeElement <optional> [jQuery] (undefined) this is the element that will be used as a reference to insert the widgets element. this argument must be a child of the "element" argument. @return this [Widget]
[ "The", "render", "method", "is", "the", "mechanism", "by", "which", "you", "pass", "a", "widget", "from", "living", "only", "on", "memory", "to", "get", "into", "the", "DOM", "and", "with", "this", "into", "the", "application", "flow", ".", "The", "recomendation", "is", "that", "render", "is", "the", "last", "method", "of", "the", "setup", "of", "a", "widget", "including", "appending", "its", "children", ".", "this", "is", "because", "once", "a", "widget", "gets", "renderer", "further", "operations", "cause", "browser", "reflows", "and", "DOM", "operations", "are", "slower", "than", "memory", "operations", ".", "This", "method", "should", "not", "be", "replaced", "by", "its", "children", "." ]
01d05ded3fb6ab1d849d441ed7550a37df5365d8
https://github.com/azendal/neon/blob/01d05ded3fb6ab1d849d441ed7550a37df5365d8/stdlib/widget.js#L310-L325
train
nodebox/g.js
src/libraries/vg/util/math.js
_grad
function _grad(hash, x, y, z) { var h, u, v; h = hash & 15; u = h < 8 ? x : y; v = h < 4 ? y : h === 12 || h === 14 ? x : z; return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v); }
javascript
function _grad(hash, x, y, z) { var h, u, v; h = hash & 15; u = h < 8 ? x : y; v = h < 4 ? y : h === 12 || h === 14 ? x : z; return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v); }
[ "function", "_grad", "(", "hash", ",", "x", ",", "y", ",", "z", ")", "{", "var", "h", ",", "u", ",", "v", ";", "h", "=", "hash", "&", "15", ";", "u", "=", "h", "<", "8", "?", "x", ":", "y", ";", "v", "=", "h", "<", "4", "?", "y", ":", "h", "===", "12", "||", "h", "===", "14", "?", "x", ":", "z", ";", "return", "(", "(", "h", "&", "1", ")", "===", "0", "?", "u", ":", "-", "u", ")", "+", "(", "(", "h", "&", "2", ")", "===", "0", "?", "v", ":", "-", "v", ")", ";", "}" ]
Convert low 4 bits of hash code into 12 gradient directions.
[ "Convert", "low", "4", "bits", "of", "hash", "code", "into", "12", "gradient", "directions", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/vg/util/math.js#L79-L85
train
asakusuma/ember-rollup
src/index.js
isPreBuilt
function isPreBuilt(indexObj, preBuiltPath) { if (!(indexObj.isDevelopingAddon && indexObj.isDevelopingAddon()) && fs.existsSync(preBuiltPath)) { return true; } return false; }
javascript
function isPreBuilt(indexObj, preBuiltPath) { if (!(indexObj.isDevelopingAddon && indexObj.isDevelopingAddon()) && fs.existsSync(preBuiltPath)) { return true; } return false; }
[ "function", "isPreBuilt", "(", "indexObj", ",", "preBuiltPath", ")", "{", "if", "(", "!", "(", "indexObj", ".", "isDevelopingAddon", "&&", "indexObj", ".", "isDevelopingAddon", "(", ")", ")", "&&", "fs", ".", "existsSync", "(", "preBuiltPath", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Verify if dependency module is prebuilt already
[ "Verify", "if", "dependency", "module", "is", "prebuilt", "already" ]
253c7f5999ca7fb33535d661749b3283720fdb77
https://github.com/asakusuma/ember-rollup/blob/253c7f5999ca7fb33535d661749b3283720fdb77/src/index.js#L10-L15
train
Natural-Intelligence/docker-compose-mocha
index.js
dockerComposeTool
function dockerComposeTool(beforeFunction/* :Function */, afterFunction/* :Function */, pathToComposeFile/* : string */, { startOnlyTheseServices, envName, envVars, healthCheck, cleanUp, containerCleanUp, shouldPullImages = true, brutallyKill = false } /* :DockerComposeToolOptions */ = {})/* : string */ { const randomComposeEnv = envName ? extractEnvFromEnvName(envName) : getRandomEnvironmentName(chance); const runNameSpecific = randomComposeEnv.envName; const runNameDisplay = `${randomComposeEnv.firstName} ${randomComposeEnv.lastName}`; const performCleanup = cleanUp === undefined ? true : cleanUp; const performContainerCleanup = containerCleanUp === undefined ? true : containerCleanUp; beforeFunction(Promise.coroutine(function* () { if (shouldPullImages) { yield dockerPullImagesFromComposeFile(pathToComposeFile, startOnlyTheseServices); } if (performCleanup) { yield cleanupOrphanEnvironments(); } const onlyTheseServicesMessage = startOnlyTheseServices ? `, using only these services: ${startOnlyTheseServices.join(',')}` : ''; const consoleMessage = `Docker: starting up runtime environment for this run (codenamed: ${runNameDisplay})${onlyTheseServicesMessage}... `; const spinner = new Spinner(`${chalk.cyan(consoleMessage)}${chalk.yellow('%s')}`); if (!process.env.NOSPIN) { spinner.setSpinnerString('|/-\\'); spinner.start(); } else { console.log(consoleMessage); } const onlyTheseServicesMessageCommandAddition = startOnlyTheseServices ? startOnlyTheseServices.join(' ') : ''; yield exec(`docker-compose -p ${runNameSpecific} -f "${pathToComposeFile}" up -d ${onlyTheseServicesMessageCommandAddition}`, envVars ? { env: envVars } : {}); if (!process.env.NOSPIN) { spinner.stop(); console.log(''); // We add this in order to generate a new line after the spinner has stopped } if (healthCheck !== null && typeof healthCheck === 'object' && healthCheck.state === true) { yield healthCheckMethods.verifyServicesReady(runNameSpecific, pathToComposeFile, healthCheck.options || {}, startOnlyTheseServices); } })); afterFunction(() => { if (performContainerCleanup) { return cleanupContainersByEnvironmentName(runNameSpecific, pathToComposeFile, runNameDisplay, brutallyKill); } return Promise.resolve(); }); return runNameSpecific; }
javascript
function dockerComposeTool(beforeFunction/* :Function */, afterFunction/* :Function */, pathToComposeFile/* : string */, { startOnlyTheseServices, envName, envVars, healthCheck, cleanUp, containerCleanUp, shouldPullImages = true, brutallyKill = false } /* :DockerComposeToolOptions */ = {})/* : string */ { const randomComposeEnv = envName ? extractEnvFromEnvName(envName) : getRandomEnvironmentName(chance); const runNameSpecific = randomComposeEnv.envName; const runNameDisplay = `${randomComposeEnv.firstName} ${randomComposeEnv.lastName}`; const performCleanup = cleanUp === undefined ? true : cleanUp; const performContainerCleanup = containerCleanUp === undefined ? true : containerCleanUp; beforeFunction(Promise.coroutine(function* () { if (shouldPullImages) { yield dockerPullImagesFromComposeFile(pathToComposeFile, startOnlyTheseServices); } if (performCleanup) { yield cleanupOrphanEnvironments(); } const onlyTheseServicesMessage = startOnlyTheseServices ? `, using only these services: ${startOnlyTheseServices.join(',')}` : ''; const consoleMessage = `Docker: starting up runtime environment for this run (codenamed: ${runNameDisplay})${onlyTheseServicesMessage}... `; const spinner = new Spinner(`${chalk.cyan(consoleMessage)}${chalk.yellow('%s')}`); if (!process.env.NOSPIN) { spinner.setSpinnerString('|/-\\'); spinner.start(); } else { console.log(consoleMessage); } const onlyTheseServicesMessageCommandAddition = startOnlyTheseServices ? startOnlyTheseServices.join(' ') : ''; yield exec(`docker-compose -p ${runNameSpecific} -f "${pathToComposeFile}" up -d ${onlyTheseServicesMessageCommandAddition}`, envVars ? { env: envVars } : {}); if (!process.env.NOSPIN) { spinner.stop(); console.log(''); // We add this in order to generate a new line after the spinner has stopped } if (healthCheck !== null && typeof healthCheck === 'object' && healthCheck.state === true) { yield healthCheckMethods.verifyServicesReady(runNameSpecific, pathToComposeFile, healthCheck.options || {}, startOnlyTheseServices); } })); afterFunction(() => { if (performContainerCleanup) { return cleanupContainersByEnvironmentName(runNameSpecific, pathToComposeFile, runNameDisplay, brutallyKill); } return Promise.resolve(); }); return runNameSpecific; }
[ "function", "dockerComposeTool", "(", "beforeFunction", ",", "afterFunction", ",", "pathToComposeFile", ",", "{", "startOnlyTheseServices", ",", "envName", ",", "envVars", ",", "healthCheck", ",", "cleanUp", ",", "containerCleanUp", ",", "shouldPullImages", "=", "true", ",", "brutallyKill", "=", "false", "}", "=", "{", "}", ")", "{", "const", "randomComposeEnv", "=", "envName", "?", "extractEnvFromEnvName", "(", "envName", ")", ":", "getRandomEnvironmentName", "(", "chance", ")", ";", "const", "runNameSpecific", "=", "randomComposeEnv", ".", "envName", ";", "const", "runNameDisplay", "=", "`", "${", "randomComposeEnv", ".", "firstName", "}", "${", "randomComposeEnv", ".", "lastName", "}", "`", ";", "const", "performCleanup", "=", "cleanUp", "===", "undefined", "?", "true", ":", "cleanUp", ";", "const", "performContainerCleanup", "=", "containerCleanUp", "===", "undefined", "?", "true", ":", "containerCleanUp", ";", "beforeFunction", "(", "Promise", ".", "coroutine", "(", "function", "*", "(", ")", "{", "if", "(", "shouldPullImages", ")", "{", "yield", "dockerPullImagesFromComposeFile", "(", "pathToComposeFile", ",", "startOnlyTheseServices", ")", ";", "}", "if", "(", "performCleanup", ")", "{", "yield", "cleanupOrphanEnvironments", "(", ")", ";", "}", "const", "onlyTheseServicesMessage", "=", "startOnlyTheseServices", "?", "`", "${", "startOnlyTheseServices", ".", "join", "(", "','", ")", "}", "`", ":", "''", ";", "const", "consoleMessage", "=", "`", "${", "runNameDisplay", "}", "${", "onlyTheseServicesMessage", "}", "`", ";", "const", "spinner", "=", "new", "Spinner", "(", "`", "${", "chalk", ".", "cyan", "(", "consoleMessage", ")", "}", "${", "chalk", ".", "yellow", "(", "'%s'", ")", "}", "`", ")", ";", "if", "(", "!", "process", ".", "env", ".", "NOSPIN", ")", "{", "spinner", ".", "setSpinnerString", "(", "'|/-\\\\'", ")", ";", "\\\\", "}", "else", "spinner", ".", "start", "(", ")", ";", "{", "console", ".", "log", "(", "consoleMessage", ")", ";", "}", "const", "onlyTheseServicesMessageCommandAddition", "=", "startOnlyTheseServices", "?", "startOnlyTheseServices", ".", "join", "(", "' '", ")", ":", "''", ";", "yield", "exec", "(", "`", "${", "runNameSpecific", "}", "${", "pathToComposeFile", "}", "${", "onlyTheseServicesMessageCommandAddition", "}", "`", ",", "envVars", "?", "{", "env", ":", "envVars", "}", ":", "{", "}", ")", ";", "if", "(", "!", "process", ".", "env", ".", "NOSPIN", ")", "{", "spinner", ".", "stop", "(", ")", ";", "console", ".", "log", "(", "''", ")", ";", "}", "}", ")", ")", ";", "if", "(", "healthCheck", "!==", "null", "&&", "typeof", "healthCheck", "===", "'object'", "&&", "healthCheck", ".", "state", "===", "true", ")", "{", "yield", "healthCheckMethods", ".", "verifyServicesReady", "(", "runNameSpecific", ",", "pathToComposeFile", ",", "healthCheck", ".", "options", "||", "{", "}", ",", "startOnlyTheseServices", ")", ";", "}", "afterFunction", "(", "(", ")", "=>", "{", "if", "(", "performContainerCleanup", ")", "{", "return", "cleanupContainersByEnvironmentName", "(", "runNameSpecific", ",", "pathToComposeFile", ",", "runNameDisplay", ",", "brutallyKill", ")", ";", "}", "return", "Promise", ".", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
Running this method will fire up the environment written in your provided Docker Compose file. The environment will run isolated and with random ports to not interfere with any other test suites which might be running on the same CI machine. This methods expects the following variables @param beforeFunction - from your Mocha.js setup file you need to provide access to the global before() function so that this code can use it to start up your environment. @param afterFunction - from your Mocha.js setup file you need to provide access to the global after() function so that this code can use it to shut down your environment and clean it from the CI server @param pathToComposeFile - the absolute path to your docker-compose.yml file for your test environment
[ "Running", "this", "method", "will", "fire", "up", "the", "environment", "written", "in", "your", "provided", "Docker", "Compose", "file", ".", "The", "environment", "will", "run", "isolated", "and", "with", "random", "ports", "to", "not", "interfere", "with", "any", "other", "test", "suites", "which", "might", "be", "running", "on", "the", "same", "CI", "machine", "." ]
acdb9ed620027424943101de27ee418705b44d21
https://github.com/Natural-Intelligence/docker-compose-mocha/blob/acdb9ed620027424943101de27ee418705b44d21/index.js#L53-L115
train
wavesjs/waves-lfo
src/common/operator/Fft.js
reverseBits
function reverseBits(x, bits) { var y = 0; for (var i = 0; i < bits; i++) { y = (y << 1) | (x & 1); x >>>= 1; } return y; }
javascript
function reverseBits(x, bits) { var y = 0; for (var i = 0; i < bits; i++) { y = (y << 1) | (x & 1); x >>>= 1; } return y; }
[ "function", "reverseBits", "(", "x", ",", "bits", ")", "{", "var", "y", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "bits", ";", "i", "++", ")", "{", "y", "=", "(", "y", "<<", "1", ")", "|", "(", "x", "&", "1", ")", ";", "x", ">>>=", "1", ";", "}", "return", "y", ";", "}" ]
Returns the integer whose value is the reverse of the lowest 'bits' bits of the integer 'x'.
[ "Returns", "the", "integer", "whose", "value", "is", "the", "reverse", "of", "the", "lowest", "bits", "bits", "of", "the", "integer", "x", "." ]
4353a8ef55b7921755fe182cb09b0df566696bc8
https://github.com/wavesjs/waves-lfo/blob/4353a8ef55b7921755fe182cb09b0df566696bc8/src/common/operator/Fft.js#L108-L117
train
ismamz/postcss-click
index.js
selectorForm
function selectorForm(selector) { var str; if (selector.indexOf('[') !== -1) { var newSelector = attributeEquals(selector); newSelector = newSelector.replace('sel=', ''); // valid sass syntax var firstSelector = firstPart(selector); if (firstSelector in jquerySelectors) { str = jquerySelectors[firstSelector] .replace('%', '"' + newSelector + '"'); } } else if (selector in jquerySelectors) { str = jquerySelectors[selector].replace('%', ''); } else { str = '$("' + selector + '")'; } return str; }
javascript
function selectorForm(selector) { var str; if (selector.indexOf('[') !== -1) { var newSelector = attributeEquals(selector); newSelector = newSelector.replace('sel=', ''); // valid sass syntax var firstSelector = firstPart(selector); if (firstSelector in jquerySelectors) { str = jquerySelectors[firstSelector] .replace('%', '"' + newSelector + '"'); } } else if (selector in jquerySelectors) { str = jquerySelectors[selector].replace('%', ''); } else { str = '$("' + selector + '")'; } return str; }
[ "function", "selectorForm", "(", "selector", ")", "{", "var", "str", ";", "if", "(", "selector", ".", "indexOf", "(", "'['", ")", "!==", "-", "1", ")", "{", "var", "newSelector", "=", "attributeEquals", "(", "selector", ")", ";", "newSelector", "=", "newSelector", ".", "replace", "(", "'sel='", ",", "''", ")", ";", "var", "firstSelector", "=", "firstPart", "(", "selector", ")", ";", "if", "(", "firstSelector", "in", "jquerySelectors", ")", "{", "str", "=", "jquerySelectors", "[", "firstSelector", "]", ".", "replace", "(", "'%'", ",", "'\"'", "+", "newSelector", "+", "'\"'", ")", ";", "}", "}", "else", "if", "(", "selector", "in", "jquerySelectors", ")", "{", "str", "=", "jquerySelectors", "[", "selector", "]", ".", "replace", "(", "'%'", ",", "''", ")", ";", "}", "else", "{", "str", "=", "'$(\"'", "+", "selector", "+", "'\")'", ";", "}", "return", "str", ";", "}" ]
Create a jquery selector @param {string} selector target or element selector @return {string} returns selector form
[ "Create", "a", "jquery", "selector" ]
697adae57f27c3c40266f0f8fd895b13371b57f3
https://github.com/ismamz/postcss-click/blob/697adae57f27c3c40266f0f8fd895b13371b57f3/index.js#L44-L61
train
Skelware/node-file-parser
src/parsers/ini.js
_getNewSection
function _getNewSection(line) { var result = new RegExp(regex.section).exec(line || ''); return result && result[1]; }
javascript
function _getNewSection(line) { var result = new RegExp(regex.section).exec(line || ''); return result && result[1]; }
[ "function", "_getNewSection", "(", "line", ")", "{", "var", "result", "=", "new", "RegExp", "(", "regex", ".", "section", ")", ".", "exec", "(", "line", "||", "''", ")", ";", "return", "result", "&&", "result", "[", "1", "]", ";", "}" ]
Checks whether a line indicates a new section or not. @method _getNewSection @param [line] {String} The line to check. @returns {String} The section name, if found. @private
[ "Checks", "whether", "a", "line", "indicates", "a", "new", "section", "or", "not", "." ]
cdc88369a3c15fa94dec001dd7fab2e621031e40
https://github.com/Skelware/node-file-parser/blob/cdc88369a3c15fa94dec001dd7fab2e621031e40/src/parsers/ini.js#L213-L216
train
Skelware/node-file-parser
src/parsers/ini.js
_isNotValidIni
function _isNotValidIni(line) { var check = (line || '').match(regex.bad); return !!(check && check.length > 1); }
javascript
function _isNotValidIni(line) { var check = (line || '').match(regex.bad); return !!(check && check.length > 1); }
[ "function", "_isNotValidIni", "(", "line", ")", "{", "var", "check", "=", "(", "line", "||", "''", ")", ".", "match", "(", "regex", ".", "bad", ")", ";", "return", "!", "!", "(", "check", "&&", "check", ".", "length", ">", "1", ")", ";", "}" ]
Checks whether the line contains only valid ini syntax or not. @method _isNotValidIni @param [line] {String} The line to check. @returns {Boolean} @private
[ "Checks", "whether", "the", "line", "contains", "only", "valid", "ini", "syntax", "or", "not", "." ]
cdc88369a3c15fa94dec001dd7fab2e621031e40
https://github.com/Skelware/node-file-parser/blob/cdc88369a3c15fa94dec001dd7fab2e621031e40/src/parsers/ini.js#L226-L229
train
remarkablemark/youtube-video-id
index.js
getYouTubeVideoId
function getYouTubeVideoId(string) { if (typeof string !== 'string') { throw new TypeError('First argument must be a string.'); } var match = string.match(regex); if (match && match.length > 1) { return match[2]; } return string; }
javascript
function getYouTubeVideoId(string) { if (typeof string !== 'string') { throw new TypeError('First argument must be a string.'); } var match = string.match(regex); if (match && match.length > 1) { return match[2]; } return string; }
[ "function", "getYouTubeVideoId", "(", "string", ")", "{", "if", "(", "typeof", "string", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'First argument must be a string.'", ")", ";", "}", "var", "match", "=", "string", ".", "match", "(", "regex", ")", ";", "if", "(", "match", "&&", "match", ".", "length", ">", "1", ")", "{", "return", "match", "[", "2", "]", ";", "}", "return", "string", ";", "}" ]
Get the YouTube video ID from a url or string. @param {String} string - The url or string. @return {String} - The video ID.
[ "Get", "the", "YouTube", "video", "ID", "from", "a", "url", "or", "string", "." ]
b316de64617cbb8f30ddff5bd0b440f0df6fd632
https://github.com/remarkablemark/youtube-video-id/blob/b316de64617cbb8f30ddff5bd0b440f0df6fd632/index.js#L20-L29
train
Skelware/node-file-parser
src/NodeFileParser.js
link
function link(file, type, options) { if (file == null || file.length === 0 || typeof file !== 'string') { return null; } if (type && typeof type !== 'string') { options = type; type = undefined; } for (var i = 0; i < parsers.length; i++) { var parser = parsers[i]; if (type ? parser.name === type : parser.pattern.test(file)) { var Handler = new parser.Handler(file, options); Handler.name = parser.name; return Handler; } } }
javascript
function link(file, type, options) { if (file == null || file.length === 0 || typeof file !== 'string') { return null; } if (type && typeof type !== 'string') { options = type; type = undefined; } for (var i = 0; i < parsers.length; i++) { var parser = parsers[i]; if (type ? parser.name === type : parser.pattern.test(file)) { var Handler = new parser.Handler(file, options); Handler.name = parser.name; return Handler; } } }
[ "function", "link", "(", "file", ",", "type", ",", "options", ")", "{", "if", "(", "file", "==", "null", "||", "file", ".", "length", "===", "0", "||", "typeof", "file", "!==", "'string'", ")", "{", "return", "null", ";", "}", "if", "(", "type", "&&", "typeof", "type", "!==", "'string'", ")", "{", "options", "=", "type", ";", "type", "=", "undefined", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "parsers", ".", "length", ";", "i", "++", ")", "{", "var", "parser", "=", "parsers", "[", "i", "]", ";", "if", "(", "type", "?", "parser", ".", "name", "===", "type", ":", "parser", ".", "pattern", ".", "test", "(", "file", ")", ")", "{", "var", "Handler", "=", "new", "parser", ".", "Handler", "(", "file", ",", "options", ")", ";", "Handler", ".", "name", "=", "parser", ".", "name", ";", "return", "Handler", ";", "}", "}", "}" ]
Links a file to get read and write access to and from that file. @method link @param file {String} The location of the file to link to. @param [type=detected] {String} Force a specific parser for unknown file types. @param [options=default] {Object} The options to pass to the FileParser that will be created. @returns {? extends FileParser} A subclass of FileParser to handle the file if the file's extension is matched, or `null` if the file has an invalid path.
[ "Links", "a", "file", "to", "get", "read", "and", "write", "access", "to", "and", "from", "that", "file", "." ]
cdc88369a3c15fa94dec001dd7fab2e621031e40
https://github.com/Skelware/node-file-parser/blob/cdc88369a3c15fa94dec001dd7fab2e621031e40/src/NodeFileParser.js#L54-L73
train
reshape/expressions
lib/index.js
parseLoopStatement
function parseLoopStatement (input) { let current = 0 let char = input[current] // parse through keys `each **foo, bar** in x`, which is everything before // the word "in" const keys = [] let key = '' while (!`${char}${lookahead(3)}`.match(/\s(in|of)\s/)) { key += char next() // if we hit a comma, we're on to the next key if (char === ',') { keys.push(key.trim()) key = '' next() } // if we reach the end of the string without getting "in/of", it's an error if (typeof char === 'undefined') { throw new Error("Loop statement lacking 'in' or 'of' keyword") } } keys.push(key.trim()) // detect whether it's an in or of const loopType = lookahead(2) // space before, in/of, space after next(4) // the rest of the string is evaluated as the array/object to loop let expression = '' while (current < input.length) { expression += char next() } return {keys, expression, loopType} // Utility: Move to the next character in the parse function next (n = 1) { for (let i = 0; i < n; i++) { char = input[++current] } } // Utility: looks ahead n characters and returns the result function lookahead (n) { let counter = current const target = current + n let res = '' while (counter < target) { res += input[++counter] } return res } }
javascript
function parseLoopStatement (input) { let current = 0 let char = input[current] // parse through keys `each **foo, bar** in x`, which is everything before // the word "in" const keys = [] let key = '' while (!`${char}${lookahead(3)}`.match(/\s(in|of)\s/)) { key += char next() // if we hit a comma, we're on to the next key if (char === ',') { keys.push(key.trim()) key = '' next() } // if we reach the end of the string without getting "in/of", it's an error if (typeof char === 'undefined') { throw new Error("Loop statement lacking 'in' or 'of' keyword") } } keys.push(key.trim()) // detect whether it's an in or of const loopType = lookahead(2) // space before, in/of, space after next(4) // the rest of the string is evaluated as the array/object to loop let expression = '' while (current < input.length) { expression += char next() } return {keys, expression, loopType} // Utility: Move to the next character in the parse function next (n = 1) { for (let i = 0; i < n; i++) { char = input[++current] } } // Utility: looks ahead n characters and returns the result function lookahead (n) { let counter = current const target = current + n let res = '' while (counter < target) { res += input[++counter] } return res } }
[ "function", "parseLoopStatement", "(", "input", ")", "{", "let", "current", "=", "0", "let", "char", "=", "input", "[", "current", "]", "const", "keys", "=", "[", "]", "let", "key", "=", "''", "while", "(", "!", "`", "${", "char", "}", "${", "lookahead", "(", "3", ")", "}", "`", ".", "match", "(", "/", "\\s(in|of)\\s", "/", ")", ")", "{", "key", "+=", "char", "next", "(", ")", "if", "(", "char", "===", "','", ")", "{", "keys", ".", "push", "(", "key", ".", "trim", "(", ")", ")", "key", "=", "''", "next", "(", ")", "}", "if", "(", "typeof", "char", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "\"Loop statement lacking 'in' or 'of' keyword\"", ")", "}", "}", "keys", ".", "push", "(", "key", ".", "trim", "(", ")", ")", "const", "loopType", "=", "lookahead", "(", "2", ")", "next", "(", "4", ")", "let", "expression", "=", "''", "while", "(", "current", "<", "input", ".", "length", ")", "{", "expression", "+=", "char", "next", "(", ")", "}", "return", "{", "keys", ",", "expression", ",", "loopType", "}", "function", "next", "(", "n", "=", "1", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "char", "=", "input", "[", "++", "current", "]", "}", "}", "function", "lookahead", "(", "n", ")", "{", "let", "counter", "=", "current", "const", "target", "=", "current", "+", "n", "let", "res", "=", "''", "while", "(", "counter", "<", "target", ")", "{", "res", "+=", "input", "[", "++", "counter", "]", "}", "return", "res", "}", "}" ]
Given a "loop" parameter from an "each" tag, parses out the param names and expression to be looped through using a mini text parser.
[ "Given", "a", "loop", "parameter", "from", "an", "each", "tag", "parses", "out", "the", "param", "names", "and", "expression", "to", "be", "looped", "through", "using", "a", "mini", "text", "parser", "." ]
4088dd03e142e16a0d6e8920f59c7785c5b52202
https://github.com/reshape/expressions/blob/4088dd03e142e16a0d6e8920f59c7785c5b52202/lib/index.js#L231-L287
train
stennettm/historical
historical.js
function (val) { return val && typeof val === 'object' && !(val instanceof Date) && !(val instanceof ObjectId) && (!Array.isArray(val) || val.length > 0) && !(val instanceof Buffer); }
javascript
function (val) { return val && typeof val === 'object' && !(val instanceof Date) && !(val instanceof ObjectId) && (!Array.isArray(val) || val.length > 0) && !(val instanceof Buffer); }
[ "function", "(", "val", ")", "{", "return", "val", "&&", "typeof", "val", "===", "'object'", "&&", "!", "(", "val", "instanceof", "Date", ")", "&&", "!", "(", "val", "instanceof", "ObjectId", ")", "&&", "(", "!", "Array", ".", "isArray", "(", "val", ")", "||", "val", ".", "length", ">", "0", ")", "&&", "!", "(", "val", "instanceof", "Buffer", ")", ";", "}" ]
CODE BETWEEN THESE COMMENT LINES WAS ADAPTED FROM THE MONGOOSE CODEBASE
[ "CODE", "BETWEEN", "THESE", "COMMENT", "LINES", "WAS", "ADAPTED", "FROM", "THE", "MONGOOSE", "CODEBASE" ]
69844dcf23964c8b4bfa211c7da650b5e55ea1cd
https://github.com/stennettm/historical/blob/69844dcf23964c8b4bfa211c7da650b5e55ea1cd/historical.js#L95-L102
train
nodebox/g.js
src/libraries/img/process.js
function (inData, outData, width, height, options) { options = defaultOptions(options, {strength: 1}); var a = -clamp(options.strength, 0, 1); convolve5x5(inData, outData, width, height, [ [a, a, a, a, a], [a, a, a, a, a], [a, a, 1 - a * 24, a, a], [a, a, a, a, a], [a, a, a, a, a] ]); }
javascript
function (inData, outData, width, height, options) { options = defaultOptions(options, {strength: 1}); var a = -clamp(options.strength, 0, 1); convolve5x5(inData, outData, width, height, [ [a, a, a, a, a], [a, a, a, a, a], [a, a, 1 - a * 24, a, a], [a, a, a, a, a], [a, a, a, a, a] ]); }
[ "function", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "options", ")", "{", "options", "=", "defaultOptions", "(", "options", ",", "{", "strength", ":", "1", "}", ")", ";", "var", "a", "=", "-", "clamp", "(", "options", ".", "strength", ",", "0", ",", "1", ")", ";", "convolve5x5", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "[", "[", "a", ",", "a", ",", "a", ",", "a", ",", "a", "]", ",", "[", "a", ",", "a", ",", "a", ",", "a", ",", "a", "]", ",", "[", "a", ",", "a", ",", "1", "-", "a", "*", "24", ",", "a", ",", "a", "]", ",", "[", "a", ",", "a", ",", "a", ",", "a", ",", "a", "]", ",", "[", "a", ",", "a", ",", "a", ",", "a", ",", "a", "]", "]", ")", ";", "}" ]
A 5x5 high-pass filter
[ "A", "5x5", "high", "-", "pass", "filter" ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/process.js#L664-L675
train
nodebox/g.js
src/libraries/img/process.js
function (inData, outData, width, height) { var c = 1 / 9; convolve3x3(inData, outData, width, height, [ [c, c, c], [c, c, c], [c, c, c] ]); }
javascript
function (inData, outData, width, height) { var c = 1 / 9; convolve3x3(inData, outData, width, height, [ [c, c, c], [c, c, c], [c, c, c] ]); }
[ "function", "(", "inData", ",", "outData", ",", "width", ",", "height", ")", "{", "var", "c", "=", "1", "/", "9", ";", "convolve3x3", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "[", "[", "c", ",", "c", ",", "c", "]", ",", "[", "c", ",", "c", ",", "c", "]", ",", "[", "c", ",", "c", ",", "c", "]", "]", ")", ";", "}" ]
A 3x3 low-pass mean filter
[ "A", "3x3", "low", "-", "pass", "mean", "filter" ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/process.js#L678-L686
train
nodebox/g.js
src/libraries/img/process.js
function (inData, outData, width, height) { var c = 1 / 25; convolve5x5(inData, outData, width, height, [ [c, c, c, c, c], [c, c, c, c, c], [c, c, c, c, c], [c, c, c, c, c], [c, c, c, c, c] ]); }
javascript
function (inData, outData, width, height) { var c = 1 / 25; convolve5x5(inData, outData, width, height, [ [c, c, c, c, c], [c, c, c, c, c], [c, c, c, c, c], [c, c, c, c, c], [c, c, c, c, c] ]); }
[ "function", "(", "inData", ",", "outData", ",", "width", ",", "height", ")", "{", "var", "c", "=", "1", "/", "25", ";", "convolve5x5", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "[", "[", "c", ",", "c", ",", "c", ",", "c", ",", "c", "]", ",", "[", "c", ",", "c", ",", "c", ",", "c", ",", "c", "]", ",", "[", "c", ",", "c", ",", "c", ",", "c", ",", "c", "]", ",", "[", "c", ",", "c", ",", "c", ",", "c", ",", "c", "]", ",", "[", "c", ",", "c", ",", "c", ",", "c", ",", "c", "]", "]", ")", ";", "}" ]
A 5x5 low-pass mean filter
[ "A", "5x5", "low", "-", "pass", "mean", "filter" ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/process.js#L689-L699
train
nodebox/g.js
src/libraries/img/process.js
function (inData, outData, width, height, options) { options = defaultOptions(options, {strength: 1}); var a = clamp(options.strength, 0, 1) * 5; convolve3x3(inData, outData, width, height, [ [ 0, -a, 0], [-a, 0, a], [ 0, a, 0] ], false, true); }
javascript
function (inData, outData, width, height, options) { options = defaultOptions(options, {strength: 1}); var a = clamp(options.strength, 0, 1) * 5; convolve3x3(inData, outData, width, height, [ [ 0, -a, 0], [-a, 0, a], [ 0, a, 0] ], false, true); }
[ "function", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "options", ")", "{", "options", "=", "defaultOptions", "(", "options", ",", "{", "strength", ":", "1", "}", ")", ";", "var", "a", "=", "clamp", "(", "options", ".", "strength", ",", "0", ",", "1", ")", "*", "5", ";", "convolve3x3", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "[", "[", "0", ",", "-", "a", ",", "0", "]", ",", "[", "-", "a", ",", "0", ",", "a", "]", ",", "[", "0", ",", "a", ",", "0", "]", "]", ",", "false", ",", "true", ")", ";", "}" ]
A 3x3 Cross edge-detect
[ "A", "3x3", "Cross", "edge", "-", "detect" ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/process.js#L702-L712
train
nodebox/g.js
src/libraries/img/process.js
function (inData, outData, width, height, options) { options = defaultOptions(options, {amount: 1, angle: 0}); var i, n = width * height * 4, amount = options.amount, angle = options.angle, x = Math.cos(-angle) * amount, y = Math.sin(-angle) * amount, a00 = -x - y, a10 = -x, a20 = y - x, a01 = -y, a21 = y, a02 = -y + x, a12 = x, a22 = y + x, tmpData = []; convolve3x3(inData, tmpData, width, height, [ [a00, a01, a02], [a10, 0, a12], [a20, a21, a22] ]); for (i = 0; i < n; i += 4) { outData[i] = 128 + tmpData[i]; outData[i + 1] = 128 + tmpData[i + 1]; outData[i + 2] = 128 + tmpData[i + 2]; outData[i + 3] = inData[i + 3]; } }
javascript
function (inData, outData, width, height, options) { options = defaultOptions(options, {amount: 1, angle: 0}); var i, n = width * height * 4, amount = options.amount, angle = options.angle, x = Math.cos(-angle) * amount, y = Math.sin(-angle) * amount, a00 = -x - y, a10 = -x, a20 = y - x, a01 = -y, a21 = y, a02 = -y + x, a12 = x, a22 = y + x, tmpData = []; convolve3x3(inData, tmpData, width, height, [ [a00, a01, a02], [a10, 0, a12], [a20, a21, a22] ]); for (i = 0; i < n; i += 4) { outData[i] = 128 + tmpData[i]; outData[i + 1] = 128 + tmpData[i + 1]; outData[i + 2] = 128 + tmpData[i + 2]; outData[i + 3] = inData[i + 3]; } }
[ "function", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "options", ")", "{", "options", "=", "defaultOptions", "(", "options", ",", "{", "amount", ":", "1", ",", "angle", ":", "0", "}", ")", ";", "var", "i", ",", "n", "=", "width", "*", "height", "*", "4", ",", "amount", "=", "options", ".", "amount", ",", "angle", "=", "options", ".", "angle", ",", "x", "=", "Math", ".", "cos", "(", "-", "angle", ")", "*", "amount", ",", "y", "=", "Math", ".", "sin", "(", "-", "angle", ")", "*", "amount", ",", "a00", "=", "-", "x", "-", "y", ",", "a10", "=", "-", "x", ",", "a20", "=", "y", "-", "x", ",", "a01", "=", "-", "y", ",", "a21", "=", "y", ",", "a02", "=", "-", "y", "+", "x", ",", "a12", "=", "x", ",", "a22", "=", "y", "+", "x", ",", "tmpData", "=", "[", "]", ";", "convolve3x3", "(", "inData", ",", "tmpData", ",", "width", ",", "height", ",", "[", "[", "a00", ",", "a01", ",", "a02", "]", ",", "[", "a10", ",", "0", ",", "a12", "]", ",", "[", "a20", ",", "a21", ",", "a22", "]", "]", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "n", ";", "i", "+=", "4", ")", "{", "outData", "[", "i", "]", "=", "128", "+", "tmpData", "[", "i", "]", ";", "outData", "[", "i", "+", "1", "]", "=", "128", "+", "tmpData", "[", "i", "+", "1", "]", ";", "outData", "[", "i", "+", "2", "]", "=", "128", "+", "tmpData", "[", "i", "+", "2", "]", ";", "outData", "[", "i", "+", "3", "]", "=", "inData", "[", "i", "+", "3", "]", ";", "}", "}" ]
3x3 directional emboss
[ "3x3", "directional", "emboss" ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/process.js#L715-L747
train
nodebox/g.js
src/libraries/img/process.js
function (inData, outData, width, height) { convolve3x3(inData, outData, width, height, [ [-1, -1, -1], [-1, 8, -1], [-1, -1, -1] ], false, true, true); }
javascript
function (inData, outData, width, height) { convolve3x3(inData, outData, width, height, [ [-1, -1, -1], [-1, 8, -1], [-1, -1, -1] ], false, true, true); }
[ "function", "(", "inData", ",", "outData", ",", "width", ",", "height", ")", "{", "convolve3x3", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "[", "[", "-", "1", ",", "-", "1", ",", "-", "1", "]", ",", "[", "-", "1", ",", "8", ",", "-", "1", "]", ",", "[", "-", "1", ",", "-", "1", ",", "-", "1", "]", "]", ",", "false", ",", "true", ",", "true", ")", ";", "}" ]
A 3x3 Laplacian edge-detect
[ "A", "3x3", "Laplacian", "edge", "-", "detect" ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/process.js#L830-L838
train
nodebox/g.js
src/libraries/img/process.js
function (inData, outData, width, height) { convolve5x5(inData, outData, width, height, [ [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, 24, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1] ], false, true, true); }
javascript
function (inData, outData, width, height) { convolve5x5(inData, outData, width, height, [ [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, 24, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1] ], false, true, true); }
[ "function", "(", "inData", ",", "outData", ",", "width", ",", "height", ")", "{", "convolve5x5", "(", "inData", ",", "outData", ",", "width", ",", "height", ",", "[", "[", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", "]", ",", "[", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", "]", ",", "[", "-", "1", ",", "-", "1", ",", "24", ",", "-", "1", ",", "-", "1", "]", ",", "[", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", "]", ",", "[", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", "]", "]", ",", "false", ",", "true", ",", "true", ")", ";", "}" ]
A 5x5 Laplacian edge-detect
[ "A", "5x5", "Laplacian", "edge", "-", "detect" ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/process.js#L841-L851
train
YouneLL/trim-request
index.js
trimStringProperties
function trimStringProperties (obj) { if (obj !== null && typeof obj === 'object') { for ( var prop in obj ) { // if the property is an object trim it too if ( typeof obj[prop] === 'object' ) { return trimStringProperties(obj[prop]); } // if it's a string remove begin and end whitespaces if ( typeof obj[prop] === 'string' ) { obj[prop] = obj[prop].trim(); } } } }
javascript
function trimStringProperties (obj) { if (obj !== null && typeof obj === 'object') { for ( var prop in obj ) { // if the property is an object trim it too if ( typeof obj[prop] === 'object' ) { return trimStringProperties(obj[prop]); } // if it's a string remove begin and end whitespaces if ( typeof obj[prop] === 'string' ) { obj[prop] = obj[prop].trim(); } } } }
[ "function", "trimStringProperties", "(", "obj", ")", "{", "if", "(", "obj", "!==", "null", "&&", "typeof", "obj", "===", "'object'", ")", "{", "for", "(", "var", "prop", "in", "obj", ")", "{", "if", "(", "typeof", "obj", "[", "prop", "]", "===", "'object'", ")", "{", "return", "trimStringProperties", "(", "obj", "[", "prop", "]", ")", ";", "}", "if", "(", "typeof", "obj", "[", "prop", "]", "===", "'string'", ")", "{", "obj", "[", "prop", "]", "=", "obj", "[", "prop", "]", ".", "trim", "(", ")", ";", "}", "}", "}", "}" ]
trim all string prpoerties of an object
[ "trim", "all", "string", "prpoerties", "of", "an", "object" ]
821ccd147d790c56ba68f62495354464721f05be
https://github.com/YouneLL/trim-request/blob/821ccd147d790c56ba68f62495354464721f05be/index.js#L2-L22
train
asakusuma/ember-rollup
src/prebuild.js
preBuild
function preBuild(addonPath) { // Require the addon let addonToBuild = require(addonPath); // Augment it with isDevelopingAddon function. addonToBuild.isDevelopingAddon = function() { return true; } // If addon has pre-built path set in it use that else use the default path if(!addonToBuild.PREBUILT_PATH) { addonToBuild.PREBUILT_PATH = `${addonPath}/pre-built`; } fs.removeSync(addonToBuild.PREBUILT_PATH); const ui = new UI({ inputStream: process.stdin, outputStream: process.stdout, errorStream: process.stderr, writeLevel: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR', ci: true | false }); const project = Project.closestSync(addonPath, ui); // Extend the current addon from base Addon const CurrentAddon = Addon.extend(Object.assign({}, addonToBuild, {root: addonPath, pkg: project.pkg})); const currAddon = new CurrentAddon(addonPath, project); // Get the tree for Addon and Vendor let addonTree = new Funnel (currAddon.treeFor('addon'), { destDir: 'addon' }); let vendorTree = new Funnel (currAddon.treeFor('vendor'), { destDir: 'vendor' }); // Merge, Build the resulting tree and store it in prebuild path return build(new Merge([addonTree, vendorTree], { annotation: '[ember-rollup] Merging prebuild addon and vendor tree' }), addonToBuild.PREBUILT_PATH); }
javascript
function preBuild(addonPath) { // Require the addon let addonToBuild = require(addonPath); // Augment it with isDevelopingAddon function. addonToBuild.isDevelopingAddon = function() { return true; } // If addon has pre-built path set in it use that else use the default path if(!addonToBuild.PREBUILT_PATH) { addonToBuild.PREBUILT_PATH = `${addonPath}/pre-built`; } fs.removeSync(addonToBuild.PREBUILT_PATH); const ui = new UI({ inputStream: process.stdin, outputStream: process.stdout, errorStream: process.stderr, writeLevel: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR', ci: true | false }); const project = Project.closestSync(addonPath, ui); // Extend the current addon from base Addon const CurrentAddon = Addon.extend(Object.assign({}, addonToBuild, {root: addonPath, pkg: project.pkg})); const currAddon = new CurrentAddon(addonPath, project); // Get the tree for Addon and Vendor let addonTree = new Funnel (currAddon.treeFor('addon'), { destDir: 'addon' }); let vendorTree = new Funnel (currAddon.treeFor('vendor'), { destDir: 'vendor' }); // Merge, Build the resulting tree and store it in prebuild path return build(new Merge([addonTree, vendorTree], { annotation: '[ember-rollup] Merging prebuild addon and vendor tree' }), addonToBuild.PREBUILT_PATH); }
[ "function", "preBuild", "(", "addonPath", ")", "{", "let", "addonToBuild", "=", "require", "(", "addonPath", ")", ";", "addonToBuild", ".", "isDevelopingAddon", "=", "function", "(", ")", "{", "return", "true", ";", "}", "if", "(", "!", "addonToBuild", ".", "PREBUILT_PATH", ")", "{", "addonToBuild", ".", "PREBUILT_PATH", "=", "`", "${", "addonPath", "}", "`", ";", "}", "fs", ".", "removeSync", "(", "addonToBuild", ".", "PREBUILT_PATH", ")", ";", "const", "ui", "=", "new", "UI", "(", "{", "inputStream", ":", "process", ".", "stdin", ",", "outputStream", ":", "process", ".", "stdout", ",", "errorStream", ":", "process", ".", "stderr", ",", "writeLevel", ":", "'DEBUG'", "|", "'INFO'", "|", "'WARNING'", "|", "'ERROR'", ",", "ci", ":", "true", "|", "false", "}", ")", ";", "const", "project", "=", "Project", ".", "closestSync", "(", "addonPath", ",", "ui", ")", ";", "const", "CurrentAddon", "=", "Addon", ".", "extend", "(", "Object", ".", "assign", "(", "{", "}", ",", "addonToBuild", ",", "{", "root", ":", "addonPath", ",", "pkg", ":", "project", ".", "pkg", "}", ")", ")", ";", "const", "currAddon", "=", "new", "CurrentAddon", "(", "addonPath", ",", "project", ")", ";", "let", "addonTree", "=", "new", "Funnel", "(", "currAddon", ".", "treeFor", "(", "'addon'", ")", ",", "{", "destDir", ":", "'addon'", "}", ")", ";", "let", "vendorTree", "=", "new", "Funnel", "(", "currAddon", ".", "treeFor", "(", "'vendor'", ")", ",", "{", "destDir", ":", "'vendor'", "}", ")", ";", "return", "build", "(", "new", "Merge", "(", "[", "addonTree", ",", "vendorTree", "]", ",", "{", "annotation", ":", "'[ember-rollup] Merging prebuild addon and vendor tree'", "}", ")", ",", "addonToBuild", ".", "PREBUILT_PATH", ")", ";", "}" ]
Pre-build the dependency of an addon and store it in prebuilt path by invoking the treeForAddon and treeForVendor hook
[ "Pre", "-", "build", "the", "dependency", "of", "an", "addon", "and", "store", "it", "in", "prebuilt", "path", "by", "invoking", "the", "treeForAddon", "and", "treeForVendor", "hook" ]
253c7f5999ca7fb33535d661749b3283720fdb77
https://github.com/asakusuma/ember-rollup/blob/253c7f5999ca7fb33535d661749b3283720fdb77/src/prebuild.js#L11-L47
train
nodebox/g.js
src/libraries/vg/util/random.js
generator
function generator(seed) { // Note: the generator didn't work with negative seed values, so here we // transform our original seed into a new (positive) seed value with which we // create a new generator. if (seed < 0) { var gen = generator(Math.abs(seed)); for (var i = 0; i < 23; i += 1) { gen(); } return generator(gen(0, 10000)); } // Based on random number generator from // http://indiegamr.com/generate-repeatable-random-numbers-in-js/ return function (min, max) { min = min || 0; max = max || 1; seed = (seed * 9301 + 49297) % 233280; var v = seed / 233280; return min + v * (max - min); }; }
javascript
function generator(seed) { // Note: the generator didn't work with negative seed values, so here we // transform our original seed into a new (positive) seed value with which we // create a new generator. if (seed < 0) { var gen = generator(Math.abs(seed)); for (var i = 0; i < 23; i += 1) { gen(); } return generator(gen(0, 10000)); } // Based on random number generator from // http://indiegamr.com/generate-repeatable-random-numbers-in-js/ return function (min, max) { min = min || 0; max = max || 1; seed = (seed * 9301 + 49297) % 233280; var v = seed / 233280; return min + v * (max - min); }; }
[ "function", "generator", "(", "seed", ")", "{", "if", "(", "seed", "<", "0", ")", "{", "var", "gen", "=", "generator", "(", "Math", ".", "abs", "(", "seed", ")", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "23", ";", "i", "+=", "1", ")", "{", "gen", "(", ")", ";", "}", "return", "generator", "(", "gen", "(", "0", ",", "10000", ")", ")", ";", "}", "return", "function", "(", "min", ",", "max", ")", "{", "min", "=", "min", "||", "0", ";", "max", "=", "max", "||", "1", ";", "seed", "=", "(", "seed", "*", "9301", "+", "49297", ")", "%", "233280", ";", "var", "v", "=", "seed", "/", "233280", ";", "return", "min", "+", "v", "*", "(", "max", "-", "min", ")", ";", "}", ";", "}" ]
Generate a random function that is seeded with the given value.
[ "Generate", "a", "random", "function", "that", "is", "seeded", "with", "the", "given", "value", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/vg/util/random.js#L6-L27
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/basicsSearch/removeExponentByOne.js
removeExponentByOne
function removeExponentByOne(node) { if (node.op === '^' && // exponent of anything Node.Type.isConstant(node.args[1]) && // to a constant node.args[1].value === '1') { // of value 1 const newNode = clone(node.args[0]); return Node.Status.nodeChanged( ChangeTypes.REMOVE_EXPONENT_BY_ONE, node, newNode); } return Node.Status.noChange(node); }
javascript
function removeExponentByOne(node) { if (node.op === '^' && // exponent of anything Node.Type.isConstant(node.args[1]) && // to a constant node.args[1].value === '1') { // of value 1 const newNode = clone(node.args[0]); return Node.Status.nodeChanged( ChangeTypes.REMOVE_EXPONENT_BY_ONE, node, newNode); } return Node.Status.noChange(node); }
[ "function", "removeExponentByOne", "(", "node", ")", "{", "if", "(", "node", ".", "op", "===", "'^'", "&&", "Node", ".", "Type", ".", "isConstant", "(", "node", ".", "args", "[", "1", "]", ")", "&&", "node", ".", "args", "[", "1", "]", ".", "value", "===", "'1'", ")", "{", "const", "newNode", "=", "clone", "(", "node", ".", "args", "[", "0", "]", ")", ";", "return", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "REMOVE_EXPONENT_BY_ONE", ",", "node", ",", "newNode", ")", ";", "}", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}" ]
If `node` is of the form x^1, reduces it to a node of the form x. Returns a Node.Status object.
[ "If", "node", "is", "of", "the", "form", "x^1", "reduces", "it", "to", "a", "node", "of", "the", "form", "x", ".", "Returns", "a", "Node", ".", "Status", "object", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/basicsSearch/removeExponentByOne.js#L9-L18
train
metadelta/metadelta
packages/solver/lib/TreeSearch.js
search
function search(simplificationFunction, node, preOrder) { let status; if (preOrder) { status = simplificationFunction(node); if (status.hasChanged()) { return status; } } if (Node.Type.isConstant(node) || Node.Type.isSymbol(node)) { return Node.Status.noChange(node); } else if (Node.Type.isUnaryMinus(node)) { status = search(simplificationFunction, node.args[0], preOrder); if (status.hasChanged()) { return Node.Status.childChanged(node, status); } } else if (Node.Type.isOperator(node) || Node.Type.isFunction(node)) { for (let i = 0; i < node.args.length; i++) { const child = node.args[i]; const childNodeStatus = search(simplificationFunction, child, preOrder); if (childNodeStatus.hasChanged()) { return Node.Status.childChanged(node, childNodeStatus, i); } } } else if (Node.Type.isParenthesis(node)) { status = search(simplificationFunction, node.content, preOrder); if (status.hasChanged()) { return Node.Status.childChanged(node, status); } } else { throw Error('Unsupported node type: ' + node); } if (!preOrder) { return simplificationFunction(node); } else { return Node.Status.noChange(node); } }
javascript
function search(simplificationFunction, node, preOrder) { let status; if (preOrder) { status = simplificationFunction(node); if (status.hasChanged()) { return status; } } if (Node.Type.isConstant(node) || Node.Type.isSymbol(node)) { return Node.Status.noChange(node); } else if (Node.Type.isUnaryMinus(node)) { status = search(simplificationFunction, node.args[0], preOrder); if (status.hasChanged()) { return Node.Status.childChanged(node, status); } } else if (Node.Type.isOperator(node) || Node.Type.isFunction(node)) { for (let i = 0; i < node.args.length; i++) { const child = node.args[i]; const childNodeStatus = search(simplificationFunction, child, preOrder); if (childNodeStatus.hasChanged()) { return Node.Status.childChanged(node, childNodeStatus, i); } } } else if (Node.Type.isParenthesis(node)) { status = search(simplificationFunction, node.content, preOrder); if (status.hasChanged()) { return Node.Status.childChanged(node, status); } } else { throw Error('Unsupported node type: ' + node); } if (!preOrder) { return simplificationFunction(node); } else { return Node.Status.noChange(node); } }
[ "function", "search", "(", "simplificationFunction", ",", "node", ",", "preOrder", ")", "{", "let", "status", ";", "if", "(", "preOrder", ")", "{", "status", "=", "simplificationFunction", "(", "node", ")", ";", "if", "(", "status", ".", "hasChanged", "(", ")", ")", "{", "return", "status", ";", "}", "}", "if", "(", "Node", ".", "Type", ".", "isConstant", "(", "node", ")", "||", "Node", ".", "Type", ".", "isSymbol", "(", "node", ")", ")", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "else", "if", "(", "Node", ".", "Type", ".", "isUnaryMinus", "(", "node", ")", ")", "{", "status", "=", "search", "(", "simplificationFunction", ",", "node", ".", "args", "[", "0", "]", ",", "preOrder", ")", ";", "if", "(", "status", ".", "hasChanged", "(", ")", ")", "{", "return", "Node", ".", "Status", ".", "childChanged", "(", "node", ",", "status", ")", ";", "}", "}", "else", "if", "(", "Node", ".", "Type", ".", "isOperator", "(", "node", ")", "||", "Node", ".", "Type", ".", "isFunction", "(", "node", ")", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "node", ".", "args", ".", "length", ";", "i", "++", ")", "{", "const", "child", "=", "node", ".", "args", "[", "i", "]", ";", "const", "childNodeStatus", "=", "search", "(", "simplificationFunction", ",", "child", ",", "preOrder", ")", ";", "if", "(", "childNodeStatus", ".", "hasChanged", "(", ")", ")", "{", "return", "Node", ".", "Status", ".", "childChanged", "(", "node", ",", "childNodeStatus", ",", "i", ")", ";", "}", "}", "}", "else", "if", "(", "Node", ".", "Type", ".", "isParenthesis", "(", "node", ")", ")", "{", "status", "=", "search", "(", "simplificationFunction", ",", "node", ".", "content", ",", "preOrder", ")", ";", "if", "(", "status", ".", "hasChanged", "(", ")", ")", "{", "return", "Node", ".", "Status", ".", "childChanged", "(", "node", ",", "status", ")", ";", "}", "}", "else", "{", "throw", "Error", "(", "'Unsupported node type: '", "+", "node", ")", ";", "}", "if", "(", "!", "preOrder", ")", "{", "return", "simplificationFunction", "(", "node", ")", ";", "}", "else", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "}" ]
A helper function for performing a tree search with a function
[ "A", "helper", "function", "for", "performing", "a", "tree", "search", "with", "a", "function" ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/TreeSearch.js#L24-L68
train
vlucas/toystore
src/index.js
zipObject
function zipObject(keys, values) { return keys.reduce(function(object, currentValue, currentIndex) { object[currentValue] = values[currentIndex]; return object; }, {}); }
javascript
function zipObject(keys, values) { return keys.reduce(function(object, currentValue, currentIndex) { object[currentValue] = values[currentIndex]; return object; }, {}); }
[ "function", "zipObject", "(", "keys", ",", "values", ")", "{", "return", "keys", ".", "reduce", "(", "function", "(", "object", ",", "currentValue", ",", "currentIndex", ")", "{", "object", "[", "currentValue", "]", "=", "values", "[", "currentIndex", "]", ";", "return", "object", ";", "}", ",", "{", "}", ")", ";", "}" ]
Create object with provided arrays of keys and values @param {String[]} keys @param {Array} values
[ "Create", "object", "with", "provided", "arrays", "of", "keys", "and", "values" ]
0c1794e6cfc9d54b79dd843696a3f00360733034
https://github.com/vlucas/toystore/blob/0c1794e6cfc9d54b79dd843696a3f00360733034/src/index.js#L14-L20
train
vlucas/toystore
src/index.js
getAll
function getAll(paths) { if (paths === undefined) { return clone(state); } if (!paths instanceof Array) { throw new Error('[toystore] getAll() argument "paths" must be an array.'); } let values = paths.map(get); return zipObject(paths, values); }
javascript
function getAll(paths) { if (paths === undefined) { return clone(state); } if (!paths instanceof Array) { throw new Error('[toystore] getAll() argument "paths" must be an array.'); } let values = paths.map(get); return zipObject(paths, values); }
[ "function", "getAll", "(", "paths", ")", "{", "if", "(", "paths", "===", "undefined", ")", "{", "return", "clone", "(", "state", ")", ";", "}", "if", "(", "!", "paths", "instanceof", "Array", ")", "{", "throw", "new", "Error", "(", "'[toystore] getAll() argument \"paths\" must be an array.'", ")", ";", "}", "let", "values", "=", "paths", ".", "map", "(", "get", ")", ";", "return", "zipObject", "(", "paths", ",", "values", ")", ";", "}" ]
Get multiple path values from store @param {String[]} paths @return {Object} key/value pair of path => value
[ "Get", "multiple", "path", "values", "from", "store" ]
0c1794e6cfc9d54b79dd843696a3f00360733034
https://github.com/vlucas/toystore/blob/0c1794e6cfc9d54b79dd843696a3f00360733034/src/index.js#L64-L76
train
vlucas/toystore
src/index.js
setAll
function setAll(obj) { let paths = Object.keys(obj); paths.map(path => setSilent(path, obj[path])); notifyWatchersOnPaths(paths); }
javascript
function setAll(obj) { let paths = Object.keys(obj); paths.map(path => setSilent(path, obj[path])); notifyWatchersOnPaths(paths); }
[ "function", "setAll", "(", "obj", ")", "{", "let", "paths", "=", "Object", ".", "keys", "(", "obj", ")", ";", "paths", ".", "map", "(", "path", "=>", "setSilent", "(", "path", ",", "obj", "[", "path", "]", ")", ")", ";", "notifyWatchersOnPaths", "(", "paths", ")", ";", "}" ]
Set multiple paths with given values to the store @param {Object} key/value pair of path => value @return null
[ "Set", "multiple", "paths", "with", "given", "values", "to", "the", "store" ]
0c1794e6cfc9d54b79dd843696a3f00360733034
https://github.com/vlucas/toystore/blob/0c1794e6cfc9d54b79dd843696a3f00360733034/src/index.js#L218-L223
train
vlucas/toystore
src/index.js
watch
function watch(paths, callback, options = {}) { paths = paths === '*' ? paths : _pathsArray(paths); let id = randomString(); let defaultOptions = { async: false, priority: 0 }; options = Object.assign({}, defaultOptions, options); watchers.push({ callback, id, options, paths, }); watchers = watchers.sort(_sortByPriority); return id; }
javascript
function watch(paths, callback, options = {}) { paths = paths === '*' ? paths : _pathsArray(paths); let id = randomString(); let defaultOptions = { async: false, priority: 0 }; options = Object.assign({}, defaultOptions, options); watchers.push({ callback, id, options, paths, }); watchers = watchers.sort(_sortByPriority); return id; }
[ "function", "watch", "(", "paths", ",", "callback", ",", "options", "=", "{", "}", ")", "{", "paths", "=", "paths", "===", "'*'", "?", "paths", ":", "_pathsArray", "(", "paths", ")", ";", "let", "id", "=", "randomString", "(", ")", ";", "let", "defaultOptions", "=", "{", "async", ":", "false", ",", "priority", ":", "0", "}", ";", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultOptions", ",", "options", ")", ";", "watchers", ".", "push", "(", "{", "callback", ",", "id", ",", "options", ",", "paths", ",", "}", ")", ";", "watchers", "=", "watchers", ".", "sort", "(", "_sortByPriority", ")", ";", "return", "id", ";", "}" ]
Watch for changes on a given key, and execute the provided callback when there are changes @param {String[]|String} String path or array of paths to watch @param {Function} callback to execute when there are changes @param {Object} options Options @param {Boolean} options.async Callback execution is async (in next cycle) or sync (as soon as the key changes) @param {Number} options.priority Controls the order the provided callback is called when multiple watches exist on the same key. @return {String} id of watcher (useful for unwatch())
[ "Watch", "for", "changes", "on", "a", "given", "key", "and", "execute", "the", "provided", "callback", "when", "there", "are", "changes" ]
0c1794e6cfc9d54b79dd843696a3f00360733034
https://github.com/vlucas/toystore/blob/0c1794e6cfc9d54b79dd843696a3f00360733034/src/index.js#L247-L264
train
vlucas/toystore
src/index.js
_deepKeys
function _deepKeys(obj, prefix = null) { return Object.keys(obj).reduce(function(acc, key){ var value = obj[key]; if (_isObject(value)) { acc.push.apply(acc, _deepKeys(value, prefix ? prefix + '.' + key : key)); } else { acc.push(prefix ? prefix + '.' + key : key); } return acc; }, []); }
javascript
function _deepKeys(obj, prefix = null) { return Object.keys(obj).reduce(function(acc, key){ var value = obj[key]; if (_isObject(value)) { acc.push.apply(acc, _deepKeys(value, prefix ? prefix + '.' + key : key)); } else { acc.push(prefix ? prefix + '.' + key : key); } return acc; }, []); }
[ "function", "_deepKeys", "(", "obj", ",", "prefix", "=", "null", ")", "{", "return", "Object", ".", "keys", "(", "obj", ")", ".", "reduce", "(", "function", "(", "acc", ",", "key", ")", "{", "var", "value", "=", "obj", "[", "key", "]", ";", "if", "(", "_isObject", "(", "value", ")", ")", "{", "acc", ".", "push", ".", "apply", "(", "acc", ",", "_deepKeys", "(", "value", ",", "prefix", "?", "prefix", "+", "'.'", "+", "key", ":", "key", ")", ")", ";", "}", "else", "{", "acc", ".", "push", "(", "prefix", "?", "prefix", "+", "'.'", "+", "key", ":", "key", ")", ";", "}", "return", "acc", ";", "}", ",", "[", "]", ")", ";", "}" ]
Get all keys for the given object recursively Ex: { user: { email: '[email protected]', id: 2 } } => ['user.email', 'user.id']
[ "Get", "all", "keys", "for", "the", "given", "object", "recursively" ]
0c1794e6cfc9d54b79dd843696a3f00360733034
https://github.com/vlucas/toystore/blob/0c1794e6cfc9d54b79dd843696a3f00360733034/src/index.js#L384-L396
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/functionsSearch/nthRoot.js
nthRootConstant
function nthRootConstant(node) { let newNode = clone(node); const radicandNode = getRadicandNode(node); const rootNode = getRootNode(node); if (Negative.isNegative(radicandNode)) { return Node.Status.noChange(node); } else if (!Node.Type.isConstant(rootNode) || Negative.isNegative(rootNode)) { return Node.Status.noChange(node); } const radicandValue = parseFloat(radicandNode.value); const rootValue = parseFloat(rootNode.value); const nthRootValue = math.nthRoot(radicandValue, rootValue); // Perfect root e.g. nthRoot(4, 2) = 2 if (nthRootValue % 1 === 0) { newNode = Node.Creator.constant(nthRootValue); return Node.Status.nodeChanged( ChangeTypes.NTH_ROOT_VALUE, node, newNode); } // Try to find if we can simplify by finding factors that can be // pulled out of the radical else { // convert the number into the product of its prime factors const factors = ConstantFactors.getPrimeFactors(radicandValue); if (factors.length > 1) { let substeps = []; const factorNodes = factors.map(Node.Creator.constant); newNode.args[0] = Node.Creator.operator('*', factorNodes); substeps.push(Node.Status.nodeChanged( ChangeTypes.FACTOR_INTO_PRIMES, node, newNode)); // run nthRoot on the new node const nodeStatus = nthRootMultiplication(newNode); if (nodeStatus.hasChanged()) { substeps = substeps.concat(nodeStatus.substeps); newNode = nodeStatus.newNode; return Node.Status.nodeChanged( ChangeTypes.NTH_ROOT_VALUE, node, newNode, true, substeps); } } } return Node.Status.noChange(node); }
javascript
function nthRootConstant(node) { let newNode = clone(node); const radicandNode = getRadicandNode(node); const rootNode = getRootNode(node); if (Negative.isNegative(radicandNode)) { return Node.Status.noChange(node); } else if (!Node.Type.isConstant(rootNode) || Negative.isNegative(rootNode)) { return Node.Status.noChange(node); } const radicandValue = parseFloat(radicandNode.value); const rootValue = parseFloat(rootNode.value); const nthRootValue = math.nthRoot(radicandValue, rootValue); // Perfect root e.g. nthRoot(4, 2) = 2 if (nthRootValue % 1 === 0) { newNode = Node.Creator.constant(nthRootValue); return Node.Status.nodeChanged( ChangeTypes.NTH_ROOT_VALUE, node, newNode); } // Try to find if we can simplify by finding factors that can be // pulled out of the radical else { // convert the number into the product of its prime factors const factors = ConstantFactors.getPrimeFactors(radicandValue); if (factors.length > 1) { let substeps = []; const factorNodes = factors.map(Node.Creator.constant); newNode.args[0] = Node.Creator.operator('*', factorNodes); substeps.push(Node.Status.nodeChanged( ChangeTypes.FACTOR_INTO_PRIMES, node, newNode)); // run nthRoot on the new node const nodeStatus = nthRootMultiplication(newNode); if (nodeStatus.hasChanged()) { substeps = substeps.concat(nodeStatus.substeps); newNode = nodeStatus.newNode; return Node.Status.nodeChanged( ChangeTypes.NTH_ROOT_VALUE, node, newNode, true, substeps); } } } return Node.Status.noChange(node); }
[ "function", "nthRootConstant", "(", "node", ")", "{", "let", "newNode", "=", "clone", "(", "node", ")", ";", "const", "radicandNode", "=", "getRadicandNode", "(", "node", ")", ";", "const", "rootNode", "=", "getRootNode", "(", "node", ")", ";", "if", "(", "Negative", ".", "isNegative", "(", "radicandNode", ")", ")", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "else", "if", "(", "!", "Node", ".", "Type", ".", "isConstant", "(", "rootNode", ")", "||", "Negative", ".", "isNegative", "(", "rootNode", ")", ")", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "const", "radicandValue", "=", "parseFloat", "(", "radicandNode", ".", "value", ")", ";", "const", "rootValue", "=", "parseFloat", "(", "rootNode", ".", "value", ")", ";", "const", "nthRootValue", "=", "math", ".", "nthRoot", "(", "radicandValue", ",", "rootValue", ")", ";", "if", "(", "nthRootValue", "%", "1", "===", "0", ")", "{", "newNode", "=", "Node", ".", "Creator", ".", "constant", "(", "nthRootValue", ")", ";", "return", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "NTH_ROOT_VALUE", ",", "node", ",", "newNode", ")", ";", "}", "else", "{", "const", "factors", "=", "ConstantFactors", ".", "getPrimeFactors", "(", "radicandValue", ")", ";", "if", "(", "factors", ".", "length", ">", "1", ")", "{", "let", "substeps", "=", "[", "]", ";", "const", "factorNodes", "=", "factors", ".", "map", "(", "Node", ".", "Creator", ".", "constant", ")", ";", "newNode", ".", "args", "[", "0", "]", "=", "Node", ".", "Creator", ".", "operator", "(", "'*'", ",", "factorNodes", ")", ";", "substeps", ".", "push", "(", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "FACTOR_INTO_PRIMES", ",", "node", ",", "newNode", ")", ")", ";", "const", "nodeStatus", "=", "nthRootMultiplication", "(", "newNode", ")", ";", "if", "(", "nodeStatus", ".", "hasChanged", "(", ")", ")", "{", "substeps", "=", "substeps", ".", "concat", "(", "nodeStatus", ".", "substeps", ")", ";", "newNode", "=", "nodeStatus", ".", "newNode", ";", "return", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "NTH_ROOT_VALUE", ",", "node", ",", "newNode", ",", "true", ",", "substeps", ")", ";", "}", "}", "}", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}" ]
Returns the nthRoot evaluated on a constant node Potentially factors the constant node into primes, and calls nthRootMultiplication on the new nthRoot
[ "Returns", "the", "nthRoot", "evaluated", "on", "a", "constant", "node", "Potentially", "factors", "the", "constant", "node", "into", "primes", "and", "calls", "nthRootMultiplication", "on", "the", "new", "nthRoot" ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/functionsSearch/nthRoot.js#L375-L422
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/functionsSearch/nthRoot.js
getRootNode
function getRootNode(node) { if (!Node.Type.isFunction(node, 'nthRoot')) { throw Error('Expected nthRoot'); } return node.args.length === 2 ? node.args[1] : Node.Creator.constant(2); }
javascript
function getRootNode(node) { if (!Node.Type.isFunction(node, 'nthRoot')) { throw Error('Expected nthRoot'); } return node.args.length === 2 ? node.args[1] : Node.Creator.constant(2); }
[ "function", "getRootNode", "(", "node", ")", "{", "if", "(", "!", "Node", ".", "Type", ".", "isFunction", "(", "node", ",", "'nthRoot'", ")", ")", "{", "throw", "Error", "(", "'Expected nthRoot'", ")", ";", "}", "return", "node", ".", "args", ".", "length", "===", "2", "?", "node", ".", "args", "[", "1", "]", ":", "Node", ".", "Creator", ".", "constant", "(", "2", ")", ";", "}" ]
Given an nthRoot node, will return the root node. The root node is the second child of the nthRoot node, but if one doesn't exist, we assume it's a square root and return 2.
[ "Given", "an", "nthRoot", "node", "will", "return", "the", "root", "node", ".", "The", "root", "node", "is", "the", "second", "child", "of", "the", "nthRoot", "node", "but", "if", "one", "doesn", "t", "exist", "we", "assume", "it", "s", "a", "square", "root", "and", "return", "2", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/functionsSearch/nthRoot.js#L429-L435
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/functionsSearch/nthRoot.js
sortNodes
function sortNodes(a, b) { if (Node.Type.isConstant(a) && Node.Type.isConstant(b)) { return parseFloat(a.value) - parseFloat(b.value); } else if (Node.Type.isConstant(a)) { return -1; } else if (Node.Type.isConstant(b)) { return 1; } return 0; }
javascript
function sortNodes(a, b) { if (Node.Type.isConstant(a) && Node.Type.isConstant(b)) { return parseFloat(a.value) - parseFloat(b.value); } else if (Node.Type.isConstant(a)) { return -1; } else if (Node.Type.isConstant(b)) { return 1; } return 0; }
[ "function", "sortNodes", "(", "a", ",", "b", ")", "{", "if", "(", "Node", ".", "Type", ".", "isConstant", "(", "a", ")", "&&", "Node", ".", "Type", ".", "isConstant", "(", "b", ")", ")", "{", "return", "parseFloat", "(", "a", ".", "value", ")", "-", "parseFloat", "(", "b", ".", "value", ")", ";", "}", "else", "if", "(", "Node", ".", "Type", ".", "isConstant", "(", "a", ")", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "Node", ".", "Type", ".", "isConstant", "(", "b", ")", ")", "{", "return", "1", ";", "}", "return", "0", ";", "}" ]
Sorts nodes, ordering constants nodes from smallest to largest and symbol nodes after
[ "Sorts", "nodes", "ordering", "constants", "nodes", "from", "smallest", "to", "largest", "and", "symbol", "nodes", "after" ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/functionsSearch/nthRoot.js#L448-L459
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/functionsSearch/nthRoot.js
isMultiplicationOfEqualNodes
function isMultiplicationOfEqualNodes(node) { if (!Node.Type.isOperator(node) || node.op !== '*') { return false; } // return if they are all equal nodes return node.args.reduce((a, b) => { return a.equals(b); }); }
javascript
function isMultiplicationOfEqualNodes(node) { if (!Node.Type.isOperator(node) || node.op !== '*') { return false; } // return if they are all equal nodes return node.args.reduce((a, b) => { return a.equals(b); }); }
[ "function", "isMultiplicationOfEqualNodes", "(", "node", ")", "{", "if", "(", "!", "Node", ".", "Type", ".", "isOperator", "(", "node", ")", "||", "node", ".", "op", "!==", "'*'", ")", "{", "return", "false", ";", "}", "return", "node", ".", "args", ".", "reduce", "(", "(", "a", ",", "b", ")", "=>", "{", "return", "a", ".", "equals", "(", "b", ")", ";", "}", ")", ";", "}" ]
Simple helper function which determines a node is a multiplication node of all equal nodes
[ "Simple", "helper", "function", "which", "determines", "a", "node", "is", "a", "multiplication", "node", "of", "all", "equal", "nodes" ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/functionsSearch/nthRoot.js#L463-L473
train
veo-labs/cas-server-mock
assets/components/login/login.controller.js
LoginController
function LoginController($scope, $location, $http) { var urlParams = $location.search(); Object.defineProperties(this, { /** * The URL of the service to redirect to. * * @property service * @type String */ service: { value: urlParams.service, writable: true } }); }
javascript
function LoginController($scope, $location, $http) { var urlParams = $location.search(); Object.defineProperties(this, { /** * The URL of the service to redirect to. * * @property service * @type String */ service: { value: urlParams.service, writable: true } }); }
[ "function", "LoginController", "(", "$scope", ",", "$location", ",", "$http", ")", "{", "var", "urlParams", "=", "$location", ".", "search", "(", ")", ";", "Object", ".", "defineProperties", "(", "this", ",", "{", "service", ":", "{", "value", ":", "urlParams", ".", "service", ",", "writable", ":", "true", "}", "}", ")", ";", "}" ]
Defines controller of the login component.
[ "Defines", "controller", "of", "the", "login", "component", "." ]
f258875841fd4d33fe63ec3089f0bd16180801d5
https://github.com/veo-labs/cas-server-mock/blob/f258875841fd4d33fe63ec3089f0bd16180801d5/assets/components/login/login.controller.js#L8-L25
train
metadelta/metadelta
packages/solver/lib/checks/canAddLikeTermPolynomialNodes.js
canAddLikeTermPolynomialNodes
function canAddLikeTermPolynomialNodes(node) { if (!Node.Type.isOperator(node) || node.op !== '+') { return false; } const args = node.args; if (!args.every(n => Node.PolynomialTerm.isPolynomialTerm(n))) { return false; } if (args.length === 1) { return false; } const polynomialTermList = args.map(n => new Node.PolynomialTerm(n)); // to add terms, they must have the same symbol name *and* exponent const firstTerm = polynomialTermList[0]; const sharedSymbol = firstTerm.getSymbolName(); const sharedExponentNode = firstTerm.getExponentNode(true); const restTerms = polynomialTermList.slice(1); return restTerms.every(term => { const haveSameSymbol = sharedSymbol === term.getSymbolName(); const exponentNode = term.getExponentNode(true); const haveSameExponent = exponentNode.equals(sharedExponentNode); return haveSameSymbol && haveSameExponent; }); }
javascript
function canAddLikeTermPolynomialNodes(node) { if (!Node.Type.isOperator(node) || node.op !== '+') { return false; } const args = node.args; if (!args.every(n => Node.PolynomialTerm.isPolynomialTerm(n))) { return false; } if (args.length === 1) { return false; } const polynomialTermList = args.map(n => new Node.PolynomialTerm(n)); // to add terms, they must have the same symbol name *and* exponent const firstTerm = polynomialTermList[0]; const sharedSymbol = firstTerm.getSymbolName(); const sharedExponentNode = firstTerm.getExponentNode(true); const restTerms = polynomialTermList.slice(1); return restTerms.every(term => { const haveSameSymbol = sharedSymbol === term.getSymbolName(); const exponentNode = term.getExponentNode(true); const haveSameExponent = exponentNode.equals(sharedExponentNode); return haveSameSymbol && haveSameExponent; }); }
[ "function", "canAddLikeTermPolynomialNodes", "(", "node", ")", "{", "if", "(", "!", "Node", ".", "Type", ".", "isOperator", "(", "node", ")", "||", "node", ".", "op", "!==", "'+'", ")", "{", "return", "false", ";", "}", "const", "args", "=", "node", ".", "args", ";", "if", "(", "!", "args", ".", "every", "(", "n", "=>", "Node", ".", "PolynomialTerm", ".", "isPolynomialTerm", "(", "n", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "args", ".", "length", "===", "1", ")", "{", "return", "false", ";", "}", "const", "polynomialTermList", "=", "args", ".", "map", "(", "n", "=>", "new", "Node", ".", "PolynomialTerm", "(", "n", ")", ")", ";", "const", "firstTerm", "=", "polynomialTermList", "[", "0", "]", ";", "const", "sharedSymbol", "=", "firstTerm", ".", "getSymbolName", "(", ")", ";", "const", "sharedExponentNode", "=", "firstTerm", ".", "getExponentNode", "(", "true", ")", ";", "const", "restTerms", "=", "polynomialTermList", ".", "slice", "(", "1", ")", ";", "return", "restTerms", ".", "every", "(", "term", "=>", "{", "const", "haveSameSymbol", "=", "sharedSymbol", "===", "term", ".", "getSymbolName", "(", ")", ";", "const", "exponentNode", "=", "term", ".", "getExponentNode", "(", "true", ")", ";", "const", "haveSameExponent", "=", "exponentNode", ".", "equals", "(", "sharedExponentNode", ")", ";", "return", "haveSameSymbol", "&&", "haveSameExponent", ";", "}", ")", ";", "}" ]
Returns true if the nodes are polynomial terms that can be added together.
[ "Returns", "true", "if", "the", "nodes", "are", "polynomial", "terms", "that", "can", "be", "added", "together", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/checks/canAddLikeTermPolynomialNodes.js#L6-L32
train
inspiredware/napi-build-utils
index.js
function (prebuild, napiVersion) { if (prebuild) { for (var i = 0; i < prebuild.length; i++) { if (prebuild[i].target === napiVersion) return true } } return false }
javascript
function (prebuild, napiVersion) { if (prebuild) { for (var i = 0; i < prebuild.length; i++) { if (prebuild[i].target === napiVersion) return true } } return false }
[ "function", "(", "prebuild", ",", "napiVersion", ")", "{", "if", "(", "prebuild", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "prebuild", ".", "length", ";", "i", "++", ")", "{", "if", "(", "prebuild", "[", "i", "]", ".", "target", "===", "napiVersion", ")", "return", "true", "}", "}", "return", "false", "}" ]
Determines whether the specified N-API version exists in the prebuild configuration object. Note that this function is speicifc to the `prebuild` and `prebuild-install` packages. @param {Object} prebuild A config object created by the `prebuild` package. @param {string} napiVersion The N-APi version to be checked. @return {boolean} @private
[ "Determines", "whether", "the", "specified", "N", "-", "API", "version", "exists", "in", "the", "prebuild", "configuration", "object", "." ]
85740222a7124b020b3261d5466a06cf0d2ea5f4
https://github.com/inspiredware/napi-build-utils/blob/85740222a7124b020b3261d5466a06cf0d2ea5f4/index.js#L145-L152
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/collectAndCombineSearch/LikeTermCollector.js
getTermName
function getTermName(node, op) { const polyNode = new Node.PolynomialTerm(node); // we 'name' polynomial terms by their symbol name let termName = polyNode.getSymbolName(); // when adding terms, the exponent matters too (e.g. 2x^2 + 5x^3 can't be combined) if (op === '+') { const exponent = print(polyNode.getExponentNode(true)); termName += '^' + exponent; } return termName; }
javascript
function getTermName(node, op) { const polyNode = new Node.PolynomialTerm(node); // we 'name' polynomial terms by their symbol name let termName = polyNode.getSymbolName(); // when adding terms, the exponent matters too (e.g. 2x^2 + 5x^3 can't be combined) if (op === '+') { const exponent = print(polyNode.getExponentNode(true)); termName += '^' + exponent; } return termName; }
[ "function", "getTermName", "(", "node", ",", "op", ")", "{", "const", "polyNode", "=", "new", "Node", ".", "PolynomialTerm", "(", "node", ")", ";", "let", "termName", "=", "polyNode", ".", "getSymbolName", "(", ")", ";", "if", "(", "op", "===", "'+'", ")", "{", "const", "exponent", "=", "print", "(", "polyNode", ".", "getExponentNode", "(", "true", ")", ")", ";", "termName", "+=", "'^'", "+", "exponent", ";", "}", "return", "termName", ";", "}" ]
Polyonomial terms are collected by categorizing them by their 'name' which is used to separate them into groups that can be combined. getTermName returns this group 'name'
[ "Polyonomial", "terms", "are", "collected", "by", "categorizing", "them", "by", "their", "name", "which", "is", "used", "to", "separate", "them", "into", "groups", "that", "can", "be", "combined", ".", "getTermName", "returns", "this", "group", "name" ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/collectAndCombineSearch/LikeTermCollector.js#L124-L134
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/collectAndCombineSearch/LikeTermCollector.js
sortTerms
function sortTerms(a, b) { if (a === b) { return 0; } // if no exponent, sort alphabetically if (a.indexOf('^') === -1) { return a < b ? -1 : 1; } // if exponent: sort by symbol, but then exponent decreasing else { const symbA = a.split('^')[0]; const expA = a.split('^')[1]; const symbB = b.split('^')[0]; const expB = b.split('^')[1]; if (symbA !== symbB) { return symbA < symbB ? -1 : 1; } else { return expA > expB ? -1 : 1; } } }
javascript
function sortTerms(a, b) { if (a === b) { return 0; } // if no exponent, sort alphabetically if (a.indexOf('^') === -1) { return a < b ? -1 : 1; } // if exponent: sort by symbol, but then exponent decreasing else { const symbA = a.split('^')[0]; const expA = a.split('^')[1]; const symbB = b.split('^')[0]; const expB = b.split('^')[1]; if (symbA !== symbB) { return symbA < symbB ? -1 : 1; } else { return expA > expB ? -1 : 1; } } }
[ "function", "sortTerms", "(", "a", ",", "b", ")", "{", "if", "(", "a", "===", "b", ")", "{", "return", "0", ";", "}", "if", "(", "a", ".", "indexOf", "(", "'^'", ")", "===", "-", "1", ")", "{", "return", "a", "<", "b", "?", "-", "1", ":", "1", ";", "}", "else", "{", "const", "symbA", "=", "a", ".", "split", "(", "'^'", ")", "[", "0", "]", ";", "const", "expA", "=", "a", ".", "split", "(", "'^'", ")", "[", "1", "]", ";", "const", "symbB", "=", "b", ".", "split", "(", "'^'", ")", "[", "0", "]", ";", "const", "expB", "=", "b", ".", "split", "(", "'^'", ")", "[", "1", "]", ";", "if", "(", "symbA", "!==", "symbB", ")", "{", "return", "symbA", "<", "symbB", "?", "-", "1", ":", "1", ";", "}", "else", "{", "return", "expA", ">", "expB", "?", "-", "1", ":", "1", ";", "}", "}", "}" ]
Sort function for termnames. Sort first by symbol name, and then by exponent.
[ "Sort", "function", "for", "termnames", ".", "Sort", "first", "by", "symbol", "name", "and", "then", "by", "exponent", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/collectAndCombineSearch/LikeTermCollector.js#L252-L273
train
MikaelMayer/Editor
bin/server.js
getSolutionByNum
function getSolutionByNum(solutionSet, num) { if(solutionSet.computed.length >= num && num >= 1) { if(solutionSet.computed.length == num) { // If we select the last computed solution, we checked if we can compute more solutions. if(solutionSet.remaining !== false) { console.log("Checking for ambiguity #" + (num + 1)); var lt = sns.lazyList.tail(solutionSet.remaining); var newSolution = getOneSolution(solutionSet.path, solutionSet.serverFileContent, lt); if(newSolution === false) { console.log("No more ambiguity"); solutionSet.remaining = false; } else { console.log("Ambiguity #" + (num + 1) + " found"); solutionSet.remaining = lt; solutionSet.computed.push(newSolution); } } } return solutionSet.computed[num - 1]; } else { console.log(`Requested invalid solution number ${num}. Returning the first`) return solutionSet.computed[0]; } }
javascript
function getSolutionByNum(solutionSet, num) { if(solutionSet.computed.length >= num && num >= 1) { if(solutionSet.computed.length == num) { // If we select the last computed solution, we checked if we can compute more solutions. if(solutionSet.remaining !== false) { console.log("Checking for ambiguity #" + (num + 1)); var lt = sns.lazyList.tail(solutionSet.remaining); var newSolution = getOneSolution(solutionSet.path, solutionSet.serverFileContent, lt); if(newSolution === false) { console.log("No more ambiguity"); solutionSet.remaining = false; } else { console.log("Ambiguity #" + (num + 1) + " found"); solutionSet.remaining = lt; solutionSet.computed.push(newSolution); } } } return solutionSet.computed[num - 1]; } else { console.log(`Requested invalid solution number ${num}. Returning the first`) return solutionSet.computed[0]; } }
[ "function", "getSolutionByNum", "(", "solutionSet", ",", "num", ")", "{", "if", "(", "solutionSet", ".", "computed", ".", "length", ">=", "num", "&&", "num", ">=", "1", ")", "{", "if", "(", "solutionSet", ".", "computed", ".", "length", "==", "num", ")", "{", "if", "(", "solutionSet", ".", "remaining", "!==", "false", ")", "{", "console", ".", "log", "(", "\"Checking for ambiguity #\"", "+", "(", "num", "+", "1", ")", ")", ";", "var", "lt", "=", "sns", ".", "lazyList", ".", "tail", "(", "solutionSet", ".", "remaining", ")", ";", "var", "newSolution", "=", "getOneSolution", "(", "solutionSet", ".", "path", ",", "solutionSet", ".", "serverFileContent", ",", "lt", ")", ";", "if", "(", "newSolution", "===", "false", ")", "{", "console", ".", "log", "(", "\"No more ambiguity\"", ")", ";", "solutionSet", ".", "remaining", "=", "false", ";", "}", "else", "{", "console", ".", "log", "(", "\"Ambiguity #\"", "+", "(", "num", "+", "1", ")", "+", "\" found\"", ")", ";", "solutionSet", ".", "remaining", "=", "lt", ";", "solutionSet", ".", "computed", ".", "push", "(", "newSolution", ")", ";", "}", "}", "}", "return", "solutionSet", ".", "computed", "[", "num", "-", "1", "]", ";", "}", "else", "{", "console", ".", "log", "(", "`", "${", "num", "}", "`", ")", "return", "solutionSet", ".", "computed", "[", "0", "]", ";", "}", "}" ]
Retrieves the given solution by 1-based index from the set of solutions If the solution is the last computed, computes remaining solutions
[ "Retrieves", "the", "given", "solution", "by", "1", "-", "based", "index", "from", "the", "set", "of", "solutions", "If", "the", "solution", "is", "the", "last", "computed", "computes", "remaining", "solutions" ]
60a8eecacaff51e5894cc3537e1a07151060dae4
https://github.com/MikaelMayer/Editor/blob/60a8eecacaff51e5894cc3537e1a07151060dae4/bin/server.js#L132-L154
train
danillouz/react-snowfetti
src/utils/particle.js
_createParticle
function _createParticle(profile, { width, height }) { const { random } = Math; const { deltaX, deltaY, deltaOpacity, radius, color, opacity } = getParticleValues(profile); return { init() { this.x = random() * width; this.y = random() * -height; this.deltaX = deltaX; this.deltaY = deltaY; this.color = color; this.radius = radius; this.opacity = opacity; this.deltaOpacity = deltaOpacity; return this; } }; }
javascript
function _createParticle(profile, { width, height }) { const { random } = Math; const { deltaX, deltaY, deltaOpacity, radius, color, opacity } = getParticleValues(profile); return { init() { this.x = random() * width; this.y = random() * -height; this.deltaX = deltaX; this.deltaY = deltaY; this.color = color; this.radius = radius; this.opacity = opacity; this.deltaOpacity = deltaOpacity; return this; } }; }
[ "function", "_createParticle", "(", "profile", ",", "{", "width", ",", "height", "}", ")", "{", "const", "{", "random", "}", "=", "Math", ";", "const", "{", "deltaX", ",", "deltaY", ",", "deltaOpacity", ",", "radius", ",", "color", ",", "opacity", "}", "=", "getParticleValues", "(", "profile", ")", ";", "return", "{", "init", "(", ")", "{", "this", ".", "x", "=", "random", "(", ")", "*", "width", ";", "this", ".", "y", "=", "random", "(", ")", "*", "-", "height", ";", "this", ".", "deltaX", "=", "deltaX", ";", "this", ".", "deltaY", "=", "deltaY", ";", "this", ".", "color", "=", "color", ";", "this", ".", "radius", "=", "radius", ";", "this", ".", "opacity", "=", "opacity", ";", "this", ".", "deltaOpacity", "=", "deltaOpacity", ";", "return", "this", ";", "}", "}", ";", "}" ]
Create a single particle Object. @private @param {array} profile - particle profile that contains type and velocity @param {object} bounds - canvas width and height @return {object} particle Object
[ "Create", "a", "single", "particle", "Object", "." ]
1c103493205a125c717b2ea6602b5a52b3b73401
https://github.com/danillouz/react-snowfetti/blob/1c103493205a125c717b2ea6602b5a52b3b73401/src/utils/particle.js#L13-L38
train
mphasize/sails-generate-ember-blueprints
templates/advanced/api/blueprints/_util/actionUtil.js
function ( query, associations ) { _.each( associations, function ( assoc ) { // if the associations is to be populated with the full records... if ( assoc.include === "record" ) query.populate( assoc.alias ); } ); return query; }
javascript
function ( query, associations ) { _.each( associations, function ( assoc ) { // if the associations is to be populated with the full records... if ( assoc.include === "record" ) query.populate( assoc.alias ); } ); return query; }
[ "function", "(", "query", ",", "associations", ")", "{", "_", ".", "each", "(", "associations", ",", "function", "(", "assoc", ")", "{", "if", "(", "assoc", ".", "include", "===", "\"record\"", ")", "query", ".", "populate", "(", "assoc", ".", "alias", ")", ";", "}", ")", ";", "return", "query", ";", "}" ]
helper function to populate a Waterline query according to the model definition include -> record @param {[type]} query [description] @param {[type]} associations [description] @return {[type]} [description]
[ "helper", "function", "to", "populate", "a", "Waterline", "query", "according", "to", "the", "model", "definition", "include", "-", ">", "record" ]
c85211c58e806b538f000d6f4f1a2b0cbe72d8c9
https://github.com/mphasize/sails-generate-ember-blueprints/blob/c85211c58e806b538f000d6f4f1a2b0cbe72d8c9/templates/advanced/api/blueprints/_util/actionUtil.js#L88-L94
train
mphasize/sails-generate-ember-blueprints
templates/advanced/api/blueprints/_util/actionUtil.js
function ( req ) { // Allow customizable blacklist for params NOT to include as criteria. req.options.criteria = req.options.criteria || {}; req.options.criteria.blacklist = req.options.criteria.blacklist || [ 'limit', 'skip', 'sort', 'populate' ]; // Validate blacklist to provide a more helpful error msg. var blacklist = req.options.criteria && req.options.criteria.blacklist; if ( blacklist && !_.isArray( blacklist ) ) { throw new Error( 'Invalid `req.options.criteria.blacklist`. Should be an array of strings (parameter names.)' ); } // Look for explicitly specified `where` parameter. var where = req.params.all().where; // If `where` parameter is a string, try to interpret it as JSON if ( _.isString( where ) ) { where = tryToParseJSON( where ); } // If `where` has not been specified, but other unbound parameter variables // **ARE** specified, build the `where` option using them. if ( !where ) { // Prune params which aren't fit to be used as `where` criteria // to build a proper where query where = req.params.all(); // Omit built-in runtime config (like query modifiers) where = _.omit( where, blacklist || [ 'limit', 'skip', 'sort' ] ); // Omit any params w/ undefined values where = _.omit( where, function ( p ) { if ( _.isUndefined( p ) ) return true; } ); // Transform ids[ .., ..] request if ( where.ids ) { where.id = where.ids; delete where.ids; } // Omit jsonp callback param (but only if jsonp is enabled) var jsonpOpts = req.options.jsonp && !req.isSocket; jsonpOpts = _.isObject( jsonpOpts ) ? jsonpOpts : { callback: JSONP_CALLBACK_PARAM }; if ( jsonpOpts ) { where = _.omit( where, [ jsonpOpts.callback ] ); } } // Merge w/ req.options.where and return where = _.merge( {}, req.options.where || {}, where ) || undefined; return where; }
javascript
function ( req ) { // Allow customizable blacklist for params NOT to include as criteria. req.options.criteria = req.options.criteria || {}; req.options.criteria.blacklist = req.options.criteria.blacklist || [ 'limit', 'skip', 'sort', 'populate' ]; // Validate blacklist to provide a more helpful error msg. var blacklist = req.options.criteria && req.options.criteria.blacklist; if ( blacklist && !_.isArray( blacklist ) ) { throw new Error( 'Invalid `req.options.criteria.blacklist`. Should be an array of strings (parameter names.)' ); } // Look for explicitly specified `where` parameter. var where = req.params.all().where; // If `where` parameter is a string, try to interpret it as JSON if ( _.isString( where ) ) { where = tryToParseJSON( where ); } // If `where` has not been specified, but other unbound parameter variables // **ARE** specified, build the `where` option using them. if ( !where ) { // Prune params which aren't fit to be used as `where` criteria // to build a proper where query where = req.params.all(); // Omit built-in runtime config (like query modifiers) where = _.omit( where, blacklist || [ 'limit', 'skip', 'sort' ] ); // Omit any params w/ undefined values where = _.omit( where, function ( p ) { if ( _.isUndefined( p ) ) return true; } ); // Transform ids[ .., ..] request if ( where.ids ) { where.id = where.ids; delete where.ids; } // Omit jsonp callback param (but only if jsonp is enabled) var jsonpOpts = req.options.jsonp && !req.isSocket; jsonpOpts = _.isObject( jsonpOpts ) ? jsonpOpts : { callback: JSONP_CALLBACK_PARAM }; if ( jsonpOpts ) { where = _.omit( where, [ jsonpOpts.callback ] ); } } // Merge w/ req.options.where and return where = _.merge( {}, req.options.where || {}, where ) || undefined; return where; }
[ "function", "(", "req", ")", "{", "req", ".", "options", ".", "criteria", "=", "req", ".", "options", ".", "criteria", "||", "{", "}", ";", "req", ".", "options", ".", "criteria", ".", "blacklist", "=", "req", ".", "options", ".", "criteria", ".", "blacklist", "||", "[", "'limit'", ",", "'skip'", ",", "'sort'", ",", "'populate'", "]", ";", "var", "blacklist", "=", "req", ".", "options", ".", "criteria", "&&", "req", ".", "options", ".", "criteria", ".", "blacklist", ";", "if", "(", "blacklist", "&&", "!", "_", ".", "isArray", "(", "blacklist", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid `req.options.criteria.blacklist`. Should be an array of strings (parameter names.)'", ")", ";", "}", "var", "where", "=", "req", ".", "params", ".", "all", "(", ")", ".", "where", ";", "if", "(", "_", ".", "isString", "(", "where", ")", ")", "{", "where", "=", "tryToParseJSON", "(", "where", ")", ";", "}", "if", "(", "!", "where", ")", "{", "where", "=", "req", ".", "params", ".", "all", "(", ")", ";", "where", "=", "_", ".", "omit", "(", "where", ",", "blacklist", "||", "[", "'limit'", ",", "'skip'", ",", "'sort'", "]", ")", ";", "where", "=", "_", ".", "omit", "(", "where", ",", "function", "(", "p", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "p", ")", ")", "return", "true", ";", "}", ")", ";", "if", "(", "where", ".", "ids", ")", "{", "where", ".", "id", "=", "where", ".", "ids", ";", "delete", "where", ".", "ids", ";", "}", "var", "jsonpOpts", "=", "req", ".", "options", ".", "jsonp", "&&", "!", "req", ".", "isSocket", ";", "jsonpOpts", "=", "_", ".", "isObject", "(", "jsonpOpts", ")", "?", "jsonpOpts", ":", "{", "callback", ":", "JSONP_CALLBACK_PARAM", "}", ";", "if", "(", "jsonpOpts", ")", "{", "where", "=", "_", ".", "omit", "(", "where", ",", "[", "jsonpOpts", ".", "callback", "]", ")", ";", "}", "}", "where", "=", "_", ".", "merge", "(", "{", "}", ",", "req", ".", "options", ".", "where", "||", "{", "}", ",", "where", ")", "||", "undefined", ";", "return", "where", ";", "}" ]
Parse `criteria` for a Waterline `find` or `update` from all request parameters. @param {Request} req @return {Object} the WHERE criteria object
[ "Parse", "criteria", "for", "a", "Waterline", "find", "or", "update", "from", "all", "request", "parameters", "." ]
c85211c58e806b538f000d6f4f1a2b0cbe72d8c9
https://github.com/mphasize/sails-generate-ember-blueprints/blob/c85211c58e806b538f000d6f4f1a2b0cbe72d8c9/templates/advanced/api/blueprints/_util/actionUtil.js#L234-L290
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/fractionsSearch/addConstantFractions.js
addNumeratorsTogether
function addNumeratorsTogether(node) { const newNode = clone(node); newNode.args[0] = Node.Creator.constant(newNode.args[0].eval()); return Node.Status.nodeChanged( ChangeTypes.ADD_NUMERATORS, node, newNode); }
javascript
function addNumeratorsTogether(node) { const newNode = clone(node); newNode.args[0] = Node.Creator.constant(newNode.args[0].eval()); return Node.Status.nodeChanged( ChangeTypes.ADD_NUMERATORS, node, newNode); }
[ "function", "addNumeratorsTogether", "(", "node", ")", "{", "const", "newNode", "=", "clone", "(", "node", ")", ";", "newNode", ".", "args", "[", "0", "]", "=", "Node", ".", "Creator", ".", "constant", "(", "newNode", ".", "args", "[", "0", "]", ".", "eval", "(", ")", ")", ";", "return", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "ADD_NUMERATORS", ",", "node", ",", "newNode", ")", ";", "}" ]
Given a node with a numerator that is an addition node, will add all the numerators and return the result
[ "Given", "a", "node", "with", "a", "numerator", "that", "is", "an", "addition", "node", "will", "add", "all", "the", "numerators", "and", "return", "the", "result" ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/fractionsSearch/addConstantFractions.js#L101-L107
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/basicsSearch/reduceExponentByZero.js
reduceExponentByZero
function reduceExponentByZero(node) { if (node.op !== '^') { return Node.Status.noChange(node); } const exponent = node.args[1]; if (Node.Type.isConstant(exponent) && exponent.value === '0') { const newNode = Node.Creator.constant(1); return Node.Status.nodeChanged( ChangeTypes.REDUCE_EXPONENT_BY_ZERO, node, newNode); } else { return Node.Status.noChange(node); } }
javascript
function reduceExponentByZero(node) { if (node.op !== '^') { return Node.Status.noChange(node); } const exponent = node.args[1]; if (Node.Type.isConstant(exponent) && exponent.value === '0') { const newNode = Node.Creator.constant(1); return Node.Status.nodeChanged( ChangeTypes.REDUCE_EXPONENT_BY_ZERO, node, newNode); } else { return Node.Status.noChange(node); } }
[ "function", "reduceExponentByZero", "(", "node", ")", "{", "if", "(", "node", ".", "op", "!==", "'^'", ")", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "const", "exponent", "=", "node", ".", "args", "[", "1", "]", ";", "if", "(", "Node", ".", "Type", ".", "isConstant", "(", "exponent", ")", "&&", "exponent", ".", "value", "===", "'0'", ")", "{", "const", "newNode", "=", "Node", ".", "Creator", ".", "constant", "(", "1", ")", ";", "return", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "REDUCE_EXPONENT_BY_ZERO", ",", "node", ",", "newNode", ")", ";", "}", "else", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "}" ]
If `node` is an exponent of something to 0, we can reduce that to just 1. Returns a Node.Status object.
[ "If", "node", "is", "an", "exponent", "of", "something", "to", "0", "we", "can", "reduce", "that", "to", "just", "1", ".", "Returns", "a", "Node", ".", "Status", "object", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/basicsSearch/reduceExponentByZero.js#L8-L21
train
Dan503/gutter-grid
gulp/config/navMap-user-defaults.js
navMap_post_defaults
function navMap_post_defaults(map, index, parent){ replaceValues(map, { //propertyName : "forced overide value" //link : '#',//using this would disable ALL links (including links already defined in the main nav map file) }); return { depth: map.location.length, index: index, //link : '#',//this wouldn't do anything as the "link" property has already been defined by this stage //parentName : parent.title,//this would set "parentName" to the current nav items parent title } }
javascript
function navMap_post_defaults(map, index, parent){ replaceValues(map, { //propertyName : "forced overide value" //link : '#',//using this would disable ALL links (including links already defined in the main nav map file) }); return { depth: map.location.length, index: index, //link : '#',//this wouldn't do anything as the "link" property has already been defined by this stage //parentName : parent.title,//this would set "parentName" to the current nav items parent title } }
[ "function", "navMap_post_defaults", "(", "map", ",", "index", ",", "parent", ")", "{", "replaceValues", "(", "map", ",", "{", "}", ")", ";", "return", "{", "depth", ":", "map", ".", "location", ".", "length", ",", "index", ":", "index", ",", "}", "}" ]
These defaults are set after the nav map has been fully generated Use this to have access to all the standard values usually present in the nav map Mostly used to define brand new default values
[ "These", "defaults", "are", "set", "after", "the", "nav", "map", "has", "been", "fully", "generated", "Use", "this", "to", "have", "access", "to", "all", "the", "standard", "values", "usually", "present", "in", "the", "nav", "map", "Mostly", "used", "to", "define", "brand", "new", "default", "values" ]
b31084da606396577474cad592998a57a63725ba
https://github.com/Dan503/gutter-grid/blob/b31084da606396577474cad592998a57a63725ba/gulp/config/navMap-user-defaults.js#L25-L38
train
webmodules/get-window
index.js
getWindow
function getWindow(node) { if (isWindow(node)) { return node; } var doc = getDocument(node); if (needsIEFallback) { // In IE 6-8, only the variable 'window' can be used to connect events (others // may be only copies). doc.parentWindow.execScript('document._parentWindow = window;', 'Javascript'); var win = doc._parentWindow; // to prevent memory leak, unset it after use // another possibility is to add an onUnload handler, // (which seems overkill to @liucougar) doc._parentWindow = null; return win; } else { // standards-compliant and newer IE return doc.defaultView || doc.parentWindow; } }
javascript
function getWindow(node) { if (isWindow(node)) { return node; } var doc = getDocument(node); if (needsIEFallback) { // In IE 6-8, only the variable 'window' can be used to connect events (others // may be only copies). doc.parentWindow.execScript('document._parentWindow = window;', 'Javascript'); var win = doc._parentWindow; // to prevent memory leak, unset it after use // another possibility is to add an onUnload handler, // (which seems overkill to @liucougar) doc._parentWindow = null; return win; } else { // standards-compliant and newer IE return doc.defaultView || doc.parentWindow; } }
[ "function", "getWindow", "(", "node", ")", "{", "if", "(", "isWindow", "(", "node", ")", ")", "{", "return", "node", ";", "}", "var", "doc", "=", "getDocument", "(", "node", ")", ";", "if", "(", "needsIEFallback", ")", "{", "doc", ".", "parentWindow", ".", "execScript", "(", "'document._parentWindow = window;'", ",", "'Javascript'", ")", ";", "var", "win", "=", "doc", ".", "_parentWindow", ";", "doc", ".", "_parentWindow", "=", "null", ";", "return", "win", ";", "}", "else", "{", "return", "doc", ".", "defaultView", "||", "doc", ".", "parentWindow", ";", "}", "}" ]
Returns the `window` object associated with the given `node`, which may be a DOM element, the Window object, a Selection, a Range. Basically any DOM object that references the Window in some way, this function will find it. @param {Mixed} node - DOM node, selection, or range in which to find the `window` object @return {Window} the `window` object associated with `node` @public
[ "Returns", "the", "window", "object", "associated", "with", "the", "given", "node", "which", "may", "be", "a", "DOM", "element", "the", "Window", "object", "a", "Selection", "a", "Range", ".", "Basically", "any", "DOM", "object", "that", "references", "the", "Window", "in", "some", "way", "this", "function", "will", "find", "it", "." ]
17e1b576914acfdaa457ce4edba90ae93b78beb1
https://github.com/webmodules/get-window/blob/17e1b576914acfdaa457ce4edba90ae93b78beb1/index.js#L38-L59
train
pugjs/pug-source-gen
lib/code-generator.js
function(block, parent) { if (!block.nodes.length) return false; // line count var lines = block.nodes[block.nodes.length - 1].line - block.nodes[0].line + 1; if (lines === 1) return false; // word count of Text node values var words = 0; // number of Code nodes that are in their own lines var codesWithOwnLine = 0; // if the previous node was the first in its line var prevStartLine = false; for (var i = 0; i < block.nodes.length; i++) { var node = block.nodes[i]; var prev = block.nodes[i - 1] || parent || {line: -1}; var next = block.nodes[i]; if (node.type === 'Text') { words += (node.val.match(/\w+(\s+|$)/g) || []).length; } else if (node.type === 'Code' && node.buffer && !node.block) { if ((node.line > prev.line || prev.type === 'Text' && prev.val === '\n') && prevStartLine) { codesWithOwnLine++; } } else { // Technically Tags can also be interpolated, but determine whether to // use multiple dot blocks or one single dot block is way too // complicated. KISS. return false; } prevStartLine = node.line > prev.line || prev.type === 'Text' && prev.val === '\n'; } return words > 0 && codesWithOwnLine / lines < 0.35; }
javascript
function(block, parent) { if (!block.nodes.length) return false; // line count var lines = block.nodes[block.nodes.length - 1].line - block.nodes[0].line + 1; if (lines === 1) return false; // word count of Text node values var words = 0; // number of Code nodes that are in their own lines var codesWithOwnLine = 0; // if the previous node was the first in its line var prevStartLine = false; for (var i = 0; i < block.nodes.length; i++) { var node = block.nodes[i]; var prev = block.nodes[i - 1] || parent || {line: -1}; var next = block.nodes[i]; if (node.type === 'Text') { words += (node.val.match(/\w+(\s+|$)/g) || []).length; } else if (node.type === 'Code' && node.buffer && !node.block) { if ((node.line > prev.line || prev.type === 'Text' && prev.val === '\n') && prevStartLine) { codesWithOwnLine++; } } else { // Technically Tags can also be interpolated, but determine whether to // use multiple dot blocks or one single dot block is way too // complicated. KISS. return false; } prevStartLine = node.line > prev.line || prev.type === 'Text' && prev.val === '\n'; } return words > 0 && codesWithOwnLine / lines < 0.35; }
[ "function", "(", "block", ",", "parent", ")", "{", "if", "(", "!", "block", ".", "nodes", ".", "length", ")", "return", "false", ";", "var", "lines", "=", "block", ".", "nodes", "[", "block", ".", "nodes", ".", "length", "-", "1", "]", ".", "line", "-", "block", ".", "nodes", "[", "0", "]", ".", "line", "+", "1", ";", "if", "(", "lines", "===", "1", ")", "return", "false", ";", "var", "words", "=", "0", ";", "var", "codesWithOwnLine", "=", "0", ";", "var", "prevStartLine", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "block", ".", "nodes", ".", "length", ";", "i", "++", ")", "{", "var", "node", "=", "block", ".", "nodes", "[", "i", "]", ";", "var", "prev", "=", "block", ".", "nodes", "[", "i", "-", "1", "]", "||", "parent", "||", "{", "line", ":", "-", "1", "}", ";", "var", "next", "=", "block", ".", "nodes", "[", "i", "]", ";", "if", "(", "node", ".", "type", "===", "'Text'", ")", "{", "words", "+=", "(", "node", ".", "val", ".", "match", "(", "/", "\\w+(\\s+|$)", "/", "g", ")", "||", "[", "]", ")", ".", "length", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'Code'", "&&", "node", ".", "buffer", "&&", "!", "node", ".", "block", ")", "{", "if", "(", "(", "node", ".", "line", ">", "prev", ".", "line", "||", "prev", ".", "type", "===", "'Text'", "&&", "prev", ".", "val", "===", "'\\n'", ")", "&&", "\\n", ")", "prevStartLine", "}", "else", "{", "codesWithOwnLine", "++", ";", "}", "{", "return", "false", ";", "}", "}", "prevStartLine", "=", "node", ".", "line", ">", "prev", ".", "line", "||", "prev", ".", "type", "===", "'Text'", "&&", "prev", ".", "val", "===", "'\\n'", ";", "}" ]
heuristics to determine if dot syntax is preferred over piped text
[ "heuristics", "to", "determine", "if", "dot", "syntax", "is", "preferred", "over", "piped", "text" ]
512a681c94626f5bef9c0d6af0f9d1f2072dfdc4
https://github.com/pugjs/pug-source-gen/blob/512a681c94626f5bef9c0d6af0f9d1f2072dfdc4/lib/code-generator.js#L143-L178
train
metadelta/metadelta
packages/solver/lib/node/PolynomialTerm.js
negativeCoefficient
function negativeCoefficient(node) { if (NodeType.isConstant(node)) { node = NodeCreator.constant(0 - parseFloat(node.value)); } else { const numeratorValue = 0 - parseFloat(node.args[0].value); node.args[0] = NodeCreator.constant(numeratorValue); } return node; }
javascript
function negativeCoefficient(node) { if (NodeType.isConstant(node)) { node = NodeCreator.constant(0 - parseFloat(node.value)); } else { const numeratorValue = 0 - parseFloat(node.args[0].value); node.args[0] = NodeCreator.constant(numeratorValue); } return node; }
[ "function", "negativeCoefficient", "(", "node", ")", "{", "if", "(", "NodeType", ".", "isConstant", "(", "node", ")", ")", "{", "node", "=", "NodeCreator", ".", "constant", "(", "0", "-", "parseFloat", "(", "node", ".", "value", ")", ")", ";", "}", "else", "{", "const", "numeratorValue", "=", "0", "-", "parseFloat", "(", "node", ".", "args", "[", "0", "]", ".", "value", ")", ";", "node", ".", "args", "[", "0", "]", "=", "NodeCreator", ".", "constant", "(", "numeratorValue", ")", ";", "}", "return", "node", ";", "}" ]
Multiplies `node`, a constant or fraction of two constant nodes, by -1 Returns a node
[ "Multiplies", "node", "a", "constant", "or", "fraction", "of", "two", "constant", "nodes", "by", "-", "1", "Returns", "a", "node" ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/node/PolynomialTerm.js#L175-L184
train
SKalt/geojson-to-gml-3.2.1
src/index.js
orderCoords
function orderCoords(coords){ if (config.coordinateOrder){ return coords; } if (coords[2]){ return [coords[1], coords[0], coords[2]]; } return coords.reverse(); }
javascript
function orderCoords(coords){ if (config.coordinateOrder){ return coords; } if (coords[2]){ return [coords[1], coords[0], coords[2]]; } return coords.reverse(); }
[ "function", "orderCoords", "(", "coords", ")", "{", "if", "(", "config", ".", "coordinateOrder", ")", "{", "return", "coords", ";", "}", "if", "(", "coords", "[", "2", "]", ")", "{", "return", "[", "coords", "[", "1", "]", ",", "coords", "[", "0", "]", ",", "coords", "[", "2", "]", "]", ";", "}", "return", "coords", ".", "reverse", "(", ")", ";", "}" ]
reorder coordinates to lat, lng iff config.coordinateOrder is false. @param {Number[]} coords An array of coordinates, [lng, lat, ...etc] @return {Number[]} An array of coordinates in the correct order.
[ "reorder", "coordinates", "to", "lat", "lng", "iff", "config", ".", "coordinateOrder", "is", "false", "." ]
3d34be2af70eedde6a58bd2149ddbfbc313b7a73
https://github.com/SKalt/geojson-to-gml-3.2.1/blob/3d34be2af70eedde6a58bd2149ddbfbc313b7a73/src/index.js#L30-L38
train
SKalt/geojson-to-gml-3.2.1
src/index.js
multi
function multi(name, memberName, membercb, geom, gmlId, params={}){ var {srsName, gmlIds} = params; let multi = `<gml:${name}${attrs({srsName, 'gml:id':gmlId})}>`; multi += `<gml:${memberName}>`; geom.forEach(function(member, i){ let _gmlId = member.id || (gmlIds || [])[i] || ''; if (name == 'MultiGeometry'){ let memberType = member.type; member = member.coordinates; multi += membercb[memberType](member, _gmlId, params); } else { multi += membercb(member, _gmlId, params); } }); multi += `</gml:${memberName}>`; return multi + `</gml:${name}>`; }
javascript
function multi(name, memberName, membercb, geom, gmlId, params={}){ var {srsName, gmlIds} = params; let multi = `<gml:${name}${attrs({srsName, 'gml:id':gmlId})}>`; multi += `<gml:${memberName}>`; geom.forEach(function(member, i){ let _gmlId = member.id || (gmlIds || [])[i] || ''; if (name == 'MultiGeometry'){ let memberType = member.type; member = member.coordinates; multi += membercb[memberType](member, _gmlId, params); } else { multi += membercb(member, _gmlId, params); } }); multi += `</gml:${memberName}>`; return multi + `</gml:${name}>`; }
[ "function", "multi", "(", "name", ",", "memberName", ",", "membercb", ",", "geom", ",", "gmlId", ",", "params", "=", "{", "}", ")", "{", "var", "{", "srsName", ",", "gmlIds", "}", "=", "params", ";", "let", "multi", "=", "`", "${", "name", "}", "${", "attrs", "(", "{", "srsName", ",", "'gml:id'", ":", "gmlId", "}", ")", "}", "`", ";", "multi", "+=", "`", "${", "memberName", "}", "`", ";", "geom", ".", "forEach", "(", "function", "(", "member", ",", "i", ")", "{", "let", "_gmlId", "=", "member", ".", "id", "||", "(", "gmlIds", "||", "[", "]", ")", "[", "i", "]", "||", "''", ";", "if", "(", "name", "==", "'MultiGeometry'", ")", "{", "let", "memberType", "=", "member", ".", "type", ";", "member", "=", "member", ".", "coordinates", ";", "multi", "+=", "membercb", "[", "memberType", "]", "(", "member", ",", "_gmlId", ",", "params", ")", ";", "}", "else", "{", "multi", "+=", "membercb", "(", "member", ",", "_gmlId", ",", "params", ")", ";", "}", "}", ")", ";", "multi", "+=", "`", "${", "memberName", "}", "`", ";", "return", "multi", "+", "`", "${", "name", "}", "`", ";", "}" ]
Optional parameters for conversion of geojson to gml geometries @typedef {Object} Params @property {?String} params.srsName as string specifying SRS, e.g. 'EPSG:4326'. Only applies to multigeometries. @property {?Number[]|?String[]} params.gmlIds an array of number/string gml:ids of the member geometries. @property {?Number|?String} params.srsDimension the dimensionality of each coordinate, i.e. 2 or 3. A handler to compile geometries to multigeometries @function @param {String} name the name of the target multigeometry @param {String} memberName the gml:tag of each multigeometry member. @param {Object[]|Array} geom an array of geojson geometries @param {String|Number} gmlId the gml:id of the multigeometry @param {Params} params optional parameters. Omit gmlIds at your own risk, however. @returns {String} a string containing gml describing the input multigeometry @throws {Error} if a member geometry cannot be converted to gml
[ "Optional", "parameters", "for", "conversion", "of", "geojson", "to", "gml", "geometries" ]
3d34be2af70eedde6a58bd2149ddbfbc313b7a73
https://github.com/SKalt/geojson-to-gml-3.2.1/blob/3d34be2af70eedde6a58bd2149ddbfbc313b7a73/src/index.js#L70-L86
train
SKalt/geojson-to-gml-3.2.1
src/index.js
makeConverter
function makeConverter(obj) { return Object.entries(obj).map(([type, converter]) => { return {[type[0].toUpperCase() + type.slice(1)]: converter}; }).reduce((a, b) => Object.assign(a, b), {}); }
javascript
function makeConverter(obj) { return Object.entries(obj).map(([type, converter]) => { return {[type[0].toUpperCase() + type.slice(1)]: converter}; }).reduce((a, b) => Object.assign(a, b), {}); }
[ "function", "makeConverter", "(", "obj", ")", "{", "return", "Object", ".", "entries", "(", "obj", ")", ".", "map", "(", "(", "[", "type", ",", "converter", "]", ")", "=>", "{", "return", "{", "[", "type", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "type", ".", "slice", "(", "1", ")", "]", ":", "converter", "}", ";", "}", ")", ".", "reduce", "(", "(", "a", ",", "b", ")", "=>", "Object", ".", "assign", "(", "a", ",", "b", ")", ",", "{", "}", ")", ";", "}" ]
A helper to de-camelcase this module's geometry conversion methods @param {Object} obj a mapping of camelcase geometry types to converter functions @return {Object} a mapping of capitalized geometry types to converter functions @example makeConverter({lineString}) // returns {LineString: lineString}
[ "A", "helper", "to", "de", "-", "camelcase", "this", "module", "s", "geometry", "conversion", "methods" ]
3d34be2af70eedde6a58bd2149ddbfbc313b7a73
https://github.com/SKalt/geojson-to-gml-3.2.1/blob/3d34be2af70eedde6a58bd2149ddbfbc313b7a73/src/index.js#L203-L208
train
metadelta/metadelta
packages/solver/lib/solveEquation/EquationOperations.js
performTermOperationOnEquation
function performTermOperationOnEquation(equation, op, term, changeType) { const oldEquation = equation.clone(); const leftTerm = clone(term); const rightTerm = clone(term); const leftNode = performTermOperationOnExpression( equation.leftNode, op, leftTerm); const rightNode = performTermOperationOnExpression( equation.rightNode, op, rightTerm); let comparator = equation.comparator; if (Negative.isNegative(term) && (op === '*' || op === '/')) { comparator = COMPARATOR_TO_INVERSE[comparator]; } const newEquation = new Equation(leftNode, rightNode, comparator); return new EquationStatus(changeType, oldEquation, newEquation); }
javascript
function performTermOperationOnEquation(equation, op, term, changeType) { const oldEquation = equation.clone(); const leftTerm = clone(term); const rightTerm = clone(term); const leftNode = performTermOperationOnExpression( equation.leftNode, op, leftTerm); const rightNode = performTermOperationOnExpression( equation.rightNode, op, rightTerm); let comparator = equation.comparator; if (Negative.isNegative(term) && (op === '*' || op === '/')) { comparator = COMPARATOR_TO_INVERSE[comparator]; } const newEquation = new Equation(leftNode, rightNode, comparator); return new EquationStatus(changeType, oldEquation, newEquation); }
[ "function", "performTermOperationOnEquation", "(", "equation", ",", "op", ",", "term", ",", "changeType", ")", "{", "const", "oldEquation", "=", "equation", ".", "clone", "(", ")", ";", "const", "leftTerm", "=", "clone", "(", "term", ")", ";", "const", "rightTerm", "=", "clone", "(", "term", ")", ";", "const", "leftNode", "=", "performTermOperationOnExpression", "(", "equation", ".", "leftNode", ",", "op", ",", "leftTerm", ")", ";", "const", "rightNode", "=", "performTermOperationOnExpression", "(", "equation", ".", "rightNode", ",", "op", ",", "rightTerm", ")", ";", "let", "comparator", "=", "equation", ".", "comparator", ";", "if", "(", "Negative", ".", "isNegative", "(", "term", ")", "&&", "(", "op", "===", "'*'", "||", "op", "===", "'/'", ")", ")", "{", "comparator", "=", "COMPARATOR_TO_INVERSE", "[", "comparator", "]", ";", "}", "const", "newEquation", "=", "new", "Equation", "(", "leftNode", ",", "rightNode", ",", "comparator", ")", ";", "return", "new", "EquationStatus", "(", "changeType", ",", "oldEquation", ",", "newEquation", ")", ";", "}" ]
Modifies the left and right sides of an equation by `op`-ing `term` to both sides. Returns an Status object.
[ "Modifies", "the", "left", "and", "right", "sides", "of", "an", "equation", "by", "op", "-", "ing", "term", "to", "both", "sides", ".", "Returns", "an", "Status", "object", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/solveEquation/EquationOperations.js#L203-L220
train
metadelta/metadelta
packages/solver/lib/solveEquation/EquationOperations.js
performTermOperationOnExpression
function performTermOperationOnExpression(expression, op, term) { const node = (Node.Type.isOperator(expression) ? Node.Creator.parenthesis(expression) : expression); term.changeGroup = 1; const newNode = Node.Creator.operator(op, [node, term]); return newNode; }
javascript
function performTermOperationOnExpression(expression, op, term) { const node = (Node.Type.isOperator(expression) ? Node.Creator.parenthesis(expression) : expression); term.changeGroup = 1; const newNode = Node.Creator.operator(op, [node, term]); return newNode; }
[ "function", "performTermOperationOnExpression", "(", "expression", ",", "op", ",", "term", ")", "{", "const", "node", "=", "(", "Node", ".", "Type", ".", "isOperator", "(", "expression", ")", "?", "Node", ".", "Creator", ".", "parenthesis", "(", "expression", ")", ":", "expression", ")", ";", "term", ".", "changeGroup", "=", "1", ";", "const", "newNode", "=", "Node", ".", "Creator", ".", "operator", "(", "op", ",", "[", "node", ",", "term", "]", ")", ";", "return", "newNode", ";", "}" ]
Performs an operation of a term on an entire given expression
[ "Performs", "an", "operation", "of", "a", "term", "on", "an", "entire", "given", "expression" ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/solveEquation/EquationOperations.js#L223-L231
train
metadelta/metadelta
packages/solver/lib/checks/canMultiplyLikeTermPolynomialNodes.js
canMultiplyLikeTermPolynomialNodes
function canMultiplyLikeTermPolynomialNodes(node) { if (!Node.Type.isOperator(node) || node.op !== '*') { return false; } const args = node.args; if (!args.every(n => Node.PolynomialTerm.isPolynomialTerm(n))) { return false; } if (args.length === 1) { return false; } const polynomialTermList = node.args.map(n => new Node.PolynomialTerm(n)); if (!polynomialTermList.every(polyTerm => !polyTerm.hasCoeff())) { return false; } const firstTerm = polynomialTermList[0]; const restTerms = polynomialTermList.slice(1); // they're considered like terms if they have the same symbol name return restTerms.every(term => firstTerm.getSymbolName() === term.getSymbolName()); }
javascript
function canMultiplyLikeTermPolynomialNodes(node) { if (!Node.Type.isOperator(node) || node.op !== '*') { return false; } const args = node.args; if (!args.every(n => Node.PolynomialTerm.isPolynomialTerm(n))) { return false; } if (args.length === 1) { return false; } const polynomialTermList = node.args.map(n => new Node.PolynomialTerm(n)); if (!polynomialTermList.every(polyTerm => !polyTerm.hasCoeff())) { return false; } const firstTerm = polynomialTermList[0]; const restTerms = polynomialTermList.slice(1); // they're considered like terms if they have the same symbol name return restTerms.every(term => firstTerm.getSymbolName() === term.getSymbolName()); }
[ "function", "canMultiplyLikeTermPolynomialNodes", "(", "node", ")", "{", "if", "(", "!", "Node", ".", "Type", ".", "isOperator", "(", "node", ")", "||", "node", ".", "op", "!==", "'*'", ")", "{", "return", "false", ";", "}", "const", "args", "=", "node", ".", "args", ";", "if", "(", "!", "args", ".", "every", "(", "n", "=>", "Node", ".", "PolynomialTerm", ".", "isPolynomialTerm", "(", "n", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "args", ".", "length", "===", "1", ")", "{", "return", "false", ";", "}", "const", "polynomialTermList", "=", "node", ".", "args", ".", "map", "(", "n", "=>", "new", "Node", ".", "PolynomialTerm", "(", "n", ")", ")", ";", "if", "(", "!", "polynomialTermList", ".", "every", "(", "polyTerm", "=>", "!", "polyTerm", ".", "hasCoeff", "(", ")", ")", ")", "{", "return", "false", ";", "}", "const", "firstTerm", "=", "polynomialTermList", "[", "0", "]", ";", "const", "restTerms", "=", "polynomialTermList", ".", "slice", "(", "1", ")", ";", "return", "restTerms", ".", "every", "(", "term", "=>", "firstTerm", ".", "getSymbolName", "(", ")", "===", "term", ".", "getSymbolName", "(", ")", ")", ";", "}" ]
Returns true if the nodes are symbolic terms with the same symbol and no coefficients.
[ "Returns", "true", "if", "the", "nodes", "are", "symbolic", "terms", "with", "the", "same", "symbol", "and", "no", "coefficients", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/checks/canMultiplyLikeTermPolynomialNodes.js#L7-L28
train
deanius/antares
demos/03-concurrent-fruit.js
simulatedUserInput
function simulatedUserInput(numArray) { // pause + first one // forEach after the first: outer + inner const rest$ = numOrArray => { if (!numOrArray.length) return after(pause, () => numOrArray) let rest = after(pause, () => numOrArray[0]) for (let i = 1; i < numOrArray.length; i++) { rest = concat(rest, after(outer, () => numOrArray[i])) } return rest } return from(numArray).pipe(concatMap(rest$)) }
javascript
function simulatedUserInput(numArray) { // pause + first one // forEach after the first: outer + inner const rest$ = numOrArray => { if (!numOrArray.length) return after(pause, () => numOrArray) let rest = after(pause, () => numOrArray[0]) for (let i = 1; i < numOrArray.length; i++) { rest = concat(rest, after(outer, () => numOrArray[i])) } return rest } return from(numArray).pipe(concatMap(rest$)) }
[ "function", "simulatedUserInput", "(", "numArray", ")", "{", "const", "rest$", "=", "numOrArray", "=>", "{", "if", "(", "!", "numOrArray", ".", "length", ")", "return", "after", "(", "pause", ",", "(", ")", "=>", "numOrArray", ")", "let", "rest", "=", "after", "(", "pause", ",", "(", ")", "=>", "numOrArray", "[", "0", "]", ")", "for", "(", "let", "i", "=", "1", ";", "i", "<", "numOrArray", ".", "length", ";", "i", "++", ")", "{", "rest", "=", "concat", "(", "rest", ",", "after", "(", "outer", ",", "(", ")", "=>", "numOrArray", "[", "i", "]", ")", ")", "}", "return", "rest", "}", "return", "from", "(", "numArray", ")", ".", "pipe", "(", "concatMap", "(", "rest$", ")", ")", "}" ]
an observable of numbers every second
[ "an", "observable", "of", "numbers", "every", "second" ]
e876afbfa3b56356c9b0a9d24a82cbf603b0a8f5
https://github.com/deanius/antares/blob/e876afbfa3b56356c9b0a9d24a82cbf603b0a8f5/demos/03-concurrent-fruit.js#L86-L99
train
deanius/antares
demos/03-concurrent-fruit.js
getUserInputFromStdin
function getUserInputFromStdin() { // set up stdin const keypress = require("keypress") keypress(process.stdin) process.stdin.setRawMode(true) process.stdin.resume() // A Subject is something that you can push values at, and // it can be subscribed to as an Observable of those values const s = new Subject() // set up handler and return the stream as Observable process.stdin.on("keypress", (ch, key = {}) => { if (key.name == "x" || (key && key.ctrl && key.name == "c")) { process.stdin.pause() s.complete() log("\nBye!") process.exit() } if (ch === "0" || Number(ch)) { s.next(Number(ch)) } else { process.stdin.pause() log("Not 0-9.\nBye!") s.complete() } }) return s.asObservable() }
javascript
function getUserInputFromStdin() { // set up stdin const keypress = require("keypress") keypress(process.stdin) process.stdin.setRawMode(true) process.stdin.resume() // A Subject is something that you can push values at, and // it can be subscribed to as an Observable of those values const s = new Subject() // set up handler and return the stream as Observable process.stdin.on("keypress", (ch, key = {}) => { if (key.name == "x" || (key && key.ctrl && key.name == "c")) { process.stdin.pause() s.complete() log("\nBye!") process.exit() } if (ch === "0" || Number(ch)) { s.next(Number(ch)) } else { process.stdin.pause() log("Not 0-9.\nBye!") s.complete() } }) return s.asObservable() }
[ "function", "getUserInputFromStdin", "(", ")", "{", "const", "keypress", "=", "require", "(", "\"keypress\"", ")", "keypress", "(", "process", ".", "stdin", ")", "process", ".", "stdin", ".", "setRawMode", "(", "true", ")", "process", ".", "stdin", ".", "resume", "(", ")", "const", "s", "=", "new", "Subject", "(", ")", "process", ".", "stdin", ".", "on", "(", "\"keypress\"", ",", "(", "ch", ",", "key", "=", "{", "}", ")", "=>", "{", "if", "(", "key", ".", "name", "==", "\"x\"", "||", "(", "key", "&&", "key", ".", "ctrl", "&&", "key", ".", "name", "==", "\"c\"", ")", ")", "{", "process", ".", "stdin", ".", "pause", "(", ")", "s", ".", "complete", "(", ")", "log", "(", "\"\\nBye!\"", ")", "\\n", "}", "process", ".", "exit", "(", ")", "}", ")", "if", "(", "ch", "===", "\"0\"", "||", "Number", "(", "ch", ")", ")", "{", "s", ".", "next", "(", "Number", "(", "ch", ")", ")", "}", "else", "{", "process", ".", "stdin", ".", "pause", "(", ")", "log", "(", "\"Not 0-9.\\nBye!\"", ")", "\\n", "}", "}" ]
get a stream - like a promise that keeps emitting events over time which you get via subscribing
[ "get", "a", "stream", "-", "like", "a", "promise", "that", "keeps", "emitting", "events", "over", "time", "which", "you", "get", "via", "subscribing" ]
e876afbfa3b56356c9b0a9d24a82cbf603b0a8f5
https://github.com/deanius/antares/blob/e876afbfa3b56356c9b0a9d24a82cbf603b0a8f5/demos/03-concurrent-fruit.js#L116-L145
train
Dan503/gutter-grid
gulp/helpers/navMap-helpers.js
getTitleMap
function getTitleMap(startMap, userSearchTerm, isRecursive) { var returnValue = false; var found = false; var isRecursive = defaultTo(isRecursive, true); function iterator(map, searchTerm){ for(var i = 0; i < map.length; i++) { var item = map[i]; //removes any html in the strings before searching for a match var itemTitle = stripTags(item.title).toLowerCase(); var providedTitle = stripTags(searchTerm).toLowerCase(); //also converts strings to lowercase so they aren't case sensitive if (itemTitle === providedTitle){ //if the provided title matches the current item title, set the return value to current item returnValue = item; found = true; break; } else if ('subnav' in item && isRecursive){ iterator(item.subnav, searchTerm); if (found){ break; } } } } iterator(startMap.subnav, userSearchTerm); if (returnValue === false){ //shouldn't do this unless the function fails console.log('\n"'+ userSearchTerm +'" title could not be found in navMap.json'); } return returnValue; }
javascript
function getTitleMap(startMap, userSearchTerm, isRecursive) { var returnValue = false; var found = false; var isRecursive = defaultTo(isRecursive, true); function iterator(map, searchTerm){ for(var i = 0; i < map.length; i++) { var item = map[i]; //removes any html in the strings before searching for a match var itemTitle = stripTags(item.title).toLowerCase(); var providedTitle = stripTags(searchTerm).toLowerCase(); //also converts strings to lowercase so they aren't case sensitive if (itemTitle === providedTitle){ //if the provided title matches the current item title, set the return value to current item returnValue = item; found = true; break; } else if ('subnav' in item && isRecursive){ iterator(item.subnav, searchTerm); if (found){ break; } } } } iterator(startMap.subnav, userSearchTerm); if (returnValue === false){ //shouldn't do this unless the function fails console.log('\n"'+ userSearchTerm +'" title could not be found in navMap.json'); } return returnValue; }
[ "function", "getTitleMap", "(", "startMap", ",", "userSearchTerm", ",", "isRecursive", ")", "{", "var", "returnValue", "=", "false", ";", "var", "found", "=", "false", ";", "var", "isRecursive", "=", "defaultTo", "(", "isRecursive", ",", "true", ")", ";", "function", "iterator", "(", "map", ",", "searchTerm", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "map", ".", "length", ";", "i", "++", ")", "{", "var", "item", "=", "map", "[", "i", "]", ";", "var", "itemTitle", "=", "stripTags", "(", "item", ".", "title", ")", ".", "toLowerCase", "(", ")", ";", "var", "providedTitle", "=", "stripTags", "(", "searchTerm", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "itemTitle", "===", "providedTitle", ")", "{", "returnValue", "=", "item", ";", "found", "=", "true", ";", "break", ";", "}", "else", "if", "(", "'subnav'", "in", "item", "&&", "isRecursive", ")", "{", "iterator", "(", "item", ".", "subnav", ",", "searchTerm", ")", ";", "if", "(", "found", ")", "{", "break", ";", "}", "}", "}", "}", "iterator", "(", "startMap", ".", "subnav", ",", "userSearchTerm", ")", ";", "if", "(", "returnValue", "===", "false", ")", "{", "console", ".", "log", "(", "'\\n\"'", "+", "\\n", "+", "userSearchTerm", ")", ";", "}", "'\" title could not be found in navMap.json'", "}" ]
function that retrieves a map from the navMap variable based on the title attribute function not to be used in regular code
[ "function", "that", "retrieves", "a", "map", "from", "the", "navMap", "variable", "based", "on", "the", "title", "attribute", "function", "not", "to", "be", "used", "in", "regular", "code" ]
b31084da606396577474cad592998a57a63725ba
https://github.com/Dan503/gutter-grid/blob/b31084da606396577474cad592998a57a63725ba/gulp/helpers/navMap-helpers.js#L15-L53
train
Dan503/gutter-grid
gulp/helpers/navMap-helpers.js
checkSearchTerm
function checkSearchTerm(searchTerm){ if (!is_string(searchTerm) && !is_numeric(searchTerm)){ console.log('\nError: This must be either a string or an interval:\n', searchTerm, ' \n'); return false; } else { return true; } }
javascript
function checkSearchTerm(searchTerm){ if (!is_string(searchTerm) && !is_numeric(searchTerm)){ console.log('\nError: This must be either a string or an interval:\n', searchTerm, ' \n'); return false; } else { return true; } }
[ "function", "checkSearchTerm", "(", "searchTerm", ")", "{", "if", "(", "!", "is_string", "(", "searchTerm", ")", "&&", "!", "is_numeric", "(", "searchTerm", ")", ")", "{", "console", ".", "log", "(", "'\\nError: This must be either a string or an interval:\\n'", ",", "\\n", ",", "\\n", ")", ";", "searchTerm", "}", "else", "' \\n'", "}" ]
Throw an error if neither a string or an interval provided
[ "Throw", "an", "error", "if", "neither", "a", "string", "or", "an", "interval", "provided" ]
b31084da606396577474cad592998a57a63725ba
https://github.com/Dan503/gutter-grid/blob/b31084da606396577474cad592998a57a63725ba/gulp/helpers/navMap-helpers.js#L56-L63
train
Dan503/gutter-grid
gulp/helpers/navMap-helpers.js
getSpecificMap
function getSpecificMap(map, array){ var returnMap; var arrayCopy = array.splice(0); //if first item in array is "current" or "subnav" it makes the function a bit more efficient //it restricts any title searches to just offspring of the current page if (array[0] === 'current' || array[0] === 'subnav'){ arrayCopy.shift(); arrayCopy = pageMap.location.concat(link); } for (var i = 0; i < arrayCopy.length; i++){ var searchTerm = arrayCopy[i]; var searchMap = typeof returnMap !== 'undefined' ? returnMap : map; //Output an error if neither a string or an interval provided if (checkSearchTerm(searchTerm)){ if (is_string(searchTerm)){ //if item is a string, do a getTitleMap function on the search term using the last map returnMap = getTitleMap(searchMap, searchTerm); } else if(is_numeric(searchTerm) && isset(searchMap.subnav)) { //if item is a number, return the map at the specified index of the last map in array returnMap = searchMap.subnav[parseInt(searchTerm)]; } else { returnMap = false; break; } } else { break; } } if (returnMap){ return returnMap; } else { return false; } }
javascript
function getSpecificMap(map, array){ var returnMap; var arrayCopy = array.splice(0); //if first item in array is "current" or "subnav" it makes the function a bit more efficient //it restricts any title searches to just offspring of the current page if (array[0] === 'current' || array[0] === 'subnav'){ arrayCopy.shift(); arrayCopy = pageMap.location.concat(link); } for (var i = 0; i < arrayCopy.length; i++){ var searchTerm = arrayCopy[i]; var searchMap = typeof returnMap !== 'undefined' ? returnMap : map; //Output an error if neither a string or an interval provided if (checkSearchTerm(searchTerm)){ if (is_string(searchTerm)){ //if item is a string, do a getTitleMap function on the search term using the last map returnMap = getTitleMap(searchMap, searchTerm); } else if(is_numeric(searchTerm) && isset(searchMap.subnav)) { //if item is a number, return the map at the specified index of the last map in array returnMap = searchMap.subnav[parseInt(searchTerm)]; } else { returnMap = false; break; } } else { break; } } if (returnMap){ return returnMap; } else { return false; } }
[ "function", "getSpecificMap", "(", "map", ",", "array", ")", "{", "var", "returnMap", ";", "var", "arrayCopy", "=", "array", ".", "splice", "(", "0", ")", ";", "if", "(", "array", "[", "0", "]", "===", "'current'", "||", "array", "[", "0", "]", "===", "'subnav'", ")", "{", "arrayCopy", ".", "shift", "(", ")", ";", "arrayCopy", "=", "pageMap", ".", "location", ".", "concat", "(", "link", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arrayCopy", ".", "length", ";", "i", "++", ")", "{", "var", "searchTerm", "=", "arrayCopy", "[", "i", "]", ";", "var", "searchMap", "=", "typeof", "returnMap", "!==", "'undefined'", "?", "returnMap", ":", "map", ";", "if", "(", "checkSearchTerm", "(", "searchTerm", ")", ")", "{", "if", "(", "is_string", "(", "searchTerm", ")", ")", "{", "returnMap", "=", "getTitleMap", "(", "searchMap", ",", "searchTerm", ")", ";", "}", "else", "if", "(", "is_numeric", "(", "searchTerm", ")", "&&", "isset", "(", "searchMap", ".", "subnav", ")", ")", "{", "returnMap", "=", "searchMap", ".", "subnav", "[", "parseInt", "(", "searchTerm", ")", "]", ";", "}", "else", "{", "returnMap", "=", "false", ";", "break", ";", "}", "}", "else", "{", "break", ";", "}", "}", "if", "(", "returnMap", ")", "{", "return", "returnMap", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
function that accepts an array to search for specific sections of the nav map array accepts both numbers and titles function not to be used in regular code
[ "function", "that", "accepts", "an", "array", "to", "search", "for", "specific", "sections", "of", "the", "nav", "map", "array", "accepts", "both", "numbers", "and", "titles", "function", "not", "to", "be", "used", "in", "regular", "code" ]
b31084da606396577474cad592998a57a63725ba
https://github.com/Dan503/gutter-grid/blob/b31084da606396577474cad592998a57a63725ba/gulp/helpers/navMap-helpers.js#L68-L108
train
Dan503/gutter-grid
gulp/helpers/navMap-helpers.js
getNavMap
function getNavMap(navMap, searchTerm, portion){ let returnMap = navMap; if (!isset(searchTerm) || is_array(searchTerm) && searchTerm.length === 0){ //if the search term is an empty array, it will return the full nav map (excluding ROOT) return returnMap; } //code for when an array is given (filters results based on numbers and titles provided in array) if (is_array(searchTerm)){ returnMap = getSpecificMap(returnMap, searchTerm); //code for when a string is given (searches full nav map for Title that matches) } else if (is_string(searchTerm)) { returnMap = getTitleMap(returnMap, searchTerm); //code for when a single number is given (treats it as a single level location variable) } else if (is_int(searchTerm)) { returnMap = returnMap[searchTerm]; //throws error if searchTerm variable doesn't make sense } else { console.log('\nThe search term must be either a string, interval or an array. \nSearch term =\n', searchTerm); } if (isset(portion)) { return returnMap[portion]; } else { return returnMap; } }
javascript
function getNavMap(navMap, searchTerm, portion){ let returnMap = navMap; if (!isset(searchTerm) || is_array(searchTerm) && searchTerm.length === 0){ //if the search term is an empty array, it will return the full nav map (excluding ROOT) return returnMap; } //code for when an array is given (filters results based on numbers and titles provided in array) if (is_array(searchTerm)){ returnMap = getSpecificMap(returnMap, searchTerm); //code for when a string is given (searches full nav map for Title that matches) } else if (is_string(searchTerm)) { returnMap = getTitleMap(returnMap, searchTerm); //code for when a single number is given (treats it as a single level location variable) } else if (is_int(searchTerm)) { returnMap = returnMap[searchTerm]; //throws error if searchTerm variable doesn't make sense } else { console.log('\nThe search term must be either a string, interval or an array. \nSearch term =\n', searchTerm); } if (isset(portion)) { return returnMap[portion]; } else { return returnMap; } }
[ "function", "getNavMap", "(", "navMap", ",", "searchTerm", ",", "portion", ")", "{", "let", "returnMap", "=", "navMap", ";", "if", "(", "!", "isset", "(", "searchTerm", ")", "||", "is_array", "(", "searchTerm", ")", "&&", "searchTerm", ".", "length", "===", "0", ")", "{", "return", "returnMap", ";", "}", "if", "(", "is_array", "(", "searchTerm", ")", ")", "{", "returnMap", "=", "getSpecificMap", "(", "returnMap", ",", "searchTerm", ")", ";", "}", "else", "if", "(", "is_string", "(", "searchTerm", ")", ")", "{", "returnMap", "=", "getTitleMap", "(", "returnMap", ",", "searchTerm", ")", ";", "}", "else", "if", "(", "is_int", "(", "searchTerm", ")", ")", "{", "returnMap", "=", "returnMap", "[", "searchTerm", "]", ";", "}", "else", "{", "console", ".", "log", "(", "'\\nThe search term must be either a string, interval or an array. \\nSearch term =\\n'", ",", "\\n", ")", ";", "}", "\\n", "}" ]
function for looking up a specific portion of the navMap using a location array or a title
[ "function", "for", "looking", "up", "a", "specific", "portion", "of", "the", "navMap", "using", "a", "location", "array", "or", "a", "title" ]
b31084da606396577474cad592998a57a63725ba
https://github.com/Dan503/gutter-grid/blob/b31084da606396577474cad592998a57a63725ba/gulp/helpers/navMap-helpers.js#L137-L169
train
IndigoUnited/automaton
lib/string/castInterpolate.js
castInterpolate
function castInterpolate(template, replacements, options) { var matches = template.match(regExp); var placeholder; var not; if (matches) { placeholder = matches[1]; // Check if exists first if (mout.object.has(replacements, placeholder)) { return mout.object.get(replacements, placeholder); } // Handle not (!) (note that !foo! is ignored but !foo isn't) if (/^!+?[^!]+$/.test(placeholder)) { placeholder = placeholder.replace(/!!+/, ''); not = placeholder.charAt(0) === '!'; placeholder = not ? placeholder.substr(1) : placeholder; if (mout.object.has(replacements, placeholder)) { placeholder = mout.object.get(replacements, placeholder); return not ? !placeholder : !!placeholder; } } } return interpolate(template, replacements, options); }
javascript
function castInterpolate(template, replacements, options) { var matches = template.match(regExp); var placeholder; var not; if (matches) { placeholder = matches[1]; // Check if exists first if (mout.object.has(replacements, placeholder)) { return mout.object.get(replacements, placeholder); } // Handle not (!) (note that !foo! is ignored but !foo isn't) if (/^!+?[^!]+$/.test(placeholder)) { placeholder = placeholder.replace(/!!+/, ''); not = placeholder.charAt(0) === '!'; placeholder = not ? placeholder.substr(1) : placeholder; if (mout.object.has(replacements, placeholder)) { placeholder = mout.object.get(replacements, placeholder); return not ? !placeholder : !!placeholder; } } } return interpolate(template, replacements, options); }
[ "function", "castInterpolate", "(", "template", ",", "replacements", ",", "options", ")", "{", "var", "matches", "=", "template", ".", "match", "(", "regExp", ")", ";", "var", "placeholder", ";", "var", "not", ";", "if", "(", "matches", ")", "{", "placeholder", "=", "matches", "[", "1", "]", ";", "if", "(", "mout", ".", "object", ".", "has", "(", "replacements", ",", "placeholder", ")", ")", "{", "return", "mout", ".", "object", ".", "get", "(", "replacements", ",", "placeholder", ")", ";", "}", "if", "(", "/", "^!+?[^!]+$", "/", ".", "test", "(", "placeholder", ")", ")", "{", "placeholder", "=", "placeholder", ".", "replace", "(", "/", "!!+", "/", ",", "''", ")", ";", "not", "=", "placeholder", ".", "charAt", "(", "0", ")", "===", "'!'", ";", "placeholder", "=", "not", "?", "placeholder", ".", "substr", "(", "1", ")", ":", "placeholder", ";", "if", "(", "mout", ".", "object", ".", "has", "(", "replacements", ",", "placeholder", ")", ")", "{", "placeholder", "=", "mout", ".", "object", ".", "get", "(", "replacements", ",", "placeholder", ")", ";", "return", "not", "?", "!", "placeholder", ":", "!", "!", "placeholder", ";", "}", "}", "}", "return", "interpolate", "(", "template", ",", "replacements", ",", "options", ")", ";", "}" ]
String interpolation with casting. Similar to the normal interpolation but if the template contains only a token and the value is available, the value will be returned. This way tokens that have values other than strings will be returned instead. @param {String} template The template @param {Object} replacements The replacements @param {Object} [options] The options @return {Mixed} The interpolated string or the real token value
[ "String", "interpolation", "with", "casting", ".", "Similar", "to", "the", "normal", "interpolation", "but", "if", "the", "template", "contains", "only", "a", "token", "and", "the", "value", "is", "available", "the", "value", "will", "be", "returned", ".", "This", "way", "tokens", "that", "have", "values", "other", "than", "strings", "will", "be", "returned", "instead", "." ]
3e86a76374a288e4f125b3e4994c9738f79c7028
https://github.com/IndigoUnited/automaton/blob/3e86a76374a288e4f125b3e4994c9738f79c7028/lib/string/castInterpolate.js#L25-L52
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/basicsSearch/reduceMultiplicationByZero.js
reduceMultiplicationByZero
function reduceMultiplicationByZero(node) { if (node.op !== '*') { return Node.Status.noChange(node); } const zeroIndex = node.args.findIndex(arg => { if (Node.Type.isConstant(arg) && arg.value === '0') { return true; } if (Node.PolynomialTerm.isPolynomialTerm(arg)) { const polyTerm = new Node.PolynomialTerm(arg); return polyTerm.getCoeffValue() === 0; } return false; }); if (zeroIndex >= 0) { // reduce to just the 0 node const newNode = Node.Creator.constant(0); return Node.Status.nodeChanged( ChangeTypes.MULTIPLY_BY_ZERO, node, newNode); } else { return Node.Status.noChange(node); } }
javascript
function reduceMultiplicationByZero(node) { if (node.op !== '*') { return Node.Status.noChange(node); } const zeroIndex = node.args.findIndex(arg => { if (Node.Type.isConstant(arg) && arg.value === '0') { return true; } if (Node.PolynomialTerm.isPolynomialTerm(arg)) { const polyTerm = new Node.PolynomialTerm(arg); return polyTerm.getCoeffValue() === 0; } return false; }); if (zeroIndex >= 0) { // reduce to just the 0 node const newNode = Node.Creator.constant(0); return Node.Status.nodeChanged( ChangeTypes.MULTIPLY_BY_ZERO, node, newNode); } else { return Node.Status.noChange(node); } }
[ "function", "reduceMultiplicationByZero", "(", "node", ")", "{", "if", "(", "node", ".", "op", "!==", "'*'", ")", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "const", "zeroIndex", "=", "node", ".", "args", ".", "findIndex", "(", "arg", "=>", "{", "if", "(", "Node", ".", "Type", ".", "isConstant", "(", "arg", ")", "&&", "arg", ".", "value", "===", "'0'", ")", "{", "return", "true", ";", "}", "if", "(", "Node", ".", "PolynomialTerm", ".", "isPolynomialTerm", "(", "arg", ")", ")", "{", "const", "polyTerm", "=", "new", "Node", ".", "PolynomialTerm", "(", "arg", ")", ";", "return", "polyTerm", ".", "getCoeffValue", "(", ")", "===", "0", ";", "}", "return", "false", ";", "}", ")", ";", "if", "(", "zeroIndex", ">=", "0", ")", "{", "const", "newNode", "=", "Node", ".", "Creator", ".", "constant", "(", "0", ")", ";", "return", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "MULTIPLY_BY_ZERO", ",", "node", ",", "newNode", ")", ";", "}", "else", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "}" ]
If `node` is a multiplication node with 0 as one of its operands, reduce the node to 0. Returns a Node.Status object.
[ "If", "node", "is", "a", "multiplication", "node", "with", "0", "as", "one", "of", "its", "operands", "reduce", "the", "node", "to", "0", ".", "Returns", "a", "Node", ".", "Status", "object", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/basicsSearch/reduceMultiplicationByZero.js#L8-L31
train
deanius/antares
demos/02-speak-up.js
speakIt
function speakIt({ action }) { const { toSpeak } = action.payload // Remember: unlike Promises, which share a similar construction, // the observable function is not run until the Observable recieves // a subscribe() call. return new Observable(observer => { try { const say = require("say") say.speak(toSpeak, null, null, () => { observer.complete() }) // An Observable allows for cancellation by returning a // cancellation function return () => { say.stop() } } catch (error) { log("-- speech synthesis not available --") observer.error() } }) }
javascript
function speakIt({ action }) { const { toSpeak } = action.payload // Remember: unlike Promises, which share a similar construction, // the observable function is not run until the Observable recieves // a subscribe() call. return new Observable(observer => { try { const say = require("say") say.speak(toSpeak, null, null, () => { observer.complete() }) // An Observable allows for cancellation by returning a // cancellation function return () => { say.stop() } } catch (error) { log("-- speech synthesis not available --") observer.error() } }) }
[ "function", "speakIt", "(", "{", "action", "}", ")", "{", "const", "{", "toSpeak", "}", "=", "action", ".", "payload", "return", "new", "Observable", "(", "observer", "=>", "{", "try", "{", "const", "say", "=", "require", "(", "\"say\"", ")", "say", ".", "speak", "(", "toSpeak", ",", "null", ",", "null", ",", "(", ")", "=>", "{", "observer", ".", "complete", "(", ")", "}", ")", "return", "(", ")", "=>", "{", "say", ".", "stop", "(", ")", "}", "}", "catch", "(", "error", ")", "{", "log", "(", "\"-- speech synthesis not available --\"", ")", "observer", ".", "error", "(", ")", "}", "}", ")", "}" ]
Return an observable that begins when subscribe is called, and completes when say.speak ends
[ "Return", "an", "observable", "that", "begins", "when", "subscribe", "is", "called", "and", "completes", "when", "say", ".", "speak", "ends" ]
e876afbfa3b56356c9b0a9d24a82cbf603b0a8f5
https://github.com/deanius/antares/blob/e876afbfa3b56356c9b0a9d24a82cbf603b0a8f5/demos/02-speak-up.js#L134-L157
train
metadelta/metadelta
packages/solver/lib/util/removeUnnecessaryParens.js
removeUnnecessaryParens
function removeUnnecessaryParens(node, rootNode=false) { // Parens that wrap everything are redundant. // NOTE: removeUnnecessaryParensSearch recursively removes parens that aren't // needed, while this step only applies to the very top level expression. // e.g. (2 + 3) * 4 can't become 2 + 3 * 4, but if (2 + 3) as a top level // expression can become 2 + 3 if (rootNode) { while (Node.Type.isParenthesis(node)) { node = node.content; } } return removeUnnecessaryParensSearch(node); }
javascript
function removeUnnecessaryParens(node, rootNode=false) { // Parens that wrap everything are redundant. // NOTE: removeUnnecessaryParensSearch recursively removes parens that aren't // needed, while this step only applies to the very top level expression. // e.g. (2 + 3) * 4 can't become 2 + 3 * 4, but if (2 + 3) as a top level // expression can become 2 + 3 if (rootNode) { while (Node.Type.isParenthesis(node)) { node = node.content; } } return removeUnnecessaryParensSearch(node); }
[ "function", "removeUnnecessaryParens", "(", "node", ",", "rootNode", "=", "false", ")", "{", "if", "(", "rootNode", ")", "{", "while", "(", "Node", ".", "Type", ".", "isParenthesis", "(", "node", ")", ")", "{", "node", "=", "node", ".", "content", ";", "}", "}", "return", "removeUnnecessaryParensSearch", "(", "node", ")", ";", "}" ]
Removes any parenthesis around nodes that can't be resolved further. Input must be a top level expression. Returns a node.
[ "Removes", "any", "parenthesis", "around", "nodes", "that", "can", "t", "be", "resolved", "further", ".", "Input", "must", "be", "a", "top", "level", "expression", ".", "Returns", "a", "node", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/util/removeUnnecessaryParens.js#L10-L22
train
metadelta/metadelta
packages/solver/lib/util/removeUnnecessaryParens.js
removeUnnecessaryParensInOperatorNode
function removeUnnecessaryParensInOperatorNode(node) { node.args.forEach((child, i) => { node.args[i] = removeUnnecessaryParensSearch(child); }); // Sometimes, parens are around expressions that have been simplified // all they can be. If that expression is part of an addition or subtraction // operation, we can remove the parenthesis. // e.g. (x+4) + 12 -> x+4 + 12 if (node.op === '+') { node.args.forEach((child, i) => { if (Node.Type.isParenthesis(child) && !canCollectOrCombine(child.content)) { // remove the parens by replacing the child node (in its args list) // with its content node.args[i] = child.content; } }); } // This is different from addition because when subtracting a group of terms //in parenthesis, we want to distribute the subtraction. // e.g. `(2 + x) - (1 + x)` => `2 + x - (1 + x)` not `2 + x - 1 + x` else if (node.op === '-') { if (Node.Type.isParenthesis(node.args[0]) && !canCollectOrCombine(node.args[0].content)) { node.args[0] = node.args[0].content; } } return node; }
javascript
function removeUnnecessaryParensInOperatorNode(node) { node.args.forEach((child, i) => { node.args[i] = removeUnnecessaryParensSearch(child); }); // Sometimes, parens are around expressions that have been simplified // all they can be. If that expression is part of an addition or subtraction // operation, we can remove the parenthesis. // e.g. (x+4) + 12 -> x+4 + 12 if (node.op === '+') { node.args.forEach((child, i) => { if (Node.Type.isParenthesis(child) && !canCollectOrCombine(child.content)) { // remove the parens by replacing the child node (in its args list) // with its content node.args[i] = child.content; } }); } // This is different from addition because when subtracting a group of terms //in parenthesis, we want to distribute the subtraction. // e.g. `(2 + x) - (1 + x)` => `2 + x - (1 + x)` not `2 + x - 1 + x` else if (node.op === '-') { if (Node.Type.isParenthesis(node.args[0]) && !canCollectOrCombine(node.args[0].content)) { node.args[0] = node.args[0].content; } } return node; }
[ "function", "removeUnnecessaryParensInOperatorNode", "(", "node", ")", "{", "node", ".", "args", ".", "forEach", "(", "(", "child", ",", "i", ")", "=>", "{", "node", ".", "args", "[", "i", "]", "=", "removeUnnecessaryParensSearch", "(", "child", ")", ";", "}", ")", ";", "if", "(", "node", ".", "op", "===", "'+'", ")", "{", "node", ".", "args", ".", "forEach", "(", "(", "child", ",", "i", ")", "=>", "{", "if", "(", "Node", ".", "Type", ".", "isParenthesis", "(", "child", ")", "&&", "!", "canCollectOrCombine", "(", "child", ".", "content", ")", ")", "{", "node", ".", "args", "[", "i", "]", "=", "child", ".", "content", ";", "}", "}", ")", ";", "}", "else", "if", "(", "node", ".", "op", "===", "'-'", ")", "{", "if", "(", "Node", ".", "Type", ".", "isParenthesis", "(", "node", ".", "args", "[", "0", "]", ")", "&&", "!", "canCollectOrCombine", "(", "node", ".", "args", "[", "0", "]", ".", "content", ")", ")", "{", "node", ".", "args", "[", "0", "]", "=", "node", ".", "args", "[", "0", "]", ".", "content", ";", "}", "}", "return", "node", ";", "}" ]
Removes unncessary parens for each operator in an operator node, and removes unncessary parens around operators that can't be simplified further. Returns a node.
[ "Removes", "unncessary", "parens", "for", "each", "operator", "in", "an", "operator", "node", "and", "removes", "unncessary", "parens", "around", "operators", "that", "can", "t", "be", "simplified", "further", ".", "Returns", "a", "node", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/util/removeUnnecessaryParens.js#L54-L84
train
metadelta/metadelta
packages/solver/lib/util/removeUnnecessaryParens.js
removeUnnecessaryParensInFunctionNode
function removeUnnecessaryParensInFunctionNode(node) { node.args.forEach((child, i) => { if (Node.Type.isParenthesis(child)) { child = child.content; } node.args[i] = removeUnnecessaryParensSearch(child); }); return node; }
javascript
function removeUnnecessaryParensInFunctionNode(node) { node.args.forEach((child, i) => { if (Node.Type.isParenthesis(child)) { child = child.content; } node.args[i] = removeUnnecessaryParensSearch(child); }); return node; }
[ "function", "removeUnnecessaryParensInFunctionNode", "(", "node", ")", "{", "node", ".", "args", ".", "forEach", "(", "(", "child", ",", "i", ")", "=>", "{", "if", "(", "Node", ".", "Type", ".", "isParenthesis", "(", "child", ")", ")", "{", "child", "=", "child", ".", "content", ";", "}", "node", ".", "args", "[", "i", "]", "=", "removeUnnecessaryParensSearch", "(", "child", ")", ";", "}", ")", ";", "return", "node", ";", "}" ]
Removes unncessary parens for each argument in a function node. Returns a node.
[ "Removes", "unncessary", "parens", "for", "each", "argument", "in", "a", "function", "node", ".", "Returns", "a", "node", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/util/removeUnnecessaryParens.js#L88-L97
train
metadelta/metadelta
packages/solver/lib/util/removeUnnecessaryParens.js
canCollectOrCombine
function canCollectOrCombine(node) { return LikeTermCollector.canCollectLikeTerms(node) || checks.resolvesToConstant(node) || checks.canSimplifyPolynomialTerms(node); }
javascript
function canCollectOrCombine(node) { return LikeTermCollector.canCollectLikeTerms(node) || checks.resolvesToConstant(node) || checks.canSimplifyPolynomialTerms(node); }
[ "function", "canCollectOrCombine", "(", "node", ")", "{", "return", "LikeTermCollector", ".", "canCollectLikeTerms", "(", "node", ")", "||", "checks", ".", "resolvesToConstant", "(", "node", ")", "||", "checks", ".", "canSimplifyPolynomialTerms", "(", "node", ")", ";", "}" ]
Returns true if any of the collect or combine steps can be applied to the expression tree `node`.
[ "Returns", "true", "if", "any", "of", "the", "collect", "or", "combine", "steps", "can", "be", "applied", "to", "the", "expression", "tree", "node", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/util/removeUnnecessaryParens.js#L157-L161
train
Corey600/zoodubbo
lib/invoker.js
Invoker
function Invoker(zk, opt) { if (!(this instanceof Invoker)) return new Invoker(zk, opt); var option = opt || {}; this._path = option.path; this._dubbo = option.dubbo; this._version = option.version; this._timeout = option.timeout; this._poolMax = option.poolMax; this._poolMin = option.poolMin; this._providers = null; // Array this._configurators = null; // Object this._loadBalance = new RandomLoadBalance(); this._parseProviders = this._parseProviders.bind(this); this._parseConfigurators = this._parseConfigurators.bind(this); if ('string' === typeof zk) { this._uris = [zk]; } else if (Array.isArray(zk)) { this._uris = zk; } else if (zk) { this._registerProviders = new Register(zk, '/dubbo/' + this._path + '/providers'); this._registerConfigurators = new Register(zk, '/dubbo/' + this._path + '/configurators'); this._registerProviders.on('change', this._parseProviders); this._registerConfigurators.on('change', this._parseConfigurators); } }
javascript
function Invoker(zk, opt) { if (!(this instanceof Invoker)) return new Invoker(zk, opt); var option = opt || {}; this._path = option.path; this._dubbo = option.dubbo; this._version = option.version; this._timeout = option.timeout; this._poolMax = option.poolMax; this._poolMin = option.poolMin; this._providers = null; // Array this._configurators = null; // Object this._loadBalance = new RandomLoadBalance(); this._parseProviders = this._parseProviders.bind(this); this._parseConfigurators = this._parseConfigurators.bind(this); if ('string' === typeof zk) { this._uris = [zk]; } else if (Array.isArray(zk)) { this._uris = zk; } else if (zk) { this._registerProviders = new Register(zk, '/dubbo/' + this._path + '/providers'); this._registerConfigurators = new Register(zk, '/dubbo/' + this._path + '/configurators'); this._registerProviders.on('change', this._parseProviders); this._registerConfigurators.on('change', this._parseConfigurators); } }
[ "function", "Invoker", "(", "zk", ",", "opt", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Invoker", ")", ")", "return", "new", "Invoker", "(", "zk", ",", "opt", ")", ";", "var", "option", "=", "opt", "||", "{", "}", ";", "this", ".", "_path", "=", "option", ".", "path", ";", "this", ".", "_dubbo", "=", "option", ".", "dubbo", ";", "this", ".", "_version", "=", "option", ".", "version", ";", "this", ".", "_timeout", "=", "option", ".", "timeout", ";", "this", ".", "_poolMax", "=", "option", ".", "poolMax", ";", "this", ".", "_poolMin", "=", "option", ".", "poolMin", ";", "this", ".", "_providers", "=", "null", ";", "this", ".", "_configurators", "=", "null", ";", "this", ".", "_loadBalance", "=", "new", "RandomLoadBalance", "(", ")", ";", "this", ".", "_parseProviders", "=", "this", ".", "_parseProviders", ".", "bind", "(", "this", ")", ";", "this", ".", "_parseConfigurators", "=", "this", ".", "_parseConfigurators", ".", "bind", "(", "this", ")", ";", "if", "(", "'string'", "===", "typeof", "zk", ")", "{", "this", ".", "_uris", "=", "[", "zk", "]", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "zk", ")", ")", "{", "this", ".", "_uris", "=", "zk", ";", "}", "else", "if", "(", "zk", ")", "{", "this", ".", "_registerProviders", "=", "new", "Register", "(", "zk", ",", "'/dubbo/'", "+", "this", ".", "_path", "+", "'/providers'", ")", ";", "this", ".", "_registerConfigurators", "=", "new", "Register", "(", "zk", ",", "'/dubbo/'", "+", "this", ".", "_path", "+", "'/configurators'", ")", ";", "this", ".", "_registerProviders", ".", "on", "(", "'change'", ",", "this", ".", "_parseProviders", ")", ";", "this", ".", "_registerConfigurators", ".", "on", "(", "'change'", ",", "this", ".", "_parseConfigurators", ")", ";", "}", "}" ]
Constructor of Invoker. @param {Client|String|Array} zk // The ZD instance or the uri of providers. @param {Object} opt { path: String // The path of service node. version: String, // The version of service. timeout: Number, // Timeout in milliseconds, defaults to 60 seconds. } @returns {Invoker} @constructor
[ "Constructor", "of", "Invoker", "." ]
c5700687898c82c18d1326ecaccc33fa20269b72
https://github.com/Corey600/zoodubbo/blob/c5700687898c82c18d1326ecaccc33fa20269b72/lib/invoker.js#L37-L65
train
vlucas/toystore
es5/index.js
_expandNestedPaths
function _expandNestedPaths(paths) { var expandedPaths = []; _pathsArray(paths).forEach(function (p) { if (p.indexOf('.') !== -1) { var pathsWithRoots = p.split('.').map(function (value, index, array) { return array.slice(0, index + 1).join('.'); }); expandedPaths = expandedPaths.concat(pathsWithRoots); } else { expandedPaths.push(p); } }); return expandedPaths; }
javascript
function _expandNestedPaths(paths) { var expandedPaths = []; _pathsArray(paths).forEach(function (p) { if (p.indexOf('.') !== -1) { var pathsWithRoots = p.split('.').map(function (value, index, array) { return array.slice(0, index + 1).join('.'); }); expandedPaths = expandedPaths.concat(pathsWithRoots); } else { expandedPaths.push(p); } }); return expandedPaths; }
[ "function", "_expandNestedPaths", "(", "paths", ")", "{", "var", "expandedPaths", "=", "[", "]", ";", "_pathsArray", "(", "paths", ")", ".", "forEach", "(", "function", "(", "p", ")", "{", "if", "(", "p", ".", "indexOf", "(", "'.'", ")", "!==", "-", "1", ")", "{", "var", "pathsWithRoots", "=", "p", ".", "split", "(", "'.'", ")", ".", "map", "(", "function", "(", "value", ",", "index", ",", "array", ")", "{", "return", "array", ".", "slice", "(", "0", ",", "index", "+", "1", ")", ".", "join", "(", "'.'", ")", ";", "}", ")", ";", "expandedPaths", "=", "expandedPaths", ".", "concat", "(", "pathsWithRoots", ")", ";", "}", "else", "{", "expandedPaths", ".", "push", "(", "p", ")", ";", "}", "}", ")", ";", "return", "expandedPaths", ";", "}" ]
Expand nested path syntax to include root paths as well. Mainly used for notifications on key updates, so updates on nested keys will notify root key, and vice-versa. Ex: 'user.email' => ['user', 'user.email'] @param {String|String[]} paths
[ "Expand", "nested", "path", "syntax", "to", "include", "root", "paths", "as", "well", ".", "Mainly", "used", "for", "notifications", "on", "key", "updates", "so", "updates", "on", "nested", "keys", "will", "notify", "root", "key", "and", "vice", "-", "versa", "." ]
0c1794e6cfc9d54b79dd843696a3f00360733034
https://github.com/vlucas/toystore/blob/0c1794e6cfc9d54b79dd843696a3f00360733034/es5/index.js#L374-L390
train
codedealer/livolo
index.js
function(remoteID, keycode) { if (!config.opened && config.pinNumber !== null) this.open(config.pinNumber); if (!config.opened) throw new Error('Trying to write with no pins opened'); debugMsg("sendButton: remoteID: " + remoteID + " keycode: " + keycode); // how many times to transmit a command for (pulse= 0; pulse <= config.repeats; pulse++) { sendPulse(1); // Start config.high = true; // first pulse is always high // transmit remoteID for (i = 15; i >= 0; i--) { var txPulse = remoteID & (1 << i); // read bits from remote ID if (txPulse > 0) { selectPulse(1); } else { selectPulse(0); } } // transmit keycode for (i = 6; i >= 0; i--) { var txPulse = keycode & (1 << i); // read bits from keycode if (txPulse > 0) { selectPulse(1); } else { selectPulse(0); } } } rpio.write(config.pinNumber, rpio.LOW); }
javascript
function(remoteID, keycode) { if (!config.opened && config.pinNumber !== null) this.open(config.pinNumber); if (!config.opened) throw new Error('Trying to write with no pins opened'); debugMsg("sendButton: remoteID: " + remoteID + " keycode: " + keycode); // how many times to transmit a command for (pulse= 0; pulse <= config.repeats; pulse++) { sendPulse(1); // Start config.high = true; // first pulse is always high // transmit remoteID for (i = 15; i >= 0; i--) { var txPulse = remoteID & (1 << i); // read bits from remote ID if (txPulse > 0) { selectPulse(1); } else { selectPulse(0); } } // transmit keycode for (i = 6; i >= 0; i--) { var txPulse = keycode & (1 << i); // read bits from keycode if (txPulse > 0) { selectPulse(1); } else { selectPulse(0); } } } rpio.write(config.pinNumber, rpio.LOW); }
[ "function", "(", "remoteID", ",", "keycode", ")", "{", "if", "(", "!", "config", ".", "opened", "&&", "config", ".", "pinNumber", "!==", "null", ")", "this", ".", "open", "(", "config", ".", "pinNumber", ")", ";", "if", "(", "!", "config", ".", "opened", ")", "throw", "new", "Error", "(", "'Trying to write with no pins opened'", ")", ";", "debugMsg", "(", "\"sendButton: remoteID: \"", "+", "remoteID", "+", "\" keycode: \"", "+", "keycode", ")", ";", "for", "(", "pulse", "=", "0", ";", "pulse", "<=", "config", ".", "repeats", ";", "pulse", "++", ")", "{", "sendPulse", "(", "1", ")", ";", "config", ".", "high", "=", "true", ";", "for", "(", "i", "=", "15", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "txPulse", "=", "remoteID", "&", "(", "1", "<<", "i", ")", ";", "if", "(", "txPulse", ">", "0", ")", "{", "selectPulse", "(", "1", ")", ";", "}", "else", "{", "selectPulse", "(", "0", ")", ";", "}", "}", "for", "(", "i", "=", "6", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "txPulse", "=", "keycode", "&", "(", "1", "<<", "i", ")", ";", "if", "(", "txPulse", ">", "0", ")", "{", "selectPulse", "(", "1", ")", ";", "}", "else", "{", "selectPulse", "(", "0", ")", ";", "}", "}", "}", "rpio", ".", "write", "(", "config", ".", "pinNumber", ",", "rpio", ".", "LOW", ")", ";", "}" ]
emulate key signal
[ "emulate", "key", "signal" ]
3e00d5a2414979adc3458b8ff3d5003913635023
https://github.com/codedealer/livolo/blob/3e00d5a2414979adc3458b8ff3d5003913635023/index.js#L75-L110
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/basicsSearch/removeMultiplicationByOne.js
removeMultiplicationByOne
function removeMultiplicationByOne(node) { if (node.op !== '*') { return Node.Status.noChange(node); } const oneIndex = node.args.findIndex(arg => { return Node.Type.isConstant(arg) && arg.value === '1'; }); if (oneIndex >= 0) { let newNode = clone(node); // remove the 1 node newNode.args.splice(oneIndex, 1); // if there's only one operand left, there's nothing left to multiply it // to, so move it up the tree if (newNode.args.length === 1) { newNode = newNode.args[0]; } return Node.Status.nodeChanged( ChangeTypes.REMOVE_MULTIPLYING_BY_ONE, node, newNode); } return Node.Status.noChange(node); }
javascript
function removeMultiplicationByOne(node) { if (node.op !== '*') { return Node.Status.noChange(node); } const oneIndex = node.args.findIndex(arg => { return Node.Type.isConstant(arg) && arg.value === '1'; }); if (oneIndex >= 0) { let newNode = clone(node); // remove the 1 node newNode.args.splice(oneIndex, 1); // if there's only one operand left, there's nothing left to multiply it // to, so move it up the tree if (newNode.args.length === 1) { newNode = newNode.args[0]; } return Node.Status.nodeChanged( ChangeTypes.REMOVE_MULTIPLYING_BY_ONE, node, newNode); } return Node.Status.noChange(node); }
[ "function", "removeMultiplicationByOne", "(", "node", ")", "{", "if", "(", "node", ".", "op", "!==", "'*'", ")", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "const", "oneIndex", "=", "node", ".", "args", ".", "findIndex", "(", "arg", "=>", "{", "return", "Node", ".", "Type", ".", "isConstant", "(", "arg", ")", "&&", "arg", ".", "value", "===", "'1'", ";", "}", ")", ";", "if", "(", "oneIndex", ">=", "0", ")", "{", "let", "newNode", "=", "clone", "(", "node", ")", ";", "newNode", ".", "args", ".", "splice", "(", "oneIndex", ",", "1", ")", ";", "if", "(", "newNode", ".", "args", ".", "length", "===", "1", ")", "{", "newNode", "=", "newNode", ".", "args", "[", "0", "]", ";", "}", "return", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "REMOVE_MULTIPLYING_BY_ONE", ",", "node", ",", "newNode", ")", ";", "}", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}" ]
If `node` is a multiplication node with 1 as one of its operands, remove 1 from the operands list. Returns a Node.Status object.
[ "If", "node", "is", "a", "multiplication", "node", "with", "1", "as", "one", "of", "its", "operands", "remove", "1", "from", "the", "operands", "list", ".", "Returns", "a", "Node", ".", "Status", "object", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/basicsSearch/removeMultiplicationByOne.js#L9-L29
train
metadelta/metadelta
packages/solver/lib/util/flattenOperands.js
maybeFlattenPolynomialTerm
function maybeFlattenPolynomialTerm(node) { // We recurse on the left side of the tree to find operands so far const operands = getOperands(node.args[0], '*'); // If the last operand (so far) under * was a constant, then it's a // polynomial term. // e.g. 2*5*6x creates a tree where the top node is implicit multiplcation // and the left branch goes to the tree with 2*5*6, and the right operand // is the symbol x. We want to check that the last argument on the left (in // this example 6) is a constant. const lastOperand = operands.pop(); // in the above example, node.args[1] would be the symbol x const nextOperand = flattenOperands(node.args[1]); // a coefficient can be constant or a fraction of constants if (Node.Type.isConstantOrConstantFraction(lastOperand)) { // we replace the constant (which we popped) with constant*symbol operands.push( Node.Creator.operator('*', [lastOperand, nextOperand], true)); } // Now we know it isn't a polynomial term, it's just another seperate operand else { operands.push(lastOperand); operands.push(nextOperand); } return operands; }
javascript
function maybeFlattenPolynomialTerm(node) { // We recurse on the left side of the tree to find operands so far const operands = getOperands(node.args[0], '*'); // If the last operand (so far) under * was a constant, then it's a // polynomial term. // e.g. 2*5*6x creates a tree where the top node is implicit multiplcation // and the left branch goes to the tree with 2*5*6, and the right operand // is the symbol x. We want to check that the last argument on the left (in // this example 6) is a constant. const lastOperand = operands.pop(); // in the above example, node.args[1] would be the symbol x const nextOperand = flattenOperands(node.args[1]); // a coefficient can be constant or a fraction of constants if (Node.Type.isConstantOrConstantFraction(lastOperand)) { // we replace the constant (which we popped) with constant*symbol operands.push( Node.Creator.operator('*', [lastOperand, nextOperand], true)); } // Now we know it isn't a polynomial term, it's just another seperate operand else { operands.push(lastOperand); operands.push(nextOperand); } return operands; }
[ "function", "maybeFlattenPolynomialTerm", "(", "node", ")", "{", "const", "operands", "=", "getOperands", "(", "node", ".", "args", "[", "0", "]", ",", "'*'", ")", ";", "const", "lastOperand", "=", "operands", ".", "pop", "(", ")", ";", "const", "nextOperand", "=", "flattenOperands", "(", "node", ".", "args", "[", "1", "]", ")", ";", "if", "(", "Node", ".", "Type", ".", "isConstantOrConstantFraction", "(", "lastOperand", ")", ")", "{", "operands", ".", "push", "(", "Node", ".", "Creator", ".", "operator", "(", "'*'", ",", "[", "lastOperand", ",", "nextOperand", "]", ",", "true", ")", ")", ";", "}", "else", "{", "operands", ".", "push", "(", "lastOperand", ")", ";", "operands", ".", "push", "(", "nextOperand", ")", ";", "}", "return", "operands", ";", "}" ]
Takes a node that might represent a multiplication with a polynomial term and flattens it appropriately so the coefficient and symbol are grouped together. Returns a new list of operands from this node that should be multiplied together.
[ "Takes", "a", "node", "that", "might", "represent", "a", "multiplication", "with", "a", "polynomial", "term", "and", "flattens", "it", "appropriately", "so", "the", "coefficient", "and", "symbol", "are", "grouped", "together", ".", "Returns", "a", "new", "list", "of", "operands", "from", "this", "node", "that", "should", "be", "multiplied", "together", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/util/flattenOperands.js#L250-L277
train
metadelta/metadelta
packages/solver/lib/util/flattenOperands.js
flattenDivision
function flattenDivision(node) { // We recurse on the left side of the tree to find operands so far // Flattening division is always considered part of a bigger picture // of multiplication, so we get operands with '*' let operands = getOperands(node.args[0], '*'); if (operands.length === 1) { node.args[0] = operands.pop(); node.args[1] = flattenOperands(node.args[1]); operands = [node]; } else { // This is the last operand, the term we'll want to add our division to const numerator = operands.pop(); // This is the denominator of the current division node we're recursing on const denominator = flattenOperands(node.args[1]); // Note that this means 2 * 3 * 4 / 5 / 6 * 7 will flatten but keep the 4/5/6 // as an operand - in simplifyDivision.js this is changed to 4/(5*6) const divisionNode = Node.Creator.operator('/', [numerator, denominator]); operands.push(divisionNode); } return operands; }
javascript
function flattenDivision(node) { // We recurse on the left side of the tree to find operands so far // Flattening division is always considered part of a bigger picture // of multiplication, so we get operands with '*' let operands = getOperands(node.args[0], '*'); if (operands.length === 1) { node.args[0] = operands.pop(); node.args[1] = flattenOperands(node.args[1]); operands = [node]; } else { // This is the last operand, the term we'll want to add our division to const numerator = operands.pop(); // This is the denominator of the current division node we're recursing on const denominator = flattenOperands(node.args[1]); // Note that this means 2 * 3 * 4 / 5 / 6 * 7 will flatten but keep the 4/5/6 // as an operand - in simplifyDivision.js this is changed to 4/(5*6) const divisionNode = Node.Creator.operator('/', [numerator, denominator]); operands.push(divisionNode); } return operands; }
[ "function", "flattenDivision", "(", "node", ")", "{", "let", "operands", "=", "getOperands", "(", "node", ".", "args", "[", "0", "]", ",", "'*'", ")", ";", "if", "(", "operands", ".", "length", "===", "1", ")", "{", "node", ".", "args", "[", "0", "]", "=", "operands", ".", "pop", "(", ")", ";", "node", ".", "args", "[", "1", "]", "=", "flattenOperands", "(", "node", ".", "args", "[", "1", "]", ")", ";", "operands", "=", "[", "node", "]", ";", "}", "else", "{", "const", "numerator", "=", "operands", ".", "pop", "(", ")", ";", "const", "denominator", "=", "flattenOperands", "(", "node", ".", "args", "[", "1", "]", ")", ";", "const", "divisionNode", "=", "Node", ".", "Creator", ".", "operator", "(", "'/'", ",", "[", "numerator", ",", "denominator", "]", ")", ";", "operands", ".", "push", "(", "divisionNode", ")", ";", "}", "return", "operands", ";", "}" ]
Takes a division node and returns a list of operands If there is multiplication in the numerator, the operands returned are to be multiplied together. Otherwise, a list of length one with just the division node is returned. getOperands might change the operator accordingly.
[ "Takes", "a", "division", "node", "and", "returns", "a", "list", "of", "operands", "If", "there", "is", "multiplication", "in", "the", "numerator", "the", "operands", "returned", "are", "to", "be", "multiplied", "together", ".", "Otherwise", "a", "list", "of", "length", "one", "with", "just", "the", "division", "node", "is", "returned", ".", "getOperands", "might", "change", "the", "operator", "accordingly", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/util/flattenOperands.js#L284-L307
train
metadelta/metadelta
packages/solver/lib/simplifyExpression/basicsSearch/removeAdditionOfZero.js
removeAdditionOfZero
function removeAdditionOfZero(node) { if (node.op !== '+') { return Node.Status.noChange(node); } const zeroIndex = node.args.findIndex(arg => { return Node.Type.isConstant(arg) && arg.value === '0'; }); let newNode = clone(node); if (zeroIndex >= 0) { // remove the 0 node newNode.args.splice(zeroIndex, 1); // if there's only one operand left, there's nothing left to add it to, // so move it up the tree if (newNode.args.length === 1) { newNode = newNode.args[0]; } return Node.Status.nodeChanged( ChangeTypes.REMOVE_ADDING_ZERO, node, newNode); } return Node.Status.noChange(node); }
javascript
function removeAdditionOfZero(node) { if (node.op !== '+') { return Node.Status.noChange(node); } const zeroIndex = node.args.findIndex(arg => { return Node.Type.isConstant(arg) && arg.value === '0'; }); let newNode = clone(node); if (zeroIndex >= 0) { // remove the 0 node newNode.args.splice(zeroIndex, 1); // if there's only one operand left, there's nothing left to add it to, // so move it up the tree if (newNode.args.length === 1) { newNode = newNode.args[0]; } return Node.Status.nodeChanged( ChangeTypes.REMOVE_ADDING_ZERO, node, newNode); } return Node.Status.noChange(node); }
[ "function", "removeAdditionOfZero", "(", "node", ")", "{", "if", "(", "node", ".", "op", "!==", "'+'", ")", "{", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}", "const", "zeroIndex", "=", "node", ".", "args", ".", "findIndex", "(", "arg", "=>", "{", "return", "Node", ".", "Type", ".", "isConstant", "(", "arg", ")", "&&", "arg", ".", "value", "===", "'0'", ";", "}", ")", ";", "let", "newNode", "=", "clone", "(", "node", ")", ";", "if", "(", "zeroIndex", ">=", "0", ")", "{", "newNode", ".", "args", ".", "splice", "(", "zeroIndex", ",", "1", ")", ";", "if", "(", "newNode", ".", "args", ".", "length", "===", "1", ")", "{", "newNode", "=", "newNode", ".", "args", "[", "0", "]", ";", "}", "return", "Node", ".", "Status", ".", "nodeChanged", "(", "ChangeTypes", ".", "REMOVE_ADDING_ZERO", ",", "node", ",", "newNode", ")", ";", "}", "return", "Node", ".", "Status", ".", "noChange", "(", "node", ")", ";", "}" ]
If `node` is an addition node with 0 as one of its operands, remove 0 from the operands list. Returns a Node.Status object.
[ "If", "node", "is", "an", "addition", "node", "with", "0", "as", "one", "of", "its", "operands", "remove", "0", "from", "the", "operands", "list", ".", "Returns", "a", "Node", ".", "Status", "object", "." ]
ce0de09f5ab9b82da62f09f7807320a6989b9070
https://github.com/metadelta/metadelta/blob/ce0de09f5ab9b82da62f09f7807320a6989b9070/packages/solver/lib/simplifyExpression/basicsSearch/removeAdditionOfZero.js#L9-L29
train