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
39,700
sat-utils/sat-api-lib
libs/es.js
connect
async function connect() { let esConfig let client // use local client if (!process.env.ES_HOST) { client = new elasticsearch.Client({host: 'localhost:9200'}) } else { await new Promise((resolve, reject) => AWS.config.getCredentials((err) => { if (err) return reject(err) resolve() })) esConfig = { host: process.env.ES_HOST, connectionClass: httpAwsEs, amazonES: { region: process.env.AWS_DEFAULT_REGION || 'us-east-1', credentials: AWS.config.credentials }, // Note that this doesn't abort the query. requestTimeout: 120000 // milliseconds } client = new elasticsearch.Client(esConfig) } await new Promise((resolve, reject) => client.ping({requestTimeout: 1000}, (err) => { if (err) { console.log('unable to connect to elasticsearch') reject('unable to connect to elasticsearch') } else { resolve() } })) return client }
javascript
async function connect() { let esConfig let client // use local client if (!process.env.ES_HOST) { client = new elasticsearch.Client({host: 'localhost:9200'}) } else { await new Promise((resolve, reject) => AWS.config.getCredentials((err) => { if (err) return reject(err) resolve() })) esConfig = { host: process.env.ES_HOST, connectionClass: httpAwsEs, amazonES: { region: process.env.AWS_DEFAULT_REGION || 'us-east-1', credentials: AWS.config.credentials }, // Note that this doesn't abort the query. requestTimeout: 120000 // milliseconds } client = new elasticsearch.Client(esConfig) } await new Promise((resolve, reject) => client.ping({requestTimeout: 1000}, (err) => { if (err) { console.log('unable to connect to elasticsearch') reject('unable to connect to elasticsearch') } else { resolve() } })) return client }
[ "async", "function", "connect", "(", ")", "{", "let", "esConfig", "let", "client", "// use local client", "if", "(", "!", "process", ".", "env", ".", "ES_HOST", ")", "{", "client", "=", "new", "elasticsearch", ".", "Client", "(", "{", "host", ":", "'localhost:9200'", "}", ")", "}", "else", "{", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "AWS", ".", "config", ".", "getCredentials", "(", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", "resolve", "(", ")", "}", ")", ")", "esConfig", "=", "{", "host", ":", "process", ".", "env", ".", "ES_HOST", ",", "connectionClass", ":", "httpAwsEs", ",", "amazonES", ":", "{", "region", ":", "process", ".", "env", ".", "AWS_DEFAULT_REGION", "||", "'us-east-1'", ",", "credentials", ":", "AWS", ".", "config", ".", "credentials", "}", ",", "// Note that this doesn't abort the query.", "requestTimeout", ":", "120000", "// milliseconds", "}", "client", "=", "new", "elasticsearch", ".", "Client", "(", "esConfig", ")", "}", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "client", ".", "ping", "(", "{", "requestTimeout", ":", "1000", "}", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "'unable to connect to elasticsearch'", ")", "reject", "(", "'unable to connect to elasticsearch'", ")", "}", "else", "{", "resolve", "(", ")", "}", "}", ")", ")", "return", "client", "}" ]
Connect to an Elasticsearch cluster
[ "Connect", "to", "an", "Elasticsearch", "cluster" ]
74ef1cb09789ecc9c18512781a95eada6fdc3813
https://github.com/sat-utils/sat-api-lib/blob/74ef1cb09789ecc9c18512781a95eada6fdc3813/libs/es.js#L30-L66
39,701
alianza-dev/az-search-sorter
src/index.js
_stringsByCharOrder
function _stringsByCharOrder(stringToMatch, givenString) { const matchingIndexes = getMatchingStringIndexes(stringToMatch, givenString); if (!matchingIndexes || !matchingIndexes.length) { return _matchRankMap.noMatch; } else { return _matchRankMap.matches; } }
javascript
function _stringsByCharOrder(stringToMatch, givenString) { const matchingIndexes = getMatchingStringIndexes(stringToMatch, givenString); if (!matchingIndexes || !matchingIndexes.length) { return _matchRankMap.noMatch; } else { return _matchRankMap.matches; } }
[ "function", "_stringsByCharOrder", "(", "stringToMatch", ",", "givenString", ")", "{", "const", "matchingIndexes", "=", "getMatchingStringIndexes", "(", "stringToMatch", ",", "givenString", ")", ";", "if", "(", "!", "matchingIndexes", "||", "!", "matchingIndexes", ".", "length", ")", "{", "return", "_matchRankMap", ".", "noMatch", ";", "}", "else", "{", "return", "_matchRankMap", ".", "matches", ";", "}", "}" ]
Returns a _matchRankMap.matches or noMatch score based on whether the characters in the givenString are found in order in the stringToMatch @param {string} stringToMatch - the string to match @param {string} givenString - the string that is given @returns {number} - matches rank or noMatch rank @private
[ "Returns", "a", "_matchRankMap", ".", "matches", "or", "noMatch", "score", "based", "on", "whether", "the", "characters", "in", "the", "givenString", "are", "found", "in", "order", "in", "the", "stringToMatch" ]
c981b206272e80712f4681cfd1f2d4eceaa6f433
https://github.com/alianza-dev/az-search-sorter/blob/c981b206272e80712f4681cfd1f2d4eceaa6f433/src/index.js#L142-L149
39,702
hex7c0/startline
index.js
readlin
function readlin(options, start, end) { return readline.createInterface({ input: interfac(options, start, end), output: null, terminal: false, }); }
javascript
function readlin(options, start, end) { return readline.createInterface({ input: interfac(options, start, end), output: null, terminal: false, }); }
[ "function", "readlin", "(", "options", ",", "start", ",", "end", ")", "{", "return", "readline", ".", "createInterface", "(", "{", "input", ":", "interfac", "(", "options", ",", "start", ",", "end", ")", ",", "output", ":", "null", ",", "terminal", ":", "false", ",", "}", ")", ";", "}" ]
build readline interface @function readlin @param {Object} options - various options. Check README.md @param {Integer} start - starting bytes @param {Integer} [end] - ending bytes @return {Objetc}
[ "build", "readline", "interface" ]
805505ea36247b93a36fb82b97a2f3f3026b7a27
https://github.com/hex7c0/startline/blob/805505ea36247b93a36fb82b97a2f3f3026b7a27/index.js#L67-L74
39,703
chevex-archived/shotgun-client
client/shotgun.client.js
function (options) { var clientShell = this, context = {}, // Default settings. defaultSettings = { namespace: 'shotgun', debug: false }; // Override default settings with supplied options. var settings = clientShell.settings = extend(true, {}, defaultSettings, options); // Instruct socket.io to connect to the server. var socket = clientShell.socket = io.connect('/' + settings.namespace); // Proxy any listeners onto the socket itself. clientShell.on = function () { socket.on.apply(socket, arguments); return clientShell; }; // Proxy any emit calls onto the socket itself. clientShell.emit = function () { socket.emit.apply(socket, arguments); return clientShell; }; function getCookies() { var cookies = {}; if (document.cookie.length > 0) document.cookie.split(';').forEach(function (cookie) { var components = cookie.split('='), name = components[0].trim(), value = components[1]; if (name.indexOf(settings.namespace + '-') === 0) { name = name.replace(settings.namespace + '-', ''); cookies[name] = decodeURIComponent(value); } }); return cookies; } clientShell // Save context when it changes. .on('contextChanged', function (contextData) { context = contextData; }) // Create a function for setting cookies in the browser. .on('setCookie', function (name, value, days) { var expiration = new Date(); expiration.setDate(expiration.getDate() + days); value = encodeURIComponent(value) + ((days === null) ? "" : ";expires=" + expiration.toUTCString()); document.cookie = settings.namespace + '-' + name + "=" + value; }) .on('getCookie', function (name, callback) { // Create a cookies property on the context and fill it with all the cookies for this shell. var cookies = getCookies(); callback(cookies[name]); }) .on('getAllCookies', function (callback) { var cookies = getCookies(); callback(cookies); }); // Create an execute function that looks similar to the shotgun shell execute function for ease of use. clientShell.execute = function (cmdStr, contextOverride, options) { // If a context was passed in then override the stored context with it. if (contextOverride) context = contextOverride; socket.emit('execute', cmdStr, context, options); return clientShell; }; return clientShell; }
javascript
function (options) { var clientShell = this, context = {}, // Default settings. defaultSettings = { namespace: 'shotgun', debug: false }; // Override default settings with supplied options. var settings = clientShell.settings = extend(true, {}, defaultSettings, options); // Instruct socket.io to connect to the server. var socket = clientShell.socket = io.connect('/' + settings.namespace); // Proxy any listeners onto the socket itself. clientShell.on = function () { socket.on.apply(socket, arguments); return clientShell; }; // Proxy any emit calls onto the socket itself. clientShell.emit = function () { socket.emit.apply(socket, arguments); return clientShell; }; function getCookies() { var cookies = {}; if (document.cookie.length > 0) document.cookie.split(';').forEach(function (cookie) { var components = cookie.split('='), name = components[0].trim(), value = components[1]; if (name.indexOf(settings.namespace + '-') === 0) { name = name.replace(settings.namespace + '-', ''); cookies[name] = decodeURIComponent(value); } }); return cookies; } clientShell // Save context when it changes. .on('contextChanged', function (contextData) { context = contextData; }) // Create a function for setting cookies in the browser. .on('setCookie', function (name, value, days) { var expiration = new Date(); expiration.setDate(expiration.getDate() + days); value = encodeURIComponent(value) + ((days === null) ? "" : ";expires=" + expiration.toUTCString()); document.cookie = settings.namespace + '-' + name + "=" + value; }) .on('getCookie', function (name, callback) { // Create a cookies property on the context and fill it with all the cookies for this shell. var cookies = getCookies(); callback(cookies[name]); }) .on('getAllCookies', function (callback) { var cookies = getCookies(); callback(cookies); }); // Create an execute function that looks similar to the shotgun shell execute function for ease of use. clientShell.execute = function (cmdStr, contextOverride, options) { // If a context was passed in then override the stored context with it. if (contextOverride) context = contextOverride; socket.emit('execute', cmdStr, context, options); return clientShell; }; return clientShell; }
[ "function", "(", "options", ")", "{", "var", "clientShell", "=", "this", ",", "context", "=", "{", "}", ",", "// Default settings.", "defaultSettings", "=", "{", "namespace", ":", "'shotgun'", ",", "debug", ":", "false", "}", ";", "// Override default settings with supplied options.", "var", "settings", "=", "clientShell", ".", "settings", "=", "extend", "(", "true", ",", "{", "}", ",", "defaultSettings", ",", "options", ")", ";", "// Instruct socket.io to connect to the server.", "var", "socket", "=", "clientShell", ".", "socket", "=", "io", ".", "connect", "(", "'/'", "+", "settings", ".", "namespace", ")", ";", "// Proxy any listeners onto the socket itself.", "clientShell", ".", "on", "=", "function", "(", ")", "{", "socket", ".", "on", ".", "apply", "(", "socket", ",", "arguments", ")", ";", "return", "clientShell", ";", "}", ";", "// Proxy any emit calls onto the socket itself.", "clientShell", ".", "emit", "=", "function", "(", ")", "{", "socket", ".", "emit", ".", "apply", "(", "socket", ",", "arguments", ")", ";", "return", "clientShell", ";", "}", ";", "function", "getCookies", "(", ")", "{", "var", "cookies", "=", "{", "}", ";", "if", "(", "document", ".", "cookie", ".", "length", ">", "0", ")", "document", ".", "cookie", ".", "split", "(", "';'", ")", ".", "forEach", "(", "function", "(", "cookie", ")", "{", "var", "components", "=", "cookie", ".", "split", "(", "'='", ")", ",", "name", "=", "components", "[", "0", "]", ".", "trim", "(", ")", ",", "value", "=", "components", "[", "1", "]", ";", "if", "(", "name", ".", "indexOf", "(", "settings", ".", "namespace", "+", "'-'", ")", "===", "0", ")", "{", "name", "=", "name", ".", "replace", "(", "settings", ".", "namespace", "+", "'-'", ",", "''", ")", ";", "cookies", "[", "name", "]", "=", "decodeURIComponent", "(", "value", ")", ";", "}", "}", ")", ";", "return", "cookies", ";", "}", "clientShell", "// Save context when it changes.", ".", "on", "(", "'contextChanged'", ",", "function", "(", "contextData", ")", "{", "context", "=", "contextData", ";", "}", ")", "// Create a function for setting cookies in the browser.", ".", "on", "(", "'setCookie'", ",", "function", "(", "name", ",", "value", ",", "days", ")", "{", "var", "expiration", "=", "new", "Date", "(", ")", ";", "expiration", ".", "setDate", "(", "expiration", ".", "getDate", "(", ")", "+", "days", ")", ";", "value", "=", "encodeURIComponent", "(", "value", ")", "+", "(", "(", "days", "===", "null", ")", "?", "\"\"", ":", "\";expires=\"", "+", "expiration", ".", "toUTCString", "(", ")", ")", ";", "document", ".", "cookie", "=", "settings", ".", "namespace", "+", "'-'", "+", "name", "+", "\"=\"", "+", "value", ";", "}", ")", ".", "on", "(", "'getCookie'", ",", "function", "(", "name", ",", "callback", ")", "{", "// Create a cookies property on the context and fill it with all the cookies for this shell.", "var", "cookies", "=", "getCookies", "(", ")", ";", "callback", "(", "cookies", "[", "name", "]", ")", ";", "}", ")", ".", "on", "(", "'getAllCookies'", ",", "function", "(", "callback", ")", "{", "var", "cookies", "=", "getCookies", "(", ")", ";", "callback", "(", "cookies", ")", ";", "}", ")", ";", "// Create an execute function that looks similar to the shotgun shell execute function for ease of use.", "clientShell", ".", "execute", "=", "function", "(", "cmdStr", ",", "contextOverride", ",", "options", ")", "{", "// If a context was passed in then override the stored context with it.", "if", "(", "contextOverride", ")", "context", "=", "contextOverride", ";", "socket", ".", "emit", "(", "'execute'", ",", "cmdStr", ",", "context", ",", "options", ")", ";", "return", "clientShell", ";", "}", ";", "return", "clientShell", ";", "}" ]
Shotgun client shell.
[ "Shotgun", "client", "shell", "." ]
1b046d665fc241aaf42a60bdd64d5c19e4d07399
https://github.com/chevex-archived/shotgun-client/blob/1b046d665fc241aaf42a60bdd64d5c19e4d07399/client/shotgun.client.js#L85-L159
39,704
stackgl/gl-mat2
transpose.js
transpose
function transpose(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { var a1 = a[1] out[1] = a[2] out[2] = a1 } else { out[0] = a[0] out[1] = a[2] out[2] = a[1] out[3] = a[3] } return out }
javascript
function transpose(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { var a1 = a[1] out[1] = a[2] out[2] = a1 } else { out[0] = a[0] out[1] = a[2] out[2] = a[1] out[3] = a[3] } return out }
[ "function", "transpose", "(", "out", ",", "a", ")", "{", "// If we are transposing ourselves we can skip a few steps but have to cache some values", "if", "(", "out", "===", "a", ")", "{", "var", "a1", "=", "a", "[", "1", "]", "out", "[", "1", "]", "=", "a", "[", "2", "]", "out", "[", "2", "]", "=", "a1", "}", "else", "{", "out", "[", "0", "]", "=", "a", "[", "0", "]", "out", "[", "1", "]", "=", "a", "[", "2", "]", "out", "[", "2", "]", "=", "a", "[", "1", "]", "out", "[", "3", "]", "=", "a", "[", "3", "]", "}", "return", "out", "}" ]
Transpose the values of a mat2 @alias mat2.transpose @param {mat2} out the receiving matrix @param {mat2} a the source matrix @returns {mat2} out
[ "Transpose", "the", "values", "of", "a", "mat2" ]
d6a04d55d605150240dc8e57ca7d2821aaa23c56
https://github.com/stackgl/gl-mat2/blob/d6a04d55d605150240dc8e57ca7d2821aaa23c56/transpose.js#L11-L25
39,705
Tabcorp/require-lint
lib/index.js
_compile
function _compile(str, filename) { var parent = this; try { var requires = detective(str); } catch (ex) { ex.toString = function() { return filename + ':' + this.loc.line + '\n ' + ex.message; } throw ex; } requires.forEach(function(req) { if (modules.isRelative(req)) { Module._load(req, parent); } else { if (!modules.isCore(req)) { dependencies.push(modules.name(req)); } } }); }
javascript
function _compile(str, filename) { var parent = this; try { var requires = detective(str); } catch (ex) { ex.toString = function() { return filename + ':' + this.loc.line + '\n ' + ex.message; } throw ex; } requires.forEach(function(req) { if (modules.isRelative(req)) { Module._load(req, parent); } else { if (!modules.isCore(req)) { dependencies.push(modules.name(req)); } } }); }
[ "function", "_compile", "(", "str", ",", "filename", ")", "{", "var", "parent", "=", "this", ";", "try", "{", "var", "requires", "=", "detective", "(", "str", ")", ";", "}", "catch", "(", "ex", ")", "{", "ex", ".", "toString", "=", "function", "(", ")", "{", "return", "filename", "+", "':'", "+", "this", ".", "loc", ".", "line", "+", "'\\n '", "+", "ex", ".", "message", ";", "}", "throw", "ex", ";", "}", "requires", ".", "forEach", "(", "function", "(", "req", ")", "{", "if", "(", "modules", ".", "isRelative", "(", "req", ")", ")", "{", "Module", ".", "_load", "(", "req", ",", "parent", ")", ";", "}", "else", "{", "if", "(", "!", "modules", ".", "isCore", "(", "req", ")", ")", "{", "dependencies", ".", "push", "(", "modules", ".", "name", "(", "req", ")", ")", ";", "}", "}", "}", ")", ";", "}" ]
override of Module._compile to find all call to "require"
[ "override", "of", "Module", ".", "_compile", "to", "find", "all", "call", "to", "require" ]
5c7ef7b3f39af24cb32dd1dd066d6671f9415ef0
https://github.com/Tabcorp/require-lint/blob/5c7ef7b3f39af24cb32dd1dd066d6671f9415ef0/lib/index.js#L30-L49
39,706
Dafrok/BMapLib.Heatmap
index.js
store
function store(hmap){ var _ = { // data is a two dimensional array // a datapoint gets saved as data[point-x-value][point-y-value] // the value at [point-x-value][point-y-value] is the occurrence of the datapoint data: [], // tight coupling of the heatmap object heatmap: hmap }; // the max occurrence - the heatmaps radial gradient alpha transition is based on it this.max = 1; this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; }
javascript
function store(hmap){ var _ = { // data is a two dimensional array // a datapoint gets saved as data[point-x-value][point-y-value] // the value at [point-x-value][point-y-value] is the occurrence of the datapoint data: [], // tight coupling of the heatmap object heatmap: hmap }; // the max occurrence - the heatmaps radial gradient alpha transition is based on it this.max = 1; this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; }
[ "function", "store", "(", "hmap", ")", "{", "var", "_", "=", "{", "// data is a two dimensional array", "// a datapoint gets saved as data[point-x-value][point-y-value]", "// the value at [point-x-value][point-y-value] is the occurrence of the datapoint", "data", ":", "[", "]", ",", "// tight coupling of the heatmap object", "heatmap", ":", "hmap", "}", ";", "// the max occurrence - the heatmaps radial gradient alpha transition is based on it", "this", ".", "max", "=", "1", ";", "this", ".", "get", "=", "function", "(", "key", ")", "{", "return", "_", "[", "key", "]", ";", "}", ";", "this", ".", "set", "=", "function", "(", "key", ",", "value", ")", "{", "_", "[", "key", "]", "=", "value", ";", "}", ";", "}" ]
store object constructor a heatmap contains a store the store has to know about the heatmap in order to trigger heatmap updates when datapoints get added
[ "store", "object", "constructor", "a", "heatmap", "contains", "a", "store", "the", "store", "has", "to", "know", "about", "the", "heatmap", "in", "order", "to", "trigger", "heatmap", "updates", "when", "datapoints", "get", "added" ]
710f22b68834b26bd1202944ba6137e42968b75d
https://github.com/Dafrok/BMapLib.Heatmap/blob/710f22b68834b26bd1202944ba6137e42968b75d/index.js#L33-L52
39,707
Dafrok/BMapLib.Heatmap
index.js
function(x, y){ if(x < 0 || y < 0) return; var me = this, heatmap = me.get("heatmap"), data = me.get("data"); if(!data[x]) data[x] = []; if(!data[x][y]) data[x][y] = 0; // if count parameter is set increment by count otherwise by 1 data[x][y]+=(arguments.length<3)?1:arguments[2]; me.set("data", data); // do we have a new maximum? if(me.max < data[x][y]){ // max changed, we need to redraw all existing(lower) datapoints heatmap.get("actx").clearRect(0,0,heatmap.get("width"),heatmap.get("height")); me.setDataSet({ max: data[x][y], data: data }, true); return; } heatmap.drawAlpha(x, y, data[x][y], true); }
javascript
function(x, y){ if(x < 0 || y < 0) return; var me = this, heatmap = me.get("heatmap"), data = me.get("data"); if(!data[x]) data[x] = []; if(!data[x][y]) data[x][y] = 0; // if count parameter is set increment by count otherwise by 1 data[x][y]+=(arguments.length<3)?1:arguments[2]; me.set("data", data); // do we have a new maximum? if(me.max < data[x][y]){ // max changed, we need to redraw all existing(lower) datapoints heatmap.get("actx").clearRect(0,0,heatmap.get("width"),heatmap.get("height")); me.setDataSet({ max: data[x][y], data: data }, true); return; } heatmap.drawAlpha(x, y, data[x][y], true); }
[ "function", "(", "x", ",", "y", ")", "{", "if", "(", "x", "<", "0", "||", "y", "<", "0", ")", "return", ";", "var", "me", "=", "this", ",", "heatmap", "=", "me", ".", "get", "(", "\"heatmap\"", ")", ",", "data", "=", "me", ".", "get", "(", "\"data\"", ")", ";", "if", "(", "!", "data", "[", "x", "]", ")", "data", "[", "x", "]", "=", "[", "]", ";", "if", "(", "!", "data", "[", "x", "]", "[", "y", "]", ")", "data", "[", "x", "]", "[", "y", "]", "=", "0", ";", "// if count parameter is set increment by count otherwise by 1", "data", "[", "x", "]", "[", "y", "]", "+=", "(", "arguments", ".", "length", "<", "3", ")", "?", "1", ":", "arguments", "[", "2", "]", ";", "me", ".", "set", "(", "\"data\"", ",", "data", ")", ";", "// do we have a new maximum?", "if", "(", "me", ".", "max", "<", "data", "[", "x", "]", "[", "y", "]", ")", "{", "// max changed, we need to redraw all existing(lower) datapoints", "heatmap", ".", "get", "(", "\"actx\"", ")", ".", "clearRect", "(", "0", ",", "0", ",", "heatmap", ".", "get", "(", "\"width\"", ")", ",", "heatmap", ".", "get", "(", "\"height\"", ")", ")", ";", "me", ".", "setDataSet", "(", "{", "max", ":", "data", "[", "x", "]", "[", "y", "]", ",", "data", ":", "data", "}", ",", "true", ")", ";", "return", ";", "}", "heatmap", ".", "drawAlpha", "(", "x", ",", "y", ",", "data", "[", "x", "]", "[", "y", "]", ",", "true", ")", ";", "}" ]
function for adding datapoints to the store datapoints are usually defined by x and y but could also contain a third parameter which represents the occurrence
[ "function", "for", "adding", "datapoints", "to", "the", "store", "datapoints", "are", "usually", "defined", "by", "x", "and", "y", "but", "could", "also", "contain", "a", "third", "parameter", "which", "represents", "the", "occurrence" ]
710f22b68834b26bd1202944ba6137e42968b75d
https://github.com/Dafrok/BMapLib.Heatmap/blob/710f22b68834b26bd1202944ba6137e42968b75d/index.js#L57-L83
39,708
Dafrok/BMapLib.Heatmap
index.js
heatmap
function heatmap(config){ // private variables var _ = { radius : 40, element : {}, canvas : {}, acanvas: {}, ctx : {}, actx : {}, legend: null, visible : true, width : 0, height : 0, max : false, gradient : false, opacity: 180, premultiplyAlpha: false, bounds: { l: 1000, r: 0, t: 1000, b: 0 }, debug: false }; // heatmap store containing the datapoints and information about the maximum // accessible via instance.store this.store = new store(this); this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; // configure the heatmap when an instance gets created this.configure(config); // and initialize it this.init(); }
javascript
function heatmap(config){ // private variables var _ = { radius : 40, element : {}, canvas : {}, acanvas: {}, ctx : {}, actx : {}, legend: null, visible : true, width : 0, height : 0, max : false, gradient : false, opacity: 180, premultiplyAlpha: false, bounds: { l: 1000, r: 0, t: 1000, b: 0 }, debug: false }; // heatmap store containing the datapoints and information about the maximum // accessible via instance.store this.store = new store(this); this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; // configure the heatmap when an instance gets created this.configure(config); // and initialize it this.init(); }
[ "function", "heatmap", "(", "config", ")", "{", "// private variables", "var", "_", "=", "{", "radius", ":", "40", ",", "element", ":", "{", "}", ",", "canvas", ":", "{", "}", ",", "acanvas", ":", "{", "}", ",", "ctx", ":", "{", "}", ",", "actx", ":", "{", "}", ",", "legend", ":", "null", ",", "visible", ":", "true", ",", "width", ":", "0", ",", "height", ":", "0", ",", "max", ":", "false", ",", "gradient", ":", "false", ",", "opacity", ":", "180", ",", "premultiplyAlpha", ":", "false", ",", "bounds", ":", "{", "l", ":", "1000", ",", "r", ":", "0", ",", "t", ":", "1000", ",", "b", ":", "0", "}", ",", "debug", ":", "false", "}", ";", "// heatmap store containing the datapoints and information about the maximum", "// accessible via instance.store", "this", ".", "store", "=", "new", "store", "(", "this", ")", ";", "this", ".", "get", "=", "function", "(", "key", ")", "{", "return", "_", "[", "key", "]", ";", "}", ";", "this", ".", "set", "=", "function", "(", "key", ",", "value", ")", "{", "_", "[", "key", "]", "=", "value", ";", "}", ";", "// configure the heatmap when an instance gets created", "this", ".", "configure", "(", "config", ")", ";", "// and initialize it", "this", ".", "init", "(", ")", ";", "}" ]
heatmap object constructor
[ "heatmap", "object", "constructor" ]
710f22b68834b26bd1202944ba6137e42968b75d
https://github.com/Dafrok/BMapLib.Heatmap/blob/710f22b68834b26bd1202944ba6137e42968b75d/index.js#L309-L348
39,709
Infomaker/cropjs
example/handlers/upload.js
function(directoryName, cbUpload, cbError) { this.directory = directoryName; this.name = ''; this.localPath = ''; this.virtualPath = ''; this.onUpload = cbUpload; this.onError = cbError; }
javascript
function(directoryName, cbUpload, cbError) { this.directory = directoryName; this.name = ''; this.localPath = ''; this.virtualPath = ''; this.onUpload = cbUpload; this.onError = cbError; }
[ "function", "(", "directoryName", ",", "cbUpload", ",", "cbError", ")", "{", "this", ".", "directory", "=", "directoryName", ";", "this", ".", "name", "=", "''", ";", "this", ".", "localPath", "=", "''", ";", "this", ".", "virtualPath", "=", "''", ";", "this", ".", "onUpload", "=", "cbUpload", ";", "this", ".", "onError", "=", "cbError", ";", "}" ]
File upload handler @param cbUpload @param cbError @param directoryName
[ "File", "upload", "handler" ]
10a84e6d83d07b327cbed3714e42b5ba3bd506b5
https://github.com/Infomaker/cropjs/blob/10a84e6d83d07b327cbed3714e42b5ba3bd506b5/example/handlers/upload.js#L10-L17
39,710
unicornjs/unicornjs
lib/uAlive.js
uServicesManager
function uServicesManager(){ client.publish('uServicesChannel', 'UPDATE'); listenClient.on('message', function(channel, message) { client.get('uServices', function(err, reply) { if (reply !== null) { uServices = JSON.parse(reply); } }); }); listenClient.on("error", function (err) { console.log("Redis listen "+ err); listenClient.quit(); }); listenClient.subscribe('uServicesChannel'); }
javascript
function uServicesManager(){ client.publish('uServicesChannel', 'UPDATE'); listenClient.on('message', function(channel, message) { client.get('uServices', function(err, reply) { if (reply !== null) { uServices = JSON.parse(reply); } }); }); listenClient.on("error", function (err) { console.log("Redis listen "+ err); listenClient.quit(); }); listenClient.subscribe('uServicesChannel'); }
[ "function", "uServicesManager", "(", ")", "{", "client", ".", "publish", "(", "'uServicesChannel'", ",", "'UPDATE'", ")", ";", "listenClient", ".", "on", "(", "'message'", ",", "function", "(", "channel", ",", "message", ")", "{", "client", ".", "get", "(", "'uServices'", ",", "function", "(", "err", ",", "reply", ")", "{", "if", "(", "reply", "!==", "null", ")", "{", "uServices", "=", "JSON", ".", "parse", "(", "reply", ")", ";", "}", "}", ")", ";", "}", ")", ";", "listenClient", ".", "on", "(", "\"error\"", ",", "function", "(", "err", ")", "{", "console", ".", "log", "(", "\"Redis listen \"", "+", "err", ")", ";", "listenClient", ".", "quit", "(", ")", ";", "}", ")", ";", "listenClient", ".", "subscribe", "(", "'uServicesChannel'", ")", ";", "}" ]
Worker Logic I want this to listen always Listen for UPDATE in the uServices object
[ "Worker", "Logic", "I", "want", "this", "to", "listen", "always", "Listen", "for", "UPDATE", "in", "the", "uServices", "object" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/lib/uAlive.js#L116-L135
39,711
stezu/node-stream
lib/consumers/v2/wait.js
throughWithCallback
function throughWithCallback(onData) { return through.obj(function (chunk, enc, next) { if (onData) { onData(null, chunk); } next(null, chunk); }); }
javascript
function throughWithCallback(onData) { return through.obj(function (chunk, enc, next) { if (onData) { onData(null, chunk); } next(null, chunk); }); }
[ "function", "throughWithCallback", "(", "onData", ")", "{", "return", "through", ".", "obj", "(", "function", "(", "chunk", ",", "enc", ",", "next", ")", "{", "if", "(", "onData", ")", "{", "onData", "(", "null", ",", "chunk", ")", ";", "}", "next", "(", "null", ",", "chunk", ")", ";", "}", ")", ";", "}" ]
Create a through stream that simply calls a callback with the contents. Make sure to also pass the data along so the stream continues. @private @static @since 1.3.0 @category Utilities @param {Function} onData - Callback with an error or parsed JSON. @returns {Stream} - Transform Stream
[ "Create", "a", "through", "stream", "that", "simply", "calls", "a", "callback", "with", "the", "contents", ".", "Make", "sure", "to", "also", "pass", "the", "data", "along", "so", "the", "stream", "continues", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v2/wait.js#L18-L28
39,712
stezu/node-stream
lib/consumers/v2/wait.js
waitObj
function waitObj(callback) { var data = []; return pipeline.obj( through.obj( function transform(chunk, enc, next) { data.push(chunk); next(); }, function Flush(next) { this.push(data); next(); } ), throughWithCallback(callback) ); }
javascript
function waitObj(callback) { var data = []; return pipeline.obj( through.obj( function transform(chunk, enc, next) { data.push(chunk); next(); }, function Flush(next) { this.push(data); next(); } ), throughWithCallback(callback) ); }
[ "function", "waitObj", "(", "callback", ")", "{", "var", "data", "=", "[", "]", ";", "return", "pipeline", ".", "obj", "(", "through", ".", "obj", "(", "function", "transform", "(", "chunk", ",", "enc", ",", "next", ")", "{", "data", ".", "push", "(", "chunk", ")", ";", "next", "(", ")", ";", "}", ",", "function", "Flush", "(", "next", ")", "{", "this", ".", "push", "(", "data", ")", ";", "next", "(", ")", ";", "}", ")", ",", "throughWithCallback", "(", "callback", ")", ")", ";", "}" ]
Creates a new stream with a single value that's an array of every item in the stream. @static @method wait.obj @since 1.0.0 @category Consumers @param {Function} callback - A function to be called with the contents of the stream. This is a convenience to avoid listening to the data/end events of the stream. @returns {Stream.Transform} - Transform stream. @example // get all of the items in an object stream objStream .pipe(nodeStream.wait.obj()); // => [{ 'name': 'paul' }, { 'name': 'lisa' }, { 'name': 'mary' }]
[ "Creates", "a", "new", "stream", "with", "a", "single", "value", "that", "s", "an", "array", "of", "every", "item", "in", "the", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v2/wait.js#L52-L70
39,713
stezu/node-stream
lib/consumers/v2/wait.js
wait
function wait(callback) { return pipeline.obj( waitObj(), through.obj(function (chunk, enc, next) { next(null, Buffer.concat(chunk.map(function (item) { return new Buffer(item, enc); }))); }), throughWithCallback(callback) ); }
javascript
function wait(callback) { return pipeline.obj( waitObj(), through.obj(function (chunk, enc, next) { next(null, Buffer.concat(chunk.map(function (item) { return new Buffer(item, enc); }))); }), throughWithCallback(callback) ); }
[ "function", "wait", "(", "callback", ")", "{", "return", "pipeline", ".", "obj", "(", "waitObj", "(", ")", ",", "through", ".", "obj", "(", "function", "(", "chunk", ",", "enc", ",", "next", ")", "{", "next", "(", "null", ",", "Buffer", ".", "concat", "(", "chunk", ".", "map", "(", "function", "(", "item", ")", "{", "return", "new", "Buffer", "(", "item", ",", "enc", ")", ";", "}", ")", ")", ")", ";", "}", ")", ",", "throughWithCallback", "(", "callback", ")", ")", ";", "}" ]
Creates a new stream with a single value that's a Buffer of the entire contents of the stream. @static @since 1.0.0 @category Consumers @param {Function} callback - A function to be called with the contents of the stream. This is a convenience to avoid listening to the data/end events of the stream. @returns {Stream.Transform} - Transform stream. @example // get the entire contents of a file fs.createReadStream('example.txt') .pipe(nodeStream.wait()); // => Buffer
[ "Creates", "a", "new", "stream", "with", "a", "single", "value", "that", "s", "a", "Buffer", "of", "the", "entire", "contents", "of", "the", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v2/wait.js#L93-L104
39,714
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
shallowEqual
function shallowEqual(actual, expected) { var keys = Object.keys(expected); var _arr2 = keys; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var key = _arr2[_i2]; if (actual[key] !== expected[key]) { return false; } } return true; }
javascript
function shallowEqual(actual, expected) { var keys = Object.keys(expected); var _arr2 = keys; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var key = _arr2[_i2]; if (actual[key] !== expected[key]) { return false; } } return true; }
[ "function", "shallowEqual", "(", "actual", ",", "expected", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "expected", ")", ";", "var", "_arr2", "=", "keys", ";", "for", "(", "var", "_i2", "=", "0", ";", "_i2", "<", "_arr2", ".", "length", ";", "_i2", "++", ")", "{", "var", "key", "=", "_arr2", "[", "_i2", "]", ";", "if", "(", "actual", "[", "key", "]", "!==", "expected", "[", "key", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Test if an object is shallowly equal.
[ "Test", "if", "an", "object", "is", "shallowly", "equal", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L231-L243
39,715
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
appendToMemberExpression
function appendToMemberExpression(member, append, computed) { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; }
javascript
function appendToMemberExpression(member, append, computed) { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; }
[ "function", "appendToMemberExpression", "(", "member", ",", "append", ",", "computed", ")", "{", "member", ".", "object", "=", "t", ".", "memberExpression", "(", "member", ".", "object", ",", "member", ".", "property", ",", "member", ".", "computed", ")", ";", "member", ".", "property", "=", "append", ";", "member", ".", "computed", "=", "!", "!", "computed", ";", "return", "member", ";", "}" ]
Append a node to a member expression.
[ "Append", "a", "node", "to", "a", "member", "expression", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L249-L254
39,716
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
prependToMemberExpression
function prependToMemberExpression(member, prepend) { member.object = t.memberExpression(prepend, member.object); return member; }
javascript
function prependToMemberExpression(member, prepend) { member.object = t.memberExpression(prepend, member.object); return member; }
[ "function", "prependToMemberExpression", "(", "member", ",", "prepend", ")", "{", "member", ".", "object", "=", "t", ".", "memberExpression", "(", "prepend", ",", "member", ".", "object", ")", ";", "return", "member", ";", "}" ]
Prepend a node to a member expression.
[ "Prepend", "a", "node", "to", "a", "member", "expression", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L260-L263
39,717
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
cloneDeep
function cloneDeep(node) { var newNode = {}; for (var key in node) { if (key[0] === "_") continue; var val = node[key]; if (val) { if (val.type) { val = t.cloneDeep(val); } else if (Array.isArray(val)) { val = val.map(t.cloneDeep); } } newNode[key] = val; } return newNode; }
javascript
function cloneDeep(node) { var newNode = {}; for (var key in node) { if (key[0] === "_") continue; var val = node[key]; if (val) { if (val.type) { val = t.cloneDeep(val); } else if (Array.isArray(val)) { val = val.map(t.cloneDeep); } } newNode[key] = val; } return newNode; }
[ "function", "cloneDeep", "(", "node", ")", "{", "var", "newNode", "=", "{", "}", ";", "for", "(", "var", "key", "in", "node", ")", "{", "if", "(", "key", "[", "0", "]", "===", "\"_\"", ")", "continue", ";", "var", "val", "=", "node", "[", "key", "]", ";", "if", "(", "val", ")", "{", "if", "(", "val", ".", "type", ")", "{", "val", "=", "t", ".", "cloneDeep", "(", "val", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "val", "=", "val", ".", "map", "(", "t", ".", "cloneDeep", ")", ";", "}", "}", "newNode", "[", "key", "]", "=", "val", ";", "}", "return", "newNode", ";", "}" ]
Create a deep clone of a `node` and all of it's child nodes exluding `_private` properties.
[ "Create", "a", "deep", "clone", "of", "a", "node", "and", "all", "of", "it", "s", "child", "nodes", "exluding", "_private", "properties", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L294-L314
39,718
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
buildMatchMemberExpression
function buildMatchMemberExpression(match, allowPartial) { var parts = match.split("."); return function (member) { // not a member expression if (!t.isMemberExpression(member)) return false; var search = [member]; var i = 0; while (search.length) { var node = search.shift(); if (allowPartial && i === parts.length) { return true; } if (t.isIdentifier(node)) { // this part doesn't match if (parts[i] !== node.name) return false; } else if (t.isLiteral(node)) { // this part doesn't match if (parts[i] !== node.value) return false; } else if (t.isMemberExpression(node)) { if (node.computed && !t.isLiteral(node.property)) { // we can't deal with this return false; } else { search.push(node.object); search.push(node.property); continue; } } else { // we can't deal with this return false; } // too many parts if (++i > parts.length) { return false; } } return true; }; }
javascript
function buildMatchMemberExpression(match, allowPartial) { var parts = match.split("."); return function (member) { // not a member expression if (!t.isMemberExpression(member)) return false; var search = [member]; var i = 0; while (search.length) { var node = search.shift(); if (allowPartial && i === parts.length) { return true; } if (t.isIdentifier(node)) { // this part doesn't match if (parts[i] !== node.name) return false; } else if (t.isLiteral(node)) { // this part doesn't match if (parts[i] !== node.value) return false; } else if (t.isMemberExpression(node)) { if (node.computed && !t.isLiteral(node.property)) { // we can't deal with this return false; } else { search.push(node.object); search.push(node.property); continue; } } else { // we can't deal with this return false; } // too many parts if (++i > parts.length) { return false; } } return true; }; }
[ "function", "buildMatchMemberExpression", "(", "match", ",", "allowPartial", ")", "{", "var", "parts", "=", "match", ".", "split", "(", "\".\"", ")", ";", "return", "function", "(", "member", ")", "{", "// not a member expression", "if", "(", "!", "t", ".", "isMemberExpression", "(", "member", ")", ")", "return", "false", ";", "var", "search", "=", "[", "member", "]", ";", "var", "i", "=", "0", ";", "while", "(", "search", ".", "length", ")", "{", "var", "node", "=", "search", ".", "shift", "(", ")", ";", "if", "(", "allowPartial", "&&", "i", "===", "parts", ".", "length", ")", "{", "return", "true", ";", "}", "if", "(", "t", ".", "isIdentifier", "(", "node", ")", ")", "{", "// this part doesn't match", "if", "(", "parts", "[", "i", "]", "!==", "node", ".", "name", ")", "return", "false", ";", "}", "else", "if", "(", "t", ".", "isLiteral", "(", "node", ")", ")", "{", "// this part doesn't match", "if", "(", "parts", "[", "i", "]", "!==", "node", ".", "value", ")", "return", "false", ";", "}", "else", "if", "(", "t", ".", "isMemberExpression", "(", "node", ")", ")", "{", "if", "(", "node", ".", "computed", "&&", "!", "t", ".", "isLiteral", "(", "node", ".", "property", ")", ")", "{", "// we can't deal with this", "return", "false", ";", "}", "else", "{", "search", ".", "push", "(", "node", ".", "object", ")", ";", "search", ".", "push", "(", "node", ".", "property", ")", ";", "continue", ";", "}", "}", "else", "{", "// we can't deal with this", "return", "false", ";", "}", "// too many parts", "if", "(", "++", "i", ">", "parts", ".", "length", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", ";", "}" ]
Build a function that when called will return whether or not the input `node` `MemberExpression` matches the input `match`. For example, given the match `React.createClass` it would match the parsed nodes of `React.createClass` and `React["createClass"]`.
[ "Build", "a", "function", "that", "when", "called", "will", "return", "whether", "or", "not", "the", "input", "node", "MemberExpression", "matches", "the", "input", "match", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L324-L369
39,719
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
removeComments
function removeComments(node) { var _arr3 = COMMENT_KEYS; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var key = _arr3[_i3]; delete node[key]; } return node; }
javascript
function removeComments(node) { var _arr3 = COMMENT_KEYS; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var key = _arr3[_i3]; delete node[key]; } return node; }
[ "function", "removeComments", "(", "node", ")", "{", "var", "_arr3", "=", "COMMENT_KEYS", ";", "for", "(", "var", "_i3", "=", "0", ";", "_i3", "<", "_arr3", ".", "length", ";", "_i3", "++", ")", "{", "var", "key", "=", "_arr3", "[", "_i3", "]", ";", "delete", "node", "[", "key", "]", ";", "}", "return", "node", ";", "}" ]
Remove comment properties from a node.
[ "Remove", "comment", "properties", "from", "a", "node", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L375-L383
39,720
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
inheritsComments
function inheritsComments(child, parent) { inheritTrailingComments(child, parent); inheritLeadingComments(child, parent); inheritInnerComments(child, parent); return child; }
javascript
function inheritsComments(child, parent) { inheritTrailingComments(child, parent); inheritLeadingComments(child, parent); inheritInnerComments(child, parent); return child; }
[ "function", "inheritsComments", "(", "child", ",", "parent", ")", "{", "inheritTrailingComments", "(", "child", ",", "parent", ")", ";", "inheritLeadingComments", "(", "child", ",", "parent", ")", ";", "inheritInnerComments", "(", "child", ",", "parent", ")", ";", "return", "child", ";", "}" ]
Inherit all unique comments from `parent` node to `child` node.
[ "Inherit", "all", "unique", "comments", "from", "parent", "node", "to", "child", "node", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L389-L394
39,721
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
inherits
function inherits(child, parent) { if (!child || !parent) return child; var _arr4 = t.INHERIT_KEYS.optional; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var key = _arr4[_i4]; if (child[key] == null) { child[key] = parent[key]; } } var _arr5 = t.INHERIT_KEYS.force; for (var _i5 = 0; _i5 < _arr5.length; _i5++) { var key = _arr5[_i5]; child[key] = parent[key]; } t.inheritsComments(child, parent); return child; }
javascript
function inherits(child, parent) { if (!child || !parent) return child; var _arr4 = t.INHERIT_KEYS.optional; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var key = _arr4[_i4]; if (child[key] == null) { child[key] = parent[key]; } } var _arr5 = t.INHERIT_KEYS.force; for (var _i5 = 0; _i5 < _arr5.length; _i5++) { var key = _arr5[_i5]; child[key] = parent[key]; } t.inheritsComments(child, parent); return child; }
[ "function", "inherits", "(", "child", ",", "parent", ")", "{", "if", "(", "!", "child", "||", "!", "parent", ")", "return", "child", ";", "var", "_arr4", "=", "t", ".", "INHERIT_KEYS", ".", "optional", ";", "for", "(", "var", "_i4", "=", "0", ";", "_i4", "<", "_arr4", ".", "length", ";", "_i4", "++", ")", "{", "var", "key", "=", "_arr4", "[", "_i4", "]", ";", "if", "(", "child", "[", "key", "]", "==", "null", ")", "{", "child", "[", "key", "]", "=", "parent", "[", "key", "]", ";", "}", "}", "var", "_arr5", "=", "t", ".", "INHERIT_KEYS", ".", "force", ";", "for", "(", "var", "_i5", "=", "0", ";", "_i5", "<", "_arr5", ".", "length", ";", "_i5", "++", ")", "{", "var", "key", "=", "_arr5", "[", "_i5", "]", ";", "child", "[", "key", "]", "=", "parent", "[", "key", "]", ";", "}", "t", ".", "inheritsComments", "(", "child", ",", "parent", ")", ";", "return", "child", ";", "}" ]
Inherit all contextual properties from `parent` node to `child` node.
[ "Inherit", "all", "contextual", "properties", "from", "parent", "node", "to", "child", "node", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L418-L438
39,722
YahooArchive/mojito-cli-test
lib/utils.js
getExclusionMatcher
function getExclusionMatcher(rules, defaultIsExclude) { return function isExcluded(name, ofType) { var index, include, pattern, rule, type, matchedRule, ret = null; if (!(ofType === 'file' || ofType === 'dir')) { throw new Error( 'Internal error: file type was not provided, was [' + ofType + ']' ); } /* check if there are any rules */ if (rules.length < 1) { throw new Error('No rules specified'); } // console.log('checking ' + name + '...'); for (index in rules) { // console.log('\t against ' + excludes[regex] + ': ' + // name.search(excludes[regex])); if (rules.hasOwnProperty(index)) { rule = rules[index]; if (rule instanceof RegExp) { pattern = rule; include = false; type = 'any'; } else { pattern = rule.pattern; include = !!rule.include; type = rule.type || 'any'; } if (!(type === 'file' || type === 'dir' || type === 'any')) { throw new Error('Invalid type for match [' + type + ']'); } if (!(pattern instanceof RegExp)) { console.log(rule); throw new Error('Pattern was not a regexp for rule'); } if (name.search(pattern) !== -1 && (type === 'any' || type === ofType)) { matchedRule = rule; ret = !include; break; } } } ret = ret === null ? !!defaultIsExclude : ret; //console.log('Match [' + name + '], Exclude= [' + ret + ']'); //console.log('Used rule'); //console.log(matchedRule); return ret; }; }
javascript
function getExclusionMatcher(rules, defaultIsExclude) { return function isExcluded(name, ofType) { var index, include, pattern, rule, type, matchedRule, ret = null; if (!(ofType === 'file' || ofType === 'dir')) { throw new Error( 'Internal error: file type was not provided, was [' + ofType + ']' ); } /* check if there are any rules */ if (rules.length < 1) { throw new Error('No rules specified'); } // console.log('checking ' + name + '...'); for (index in rules) { // console.log('\t against ' + excludes[regex] + ': ' + // name.search(excludes[regex])); if (rules.hasOwnProperty(index)) { rule = rules[index]; if (rule instanceof RegExp) { pattern = rule; include = false; type = 'any'; } else { pattern = rule.pattern; include = !!rule.include; type = rule.type || 'any'; } if (!(type === 'file' || type === 'dir' || type === 'any')) { throw new Error('Invalid type for match [' + type + ']'); } if (!(pattern instanceof RegExp)) { console.log(rule); throw new Error('Pattern was not a regexp for rule'); } if (name.search(pattern) !== -1 && (type === 'any' || type === ofType)) { matchedRule = rule; ret = !include; break; } } } ret = ret === null ? !!defaultIsExclude : ret; //console.log('Match [' + name + '], Exclude= [' + ret + ']'); //console.log('Used rule'); //console.log(matchedRule); return ret; }; }
[ "function", "getExclusionMatcher", "(", "rules", ",", "defaultIsExclude", ")", "{", "return", "function", "isExcluded", "(", "name", ",", "ofType", ")", "{", "var", "index", ",", "include", ",", "pattern", ",", "rule", ",", "type", ",", "matchedRule", ",", "ret", "=", "null", ";", "if", "(", "!", "(", "ofType", "===", "'file'", "||", "ofType", "===", "'dir'", ")", ")", "{", "throw", "new", "Error", "(", "'Internal error: file type was not provided, was ['", "+", "ofType", "+", "']'", ")", ";", "}", "/* check if there are any rules */", "if", "(", "rules", ".", "length", "<", "1", ")", "{", "throw", "new", "Error", "(", "'No rules specified'", ")", ";", "}", "// console.log('checking ' + name + '...');", "for", "(", "index", "in", "rules", ")", "{", "// console.log('\\t against ' + excludes[regex] + ': ' +", "// name.search(excludes[regex]));", "if", "(", "rules", ".", "hasOwnProperty", "(", "index", ")", ")", "{", "rule", "=", "rules", "[", "index", "]", ";", "if", "(", "rule", "instanceof", "RegExp", ")", "{", "pattern", "=", "rule", ";", "include", "=", "false", ";", "type", "=", "'any'", ";", "}", "else", "{", "pattern", "=", "rule", ".", "pattern", ";", "include", "=", "!", "!", "rule", ".", "include", ";", "type", "=", "rule", ".", "type", "||", "'any'", ";", "}", "if", "(", "!", "(", "type", "===", "'file'", "||", "type", "===", "'dir'", "||", "type", "===", "'any'", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid type for match ['", "+", "type", "+", "']'", ")", ";", "}", "if", "(", "!", "(", "pattern", "instanceof", "RegExp", ")", ")", "{", "console", ".", "log", "(", "rule", ")", ";", "throw", "new", "Error", "(", "'Pattern was not a regexp for rule'", ")", ";", "}", "if", "(", "name", ".", "search", "(", "pattern", ")", "!==", "-", "1", "&&", "(", "type", "===", "'any'", "||", "type", "===", "ofType", ")", ")", "{", "matchedRule", "=", "rule", ";", "ret", "=", "!", "include", ";", "break", ";", "}", "}", "}", "ret", "=", "ret", "===", "null", "?", "!", "!", "defaultIsExclude", ":", "ret", ";", "//console.log('Match [' + name + '], Exclude= [' + ret + ']');", "//console.log('Used rule');", "//console.log(matchedRule);", "return", "ret", ";", "}", ";", "}" ]
returns a function that determines whether a name is excluded from a list using a set of firewall style rules. Each rule looks like this: { pattern: /matchPattern/, include: true|false, type: file|dir|any } If a file matches a rule, it is included or excluded based on the value of the include flag If rule is a regexp, it is taken to be { pattern: regexp, include: false, type: 'any' } - i.e. it is an exclusion rule. The first rule that matches, wins. The defaultIsExclude value specifies the behavior when none of the rules match (if not specified, the file is included) @param {Array} rules set of rules to determine what files and directories are copied. @param {boolean} defaultIsExclude determines what to do when none of the rules match. @return {function} A match function.
[ "returns", "a", "function", "that", "determines", "whether", "a", "name", "is", "excluded", "from", "a", "list", "using", "a", "set", "of", "firewall", "style", "rules", "." ]
3677c4c9bb23406696a2d9e0f8a54c62663a1f32
https://github.com/YahooArchive/mojito-cli-test/blob/3677c4c9bb23406696a2d9e0f8a54c62663a1f32/lib/utils.js#L38-L104
39,723
YahooArchive/mojito-cli-test
lib/utils.js
copyUsingMatcher
function copyUsingMatcher(src, dest, excludeMatcher) { var filenames, basedir, i, name, file, newdest, type; //console.log('copying ' + src + ' to ' + dest); /* check if source path exists */ if (!exists(src)) { throw new Error(src + ' does not exist'); } /* check if source is a directory */ if (!fs.statSync(src).isDirectory()) { throw new Error(src + ' must be a directory'); } /* get the names of all files and directories under source in an array */ filenames = fs.readdirSync(src); basedir = src; /* check if destination directory exists */ if (!exists(dest)) { fs.mkdirSync(dest, parseInt('755', 8)); } for (i = 0; i < filenames.length; i += 1) { name = filenames[i]; file = basedir + '/' + name; type = fs.statSync(file).isDirectory() ? 'dir' : 'file'; newdest = dest + '/' + name; if (!excludeMatcher(file, type)) { //console.log('Copy ' + file + ' as ' + newdest); if (type === 'dir') { copyUsingMatcher(file, newdest, excludeMatcher); } else { copyFile(file, newdest); } } } }
javascript
function copyUsingMatcher(src, dest, excludeMatcher) { var filenames, basedir, i, name, file, newdest, type; //console.log('copying ' + src + ' to ' + dest); /* check if source path exists */ if (!exists(src)) { throw new Error(src + ' does not exist'); } /* check if source is a directory */ if (!fs.statSync(src).isDirectory()) { throw new Error(src + ' must be a directory'); } /* get the names of all files and directories under source in an array */ filenames = fs.readdirSync(src); basedir = src; /* check if destination directory exists */ if (!exists(dest)) { fs.mkdirSync(dest, parseInt('755', 8)); } for (i = 0; i < filenames.length; i += 1) { name = filenames[i]; file = basedir + '/' + name; type = fs.statSync(file).isDirectory() ? 'dir' : 'file'; newdest = dest + '/' + name; if (!excludeMatcher(file, type)) { //console.log('Copy ' + file + ' as ' + newdest); if (type === 'dir') { copyUsingMatcher(file, newdest, excludeMatcher); } else { copyFile(file, newdest); } } } }
[ "function", "copyUsingMatcher", "(", "src", ",", "dest", ",", "excludeMatcher", ")", "{", "var", "filenames", ",", "basedir", ",", "i", ",", "name", ",", "file", ",", "newdest", ",", "type", ";", "//console.log('copying ' + src + ' to ' + dest);", "/* check if source path exists */", "if", "(", "!", "exists", "(", "src", ")", ")", "{", "throw", "new", "Error", "(", "src", "+", "' does not exist'", ")", ";", "}", "/* check if source is a directory */", "if", "(", "!", "fs", ".", "statSync", "(", "src", ")", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "Error", "(", "src", "+", "' must be a directory'", ")", ";", "}", "/* get the names of all files and directories under source in an array */", "filenames", "=", "fs", ".", "readdirSync", "(", "src", ")", ";", "basedir", "=", "src", ";", "/* check if destination directory exists */", "if", "(", "!", "exists", "(", "dest", ")", ")", "{", "fs", ".", "mkdirSync", "(", "dest", ",", "parseInt", "(", "'755'", ",", "8", ")", ")", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "filenames", ".", "length", ";", "i", "+=", "1", ")", "{", "name", "=", "filenames", "[", "i", "]", ";", "file", "=", "basedir", "+", "'/'", "+", "name", ";", "type", "=", "fs", ".", "statSync", "(", "file", ")", ".", "isDirectory", "(", ")", "?", "'dir'", ":", "'file'", ";", "newdest", "=", "dest", "+", "'/'", "+", "name", ";", "if", "(", "!", "excludeMatcher", "(", "file", ",", "type", ")", ")", "{", "//console.log('Copy ' + file + ' as ' + newdest);", "if", "(", "type", "===", "'dir'", ")", "{", "copyUsingMatcher", "(", "file", ",", "newdest", ",", "excludeMatcher", ")", ";", "}", "else", "{", "copyFile", "(", "file", ",", "newdest", ")", ";", "}", "}", "}", "}" ]
recursively copies the source to destination directory based on a matcher that returns whether a file is to be excluded. @param {string} src source dir. @param {string} dest destination dir. @param {function} excludeMatcher the matcher that determines if a given file is to be excluded.
[ "recursively", "copies", "the", "source", "to", "destination", "directory", "based", "on", "a", "matcher", "that", "returns", "whether", "a", "file", "is", "to", "be", "excluded", "." ]
3677c4c9bb23406696a2d9e0f8a54c62663a1f32
https://github.com/YahooArchive/mojito-cli-test/blob/3677c4c9bb23406696a2d9e0f8a54c62663a1f32/lib/utils.js#L125-L175
39,724
manuel-di-iorio/promisify-es6
index.js
function (method, context) { return function () { var args = Array.prototype.slice.call(arguments); var lastIndex = args.length - 1; var lastArg = args && args.length > 0 ? args[lastIndex] : null; var cb = typeof lastArg === 'function' ? lastArg : null; if (cb) { return method.apply(context, args); } return new Promise(function (resolve, reject) { args.push(function (err, val) { if (err) return reject(err); resolve(val); }); method.apply(context, args); }); }; }
javascript
function (method, context) { return function () { var args = Array.prototype.slice.call(arguments); var lastIndex = args.length - 1; var lastArg = args && args.length > 0 ? args[lastIndex] : null; var cb = typeof lastArg === 'function' ? lastArg : null; if (cb) { return method.apply(context, args); } return new Promise(function (resolve, reject) { args.push(function (err, val) { if (err) return reject(err); resolve(val); }); method.apply(context, args); }); }; }
[ "function", "(", "method", ",", "context", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "lastIndex", "=", "args", ".", "length", "-", "1", ";", "var", "lastArg", "=", "args", "&&", "args", ".", "length", ">", "0", "?", "args", "[", "lastIndex", "]", ":", "null", ";", "var", "cb", "=", "typeof", "lastArg", "===", "'function'", "?", "lastArg", ":", "null", ";", "if", "(", "cb", ")", "{", "return", "method", ".", "apply", "(", "context", ",", "args", ")", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "args", ".", "push", "(", "function", "(", "err", ",", "val", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "val", ")", ";", "}", ")", ";", "method", ".", "apply", "(", "context", ",", "args", ")", ";", "}", ")", ";", "}", ";", "}" ]
PROMISIFY CALLBACK-STYLE FUNCTIONS TO ES6 PROMISES EXAMPLE: const fn = promisify( (callback) => callback(null, "Hello world!") ); fn((err, str) => console.log(str)); fn().then((str) => console.log(str)); //Both functions, will log 'Hello world!' Note: The function you pass, may have any arguments you want, but the latest have to be the callback, which you will call with: next(err, value) @param method: Function/Array/Map = The function(s) to promisify @param options: Map = "context" (default is function): The context which to apply the called function "replace" (default is falsy): When passed an array/map, if to replace the original object @return: A promise if passed a function, otherwise the object with the promises @license: MIT @version: 1.0.3 @author: Manuel Di Iorio
[ "PROMISIFY", "CALLBACK", "-", "STYLE", "FUNCTIONS", "TO", "ES6", "PROMISES" ]
3fb20250c335aebf22775e6b0fbb42e3f6eb662c
https://github.com/manuel-di-iorio/promisify-es6/blob/3fb20250c335aebf22775e6b0fbb42e3f6eb662c/index.js#L24-L44
39,725
panta82/readdir-plus
lib/readdir-plus.js
readdirPlus
function readdirPlus(path, userOptions, callback) { if (libTools.isFunction(userOptions)) { callback = userOptions; userOptions = null; } var options = libTools.merge(libVars.DEFAULT_OPTIONS); if (userOptions) { userOptions.stat = normalizeSection(userOptions.stat); userOptions.content = normalizeSection(userOptions.content); if (userOptions.content) { normalizeArray(userOptions.content, options.content, "asText"); normalizeArray(userOptions.content, options.content, "asBinary"); } libTools.merge(userOptions, options); } if (path[path.length - 1] !== libPath.sep) { path += libPath.sep; } setupFn(options.readdir); setupFn(options.stat); setupFn(options.content); return doReadDir(path, options, function (err, results) { if (err) { return callback && callback(err); } return callback && callback(null, results); }); function normalizeSection(section) { if (libTools.isBoolean(section)) { return { enabled: section }; } if (libTools.isAnonObject(section) && !libTools.isBoolean(section.enabled)) { section.enabled = true; } return section; } function setupFn(opts) { if (!opts.fn) { opts.fn = options.sync ? opts.fnSync : opts.fnAsync; } if (options.sync) { opts.fn = libTools.syncWrapper(opts.fn); } } function normalizeArray(target, source, property) { if (!target[property] || target[property] === true) { return; } if (!libTools.isArray(target[property])) { target[property] = [target[property]]; } else if (target[property].length === 1 && libTools.isArray(target[property][0])) { // array wrapped in array, replaces source value target[property] = target[property][0]; } else { target[property] = source[property].concat(target[property]); } } }
javascript
function readdirPlus(path, userOptions, callback) { if (libTools.isFunction(userOptions)) { callback = userOptions; userOptions = null; } var options = libTools.merge(libVars.DEFAULT_OPTIONS); if (userOptions) { userOptions.stat = normalizeSection(userOptions.stat); userOptions.content = normalizeSection(userOptions.content); if (userOptions.content) { normalizeArray(userOptions.content, options.content, "asText"); normalizeArray(userOptions.content, options.content, "asBinary"); } libTools.merge(userOptions, options); } if (path[path.length - 1] !== libPath.sep) { path += libPath.sep; } setupFn(options.readdir); setupFn(options.stat); setupFn(options.content); return doReadDir(path, options, function (err, results) { if (err) { return callback && callback(err); } return callback && callback(null, results); }); function normalizeSection(section) { if (libTools.isBoolean(section)) { return { enabled: section }; } if (libTools.isAnonObject(section) && !libTools.isBoolean(section.enabled)) { section.enabled = true; } return section; } function setupFn(opts) { if (!opts.fn) { opts.fn = options.sync ? opts.fnSync : opts.fnAsync; } if (options.sync) { opts.fn = libTools.syncWrapper(opts.fn); } } function normalizeArray(target, source, property) { if (!target[property] || target[property] === true) { return; } if (!libTools.isArray(target[property])) { target[property] = [target[property]]; } else if (target[property].length === 1 && libTools.isArray(target[property][0])) { // array wrapped in array, replaces source value target[property] = target[property][0]; } else { target[property] = source[property].concat(target[property]); } } }
[ "function", "readdirPlus", "(", "path", ",", "userOptions", ",", "callback", ")", "{", "if", "(", "libTools", ".", "isFunction", "(", "userOptions", ")", ")", "{", "callback", "=", "userOptions", ";", "userOptions", "=", "null", ";", "}", "var", "options", "=", "libTools", ".", "merge", "(", "libVars", ".", "DEFAULT_OPTIONS", ")", ";", "if", "(", "userOptions", ")", "{", "userOptions", ".", "stat", "=", "normalizeSection", "(", "userOptions", ".", "stat", ")", ";", "userOptions", ".", "content", "=", "normalizeSection", "(", "userOptions", ".", "content", ")", ";", "if", "(", "userOptions", ".", "content", ")", "{", "normalizeArray", "(", "userOptions", ".", "content", ",", "options", ".", "content", ",", "\"asText\"", ")", ";", "normalizeArray", "(", "userOptions", ".", "content", ",", "options", ".", "content", ",", "\"asBinary\"", ")", ";", "}", "libTools", ".", "merge", "(", "userOptions", ",", "options", ")", ";", "}", "if", "(", "path", "[", "path", ".", "length", "-", "1", "]", "!==", "libPath", ".", "sep", ")", "{", "path", "+=", "libPath", ".", "sep", ";", "}", "setupFn", "(", "options", ".", "readdir", ")", ";", "setupFn", "(", "options", ".", "stat", ")", ";", "setupFn", "(", "options", ".", "content", ")", ";", "return", "doReadDir", "(", "path", ",", "options", ",", "function", "(", "err", ",", "results", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "&&", "callback", "(", "err", ")", ";", "}", "return", "callback", "&&", "callback", "(", "null", ",", "results", ")", ";", "}", ")", ";", "function", "normalizeSection", "(", "section", ")", "{", "if", "(", "libTools", ".", "isBoolean", "(", "section", ")", ")", "{", "return", "{", "enabled", ":", "section", "}", ";", "}", "if", "(", "libTools", ".", "isAnonObject", "(", "section", ")", "&&", "!", "libTools", ".", "isBoolean", "(", "section", ".", "enabled", ")", ")", "{", "section", ".", "enabled", "=", "true", ";", "}", "return", "section", ";", "}", "function", "setupFn", "(", "opts", ")", "{", "if", "(", "!", "opts", ".", "fn", ")", "{", "opts", ".", "fn", "=", "options", ".", "sync", "?", "opts", ".", "fnSync", ":", "opts", ".", "fnAsync", ";", "}", "if", "(", "options", ".", "sync", ")", "{", "opts", ".", "fn", "=", "libTools", ".", "syncWrapper", "(", "opts", ".", "fn", ")", ";", "}", "}", "function", "normalizeArray", "(", "target", ",", "source", ",", "property", ")", "{", "if", "(", "!", "target", "[", "property", "]", "||", "target", "[", "property", "]", "===", "true", ")", "{", "return", ";", "}", "if", "(", "!", "libTools", ".", "isArray", "(", "target", "[", "property", "]", ")", ")", "{", "target", "[", "property", "]", "=", "[", "target", "[", "property", "]", "]", ";", "}", "else", "if", "(", "target", "[", "property", "]", ".", "length", "===", "1", "&&", "libTools", ".", "isArray", "(", "target", "[", "property", "]", "[", "0", "]", ")", ")", "{", "// array wrapped in array, replaces source value", "target", "[", "property", "]", "=", "target", "[", "property", "]", "[", "0", "]", ";", "}", "else", "{", "target", "[", "property", "]", "=", "source", "[", "property", "]", ".", "concat", "(", "target", "[", "property", "]", ")", ";", "}", "}", "}" ]
Read files recursively @param {string} path Path to read @param {ReaddirPlusOptions|object} [userOptions] @param {function(Error, ReaddirPlusFile[])} callback
[ "Read", "files", "recursively" ]
a3c0dc9356ebbcdfebf7565286709984b0770720
https://github.com/panta82/readdir-plus/blob/a3c0dc9356ebbcdfebf7565286709984b0770720/lib/readdir-plus.js#L263-L333
39,726
stadt-bielefeld/mapfile2js
src/parse.js
parse
function parse(c) { let ret = []; // replace windows line breaks with linux line breaks let c1 = c.replace(new RegExp('[\r][\n]', 'g'), '\n'); // split string to line array let c2 = c1.split('\n'); for (let i = 0; i < c2.length; i++) { //line object let lo = {}; // line let l = c2[i]; // trim line let l1 = l.trim(); // set line number lo.num = i + 1; // set original line lo.content = l1; // check empty line if (l1 === '') { lo.isEmpty = true; } else { lo.isEmpty = false; // check line comment if (l1.startsWith('#')) { lo.isComment = true; lo.comment = lo.content.substring(1,lo.content.length).trim(); } else { lo.isComment = false; // Check included comments lo = Object.assign(lo, checkComment(l1)); // check key value lo = Object.assign(lo, checkKeyValue(lo.contentWithoutComment)); // check block key lo = Object.assign(lo, checkBlockKey(lo)); } } //console.log(lo); ret.push(lo); } checkBlockEndSum(ret); determineDepth(ret); return ret; }
javascript
function parse(c) { let ret = []; // replace windows line breaks with linux line breaks let c1 = c.replace(new RegExp('[\r][\n]', 'g'), '\n'); // split string to line array let c2 = c1.split('\n'); for (let i = 0; i < c2.length; i++) { //line object let lo = {}; // line let l = c2[i]; // trim line let l1 = l.trim(); // set line number lo.num = i + 1; // set original line lo.content = l1; // check empty line if (l1 === '') { lo.isEmpty = true; } else { lo.isEmpty = false; // check line comment if (l1.startsWith('#')) { lo.isComment = true; lo.comment = lo.content.substring(1,lo.content.length).trim(); } else { lo.isComment = false; // Check included comments lo = Object.assign(lo, checkComment(l1)); // check key value lo = Object.assign(lo, checkKeyValue(lo.contentWithoutComment)); // check block key lo = Object.assign(lo, checkBlockKey(lo)); } } //console.log(lo); ret.push(lo); } checkBlockEndSum(ret); determineDepth(ret); return ret; }
[ "function", "parse", "(", "c", ")", "{", "let", "ret", "=", "[", "]", ";", "// replace windows line breaks with linux line breaks", "let", "c1", "=", "c", ".", "replace", "(", "new", "RegExp", "(", "'[\\r][\\n]'", ",", "'g'", ")", ",", "'\\n'", ")", ";", "// split string to line array", "let", "c2", "=", "c1", ".", "split", "(", "'\\n'", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "c2", ".", "length", ";", "i", "++", ")", "{", "//line object", "let", "lo", "=", "{", "}", ";", "// line", "let", "l", "=", "c2", "[", "i", "]", ";", "// trim line", "let", "l1", "=", "l", ".", "trim", "(", ")", ";", "// set line number", "lo", ".", "num", "=", "i", "+", "1", ";", "// set original line", "lo", ".", "content", "=", "l1", ";", "// check empty line", "if", "(", "l1", "===", "''", ")", "{", "lo", ".", "isEmpty", "=", "true", ";", "}", "else", "{", "lo", ".", "isEmpty", "=", "false", ";", "// check line comment", "if", "(", "l1", ".", "startsWith", "(", "'#'", ")", ")", "{", "lo", ".", "isComment", "=", "true", ";", "lo", ".", "comment", "=", "lo", ".", "content", ".", "substring", "(", "1", ",", "lo", ".", "content", ".", "length", ")", ".", "trim", "(", ")", ";", "}", "else", "{", "lo", ".", "isComment", "=", "false", ";", "// Check included comments", "lo", "=", "Object", ".", "assign", "(", "lo", ",", "checkComment", "(", "l1", ")", ")", ";", "// check key value", "lo", "=", "Object", ".", "assign", "(", "lo", ",", "checkKeyValue", "(", "lo", ".", "contentWithoutComment", ")", ")", ";", "// check block key", "lo", "=", "Object", ".", "assign", "(", "lo", ",", "checkBlockKey", "(", "lo", ")", ")", ";", "}", "}", "//console.log(lo);", "ret", ".", "push", "(", "lo", ")", ";", "}", "checkBlockEndSum", "(", "ret", ")", ";", "determineDepth", "(", "ret", ")", ";", "return", "ret", ";", "}" ]
Parses a MapServer Mapfile to a JavaScript object. @param {string} c Content of a MapServer Mapfile @returns {array}
[ "Parses", "a", "MapServer", "Mapfile", "to", "a", "JavaScript", "object", "." ]
08497189503e8823d1c9f26b74ce4ad1025e59dd
https://github.com/stadt-bielefeld/mapfile2js/blob/08497189503e8823d1c9f26b74ce4ad1025e59dd/src/parse.js#L29-L91
39,727
stadt-bielefeld/mapfile2js
src/build.js
build
function build(obj, options) { // options let opt = Object.assign(defaultOptions, options); // mapfile content let map = ''; // determine one tab with spaces let tab = ''; for (let i = 0; i < opt.tabSize; i++) { tab += ' '; } //determine key-value-spaces determineKeyValueSpaces(obj, opt.tabSize); //iterate over all lines obj.forEach((line) => { //Add empty lines if (line.isEmpty) { if (opt.emptyLines) { map += opt.lineBreak; } } else { //Add comment lines if (line.isComment) { if (opt.comments) { map += determineTabs(line, tab) + '#' + opt.commentPrefix + line.comment + opt.lineBreak; } } else { //Add key if (line.key) { //Key only if (line.isKeyOnly) { map += determineTabs(line, tab) + line.key + opt.lineBreak; } else { //Key with value map += determineTabs(line, tab) + line.key; //Add value if (line.value) { if (line.includesComment) { //Add comment map += line.keyValueSpaces + line.value; if (opt.comments) { if (line.comment) { map += tab + '#' + opt.commentPrefix + line.comment + opt.lineBreak; } else { map += opt.lineBreak; } } else { map += opt.lineBreak; } } else { //Without comments map += line.keyValueSpaces + line.value + opt.lineBreak; } } } } } } }); return map; }
javascript
function build(obj, options) { // options let opt = Object.assign(defaultOptions, options); // mapfile content let map = ''; // determine one tab with spaces let tab = ''; for (let i = 0; i < opt.tabSize; i++) { tab += ' '; } //determine key-value-spaces determineKeyValueSpaces(obj, opt.tabSize); //iterate over all lines obj.forEach((line) => { //Add empty lines if (line.isEmpty) { if (opt.emptyLines) { map += opt.lineBreak; } } else { //Add comment lines if (line.isComment) { if (opt.comments) { map += determineTabs(line, tab) + '#' + opt.commentPrefix + line.comment + opt.lineBreak; } } else { //Add key if (line.key) { //Key only if (line.isKeyOnly) { map += determineTabs(line, tab) + line.key + opt.lineBreak; } else { //Key with value map += determineTabs(line, tab) + line.key; //Add value if (line.value) { if (line.includesComment) { //Add comment map += line.keyValueSpaces + line.value; if (opt.comments) { if (line.comment) { map += tab + '#' + opt.commentPrefix + line.comment + opt.lineBreak; } else { map += opt.lineBreak; } } else { map += opt.lineBreak; } } else { //Without comments map += line.keyValueSpaces + line.value + opt.lineBreak; } } } } } } }); return map; }
[ "function", "build", "(", "obj", ",", "options", ")", "{", "// options", "let", "opt", "=", "Object", ".", "assign", "(", "defaultOptions", ",", "options", ")", ";", "// mapfile content", "let", "map", "=", "''", ";", "// determine one tab with spaces", "let", "tab", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "opt", ".", "tabSize", ";", "i", "++", ")", "{", "tab", "+=", "' '", ";", "}", "//determine key-value-spaces", "determineKeyValueSpaces", "(", "obj", ",", "opt", ".", "tabSize", ")", ";", "//iterate over all lines", "obj", ".", "forEach", "(", "(", "line", ")", "=>", "{", "//Add empty lines", "if", "(", "line", ".", "isEmpty", ")", "{", "if", "(", "opt", ".", "emptyLines", ")", "{", "map", "+=", "opt", ".", "lineBreak", ";", "}", "}", "else", "{", "//Add comment lines", "if", "(", "line", ".", "isComment", ")", "{", "if", "(", "opt", ".", "comments", ")", "{", "map", "+=", "determineTabs", "(", "line", ",", "tab", ")", "+", "'#'", "+", "opt", ".", "commentPrefix", "+", "line", ".", "comment", "+", "opt", ".", "lineBreak", ";", "}", "}", "else", "{", "//Add key", "if", "(", "line", ".", "key", ")", "{", "//Key only", "if", "(", "line", ".", "isKeyOnly", ")", "{", "map", "+=", "determineTabs", "(", "line", ",", "tab", ")", "+", "line", ".", "key", "+", "opt", ".", "lineBreak", ";", "}", "else", "{", "//Key with value", "map", "+=", "determineTabs", "(", "line", ",", "tab", ")", "+", "line", ".", "key", ";", "//Add value", "if", "(", "line", ".", "value", ")", "{", "if", "(", "line", ".", "includesComment", ")", "{", "//Add comment", "map", "+=", "line", ".", "keyValueSpaces", "+", "line", ".", "value", ";", "if", "(", "opt", ".", "comments", ")", "{", "if", "(", "line", ".", "comment", ")", "{", "map", "+=", "tab", "+", "'#'", "+", "opt", ".", "commentPrefix", "+", "line", ".", "comment", "+", "opt", ".", "lineBreak", ";", "}", "else", "{", "map", "+=", "opt", ".", "lineBreak", ";", "}", "}", "else", "{", "map", "+=", "opt", ".", "lineBreak", ";", "}", "}", "else", "{", "//Without comments", "map", "+=", "line", ".", "keyValueSpaces", "+", "line", ".", "value", "+", "opt", ".", "lineBreak", ";", "}", "}", "}", "}", "}", "}", "}", ")", ";", "return", "map", ";", "}" ]
Builds a MapFiles from object. @param {object} obj MapFile as JavaScript object. @param {object} [options] Build options. @param {number} [options.tabSize] Size of tabulator. Default is `2`. @param {string} [options.lineBreak] Line break character. Default is `\n`. @param {boolean} [options.comments] Build comments. Default is `true`. @param {boolean} [options.commentPrefix] Build comments with a prefix. Default is ` `. @param {boolean} [options.emptyLines] Build empty lines. Default is `true`. @returns {string} MapServer Mapfile as string.
[ "Builds", "a", "MapFiles", "from", "object", "." ]
08497189503e8823d1c9f26b74ce4ad1025e59dd
https://github.com/stadt-bielefeld/mapfile2js/blob/08497189503e8823d1c9f26b74ce4ad1025e59dd/src/build.js#L27-L98
39,728
thlorenz/mothership
index.js
mothership
function mothership(start, ismothership, cb) { (function findShip (root) { findParentDir(root, 'package.json', function (err, packageDir) { if (err) return cb(err); if (!packageDir) return cb(); var pack; try { pack = require(path.join(packageDir, 'package.json')); if (ismothership(pack)) return cb(null, { path: path.join(packageDir, 'package.json'), pack: pack }); findShip(path.resolve(root, '..')); } catch (e) { cb(e); } }); })(start); }
javascript
function mothership(start, ismothership, cb) { (function findShip (root) { findParentDir(root, 'package.json', function (err, packageDir) { if (err) return cb(err); if (!packageDir) return cb(); var pack; try { pack = require(path.join(packageDir, 'package.json')); if (ismothership(pack)) return cb(null, { path: path.join(packageDir, 'package.json'), pack: pack }); findShip(path.resolve(root, '..')); } catch (e) { cb(e); } }); })(start); }
[ "function", "mothership", "(", "start", ",", "ismothership", ",", "cb", ")", "{", "(", "function", "findShip", "(", "root", ")", "{", "findParentDir", "(", "root", ",", "'package.json'", ",", "function", "(", "err", ",", "packageDir", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "!", "packageDir", ")", "return", "cb", "(", ")", ";", "var", "pack", ";", "try", "{", "pack", "=", "require", "(", "path", ".", "join", "(", "packageDir", ",", "'package.json'", ")", ")", ";", "if", "(", "ismothership", "(", "pack", ")", ")", "return", "cb", "(", "null", ",", "{", "path", ":", "path", ".", "join", "(", "packageDir", ",", "'package.json'", ")", ",", "pack", ":", "pack", "}", ")", ";", "findShip", "(", "path", ".", "resolve", "(", "root", ",", "'..'", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "cb", "(", "e", ")", ";", "}", "}", ")", ";", "}", ")", "(", "start", ")", ";", "}" ]
Searches upwards from start for package.json files, asking for each if it is the mothership. If a mothership is found it calls back with that. If it reaches the top of the univers it calls back with nothing. ##### mothership result - `path`: full path to the `package.json` that is the mother ship - `pack`: the `package.json` object, same that was passed to ismothership @name mothership @function @param {string} start full path at which to start looking for the mothership @param {function} ismothership invoked with the package object, needs to return true if it is the mothership @param {function} cb called back with either an error or full path to package.json that is the mothership
[ "Searches", "upwards", "from", "start", "for", "package", ".", "json", "files", "asking", "for", "each", "if", "it", "is", "the", "mothership", ".", "If", "a", "mothership", "is", "found", "it", "calls", "back", "with", "that", ".", "If", "it", "reaches", "the", "top", "of", "the", "univers", "it", "calls", "back", "with", "nothing", "." ]
b60eda433a31ad0a55f7f3d64beadface99980dc
https://github.com/thlorenz/mothership/blob/b60eda433a31ad0a55f7f3d64beadface99980dc/index.js#L23-L40
39,729
preceptorjs/taxi
lib/scripts/stitching.js
function (horizontalPadding) { var de = document.documentElement, body = document.body, el, initData; // Create a div to figure out the size of the view-port across browsers el = document.createElement('div'); el.style.position = "fixed"; el.style.top = 0; el.style.left = 0; el.style.bottom = 0; el.style.right = 0; de.insertBefore(el, de.firstChild); initData = { bodyOverflow: body.style.overflow, bodyWidth: body.style.width, bodyHeight: body.style.height, viewPortWidth: el.offsetWidth, horizontalPadding: horizontalPadding }; de.removeChild(el); // Remove scrollbars body.style.overflow = 'hidden'; // Make document only one pixel height and twice wide as the view-port body.style.width = ((initData.viewPortWidth - horizontalPadding) * 2) + 'px'; body.style.height = '1px'; return JSON.stringify(initData); }
javascript
function (horizontalPadding) { var de = document.documentElement, body = document.body, el, initData; // Create a div to figure out the size of the view-port across browsers el = document.createElement('div'); el.style.position = "fixed"; el.style.top = 0; el.style.left = 0; el.style.bottom = 0; el.style.right = 0; de.insertBefore(el, de.firstChild); initData = { bodyOverflow: body.style.overflow, bodyWidth: body.style.width, bodyHeight: body.style.height, viewPortWidth: el.offsetWidth, horizontalPadding: horizontalPadding }; de.removeChild(el); // Remove scrollbars body.style.overflow = 'hidden'; // Make document only one pixel height and twice wide as the view-port body.style.width = ((initData.viewPortWidth - horizontalPadding) * 2) + 'px'; body.style.height = '1px'; return JSON.stringify(initData); }
[ "function", "(", "horizontalPadding", ")", "{", "var", "de", "=", "document", ".", "documentElement", ",", "body", "=", "document", ".", "body", ",", "el", ",", "initData", ";", "// Create a div to figure out the size of the view-port across browsers", "el", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "el", ".", "style", ".", "position", "=", "\"fixed\"", ";", "el", ".", "style", ".", "top", "=", "0", ";", "el", ".", "style", ".", "left", "=", "0", ";", "el", ".", "style", ".", "bottom", "=", "0", ";", "el", ".", "style", ".", "right", "=", "0", ";", "de", ".", "insertBefore", "(", "el", ",", "de", ".", "firstChild", ")", ";", "initData", "=", "{", "bodyOverflow", ":", "body", ".", "style", ".", "overflow", ",", "bodyWidth", ":", "body", ".", "style", ".", "width", ",", "bodyHeight", ":", "body", ".", "style", ".", "height", ",", "viewPortWidth", ":", "el", ".", "offsetWidth", ",", "horizontalPadding", ":", "horizontalPadding", "}", ";", "de", ".", "removeChild", "(", "el", ")", ";", "// Remove scrollbars", "body", ".", "style", ".", "overflow", "=", "'hidden'", ";", "// Make document only one pixel height and twice wide as the view-port", "body", ".", "style", ".", "width", "=", "(", "(", "initData", ".", "viewPortWidth", "-", "horizontalPadding", ")", "*", "2", ")", "+", "'px'", ";", "body", ".", "style", ".", "height", "=", "'1px'", ";", "return", "JSON", ".", "stringify", "(", "initData", ")", ";", "}" ]
Initializes the stitching determination. It gathers the current document state, and it will modify the document as needed. @method init @param {int} horizontalPadding
[ "Initializes", "the", "stitching", "determination", ".", "It", "gathers", "the", "current", "document", "state", "and", "it", "will", "modify", "the", "document", "as", "needed", "." ]
96ab5a5c5fa9dc50f325ba4de52dd90009073ca3
https://github.com/preceptorjs/taxi/blob/96ab5a5c5fa9dc50f325ba4de52dd90009073ca3/lib/scripts/stitching.js#L11-L43
39,730
preceptorjs/taxi
lib/scripts/stitching.js
function (initData) { var body = document.body; body.style.overflow = initData.bodyOverflow; body.style.width = initData.bodyWidth; body.style.height = initData.bodyHeight; }
javascript
function (initData) { var body = document.body; body.style.overflow = initData.bodyOverflow; body.style.width = initData.bodyWidth; body.style.height = initData.bodyHeight; }
[ "function", "(", "initData", ")", "{", "var", "body", "=", "document", ".", "body", ";", "body", ".", "style", ".", "overflow", "=", "initData", ".", "bodyOverflow", ";", "body", ".", "style", ".", "width", "=", "initData", ".", "bodyWidth", ";", "body", ".", "style", ".", "height", "=", "initData", ".", "bodyHeight", ";", "}" ]
Revert changes done to the document during the init-phase @method revert @param {object} initData Data gathered during init-phase
[ "Revert", "changes", "done", "to", "the", "document", "during", "the", "init", "-", "phase" ]
96ab5a5c5fa9dc50f325ba4de52dd90009073ca3
https://github.com/preceptorjs/taxi/blob/96ab5a5c5fa9dc50f325ba4de52dd90009073ca3/lib/scripts/stitching.js#L51-L57
39,731
lidl-ecommerce/grunt-kss-node
tasks/kss.js
buildKssCmd
function buildKssCmd(node, kssNpmPath, options, files) { var cmd = [ node, kssNpmPath ], options; for (var optionName in options) { if (options.hasOwnProperty(optionName)) { grunt.log.debug('Reading option: ' + optionName); var values = options[optionName]; if (!Array.isArray(values)) { values = [values]; } for (var i = 0; i < values.length; i++) { if (values[i] && typeof values[i] === 'boolean') { grunt.log.debug(' > TRUE'); cmd.push('--' + optionName); } else if (typeof values[i] === 'string') { cmd.push('--' + optionName, values[i]); grunt.log.debug(' > ' + values[i]); } } } } files.forEach(function parseDestinationsFile(file) { if (file.src.length === 0) { grunt.log.error('No source files found'); grunt.fail.warn('Wrong configuration', 1); } cmd.push('--destination', '"' + file.dest + '"'); for (var i = 0; i < file.src.length; i++) { cmd.push('--source', '"' + file.src[i] + '"'); } dest = file.dest; }); return cmd; }
javascript
function buildKssCmd(node, kssNpmPath, options, files) { var cmd = [ node, kssNpmPath ], options; for (var optionName in options) { if (options.hasOwnProperty(optionName)) { grunt.log.debug('Reading option: ' + optionName); var values = options[optionName]; if (!Array.isArray(values)) { values = [values]; } for (var i = 0; i < values.length; i++) { if (values[i] && typeof values[i] === 'boolean') { grunt.log.debug(' > TRUE'); cmd.push('--' + optionName); } else if (typeof values[i] === 'string') { cmd.push('--' + optionName, values[i]); grunt.log.debug(' > ' + values[i]); } } } } files.forEach(function parseDestinationsFile(file) { if (file.src.length === 0) { grunt.log.error('No source files found'); grunt.fail.warn('Wrong configuration', 1); } cmd.push('--destination', '"' + file.dest + '"'); for (var i = 0; i < file.src.length; i++) { cmd.push('--source', '"' + file.src[i] + '"'); } dest = file.dest; }); return cmd; }
[ "function", "buildKssCmd", "(", "node", ",", "kssNpmPath", ",", "options", ",", "files", ")", "{", "var", "cmd", "=", "[", "node", ",", "kssNpmPath", "]", ",", "options", ";", "for", "(", "var", "optionName", "in", "options", ")", "{", "if", "(", "options", ".", "hasOwnProperty", "(", "optionName", ")", ")", "{", "grunt", ".", "log", ".", "debug", "(", "'Reading option: '", "+", "optionName", ")", ";", "var", "values", "=", "options", "[", "optionName", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "values", ")", ")", "{", "values", "=", "[", "values", "]", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "{", "if", "(", "values", "[", "i", "]", "&&", "typeof", "values", "[", "i", "]", "===", "'boolean'", ")", "{", "grunt", ".", "log", ".", "debug", "(", "' > TRUE'", ")", ";", "cmd", ".", "push", "(", "'--'", "+", "optionName", ")", ";", "}", "else", "if", "(", "typeof", "values", "[", "i", "]", "===", "'string'", ")", "{", "cmd", ".", "push", "(", "'--'", "+", "optionName", ",", "values", "[", "i", "]", ")", ";", "grunt", ".", "log", ".", "debug", "(", "' > '", "+", "values", "[", "i", "]", ")", ";", "}", "}", "}", "}", "files", ".", "forEach", "(", "function", "parseDestinationsFile", "(", "file", ")", "{", "if", "(", "file", ".", "src", ".", "length", "===", "0", ")", "{", "grunt", ".", "log", ".", "error", "(", "'No source files found'", ")", ";", "grunt", ".", "fail", ".", "warn", "(", "'Wrong configuration'", ",", "1", ")", ";", "}", "cmd", ".", "push", "(", "'--destination'", ",", "'\"'", "+", "file", ".", "dest", "+", "'\"'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "file", ".", "src", ".", "length", ";", "i", "++", ")", "{", "cmd", ".", "push", "(", "'--source'", ",", "'\"'", "+", "file", ".", "src", "[", "i", "]", "+", "'\"'", ")", ";", "}", "dest", "=", "file", ".", "dest", ";", "}", ")", ";", "return", "cmd", ";", "}" ]
build kss command @private @param {string} node path to nodejs bin @param {string} kssNpmPath path to kss bin @param {array} options kss options @param {array} files file list grunt.task.current.files @returns {array}
[ "build", "kss", "command" ]
c32cb7f43b12afaa2b9a55e183fbdfd61345c55d
https://github.com/lidl-ecommerce/grunt-kss-node/blob/c32cb7f43b12afaa2b9a55e183fbdfd61345c55d/tasks/kss.js#L48-L89
39,732
lidl-ecommerce/grunt-kss-node
tasks/kss.js
getKssNode
function getKssNode(baseKssPath, currentPath) { var kss = null; var localKss = currentPath + '/node_modules/' + baseKssPath; if (grunt.file.exists(localKss)) { return localKss; } var projektPath = path.dirname(currentPath); var projectKss = projektPath + '/' + baseKssPath; if (grunt.file.exists(projectKss)) { return projectKss; } else { grunt.log.error('Kss-node not found, please install kss!'); grunt.fail.warn('Wrong installation/environnement', 1); } }
javascript
function getKssNode(baseKssPath, currentPath) { var kss = null; var localKss = currentPath + '/node_modules/' + baseKssPath; if (grunt.file.exists(localKss)) { return localKss; } var projektPath = path.dirname(currentPath); var projectKss = projektPath + '/' + baseKssPath; if (grunt.file.exists(projectKss)) { return projectKss; } else { grunt.log.error('Kss-node not found, please install kss!'); grunt.fail.warn('Wrong installation/environnement', 1); } }
[ "function", "getKssNode", "(", "baseKssPath", ",", "currentPath", ")", "{", "var", "kss", "=", "null", ";", "var", "localKss", "=", "currentPath", "+", "'/node_modules/'", "+", "baseKssPath", ";", "if", "(", "grunt", ".", "file", ".", "exists", "(", "localKss", ")", ")", "{", "return", "localKss", ";", "}", "var", "projektPath", "=", "path", ".", "dirname", "(", "currentPath", ")", ";", "var", "projectKss", "=", "projektPath", "+", "'/'", "+", "baseKssPath", ";", "if", "(", "grunt", ".", "file", ".", "exists", "(", "projectKss", ")", ")", "{", "return", "projectKss", ";", "}", "else", "{", "grunt", ".", "log", ".", "error", "(", "'Kss-node not found, please install kss!'", ")", ";", "grunt", ".", "fail", ".", "warn", "(", "'Wrong installation/environnement'", ",", "1", ")", ";", "}", "}" ]
found out the kss-node module @param {string} baseKssPath base dir 'kss/bin/kss-node' @param {string} currentPath current Project Path @returns {string}
[ "found", "out", "the", "kss", "-", "node", "module" ]
c32cb7f43b12afaa2b9a55e183fbdfd61345c55d
https://github.com/lidl-ecommerce/grunt-kss-node/blob/c32cb7f43b12afaa2b9a55e183fbdfd61345c55d/tasks/kss.js#L117-L132
39,733
stezu/node-stream
lib/consumers/v1/wait.js
waitObj
function waitObj(stream, onEnd) { var data = []; /** * Send the correct data to the onEnd callback. * * @private * @param {Error} [err] - Optional error. * @returns {undefined} */ var done = _.once(function (err) { if (err) { return onEnd(err); } return onEnd(null, data); }); stream.on('data', function (chunk) { data.push(chunk); }); stream.on('error', done); stream.on('end', done); }
javascript
function waitObj(stream, onEnd) { var data = []; /** * Send the correct data to the onEnd callback. * * @private * @param {Error} [err] - Optional error. * @returns {undefined} */ var done = _.once(function (err) { if (err) { return onEnd(err); } return onEnd(null, data); }); stream.on('data', function (chunk) { data.push(chunk); }); stream.on('error', done); stream.on('end', done); }
[ "function", "waitObj", "(", "stream", ",", "onEnd", ")", "{", "var", "data", "=", "[", "]", ";", "/**\n * Send the correct data to the onEnd callback.\n *\n * @private\n * @param {Error} [err] - Optional error.\n * @returns {undefined}\n */", "var", "done", "=", "_", ".", "once", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "onEnd", "(", "err", ")", ";", "}", "return", "onEnd", "(", "null", ",", "data", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "data", ".", "push", "(", "chunk", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'error'", ",", "done", ")", ";", "stream", ".", "on", "(", "'end'", ",", "done", ")", ";", "}" ]
Wait for the contents of an object stream. @private @deprecated @static @since 0.0.1 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Wait", "for", "the", "contents", "of", "an", "object", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/wait.js#L18-L42
39,734
stezu/node-stream
lib/consumers/v1/wait.js
wait
function wait(stream, onEnd) { waitObj(stream, function (err, data) { if (err) { return onEnd(err); } return onEnd(null, Buffer.concat(data.map(function (item) { return new Buffer(item); }))); }); }
javascript
function wait(stream, onEnd) { waitObj(stream, function (err, data) { if (err) { return onEnd(err); } return onEnd(null, Buffer.concat(data.map(function (item) { return new Buffer(item); }))); }); }
[ "function", "wait", "(", "stream", ",", "onEnd", ")", "{", "waitObj", "(", "stream", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "onEnd", "(", "err", ")", ";", "}", "return", "onEnd", "(", "null", ",", "Buffer", ".", "concat", "(", "data", ".", "map", "(", "function", "(", "item", ")", "{", "return", "new", "Buffer", "(", "item", ")", ";", "}", ")", ")", ")", ";", "}", ")", ";", "}" ]
Wait for the contents of a stream. @private @deprecated @static @since 0.0.1 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Wait", "for", "the", "contents", "of", "a", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/wait.js#L57-L69
39,735
stezu/node-stream
lib/consumers/v1/wait.js
waitJson
function waitJson(stream, onEnd) { wait(stream, function (err, data) { if (err) { return onEnd(err); } return parse(data, onEnd); }); }
javascript
function waitJson(stream, onEnd) { wait(stream, function (err, data) { if (err) { return onEnd(err); } return parse(data, onEnd); }); }
[ "function", "waitJson", "(", "stream", ",", "onEnd", ")", "{", "wait", "(", "stream", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "onEnd", "(", "err", ")", ";", "}", "return", "parse", "(", "data", ",", "onEnd", ")", ";", "}", ")", ";", "}" ]
Wait for the stream contents, then parse for JSON. @private @deprecated @static @since 0.0.2 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Wait", "for", "the", "stream", "contents", "then", "parse", "for", "JSON", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/wait.js#L84-L94
39,736
stezu/node-stream
lib/modifiers/pipeline.js
pipeline
function pipeline() { var streams = getArgs(arguments); // When given no arguments, we should still return a stream if (streams.length === 0) { return new PassThrough(); } // Since a duplex requires at least two streams, we return single streams if (streams.length === 1) { return streams[0]; } return pump(streams); }
javascript
function pipeline() { var streams = getArgs(arguments); // When given no arguments, we should still return a stream if (streams.length === 0) { return new PassThrough(); } // Since a duplex requires at least two streams, we return single streams if (streams.length === 1) { return streams[0]; } return pump(streams); }
[ "function", "pipeline", "(", ")", "{", "var", "streams", "=", "getArgs", "(", "arguments", ")", ";", "// When given no arguments, we should still return a stream", "if", "(", "streams", ".", "length", "===", "0", ")", "{", "return", "new", "PassThrough", "(", ")", ";", "}", "// Since a duplex requires at least two streams, we return single streams", "if", "(", "streams", ".", "length", "===", "1", ")", "{", "return", "streams", "[", "0", "]", ";", "}", "return", "pump", "(", "streams", ")", ";", "}" ]
Pipes all given streams together and destroys all of them if one of them closes. In addition, it returns a Duplex stream that you can write to and read from as well. This is primarily used to create a single stream to an outside caller that internally is made up of many streams. It's also especially useful for handling errors on all of the streams in a pipeline with a single error handler on the returned Duplex. @method @static @since 1.0.0 @category Util @param {...(Stream|Stream[])} streams - A series of streams that will be combined into a single output stream. @returns {Stream.Duplex} - Duplex stream. @example // emit the largest line in a file function getLargestLine() { return nodeStream.pipeline( nodeStream.split(), nodeStream.sort((a, b) => { return a.length < b.length; }), nodeStream.take(1) ); } // find the longest line of a haiku process.stdin // => ['refreshing and cool\nlove is ', 'a sweet summer ', 'rain\nthat washes the world'] .pipe(getLargestLine()) // => ['love is a sweet summer rain']
[ "Pipes", "all", "given", "streams", "together", "and", "destroys", "all", "of", "them", "if", "one", "of", "them", "closes", ".", "In", "addition", "it", "returns", "a", "Duplex", "stream", "that", "you", "can", "write", "to", "and", "read", "from", "as", "well", ".", "This", "is", "primarily", "used", "to", "create", "a", "single", "stream", "to", "an", "outside", "caller", "that", "internally", "is", "made", "up", "of", "many", "streams", ".", "It", "s", "also", "especially", "useful", "for", "handling", "errors", "on", "all", "of", "the", "streams", "in", "a", "pipeline", "with", "a", "single", "error", "handler", "on", "the", "returned", "Duplex", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/pipeline.js#L50-L64
39,737
stezu/node-stream
lib/modifiers/pipeline.js
pipelineObj
function pipelineObj() { var streams = getArgs(arguments); // When given no arguments, we should still return a stream if (streams.length === 0) { return new PassThrough({ objectMode: true }); } // Since a duplex requires at least two streams, we return single streams if (streams.length === 1) { return streams[0]; } return pumpObj(streams); }
javascript
function pipelineObj() { var streams = getArgs(arguments); // When given no arguments, we should still return a stream if (streams.length === 0) { return new PassThrough({ objectMode: true }); } // Since a duplex requires at least two streams, we return single streams if (streams.length === 1) { return streams[0]; } return pumpObj(streams); }
[ "function", "pipelineObj", "(", ")", "{", "var", "streams", "=", "getArgs", "(", "arguments", ")", ";", "// When given no arguments, we should still return a stream", "if", "(", "streams", ".", "length", "===", "0", ")", "{", "return", "new", "PassThrough", "(", "{", "objectMode", ":", "true", "}", ")", ";", "}", "// Since a duplex requires at least two streams, we return single streams", "if", "(", "streams", ".", "length", "===", "1", ")", "{", "return", "streams", "[", "0", "]", ";", "}", "return", "pumpObj", "(", "streams", ")", ";", "}" ]
Object mode of `pipeline`. Pipes all given streams together and destroys all of them if one of them closes. In addition, it returns a Duplex stream that you can write to and read from as well. This is primarily used to create a single stream to an outside caller that internally is made up of many streams. It's also especially useful for handling errors on all of the streams in a pipeline with a single error handler on the returned Duplex. @method @static @method pipeline.obj @since 1.0.0 @category Util @param {...(Stream|Stream[])} streams - A series of streams that will be combined into a single output stream. @returns {Stream.Duplex} - Duplex stream. @example // read the contents of a file and parse json function readJson() { return nodeStream.pipeline.obj( nodeStream.wait(), nodeStream.parse() ); } // parse stdin as JSON in a single step process.stdin // => ['{"', 'banana":', '"appl', 'e"}'] .pipe(readJson()) // => { 'banana': 'apple' }
[ "Object", "mode", "of", "pipeline", ".", "Pipes", "all", "given", "streams", "together", "and", "destroys", "all", "of", "them", "if", "one", "of", "them", "closes", ".", "In", "addition", "it", "returns", "a", "Duplex", "stream", "that", "you", "can", "write", "to", "and", "read", "from", "as", "well", ".", "This", "is", "primarily", "used", "to", "create", "a", "single", "stream", "to", "an", "outside", "caller", "that", "internally", "is", "made", "up", "of", "many", "streams", ".", "It", "s", "also", "especially", "useful", "for", "handling", "errors", "on", "all", "of", "the", "streams", "in", "a", "pipeline", "with", "a", "single", "error", "handler", "on", "the", "returned", "Duplex", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/pipeline.js#L99-L113
39,738
juanprietob/clusterpost
src/clusterpost-execution/executionserver.methods.js
function(dir, files){ fs.readdirSync(dir).forEach(function(file){ try{ var current = path.join(dir, file); var stat = fs.statSync(current); if (stat && stat.isDirectory()) { getAllFiles(current, files); }else { files.push(current); } }catch(e){ console.error(e); } }); }
javascript
function(dir, files){ fs.readdirSync(dir).forEach(function(file){ try{ var current = path.join(dir, file); var stat = fs.statSync(current); if (stat && stat.isDirectory()) { getAllFiles(current, files); }else { files.push(current); } }catch(e){ console.error(e); } }); }
[ "function", "(", "dir", ",", "files", ")", "{", "fs", ".", "readdirSync", "(", "dir", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "try", "{", "var", "current", "=", "path", ".", "join", "(", "dir", ",", "file", ")", ";", "var", "stat", "=", "fs", ".", "statSync", "(", "current", ")", ";", "if", "(", "stat", "&&", "stat", ".", "isDirectory", "(", ")", ")", "{", "getAllFiles", "(", "current", ",", "files", ")", ";", "}", "else", "{", "files", ".", "push", "(", "current", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Read all files in directory and return an array with all files
[ "Read", "all", "files", "in", "directory", "and", "return", "an", "array", "with", "all", "files" ]
5893d83d4f03f35e475b36cdcc975fb5154d12f5
https://github.com/juanprietob/clusterpost/blob/5893d83d4f03f35e475b36cdcc975fb5154d12f5/src/clusterpost-execution/executionserver.methods.js#L51-L65
39,739
MellowMelon/gridgy
src/findFaceCover.js
add
function add(x, y) { if (!retTable[x + "," + y]) { retTable[x + "," + y] = true; retArray.push([x, y]); } }
javascript
function add(x, y) { if (!retTable[x + "," + y]) { retTable[x + "," + y] = true; retArray.push([x, y]); } }
[ "function", "add", "(", "x", ",", "y", ")", "{", "if", "(", "!", "retTable", "[", "x", "+", "\",\"", "+", "y", "]", ")", "{", "retTable", "[", "x", "+", "\",\"", "+", "y", "]", "=", "true", ";", "retArray", ".", "push", "(", "[", "x", ",", "y", "]", ")", ";", "}", "}" ]
Helper to only add to the return array if not added before.
[ "Helper", "to", "only", "add", "to", "the", "return", "array", "if", "not", "added", "before", "." ]
1392b3b81ea1f448ad8041176855ef0aa8155a0f
https://github.com/MellowMelon/gridgy/blob/1392b3b81ea1f448ad8041176855ef0aa8155a0f/src/findFaceCover.js#L89-L94
39,740
upptalk/upptalk.js
dist/upptalk.js
ParseArray
function ParseArray(array, encoding, obj) { for (var n = 0; n < encoding.length; ++n) { var value = array[n]; if (!value) continue; var field = encoding[n]; var fieldAlpha = field.replace(NON_ALPHA_CHARS, ""); if (field != fieldAlpha) value = new RegExp(field.replace(fieldAlpha, value)); obj[fieldAlpha] = value; } return obj; }
javascript
function ParseArray(array, encoding, obj) { for (var n = 0; n < encoding.length; ++n) { var value = array[n]; if (!value) continue; var field = encoding[n]; var fieldAlpha = field.replace(NON_ALPHA_CHARS, ""); if (field != fieldAlpha) value = new RegExp(field.replace(fieldAlpha, value)); obj[fieldAlpha] = value; } return obj; }
[ "function", "ParseArray", "(", "array", ",", "encoding", ",", "obj", ")", "{", "for", "(", "var", "n", "=", "0", ";", "n", "<", "encoding", ".", "length", ";", "++", "n", ")", "{", "var", "value", "=", "array", "[", "n", "]", ";", "if", "(", "!", "value", ")", "continue", ";", "var", "field", "=", "encoding", "[", "n", "]", ";", "var", "fieldAlpha", "=", "field", ".", "replace", "(", "NON_ALPHA_CHARS", ",", "\"\"", ")", ";", "if", "(", "field", "!=", "fieldAlpha", ")", "value", "=", "new", "RegExp", "(", "field", ".", "replace", "(", "fieldAlpha", ",", "value", ")", ")", ";", "obj", "[", "fieldAlpha", "]", "=", "value", ";", "}", "return", "obj", ";", "}" ]
Parse an array of strings into a convenient object. We store meta data as arrays since thats much more compact than JSON.
[ "Parse", "an", "array", "of", "strings", "into", "a", "convenient", "object", ".", "We", "store", "meta", "data", "as", "arrays", "since", "thats", "much", "more", "compact", "than", "JSON", "." ]
1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c
https://github.com/upptalk/upptalk.js/blob/1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c/dist/upptalk.js#L1807-L1819
39,741
upptalk/upptalk.js
dist/upptalk.js
ParseMetaData
function ParseMetaData(countryCode, md) { var array = eval(md.replace(BACKSLASH, "\\\\")); md = ParseArray(array, META_DATA_ENCODING, { countryCode: countryCode }); regionCache[md.region] = md; return md; }
javascript
function ParseMetaData(countryCode, md) { var array = eval(md.replace(BACKSLASH, "\\\\")); md = ParseArray(array, META_DATA_ENCODING, { countryCode: countryCode }); regionCache[md.region] = md; return md; }
[ "function", "ParseMetaData", "(", "countryCode", ",", "md", ")", "{", "var", "array", "=", "eval", "(", "md", ".", "replace", "(", "BACKSLASH", ",", "\"\\\\\\\\\"", ")", ")", ";", "md", "=", "ParseArray", "(", "array", ",", "META_DATA_ENCODING", ",", "{", "countryCode", ":", "countryCode", "}", ")", ";", "regionCache", "[", "md", ".", "region", "]", "=", "md", ";", "return", "md", ";", "}" ]
Parse string encoded meta data into a convenient object representation.
[ "Parse", "string", "encoded", "meta", "data", "into", "a", "convenient", "object", "representation", "." ]
1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c
https://github.com/upptalk/upptalk.js/blob/1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c/dist/upptalk.js#L1823-L1830
39,742
upptalk/upptalk.js
dist/upptalk.js
ParseFormat
function ParseFormat(md) { var formats = md.formats; if (!formats) { return null; } // Bail if we already parsed the format definitions. if (!(Array.isArray(formats[0]))) return; for (var n = 0; n < formats.length; ++n) { formats[n] = ParseArray(formats[n], FORMAT_ENCODING, {}); } }
javascript
function ParseFormat(md) { var formats = md.formats; if (!formats) { return null; } // Bail if we already parsed the format definitions. if (!(Array.isArray(formats[0]))) return; for (var n = 0; n < formats.length; ++n) { formats[n] = ParseArray(formats[n], FORMAT_ENCODING, {}); } }
[ "function", "ParseFormat", "(", "md", ")", "{", "var", "formats", "=", "md", ".", "formats", ";", "if", "(", "!", "formats", ")", "{", "return", "null", ";", "}", "// Bail if we already parsed the format definitions.", "if", "(", "!", "(", "Array", ".", "isArray", "(", "formats", "[", "0", "]", ")", ")", ")", "return", ";", "for", "(", "var", "n", "=", "0", ";", "n", "<", "formats", ".", "length", ";", "++", "n", ")", "{", "formats", "[", "n", "]", "=", "ParseArray", "(", "formats", "[", "n", "]", ",", "FORMAT_ENCODING", ",", "{", "}", ")", ";", "}", "}" ]
Parse string encoded format data into a convenient object representation.
[ "Parse", "string", "encoded", "format", "data", "into", "a", "convenient", "object", "representation", "." ]
1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c
https://github.com/upptalk/upptalk.js/blob/1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c/dist/upptalk.js#L1834-L1847
39,743
upptalk/upptalk.js
dist/upptalk.js
FormatNumber
function FormatNumber(regionMetaData, number, intl) { // We lazily parse the format description in the meta data for the region, // so make sure to parse it now if we haven't already done so. ParseFormat(regionMetaData); var formats = regionMetaData.formats; if (!formats) { return null; } for (var n = 0; n < formats.length; ++n) { var format = formats[n]; // The leading digits field is optional. If we don't have it, just // use the matching pattern to qualify numbers. if (format.leadingDigits && !format.leadingDigits.test(number)) continue; if (!format.pattern.test(number)) continue; if (intl) { // If there is no international format, just fall back to the national // format. var internationalFormat = format.internationalFormat; if (!internationalFormat) internationalFormat = format.nationalFormat; // Some regions have numbers that can't be dialed from outside the // country, indicated by "NA" for the international format of that // number format pattern. if (internationalFormat == "NA") return null; // Prepend "+" and the country code. number = "+" + regionMetaData.countryCode + " " + number.replace(format.pattern, internationalFormat); } else { number = number.replace(format.pattern, format.nationalFormat); // The region has a national prefix formatting rule, and it can be overwritten // by each actual number format rule. var nationalPrefixFormattingRule = regionMetaData.nationalPrefixFormattingRule; if (format.nationalPrefixFormattingRule) nationalPrefixFormattingRule = format.nationalPrefixFormattingRule; if (nationalPrefixFormattingRule) { // The prefix formatting rule contains two magic markers, "$NP" and "$FG". // "$NP" will be replaced by the national prefix, and "$FG" with the // first group of numbers. var match = number.match(SPLIT_FIRST_GROUP); if (match) { var firstGroup = match[1]; var rest = match[2]; var prefix = nationalPrefixFormattingRule; prefix = prefix.replace("$NP", regionMetaData.nationalPrefix); prefix = prefix.replace("$FG", firstGroup); number = prefix + rest; } } } return (number == "NA") ? null : number; } return null; }
javascript
function FormatNumber(regionMetaData, number, intl) { // We lazily parse the format description in the meta data for the region, // so make sure to parse it now if we haven't already done so. ParseFormat(regionMetaData); var formats = regionMetaData.formats; if (!formats) { return null; } for (var n = 0; n < formats.length; ++n) { var format = formats[n]; // The leading digits field is optional. If we don't have it, just // use the matching pattern to qualify numbers. if (format.leadingDigits && !format.leadingDigits.test(number)) continue; if (!format.pattern.test(number)) continue; if (intl) { // If there is no international format, just fall back to the national // format. var internationalFormat = format.internationalFormat; if (!internationalFormat) internationalFormat = format.nationalFormat; // Some regions have numbers that can't be dialed from outside the // country, indicated by "NA" for the international format of that // number format pattern. if (internationalFormat == "NA") return null; // Prepend "+" and the country code. number = "+" + regionMetaData.countryCode + " " + number.replace(format.pattern, internationalFormat); } else { number = number.replace(format.pattern, format.nationalFormat); // The region has a national prefix formatting rule, and it can be overwritten // by each actual number format rule. var nationalPrefixFormattingRule = regionMetaData.nationalPrefixFormattingRule; if (format.nationalPrefixFormattingRule) nationalPrefixFormattingRule = format.nationalPrefixFormattingRule; if (nationalPrefixFormattingRule) { // The prefix formatting rule contains two magic markers, "$NP" and "$FG". // "$NP" will be replaced by the national prefix, and "$FG" with the // first group of numbers. var match = number.match(SPLIT_FIRST_GROUP); if (match) { var firstGroup = match[1]; var rest = match[2]; var prefix = nationalPrefixFormattingRule; prefix = prefix.replace("$NP", regionMetaData.nationalPrefix); prefix = prefix.replace("$FG", firstGroup); number = prefix + rest; } } } return (number == "NA") ? null : number; } return null; }
[ "function", "FormatNumber", "(", "regionMetaData", ",", "number", ",", "intl", ")", "{", "// We lazily parse the format description in the meta data for the region,", "// so make sure to parse it now if we haven't already done so.", "ParseFormat", "(", "regionMetaData", ")", ";", "var", "formats", "=", "regionMetaData", ".", "formats", ";", "if", "(", "!", "formats", ")", "{", "return", "null", ";", "}", "for", "(", "var", "n", "=", "0", ";", "n", "<", "formats", ".", "length", ";", "++", "n", ")", "{", "var", "format", "=", "formats", "[", "n", "]", ";", "// The leading digits field is optional. If we don't have it, just", "// use the matching pattern to qualify numbers.", "if", "(", "format", ".", "leadingDigits", "&&", "!", "format", ".", "leadingDigits", ".", "test", "(", "number", ")", ")", "continue", ";", "if", "(", "!", "format", ".", "pattern", ".", "test", "(", "number", ")", ")", "continue", ";", "if", "(", "intl", ")", "{", "// If there is no international format, just fall back to the national", "// format.", "var", "internationalFormat", "=", "format", ".", "internationalFormat", ";", "if", "(", "!", "internationalFormat", ")", "internationalFormat", "=", "format", ".", "nationalFormat", ";", "// Some regions have numbers that can't be dialed from outside the", "// country, indicated by \"NA\" for the international format of that", "// number format pattern.", "if", "(", "internationalFormat", "==", "\"NA\"", ")", "return", "null", ";", "// Prepend \"+\" and the country code.", "number", "=", "\"+\"", "+", "regionMetaData", ".", "countryCode", "+", "\" \"", "+", "number", ".", "replace", "(", "format", ".", "pattern", ",", "internationalFormat", ")", ";", "}", "else", "{", "number", "=", "number", ".", "replace", "(", "format", ".", "pattern", ",", "format", ".", "nationalFormat", ")", ";", "// The region has a national prefix formatting rule, and it can be overwritten", "// by each actual number format rule.", "var", "nationalPrefixFormattingRule", "=", "regionMetaData", ".", "nationalPrefixFormattingRule", ";", "if", "(", "format", ".", "nationalPrefixFormattingRule", ")", "nationalPrefixFormattingRule", "=", "format", ".", "nationalPrefixFormattingRule", ";", "if", "(", "nationalPrefixFormattingRule", ")", "{", "// The prefix formatting rule contains two magic markers, \"$NP\" and \"$FG\".", "// \"$NP\" will be replaced by the national prefix, and \"$FG\" with the", "// first group of numbers.", "var", "match", "=", "number", ".", "match", "(", "SPLIT_FIRST_GROUP", ")", ";", "if", "(", "match", ")", "{", "var", "firstGroup", "=", "match", "[", "1", "]", ";", "var", "rest", "=", "match", "[", "2", "]", ";", "var", "prefix", "=", "nationalPrefixFormattingRule", ";", "prefix", "=", "prefix", ".", "replace", "(", "\"$NP\"", ",", "regionMetaData", ".", "nationalPrefix", ")", ";", "prefix", "=", "prefix", ".", "replace", "(", "\"$FG\"", ",", "firstGroup", ")", ";", "number", "=", "prefix", "+", "rest", ";", "}", "}", "}", "return", "(", "number", "==", "\"NA\"", ")", "?", "null", ":", "number", ";", "}", "return", "null", ";", "}" ]
Format a national number for a given region. The boolean flag "intl" indicates whether we want the national or international format.
[ "Format", "a", "national", "number", "for", "a", "given", "region", ".", "The", "boolean", "flag", "intl", "indicates", "whether", "we", "want", "the", "national", "or", "international", "format", "." ]
1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c
https://github.com/upptalk/upptalk.js/blob/1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c/dist/upptalk.js#L1896-L1951
39,744
upptalk/upptalk.js
dist/upptalk.js
IsNationalNumber
function IsNationalNumber(number, md) { return IsValidNumber(number, md) && md.nationalPattern.test(number); }
javascript
function IsNationalNumber(number, md) { return IsValidNumber(number, md) && md.nationalPattern.test(number); }
[ "function", "IsNationalNumber", "(", "number", ",", "md", ")", "{", "return", "IsValidNumber", "(", "number", ",", "md", ")", "&&", "md", ".", "nationalPattern", ".", "test", "(", "number", ")", ";", "}" ]
Check whether the number is a valid national number for the given region.
[ "Check", "whether", "the", "number", "is", "a", "valid", "national", "number", "for", "the", "given", "region", "." ]
1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c
https://github.com/upptalk/upptalk.js/blob/1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c/dist/upptalk.js#L1991-L1993
39,745
upptalk/upptalk.js
dist/upptalk.js
ParseCountryCode
function ParseCountryCode(number) { for (var n = 1; n <= 3; ++n) { var cc = number.substr(0,n); if (dataBase[cc]) return cc; } return null; }
javascript
function ParseCountryCode(number) { for (var n = 1; n <= 3; ++n) { var cc = number.substr(0,n); if (dataBase[cc]) return cc; } return null; }
[ "function", "ParseCountryCode", "(", "number", ")", "{", "for", "(", "var", "n", "=", "1", ";", "n", "<=", "3", ";", "++", "n", ")", "{", "var", "cc", "=", "number", ".", "substr", "(", "0", ",", "n", ")", ";", "if", "(", "dataBase", "[", "cc", "]", ")", "return", "cc", ";", "}", "return", "null", ";", "}" ]
Determine the country code a number starts with, or return null if its not a valid country code.
[ "Determine", "the", "country", "code", "a", "number", "starts", "with", "or", "return", "null", "if", "its", "not", "a", "valid", "country", "code", "." ]
1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c
https://github.com/upptalk/upptalk.js/blob/1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c/dist/upptalk.js#L1997-L2004
39,746
upptalk/upptalk.js
dist/upptalk.js
ParseInternationalNumber
function ParseInternationalNumber(number) { var ret; // Parse and strip the country code. var countryCode = ParseCountryCode(number); if (!countryCode) return null; number = number.substr(countryCode.length); // Lookup the meta data for the region (or regions) and if the rest of // the number parses for that region, return the parsed number. var entry = dataBase[countryCode]; if (Array.isArray(entry)) { for (var n = 0; n < entry.length; ++n) { if (typeof entry[n] == "string") entry[n] = ParseMetaData(countryCode, entry[n]); if (n > 0) entry[n].formats = entry[0].formats; ret = ParseNationalNumber(number, entry[n]) if (ret) return ret; } return null; } if (typeof entry == "string") entry = dataBase[countryCode] = ParseMetaData(countryCode, entry); return ParseNationalNumber(number, entry); }
javascript
function ParseInternationalNumber(number) { var ret; // Parse and strip the country code. var countryCode = ParseCountryCode(number); if (!countryCode) return null; number = number.substr(countryCode.length); // Lookup the meta data for the region (or regions) and if the rest of // the number parses for that region, return the parsed number. var entry = dataBase[countryCode]; if (Array.isArray(entry)) { for (var n = 0; n < entry.length; ++n) { if (typeof entry[n] == "string") entry[n] = ParseMetaData(countryCode, entry[n]); if (n > 0) entry[n].formats = entry[0].formats; ret = ParseNationalNumber(number, entry[n]) if (ret) return ret; } return null; } if (typeof entry == "string") entry = dataBase[countryCode] = ParseMetaData(countryCode, entry); return ParseNationalNumber(number, entry); }
[ "function", "ParseInternationalNumber", "(", "number", ")", "{", "var", "ret", ";", "// Parse and strip the country code.", "var", "countryCode", "=", "ParseCountryCode", "(", "number", ")", ";", "if", "(", "!", "countryCode", ")", "return", "null", ";", "number", "=", "number", ".", "substr", "(", "countryCode", ".", "length", ")", ";", "// Lookup the meta data for the region (or regions) and if the rest of", "// the number parses for that region, return the parsed number.", "var", "entry", "=", "dataBase", "[", "countryCode", "]", ";", "if", "(", "Array", ".", "isArray", "(", "entry", ")", ")", "{", "for", "(", "var", "n", "=", "0", ";", "n", "<", "entry", ".", "length", ";", "++", "n", ")", "{", "if", "(", "typeof", "entry", "[", "n", "]", "==", "\"string\"", ")", "entry", "[", "n", "]", "=", "ParseMetaData", "(", "countryCode", ",", "entry", "[", "n", "]", ")", ";", "if", "(", "n", ">", "0", ")", "entry", "[", "n", "]", ".", "formats", "=", "entry", "[", "0", "]", ".", "formats", ";", "ret", "=", "ParseNationalNumber", "(", "number", ",", "entry", "[", "n", "]", ")", "if", "(", "ret", ")", "return", "ret", ";", "}", "return", "null", ";", "}", "if", "(", "typeof", "entry", "==", "\"string\"", ")", "entry", "=", "dataBase", "[", "countryCode", "]", "=", "ParseMetaData", "(", "countryCode", ",", "entry", ")", ";", "return", "ParseNationalNumber", "(", "number", ",", "entry", ")", ";", "}" ]
Parse an international number that starts with the country code. Return null if the number is not a valid international number.
[ "Parse", "an", "international", "number", "that", "starts", "with", "the", "country", "code", ".", "Return", "null", "if", "the", "number", "is", "not", "a", "valid", "international", "number", "." ]
1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c
https://github.com/upptalk/upptalk.js/blob/1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c/dist/upptalk.js#L2008-L2035
39,747
upptalk/upptalk.js
dist/upptalk.js
ParseNumber
function ParseNumber(number, defaultRegion) { var ret; // Remove formating characters and whitespace. number = PhoneNumberNormalizer.Normalize(number); // If there is no defaultRegion, we can't parse international access codes. if (!defaultRegion && number[0] !== '+') return null; // Detect and strip leading '+'. if (number[0] === '+') return ParseInternationalNumber(number.replace(LEADING_PLUS_CHARS_PATTERN, "")); // Lookup the meta data for the given region. var md = FindMetaDataForRegion(defaultRegion.toUpperCase()); // See if the number starts with an international prefix, and if the // number resulting from stripping the code is valid, then remove the // prefix and flag the number as international. if (md.internationalPrefix.test(number)) { var possibleNumber = number.replace(md.internationalPrefix, ""); ret = ParseInternationalNumber(possibleNumber) if (ret) return ret; } // This is not an international number. See if its a national one for // the current region. National numbers can start with the national // prefix, or without. if (md.nationalPrefixForParsing) { // Some regions have specific national prefix parse rules. Apply those. var withoutPrefix = number.replace(md.nationalPrefixForParsing, md.nationalPrefixTransformRule || ''); ret = ParseNationalNumber(withoutPrefix, md) if (ret) return ret; } else { // If there is no specific national prefix rule, just strip off the // national prefix from the beginning of the number (if there is one). var nationalPrefix = md.nationalPrefix; if (nationalPrefix && number.indexOf(nationalPrefix) == 0 && (ret = ParseNationalNumber(number.substr(nationalPrefix.length), md))) { return ret; } } ret = ParseNationalNumber(number, md) if (ret) return ret; // Now lets see if maybe its an international number after all, but // without '+' or the international prefix. ret = ParseInternationalNumber(number) if (ret) return ret; // If the number matches the possible numbers of the current region, // return it as a possible number. if (md.possiblePattern.test(number)) return new NationalNumber(md, number); // We couldn't parse the number at all. return null; }
javascript
function ParseNumber(number, defaultRegion) { var ret; // Remove formating characters and whitespace. number = PhoneNumberNormalizer.Normalize(number); // If there is no defaultRegion, we can't parse international access codes. if (!defaultRegion && number[0] !== '+') return null; // Detect and strip leading '+'. if (number[0] === '+') return ParseInternationalNumber(number.replace(LEADING_PLUS_CHARS_PATTERN, "")); // Lookup the meta data for the given region. var md = FindMetaDataForRegion(defaultRegion.toUpperCase()); // See if the number starts with an international prefix, and if the // number resulting from stripping the code is valid, then remove the // prefix and flag the number as international. if (md.internationalPrefix.test(number)) { var possibleNumber = number.replace(md.internationalPrefix, ""); ret = ParseInternationalNumber(possibleNumber) if (ret) return ret; } // This is not an international number. See if its a national one for // the current region. National numbers can start with the national // prefix, or without. if (md.nationalPrefixForParsing) { // Some regions have specific national prefix parse rules. Apply those. var withoutPrefix = number.replace(md.nationalPrefixForParsing, md.nationalPrefixTransformRule || ''); ret = ParseNationalNumber(withoutPrefix, md) if (ret) return ret; } else { // If there is no specific national prefix rule, just strip off the // national prefix from the beginning of the number (if there is one). var nationalPrefix = md.nationalPrefix; if (nationalPrefix && number.indexOf(nationalPrefix) == 0 && (ret = ParseNationalNumber(number.substr(nationalPrefix.length), md))) { return ret; } } ret = ParseNationalNumber(number, md) if (ret) return ret; // Now lets see if maybe its an international number after all, but // without '+' or the international prefix. ret = ParseInternationalNumber(number) if (ret) return ret; // If the number matches the possible numbers of the current region, // return it as a possible number. if (md.possiblePattern.test(number)) return new NationalNumber(md, number); // We couldn't parse the number at all. return null; }
[ "function", "ParseNumber", "(", "number", ",", "defaultRegion", ")", "{", "var", "ret", ";", "// Remove formating characters and whitespace.", "number", "=", "PhoneNumberNormalizer", ".", "Normalize", "(", "number", ")", ";", "// If there is no defaultRegion, we can't parse international access codes.", "if", "(", "!", "defaultRegion", "&&", "number", "[", "0", "]", "!==", "'+'", ")", "return", "null", ";", "// Detect and strip leading '+'.", "if", "(", "number", "[", "0", "]", "===", "'+'", ")", "return", "ParseInternationalNumber", "(", "number", ".", "replace", "(", "LEADING_PLUS_CHARS_PATTERN", ",", "\"\"", ")", ")", ";", "// Lookup the meta data for the given region.", "var", "md", "=", "FindMetaDataForRegion", "(", "defaultRegion", ".", "toUpperCase", "(", ")", ")", ";", "// See if the number starts with an international prefix, and if the", "// number resulting from stripping the code is valid, then remove the", "// prefix and flag the number as international.", "if", "(", "md", ".", "internationalPrefix", ".", "test", "(", "number", ")", ")", "{", "var", "possibleNumber", "=", "number", ".", "replace", "(", "md", ".", "internationalPrefix", ",", "\"\"", ")", ";", "ret", "=", "ParseInternationalNumber", "(", "possibleNumber", ")", "if", "(", "ret", ")", "return", "ret", ";", "}", "// This is not an international number. See if its a national one for", "// the current region. National numbers can start with the national", "// prefix, or without.", "if", "(", "md", ".", "nationalPrefixForParsing", ")", "{", "// Some regions have specific national prefix parse rules. Apply those.", "var", "withoutPrefix", "=", "number", ".", "replace", "(", "md", ".", "nationalPrefixForParsing", ",", "md", ".", "nationalPrefixTransformRule", "||", "''", ")", ";", "ret", "=", "ParseNationalNumber", "(", "withoutPrefix", ",", "md", ")", "if", "(", "ret", ")", "return", "ret", ";", "}", "else", "{", "// If there is no specific national prefix rule, just strip off the", "// national prefix from the beginning of the number (if there is one).", "var", "nationalPrefix", "=", "md", ".", "nationalPrefix", ";", "if", "(", "nationalPrefix", "&&", "number", ".", "indexOf", "(", "nationalPrefix", ")", "==", "0", "&&", "(", "ret", "=", "ParseNationalNumber", "(", "number", ".", "substr", "(", "nationalPrefix", ".", "length", ")", ",", "md", ")", ")", ")", "{", "return", "ret", ";", "}", "}", "ret", "=", "ParseNationalNumber", "(", "number", ",", "md", ")", "if", "(", "ret", ")", "return", "ret", ";", "// Now lets see if maybe its an international number after all, but", "// without '+' or the international prefix.", "ret", "=", "ParseInternationalNumber", "(", "number", ")", "if", "(", "ret", ")", "return", "ret", ";", "// If the number matches the possible numbers of the current region,", "// return it as a possible number.", "if", "(", "md", ".", "possiblePattern", ".", "test", "(", "number", ")", ")", "return", "new", "NationalNumber", "(", "md", ",", "number", ")", ";", "// We couldn't parse the number at all.", "return", "null", ";", "}" ]
Parse a number and transform it into the national format, removing any international dial prefixes and country codes.
[ "Parse", "a", "number", "and", "transform", "it", "into", "the", "national", "format", "removing", "any", "international", "dial", "prefixes", "and", "country", "codes", "." ]
1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c
https://github.com/upptalk/upptalk.js/blob/1b457c1a23c4ac07bcb4b1d8b9b1ec37037a415c/dist/upptalk.js#L2051-L2114
39,748
kubosho/kotori
src/cli/cli.js
translateOptions
function translateOptions(cliOptions) { return { config: cliOptions.config, output: cliOptions.output, watch : cliOptions.watch }; }
javascript
function translateOptions(cliOptions) { return { config: cliOptions.config, output: cliOptions.output, watch : cliOptions.watch }; }
[ "function", "translateOptions", "(", "cliOptions", ")", "{", "return", "{", "config", ":", "cliOptions", ".", "config", ",", "output", ":", "cliOptions", ".", "output", ",", "watch", ":", "cliOptions", ".", "watch", "}", ";", "}" ]
Translates the CLI options into the options expected by the CLIEngine @param {Object} cliOptions - The CLI options object (optionator format) @returns {Object} The options object for the CLIEngine @private
[ "Translates", "the", "CLI", "options", "into", "the", "options", "expected", "by", "the", "CLIEngine" ]
4a869d470408db17733caf9dabe67ecaa20cf4b7
https://github.com/kubosho/kotori/blob/4a869d470408db17733caf9dabe67ecaa20cf4b7/src/cli/cli.js#L12-L18
39,749
noderaider/repackage
jspm_packages/npm/[email protected]/lib/transformation/helpers/build-react-transformer.js
buildJSXOpeningElementAttributes
function buildJSXOpeningElementAttributes(attribs, file) { var _props = []; var objs = []; var pushProps = function pushProps() { if (!_props.length) return; objs.push(t.objectExpression(_props)); _props = []; }; while (attribs.length) { var prop = attribs.shift(); if (t.isJSXSpreadAttribute(prop)) { pushProps(); objs.push(prop.argument); } else { _props.push(prop); } } pushProps(); if (objs.length === 1) { // only one object attribs = objs[0]; } else { // looks like we have multiple objects if (!t.isObjectExpression(objs[0])) { objs.unshift(t.objectExpression([])); } // spread it attribs = t.callExpression(file.addHelper("extends"), objs); } return attribs; }
javascript
function buildJSXOpeningElementAttributes(attribs, file) { var _props = []; var objs = []; var pushProps = function pushProps() { if (!_props.length) return; objs.push(t.objectExpression(_props)); _props = []; }; while (attribs.length) { var prop = attribs.shift(); if (t.isJSXSpreadAttribute(prop)) { pushProps(); objs.push(prop.argument); } else { _props.push(prop); } } pushProps(); if (objs.length === 1) { // only one object attribs = objs[0]; } else { // looks like we have multiple objects if (!t.isObjectExpression(objs[0])) { objs.unshift(t.objectExpression([])); } // spread it attribs = t.callExpression(file.addHelper("extends"), objs); } return attribs; }
[ "function", "buildJSXOpeningElementAttributes", "(", "attribs", ",", "file", ")", "{", "var", "_props", "=", "[", "]", ";", "var", "objs", "=", "[", "]", ";", "var", "pushProps", "=", "function", "pushProps", "(", ")", "{", "if", "(", "!", "_props", ".", "length", ")", "return", ";", "objs", ".", "push", "(", "t", ".", "objectExpression", "(", "_props", ")", ")", ";", "_props", "=", "[", "]", ";", "}", ";", "while", "(", "attribs", ".", "length", ")", "{", "var", "prop", "=", "attribs", ".", "shift", "(", ")", ";", "if", "(", "t", ".", "isJSXSpreadAttribute", "(", "prop", ")", ")", "{", "pushProps", "(", ")", ";", "objs", ".", "push", "(", "prop", ".", "argument", ")", ";", "}", "else", "{", "_props", ".", "push", "(", "prop", ")", ";", "}", "}", "pushProps", "(", ")", ";", "if", "(", "objs", ".", "length", "===", "1", ")", "{", "// only one object", "attribs", "=", "objs", "[", "0", "]", ";", "}", "else", "{", "// looks like we have multiple objects", "if", "(", "!", "t", ".", "isObjectExpression", "(", "objs", "[", "0", "]", ")", ")", "{", "objs", ".", "unshift", "(", "t", ".", "objectExpression", "(", "[", "]", ")", ")", ";", "}", "// spread it", "attribs", "=", "t", ".", "callExpression", "(", "file", ".", "addHelper", "(", "\"extends\"", ")", ",", "objs", ")", ";", "}", "return", "attribs", ";", "}" ]
The logic for this is quite terse. It's because we need to support spread elements. We loop over all attributes, breaking on spreads, we then push a new object containg all prior attributes to an array for later processing.
[ "The", "logic", "for", "this", "is", "quite", "terse", ".", "It", "s", "because", "we", "need", "to", "support", "spread", "elements", ".", "We", "loop", "over", "all", "attributes", "breaking", "on", "spreads", "we", "then", "push", "a", "new", "object", "containg", "all", "prior", "attributes", "to", "an", "array", "for", "later", "processing", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/transformation/helpers/build-react-transformer.js#L157-L194
39,750
jonathantneal/reshape-tape
index.js
requireOrThrow
function requireOrThrow(name) { try { return require(name); } catch (error) { log.fail('reshape-tape', `${name} failed to load`); return process.exit(1); } }
javascript
function requireOrThrow(name) { try { return require(name); } catch (error) { log.fail('reshape-tape', `${name} failed to load`); return process.exit(1); } }
[ "function", "requireOrThrow", "(", "name", ")", "{", "try", "{", "return", "require", "(", "name", ")", ";", "}", "catch", "(", "error", ")", "{", "log", ".", "fail", "(", "'reshape-tape'", ",", "`", "${", "name", "}", "`", ")", ";", "return", "process", ".", "exit", "(", "1", ")", ";", "}", "}" ]
load modules or throw an error
[ "load", "modules", "or", "throw", "an", "error" ]
af8be531ea46f7e4bacf65fe01673f0dd8e28351
https://github.com/jonathantneal/reshape-tape/blob/af8be531ea46f7e4bacf65fe01673f0dd8e28351/index.js#L138-L146
39,751
jonathantneal/reshape-tape
index.js
readFile
function readFile(filename) { return new Promise( (resolve, reject) => fs.readFile(filename, 'utf8', (error, data) => error ? reject(error) : resolve(data) ) ); }
javascript
function readFile(filename) { return new Promise( (resolve, reject) => fs.readFile(filename, 'utf8', (error, data) => error ? reject(error) : resolve(data) ) ); }
[ "function", "readFile", "(", "filename", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "fs", ".", "readFile", "(", "filename", ",", "'utf8'", ",", "(", "error", ",", "data", ")", "=>", "error", "?", "reject", "(", "error", ")", ":", "resolve", "(", "data", ")", ")", ")", ";", "}" ]
Promise fs.readFile
[ "Promise", "fs", ".", "readFile" ]
af8be531ea46f7e4bacf65fe01673f0dd8e28351
https://github.com/jonathantneal/reshape-tape/blob/af8be531ea46f7e4bacf65fe01673f0dd8e28351/index.js#L149-L155
39,752
jonathantneal/reshape-tape
index.js
writeFile
function writeFile(filename, data) { return new Promise( (resolve, reject) => fs.writeFile(filename, data, (error) => error ? reject(error) : resolve() ) ); }
javascript
function writeFile(filename, data) { return new Promise( (resolve, reject) => fs.writeFile(filename, data, (error) => error ? reject(error) : resolve() ) ); }
[ "function", "writeFile", "(", "filename", ",", "data", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "fs", ".", "writeFile", "(", "filename", ",", "data", ",", "(", "error", ")", "=>", "error", "?", "reject", "(", "error", ")", ":", "resolve", "(", ")", ")", ")", ";", "}" ]
Promise fs.writeFile
[ "Promise", "fs", ".", "writeFile" ]
af8be531ea46f7e4bacf65fe01673f0dd8e28351
https://github.com/jonathantneal/reshape-tape/blob/af8be531ea46f7e4bacf65fe01673f0dd8e28351/index.js#L158-L164
39,753
gcochard/chrome-stub
lib/chrome/StorageArea.js
defer
function defer(cb) { if (storage.LATENCY === 0 && typeof process !== 'undefined') { process.nextTick(cb); } else { setTimeout(cb, storage.LATENCY); } }
javascript
function defer(cb) { if (storage.LATENCY === 0 && typeof process !== 'undefined') { process.nextTick(cb); } else { setTimeout(cb, storage.LATENCY); } }
[ "function", "defer", "(", "cb", ")", "{", "if", "(", "storage", ".", "LATENCY", "===", "0", "&&", "typeof", "process", "!==", "'undefined'", ")", "{", "process", ".", "nextTick", "(", "cb", ")", ";", "}", "else", "{", "setTimeout", "(", "cb", ",", "storage", ".", "LATENCY", ")", ";", "}", "}" ]
Defer callback execution to the next process tick, or optionally set chrome.storage.LATENCY to simulate latency in storage access
[ "Defer", "callback", "execution", "to", "the", "next", "process", "tick", "or", "optionally", "set", "chrome", ".", "storage", ".", "LATENCY", "to", "simulate", "latency", "in", "storage", "access" ]
af6a306d19e9b3ccb2093fc95ccb90234c2b36d3
https://github.com/gcochard/chrome-stub/blob/af6a306d19e9b3ccb2093fc95ccb90234c2b36d3/lib/chrome/StorageArea.js#L14-L20
39,754
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/introspection.js
getSource
function getSource() { var node = this.node; if (node.end) { return this.hub.file.code.slice(node.start, node.end); } else { return ""; } }
javascript
function getSource() { var node = this.node; if (node.end) { return this.hub.file.code.slice(node.start, node.end); } else { return ""; } }
[ "function", "getSource", "(", ")", "{", "var", "node", "=", "this", ".", "node", ";", "if", "(", "node", ".", "end", ")", "{", "return", "this", ".", "hub", ".", "file", ".", "code", ".", "slice", "(", "node", ".", "start", ",", "node", ".", "end", ")", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}" ]
Get the source code associated with this node.
[ "Get", "the", "source", "code", "associated", "with", "this", "node", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/introspection.js#L258-L265
39,755
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/introspection.js
_guessExecutionStatusRelativeTo
function _guessExecutionStatusRelativeTo(target) { // check if the two paths are in different functions, we can't track execution of these var targetFuncParent = target.scope.getFunctionParent(); var selfFuncParent = this.scope.getFunctionParent(); if (targetFuncParent !== selfFuncParent) { return "function"; } var targetPaths = target.getAncestry(); //if (targetPaths.indexOf(this) >= 0) return "after"; var selfPaths = this.getAncestry(); // get ancestor where the branches intersect var commonPath; var targetIndex; var selfIndex; for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { var selfPath = selfPaths[selfIndex]; targetIndex = targetPaths.indexOf(selfPath); if (targetIndex >= 0) { commonPath = selfPath; break; } } if (!commonPath) { return "before"; } // get the relationship paths that associate these nodes to their common ancestor var targetRelationship = targetPaths[targetIndex - 1]; var selfRelationship = selfPaths[selfIndex - 1]; if (!targetRelationship || !selfRelationship) { return "before"; } // container list so let's see which one is after the other if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { return targetRelationship.key > selfRelationship.key ? "before" : "after"; } // otherwise we're associated by a parent node, check which key comes before the other var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); return targetKeyPosition > selfKeyPosition ? "before" : "after"; }
javascript
function _guessExecutionStatusRelativeTo(target) { // check if the two paths are in different functions, we can't track execution of these var targetFuncParent = target.scope.getFunctionParent(); var selfFuncParent = this.scope.getFunctionParent(); if (targetFuncParent !== selfFuncParent) { return "function"; } var targetPaths = target.getAncestry(); //if (targetPaths.indexOf(this) >= 0) return "after"; var selfPaths = this.getAncestry(); // get ancestor where the branches intersect var commonPath; var targetIndex; var selfIndex; for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { var selfPath = selfPaths[selfIndex]; targetIndex = targetPaths.indexOf(selfPath); if (targetIndex >= 0) { commonPath = selfPath; break; } } if (!commonPath) { return "before"; } // get the relationship paths that associate these nodes to their common ancestor var targetRelationship = targetPaths[targetIndex - 1]; var selfRelationship = selfPaths[selfIndex - 1]; if (!targetRelationship || !selfRelationship) { return "before"; } // container list so let's see which one is after the other if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { return targetRelationship.key > selfRelationship.key ? "before" : "after"; } // otherwise we're associated by a parent node, check which key comes before the other var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); return targetKeyPosition > selfKeyPosition ? "before" : "after"; }
[ "function", "_guessExecutionStatusRelativeTo", "(", "target", ")", "{", "// check if the two paths are in different functions, we can't track execution of these", "var", "targetFuncParent", "=", "target", ".", "scope", ".", "getFunctionParent", "(", ")", ";", "var", "selfFuncParent", "=", "this", ".", "scope", ".", "getFunctionParent", "(", ")", ";", "if", "(", "targetFuncParent", "!==", "selfFuncParent", ")", "{", "return", "\"function\"", ";", "}", "var", "targetPaths", "=", "target", ".", "getAncestry", "(", ")", ";", "//if (targetPaths.indexOf(this) >= 0) return \"after\";", "var", "selfPaths", "=", "this", ".", "getAncestry", "(", ")", ";", "// get ancestor where the branches intersect", "var", "commonPath", ";", "var", "targetIndex", ";", "var", "selfIndex", ";", "for", "(", "selfIndex", "=", "0", ";", "selfIndex", "<", "selfPaths", ".", "length", ";", "selfIndex", "++", ")", "{", "var", "selfPath", "=", "selfPaths", "[", "selfIndex", "]", ";", "targetIndex", "=", "targetPaths", ".", "indexOf", "(", "selfPath", ")", ";", "if", "(", "targetIndex", ">=", "0", ")", "{", "commonPath", "=", "selfPath", ";", "break", ";", "}", "}", "if", "(", "!", "commonPath", ")", "{", "return", "\"before\"", ";", "}", "// get the relationship paths that associate these nodes to their common ancestor", "var", "targetRelationship", "=", "targetPaths", "[", "targetIndex", "-", "1", "]", ";", "var", "selfRelationship", "=", "selfPaths", "[", "selfIndex", "-", "1", "]", ";", "if", "(", "!", "targetRelationship", "||", "!", "selfRelationship", ")", "{", "return", "\"before\"", ";", "}", "// container list so let's see which one is after the other", "if", "(", "targetRelationship", ".", "listKey", "&&", "targetRelationship", ".", "container", "===", "selfRelationship", ".", "container", ")", "{", "return", "targetRelationship", ".", "key", ">", "selfRelationship", ".", "key", "?", "\"before\"", ":", "\"after\"", ";", "}", "// otherwise we're associated by a parent node, check which key comes before the other", "var", "targetKeyPosition", "=", "t", ".", "VISITOR_KEYS", "[", "targetRelationship", ".", "type", "]", ".", "indexOf", "(", "targetRelationship", ".", "key", ")", ";", "var", "selfKeyPosition", "=", "t", ".", "VISITOR_KEYS", "[", "selfRelationship", ".", "type", "]", ".", "indexOf", "(", "selfRelationship", ".", "key", ")", ";", "return", "targetKeyPosition", ">", "selfKeyPosition", "?", "\"before\"", ":", "\"after\"", ";", "}" ]
Given a `target` check the execution status of it relative to the current path. "Execution status" simply refers to where or not we **think** this will execuete before or after the input `target` element.
[ "Given", "a", "target", "check", "the", "execution", "status", "of", "it", "relative", "to", "the", "current", "path", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/introspection.js#L282-L327
39,756
briancsparks/aws-json
aws-json.js
function(item) { var result = {}; _.each(item, function(value, key) { if (fix[key]) { result[key] = parseItem(fix[key](value)); } else if (key === 'Tags') { result[key] = parseTags(value); } else { result[key] = parseItem(value); } }); return result; }
javascript
function(item) { var result = {}; _.each(item, function(value, key) { if (fix[key]) { result[key] = parseItem(fix[key](value)); } else if (key === 'Tags') { result[key] = parseTags(value); } else { result[key] = parseItem(value); } }); return result; }
[ "function", "(", "item", ")", "{", "var", "result", "=", "{", "}", ";", "_", ".", "each", "(", "item", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "fix", "[", "key", "]", ")", "{", "result", "[", "key", "]", "=", "parseItem", "(", "fix", "[", "key", "]", "(", "value", ")", ")", ";", "}", "else", "if", "(", "key", "===", "'Tags'", ")", "{", "result", "[", "key", "]", "=", "parseTags", "(", "value", ")", ";", "}", "else", "{", "result", "[", "key", "]", "=", "parseItem", "(", "value", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Parse an object that we know is an AWS object.
[ "Parse", "an", "object", "that", "we", "know", "is", "an", "AWS", "object", "." ]
df224093d0d5018834625f7a6fa640773814a311
https://github.com/briancsparks/aws-json/blob/df224093d0d5018834625f7a6fa640773814a311/aws-json.js#L99-L113
39,757
briancsparks/aws-json
aws-json.js
function(item) { var result; if (_.isArray(item)) { result = []; _.each(item, function(value) { result.push(parseItem(value)); }); return result; } /* otherwise */ if (_.isObject(item)) { return parseObject(item); } /* otherwise -- just a normal (non-compound) item */ return item; }
javascript
function(item) { var result; if (_.isArray(item)) { result = []; _.each(item, function(value) { result.push(parseItem(value)); }); return result; } /* otherwise */ if (_.isObject(item)) { return parseObject(item); } /* otherwise -- just a normal (non-compound) item */ return item; }
[ "function", "(", "item", ")", "{", "var", "result", ";", "if", "(", "_", ".", "isArray", "(", "item", ")", ")", "{", "result", "=", "[", "]", ";", "_", ".", "each", "(", "item", ",", "function", "(", "value", ")", "{", "result", ".", "push", "(", "parseItem", "(", "value", ")", ")", ";", "}", ")", ";", "return", "result", ";", "}", "/* otherwise */", "if", "(", "_", ".", "isObject", "(", "item", ")", ")", "{", "return", "parseObject", "(", "item", ")", ";", "}", "/* otherwise -- just a normal (non-compound) item */", "return", "item", ";", "}" ]
Parse an item - it might be an Array, an Object, or a POD.
[ "Parse", "an", "item", "-", "it", "might", "be", "an", "Array", "an", "Object", "or", "a", "POD", "." ]
df224093d0d5018834625f7a6fa640773814a311
https://github.com/briancsparks/aws-json/blob/df224093d0d5018834625f7a6fa640773814a311/aws-json.js#L118-L136
39,758
myelements/myelements.jquery
lib/client/lib/localforage/localforage.js
iterate
function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (cursor) { var result = iterator(cursor.value, cursor.key); if (result !== void(0)) { resolve(result); } else { cursor["continue"](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })["catch"](reject); }); executeDeferedCallback(promise, callback); return promise; }
javascript
function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (cursor) { var result = iterator(cursor.value, cursor.key); if (result !== void(0)) { resolve(result); } else { cursor["continue"](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })["catch"](reject); }); executeDeferedCallback(promise, callback); return promise; }
[ "function", "iterate", "(", "iterator", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "promise", "=", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "self", ".", "ready", "(", ")", ".", "then", "(", "function", "(", ")", "{", "var", "dbInfo", "=", "self", ".", "_dbInfo", ";", "var", "store", "=", "dbInfo", ".", "db", ".", "transaction", "(", "dbInfo", ".", "storeName", ",", "'readonly'", ")", ".", "objectStore", "(", "dbInfo", ".", "storeName", ")", ";", "var", "req", "=", "store", ".", "openCursor", "(", ")", ";", "req", ".", "onsuccess", "=", "function", "(", ")", "{", "var", "cursor", "=", "req", ".", "result", ";", "if", "(", "cursor", ")", "{", "var", "result", "=", "iterator", "(", "cursor", ".", "value", ",", "cursor", ".", "key", ")", ";", "if", "(", "result", "!==", "void", "(", "0", ")", ")", "{", "resolve", "(", "result", ")", ";", "}", "else", "{", "cursor", "[", "\"continue\"", "]", "(", ")", ";", "}", "}", "else", "{", "resolve", "(", ")", ";", "}", "}", ";", "req", ".", "onerror", "=", "function", "(", ")", "{", "reject", "(", "req", ".", "error", ")", ";", "}", ";", "}", ")", "[", "\"catch\"", "]", "(", "reject", ")", ";", "}", ")", ";", "executeDeferedCallback", "(", "promise", ",", "callback", ")", ";", "return", "promise", ";", "}" ]
Iterate over all items stored in database.
[ "Iterate", "over", "all", "items", "stored", "in", "database", "." ]
0123edec30fc70ea494611695b5b2593e4f23745
https://github.com/myelements/myelements.jquery/blob/0123edec30fc70ea494611695b5b2593e4f23745/lib/client/lib/localforage/localforage.js#L779-L815
39,759
codius-deprecated/codius-engine
lib/compiler.js
function (config) { events.EventEmitter.call(this); this.config = config; this.ignoreFiles = config.ignoreFiles || ['.codiusignore']; this._filesystem = Compiler.RealFilesystem; }
javascript
function (config) { events.EventEmitter.call(this); this.config = config; this.ignoreFiles = config.ignoreFiles || ['.codiusignore']; this._filesystem = Compiler.RealFilesystem; }
[ "function", "(", "config", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "config", "=", "config", ";", "this", ".", "ignoreFiles", "=", "config", ".", "ignoreFiles", "||", "[", "'.codiusignore'", "]", ";", "this", ".", "_filesystem", "=", "Compiler", ".", "RealFilesystem", ";", "}" ]
Contracts compiler. This class will parse contract manifests and files and emit events for processing them.
[ "Contracts", "compiler", "." ]
48aaea3d1a0dd2cf755a1905ff040e1667e8d131
https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/compiler.js#L35-L42
39,760
stezu/node-stream
lib/consumers/v1/forEach.js
forEachObj
function forEachObj(stream, onData, onEnd) { var done = _.once(onEnd); stream.on('data', onData); stream.on('error', done); stream.on('end', done); }
javascript
function forEachObj(stream, onData, onEnd) { var done = _.once(onEnd); stream.on('data', onData); stream.on('error', done); stream.on('end', done); }
[ "function", "forEachObj", "(", "stream", ",", "onData", ",", "onEnd", ")", "{", "var", "done", "=", "_", ".", "once", "(", "onEnd", ")", ";", "stream", ".", "on", "(", "'data'", ",", "onData", ")", ";", "stream", ".", "on", "(", "'error'", ",", "done", ")", ";", "stream", ".", "on", "(", "'end'", ",", "done", ")", ";", "}" ]
Read the items in a stream. @private @deprecated @static @since 0.0.1 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onData - Callback for each item in the stream. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Read", "the", "items", "in", "a", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/forEach.js#L17-L23
39,761
stezu/node-stream
lib/consumers/v1/forEach.js
forEach
function forEach(stream, onData, onEnd) { forEachObj(stream, function (chunk) { onData(new Buffer(chunk)); }, onEnd); }
javascript
function forEach(stream, onData, onEnd) { forEachObj(stream, function (chunk) { onData(new Buffer(chunk)); }, onEnd); }
[ "function", "forEach", "(", "stream", ",", "onData", ",", "onEnd", ")", "{", "forEachObj", "(", "stream", ",", "function", "(", "chunk", ")", "{", "onData", "(", "new", "Buffer", "(", "chunk", ")", ")", ";", "}", ",", "onEnd", ")", ";", "}" ]
Read the items in a stream and convert to buffers. @private @deprecated @static @since 0.0.1 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onData - Callback for each item in the stream. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Read", "the", "items", "in", "a", "stream", "and", "convert", "to", "buffers", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/forEach.js#L39-L44
39,762
stezu/node-stream
lib/consumers/v1/forEach.js
forEachJson
function forEachJson(stream, onData, onEnd) { forEach(stream, function (chunk) { var parsed; try { parsed = JSON.parse(chunk); } catch (e) { return stream.emit('error', e); } return onData(parsed); }, onEnd); }
javascript
function forEachJson(stream, onData, onEnd) { forEach(stream, function (chunk) { var parsed; try { parsed = JSON.parse(chunk); } catch (e) { return stream.emit('error', e); } return onData(parsed); }, onEnd); }
[ "function", "forEachJson", "(", "stream", ",", "onData", ",", "onEnd", ")", "{", "forEach", "(", "stream", ",", "function", "(", "chunk", ")", "{", "var", "parsed", ";", "try", "{", "parsed", "=", "JSON", ".", "parse", "(", "chunk", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "stream", ".", "emit", "(", "'error'", ",", "e", ")", ";", "}", "return", "onData", "(", "parsed", ")", ";", "}", ",", "onEnd", ")", ";", "}" ]
Read the items in a stream and parse each item for JSON. @private @deprecated @static @since 0.0.2 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onData - Callback for each item in the stream. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Read", "the", "items", "in", "a", "stream", "and", "parse", "each", "item", "for", "JSON", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/forEach.js#L60-L73
39,763
stezu/node-stream
lib/modifiers/sort.js
sort
function sort(compareFunction) { return pipeline.obj( // collect all items into an array wait.obj(), // sort the array map(function (chunk, next) { // compareFunction can be null, undefined or a Function if (!_.isNil(compareFunction) && !_.isFunction(compareFunction)) { return next(new TypeError('Expected `compareFunction` to be a function.')); } return next(null, chunk.sort(compareFunction)); }), // expand the array so all input items are re-emitted through.obj(function Transform(chunk, enc, next) { var self = this; var len = chunk.length; // recursively add array items to the stream asynchronously (function emitNextItem(i) { setImmediate(function () { self.push(chunk[i]); // keep pushing items to the stream if more items are available if (i < len - 1) { emitNextItem(i + 1); return; } // the array has been depleted next(); }); }(0)); }) ); }
javascript
function sort(compareFunction) { return pipeline.obj( // collect all items into an array wait.obj(), // sort the array map(function (chunk, next) { // compareFunction can be null, undefined or a Function if (!_.isNil(compareFunction) && !_.isFunction(compareFunction)) { return next(new TypeError('Expected `compareFunction` to be a function.')); } return next(null, chunk.sort(compareFunction)); }), // expand the array so all input items are re-emitted through.obj(function Transform(chunk, enc, next) { var self = this; var len = chunk.length; // recursively add array items to the stream asynchronously (function emitNextItem(i) { setImmediate(function () { self.push(chunk[i]); // keep pushing items to the stream if more items are available if (i < len - 1) { emitNextItem(i + 1); return; } // the array has been depleted next(); }); }(0)); }) ); }
[ "function", "sort", "(", "compareFunction", ")", "{", "return", "pipeline", ".", "obj", "(", "// collect all items into an array", "wait", ".", "obj", "(", ")", ",", "// sort the array", "map", "(", "function", "(", "chunk", ",", "next", ")", "{", "// compareFunction can be null, undefined or a Function", "if", "(", "!", "_", ".", "isNil", "(", "compareFunction", ")", "&&", "!", "_", ".", "isFunction", "(", "compareFunction", ")", ")", "{", "return", "next", "(", "new", "TypeError", "(", "'Expected `compareFunction` to be a function.'", ")", ")", ";", "}", "return", "next", "(", "null", ",", "chunk", ".", "sort", "(", "compareFunction", ")", ")", ";", "}", ")", ",", "// expand the array so all input items are re-emitted", "through", ".", "obj", "(", "function", "Transform", "(", "chunk", ",", "enc", ",", "next", ")", "{", "var", "self", "=", "this", ";", "var", "len", "=", "chunk", ".", "length", ";", "// recursively add array items to the stream asynchronously", "(", "function", "emitNextItem", "(", "i", ")", "{", "setImmediate", "(", "function", "(", ")", "{", "self", ".", "push", "(", "chunk", "[", "i", "]", ")", ";", "// keep pushing items to the stream if more items are available", "if", "(", "i", "<", "len", "-", "1", ")", "{", "emitNextItem", "(", "i", "+", "1", ")", ";", "return", ";", "}", "// the array has been depleted", "next", "(", ")", ";", "}", ")", ";", "}", "(", "0", ")", ")", ";", "}", ")", ")", ";", "}" ]
Creates a new stream where all elements of the source stream have been sorted by the Array.sort method. Each value will be emitted individually. *Note:* This method will buffer all contents of the source stream before sending it. You should not use this method if your source stream is large as it could consume large amounts of memory. @static @since 1.3.0 @category Modifiers @param {Function} compareFunction - A function that will be passed directly to Array.sort for item comparison. @returns {Stream.Transform} - Transform stream. @example // sort a stream of numbers objStream // => [10, 3, 9, 2, 4, 1] .pipe(nodeStream.sort()) // => [1, 2, 3, 4, 9, 10]
[ "Creates", "a", "new", "stream", "where", "all", "elements", "of", "the", "source", "stream", "have", "been", "sorted", "by", "the", "Array", ".", "sort", "method", ".", "Each", "value", "will", "be", "emitted", "individually", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/sort.js#L31-L73
39,764
smclab/ti-soap
wsdl.js
function(href, obj) { for (var j in obj) { if (obj.hasOwnProperty(j)) { href.obj[j] = obj[j]; } } }
javascript
function(href, obj) { for (var j in obj) { if (obj.hasOwnProperty(j)) { href.obj[j] = obj[j]; } } }
[ "function", "(", "href", ",", "obj", ")", "{", "for", "(", "var", "j", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "j", ")", ")", "{", "href", ".", "obj", "[", "j", "]", "=", "obj", "[", "j", "]", ";", "}", "}", "}" ]
merge obj with href
[ "merge", "obj", "with", "href" ]
c6ac846351b26ce43423a35f2dd8a9881e062e25
https://github.com/smclab/ti-soap/blob/c6ac846351b26ce43423a35f2dd8a9881e062e25/wsdl.js#L1276-L1282
39,765
SuperheroUI/shCore
src/util/get-decimal.js
getDecimal
function getDecimal(value) { if (!value) { return 0; } var num = value; if (!_.isNumber(value)) { var isNeg = ('-' && _.includes(value, '-')); var regExp = '[^0-9.]'; var numString = value.toString().replace(new RegExp(regExp, 'g'), ''); var numList = numString.split('.'); // numList will always have at least one value in array because we checked for an empty string earlier. numList[0] += '.'; numString = numList.join(''); num = parseFloat(numString); if (!num) { num = 0; } else if (isNeg) { num *= -1; } } return num; }
javascript
function getDecimal(value) { if (!value) { return 0; } var num = value; if (!_.isNumber(value)) { var isNeg = ('-' && _.includes(value, '-')); var regExp = '[^0-9.]'; var numString = value.toString().replace(new RegExp(regExp, 'g'), ''); var numList = numString.split('.'); // numList will always have at least one value in array because we checked for an empty string earlier. numList[0] += '.'; numString = numList.join(''); num = parseFloat(numString); if (!num) { num = 0; } else if (isNeg) { num *= -1; } } return num; }
[ "function", "getDecimal", "(", "value", ")", "{", "if", "(", "!", "value", ")", "{", "return", "0", ";", "}", "var", "num", "=", "value", ";", "if", "(", "!", "_", ".", "isNumber", "(", "value", ")", ")", "{", "var", "isNeg", "=", "(", "'-'", "&&", "_", ".", "includes", "(", "value", ",", "'-'", ")", ")", ";", "var", "regExp", "=", "'[^0-9.]'", ";", "var", "numString", "=", "value", ".", "toString", "(", ")", ".", "replace", "(", "new", "RegExp", "(", "regExp", ",", "'g'", ")", ",", "''", ")", ";", "var", "numList", "=", "numString", ".", "split", "(", "'.'", ")", ";", "// numList will always have at least one value in array because we checked for an empty string earlier.", "numList", "[", "0", "]", "+=", "'.'", ";", "numString", "=", "numList", ".", "join", "(", "''", ")", ";", "num", "=", "parseFloat", "(", "numString", ")", ";", "if", "(", "!", "num", ")", "{", "num", "=", "0", ";", "}", "else", "if", "(", "isNeg", ")", "{", "num", "*=", "-", "1", ";", "}", "}", "return", "num", ";", "}" ]
Get a decimal value from a string or number, remove any unnecessary characters. @param {string} value Alpha characters will be removed and a decimal will be returned. For example if you give it 'b.123' 0.123 will be returned. @returns {number}
[ "Get", "a", "decimal", "value", "from", "a", "string", "or", "number", "remove", "any", "unnecessary", "characters", "." ]
d92e2094a00e1148a5790cd928af70428524fb34
https://github.com/SuperheroUI/shCore/blob/d92e2094a00e1148a5790cd928af70428524fb34/src/util/get-decimal.js#L10-L37
39,766
stezu/node-stream
lib/modifiers/intersperse.js
intersperse
function intersperse(value) { var first = true; return through.obj(function Transform(chunk, enc, next) { // Emit the value for everything but the first item if (first) { first = false; } else { this.push(value); } // Forward the original data next(null, chunk); }); }
javascript
function intersperse(value) { var first = true; return through.obj(function Transform(chunk, enc, next) { // Emit the value for everything but the first item if (first) { first = false; } else { this.push(value); } // Forward the original data next(null, chunk); }); }
[ "function", "intersperse", "(", "value", ")", "{", "var", "first", "=", "true", ";", "return", "through", ".", "obj", "(", "function", "Transform", "(", "chunk", ",", "enc", ",", "next", ")", "{", "// Emit the value for everything but the first item", "if", "(", "first", ")", "{", "first", "=", "false", ";", "}", "else", "{", "this", ".", "push", "(", "value", ")", ";", "}", "// Forward the original data", "next", "(", "null", ",", "chunk", ")", ";", "}", ")", ";", "}" ]
Creates a new stream with the `value` emitted between every item in the source stream. @static @since 1.3.0 @category Modifiers @param {String} value - Value that should be emitted between every existing item. @returns {Stream.Transform} - Transform stream. @example // Log some values to the console with new lines interspersed shoppingList // => ['banana', 'apple', 'orange'] .pipe(nodeStream.intersperse('\n')) .pipe(process.stdout) // => ['banana', '\n', 'apple', '\n', 'orange']
[ "Creates", "a", "new", "stream", "with", "the", "value", "emitted", "between", "every", "item", "in", "the", "source", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/intersperse.js#L22-L37
39,767
jaredhanson/node-functionpool
lib/functionpool/pool.js
Pool
function Pool(options, fn) { if (typeof options == 'function') { fn = options; options = {}; } options = options || {}; if (!fn) { throw new Error('Pool requires a worker function') }; if (fn.length < 1) { throw new Error('Pool worker function must accept done callback as an argument') }; EventEmitter.call(this); this._fn = fn; this._workers = this._createWorkers(options.size || 5); this._working = 0; this._queue = []; var self = this; this.on('task', function() { if (self._workers.length == self._working) { return; } self._dispatch(); }); this.on('done', function() { // TODO: emit a `drain` event if the pool was previously queuing, and now // has slots available if (self._working == 0 && self._queue.length == 0) { self.emit('idle'); } if (self._queue.length == 0) { return; } self._dispatch(); }) }
javascript
function Pool(options, fn) { if (typeof options == 'function') { fn = options; options = {}; } options = options || {}; if (!fn) { throw new Error('Pool requires a worker function') }; if (fn.length < 1) { throw new Error('Pool worker function must accept done callback as an argument') }; EventEmitter.call(this); this._fn = fn; this._workers = this._createWorkers(options.size || 5); this._working = 0; this._queue = []; var self = this; this.on('task', function() { if (self._workers.length == self._working) { return; } self._dispatch(); }); this.on('done', function() { // TODO: emit a `drain` event if the pool was previously queuing, and now // has slots available if (self._working == 0 && self._queue.length == 0) { self.emit('idle'); } if (self._queue.length == 0) { return; } self._dispatch(); }) }
[ "function", "Pool", "(", "options", ",", "fn", ")", "{", "if", "(", "typeof", "options", "==", "'function'", ")", "{", "fn", "=", "options", ";", "options", "=", "{", "}", ";", "}", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "fn", ")", "{", "throw", "new", "Error", "(", "'Pool requires a worker function'", ")", "}", ";", "if", "(", "fn", ".", "length", "<", "1", ")", "{", "throw", "new", "Error", "(", "'Pool worker function must accept done callback as an argument'", ")", "}", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_fn", "=", "fn", ";", "this", ".", "_workers", "=", "this", ".", "_createWorkers", "(", "options", ".", "size", "||", "5", ")", ";", "this", ".", "_working", "=", "0", ";", "this", ".", "_queue", "=", "[", "]", ";", "var", "self", "=", "this", ";", "this", ".", "on", "(", "'task'", ",", "function", "(", ")", "{", "if", "(", "self", ".", "_workers", ".", "length", "==", "self", ".", "_working", ")", "{", "return", ";", "}", "self", ".", "_dispatch", "(", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'done'", ",", "function", "(", ")", "{", "// TODO: emit a `drain` event if the pool was previously queuing, and now", "// has slots available", "if", "(", "self", ".", "_working", "==", "0", "&&", "self", ".", "_queue", ".", "length", "==", "0", ")", "{", "self", ".", "emit", "(", "'idle'", ")", ";", "}", "if", "(", "self", ".", "_queue", ".", "length", "==", "0", ")", "{", "return", ";", "}", "self", ".", "_dispatch", "(", ")", ";", "}", ")", "}" ]
`Pool` constructor. Assigns `fn` to a pool used to execute (potentially expensive) tasks. The pool has a limited size (defaulting to 5), which controls the maximum number of tasks that will be allowed to execute concurrently. After the limit has been reached, tasks will be queued and executed when prior tasks complete. `fn` must accept a `done` callback, which it must invoke with a result (or error) upon completion. Options: - `size` maximum number of tasks allowed to execute concurrently (default: 5) Examples: new Pool(function(name, done) { setTimeout(function() { done(null, 'Hello ' + name) }, 1000); }); new Pool({ size: 3 }, function(x, y, done) { setTimeout(function() { done(null, x + y) }, 5000); }); @param {Object} options @param {Function} fn @api public
[ "Pool", "constructor", "." ]
350a4a9b2e34f115b58477abfda9f2dbe63a0647
https://github.com/jaredhanson/node-functionpool/blob/350a4a9b2e34f115b58477abfda9f2dbe63a0647/lib/functionpool/pool.js#L37-L65
39,768
nlehuen/capisce
lib/capisce.js
_go
function _go() { if(workers < concurrency) { var job = queue.shift(); if(job !== undefined) { var worker = job.shift(); job.push(over); workers++; process.nextTick(function nextTickWorker() { worker.apply(null, job); }); return true; } } return false; }
javascript
function _go() { if(workers < concurrency) { var job = queue.shift(); if(job !== undefined) { var worker = job.shift(); job.push(over); workers++; process.nextTick(function nextTickWorker() { worker.apply(null, job); }); return true; } } return false; }
[ "function", "_go", "(", ")", "{", "if", "(", "workers", "<", "concurrency", ")", "{", "var", "job", "=", "queue", ".", "shift", "(", ")", ";", "if", "(", "job", "!==", "undefined", ")", "{", "var", "worker", "=", "job", ".", "shift", "(", ")", ";", "job", ".", "push", "(", "over", ")", ";", "workers", "++", ";", "process", ".", "nextTick", "(", "function", "nextTickWorker", "(", ")", "{", "worker", ".", "apply", "(", "null", ",", "job", ")", ";", "}", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
This function launches a new worker, if possible It returns true if a new worker was launched, false otherwise.
[ "This", "function", "launches", "a", "new", "worker", "if", "possible", "It", "returns", "true", "if", "a", "new", "worker", "was", "launched", "false", "otherwise", "." ]
2dada7facccf02ebdffabe37746c0ca9f22e9ea8
https://github.com/nlehuen/capisce/blob/2dada7facccf02ebdffabe37746c0ca9f22e9ea8/lib/capisce.js#L32-L46
39,769
divio/djangocms-casper-helpers
helpers.js
function (credentials) { return function () { return this.thenOpen(globals.adminUrl).then(function () { this.fill('#login-form', credentials || globals.credentials, true); }).waitForResource(/login/).thenEvaluate(function () { localStorage.clear(); }); }; }
javascript
function (credentials) { return function () { return this.thenOpen(globals.adminUrl).then(function () { this.fill('#login-form', credentials || globals.credentials, true); }).waitForResource(/login/).thenEvaluate(function () { localStorage.clear(); }); }; }
[ "function", "(", "credentials", ")", "{", "return", "function", "(", ")", "{", "return", "this", ".", "thenOpen", "(", "globals", ".", "adminUrl", ")", ".", "then", "(", "function", "(", ")", "{", "this", ".", "fill", "(", "'#login-form'", ",", "credentials", "||", "globals", ".", "credentials", ",", "true", ")", ";", "}", ")", ".", "waitForResource", "(", "/", "login", "/", ")", ".", "thenEvaluate", "(", "function", "(", ")", "{", "localStorage", ".", "clear", "(", ")", ";", "}", ")", ";", "}", ";", "}" ]
Logs in with the given parameters @param {Object} [credentials=globals.credentials] @param {String} credentials.username @param {String} credentials.password @returns {Function}
[ "Logs", "in", "with", "the", "given", "parameters" ]
200e0f29b01341cba34e7bc9e7d329f81d531b2a
https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/helpers.js#L16-L24
39,770
divio/djangocms-casper-helpers
helpers.js
function (opts) { var that = this; return function () { return this.thenOpen(globals.adminPagesUrl) .waitUntilVisible('.js-cms-pagetree-options') .then(that.expandPageTree()) .then(function () { var pageId; var pageNodeId; var data = ''; var href = ''; if (opts && opts.title) { pageId = that.getPageId(opts.title); pageNodeId = that.getPageNodeId(opts.title); } if (pageId) { data = '[data-node-id="' + pageNodeId + '"]'; href = '[href*="' + pageId + '"]'; } return this.then(function () { this.click('.cms-pagetree-jstree .js-cms-pagetree-options' + data); }) .then(that.waitUntilActionsDropdownLoaded()) .then(function () { this.click('.cms-pagetree-jstree [href*="delete"]' + href); }); }) .waitForUrl(/delete/) .waitUntilVisible('input[type=submit]') .then(function () { this.click('input[type=submit]'); }) .wait(1000) .then(that.waitUntilAllAjaxCallsFinish()); }; }
javascript
function (opts) { var that = this; return function () { return this.thenOpen(globals.adminPagesUrl) .waitUntilVisible('.js-cms-pagetree-options') .then(that.expandPageTree()) .then(function () { var pageId; var pageNodeId; var data = ''; var href = ''; if (opts && opts.title) { pageId = that.getPageId(opts.title); pageNodeId = that.getPageNodeId(opts.title); } if (pageId) { data = '[data-node-id="' + pageNodeId + '"]'; href = '[href*="' + pageId + '"]'; } return this.then(function () { this.click('.cms-pagetree-jstree .js-cms-pagetree-options' + data); }) .then(that.waitUntilActionsDropdownLoaded()) .then(function () { this.click('.cms-pagetree-jstree [href*="delete"]' + href); }); }) .waitForUrl(/delete/) .waitUntilVisible('input[type=submit]') .then(function () { this.click('input[type=submit]'); }) .wait(1000) .then(that.waitUntilAllAjaxCallsFinish()); }; }
[ "function", "(", "opts", ")", "{", "var", "that", "=", "this", ";", "return", "function", "(", ")", "{", "return", "this", ".", "thenOpen", "(", "globals", ".", "adminPagesUrl", ")", ".", "waitUntilVisible", "(", "'.js-cms-pagetree-options'", ")", ".", "then", "(", "that", ".", "expandPageTree", "(", ")", ")", ".", "then", "(", "function", "(", ")", "{", "var", "pageId", ";", "var", "pageNodeId", ";", "var", "data", "=", "''", ";", "var", "href", "=", "''", ";", "if", "(", "opts", "&&", "opts", ".", "title", ")", "{", "pageId", "=", "that", ".", "getPageId", "(", "opts", ".", "title", ")", ";", "pageNodeId", "=", "that", ".", "getPageNodeId", "(", "opts", ".", "title", ")", ";", "}", "if", "(", "pageId", ")", "{", "data", "=", "'[data-node-id=\"'", "+", "pageNodeId", "+", "'\"]'", ";", "href", "=", "'[href*=\"'", "+", "pageId", "+", "'\"]'", ";", "}", "return", "this", ".", "then", "(", "function", "(", ")", "{", "this", ".", "click", "(", "'.cms-pagetree-jstree .js-cms-pagetree-options'", "+", "data", ")", ";", "}", ")", ".", "then", "(", "that", ".", "waitUntilActionsDropdownLoaded", "(", ")", ")", ".", "then", "(", "function", "(", ")", "{", "this", ".", "click", "(", "'.cms-pagetree-jstree [href*=\"delete\"]'", "+", "href", ")", ";", "}", ")", ";", "}", ")", ".", "waitForUrl", "(", "/", "delete", "/", ")", ".", "waitUntilVisible", "(", "'input[type=submit]'", ")", ".", "then", "(", "function", "(", ")", "{", "this", ".", "click", "(", "'input[type=submit]'", ")", ";", "}", ")", ".", "wait", "(", "1000", ")", ".", "then", "(", "that", ".", "waitUntilAllAjaxCallsFinish", "(", ")", ")", ";", "}", ";", "}" ]
removes a page by name, or the first encountered one @param {Object} opts @param {String} [opts.title] Name of the page to delete @returns {Function}
[ "removes", "a", "page", "by", "name", "or", "the", "first", "encountered", "one" ]
200e0f29b01341cba34e7bc9e7d329f81d531b2a
https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/helpers.js#L40-L79
39,771
divio/djangocms-casper-helpers
helpers.js
function (opts) { var that = this; return function () { return this.then(function () { this.click('.js-cms-pagetree-options[data-node-id="' + opts.page + '"]'); }) .then(that.waitUntilActionsDropdownLoaded()) .then(function () { this.mouse.click('.js-cms-tree-item-copy[data-node-id="' + opts.page + '"]'); }) .wait(100); }; }
javascript
function (opts) { var that = this; return function () { return this.then(function () { this.click('.js-cms-pagetree-options[data-node-id="' + opts.page + '"]'); }) .then(that.waitUntilActionsDropdownLoaded()) .then(function () { this.mouse.click('.js-cms-tree-item-copy[data-node-id="' + opts.page + '"]'); }) .wait(100); }; }
[ "function", "(", "opts", ")", "{", "var", "that", "=", "this", ";", "return", "function", "(", ")", "{", "return", "this", ".", "then", "(", "function", "(", ")", "{", "this", ".", "click", "(", "'.js-cms-pagetree-options[data-node-id=\"'", "+", "opts", ".", "page", "+", "'\"]'", ")", ";", "}", ")", ".", "then", "(", "that", ".", "waitUntilActionsDropdownLoaded", "(", ")", ")", ".", "then", "(", "function", "(", ")", "{", "this", ".", "mouse", ".", "click", "(", "'.js-cms-tree-item-copy[data-node-id=\"'", "+", "opts", ".", "page", "+", "'\"]'", ")", ";", "}", ")", ".", "wait", "(", "100", ")", ";", "}", ";", "}" ]
Opens dropdown and triggers copying a page @public @param {Object} opts @param {Number|String} opts.page page id @returns {Function}
[ "Opens", "dropdown", "and", "triggers", "copying", "a", "page" ]
200e0f29b01341cba34e7bc9e7d329f81d531b2a
https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/helpers.js#L117-L130
39,772
divio/djangocms-casper-helpers
helpers.js
function (view) { return function () { if ( view === 'structure' && this.exists('.cms-toolbar-item-cms-mode-switcher .cms-btn-active') || view === 'content' && !this.exists('.cms-toolbar-item-cms-mode-switcher .cms-btn-active') ) { return this.wait(100); } return this.waitForSelector('.cms-toolbar-expanded') .then(function () { return this.click('.cms-toolbar-item-cms-mode-switcher .cms-btn'); }) .then(function () { if (view === 'structure') { return this.waitForSelector('.cms-structure-content .cms-dragarea'); } else if (view === 'content') { return this.waitWhileSelector('.cms-structure-mode-structure'); } throw new Error( 'Invalid arguments passed to cms.switchTo, should be either "structure" or "content"' ); }); }; }
javascript
function (view) { return function () { if ( view === 'structure' && this.exists('.cms-toolbar-item-cms-mode-switcher .cms-btn-active') || view === 'content' && !this.exists('.cms-toolbar-item-cms-mode-switcher .cms-btn-active') ) { return this.wait(100); } return this.waitForSelector('.cms-toolbar-expanded') .then(function () { return this.click('.cms-toolbar-item-cms-mode-switcher .cms-btn'); }) .then(function () { if (view === 'structure') { return this.waitForSelector('.cms-structure-content .cms-dragarea'); } else if (view === 'content') { return this.waitWhileSelector('.cms-structure-mode-structure'); } throw new Error( 'Invalid arguments passed to cms.switchTo, should be either "structure" or "content"' ); }); }; }
[ "function", "(", "view", ")", "{", "return", "function", "(", ")", "{", "if", "(", "view", "===", "'structure'", "&&", "this", ".", "exists", "(", "'.cms-toolbar-item-cms-mode-switcher .cms-btn-active'", ")", "||", "view", "===", "'content'", "&&", "!", "this", ".", "exists", "(", "'.cms-toolbar-item-cms-mode-switcher .cms-btn-active'", ")", ")", "{", "return", "this", ".", "wait", "(", "100", ")", ";", "}", "return", "this", ".", "waitForSelector", "(", "'.cms-toolbar-expanded'", ")", ".", "then", "(", "function", "(", ")", "{", "return", "this", ".", "click", "(", "'.cms-toolbar-item-cms-mode-switcher .cms-btn'", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "view", "===", "'structure'", ")", "{", "return", "this", ".", "waitForSelector", "(", "'.cms-structure-content .cms-dragarea'", ")", ";", "}", "else", "if", "(", "view", "===", "'content'", ")", "{", "return", "this", ".", "waitWhileSelector", "(", "'.cms-structure-mode-structure'", ")", ";", "}", "throw", "new", "Error", "(", "'Invalid arguments passed to cms.switchTo, should be either \"structure\" or \"content\"'", ")", ";", "}", ")", ";", "}", ";", "}" ]
Switches structureboard to a specific mode. @function switchTo @param {String} view 'structure' or 'content' @returns {Function}
[ "Switches", "structureboard", "to", "a", "specific", "mode", "." ]
200e0f29b01341cba34e7bc9e7d329f81d531b2a
https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/helpers.js#L457-L482
39,773
divio/djangocms-casper-helpers
helpers.js
function (selector) { return function () { return this.then(function () { // if "Expand all" is visible then if (this.visible(selector + ' .cms-dragbar-expand-all')) { this.click(selector + ' .cms-dragbar-expand-all'); } else if (this.visible(selector + ' .cms-dragbar-collapse-all')) { // if not visible, then first "Collapse all" this.click(selector + ' .cms-dragbar-collapse-all'); this.wait(100); this.click(selector + ' .cms-dragbar-expand-all'); } else { throw new Error('Given placeholder has no plugins'); } }); }; }
javascript
function (selector) { return function () { return this.then(function () { // if "Expand all" is visible then if (this.visible(selector + ' .cms-dragbar-expand-all')) { this.click(selector + ' .cms-dragbar-expand-all'); } else if (this.visible(selector + ' .cms-dragbar-collapse-all')) { // if not visible, then first "Collapse all" this.click(selector + ' .cms-dragbar-collapse-all'); this.wait(100); this.click(selector + ' .cms-dragbar-expand-all'); } else { throw new Error('Given placeholder has no plugins'); } }); }; }
[ "function", "(", "selector", ")", "{", "return", "function", "(", ")", "{", "return", "this", ".", "then", "(", "function", "(", ")", "{", "// if \"Expand all\" is visible then", "if", "(", "this", ".", "visible", "(", "selector", "+", "' .cms-dragbar-expand-all'", ")", ")", "{", "this", ".", "click", "(", "selector", "+", "' .cms-dragbar-expand-all'", ")", ";", "}", "else", "if", "(", "this", ".", "visible", "(", "selector", "+", "' .cms-dragbar-collapse-all'", ")", ")", "{", "// if not visible, then first \"Collapse all\"", "this", ".", "click", "(", "selector", "+", "' .cms-dragbar-collapse-all'", ")", ";", "this", ".", "wait", "(", "100", ")", ";", "this", ".", "click", "(", "selector", "+", "' .cms-dragbar-expand-all'", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Given placeholder has no plugins'", ")", ";", "}", "}", ")", ";", "}", ";", "}" ]
Expands all plugins in the given placeholder. @function expandPlaceholderPlugins @param {String} selector placeholder selector @returns {Function}
[ "Expands", "all", "plugins", "in", "the", "given", "placeholder", "." ]
200e0f29b01341cba34e7bc9e7d329f81d531b2a
https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/helpers.js#L491-L507
39,774
divio/djangocms-casper-helpers
helpers.js
function () { var that = this; return function () { return this.then(function () { if (this.visible('.jstree-closed')) { this.click('.jstree-closed > .jstree-ocl'); // there's no clear way to check if the page was loading // or was already in the DOM return casper .then(that.waitUntilAllAjaxCallsFinish()) .then(that.expandPageTree()); } return casper.wait(1000) .then(that.waitUntilAllAjaxCallsFinish()); }); }; }
javascript
function () { var that = this; return function () { return this.then(function () { if (this.visible('.jstree-closed')) { this.click('.jstree-closed > .jstree-ocl'); // there's no clear way to check if the page was loading // or was already in the DOM return casper .then(that.waitUntilAllAjaxCallsFinish()) .then(that.expandPageTree()); } return casper.wait(1000) .then(that.waitUntilAllAjaxCallsFinish()); }); }; }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "return", "function", "(", ")", "{", "return", "this", ".", "then", "(", "function", "(", ")", "{", "if", "(", "this", ".", "visible", "(", "'.jstree-closed'", ")", ")", "{", "this", ".", "click", "(", "'.jstree-closed > .jstree-ocl'", ")", ";", "// there's no clear way to check if the page was loading", "// or was already in the DOM", "return", "casper", ".", "then", "(", "that", ".", "waitUntilAllAjaxCallsFinish", "(", ")", ")", ".", "then", "(", "that", ".", "expandPageTree", "(", ")", ")", ";", "}", "return", "casper", ".", "wait", "(", "1000", ")", ".", "then", "(", "that", ".", "waitUntilAllAjaxCallsFinish", "(", ")", ")", ";", "}", ")", ";", "}", ";", "}" ]
Recursively expands the page tree to operate on page nodes. @function expandPageTree @returns {Function}
[ "Recursively", "expands", "the", "page", "tree", "to", "operate", "on", "page", "nodes", "." ]
200e0f29b01341cba34e7bc9e7d329f81d531b2a
https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/helpers.js#L537-L555
39,775
divio/djangocms-casper-helpers
helpers.js
function (title) { // important to pass single param, because casper acts // weirdly with single key objects https://github.com/n1k0/casperjs/issues/353 return casper.evaluate(function (anchorTitle) { return CMS.$('.jstree-anchor').map(function () { var anchor = CMS.$(this); if (anchor.text().trim() === anchorTitle) { return anchor.parent().data('nodeId'); } }).toArray(); }, title); }
javascript
function (title) { // important to pass single param, because casper acts // weirdly with single key objects https://github.com/n1k0/casperjs/issues/353 return casper.evaluate(function (anchorTitle) { return CMS.$('.jstree-anchor').map(function () { var anchor = CMS.$(this); if (anchor.text().trim() === anchorTitle) { return anchor.parent().data('nodeId'); } }).toArray(); }, title); }
[ "function", "(", "title", ")", "{", "// important to pass single param, because casper acts", "// weirdly with single key objects https://github.com/n1k0/casperjs/issues/353", "return", "casper", ".", "evaluate", "(", "function", "(", "anchorTitle", ")", "{", "return", "CMS", ".", "$", "(", "'.jstree-anchor'", ")", ".", "map", "(", "function", "(", ")", "{", "var", "anchor", "=", "CMS", ".", "$", "(", "this", ")", ";", "if", "(", "anchor", ".", "text", "(", ")", ".", "trim", "(", ")", "===", "anchorTitle", ")", "{", "return", "anchor", ".", "parent", "(", ")", ".", "data", "(", "'nodeId'", ")", ";", "}", "}", ")", ".", "toArray", "(", ")", ";", "}", ",", "title", ")", ";", "}" ]
Returns page nodeIds of all the pages with same title. Pages has to be visible in the page tree. See `expandPageTree`. @function _getPageNodeIds @private @param {String} title page title @returns {String[]|Boolean} page node ids as an array of strings or false if couldn't be found
[ "Returns", "page", "nodeIds", "of", "all", "the", "pages", "with", "same", "title", ".", "Pages", "has", "to", "be", "visible", "in", "the", "page", "tree", ".", "See", "expandPageTree", "." ]
200e0f29b01341cba34e7bc9e7d329f81d531b2a
https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/helpers.js#L611-L623
39,776
divio/djangocms-casper-helpers
helpers.js
getXPathForAdminSection
function getXPathForAdminSection(options) { var xpath = '//div[.//caption/a[contains(text(), "' + options.section + '")]]'; if (options.link) { xpath += '//th[./a[contains(text(), "' + options.row + '")]]'; xpath += '/following-sibling::td/a[contains(text(), "' + options.link + '")]'; } else { xpath += '//th/a[contains(text(), "' + options.row + '")]'; } return xpath; }
javascript
function getXPathForAdminSection(options) { var xpath = '//div[.//caption/a[contains(text(), "' + options.section + '")]]'; if (options.link) { xpath += '//th[./a[contains(text(), "' + options.row + '")]]'; xpath += '/following-sibling::td/a[contains(text(), "' + options.link + '")]'; } else { xpath += '//th/a[contains(text(), "' + options.row + '")]'; } return xpath; }
[ "function", "getXPathForAdminSection", "(", "options", ")", "{", "var", "xpath", "=", "'//div[.//caption/a[contains(text(), \"'", "+", "options", ".", "section", "+", "'\")]]'", ";", "if", "(", "options", ".", "link", ")", "{", "xpath", "+=", "'//th[./a[contains(text(), \"'", "+", "options", ".", "row", "+", "'\")]]'", ";", "xpath", "+=", "'/following-sibling::td/a[contains(text(), \"'", "+", "options", ".", "link", "+", "'\")]'", ";", "}", "else", "{", "xpath", "+=", "'//th/a[contains(text(), \"'", "+", "options", ".", "row", "+", "'\")]'", ";", "}", "return", "xpath", ";", "}" ]
Returns xpath expression to the specific row in the admin. Can also be used to find xpath to specific links in that row. @function getXPathForAdminSection @param {Object} options @param {String} options.section module name, e.g. Django CMS @param {String} options.row module row, e.g Pages, Users @param {String} [options.link] specific link in the row, e.g "Add" or "Change" @returns {String}
[ "Returns", "xpath", "expression", "to", "the", "specific", "row", "in", "the", "admin", ".", "Can", "also", "be", "used", "to", "find", "xpath", "to", "specific", "links", "in", "that", "row", "." ]
200e0f29b01341cba34e7bc9e7d329f81d531b2a
https://github.com/divio/djangocms-casper-helpers/blob/200e0f29b01341cba34e7bc9e7d329f81d531b2a/helpers.js#L750-L761
39,777
fluree/fql-react
src/index.js
workerMessageHandler
function workerMessageHandler(e) { const msg = e.data; var cb; SHOULD_LOG && console.log("Worker received message: " + JSON.stringify(msg)); switch (msg.event) { case "connInit": workerInitialized = true; workerQueue.forEach(workerInvoke); workerQueue = []; break; case "connStatus": const response = msg.data || {}; const statusCode = response.status; if (connStatus[msg.conn]) { switch (statusCode) { case 200: connStatus[msg.conn].ready = true; break; case 401: // authorization error, need to log in connStatus[msg.conn].ready = false; connStatus[msg.conn].user = null; connStatus[msg.conn].anonymous = true; break; default: console.warn("Invalid connection response status: " + JSON.stringify(response)); break; } } break; case "connClosed": cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "connLogout": cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "setState": const comp = componentIdx[msg.ref]; if (comp) { comp.setState(msg.data); } else { SHOULD_LOG && console.warn("Component no longer registered: " + msg.ref); } break; case "remoteInvoke": // check for a callback cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "login": // if login successful, update conn's connStatus if (msg.data.status === 200) { connStatus[msg.conn].token = msg.data.body.token; connStatus[msg.conn].user = msg.data.body.user; connStatus[msg.conn].anonymous = msg.data.body.anonymous; } // if there was a callback passed to login(), execute cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; default: SHOULD_LOG && console.warn("Unreconized event from worker: " + msg.event + ". Full message: " + JSON.stringify(msg)); break; } return; }
javascript
function workerMessageHandler(e) { const msg = e.data; var cb; SHOULD_LOG && console.log("Worker received message: " + JSON.stringify(msg)); switch (msg.event) { case "connInit": workerInitialized = true; workerQueue.forEach(workerInvoke); workerQueue = []; break; case "connStatus": const response = msg.data || {}; const statusCode = response.status; if (connStatus[msg.conn]) { switch (statusCode) { case 200: connStatus[msg.conn].ready = true; break; case 401: // authorization error, need to log in connStatus[msg.conn].ready = false; connStatus[msg.conn].user = null; connStatus[msg.conn].anonymous = true; break; default: console.warn("Invalid connection response status: " + JSON.stringify(response)); break; } } break; case "connClosed": cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "connLogout": cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "setState": const comp = componentIdx[msg.ref]; if (comp) { comp.setState(msg.data); } else { SHOULD_LOG && console.warn("Component no longer registered: " + msg.ref); } break; case "remoteInvoke": // check for a callback cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; case "login": // if login successful, update conn's connStatus if (msg.data.status === 200) { connStatus[msg.conn].token = msg.data.body.token; connStatus[msg.conn].user = msg.data.body.user; connStatus[msg.conn].anonymous = msg.data.body.anonymous; } // if there was a callback passed to login(), execute cb = callbackRegistry[msg.ref]; if (cb) { delete callbackRegistry[msg.ref]; cb(msg.data); } break; default: SHOULD_LOG && console.warn("Unreconized event from worker: " + msg.event + ". Full message: " + JSON.stringify(msg)); break; } return; }
[ "function", "workerMessageHandler", "(", "e", ")", "{", "const", "msg", "=", "e", ".", "data", ";", "var", "cb", ";", "SHOULD_LOG", "&&", "console", ".", "log", "(", "\"Worker received message: \"", "+", "JSON", ".", "stringify", "(", "msg", ")", ")", ";", "switch", "(", "msg", ".", "event", ")", "{", "case", "\"connInit\"", ":", "workerInitialized", "=", "true", ";", "workerQueue", ".", "forEach", "(", "workerInvoke", ")", ";", "workerQueue", "=", "[", "]", ";", "break", ";", "case", "\"connStatus\"", ":", "const", "response", "=", "msg", ".", "data", "||", "{", "}", ";", "const", "statusCode", "=", "response", ".", "status", ";", "if", "(", "connStatus", "[", "msg", ".", "conn", "]", ")", "{", "switch", "(", "statusCode", ")", "{", "case", "200", ":", "connStatus", "[", "msg", ".", "conn", "]", ".", "ready", "=", "true", ";", "break", ";", "case", "401", ":", "// authorization error, need to log in", "connStatus", "[", "msg", ".", "conn", "]", ".", "ready", "=", "false", ";", "connStatus", "[", "msg", ".", "conn", "]", ".", "user", "=", "null", ";", "connStatus", "[", "msg", ".", "conn", "]", ".", "anonymous", "=", "true", ";", "break", ";", "default", ":", "console", ".", "warn", "(", "\"Invalid connection response status: \"", "+", "JSON", ".", "stringify", "(", "response", ")", ")", ";", "break", ";", "}", "}", "break", ";", "case", "\"connClosed\"", ":", "cb", "=", "callbackRegistry", "[", "msg", ".", "ref", "]", ";", "if", "(", "cb", ")", "{", "delete", "callbackRegistry", "[", "msg", ".", "ref", "]", ";", "cb", "(", "msg", ".", "data", ")", ";", "}", "break", ";", "case", "\"connLogout\"", ":", "cb", "=", "callbackRegistry", "[", "msg", ".", "ref", "]", ";", "if", "(", "cb", ")", "{", "delete", "callbackRegistry", "[", "msg", ".", "ref", "]", ";", "cb", "(", "msg", ".", "data", ")", ";", "}", "break", ";", "case", "\"setState\"", ":", "const", "comp", "=", "componentIdx", "[", "msg", ".", "ref", "]", ";", "if", "(", "comp", ")", "{", "comp", ".", "setState", "(", "msg", ".", "data", ")", ";", "}", "else", "{", "SHOULD_LOG", "&&", "console", ".", "warn", "(", "\"Component no longer registered: \"", "+", "msg", ".", "ref", ")", ";", "}", "break", ";", "case", "\"remoteInvoke\"", ":", "// check for a callback", "cb", "=", "callbackRegistry", "[", "msg", ".", "ref", "]", ";", "if", "(", "cb", ")", "{", "delete", "callbackRegistry", "[", "msg", ".", "ref", "]", ";", "cb", "(", "msg", ".", "data", ")", ";", "}", "break", ";", "case", "\"login\"", ":", "// if login successful, update conn's connStatus", "if", "(", "msg", ".", "data", ".", "status", "===", "200", ")", "{", "connStatus", "[", "msg", ".", "conn", "]", ".", "token", "=", "msg", ".", "data", ".", "body", ".", "token", ";", "connStatus", "[", "msg", ".", "conn", "]", ".", "user", "=", "msg", ".", "data", ".", "body", ".", "user", ";", "connStatus", "[", "msg", ".", "conn", "]", ".", "anonymous", "=", "msg", ".", "data", ".", "body", ".", "anonymous", ";", "}", "// if there was a callback passed to login(), execute", "cb", "=", "callbackRegistry", "[", "msg", ".", "ref", "]", ";", "if", "(", "cb", ")", "{", "delete", "callbackRegistry", "[", "msg", ".", "ref", "]", ";", "cb", "(", "msg", ".", "data", ")", ";", "}", "break", ";", "default", ":", "SHOULD_LOG", "&&", "console", ".", "warn", "(", "\"Unreconized event from worker: \"", "+", "msg", ".", "event", "+", "\". Full message: \"", "+", "JSON", ".", "stringify", "(", "msg", ")", ")", ";", "break", ";", "}", "return", ";", "}" ]
worker.onmessage handler
[ "worker", ".", "onmessage", "handler" ]
299fc52d80ee7ec57b5fa6cb5ad0e4618ced2bd3
https://github.com/fluree/fql-react/blob/299fc52d80ee7ec57b5fa6cb5ad0e4618ced2bd3/src/index.js#L45-L132
39,778
fluree/fql-react
src/index.js
isClosed
function isClosed(connId) { const connObj = connStatus[connId]; return (connObj && Object.keys(connObj).length === 0); }
javascript
function isClosed(connId) { const connObj = connStatus[connId]; return (connObj && Object.keys(connObj).length === 0); }
[ "function", "isClosed", "(", "connId", ")", "{", "const", "connObj", "=", "connStatus", "[", "connId", "]", ";", "return", "(", "connObj", "&&", "Object", ".", "keys", "(", "connObj", ")", ".", "length", "===", "0", ")", ";", "}" ]
we use a global to track connection state, get method for it
[ "we", "use", "a", "global", "to", "track", "connection", "state", "get", "method", "for", "it" ]
299fc52d80ee7ec57b5fa6cb5ad0e4618ced2bd3
https://github.com/fluree/fql-react/blob/299fc52d80ee7ec57b5fa6cb5ad0e4618ced2bd3/src/index.js#L159-L162
39,779
fluree/fql-react
src/index.js
getMissingVars
function getMissingVars(flurQL, opts) { const vars = flurQL.vars; if (!vars || !Array.isArray(vars)) { return []; } if (opts && opts.vars) { return vars.filter((v) => { return !opts.vars[v]; }); } else { return vars; } }
javascript
function getMissingVars(flurQL, opts) { const vars = flurQL.vars; if (!vars || !Array.isArray(vars)) { return []; } if (opts && opts.vars) { return vars.filter((v) => { return !opts.vars[v]; }); } else { return vars; } }
[ "function", "getMissingVars", "(", "flurQL", ",", "opts", ")", "{", "const", "vars", "=", "flurQL", ".", "vars", ";", "if", "(", "!", "vars", "||", "!", "Array", ".", "isArray", "(", "vars", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "opts", "&&", "opts", ".", "vars", ")", "{", "return", "vars", ".", "filter", "(", "(", "v", ")", "=>", "{", "return", "!", "opts", ".", "vars", "[", "v", "]", ";", "}", ")", ";", "}", "else", "{", "return", "vars", ";", "}", "}" ]
given a query and options, returns a vector of variables that were not provided via options. We use this to look for the variables in props
[ "given", "a", "query", "and", "options", "returns", "a", "vector", "of", "variables", "that", "were", "not", "provided", "via", "options", ".", "We", "use", "this", "to", "look", "for", "the", "variables", "in", "props" ]
299fc52d80ee7ec57b5fa6cb5ad0e4618ced2bd3
https://github.com/fluree/fql-react/blob/299fc52d80ee7ec57b5fa6cb5ad0e4618ced2bd3/src/index.js#L367-L379
39,780
fluree/fql-react
src/index.js
fillDefaultResult
function fillDefaultResult(query) { if (!query) return {}; const graph = query.graph || query; if (!Array.isArray(graph)) { // invalid graph return; } var defaultResult = {}; graph.map(([stream, opts]) => { if (opts.as) { defaultResult[opts.as] = null; } else { defaultResult[stream] = null; } }); return defaultResult; }
javascript
function fillDefaultResult(query) { if (!query) return {}; const graph = query.graph || query; if (!Array.isArray(graph)) { // invalid graph return; } var defaultResult = {}; graph.map(([stream, opts]) => { if (opts.as) { defaultResult[opts.as] = null; } else { defaultResult[stream] = null; } }); return defaultResult; }
[ "function", "fillDefaultResult", "(", "query", ")", "{", "if", "(", "!", "query", ")", "return", "{", "}", ";", "const", "graph", "=", "query", ".", "graph", "||", "query", ";", "if", "(", "!", "Array", ".", "isArray", "(", "graph", ")", ")", "{", "// invalid graph", "return", ";", "}", "var", "defaultResult", "=", "{", "}", ";", "graph", ".", "map", "(", "(", "[", "stream", ",", "opts", "]", ")", "=>", "{", "if", "(", "opts", ".", "as", ")", "{", "defaultResult", "[", "opts", ".", "as", "]", "=", "null", ";", "}", "else", "{", "defaultResult", "[", "stream", "]", "=", "null", ";", "}", "}", ")", ";", "return", "defaultResult", ";", "}" ]
Create an empty map of the top level query nodes so less boilerplate is required to test if a property exists in the wrapped component
[ "Create", "an", "empty", "map", "of", "the", "top", "level", "query", "nodes", "so", "less", "boilerplate", "is", "required", "to", "test", "if", "a", "property", "exists", "in", "the", "wrapped", "component" ]
299fc52d80ee7ec57b5fa6cb5ad0e4618ced2bd3
https://github.com/fluree/fql-react/blob/299fc52d80ee7ec57b5fa6cb5ad0e4618ced2bd3/src/index.js#L384-L404
39,781
kubosho/kotori
src/config.js
loadConfigCore
function loadConfigCore(configItem) { if (typeof configItem === "string") { configItem = fs.readFileSync(configItem, "utf8"); } else if (typeof configItem === "object") { // do nothing } else { throw new Error("Unexpected config item type."); } return configItem; }
javascript
function loadConfigCore(configItem) { if (typeof configItem === "string") { configItem = fs.readFileSync(configItem, "utf8"); } else if (typeof configItem === "object") { // do nothing } else { throw new Error("Unexpected config item type."); } return configItem; }
[ "function", "loadConfigCore", "(", "configItem", ")", "{", "if", "(", "typeof", "configItem", "===", "\"string\"", ")", "{", "configItem", "=", "fs", ".", "readFileSync", "(", "configItem", ",", "\"utf8\"", ")", ";", "}", "else", "if", "(", "typeof", "configItem", "===", "\"object\"", ")", "{", "// do nothing", "}", "else", "{", "throw", "new", "Error", "(", "\"Unexpected config item type.\"", ")", ";", "}", "return", "configItem", ";", "}" ]
Load config core function, from object or local config file @param {Object|String} configItem - Config object or file path @returns {Object} Kotori config @private
[ "Load", "config", "core", "function", "from", "object", "or", "local", "config", "file" ]
4a869d470408db17733caf9dabe67ecaa20cf4b7
https://github.com/kubosho/kotori/blob/4a869d470408db17733caf9dabe67ecaa20cf4b7/src/config.js#L67-L77
39,782
kubosho/kotori
src/config.js
parseConfigCore
function parseConfigCore(configItem) { if (isObject(configItem) || isJSON(configItem)) { try { configItem = JSON.parse(configItem); } catch (err) { // configItem is Object. if (/^Unexpected token.*/.test(err.message)) { return configItem; } } return configItem; } }
javascript
function parseConfigCore(configItem) { if (isObject(configItem) || isJSON(configItem)) { try { configItem = JSON.parse(configItem); } catch (err) { // configItem is Object. if (/^Unexpected token.*/.test(err.message)) { return configItem; } } return configItem; } }
[ "function", "parseConfigCore", "(", "configItem", ")", "{", "if", "(", "isObject", "(", "configItem", ")", "||", "isJSON", "(", "configItem", ")", ")", "{", "try", "{", "configItem", "=", "JSON", ".", "parse", "(", "configItem", ")", ";", "}", "catch", "(", "err", ")", "{", "// configItem is Object.", "if", "(", "/", "^Unexpected token.*", "/", ".", "test", "(", "err", ".", "message", ")", ")", "{", "return", "configItem", ";", "}", "}", "return", "configItem", ";", "}", "}" ]
Parse config core function @param {Object} configItem - Config object @returns {Object} Kotori config @private
[ "Parse", "config", "core", "function" ]
4a869d470408db17733caf9dabe67ecaa20cf4b7
https://github.com/kubosho/kotori/blob/4a869d470408db17733caf9dabe67ecaa20cf4b7/src/config.js#L85-L98
39,783
sumeetdas/Meow
lib/blog.js
findBlogs
function findBlogs (pRequest, pResponse) { var query = pRequest.params.query, posts = cache.get('posts') || {}; var blogsToSend = []; for (var key in posts) { var post = new Post(posts[key]); if (post.containsQuery(query)) { blogsToSend.push(posts[key]); } } return pResponse.status(201).send(blogsToSend).end(); }
javascript
function findBlogs (pRequest, pResponse) { var query = pRequest.params.query, posts = cache.get('posts') || {}; var blogsToSend = []; for (var key in posts) { var post = new Post(posts[key]); if (post.containsQuery(query)) { blogsToSend.push(posts[key]); } } return pResponse.status(201).send(blogsToSend).end(); }
[ "function", "findBlogs", "(", "pRequest", ",", "pResponse", ")", "{", "var", "query", "=", "pRequest", ".", "params", ".", "query", ",", "posts", "=", "cache", ".", "get", "(", "'posts'", ")", "||", "{", "}", ";", "var", "blogsToSend", "=", "[", "]", ";", "for", "(", "var", "key", "in", "posts", ")", "{", "var", "post", "=", "new", "Post", "(", "posts", "[", "key", "]", ")", ";", "if", "(", "post", ".", "containsQuery", "(", "query", ")", ")", "{", "blogsToSend", ".", "push", "(", "posts", "[", "key", "]", ")", ";", "}", "}", "return", "pResponse", ".", "status", "(", "201", ")", ".", "send", "(", "blogsToSend", ")", ".", "end", "(", ")", ";", "}" ]
This function finds blogs which matches given blog post title, tags and keywords with the query text @param pRequest @param pResponse
[ "This", "function", "finds", "blogs", "which", "matches", "given", "blog", "post", "title", "tags", "and", "keywords", "with", "the", "query", "text" ]
965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9
https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/blog.js#L352-L367
39,784
EikosPartners/scalejs
dist/scalejs.application.js
registerModules
function registerModules() { // Dynamic module loading is no longer supported for simplicity. // Module is free to load any of its resources dynamically. // Or an extension can provide dynamic module loading capabilities as needed. if (_scalejs2.default.isApplicationRunning()) { throw new Error('Can\'t register module since the application is already running.', 'Dynamic module loading is not supported.'); } Array.prototype.push.apply(moduleRegistrations, toArray(arguments).filter(function (m) { return m; })); }
javascript
function registerModules() { // Dynamic module loading is no longer supported for simplicity. // Module is free to load any of its resources dynamically. // Or an extension can provide dynamic module loading capabilities as needed. if (_scalejs2.default.isApplicationRunning()) { throw new Error('Can\'t register module since the application is already running.', 'Dynamic module loading is not supported.'); } Array.prototype.push.apply(moduleRegistrations, toArray(arguments).filter(function (m) { return m; })); }
[ "function", "registerModules", "(", ")", "{", "// Dynamic module loading is no longer supported for simplicity.", "// Module is free to load any of its resources dynamically.", "// Or an extension can provide dynamic module loading capabilities as needed.", "if", "(", "_scalejs2", ".", "default", ".", "isApplicationRunning", "(", ")", ")", "{", "throw", "new", "Error", "(", "'Can\\'t register module since the application is already running.'", ",", "'Dynamic module loading is not supported.'", ")", ";", "}", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "moduleRegistrations", ",", "toArray", "(", "arguments", ")", ".", "filter", "(", "function", "(", "m", ")", "{", "return", "m", ";", "}", ")", ")", ";", "}" ]
Registers a series of modules to the application @param {Function|Object} [module...] modules to register @memberOf application Application manages the life cycle of modules. @namespace scalejs.application @module application /*global define
[ "Registers", "a", "series", "of", "modules", "to", "the", "application" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.application.js#L50-L61
39,785
stezu/node-stream
lib/modifiers/take.js
take
function take(n) { var idx = 0; return map(function (chunk, next) { idx += 1; if (!_.isInteger(n)) { return next(new TypeError('Expected `n` to be an integer.')); } // take n items from the source stream if (idx <= n) { return next(null, chunk); } // drop all other items return next(); }); }
javascript
function take(n) { var idx = 0; return map(function (chunk, next) { idx += 1; if (!_.isInteger(n)) { return next(new TypeError('Expected `n` to be an integer.')); } // take n items from the source stream if (idx <= n) { return next(null, chunk); } // drop all other items return next(); }); }
[ "function", "take", "(", "n", ")", "{", "var", "idx", "=", "0", ";", "return", "map", "(", "function", "(", "chunk", ",", "next", ")", "{", "idx", "+=", "1", ";", "if", "(", "!", "_", ".", "isInteger", "(", "n", ")", ")", "{", "return", "next", "(", "new", "TypeError", "(", "'Expected `n` to be an integer.'", ")", ")", ";", "}", "// take n items from the source stream", "if", "(", "idx", "<=", "n", ")", "{", "return", "next", "(", "null", ",", "chunk", ")", ";", "}", "// drop all other items", "return", "next", "(", ")", ";", "}", ")", ";", "}" ]
Creates a new Stream with the first `n` values from the source stream. @static @since 1.4.0 @category Modifiers @param {Number} n - Number of items to take from the source stream. @returns {Stream.Transform} - Transform stream. @example // take the first 3 items from a stream inStream // => ['b', 'a', 'n', 'a', 'n', 'a'] .pipe(nodeStream.take(3)) .pipe(process.stdout) // => ['b', 'a', 'n']
[ "Creates", "a", "new", "Stream", "with", "the", "first", "n", "values", "from", "the", "source", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/take.js#L23-L41
39,786
stezu/node-stream
lib/modifiers/flatten.js
flatten
function flatten() { return through.obj(function Transform(data, enc, cb) { var self = this; if (!_.isArray(data)) { return cb(null, data); } data.forEach(function (val) { self.push(val); }); return cb(); }); }
javascript
function flatten() { return through.obj(function Transform(data, enc, cb) { var self = this; if (!_.isArray(data)) { return cb(null, data); } data.forEach(function (val) { self.push(val); }); return cb(); }); }
[ "function", "flatten", "(", ")", "{", "return", "through", ".", "obj", "(", "function", "Transform", "(", "data", ",", "enc", ",", "cb", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "_", ".", "isArray", "(", "data", ")", ")", "{", "return", "cb", "(", "null", ",", "data", ")", ";", "}", "data", ".", "forEach", "(", "function", "(", "val", ")", "{", "self", ".", "push", "(", "val", ")", ";", "}", ")", ";", "return", "cb", "(", ")", ";", "}", ")", ";", "}" ]
Returns a new stream that flattens all arrays passing through by one level. All non-array items will be passed through as-is. @method @static @since 1.5.0 @category Modifiers @returns {Stream.Transform} - Transform stream. @example const input = nodeStream.through.obj(); input.pipe(nodeStream.flatten()); input.write([1, 2, 3]); input.write([4, 5]); input.write(6); // => [1, 2, 3, 4, 5, 6] @example const input = nodeStream.through.obj(); input // batch items that are read .pipe(nodeStream.batch({ count: 2 })) // perform a transform action on the batches .pipe(transformBatch()) // flatten the batches back .pipe(nodeStream.flatten()); input.write(1); input.write(2); input.write(3); input.write(4); input.write(5); // => [1, 2, 3, 4, 5]
[ "Returns", "a", "new", "stream", "that", "flattens", "all", "arrays", "passing", "through", "by", "one", "level", ".", "All", "non", "-", "array", "items", "will", "be", "passed", "through", "as", "-", "is", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/flatten.js#L47-L61
39,787
mikolalysenko/frame-hop
hop.js
createHopStream
function createHopStream(frame_size, hop_size, onFrame, max_data_size) { if(hop_size > frame_size) { throw new Error("Hop size must be smaller than frame size") } max_data_size = max_data_size || frame_size var buffer = new Float32Array(2*frame_size + max_data_size) var ptr = 0 var frame_slices = [] for(var j=0; j+frame_size<=buffer.length; j+=hop_size) { frame_slices.push(buffer.subarray(j, j+frame_size)) } return function processHopData(data) { var i, j, k buffer.set(data, ptr) ptr += data.length for(i=0, j=0; j+frame_size<=ptr; ++i, j+=hop_size) { onFrame(frame_slices[i]) } for(k=0; j<ptr; ) { buffer.set(frame_slices[i], k) var nhops = Math.ceil((k+frame_size) / hop_size)|0 var nptr = nhops * hop_size if(nptr !== k+frame_size) { nhops -= 1 nptr -= hop_size } i += nhops j += (nptr - k) k = nptr } ptr += k - j } }
javascript
function createHopStream(frame_size, hop_size, onFrame, max_data_size) { if(hop_size > frame_size) { throw new Error("Hop size must be smaller than frame size") } max_data_size = max_data_size || frame_size var buffer = new Float32Array(2*frame_size + max_data_size) var ptr = 0 var frame_slices = [] for(var j=0; j+frame_size<=buffer.length; j+=hop_size) { frame_slices.push(buffer.subarray(j, j+frame_size)) } return function processHopData(data) { var i, j, k buffer.set(data, ptr) ptr += data.length for(i=0, j=0; j+frame_size<=ptr; ++i, j+=hop_size) { onFrame(frame_slices[i]) } for(k=0; j<ptr; ) { buffer.set(frame_slices[i], k) var nhops = Math.ceil((k+frame_size) / hop_size)|0 var nptr = nhops * hop_size if(nptr !== k+frame_size) { nhops -= 1 nptr -= hop_size } i += nhops j += (nptr - k) k = nptr } ptr += k - j } }
[ "function", "createHopStream", "(", "frame_size", ",", "hop_size", ",", "onFrame", ",", "max_data_size", ")", "{", "if", "(", "hop_size", ">", "frame_size", ")", "{", "throw", "new", "Error", "(", "\"Hop size must be smaller than frame size\"", ")", "}", "max_data_size", "=", "max_data_size", "||", "frame_size", "var", "buffer", "=", "new", "Float32Array", "(", "2", "*", "frame_size", "+", "max_data_size", ")", "var", "ptr", "=", "0", "var", "frame_slices", "=", "[", "]", "for", "(", "var", "j", "=", "0", ";", "j", "+", "frame_size", "<=", "buffer", ".", "length", ";", "j", "+=", "hop_size", ")", "{", "frame_slices", ".", "push", "(", "buffer", ".", "subarray", "(", "j", ",", "j", "+", "frame_size", ")", ")", "}", "return", "function", "processHopData", "(", "data", ")", "{", "var", "i", ",", "j", ",", "k", "buffer", ".", "set", "(", "data", ",", "ptr", ")", "ptr", "+=", "data", ".", "length", "for", "(", "i", "=", "0", ",", "j", "=", "0", ";", "j", "+", "frame_size", "<=", "ptr", ";", "++", "i", ",", "j", "+=", "hop_size", ")", "{", "onFrame", "(", "frame_slices", "[", "i", "]", ")", "}", "for", "(", "k", "=", "0", ";", "j", "<", "ptr", ";", ")", "{", "buffer", ".", "set", "(", "frame_slices", "[", "i", "]", ",", "k", ")", "var", "nhops", "=", "Math", ".", "ceil", "(", "(", "k", "+", "frame_size", ")", "/", "hop_size", ")", "|", "0", "var", "nptr", "=", "nhops", "*", "hop_size", "if", "(", "nptr", "!==", "k", "+", "frame_size", ")", "{", "nhops", "-=", "1", "nptr", "-=", "hop_size", "}", "i", "+=", "nhops", "j", "+=", "(", "nptr", "-", "k", ")", "k", "=", "nptr", "}", "ptr", "+=", "k", "-", "j", "}", "}" ]
Slices a stream of frames into a stream of overlapping windows The size of each frame is the same as the size o
[ "Slices", "a", "stream", "of", "frames", "into", "a", "stream", "of", "overlapping", "windows", "The", "size", "of", "each", "frame", "is", "the", "same", "as", "the", "size", "o" ]
b64aff8f0c23cedafa6aaa0dc952ba6e3bfb84dc
https://github.com/mikolalysenko/frame-hop/blob/b64aff8f0c23cedafa6aaa0dc952ba6e3bfb84dc/hop.js#L5-L37
39,788
CTRLLA/ctrllr
Gruntfile.js
function(file, tasks, options) { /** skip if no tasks or checking Gruntfile */ if (!tasks.length || file && file === 'Gruntfile.js') { return ''; } var result = '* ' + file + ' (' + tasks.length + ')\n\n'; /** iterate over tasks, add data */ tasks.forEach(function(task) { result += ' [' + task.lineNumber + ' - ' + task.priority + '] ' + task.line.trim() + '\n'; result += '\n'; }); return result; }
javascript
function(file, tasks, options) { /** skip if no tasks or checking Gruntfile */ if (!tasks.length || file && file === 'Gruntfile.js') { return ''; } var result = '* ' + file + ' (' + tasks.length + ')\n\n'; /** iterate over tasks, add data */ tasks.forEach(function(task) { result += ' [' + task.lineNumber + ' - ' + task.priority + '] ' + task.line.trim() + '\n'; result += '\n'; }); return result; }
[ "function", "(", "file", ",", "tasks", ",", "options", ")", "{", "/** skip if no tasks or checking Gruntfile */", "if", "(", "!", "tasks", ".", "length", "||", "file", "&&", "file", "===", "'Gruntfile.js'", ")", "{", "return", "''", ";", "}", "var", "result", "=", "'* '", "+", "file", "+", "' ('", "+", "tasks", ".", "length", "+", "')\\n\\n'", ";", "/** iterate over tasks, add data */", "tasks", ".", "forEach", "(", "function", "(", "task", ")", "{", "result", "+=", "' ['", "+", "task", ".", "lineNumber", "+", "' - '", "+", "task", ".", "priority", "+", "'] '", "+", "task", ".", "line", ".", "trim", "(", ")", "+", "'\\n'", ";", "result", "+=", "'\\n'", ";", "}", ")", ";", "return", "result", ";", "}" ]
flow for each file
[ "flow", "for", "each", "file" ]
bf7a58de221dd8a083a2c72b7aa14d1f05c8d350
https://github.com/CTRLLA/ctrllr/blob/bf7a58de221dd8a083a2c72b7aa14d1f05c8d350/Gruntfile.js#L90-L107
39,789
StorjOld/bridge-client-javascript
lib/client.js
Client
function Client(uri, options) { if (!(this instanceof Client)) { return new Client(uri, options); } this._options = options || {}; this._options.baseURI = uri || 'https://api.storj.io'; }
javascript
function Client(uri, options) { if (!(this instanceof Client)) { return new Client(uri, options); } this._options = options || {}; this._options.baseURI = uri || 'https://api.storj.io'; }
[ "function", "Client", "(", "uri", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Client", ")", ")", "{", "return", "new", "Client", "(", "uri", ",", "options", ")", ";", "}", "this", ".", "_options", "=", "options", "||", "{", "}", ";", "this", ".", "_options", ".", "baseURI", "=", "uri", "||", "'https://api.storj.io'", ";", "}" ]
Exposes a Storj Bridge API client @constructor @param {String} uri - API base URI ('https://api.storj.io') @param {Object} options @param {storj.KeyPair} options.keypair - KeyPair instance for request signing @param {Object} options.basicauth @param {String} options.basicauth.email - Email address for HTTP basic auth @param {String} options.basicauth.password - Password for HTTP basic auth
[ "Exposes", "a", "Storj", "Bridge", "API", "client" ]
a0778231a649937ad66b0605001bf19f5b007edf
https://github.com/StorjOld/bridge-client-javascript/blob/a0778231a649937ad66b0605001bf19f5b007edf/lib/client.js#L24-L31
39,790
glo-js/glo-mesh
lib/buffer.js
update
function update (data) { this.bind() this.length = data.length this.byteLength = this.length * data.BYTES_PER_ELEMENT this.gl.bufferData(this.type, data, this.usage) }
javascript
function update (data) { this.bind() this.length = data.length this.byteLength = this.length * data.BYTES_PER_ELEMENT this.gl.bufferData(this.type, data, this.usage) }
[ "function", "update", "(", "data", ")", "{", "this", ".", "bind", "(", ")", "this", ".", "length", "=", "data", ".", "length", "this", ".", "byteLength", "=", "this", ".", "length", "*", "data", ".", "BYTES_PER_ELEMENT", "this", ".", "gl", ".", "bufferData", "(", "this", ".", "type", ",", "data", ",", "this", ".", "usage", ")", "}" ]
since this is mostly internal, we will KISS and just stick to typed arrays
[ "since", "this", "is", "mostly", "internal", "we", "will", "KISS", "and", "just", "stick", "to", "typed", "arrays" ]
e2755932f2f0b3c0965e5317f599104ac410902d
https://github.com/glo-js/glo-mesh/blob/e2755932f2f0b3c0965e5317f599104ac410902d/lib/buffer.js#L52-L57
39,791
ceejbot/polyclay
lib/polyclay.js
function() { if (arguments.length === 0) return this.__attributes[propname]; var newval = arguments[0]; this.__attributes[propname] = newval; this.emit('change.' + propname, newval); }
javascript
function() { if (arguments.length === 0) return this.__attributes[propname]; var newval = arguments[0]; this.__attributes[propname] = newval; this.emit('change.' + propname, newval); }
[ "function", "(", ")", "{", "if", "(", "arguments", ".", "length", "===", "0", ")", "return", "this", ".", "__attributes", "[", "propname", "]", ";", "var", "newval", "=", "arguments", "[", "0", "]", ";", "this", ".", "__attributes", "[", "propname", "]", "=", "newval", ";", "this", ".", "emit", "(", "'change.'", "+", "propname", ",", "newval", ")", ";", "}" ]
No type validation on optional properties.
[ "No", "type", "validation", "on", "optional", "properties", "." ]
d4684b511e4d140d25333ec5f9869d34338b52b7
https://github.com/ceejbot/polyclay/blob/d4684b511e4d140d25333ec5f9869d34338b52b7/lib/polyclay.js#L324-L332
39,792
kevoree/kevoree-js
tools/kevoree-gen-model/kevoree-gen-model.js
errHandler
function errHandler(err) { process.stderr.write(chalk.red('Model generation failed!') + '\n'); switch (err.code) { default: case 'PARSE_FAIL': if (!quiet) { process.stderr.write('\n' + err.stack + '\n'); } break; case 'ENOENT': if (!quiet) { process.stderr.write('\n' + err.stack.replace('ENOENT, lstat ', 'unable to find ') + '\n'); } break; } callback(err); }
javascript
function errHandler(err) { process.stderr.write(chalk.red('Model generation failed!') + '\n'); switch (err.code) { default: case 'PARSE_FAIL': if (!quiet) { process.stderr.write('\n' + err.stack + '\n'); } break; case 'ENOENT': if (!quiet) { process.stderr.write('\n' + err.stack.replace('ENOENT, lstat ', 'unable to find ') + '\n'); } break; } callback(err); }
[ "function", "errHandler", "(", "err", ")", "{", "process", ".", "stderr", ".", "write", "(", "chalk", ".", "red", "(", "'Model generation failed!'", ")", "+", "'\\n'", ")", ";", "switch", "(", "err", ".", "code", ")", "{", "default", ":", "case", "'PARSE_FAIL'", ":", "if", "(", "!", "quiet", ")", "{", "process", ".", "stderr", ".", "write", "(", "'\\n'", "+", "err", ".", "stack", "+", "'\\n'", ")", ";", "}", "break", ";", "case", "'ENOENT'", ":", "if", "(", "!", "quiet", ")", "{", "process", ".", "stderr", ".", "write", "(", "'\\n'", "+", "err", ".", "stack", ".", "replace", "(", "'ENOENT, lstat '", ",", "'unable to find '", ")", "+", "'\\n'", ")", ";", "}", "break", ";", "}", "callback", "(", "err", ")", ";", "}" ]
Handles Error object @param err
[ "Handles", "Error", "object" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-gen-model/kevoree-gen-model.js#L24-L42
39,793
stackgl/gl-mat2
adjoint.js
adjoint
function adjoint(out, a) { // Caching this value is nessecary if out == a var a0 = a[0] out[0] = a[3] out[1] = -a[1] out[2] = -a[2] out[3] = a0 return out }
javascript
function adjoint(out, a) { // Caching this value is nessecary if out == a var a0 = a[0] out[0] = a[3] out[1] = -a[1] out[2] = -a[2] out[3] = a0 return out }
[ "function", "adjoint", "(", "out", ",", "a", ")", "{", "// Caching this value is nessecary if out == a", "var", "a0", "=", "a", "[", "0", "]", "out", "[", "0", "]", "=", "a", "[", "3", "]", "out", "[", "1", "]", "=", "-", "a", "[", "1", "]", "out", "[", "2", "]", "=", "-", "a", "[", "2", "]", "out", "[", "3", "]", "=", "a0", "return", "out", "}" ]
Calculates the adjugate of a mat2 @alias mat2.adjoint @param {mat2} out the receiving matrix @param {mat2} a the source matrix @returns {mat2} out
[ "Calculates", "the", "adjugate", "of", "a", "mat2" ]
d6a04d55d605150240dc8e57ca7d2821aaa23c56
https://github.com/stackgl/gl-mat2/blob/d6a04d55d605150240dc8e57ca7d2821aaa23c56/adjoint.js#L11-L20
39,794
eight04/bbs-reader
bbs-reader.js
stripColon
function stripColon(text) { var i = text.indexOf(":"); if (i >= 0) { text = text.substr(i).trim(); if (text[1] == " ") { text = text.substr(1).trim(); } } return text; }
javascript
function stripColon(text) { var i = text.indexOf(":"); if (i >= 0) { text = text.substr(i).trim(); if (text[1] == " ") { text = text.substr(1).trim(); } } return text; }
[ "function", "stripColon", "(", "text", ")", "{", "var", "i", "=", "text", ".", "indexOf", "(", "\":\"", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "text", "=", "text", ".", "substr", "(", "i", ")", ".", "trim", "(", ")", ";", "if", "(", "text", "[", "1", "]", "==", "\" \"", ")", "{", "text", "=", "text", ".", "substr", "(", "1", ")", ".", "trim", "(", ")", ";", "}", "}", "return", "text", ";", "}" ]
Remove label before colon.
[ "Remove", "label", "before", "colon", "." ]
98e90082b0eb39824e9c1581b39e3cc88437dcff
https://github.com/eight04/bbs-reader/blob/98e90082b0eb39824e9c1581b39e3cc88437dcff/bbs-reader.js#L2-L11
39,795
eight04/bbs-reader
bbs-reader.js
splitLabel
function splitLabel(text) { var label = "", right = ""; var i = text.lastIndexOf(":"); if (i >= 0) { right = text.substr(i + 1).trim(); if (right) { text = text.substr(0, i); i = text.lastIndexOf(" "); if (i >= 0) { label = text.substr(i + 1); if (label) { text = text.substr(0, i); } } } } return [text, label, right]; }
javascript
function splitLabel(text) { var label = "", right = ""; var i = text.lastIndexOf(":"); if (i >= 0) { right = text.substr(i + 1).trim(); if (right) { text = text.substr(0, i); i = text.lastIndexOf(" "); if (i >= 0) { label = text.substr(i + 1); if (label) { text = text.substr(0, i); } } } } return [text, label, right]; }
[ "function", "splitLabel", "(", "text", ")", "{", "var", "label", "=", "\"\"", ",", "right", "=", "\"\"", ";", "var", "i", "=", "text", ".", "lastIndexOf", "(", "\":\"", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "right", "=", "text", ".", "substr", "(", "i", "+", "1", ")", ".", "trim", "(", ")", ";", "if", "(", "right", ")", "{", "text", "=", "text", ".", "substr", "(", "0", ",", "i", ")", ";", "i", "=", "text", ".", "lastIndexOf", "(", "\" \"", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "label", "=", "text", ".", "substr", "(", "i", "+", "1", ")", ";", "if", "(", "label", ")", "{", "text", "=", "text", ".", "substr", "(", "0", ",", "i", ")", ";", "}", "}", "}", "}", "return", "[", "text", ",", "label", ",", "right", "]", ";", "}" ]
Split right label
[ "Split", "right", "label" ]
98e90082b0eb39824e9c1581b39e3cc88437dcff
https://github.com/eight04/bbs-reader/blob/98e90082b0eb39824e9c1581b39e3cc88437dcff/bbs-reader.js#L14-L32
39,796
eight04/bbs-reader
bbs-reader.js
makeHead
function makeHead(lLabel, lText, rLabel, rText) { if (!lText) { return ""; } var fillSpace = 78, result = "<div class='line'>"; fillSpace -= 2 + lLabel.length + 1 + lText.length; if (rText) { fillSpace -= 2 + rLabel.length + 2 + rText.length; } if (fillSpace < 0) { fillSpace = 0; } var span = new Span(4, 7, false); span.text = " " + lLabel + " "; result += span.toString(); span.f = 7; span.b = 4; span.text = " " + lText + " ".repeat(fillSpace); result += span.toString(); // result += makeSpan({f:4,b:7,text:" "+lLabel+" "}) + makeSpan({f:7,b:4,text:" "+lText+" ".repeat(fillSpace)}); if (rText) { span.f = 4; span.b = 7; span.text = " " + rLabel + " "; result += span.toString(); span.f = 7; span.b = 4; span.text = " " + rText + " "; result += span.toString(); // result += makeSpan({f:4,b:7,text:" "+rLabel+" "}) + makeSpan({f:7,b:4,text:" "+rText+" "}); } result += "</div>"; return result; }
javascript
function makeHead(lLabel, lText, rLabel, rText) { if (!lText) { return ""; } var fillSpace = 78, result = "<div class='line'>"; fillSpace -= 2 + lLabel.length + 1 + lText.length; if (rText) { fillSpace -= 2 + rLabel.length + 2 + rText.length; } if (fillSpace < 0) { fillSpace = 0; } var span = new Span(4, 7, false); span.text = " " + lLabel + " "; result += span.toString(); span.f = 7; span.b = 4; span.text = " " + lText + " ".repeat(fillSpace); result += span.toString(); // result += makeSpan({f:4,b:7,text:" "+lLabel+" "}) + makeSpan({f:7,b:4,text:" "+lText+" ".repeat(fillSpace)}); if (rText) { span.f = 4; span.b = 7; span.text = " " + rLabel + " "; result += span.toString(); span.f = 7; span.b = 4; span.text = " " + rText + " "; result += span.toString(); // result += makeSpan({f:4,b:7,text:" "+rLabel+" "}) + makeSpan({f:7,b:4,text:" "+rText+" "}); } result += "</div>"; return result; }
[ "function", "makeHead", "(", "lLabel", ",", "lText", ",", "rLabel", ",", "rText", ")", "{", "if", "(", "!", "lText", ")", "{", "return", "\"\"", ";", "}", "var", "fillSpace", "=", "78", ",", "result", "=", "\"<div class='line'>\"", ";", "fillSpace", "-=", "2", "+", "lLabel", ".", "length", "+", "1", "+", "lText", ".", "length", ";", "if", "(", "rText", ")", "{", "fillSpace", "-=", "2", "+", "rLabel", ".", "length", "+", "2", "+", "rText", ".", "length", ";", "}", "if", "(", "fillSpace", "<", "0", ")", "{", "fillSpace", "=", "0", ";", "}", "var", "span", "=", "new", "Span", "(", "4", ",", "7", ",", "false", ")", ";", "span", ".", "text", "=", "\" \"", "+", "lLabel", "+", "\" \"", ";", "result", "+=", "span", ".", "toString", "(", ")", ";", "span", ".", "f", "=", "7", ";", "span", ".", "b", "=", "4", ";", "span", ".", "text", "=", "\" \"", "+", "lText", "+", "\" \"", ".", "repeat", "(", "fillSpace", ")", ";", "result", "+=", "span", ".", "toString", "(", ")", ";", "// result += makeSpan({f:4,b:7,text:\" \"+lLabel+\" \"}) + makeSpan({f:7,b:4,text:\" \"+lText+\" \".repeat(fillSpace)});", "if", "(", "rText", ")", "{", "span", ".", "f", "=", "4", ";", "span", ".", "b", "=", "7", ";", "span", ".", "text", "=", "\" \"", "+", "rLabel", "+", "\" \"", ";", "result", "+=", "span", ".", "toString", "(", ")", ";", "span", ".", "f", "=", "7", ";", "span", ".", "b", "=", "4", ";", "span", ".", "text", "=", "\" \"", "+", "rText", "+", "\" \"", ";", "result", "+=", "span", ".", "toString", "(", ")", ";", "// result += makeSpan({f:4,b:7,text:\" \"+rLabel+\" \"}) + makeSpan({f:7,b:4,text:\" \"+rText+\" \"});", "}", "result", "+=", "\"</div>\"", ";", "return", "result", ";", "}" ]
create head line
[ "create", "head", "line" ]
98e90082b0eb39824e9c1581b39e3cc88437dcff
https://github.com/eight04/bbs-reader/blob/98e90082b0eb39824e9c1581b39e3cc88437dcff/bbs-reader.js#L99-L148
39,797
eight04/bbs-reader
bbs-reader.js
extractColor
function extractColor(text, i, color) { var matches = [], match; text = text.slice(i); while ((match = text.match(/^\x1b\[([\d;]*)m/))) { matches.push(match); text = text.slice(match[0].length); i += match[0].length; } if (!matches.length) { return null; } var tokens = matches.map(function(match){ return match[1].split(";"); }); tokens = Array.prototype.concat.apply([], tokens); var span = color.copy(); span.i = i; var code; for (i = 0; i < tokens.length; i++) { code = +tokens[i]; if (code == 0) { span.reset(); } else if (code == 1) { span.l = true; } else if (code == 5) { span.flash = true; } else if (code == 7) { var t = span.f; span.f = span.b; span.b = t; } else if (code < 40) { span.f = code - 30; } else if (code < 50) { span.b = code - 40; } } return span; }
javascript
function extractColor(text, i, color) { var matches = [], match; text = text.slice(i); while ((match = text.match(/^\x1b\[([\d;]*)m/))) { matches.push(match); text = text.slice(match[0].length); i += match[0].length; } if (!matches.length) { return null; } var tokens = matches.map(function(match){ return match[1].split(";"); }); tokens = Array.prototype.concat.apply([], tokens); var span = color.copy(); span.i = i; var code; for (i = 0; i < tokens.length; i++) { code = +tokens[i]; if (code == 0) { span.reset(); } else if (code == 1) { span.l = true; } else if (code == 5) { span.flash = true; } else if (code == 7) { var t = span.f; span.f = span.b; span.b = t; } else if (code < 40) { span.f = code - 30; } else if (code < 50) { span.b = code - 40; } } return span; }
[ "function", "extractColor", "(", "text", ",", "i", ",", "color", ")", "{", "var", "matches", "=", "[", "]", ",", "match", ";", "text", "=", "text", ".", "slice", "(", "i", ")", ";", "while", "(", "(", "match", "=", "text", ".", "match", "(", "/", "^\\x1b\\[([\\d;]*)m", "/", ")", ")", ")", "{", "matches", ".", "push", "(", "match", ")", ";", "text", "=", "text", ".", "slice", "(", "match", "[", "0", "]", ".", "length", ")", ";", "i", "+=", "match", "[", "0", "]", ".", "length", ";", "}", "if", "(", "!", "matches", ".", "length", ")", "{", "return", "null", ";", "}", "var", "tokens", "=", "matches", ".", "map", "(", "function", "(", "match", ")", "{", "return", "match", "[", "1", "]", ".", "split", "(", "\";\"", ")", ";", "}", ")", ";", "tokens", "=", "Array", ".", "prototype", ".", "concat", ".", "apply", "(", "[", "]", ",", "tokens", ")", ";", "var", "span", "=", "color", ".", "copy", "(", ")", ";", "span", ".", "i", "=", "i", ";", "var", "code", ";", "for", "(", "i", "=", "0", ";", "i", "<", "tokens", ".", "length", ";", "i", "++", ")", "{", "code", "=", "+", "tokens", "[", "i", "]", ";", "if", "(", "code", "==", "0", ")", "{", "span", ".", "reset", "(", ")", ";", "}", "else", "if", "(", "code", "==", "1", ")", "{", "span", ".", "l", "=", "true", ";", "}", "else", "if", "(", "code", "==", "5", ")", "{", "span", ".", "flash", "=", "true", ";", "}", "else", "if", "(", "code", "==", "7", ")", "{", "var", "t", "=", "span", ".", "f", ";", "span", ".", "f", "=", "span", ".", "b", ";", "span", ".", "b", "=", "t", ";", "}", "else", "if", "(", "code", "<", "40", ")", "{", "span", ".", "f", "=", "code", "-", "30", ";", "}", "else", "if", "(", "code", "<", "50", ")", "{", "span", ".", "b", "=", "code", "-", "40", ";", "}", "}", "return", "span", ";", "}" ]
extract text to color
[ "extract", "text", "to", "color" ]
98e90082b0eb39824e9c1581b39e3cc88437dcff
https://github.com/eight04/bbs-reader/blob/98e90082b0eb39824e9c1581b39e3cc88437dcff/bbs-reader.js#L151-L196
39,798
eight04/bbs-reader
bbs-reader.js
bbsReader
function bbsReader(data) { var i = 0, match, result = ""; var author, title, time, label, board; if ((match = /^(\xa7@\xaa\xcc:.*)\n(.*)\n(.*)\n/.exec(data))) { // draw header author = stripColon(match[1]); title = stripColon(match[2]); time = stripColon(match[3]); // find board var t = splitLabel(author); author = t[0]; label = t[1]; board = t[2]; // δ½œθ€… result += makeHead("\xa7@\xaa\xcc", author, label, board); // ζ¨™ι‘Œ result += makeHead("\xbc\xd0\xc3D", title); // ζ™‚ι–“ result += makeHead("\xae\xc9\xb6\xa1", time); // ─ result += "<div class='line'><span class='f6'>" + "\xa2w".repeat(39) + "</span></div>"; i += match[0].length; } var span = new Span(7, 0, false), pos = 0, cleanLine = false, cjk = false; result += "<div class='line'>"; for (; i < data.length; i++) { // Special color if (pos == 0) { var ch = data.substr(i, 2); if (ch == "\xa1\xb0") { // β€» cleanLine = true; span.reset(); span.f = 2; } else if (ch == ": ") { // : cleanLine = true; span.reset(); span.f = 6; } } if (data[i] == "\x1b") { // ESC var span2 = extractColor(data, i, span); if (!span2) { span.text += data[i]; pos++; } else if (cjk && data[span2.i] != "\n") { span.text += data[span2.i]; span.halfEnd = true; result += span.toString(); span2.text += span.text.substring(span.text.length - 2); span2.halfStart = true; pos++; i = span2.i; span = span2; cjk = false; } else { cjk = false; result += span.toString(); if (span2.i <= i) { throw new Error("bbs-reader crashed! infinite loop"); } i = span2.i - 1; span = span2; } } else if (data[i] == "\r" && data[i + 1] == "\n") { continue; } else if (data[i] == "\r" || data[i] == "\n") { result += span.toString() + "</div><div class='line'>"; span.text = ""; span.halfStart = false; span.halfEnd = false; cjk = false; if (cleanLine) { span.reset(); cleanLine = false; } pos = 0; } else { if (cjk) { cjk = false; } else if (data.charCodeAt(i) & 0x80) { cjk = true; } span.text += data[i]; pos++; } } result += span.toString() + "</div>"; return { html: result, title: title, author: author, time: time }; }
javascript
function bbsReader(data) { var i = 0, match, result = ""; var author, title, time, label, board; if ((match = /^(\xa7@\xaa\xcc:.*)\n(.*)\n(.*)\n/.exec(data))) { // draw header author = stripColon(match[1]); title = stripColon(match[2]); time = stripColon(match[3]); // find board var t = splitLabel(author); author = t[0]; label = t[1]; board = t[2]; // δ½œθ€… result += makeHead("\xa7@\xaa\xcc", author, label, board); // ζ¨™ι‘Œ result += makeHead("\xbc\xd0\xc3D", title); // ζ™‚ι–“ result += makeHead("\xae\xc9\xb6\xa1", time); // ─ result += "<div class='line'><span class='f6'>" + "\xa2w".repeat(39) + "</span></div>"; i += match[0].length; } var span = new Span(7, 0, false), pos = 0, cleanLine = false, cjk = false; result += "<div class='line'>"; for (; i < data.length; i++) { // Special color if (pos == 0) { var ch = data.substr(i, 2); if (ch == "\xa1\xb0") { // β€» cleanLine = true; span.reset(); span.f = 2; } else if (ch == ": ") { // : cleanLine = true; span.reset(); span.f = 6; } } if (data[i] == "\x1b") { // ESC var span2 = extractColor(data, i, span); if (!span2) { span.text += data[i]; pos++; } else if (cjk && data[span2.i] != "\n") { span.text += data[span2.i]; span.halfEnd = true; result += span.toString(); span2.text += span.text.substring(span.text.length - 2); span2.halfStart = true; pos++; i = span2.i; span = span2; cjk = false; } else { cjk = false; result += span.toString(); if (span2.i <= i) { throw new Error("bbs-reader crashed! infinite loop"); } i = span2.i - 1; span = span2; } } else if (data[i] == "\r" && data[i + 1] == "\n") { continue; } else if (data[i] == "\r" || data[i] == "\n") { result += span.toString() + "</div><div class='line'>"; span.text = ""; span.halfStart = false; span.halfEnd = false; cjk = false; if (cleanLine) { span.reset(); cleanLine = false; } pos = 0; } else { if (cjk) { cjk = false; } else if (data.charCodeAt(i) & 0x80) { cjk = true; } span.text += data[i]; pos++; } } result += span.toString() + "</div>"; return { html: result, title: title, author: author, time: time }; }
[ "function", "bbsReader", "(", "data", ")", "{", "var", "i", "=", "0", ",", "match", ",", "result", "=", "\"\"", ";", "var", "author", ",", "title", ",", "time", ",", "label", ",", "board", ";", "if", "(", "(", "match", "=", "/", "^(\\xa7@\\xaa\\xcc:.*)\\n(.*)\\n(.*)\\n", "/", ".", "exec", "(", "data", ")", ")", ")", "{", "// draw header ", "author", "=", "stripColon", "(", "match", "[", "1", "]", ")", ";", "title", "=", "stripColon", "(", "match", "[", "2", "]", ")", ";", "time", "=", "stripColon", "(", "match", "[", "3", "]", ")", ";", "// find board", "var", "t", "=", "splitLabel", "(", "author", ")", ";", "author", "=", "t", "[", "0", "]", ";", "label", "=", "t", "[", "1", "]", ";", "board", "=", "t", "[", "2", "]", ";", "// δ½œθ€…", "result", "+=", "makeHead", "(", "\"\\xa7@\\xaa\\xcc\"", ",", "author", ",", "label", ",", "board", ")", ";", "// ζ¨™ι‘Œ", "result", "+=", "makeHead", "(", "\"\\xbc\\xd0\\xc3D\"", ",", "title", ")", ";", "// ζ™‚ι–“", "result", "+=", "makeHead", "(", "\"\\xae\\xc9\\xb6\\xa1\"", ",", "time", ")", ";", "// ─", "result", "+=", "\"<div class='line'><span class='f6'>\"", "+", "\"\\xa2w\"", ".", "repeat", "(", "39", ")", "+", "\"</span></div>\"", ";", "i", "+=", "match", "[", "0", "]", ".", "length", ";", "}", "var", "span", "=", "new", "Span", "(", "7", ",", "0", ",", "false", ")", ",", "pos", "=", "0", ",", "cleanLine", "=", "false", ",", "cjk", "=", "false", ";", "result", "+=", "\"<div class='line'>\"", ";", "for", "(", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "// Special color", "if", "(", "pos", "==", "0", ")", "{", "var", "ch", "=", "data", ".", "substr", "(", "i", ",", "2", ")", ";", "if", "(", "ch", "==", "\"\\xa1\\xb0\"", ")", "{", "// β€»", "cleanLine", "=", "true", ";", "span", ".", "reset", "(", ")", ";", "span", ".", "f", "=", "2", ";", "}", "else", "if", "(", "ch", "==", "\": \"", ")", "{", "// : ", "cleanLine", "=", "true", ";", "span", ".", "reset", "(", ")", ";", "span", ".", "f", "=", "6", ";", "}", "}", "if", "(", "data", "[", "i", "]", "==", "\"\\x1b\"", ")", "{", "// ESC", "var", "span2", "=", "extractColor", "(", "data", ",", "i", ",", "span", ")", ";", "if", "(", "!", "span2", ")", "{", "span", ".", "text", "+=", "data", "[", "i", "]", ";", "pos", "++", ";", "}", "else", "if", "(", "cjk", "&&", "data", "[", "span2", ".", "i", "]", "!=", "\"\\n\"", ")", "{", "span", ".", "text", "+=", "data", "[", "span2", ".", "i", "]", ";", "span", ".", "halfEnd", "=", "true", ";", "result", "+=", "span", ".", "toString", "(", ")", ";", "span2", ".", "text", "+=", "span", ".", "text", ".", "substring", "(", "span", ".", "text", ".", "length", "-", "2", ")", ";", "span2", ".", "halfStart", "=", "true", ";", "pos", "++", ";", "i", "=", "span2", ".", "i", ";", "span", "=", "span2", ";", "cjk", "=", "false", ";", "}", "else", "{", "cjk", "=", "false", ";", "result", "+=", "span", ".", "toString", "(", ")", ";", "if", "(", "span2", ".", "i", "<=", "i", ")", "{", "throw", "new", "Error", "(", "\"bbs-reader crashed! infinite loop\"", ")", ";", "}", "i", "=", "span2", ".", "i", "-", "1", ";", "span", "=", "span2", ";", "}", "}", "else", "if", "(", "data", "[", "i", "]", "==", "\"\\r\"", "&&", "data", "[", "i", "+", "1", "]", "==", "\"\\n\"", ")", "{", "continue", ";", "}", "else", "if", "(", "data", "[", "i", "]", "==", "\"\\r\"", "||", "data", "[", "i", "]", "==", "\"\\n\"", ")", "{", "result", "+=", "span", ".", "toString", "(", ")", "+", "\"</div><div class='line'>\"", ";", "span", ".", "text", "=", "\"\"", ";", "span", ".", "halfStart", "=", "false", ";", "span", ".", "halfEnd", "=", "false", ";", "cjk", "=", "false", ";", "if", "(", "cleanLine", ")", "{", "span", ".", "reset", "(", ")", ";", "cleanLine", "=", "false", ";", "}", "pos", "=", "0", ";", "}", "else", "{", "if", "(", "cjk", ")", "{", "cjk", "=", "false", ";", "}", "else", "if", "(", "data", ".", "charCodeAt", "(", "i", ")", "&", "0x80", ")", "{", "cjk", "=", "true", ";", "}", "span", ".", "text", "+=", "data", "[", "i", "]", ";", "pos", "++", ";", "}", "}", "result", "+=", "span", ".", "toString", "(", ")", "+", "\"</div>\"", ";", "return", "{", "html", ":", "result", ",", "title", ":", "title", ",", "author", ":", "author", ",", "time", ":", "time", "}", ";", "}" ]
convert ansi string into html
[ "convert", "ansi", "string", "into", "html" ]
98e90082b0eb39824e9c1581b39e3cc88437dcff
https://github.com/eight04/bbs-reader/blob/98e90082b0eb39824e9c1581b39e3cc88437dcff/bbs-reader.js#L199-L312
39,799
skerit/protoblast
lib/function_flow.js
forEach
function forEach(data, task, callback) { var wrapTask, isArray, subject, test, len, i; isArray = Array.isArray(data); i = -1; if (isArray) { subject = data; wrapTask = function wrapTask(next) { task(subject[i], i, next); }; } else { subject = Bound.Object.dissect(data); wrapTask = function wrapTask(next) { task(subject[i].value, subject[i].key, next); }; } len = subject.length; test = function test() { return ++i < len; }; return Blast.Collection.Function['while'](test, wrapTask, callback); }
javascript
function forEach(data, task, callback) { var wrapTask, isArray, subject, test, len, i; isArray = Array.isArray(data); i = -1; if (isArray) { subject = data; wrapTask = function wrapTask(next) { task(subject[i], i, next); }; } else { subject = Bound.Object.dissect(data); wrapTask = function wrapTask(next) { task(subject[i].value, subject[i].key, next); }; } len = subject.length; test = function test() { return ++i < len; }; return Blast.Collection.Function['while'](test, wrapTask, callback); }
[ "function", "forEach", "(", "data", ",", "task", ",", "callback", ")", "{", "var", "wrapTask", ",", "isArray", ",", "subject", ",", "test", ",", "len", ",", "i", ";", "isArray", "=", "Array", ".", "isArray", "(", "data", ")", ";", "i", "=", "-", "1", ";", "if", "(", "isArray", ")", "{", "subject", "=", "data", ";", "wrapTask", "=", "function", "wrapTask", "(", "next", ")", "{", "task", "(", "subject", "[", "i", "]", ",", "i", ",", "next", ")", ";", "}", ";", "}", "else", "{", "subject", "=", "Bound", ".", "Object", ".", "dissect", "(", "data", ")", ";", "wrapTask", "=", "function", "wrapTask", "(", "next", ")", "{", "task", "(", "subject", "[", "i", "]", ".", "value", ",", "subject", "[", "i", "]", ".", "key", ",", "next", ")", ";", "}", ";", "}", "len", "=", "subject", ".", "length", ";", "test", "=", "function", "test", "(", ")", "{", "return", "++", "i", "<", "len", ";", "}", ";", "return", "Blast", ".", "Collection", ".", "Function", "[", "'while'", "]", "(", "test", ",", "wrapTask", ",", "callback", ")", ";", "}" ]
Do `task` for each entry in data serially @author Jelle De Loecker <[email protected]> @since 0.1.4 @version 0.1.4 @param {Function} test @param {Function} task @param {Function} callback @return {Object}
[ "Do", "task", "for", "each", "entry", "in", "data", "serially" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_flow.js#L679-L711