id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
35,500
haroldiedema/joii
src/Reflection.js
function() { // Get the "declaration" part of the method. var prefix = this['super']('toString').split(':')[0], body = '[Function', args = this.getParameters(), is_var = this.usesVariadicArguments(); if (args.length > 0 && typeof (args[0]) === 'object') { // right now, this is spitting out every overload's signature one after another, each on a new line. // should probably find a better way to do this for (var idx = 0; idx < args.length; idx++) { var function_parameters_meta = args[idx]; body += ' ('; var first_time = true; for (var i = 0; i < function_parameters_meta.length; i++) { if (!first_time) { body += ', '; } first_time = false; body += function_parameters_meta[i].type; if (function_parameters_meta[i].name !== null) { body += " " + function_parameters_meta[i].name; is_var = true; } } var data = this.reflector.getProto().__joii__.metadata[this.name].overloads[idx].fn.toString(); is_var = data.match(/[\(|\.|\ ](arguments)[\)|\.|\,|\ |]/g); if (is_var) { body += ', ...'; } body += ')\n'; } } else if (args.length > 0) { body += ' (' + args.join(', '); if (is_var) { body += ', ...'; } body += ')'; } else if (args.length === 0 && is_var) { body += ' (...)'; } body += ']'; return prefix + ': ' + body; }
javascript
function() { // Get the "declaration" part of the method. var prefix = this['super']('toString').split(':')[0], body = '[Function', args = this.getParameters(), is_var = this.usesVariadicArguments(); if (args.length > 0 && typeof (args[0]) === 'object') { // right now, this is spitting out every overload's signature one after another, each on a new line. // should probably find a better way to do this for (var idx = 0; idx < args.length; idx++) { var function_parameters_meta = args[idx]; body += ' ('; var first_time = true; for (var i = 0; i < function_parameters_meta.length; i++) { if (!first_time) { body += ', '; } first_time = false; body += function_parameters_meta[i].type; if (function_parameters_meta[i].name !== null) { body += " " + function_parameters_meta[i].name; is_var = true; } } var data = this.reflector.getProto().__joii__.metadata[this.name].overloads[idx].fn.toString(); is_var = data.match(/[\(|\.|\ ](arguments)[\)|\.|\,|\ |]/g); if (is_var) { body += ', ...'; } body += ')\n'; } } else if (args.length > 0) { body += ' (' + args.join(', '); if (is_var) { body += ', ...'; } body += ')'; } else if (args.length === 0 && is_var) { body += ' (...)'; } body += ']'; return prefix + ': ' + body; }
[ "function", "(", ")", "{", "// Get the \"declaration\" part of the method.", "var", "prefix", "=", "this", "[", "'super'", "]", "(", "'toString'", ")", ".", "split", "(", "':'", ")", "[", "0", "]", ",", "body", "=", "'[Function'", ",", "args", "=", "this", ".", "getParameters", "(", ")", ",", "is_var", "=", "this", ".", "usesVariadicArguments", "(", ")", ";", "if", "(", "args", ".", "length", ">", "0", "&&", "typeof", "(", "args", "[", "0", "]", ")", "===", "'object'", ")", "{", "// right now, this is spitting out every overload's signature one after another, each on a new line.", "// should probably find a better way to do this", "for", "(", "var", "idx", "=", "0", ";", "idx", "<", "args", ".", "length", ";", "idx", "++", ")", "{", "var", "function_parameters_meta", "=", "args", "[", "idx", "]", ";", "body", "+=", "' ('", ";", "var", "first_time", "=", "true", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "function_parameters_meta", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "first_time", ")", "{", "body", "+=", "', '", ";", "}", "first_time", "=", "false", ";", "body", "+=", "function_parameters_meta", "[", "i", "]", ".", "type", ";", "if", "(", "function_parameters_meta", "[", "i", "]", ".", "name", "!==", "null", ")", "{", "body", "+=", "\" \"", "+", "function_parameters_meta", "[", "i", "]", ".", "name", ";", "is_var", "=", "true", ";", "}", "}", "var", "data", "=", "this", ".", "reflector", ".", "getProto", "(", ")", ".", "__joii__", ".", "metadata", "[", "this", ".", "name", "]", ".", "overloads", "[", "idx", "]", ".", "fn", ".", "toString", "(", ")", ";", "is_var", "=", "data", ".", "match", "(", "/", "[\\(|\\.|\\ ](arguments)[\\)|\\.|\\,|\\ |]", "/", "g", ")", ";", "if", "(", "is_var", ")", "{", "body", "+=", "', ...'", ";", "}", "body", "+=", "')\\n'", ";", "}", "}", "else", "if", "(", "args", ".", "length", ">", "0", ")", "{", "body", "+=", "' ('", "+", "args", ".", "join", "(", "', '", ")", ";", "if", "(", "is_var", ")", "{", "body", "+=", "', ...'", ";", "}", "body", "+=", "')'", ";", "}", "else", "if", "(", "args", ".", "length", "===", "0", "&&", "is_var", ")", "{", "body", "+=", "' (...)'", ";", "}", "body", "+=", "']'", ";", "return", "prefix", "+", "': '", "+", "body", ";", "}" ]
Returns a string representation of the method. @return string
[ "Returns", "a", "string", "representation", "of", "the", "method", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L526-L576
35,501
telligro/opal-nodes
packages/opal-node-pdfreader/pdfreader.js
sendError
function sendError(node, msg, err, ...attrs) { if (check.string(err)) { msg.error = { node: node.name, message: util.format(err, ...attrs), }; } else if (check.instance(err, Error)) { msg.error = err; } node.error(node.name + ': ' + msg.error.message, msg); }
javascript
function sendError(node, msg, err, ...attrs) { if (check.string(err)) { msg.error = { node: node.name, message: util.format(err, ...attrs), }; } else if (check.instance(err, Error)) { msg.error = err; } node.error(node.name + ': ' + msg.error.message, msg); }
[ "function", "sendError", "(", "node", ",", "msg", ",", "err", ",", "...", "attrs", ")", "{", "if", "(", "check", ".", "string", "(", "err", ")", ")", "{", "msg", ".", "error", "=", "{", "node", ":", "node", ".", "name", ",", "message", ":", "util", ".", "format", "(", "err", ",", "...", "attrs", ")", ",", "}", ";", "}", "else", "if", "(", "check", ".", "instance", "(", "err", ",", "Error", ")", ")", "{", "msg", ".", "error", "=", "err", ";", "}", "node", ".", "error", "(", "node", ".", "name", "+", "': '", "+", "msg", ".", "error", ".", "message", ",", "msg", ")", ";", "}" ]
sends Error back to node-red @function @param {object} node - the node object returned by createNode @param {object} msg - msg object passed as input to this node. @param {object} err - error object. @param {object} attrs - attrs to be used to construct error message.
[ "sends", "Error", "back", "to", "node", "-", "red" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-pdfreader/pdfreader.js#L35-L45
35,502
node-modules/ndir
lib/ndir.js
Walk
function Walk(root, onDir, onEnd, onError) { if (!(this instanceof Walk)) { return new Walk(root, onDir, onEnd, onError); } this.dirs = [path.resolve(root)]; if (onDir) { this.on('dir', onDir); } if (onEnd) { this.on('end', onEnd); } onError && this.on('error', onError); var self = this; // let listen `files` Event first. process.nextTick(function () { self.next(); }); }
javascript
function Walk(root, onDir, onEnd, onError) { if (!(this instanceof Walk)) { return new Walk(root, onDir, onEnd, onError); } this.dirs = [path.resolve(root)]; if (onDir) { this.on('dir', onDir); } if (onEnd) { this.on('end', onEnd); } onError && this.on('error', onError); var self = this; // let listen `files` Event first. process.nextTick(function () { self.next(); }); }
[ "function", "Walk", "(", "root", ",", "onDir", ",", "onEnd", ",", "onError", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Walk", ")", ")", "{", "return", "new", "Walk", "(", "root", ",", "onDir", ",", "onEnd", ",", "onError", ")", ";", "}", "this", ".", "dirs", "=", "[", "path", ".", "resolve", "(", "root", ")", "]", ";", "if", "(", "onDir", ")", "{", "this", ".", "on", "(", "'dir'", ",", "onDir", ")", ";", "}", "if", "(", "onEnd", ")", "{", "this", ".", "on", "(", "'end'", ",", "onEnd", ")", ";", "}", "onError", "&&", "this", ".", "on", "(", "'error'", ",", "onError", ")", ";", "var", "self", "=", "this", ";", "// let listen `files` Event first.", "process", ".", "nextTick", "(", "function", "(", ")", "{", "self", ".", "next", "(", ")", ";", "}", ")", ";", "}" ]
dir Walker Class. @constructor @param {String} root Root path. @param {Function(dirpath, files)} [onDir] The `dir` event callback. @param {Function} [onEnd] The `end` event callback. @param {Function(err)} [onError] The `error` event callback. @public
[ "dir", "Walker", "Class", "." ]
d8fe9dca7c103f4180624bfa86ed6bbeaad67847
https://github.com/node-modules/ndir/blob/d8fe9dca7c103f4180624bfa86ed6bbeaad67847/lib/ndir.js#L27-L44
35,503
node-modules/ndir
lib/ndir.js
LineReader
function LineReader(file) { if (typeof file === 'string') { this.readstream = fs.createReadStream(file); } else { this.readstream = file; } this.remainBuffers = []; var self = this; this.readstream.on('data', function (data) { self.ondata(data); }); this.readstream.on('error', function (err) { self.emit('error', err); }); this.readstream.on('end', function () { self.emit('end'); }); }
javascript
function LineReader(file) { if (typeof file === 'string') { this.readstream = fs.createReadStream(file); } else { this.readstream = file; } this.remainBuffers = []; var self = this; this.readstream.on('data', function (data) { self.ondata(data); }); this.readstream.on('error', function (err) { self.emit('error', err); }); this.readstream.on('end', function () { self.emit('end'); }); }
[ "function", "LineReader", "(", "file", ")", "{", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "this", ".", "readstream", "=", "fs", ".", "createReadStream", "(", "file", ")", ";", "}", "else", "{", "this", ".", "readstream", "=", "file", ";", "}", "this", ".", "remainBuffers", "=", "[", "]", ";", "var", "self", "=", "this", ";", "this", ".", "readstream", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "self", ".", "ondata", "(", "data", ")", ";", "}", ")", ";", "this", ".", "readstream", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "this", ".", "readstream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'end'", ")", ";", "}", ")", ";", "}" ]
Read stream data line by line. @constructor @param {String|ReadStream} file File path or data stream object.
[ "Read", "stream", "data", "line", "by", "line", "." ]
d8fe9dca7c103f4180624bfa86ed6bbeaad67847
https://github.com/node-modules/ndir/blob/d8fe9dca7c103f4180624bfa86ed6bbeaad67847/lib/ndir.js#L197-L214
35,504
wavesjs/waves-lfo
benchmarks/wasm/src/index.js
loadWebAssembly
function loadWebAssembly(filename, imports) { // Fetch the file and compile it return fetch(filename) .then(response => response.arrayBuffer()) .then(buffer => WebAssembly.compile(buffer)) .then(module => { // create the imports for the module, including the // standard dynamic library imports imports = imports || {}; imports.env = imports.env || {}; imports.env.memoryBase = imports.env.memoryBase || 0; imports.env.tableBase = imports.env.tableBase || 0; // note: just take really memory for now... if (!imports.env.memory) imports.env.memory = new WebAssembly.Memory({ initial: 256 }); if (!imports.env.table) imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' }); // create the instance const instance = new WebAssembly.Instance(module, imports); return Promise.resolve({ instance, imports }); }); }
javascript
function loadWebAssembly(filename, imports) { // Fetch the file and compile it return fetch(filename) .then(response => response.arrayBuffer()) .then(buffer => WebAssembly.compile(buffer)) .then(module => { // create the imports for the module, including the // standard dynamic library imports imports = imports || {}; imports.env = imports.env || {}; imports.env.memoryBase = imports.env.memoryBase || 0; imports.env.tableBase = imports.env.tableBase || 0; // note: just take really memory for now... if (!imports.env.memory) imports.env.memory = new WebAssembly.Memory({ initial: 256 }); if (!imports.env.table) imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' }); // create the instance const instance = new WebAssembly.Instance(module, imports); return Promise.resolve({ instance, imports }); }); }
[ "function", "loadWebAssembly", "(", "filename", ",", "imports", ")", "{", "// Fetch the file and compile it", "return", "fetch", "(", "filename", ")", ".", "then", "(", "response", "=>", "response", ".", "arrayBuffer", "(", ")", ")", ".", "then", "(", "buffer", "=>", "WebAssembly", ".", "compile", "(", "buffer", ")", ")", ".", "then", "(", "module", "=>", "{", "// create the imports for the module, including the", "// standard dynamic library imports", "imports", "=", "imports", "||", "{", "}", ";", "imports", ".", "env", "=", "imports", ".", "env", "||", "{", "}", ";", "imports", ".", "env", ".", "memoryBase", "=", "imports", ".", "env", ".", "memoryBase", "||", "0", ";", "imports", ".", "env", ".", "tableBase", "=", "imports", ".", "env", ".", "tableBase", "||", "0", ";", "// note: just take really memory for now...", "if", "(", "!", "imports", ".", "env", ".", "memory", ")", "imports", ".", "env", ".", "memory", "=", "new", "WebAssembly", ".", "Memory", "(", "{", "initial", ":", "256", "}", ")", ";", "if", "(", "!", "imports", ".", "env", ".", "table", ")", "imports", ".", "env", ".", "table", "=", "new", "WebAssembly", ".", "Table", "(", "{", "initial", ":", "0", ",", "element", ":", "'anyfunc'", "}", ")", ";", "// create the instance", "const", "instance", "=", "new", "WebAssembly", ".", "Instance", "(", "module", ",", "imports", ")", ";", "return", "Promise", ".", "resolve", "(", "{", "instance", ",", "imports", "}", ")", ";", "}", ")", ";", "}" ]
loads a WebAssembly dynamic library, returns a promise. imports is an optional imports object
[ "loads", "a", "WebAssembly", "dynamic", "library", "returns", "a", "promise", ".", "imports", "is", "an", "optional", "imports", "object" ]
4353a8ef55b7921755fe182cb09b0df566696bc8
https://github.com/wavesjs/waves-lfo/blob/4353a8ef55b7921755fe182cb09b0df566696bc8/benchmarks/wasm/src/index.js#L21-L45
35,505
sipcapture/hep-js
index.js
function(message) { if (debug) console.log('Decoding HEP3 Packet...'); try { var HEP = hepHeader.parse(message); if(HEP.payload && HEP.payload.length>0){ var data = HEP.payload; var tot = 0; var decoded = {}; var PAYLOAD; while(true){ PAYLOAD = hepParse.parse( data.slice(tot) ); var tmp = hepDecode(PAYLOAD); decoded = mixinDeep(decoded, tmp); tot += PAYLOAD.length; if(tot>=HEP.payload.length) { break; } } if(debug) console.log(decoded); return decoded; } } catch(e) { return false; } }
javascript
function(message) { if (debug) console.log('Decoding HEP3 Packet...'); try { var HEP = hepHeader.parse(message); if(HEP.payload && HEP.payload.length>0){ var data = HEP.payload; var tot = 0; var decoded = {}; var PAYLOAD; while(true){ PAYLOAD = hepParse.parse( data.slice(tot) ); var tmp = hepDecode(PAYLOAD); decoded = mixinDeep(decoded, tmp); tot += PAYLOAD.length; if(tot>=HEP.payload.length) { break; } } if(debug) console.log(decoded); return decoded; } } catch(e) { return false; } }
[ "function", "(", "message", ")", "{", "if", "(", "debug", ")", "console", ".", "log", "(", "'Decoding HEP3 Packet...'", ")", ";", "try", "{", "var", "HEP", "=", "hepHeader", ".", "parse", "(", "message", ")", ";", "if", "(", "HEP", ".", "payload", "&&", "HEP", ".", "payload", ".", "length", ">", "0", ")", "{", "var", "data", "=", "HEP", ".", "payload", ";", "var", "tot", "=", "0", ";", "var", "decoded", "=", "{", "}", ";", "var", "PAYLOAD", ";", "while", "(", "true", ")", "{", "PAYLOAD", "=", "hepParse", ".", "parse", "(", "data", ".", "slice", "(", "tot", ")", ")", ";", "var", "tmp", "=", "hepDecode", "(", "PAYLOAD", ")", ";", "decoded", "=", "mixinDeep", "(", "decoded", ",", "tmp", ")", ";", "tot", "+=", "PAYLOAD", ".", "length", ";", "if", "(", "tot", ">=", "HEP", ".", "payload", ".", "length", ")", "{", "break", ";", "}", "}", "if", "(", "debug", ")", "console", ".", "log", "(", "decoded", ")", ";", "return", "decoded", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Decode HEP3 Packet to JSON Object. @param {Buffer} hep message @return {Object}
[ "Decode", "HEP3", "Packet", "to", "JSON", "Object", "." ]
03922c439e4cce39ff2a0a87743476dfcdc2f298
https://github.com/sipcapture/hep-js/blob/03922c439e4cce39ff2a0a87743476dfcdc2f298/index.js#L39-L62
35,506
nodebox/g.js
src/libraries/img/img.js
toGradientData
function toGradientData(v1, v2, v3, v4, v5) { var startColor, endColor, type, rotation, spread, d; var data = {}; if (arguments.length === 1) { // The argument is a dictionary or undefined. d = v1 || {}; startColor = d.startColor; endColor = d.endColor; type = d.type; rotation = d.rotation; spread = d.spread; } else if (arguments.length >= 2) { // The first two arguments are a start color and an end color. startColor = v1; endColor = v2; type = 'linear'; rotation = 0; spread = 0; if (arguments.length === 3) { if (typeof v3 === 'string') { // The type can be either linear or radial. type = v3; } else if (typeof v3 === 'number') { // The type is implicitly linear and the third argument is the rotation angle. rotation = v3; } } else if (arguments.length === 4) { if (typeof v3 === 'number') { // The type is implicitly linear and the third/forth arguments are the rotation angle and gradient spread. rotation = v3; spread = v4; } else if (v3 === 'linear') { // The type is explicitly linear and the forth argument is the rotation angle. rotation = v4; } else if (v3 === 'radial') { // The type is explicitly radial and the forth argument is the gradient spread. type = v3; spread = v4; } else { throw new Error('Wrong argument provided: ' + v3); } } else if (arguments.length === 5) { // Type, rotation (unused in case of radial type gradient), and gradient spread. type = v3; rotation = v4; spread = v5; } } if (!startColor && startColor !== 0) { throw new Error('No startColor was given.'); } if (!endColor && endColor !== 0) { throw new Error('No endColor was given.'); } try { data.startColor = toColor(startColor); } catch (e1) { throw new Error('startColor is not a valid color: ' + startColor); } try { data.endColor = toColor(endColor); } catch (e2) { throw new Error('endColor is not a valid color: ' + endColor); } if (type === undefined) { type = 'linear'; } if (type !== 'linear' && type !== 'radial') { throw new Error('Unknown gradient type: ' + type); } data.type = type; if (spread === undefined) { spread = 0; } if (typeof spread !== 'number') { throw new Error('Spread value is not a number: ' + spread); } if (type === 'linear') { if (rotation === undefined) { rotation = 0; } if (typeof rotation !== 'number') { throw new Error('Rotation value is not a number: ' + rotation); } data.rotation = rotation; } data.spread = clamp(spread, 0, 0.99); return data; }
javascript
function toGradientData(v1, v2, v3, v4, v5) { var startColor, endColor, type, rotation, spread, d; var data = {}; if (arguments.length === 1) { // The argument is a dictionary or undefined. d = v1 || {}; startColor = d.startColor; endColor = d.endColor; type = d.type; rotation = d.rotation; spread = d.spread; } else if (arguments.length >= 2) { // The first two arguments are a start color and an end color. startColor = v1; endColor = v2; type = 'linear'; rotation = 0; spread = 0; if (arguments.length === 3) { if (typeof v3 === 'string') { // The type can be either linear or radial. type = v3; } else if (typeof v3 === 'number') { // The type is implicitly linear and the third argument is the rotation angle. rotation = v3; } } else if (arguments.length === 4) { if (typeof v3 === 'number') { // The type is implicitly linear and the third/forth arguments are the rotation angle and gradient spread. rotation = v3; spread = v4; } else if (v3 === 'linear') { // The type is explicitly linear and the forth argument is the rotation angle. rotation = v4; } else if (v3 === 'radial') { // The type is explicitly radial and the forth argument is the gradient spread. type = v3; spread = v4; } else { throw new Error('Wrong argument provided: ' + v3); } } else if (arguments.length === 5) { // Type, rotation (unused in case of radial type gradient), and gradient spread. type = v3; rotation = v4; spread = v5; } } if (!startColor && startColor !== 0) { throw new Error('No startColor was given.'); } if (!endColor && endColor !== 0) { throw new Error('No endColor was given.'); } try { data.startColor = toColor(startColor); } catch (e1) { throw new Error('startColor is not a valid color: ' + startColor); } try { data.endColor = toColor(endColor); } catch (e2) { throw new Error('endColor is not a valid color: ' + endColor); } if (type === undefined) { type = 'linear'; } if (type !== 'linear' && type !== 'radial') { throw new Error('Unknown gradient type: ' + type); } data.type = type; if (spread === undefined) { spread = 0; } if (typeof spread !== 'number') { throw new Error('Spread value is not a number: ' + spread); } if (type === 'linear') { if (rotation === undefined) { rotation = 0; } if (typeof rotation !== 'number') { throw new Error('Rotation value is not a number: ' + rotation); } data.rotation = rotation; } data.spread = clamp(spread, 0, 0.99); return data; }
[ "function", "toGradientData", "(", "v1", ",", "v2", ",", "v3", ",", "v4", ",", "v5", ")", "{", "var", "startColor", ",", "endColor", ",", "type", ",", "rotation", ",", "spread", ",", "d", ";", "var", "data", "=", "{", "}", ";", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "// The argument is a dictionary or undefined.", "d", "=", "v1", "||", "{", "}", ";", "startColor", "=", "d", ".", "startColor", ";", "endColor", "=", "d", ".", "endColor", ";", "type", "=", "d", ".", "type", ";", "rotation", "=", "d", ".", "rotation", ";", "spread", "=", "d", ".", "spread", ";", "}", "else", "if", "(", "arguments", ".", "length", ">=", "2", ")", "{", "// The first two arguments are a start color and an end color.", "startColor", "=", "v1", ";", "endColor", "=", "v2", ";", "type", "=", "'linear'", ";", "rotation", "=", "0", ";", "spread", "=", "0", ";", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "if", "(", "typeof", "v3", "===", "'string'", ")", "{", "// The type can be either linear or radial.", "type", "=", "v3", ";", "}", "else", "if", "(", "typeof", "v3", "===", "'number'", ")", "{", "// The type is implicitly linear and the third argument is the rotation angle.", "rotation", "=", "v3", ";", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "4", ")", "{", "if", "(", "typeof", "v3", "===", "'number'", ")", "{", "// The type is implicitly linear and the third/forth arguments are the rotation angle and gradient spread.", "rotation", "=", "v3", ";", "spread", "=", "v4", ";", "}", "else", "if", "(", "v3", "===", "'linear'", ")", "{", "// The type is explicitly linear and the forth argument is the rotation angle.", "rotation", "=", "v4", ";", "}", "else", "if", "(", "v3", "===", "'radial'", ")", "{", "// The type is explicitly radial and the forth argument is the gradient spread.", "type", "=", "v3", ";", "spread", "=", "v4", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Wrong argument provided: '", "+", "v3", ")", ";", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "5", ")", "{", "// Type, rotation (unused in case of radial type gradient), and gradient spread.", "type", "=", "v3", ";", "rotation", "=", "v4", ";", "spread", "=", "v5", ";", "}", "}", "if", "(", "!", "startColor", "&&", "startColor", "!==", "0", ")", "{", "throw", "new", "Error", "(", "'No startColor was given.'", ")", ";", "}", "if", "(", "!", "endColor", "&&", "endColor", "!==", "0", ")", "{", "throw", "new", "Error", "(", "'No endColor was given.'", ")", ";", "}", "try", "{", "data", ".", "startColor", "=", "toColor", "(", "startColor", ")", ";", "}", "catch", "(", "e1", ")", "{", "throw", "new", "Error", "(", "'startColor is not a valid color: '", "+", "startColor", ")", ";", "}", "try", "{", "data", ".", "endColor", "=", "toColor", "(", "endColor", ")", ";", "}", "catch", "(", "e2", ")", "{", "throw", "new", "Error", "(", "'endColor is not a valid color: '", "+", "endColor", ")", ";", "}", "if", "(", "type", "===", "undefined", ")", "{", "type", "=", "'linear'", ";", "}", "if", "(", "type", "!==", "'linear'", "&&", "type", "!==", "'radial'", ")", "{", "throw", "new", "Error", "(", "'Unknown gradient type: '", "+", "type", ")", ";", "}", "data", ".", "type", "=", "type", ";", "if", "(", "spread", "===", "undefined", ")", "{", "spread", "=", "0", ";", "}", "if", "(", "typeof", "spread", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "'Spread value is not a number: '", "+", "spread", ")", ";", "}", "if", "(", "type", "===", "'linear'", ")", "{", "if", "(", "rotation", "===", "undefined", ")", "{", "rotation", "=", "0", ";", "}", "if", "(", "typeof", "rotation", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "'Rotation value is not a number: '", "+", "rotation", ")", ";", "}", "data", ".", "rotation", "=", "rotation", ";", "}", "data", ".", "spread", "=", "clamp", "(", "spread", ",", "0", ",", "0.99", ")", ";", "return", "data", ";", "}" ]
Converts a number of arguments into a dictionary of gradient information that is understood by the renderer.
[ "Converts", "a", "number", "of", "arguments", "into", "a", "dictionary", "of", "gradient", "information", "that", "is", "understood", "by", "the", "renderer", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/img.js#L124-L214
35,507
nodebox/g.js
src/libraries/img/img.js
function (canvas) { this.width = canvas.width; this.height = canvas.height; var ctx = canvas.getContext('2d'); this._data = ctx.getImageData(0, 0, this.width, this.height); this.array = this._data.data; }
javascript
function (canvas) { this.width = canvas.width; this.height = canvas.height; var ctx = canvas.getContext('2d'); this._data = ctx.getImageData(0, 0, this.width, this.height); this.array = this._data.data; }
[ "function", "(", "canvas", ")", "{", "this", ".", "width", "=", "canvas", ".", "width", ";", "this", ".", "height", "=", "canvas", ".", "height", ";", "var", "ctx", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "this", ".", "_data", "=", "ctx", ".", "getImageData", "(", "0", ",", "0", ",", "this", ".", "width", ",", "this", ".", "height", ")", ";", "this", ".", "array", "=", "this", ".", "_data", ".", "data", ";", "}" ]
IMAGE PIXELS.
[ "IMAGE", "PIXELS", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/img.js#L457-L463
35,508
arifsetiawan/flatten
lib/flatten.js
walkModules
function walkModules(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.forEach(function(file) { file = dir + path.sep + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { if (file.indexOf('node_modules') > -1) { walkModules(file, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { if (!--pending) done(null, results); } } else { if (file.slice(-12) === 'package.json') { var parts = file.split(path.sep); if (parts[parts.length-3] === 'node_modules') { results.push(file); } } if (!--pending) done(null, results); } }); }); }); }
javascript
function walkModules(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.forEach(function(file) { file = dir + path.sep + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { if (file.indexOf('node_modules') > -1) { walkModules(file, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { if (!--pending) done(null, results); } } else { if (file.slice(-12) === 'package.json') { var parts = file.split(path.sep); if (parts[parts.length-3] === 'node_modules') { results.push(file); } } if (!--pending) done(null, results); } }); }); }); }
[ "function", "walkModules", "(", "dir", ",", "done", ")", "{", "var", "results", "=", "[", "]", ";", "fs", ".", "readdir", "(", "dir", ",", "function", "(", "err", ",", "list", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "var", "pending", "=", "list", ".", "length", ";", "if", "(", "!", "pending", ")", "return", "done", "(", "null", ",", "results", ")", ";", "list", ".", "forEach", "(", "function", "(", "file", ")", "{", "file", "=", "dir", "+", "path", ".", "sep", "+", "file", ";", "fs", ".", "stat", "(", "file", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "stat", "&&", "stat", ".", "isDirectory", "(", ")", ")", "{", "if", "(", "file", ".", "indexOf", "(", "'node_modules'", ")", ">", "-", "1", ")", "{", "walkModules", "(", "file", ",", "function", "(", "err", ",", "res", ")", "{", "results", "=", "results", ".", "concat", "(", "res", ")", ";", "if", "(", "!", "--", "pending", ")", "done", "(", "null", ",", "results", ")", ";", "}", ")", ";", "}", "else", "{", "if", "(", "!", "--", "pending", ")", "done", "(", "null", ",", "results", ")", ";", "}", "}", "else", "{", "if", "(", "file", ".", "slice", "(", "-", "12", ")", "===", "'package.json'", ")", "{", "var", "parts", "=", "file", ".", "split", "(", "path", ".", "sep", ")", ";", "if", "(", "parts", "[", "parts", ".", "length", "-", "3", "]", "===", "'node_modules'", ")", "{", "results", ".", "push", "(", "file", ")", ";", "}", "}", "if", "(", "!", "--", "pending", ")", "done", "(", "null", ",", "results", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Walk module folder Find folder node_modules, scan its folders, find package.json and store it, recursively @param {String} dir Directory name @param {Function} done this will contains array of package.json file
[ "Walk", "module", "folder" ]
d5dbbf3753270df5fc0890a794bf0f7b24e1d00b
https://github.com/arifsetiawan/flatten/blob/d5dbbf3753270df5fc0890a794bf0f7b24e1d00b/lib/flatten.js#L188-L227
35,509
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
readRows
function readRows(ws, rows, opts) { let contents = {}; if (typeof rows === 'string') { rows = rows.split(','); } opts = (opts === undefined) ? {} : opts; // console.log('Typeof Rows %s', typeof rows); // console.log('Typeof Rows %s', rows); // console.log('Length Rows %d', rows.length); let dRange = xlsx.utils.decode_range(ws['!ref']); for (let i = 0; i < rows.length; ++i) { // console.log('rows[%d]=%s', i, rows[i]); let dRow = xlsx.utils.decode_row(rows[i]); for (let C = dRange.s.c; C <= dRange.e.c; ++C) { let encCell = xlsx.utils.encode_cell({c: C, r: dRow}); contents[encCell] = ws[encCell] || {}; } } contents['!ref'] = ws['!ref']; if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((row) => { // console.log(typeof row); return check.object(row) ? check.nonEmptyObject(row) : check.nonEmptyArray(row); }); } return contentsJson; }
javascript
function readRows(ws, rows, opts) { let contents = {}; if (typeof rows === 'string') { rows = rows.split(','); } opts = (opts === undefined) ? {} : opts; // console.log('Typeof Rows %s', typeof rows); // console.log('Typeof Rows %s', rows); // console.log('Length Rows %d', rows.length); let dRange = xlsx.utils.decode_range(ws['!ref']); for (let i = 0; i < rows.length; ++i) { // console.log('rows[%d]=%s', i, rows[i]); let dRow = xlsx.utils.decode_row(rows[i]); for (let C = dRange.s.c; C <= dRange.e.c; ++C) { let encCell = xlsx.utils.encode_cell({c: C, r: dRow}); contents[encCell] = ws[encCell] || {}; } } contents['!ref'] = ws['!ref']; if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((row) => { // console.log(typeof row); return check.object(row) ? check.nonEmptyObject(row) : check.nonEmptyArray(row); }); } return contentsJson; }
[ "function", "readRows", "(", "ws", ",", "rows", ",", "opts", ")", "{", "let", "contents", "=", "{", "}", ";", "if", "(", "typeof", "rows", "===", "'string'", ")", "{", "rows", "=", "rows", ".", "split", "(", "','", ")", ";", "}", "opts", "=", "(", "opts", "===", "undefined", ")", "?", "{", "}", ":", "opts", ";", "// console.log('Typeof Rows %s', typeof rows);", "// console.log('Typeof Rows %s', rows);", "// console.log('Length Rows %d', rows.length);", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "ws", "[", "'!ref'", "]", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "++", "i", ")", "{", "// console.log('rows[%d]=%s', i, rows[i]);", "let", "dRow", "=", "xlsx", ".", "utils", ".", "decode_row", "(", "rows", "[", "i", "]", ")", ";", "for", "(", "let", "C", "=", "dRange", ".", "s", ".", "c", ";", "C", "<=", "dRange", ".", "e", ".", "c", ";", "++", "C", ")", "{", "let", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "C", ",", "r", ":", "dRow", "}", ")", ";", "contents", "[", "encCell", "]", "=", "ws", "[", "encCell", "]", "||", "{", "}", ";", "}", "}", "contents", "[", "'!ref'", "]", "=", "ws", "[", "'!ref'", "]", ";", "if", "(", "opts", ".", "asis", ")", "{", "return", "contents", ";", "}", "Object", ".", "assign", "(", "opts", ",", "{", "header", ":", "1", ",", "raw", ":", "true", ",", "blankrows", ":", "true", ",", "}", ")", ";", "opts", ".", "header", "=", "opts", ".", "useLabel", "?", "'A'", ":", "opts", ".", "header", ";", "let", "contentsJson", "=", "xlsx", ".", "utils", ".", "sheet_to_json", "(", "contents", ",", "opts", ")", ";", "if", "(", "opts", ".", "removeEmpty", ")", "{", "contentsJson", "=", "contentsJson", ".", "filter", "(", "(", "row", ")", "=>", "{", "// console.log(typeof row);", "return", "check", ".", "object", "(", "row", ")", "?", "check", ".", "nonEmptyObject", "(", "row", ")", ":", "check", ".", "nonEmptyArray", "(", "row", ")", ";", "}", ")", ";", "}", "return", "contentsJson", ";", "}" ]
reads a specified rows from an opened workbook @function @param {object} ws - worksheet. @param {object} rows - rows to be fetched. @param {{asis: bool, useLabel: boolean, header: string, removeEmpty:boolean}} opts - options for processing the read request @return {object} contentsJson - returns the fetched content as a JSON
[ "reads", "a", "specified", "rows", "from", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L88-L131
35,510
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
readCols
function readCols(ws, cols, opts) { // console.log('Reading cols ' + cols.length); // console.log(cols); let contents = {}; if (typeof cols === 'string') { cols = cols.split(','); } opts = (opts === undefined) ? {} : opts; let dRange = xlsx.utils.decode_range(ws['!ref']); for (let i = 0; i < cols.length; ++i) { // console.log('Reading col:' + cols[i]); let dCol = xlsx.utils.decode_col(cols[i]); for (let R = dRange.s.r; R <= dRange.e.r; ++R) { // console.log('Reading cell:' + cols[i] + ', ' + R); let encCell = xlsx.utils.encode_cell({c: dCol, r: R}); contents[encCell] = ws[encCell] || {}; // console.log('Done cell:' + cols[i] + ', ' + R + ', ' + JSON.stringify(contents[encCell])); } } contents['!ref'] = ws['!ref']; if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((col) => { // console.log(typeof col); return check.object(col) ? check.nonEmptyObject(col) : check.nonEmptyArray(col); }); } return contentsJson; }
javascript
function readCols(ws, cols, opts) { // console.log('Reading cols ' + cols.length); // console.log(cols); let contents = {}; if (typeof cols === 'string') { cols = cols.split(','); } opts = (opts === undefined) ? {} : opts; let dRange = xlsx.utils.decode_range(ws['!ref']); for (let i = 0; i < cols.length; ++i) { // console.log('Reading col:' + cols[i]); let dCol = xlsx.utils.decode_col(cols[i]); for (let R = dRange.s.r; R <= dRange.e.r; ++R) { // console.log('Reading cell:' + cols[i] + ', ' + R); let encCell = xlsx.utils.encode_cell({c: dCol, r: R}); contents[encCell] = ws[encCell] || {}; // console.log('Done cell:' + cols[i] + ', ' + R + ', ' + JSON.stringify(contents[encCell])); } } contents['!ref'] = ws['!ref']; if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((col) => { // console.log(typeof col); return check.object(col) ? check.nonEmptyObject(col) : check.nonEmptyArray(col); }); } return contentsJson; }
[ "function", "readCols", "(", "ws", ",", "cols", ",", "opts", ")", "{", "// console.log('Reading cols ' + cols.length);", "// console.log(cols);", "let", "contents", "=", "{", "}", ";", "if", "(", "typeof", "cols", "===", "'string'", ")", "{", "cols", "=", "cols", ".", "split", "(", "','", ")", ";", "}", "opts", "=", "(", "opts", "===", "undefined", ")", "?", "{", "}", ":", "opts", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "ws", "[", "'!ref'", "]", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "cols", ".", "length", ";", "++", "i", ")", "{", "// console.log('Reading col:' + cols[i]);", "let", "dCol", "=", "xlsx", ".", "utils", ".", "decode_col", "(", "cols", "[", "i", "]", ")", ";", "for", "(", "let", "R", "=", "dRange", ".", "s", ".", "r", ";", "R", "<=", "dRange", ".", "e", ".", "r", ";", "++", "R", ")", "{", "// console.log('Reading cell:' + cols[i] + ', ' + R);", "let", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "dCol", ",", "r", ":", "R", "}", ")", ";", "contents", "[", "encCell", "]", "=", "ws", "[", "encCell", "]", "||", "{", "}", ";", "// console.log('Done cell:' + cols[i] + ', ' + R + ', ' + JSON.stringify(contents[encCell]));", "}", "}", "contents", "[", "'!ref'", "]", "=", "ws", "[", "'!ref'", "]", ";", "if", "(", "opts", ".", "asis", ")", "{", "return", "contents", ";", "}", "Object", ".", "assign", "(", "opts", ",", "{", "header", ":", "1", ",", "raw", ":", "true", ",", "blankrows", ":", "true", ",", "}", ")", ";", "opts", ".", "header", "=", "opts", ".", "useLabel", "?", "'A'", ":", "opts", ".", "header", ";", "let", "contentsJson", "=", "xlsx", ".", "utils", ".", "sheet_to_json", "(", "contents", ",", "opts", ")", ";", "if", "(", "opts", ".", "removeEmpty", ")", "{", "contentsJson", "=", "contentsJson", ".", "filter", "(", "(", "col", ")", "=>", "{", "// console.log(typeof col);", "return", "check", ".", "object", "(", "col", ")", "?", "check", ".", "nonEmptyObject", "(", "col", ")", ":", "check", ".", "nonEmptyArray", "(", "col", ")", ";", "}", ")", ";", "}", "return", "contentsJson", ";", "}" ]
reads a specified cols from an opened workbook @function @param {object} ws - worksheet. @param {object} cols - cols to be fetched. @param {{asis: bool, useLabel: boolean, header: string, removeEmpty:boolean}} opts - options for processing the read request @return {object} contentsJson - returns the fetched content as a JSON
[ "reads", "a", "specified", "cols", "from", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L144-L188
35,511
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
readRegion
function readRegion(ws, range, opts) { let contents = {}; opts = (opts === undefined) ? {} : opts; // console.log('Xref:%s', ws['!ref']); let dORange = xlsx.utils.decode_range(ws['!ref']); let dRange = xlsx.utils.decode_range(range); // Support for cols only ranges like !A:A,!A:C dRange.s.r = (isNaN(dRange.s.r)) ? dORange.s.r : dRange.s.r; dRange.e.r = (isNaN(dRange.e.r)) ? dORange.e.r : dRange.e.r; // Single for row only ranges like !1:1, !1:3 dRange.s.c = (dRange.s.c === -1) ? dORange.s.c : dRange.s.c; dRange.e.c = (dRange.e.c === -1) ? dORange.e.c : dRange.e.c; for (let R = dRange.s.r; R <= dRange.e.r; ++R) { for (let C = dRange.s.c; C <= dRange.e.c; ++C) { let cellref = xlsx.utils.encode_cell({c: C, r: R}); contents[cellref] = ws[cellref] || {}; } } // console.log(JSON.stringify(dRange)); contents['!ref'] = xlsx.utils.encode_range(dRange); if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((row) => { // console.log(typeof row); return check.object(row) ? check.nonEmptyObject(row) : check.nonEmptyArray(row); }); } return contentsJson; }
javascript
function readRegion(ws, range, opts) { let contents = {}; opts = (opts === undefined) ? {} : opts; // console.log('Xref:%s', ws['!ref']); let dORange = xlsx.utils.decode_range(ws['!ref']); let dRange = xlsx.utils.decode_range(range); // Support for cols only ranges like !A:A,!A:C dRange.s.r = (isNaN(dRange.s.r)) ? dORange.s.r : dRange.s.r; dRange.e.r = (isNaN(dRange.e.r)) ? dORange.e.r : dRange.e.r; // Single for row only ranges like !1:1, !1:3 dRange.s.c = (dRange.s.c === -1) ? dORange.s.c : dRange.s.c; dRange.e.c = (dRange.e.c === -1) ? dORange.e.c : dRange.e.c; for (let R = dRange.s.r; R <= dRange.e.r; ++R) { for (let C = dRange.s.c; C <= dRange.e.c; ++C) { let cellref = xlsx.utils.encode_cell({c: C, r: R}); contents[cellref] = ws[cellref] || {}; } } // console.log(JSON.stringify(dRange)); contents['!ref'] = xlsx.utils.encode_range(dRange); if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((row) => { // console.log(typeof row); return check.object(row) ? check.nonEmptyObject(row) : check.nonEmptyArray(row); }); } return contentsJson; }
[ "function", "readRegion", "(", "ws", ",", "range", ",", "opts", ")", "{", "let", "contents", "=", "{", "}", ";", "opts", "=", "(", "opts", "===", "undefined", ")", "?", "{", "}", ":", "opts", ";", "// console.log('Xref:%s', ws['!ref']);", "let", "dORange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "ws", "[", "'!ref'", "]", ")", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "range", ")", ";", "// Support for cols only ranges like !A:A,!A:C", "dRange", ".", "s", ".", "r", "=", "(", "isNaN", "(", "dRange", ".", "s", ".", "r", ")", ")", "?", "dORange", ".", "s", ".", "r", ":", "dRange", ".", "s", ".", "r", ";", "dRange", ".", "e", ".", "r", "=", "(", "isNaN", "(", "dRange", ".", "e", ".", "r", ")", ")", "?", "dORange", ".", "e", ".", "r", ":", "dRange", ".", "e", ".", "r", ";", "// Single for row only ranges like !1:1, !1:3", "dRange", ".", "s", ".", "c", "=", "(", "dRange", ".", "s", ".", "c", "===", "-", "1", ")", "?", "dORange", ".", "s", ".", "c", ":", "dRange", ".", "s", ".", "c", ";", "dRange", ".", "e", ".", "c", "=", "(", "dRange", ".", "e", ".", "c", "===", "-", "1", ")", "?", "dORange", ".", "e", ".", "c", ":", "dRange", ".", "e", ".", "c", ";", "for", "(", "let", "R", "=", "dRange", ".", "s", ".", "r", ";", "R", "<=", "dRange", ".", "e", ".", "r", ";", "++", "R", ")", "{", "for", "(", "let", "C", "=", "dRange", ".", "s", ".", "c", ";", "C", "<=", "dRange", ".", "e", ".", "c", ";", "++", "C", ")", "{", "let", "cellref", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "C", ",", "r", ":", "R", "}", ")", ";", "contents", "[", "cellref", "]", "=", "ws", "[", "cellref", "]", "||", "{", "}", ";", "}", "}", "// console.log(JSON.stringify(dRange));", "contents", "[", "'!ref'", "]", "=", "xlsx", ".", "utils", ".", "encode_range", "(", "dRange", ")", ";", "if", "(", "opts", ".", "asis", ")", "{", "return", "contents", ";", "}", "Object", ".", "assign", "(", "opts", ",", "{", "header", ":", "1", ",", "raw", ":", "true", ",", "blankrows", ":", "true", ",", "}", ")", ";", "opts", ".", "header", "=", "opts", ".", "useLabel", "?", "'A'", ":", "opts", ".", "header", ";", "let", "contentsJson", "=", "xlsx", ".", "utils", ".", "sheet_to_json", "(", "contents", ",", "opts", ")", ";", "if", "(", "opts", ".", "removeEmpty", ")", "{", "contentsJson", "=", "contentsJson", ".", "filter", "(", "(", "row", ")", "=>", "{", "// console.log(typeof row);", "return", "check", ".", "object", "(", "row", ")", "?", "check", ".", "nonEmptyObject", "(", "row", ")", ":", "check", ".", "nonEmptyArray", "(", "row", ")", ";", "}", ")", ";", "}", "return", "contentsJson", ";", "}" ]
reads a specified region from an opened workbook @function @param {object} ws - worksheet. @param {object} range - rows to be fetched. @param {{asis: bool, useLabel: boolean, header: string, removeEmpty:boolean}} opts - options for processing the read request @return {object} contentsJson - returns the fetched content as a JSON
[ "reads", "a", "specified", "region", "from", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L201-L247
35,512
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
writeRegion
function writeRegion(ws, urange, contents) { let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let dUrange = xlsx.utils.decode_range(urange); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; for (let R = dUrange.s.r, i = 0; R <= dUrange.e.r; ++R, ++i) { let cellVal = contents[i]; if (R > newRef.e.r) { newRef.e.r = R; } for (let C = dUrange.s.c, j = 0; C <= dUrange.e.c; ++C, ++j) { encCell = xlsx.utils.encode_cell({c: C, r: R}); if (C > newRef.e.c) { newRef.e.c = C; } ws[encCell] = updateCellData(ws[encCell], cellVal[j]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
javascript
function writeRegion(ws, urange, contents) { let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let dUrange = xlsx.utils.decode_range(urange); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; for (let R = dUrange.s.r, i = 0; R <= dUrange.e.r; ++R, ++i) { let cellVal = contents[i]; if (R > newRef.e.r) { newRef.e.r = R; } for (let C = dUrange.s.c, j = 0; C <= dUrange.e.c; ++C, ++j) { encCell = xlsx.utils.encode_cell({c: C, r: R}); if (C > newRef.e.c) { newRef.e.c = C; } ws[encCell] = updateCellData(ws[encCell], cellVal[j]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
[ "function", "writeRegion", "(", "ws", ",", "urange", ",", "contents", ")", "{", "let", "range", "=", "ws", "[", "'!ref'", "]", ";", "range", "=", "check", ".", "undefined", "(", "range", ")", "?", "'A1:A1'", ":", "range", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "range", ")", ";", "let", "dUrange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "urange", ")", ";", "let", "newRef", "=", "{", "s", ":", "{", "c", ":", "0", ",", "r", ":", "0", "}", ",", "e", ":", "{", "c", ":", "dRange", ".", "e", ".", "c", ",", "r", ":", "dRange", ".", "e", ".", "r", "}", "}", ";", "let", "encCell", ";", "for", "(", "let", "R", "=", "dUrange", ".", "s", ".", "r", ",", "i", "=", "0", ";", "R", "<=", "dUrange", ".", "e", ".", "r", ";", "++", "R", ",", "++", "i", ")", "{", "let", "cellVal", "=", "contents", "[", "i", "]", ";", "if", "(", "R", ">", "newRef", ".", "e", ".", "r", ")", "{", "newRef", ".", "e", ".", "r", "=", "R", ";", "}", "for", "(", "let", "C", "=", "dUrange", ".", "s", ".", "c", ",", "j", "=", "0", ";", "C", "<=", "dUrange", ".", "e", ".", "c", ";", "++", "C", ",", "++", "j", ")", "{", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "C", ",", "r", ":", "R", "}", ")", ";", "if", "(", "C", ">", "newRef", ".", "e", ".", "c", ")", "{", "newRef", ".", "e", ".", "c", "=", "C", ";", "}", "ws", "[", "encCell", "]", "=", "updateCellData", "(", "ws", "[", "encCell", "]", ",", "cellVal", "[", "j", "]", ")", ";", "}", "}", "ws", "[", "'!ref'", "]", "=", "xlsx", ".", "utils", ".", "encode_range", "(", "newRef", ")", ";", "return", "ws", ";", "}" ]
writes a specified region to an opened workbook @function @param {object} ws - worksheet. @param {object} urange - range where contents are written @param {boolean} contents - contents that are to written to specified range @return {object} ws - returns the modified worksheet
[ "writes", "a", "specified", "region", "to", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L257-L282
35,513
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
writeCols
function writeCols(ws, cols, contents) { let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; if (typeof cols === 'string') { cols = cols.split(','); } for (let i = 0; i < cols.length; ++i) { let dCol = xlsx.utils.decode_col(cols[i]); let cellVal = contents[i]; if (dCol > newRef.e.c) { newRef.e.c = dCol; } for (let R = dRange.s.r; R < cellVal.length; ++R) { encCell = xlsx.utils.encode_cell({c: dCol, r: R}); if (R > newRef.e.r) { newRef.e.r = R; } ws[encCell] = updateCellData(ws[encCell], cellVal[R]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
javascript
function writeCols(ws, cols, contents) { let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; if (typeof cols === 'string') { cols = cols.split(','); } for (let i = 0; i < cols.length; ++i) { let dCol = xlsx.utils.decode_col(cols[i]); let cellVal = contents[i]; if (dCol > newRef.e.c) { newRef.e.c = dCol; } for (let R = dRange.s.r; R < cellVal.length; ++R) { encCell = xlsx.utils.encode_cell({c: dCol, r: R}); if (R > newRef.e.r) { newRef.e.r = R; } ws[encCell] = updateCellData(ws[encCell], cellVal[R]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
[ "function", "writeCols", "(", "ws", ",", "cols", ",", "contents", ")", "{", "let", "range", "=", "ws", "[", "'!ref'", "]", ";", "range", "=", "check", ".", "undefined", "(", "range", ")", "?", "'A1:A1'", ":", "range", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "range", ")", ";", "let", "newRef", "=", "{", "s", ":", "{", "c", ":", "0", ",", "r", ":", "0", "}", ",", "e", ":", "{", "c", ":", "dRange", ".", "e", ".", "c", ",", "r", ":", "dRange", ".", "e", ".", "r", "}", "}", ";", "let", "encCell", ";", "if", "(", "typeof", "cols", "===", "'string'", ")", "{", "cols", "=", "cols", ".", "split", "(", "','", ")", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "cols", ".", "length", ";", "++", "i", ")", "{", "let", "dCol", "=", "xlsx", ".", "utils", ".", "decode_col", "(", "cols", "[", "i", "]", ")", ";", "let", "cellVal", "=", "contents", "[", "i", "]", ";", "if", "(", "dCol", ">", "newRef", ".", "e", ".", "c", ")", "{", "newRef", ".", "e", ".", "c", "=", "dCol", ";", "}", "for", "(", "let", "R", "=", "dRange", ".", "s", ".", "r", ";", "R", "<", "cellVal", ".", "length", ";", "++", "R", ")", "{", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "dCol", ",", "r", ":", "R", "}", ")", ";", "if", "(", "R", ">", "newRef", ".", "e", ".", "r", ")", "{", "newRef", ".", "e", ".", "r", "=", "R", ";", "}", "ws", "[", "encCell", "]", "=", "updateCellData", "(", "ws", "[", "encCell", "]", ",", "cellVal", "[", "R", "]", ")", ";", "}", "}", "ws", "[", "'!ref'", "]", "=", "xlsx", ".", "utils", ".", "encode_range", "(", "newRef", ")", ";", "return", "ws", ";", "}" ]
writes specified cols to an opened workbook @function @param {object} ws - worksheet. @param {object} cols - cols where contents are written @param {boolean} contents - contents that are to written to specified cols @return {object} ws - returns the modified worksheet
[ "writes", "specified", "cols", "to", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L292-L320
35,514
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
writeRows
function writeRows(ws, rows, contents) { // console.log('Typeof Rows %s', typeof rows); // console.log('Typeof Rows %s', rows); // console.log('Length Rows %d', rows.length); let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; if (typeof rows === 'string') { rows = rows.split(','); } for (let i = 0; i < rows.length; ++i) { let dRow = xlsx.utils.decode_row(rows[i]); let cellVal = contents[i]; // console.log('contents[%d]=%s', i, cellVal); if (dRow > newRef.e.r) { newRef.e.r = dRow; } for (let C = dRange.s.c; C < cellVal.length; ++C) { encCell = xlsx.utils.encode_cell({c: C, r: dRow}); if (C > newRef.e.c) { newRef.e.c = C; } ws[encCell] = updateCellData(ws[encCell], cellVal[C]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
javascript
function writeRows(ws, rows, contents) { // console.log('Typeof Rows %s', typeof rows); // console.log('Typeof Rows %s', rows); // console.log('Length Rows %d', rows.length); let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; if (typeof rows === 'string') { rows = rows.split(','); } for (let i = 0; i < rows.length; ++i) { let dRow = xlsx.utils.decode_row(rows[i]); let cellVal = contents[i]; // console.log('contents[%d]=%s', i, cellVal); if (dRow > newRef.e.r) { newRef.e.r = dRow; } for (let C = dRange.s.c; C < cellVal.length; ++C) { encCell = xlsx.utils.encode_cell({c: C, r: dRow}); if (C > newRef.e.c) { newRef.e.c = C; } ws[encCell] = updateCellData(ws[encCell], cellVal[C]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
[ "function", "writeRows", "(", "ws", ",", "rows", ",", "contents", ")", "{", "// console.log('Typeof Rows %s', typeof rows);", "// console.log('Typeof Rows %s', rows);", "// console.log('Length Rows %d', rows.length);", "let", "range", "=", "ws", "[", "'!ref'", "]", ";", "range", "=", "check", ".", "undefined", "(", "range", ")", "?", "'A1:A1'", ":", "range", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "range", ")", ";", "let", "newRef", "=", "{", "s", ":", "{", "c", ":", "0", ",", "r", ":", "0", "}", ",", "e", ":", "{", "c", ":", "dRange", ".", "e", ".", "c", ",", "r", ":", "dRange", ".", "e", ".", "r", "}", "}", ";", "let", "encCell", ";", "if", "(", "typeof", "rows", "===", "'string'", ")", "{", "rows", "=", "rows", ".", "split", "(", "','", ")", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "++", "i", ")", "{", "let", "dRow", "=", "xlsx", ".", "utils", ".", "decode_row", "(", "rows", "[", "i", "]", ")", ";", "let", "cellVal", "=", "contents", "[", "i", "]", ";", "// console.log('contents[%d]=%s', i, cellVal);", "if", "(", "dRow", ">", "newRef", ".", "e", ".", "r", ")", "{", "newRef", ".", "e", ".", "r", "=", "dRow", ";", "}", "for", "(", "let", "C", "=", "dRange", ".", "s", ".", "c", ";", "C", "<", "cellVal", ".", "length", ";", "++", "C", ")", "{", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "C", ",", "r", ":", "dRow", "}", ")", ";", "if", "(", "C", ">", "newRef", ".", "e", ".", "c", ")", "{", "newRef", ".", "e", ".", "c", "=", "C", ";", "}", "ws", "[", "encCell", "]", "=", "updateCellData", "(", "ws", "[", "encCell", "]", ",", "cellVal", "[", "C", "]", ")", ";", "}", "}", "ws", "[", "'!ref'", "]", "=", "xlsx", ".", "utils", ".", "encode_range", "(", "newRef", ")", ";", "return", "ws", ";", "}" ]
writes specified rows to an opened workbook @function @param {object} ws - worksheet. @param {object} rows - rows where contents are written @param {boolean} contents - contents that are to written to specified rows @return {object} ws - returns the modified worksheet
[ "writes", "specified", "rows", "to", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L330-L360
35,515
angular/gulp-clang-format
index.js
format
function format(opt_clangOptions, opt_clangFormat) { var actualClangFormat = opt_clangFormat || clangFormat; var optsStr = getOptsString(opt_clangOptions); function formatFilter(file, enc, done) { function onClangFormatFinished() { file.contents = Buffer.from(formatted, 'utf-8'); done(null, file); } var formatted = ''; actualClangFormat(file, enc, optsStr, onClangFormatFinished) .on('data', function(b) { formatted += b.toString(); }) .on('error', this.emit.bind(this, 'error')); } return through2.obj(formatFilter); }
javascript
function format(opt_clangOptions, opt_clangFormat) { var actualClangFormat = opt_clangFormat || clangFormat; var optsStr = getOptsString(opt_clangOptions); function formatFilter(file, enc, done) { function onClangFormatFinished() { file.contents = Buffer.from(formatted, 'utf-8'); done(null, file); } var formatted = ''; actualClangFormat(file, enc, optsStr, onClangFormatFinished) .on('data', function(b) { formatted += b.toString(); }) .on('error', this.emit.bind(this, 'error')); } return through2.obj(formatFilter); }
[ "function", "format", "(", "opt_clangOptions", ",", "opt_clangFormat", ")", "{", "var", "actualClangFormat", "=", "opt_clangFormat", "||", "clangFormat", ";", "var", "optsStr", "=", "getOptsString", "(", "opt_clangOptions", ")", ";", "function", "formatFilter", "(", "file", ",", "enc", ",", "done", ")", "{", "function", "onClangFormatFinished", "(", ")", "{", "file", ".", "contents", "=", "Buffer", ".", "from", "(", "formatted", ",", "'utf-8'", ")", ";", "done", "(", "null", ",", "file", ")", ";", "}", "var", "formatted", "=", "''", ";", "actualClangFormat", "(", "file", ",", "enc", ",", "optsStr", ",", "onClangFormatFinished", ")", ".", "on", "(", "'data'", ",", "function", "(", "b", ")", "{", "formatted", "+=", "b", ".", "toString", "(", ")", ";", "}", ")", ".", "on", "(", "'error'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'error'", ")", ")", ";", "}", "return", "through2", ".", "obj", "(", "formatFilter", ")", ";", "}" ]
Formats files using clang-format. @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.
[ "Formats", "files", "using", "clang", "-", "format", "." ]
585c281cdd7788e6dee8082d6c9e5f53830baa4a
https://github.com/angular/gulp-clang-format/blob/585c281cdd7788e6dee8082d6c9e5f53830baa4a/index.js#L19-L34
35,516
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
35,517
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", ";", "// 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", ";", "}" ]
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
35,518
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
35,519
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
35,520
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
35,521
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
35,522
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", ")", "{", "// 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", ";", "}", "}" ]
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
35,523
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", ";", "// 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", ";", "}" ]
DTSTART is not part of RRULE
[ "DTSTART", "is", "not", "part", "of", "RRULE" ]
3c2f27df921878eec1f14509e661a13a06514de8
https://github.com/solderjs/rrecurjs/blob/3c2f27df921878eec1f14509e661a13a06514de8/rrecur.js#L142-L226
35,524
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
35,525
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
35,526
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
35,527
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
35,528
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
35,529
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'", ")", "{", "// 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", ";", "}" ]
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
35,530
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", "(", ")", "// 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", "(", ")", ")", "}" ]
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
35,531
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
35,532
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
35,533
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
35,534
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
35,535
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
35,536
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
35,537
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
35,538
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
35,539
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", "`", ";", "// doing append job", "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
35,540
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
35,541
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
35,542
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
35,543
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
35,544
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
35,545
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", "/* :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", "?", "`", "${", "startOnlyTheseServices", ".", "join", "(", "','", ")", "}", "`", ":", "''", ";", "const", "consoleMessage", "=", "`", "${", "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", "(", "`", "${", "runNameSpecific", "}", "${", "pathToComposeFile", "}", "${", "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", ";", "}" ]
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
35,546
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
35,547
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='", ",", "''", ")", ";", "// 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", ";", "}" ]
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
35,548
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
35,549
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
35,550
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
35,551
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
35,552
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", "]", "// 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", "}", "}" ]
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
35,553
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
35,554
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
35,555
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
35,556
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
35,557
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
35,558
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
35,559
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
35,560
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
35,561
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 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", "(", ")", ";", "}", "}", "}", "}" ]
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
35,562
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", ")", "{", "// 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", "}", "`", ";", "}", "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", ")", ";", "}" ]
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
35,563
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", ")", "{", "// 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", ")", ";", "}", ";", "}" ]
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
35,564
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", "===", "'^'", "&&", "// 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", ")", ";", "}" ]
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
35,565
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
35,566
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
35,567
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
35,568
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
35,569
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
35,570
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
35,571
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", ")", ";", "// 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", ")", ";", "}" ]
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
35,572
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
35,573
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
35,574
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 if they are all equal nodes", "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
35,575
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", ",", "{", "/**\n * The URL of the service to redirect to.\n *\n * @property service\n * @type String\n */", "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
35,576
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", ")", ")", ";", "// 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", ";", "}", ")", ";", "}" ]
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
35,577
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
35,578
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", ")", ";", "// 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", ";", "}" ]
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
35,579
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 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", ";", "}", "}", "}" ]
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
35,580
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 we select the last computed solution, we checked if we can compute more solutions.\r", "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
35,581
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
35,582
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 the associations is to be populated with the full records...", "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
35,583
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", ")", "{", "// 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", ";", "}" ]
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
35,584
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
35,585
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
35,586
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", ",", "{", "//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", "}", "}" ]
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
35,587
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", ")", "{", "// 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", ";", "}", "}" ]
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
35,588
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", ";", "// 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", ";", "}" ]
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
35,589
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
35,590
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
35,591
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
35,592
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
35,593
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
35,594
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
35,595
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", ")", ";", "// they're considered like terms if they have the same symbol name", "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
35,596
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", ")", "{", "// 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$", ")", ")", "}" ]
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
35,597
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", "(", ")", "{", "// 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", "(", ")", "}" ]
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
35,598
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", "]", ";", "//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 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
35,599
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'", ",", "searchTerm", ",", "' \\n'", ")", ";", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
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