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
20,100
mapbox/tcx
index.js
numarray
function numarray(x) { for (var j = 0, o = []; j < x.length; j++) o[j] = parseFloat(x[j]); return o; }
javascript
function numarray(x) { for (var j = 0, o = []; j < x.length; j++) o[j] = parseFloat(x[j]); return o; }
[ "function", "numarray", "(", "x", ")", "{", "for", "(", "var", "j", "=", "0", ",", "o", "=", "[", "]", ";", "j", "<", "x", ".", "length", ";", "j", "++", ")", "o", "[", "j", "]", "=", "parseFloat", "(", "x", "[", "j", "]", ")", ";", "return", "o", ";", "}" ]
cast array x into numbers
[ "cast", "array", "x", "into", "numbers" ]
eb23fee47ad46f42071ac6b94d4fe0c46e17c5a5
https://github.com/mapbox/tcx/blob/eb23fee47ad46f42071ac6b94d4fe0c46e17c5a5/index.js#L10-L13
20,101
evrythng/evrythng.js
dist/evrythng.js
isThenable
function isThenable(o) { var _then, o_type = typeof o; if (o != null && ( o_type == "object" || o_type == "function" ) ) { _then = o.then; } return typeof _then == "function" ? _then : false; }
javascript
function isThenable(o) { var _then, o_type = typeof o; if (o != null && ( o_type == "object" || o_type == "function" ) ) { _then = o.then; } return typeof _then == "function" ? _then : false; }
[ "function", "isThenable", "(", "o", ")", "{", "var", "_then", ",", "o_type", "=", "typeof", "o", ";", "if", "(", "o", "!=", "null", "&&", "(", "o_type", "==", "\"object\"", "||", "o_type", "==", "\"function\"", ")", ")", "{", "_then", "=", "o", ".", "then", ";", "}", "return", "typeof", "_then", "==", "\"function\"", "?", "_then", ":", "false", ";", "}" ]
promise duck typing
[ "promise", "duck", "typing" ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L1205-L1216
20,102
evrythng/evrythng.js
dist/evrythng.js
function (params, noEncode) { if(this.isObject(params)){ var paramsStr = []; for (var key in params) { if (params.hasOwnProperty(key) && params[key] !== undefined) { var value = this.isObject(params[key])? this.buildParams(params[key], true) : params[key]; paramsStr.push((noEncode? key : encodeURIComponent(key)) + '=' + (noEncode? this.escapeSpecials(value) : encodeURIComponent(value))); } } // Build string from the array. return paramsStr.join('&'); } else { return params; } }
javascript
function (params, noEncode) { if(this.isObject(params)){ var paramsStr = []; for (var key in params) { if (params.hasOwnProperty(key) && params[key] !== undefined) { var value = this.isObject(params[key])? this.buildParams(params[key], true) : params[key]; paramsStr.push((noEncode? key : encodeURIComponent(key)) + '=' + (noEncode? this.escapeSpecials(value) : encodeURIComponent(value))); } } // Build string from the array. return paramsStr.join('&'); } else { return params; } }
[ "function", "(", "params", ",", "noEncode", ")", "{", "if", "(", "this", ".", "isObject", "(", "params", ")", ")", "{", "var", "paramsStr", "=", "[", "]", ";", "for", "(", "var", "key", "in", "params", ")", "{", "if", "(", "params", ".", "hasOwnProperty", "(", "key", ")", "&&", "params", "[", "key", "]", "!==", "undefined", ")", "{", "var", "value", "=", "this", ".", "isObject", "(", "params", "[", "key", "]", ")", "?", "this", ".", "buildParams", "(", "params", "[", "key", "]", ",", "true", ")", ":", "params", "[", "key", "]", ";", "paramsStr", ".", "push", "(", "(", "noEncode", "?", "key", ":", "encodeURIComponent", "(", "key", ")", ")", "+", "'='", "+", "(", "noEncode", "?", "this", ".", "escapeSpecials", "(", "value", ")", ":", "encodeURIComponent", "(", "value", ")", ")", ")", ";", "}", "}", "// Build string from the array.", "return", "paramsStr", ".", "join", "(", "'&'", ")", ";", "}", "else", "{", "return", "params", ";", "}", "}" ]
Build URL query string params out of a javascript object. Encode key and value components as they are appended to query string.
[ "Build", "URL", "query", "string", "params", "out", "of", "a", "javascript", "object", ".", "Encode", "key", "and", "value", "components", "as", "they", "are", "appended", "to", "query", "string", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L1570-L1589
20,103
evrythng/evrythng.js
dist/evrythng.js
function(options){ var url = options.apiUrl + (options.url ? options.url : ''); if(options.params) { url += (url.indexOf('?') === -1 ? '?' : '&') + this.buildParams(options.params); } return url; }
javascript
function(options){ var url = options.apiUrl + (options.url ? options.url : ''); if(options.params) { url += (url.indexOf('?') === -1 ? '?' : '&') + this.buildParams(options.params); } return url; }
[ "function", "(", "options", ")", "{", "var", "url", "=", "options", ".", "apiUrl", "+", "(", "options", ".", "url", "?", "options", ".", "url", ":", "''", ")", ";", "if", "(", "options", ".", "params", ")", "{", "url", "+=", "(", "url", ".", "indexOf", "(", "'?'", ")", "===", "-", "1", "?", "'?'", ":", "'&'", ")", "+", "this", ".", "buildParams", "(", "options", ".", "params", ")", ";", "}", "return", "url", ";", "}" ]
Build full URL from a base url and params, if there are any.
[ "Build", "full", "URL", "from", "a", "base", "url", "and", "params", "if", "there", "are", "any", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L1592-L1600
20,104
evrythng/evrythng.js
dist/evrythng.js
function(options){ if (typeof window !== 'undefined' && window.navigator.geolocation) { // Have default options, but allow to extend with custom. var geolocationOptions = this.extend({ maximumAge: 0, timeout: 10000, enableHighAccuracy: true }, options); return new Promise(function (resolve, reject) { window.navigator.geolocation.getCurrentPosition(function (position) { resolve(position); }, function (err) { var errorMessage = 'Geolocation: '; if(err.code === 1) { errorMessage = 'You didn\'t share your location.'; } else if(err.code === 2) { errorMessage = 'Couldn\'t detect your current location.'; } else if(err.code === 3) { errorMessage = 'Retrieving position timed out.'; } else { errorMessage = 'Unknown error.'; } reject(errorMessage); }, geolocationOptions); }); }else{ return new Promise(function (resolve, reject) { reject('Your browser\/environment doesn\'t support geolocation.'); }); } }
javascript
function(options){ if (typeof window !== 'undefined' && window.navigator.geolocation) { // Have default options, but allow to extend with custom. var geolocationOptions = this.extend({ maximumAge: 0, timeout: 10000, enableHighAccuracy: true }, options); return new Promise(function (resolve, reject) { window.navigator.geolocation.getCurrentPosition(function (position) { resolve(position); }, function (err) { var errorMessage = 'Geolocation: '; if(err.code === 1) { errorMessage = 'You didn\'t share your location.'; } else if(err.code === 2) { errorMessage = 'Couldn\'t detect your current location.'; } else if(err.code === 3) { errorMessage = 'Retrieving position timed out.'; } else { errorMessage = 'Unknown error.'; } reject(errorMessage); }, geolocationOptions); }); }else{ return new Promise(function (resolve, reject) { reject('Your browser\/environment doesn\'t support geolocation.'); }); } }
[ "function", "(", "options", ")", "{", "if", "(", "typeof", "window", "!==", "'undefined'", "&&", "window", ".", "navigator", ".", "geolocation", ")", "{", "// Have default options, but allow to extend with custom.", "var", "geolocationOptions", "=", "this", ".", "extend", "(", "{", "maximumAge", ":", "0", ",", "timeout", ":", "10000", ",", "enableHighAccuracy", ":", "true", "}", ",", "options", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "window", ".", "navigator", ".", "geolocation", ".", "getCurrentPosition", "(", "function", "(", "position", ")", "{", "resolve", "(", "position", ")", ";", "}", ",", "function", "(", "err", ")", "{", "var", "errorMessage", "=", "'Geolocation: '", ";", "if", "(", "err", ".", "code", "===", "1", ")", "{", "errorMessage", "=", "'You didn\\'t share your location.'", ";", "}", "else", "if", "(", "err", ".", "code", "===", "2", ")", "{", "errorMessage", "=", "'Couldn\\'t detect your current location.'", ";", "}", "else", "if", "(", "err", ".", "code", "===", "3", ")", "{", "errorMessage", "=", "'Retrieving position timed out.'", ";", "}", "else", "{", "errorMessage", "=", "'Unknown error.'", ";", "}", "reject", "(", "errorMessage", ")", ";", "}", ",", "geolocationOptions", ")", ";", "}", ")", ";", "}", "else", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "reject", "(", "'Your browser\\/environment doesn\\'t support geolocation.'", ")", ";", "}", ")", ";", "}", "}" ]
Get current position using HTML5 Geolocation and resolve promise once it has returned.
[ "Get", "current", "position", "using", "HTML5", "Geolocation", "and", "resolve", "promise", "once", "it", "has", "returned", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L1604-L1643
20,105
evrythng/evrythng.js
dist/evrythng.js
function (customSettings) { if(Utils.isObject(customSettings)){ this.settings = Utils.extend(this.settings, customSettings); }else{ throw new TypeError('Setup should be called with an options object.'); } return this.settings; }
javascript
function (customSettings) { if(Utils.isObject(customSettings)){ this.settings = Utils.extend(this.settings, customSettings); }else{ throw new TypeError('Setup should be called with an options object.'); } return this.settings; }
[ "function", "(", "customSettings", ")", "{", "if", "(", "Utils", ".", "isObject", "(", "customSettings", ")", ")", "{", "this", ".", "settings", "=", "Utils", ".", "extend", "(", "this", ".", "settings", ",", "customSettings", ")", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'Setup should be called with an options object.'", ")", ";", "}", "return", "this", ".", "settings", ";", "}" ]
Setup method allows the developer to change overall settings for every subsequent request. However, these can be overridden for each request as well. Setup merges current settings with the new custom ones.
[ "Setup", "method", "allows", "the", "developer", "to", "change", "overall", "settings", "for", "every", "subsequent", "request", ".", "However", "these", "can", "be", "overridden", "for", "each", "request", "as", "well", ".", "Setup", "merges", "current", "settings", "with", "the", "new", "custom", "ones", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L1797-L1804
20,106
evrythng/evrythng.js
dist/evrythng.js
function (plugin){ if (Utils.isObject(plugin) && Utils.isFunction(plugin.install)) { var installArgs = []; // Inject plugin dependencies as requested, using the synchronous // require API for Require.js and Almond.js. if(plugin.$inject){ plugin.$inject.forEach(function (dependency) { installArgs.push(require(dependency)); }); } plugin.install.apply(plugin, installArgs); return this; } else { throw new TypeError('Plugin must implement \'install()\' method.'); } }
javascript
function (plugin){ if (Utils.isObject(plugin) && Utils.isFunction(plugin.install)) { var installArgs = []; // Inject plugin dependencies as requested, using the synchronous // require API for Require.js and Almond.js. if(plugin.$inject){ plugin.$inject.forEach(function (dependency) { installArgs.push(require(dependency)); }); } plugin.install.apply(plugin, installArgs); return this; } else { throw new TypeError('Plugin must implement \'install()\' method.'); } }
[ "function", "(", "plugin", ")", "{", "if", "(", "Utils", ".", "isObject", "(", "plugin", ")", "&&", "Utils", ".", "isFunction", "(", "plugin", ".", "install", ")", ")", "{", "var", "installArgs", "=", "[", "]", ";", "// Inject plugin dependencies as requested, using the synchronous", "// require API for Require.js and Almond.js.", "if", "(", "plugin", ".", "$inject", ")", "{", "plugin", ".", "$inject", ".", "forEach", "(", "function", "(", "dependency", ")", "{", "installArgs", ".", "push", "(", "require", "(", "dependency", ")", ")", ";", "}", ")", ";", "}", "plugin", ".", "install", ".", "apply", "(", "plugin", ",", "installArgs", ")", ";", "return", "this", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'Plugin must implement \\'install()\\' method.'", ")", ";", "}", "}" ]
Use the passed plugin features by requiring its dependencies and installing it.
[ "Use", "the", "passed", "plugin", "features", "by", "requiring", "its", "dependencies", "and", "installing", "it", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L1808-L1826
20,107
evrythng/evrythng.js
dist/evrythng.js
function (headers) { var parsed = {}; if (headers) { headers = headers.trim().split("\n"); for (var h in headers) { if (headers.hasOwnProperty(h)) { var header = headers[h].match(/([^:]+):(.*)/); parsed[header[1].trim().toLowerCase()] = header[2].trim(); } } } return parsed; }
javascript
function (headers) { var parsed = {}; if (headers) { headers = headers.trim().split("\n"); for (var h in headers) { if (headers.hasOwnProperty(h)) { var header = headers[h].match(/([^:]+):(.*)/); parsed[header[1].trim().toLowerCase()] = header[2].trim(); } } } return parsed; }
[ "function", "(", "headers", ")", "{", "var", "parsed", "=", "{", "}", ";", "if", "(", "headers", ")", "{", "headers", "=", "headers", ".", "trim", "(", ")", ".", "split", "(", "\"\\n\"", ")", ";", "for", "(", "var", "h", "in", "headers", ")", "{", "if", "(", "headers", ".", "hasOwnProperty", "(", "h", ")", ")", "{", "var", "header", "=", "headers", "[", "h", "]", ".", "match", "(", "/", "([^:]+):(.*)", "/", ")", ";", "parsed", "[", "header", "[", "1", "]", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", "]", "=", "header", "[", "2", "]", ".", "trim", "(", ")", ";", "}", "}", "}", "return", "parsed", ";", "}" ]
XMLHttpRequest returns a not very usable single big string with all headers
[ "XMLHttpRequest", "returns", "a", "not", "very", "usable", "single", "big", "string", "with", "all", "headers" ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L1898-L1911
20,108
evrythng/evrythng.js
dist/evrythng.js
_createXhr
function _createXhr(method, url, options) { var xhr = new XMLHttpRequest(); xhr.open(method, url); // Setup headers, including the *Authorization* that holds the Api Key. for (var header in options.headers) { if (options.headers.hasOwnProperty(header)) { xhr.setRequestHeader(header, options.headers[header]); } } // Set timeout. if (options.timeout > 0) { xhr.timeout = options.timeout; } return xhr; }
javascript
function _createXhr(method, url, options) { var xhr = new XMLHttpRequest(); xhr.open(method, url); // Setup headers, including the *Authorization* that holds the Api Key. for (var header in options.headers) { if (options.headers.hasOwnProperty(header)) { xhr.setRequestHeader(header, options.headers[header]); } } // Set timeout. if (options.timeout > 0) { xhr.timeout = options.timeout; } return xhr; }
[ "function", "_createXhr", "(", "method", ",", "url", ",", "options", ")", "{", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "open", "(", "method", ",", "url", ")", ";", "// Setup headers, including the *Authorization* that holds the Api Key.", "for", "(", "var", "header", "in", "options", ".", "headers", ")", "{", "if", "(", "options", ".", "headers", ".", "hasOwnProperty", "(", "header", ")", ")", "{", "xhr", ".", "setRequestHeader", "(", "header", ",", "options", ".", "headers", "[", "header", "]", ")", ";", "}", "}", "// Set timeout.", "if", "(", "options", ".", "timeout", ">", "0", ")", "{", "xhr", ".", "timeout", "=", "options", ".", "timeout", ";", "}", "return", "xhr", ";", "}" ]
Create an asynchronous XHR2 object.
[ "Create", "an", "asynchronous", "XHR2", "object", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L1960-L1978
20,109
evrythng/evrythng.js
dist/evrythng.js
errorHandler
function errorHandler(response) { if (response) { var errorData = _buildError(xhr, url, method, response); Logger.error(errorData); if (errorCallback) { Logger.warnCallbackDeprecation(); errorCallback(errorData); } reject(errorData); } }
javascript
function errorHandler(response) { if (response) { var errorData = _buildError(xhr, url, method, response); Logger.error(errorData); if (errorCallback) { Logger.warnCallbackDeprecation(); errorCallback(errorData); } reject(errorData); } }
[ "function", "errorHandler", "(", "response", ")", "{", "if", "(", "response", ")", "{", "var", "errorData", "=", "_buildError", "(", "xhr", ",", "url", ",", "method", ",", "response", ")", ";", "Logger", ".", "error", "(", "errorData", ")", ";", "if", "(", "errorCallback", ")", "{", "Logger", ".", "warnCallbackDeprecation", "(", ")", ";", "errorCallback", "(", "errorData", ")", ";", "}", "reject", "(", "errorData", ")", ";", "}", "}" ]
Define internal error handler.
[ "Define", "internal", "error", "handler", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L2018-L2029
20,110
evrythng/evrythng.js
dist/evrythng.js
handler
function handler() { try { if (this.readyState === this.DONE) { var response = _buildResponse(this, options.fullResponse); // Resolve or reject promise given the response status. // HTTP status of 2xx is considered a success. if (this.status >= 200 && this.status < 300) { if (successCallback) { Logger.warnCallbackDeprecation(); successCallback(response); } resolve(response); } else { errorHandler(response); } } } catch (exception) { // Do nothing, will be handled by ontimeout. } }
javascript
function handler() { try { if (this.readyState === this.DONE) { var response = _buildResponse(this, options.fullResponse); // Resolve or reject promise given the response status. // HTTP status of 2xx is considered a success. if (this.status >= 200 && this.status < 300) { if (successCallback) { Logger.warnCallbackDeprecation(); successCallback(response); } resolve(response); } else { errorHandler(response); } } } catch (exception) { // Do nothing, will be handled by ontimeout. } }
[ "function", "handler", "(", ")", "{", "try", "{", "if", "(", "this", ".", "readyState", "===", "this", ".", "DONE", ")", "{", "var", "response", "=", "_buildResponse", "(", "this", ",", "options", ".", "fullResponse", ")", ";", "// Resolve or reject promise given the response status.", "// HTTP status of 2xx is considered a success.", "if", "(", "this", ".", "status", ">=", "200", "&&", "this", ".", "status", "<", "300", ")", "{", "if", "(", "successCallback", ")", "{", "Logger", ".", "warnCallbackDeprecation", "(", ")", ";", "successCallback", "(", "response", ")", ";", "}", "resolve", "(", "response", ")", ";", "}", "else", "{", "errorHandler", "(", "response", ")", ";", "}", "}", "}", "catch", "(", "exception", ")", "{", "// Do nothing, will be handled by ontimeout.", "}", "}" ]
Define the response handler.
[ "Define", "the", "response", "handler", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L2032-L2055
20,111
evrythng/evrythng.js
dist/evrythng.js
_buildError
function _buildError(url, status, method, response) { var errorData = response || {}; errorData.status = status; errorData.url = url; errorData.method = method; return errorData; }
javascript
function _buildError(url, status, method, response) { var errorData = response || {}; errorData.status = status; errorData.url = url; errorData.method = method; return errorData; }
[ "function", "_buildError", "(", "url", ",", "status", ",", "method", ",", "response", ")", "{", "var", "errorData", "=", "response", "||", "{", "}", ";", "errorData", ".", "status", "=", "status", ";", "errorData", ".", "url", "=", "url", ";", "errorData", ".", "method", "=", "method", ";", "return", "errorData", ";", "}" ]
Forward EVRYTHNG API error and extend with URL and Method.
[ "Forward", "EVRYTHNG", "API", "error", "and", "extend", "with", "URL", "and", "Method", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L2102-L2110
20,112
evrythng/evrythng.js
dist/evrythng.js
jsonp
function jsonp(options, successCallback, errorCallback) { /*jshint camelcase:false */ options = options || {}; // Define unique callback name. var uniqueName = 'callback_json' + (++counter); // Send all data (including method, api key and data) via GET // request params. var params = options.params || {}; params.callback = uniqueName; params.access_token = options.authorization; params.method = options.method || 'get'; params.data = JSON.stringify(options.data); options.params = params; options.apiUrl = options.apiUrl && options.apiUrl.replace('//api', '//js-api'); // Evrythng REST API default endpoint does not provide JSON-P // support, which '//js-api.evrythng.com' does. var url = Utils.buildUrl(options); // Return a promise and resolve/reject it in the callback function. return new Promise(function(resolve, reject) { // Attach callback as a global method. Evrythng's REST API error // responses always have a status and array of errors. window[uniqueName] = function(response){ if (response.errors && response.status) { var errorData = _buildError(url, response.status, params.method, response); Logger.error(errorData); if(errorCallback) { Logger.warnCallbackDeprecation(); errorCallback(errorData); } reject(errorData); }else { if(successCallback) { Logger.warnCallbackDeprecation(); successCallback(response); } try { response = JSON.parse(response); } catch(e){} resolve(response); } // Remove callback from window. try { delete window[uniqueName]; } catch (e) {} window[uniqueName] = null; }; _load(url, reject); }); }
javascript
function jsonp(options, successCallback, errorCallback) { /*jshint camelcase:false */ options = options || {}; // Define unique callback name. var uniqueName = 'callback_json' + (++counter); // Send all data (including method, api key and data) via GET // request params. var params = options.params || {}; params.callback = uniqueName; params.access_token = options.authorization; params.method = options.method || 'get'; params.data = JSON.stringify(options.data); options.params = params; options.apiUrl = options.apiUrl && options.apiUrl.replace('//api', '//js-api'); // Evrythng REST API default endpoint does not provide JSON-P // support, which '//js-api.evrythng.com' does. var url = Utils.buildUrl(options); // Return a promise and resolve/reject it in the callback function. return new Promise(function(resolve, reject) { // Attach callback as a global method. Evrythng's REST API error // responses always have a status and array of errors. window[uniqueName] = function(response){ if (response.errors && response.status) { var errorData = _buildError(url, response.status, params.method, response); Logger.error(errorData); if(errorCallback) { Logger.warnCallbackDeprecation(); errorCallback(errorData); } reject(errorData); }else { if(successCallback) { Logger.warnCallbackDeprecation(); successCallback(response); } try { response = JSON.parse(response); } catch(e){} resolve(response); } // Remove callback from window. try { delete window[uniqueName]; } catch (e) {} window[uniqueName] = null; }; _load(url, reject); }); }
[ "function", "jsonp", "(", "options", ",", "successCallback", ",", "errorCallback", ")", "{", "/*jshint camelcase:false */", "options", "=", "options", "||", "{", "}", ";", "// Define unique callback name.", "var", "uniqueName", "=", "'callback_json'", "+", "(", "++", "counter", ")", ";", "// Send all data (including method, api key and data) via GET", "// request params.", "var", "params", "=", "options", ".", "params", "||", "{", "}", ";", "params", ".", "callback", "=", "uniqueName", ";", "params", ".", "access_token", "=", "options", ".", "authorization", ";", "params", ".", "method", "=", "options", ".", "method", "||", "'get'", ";", "params", ".", "data", "=", "JSON", ".", "stringify", "(", "options", ".", "data", ")", ";", "options", ".", "params", "=", "params", ";", "options", ".", "apiUrl", "=", "options", ".", "apiUrl", "&&", "options", ".", "apiUrl", ".", "replace", "(", "'//api'", ",", "'//js-api'", ")", ";", "// Evrythng REST API default endpoint does not provide JSON-P", "// support, which '//js-api.evrythng.com' does.", "var", "url", "=", "Utils", ".", "buildUrl", "(", "options", ")", ";", "// Return a promise and resolve/reject it in the callback function.", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// Attach callback as a global method. Evrythng's REST API error", "// responses always have a status and array of errors.", "window", "[", "uniqueName", "]", "=", "function", "(", "response", ")", "{", "if", "(", "response", ".", "errors", "&&", "response", ".", "status", ")", "{", "var", "errorData", "=", "_buildError", "(", "url", ",", "response", ".", "status", ",", "params", ".", "method", ",", "response", ")", ";", "Logger", ".", "error", "(", "errorData", ")", ";", "if", "(", "errorCallback", ")", "{", "Logger", ".", "warnCallbackDeprecation", "(", ")", ";", "errorCallback", "(", "errorData", ")", ";", "}", "reject", "(", "errorData", ")", ";", "}", "else", "{", "if", "(", "successCallback", ")", "{", "Logger", ".", "warnCallbackDeprecation", "(", ")", ";", "successCallback", "(", "response", ")", ";", "}", "try", "{", "response", "=", "JSON", ".", "parse", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "resolve", "(", "response", ")", ";", "}", "// Remove callback from window.", "try", "{", "delete", "window", "[", "uniqueName", "]", ";", "}", "catch", "(", "e", ")", "{", "}", "window", "[", "uniqueName", "]", "=", "null", ";", "}", ";", "_load", "(", "url", ",", "reject", ")", ";", "}", ")", ";", "}" ]
Jsonp method sets prepares the script url with all the information provided and defines the callback handler.
[ "Jsonp", "method", "sets", "prepares", "the", "script", "url", "with", "all", "the", "information", "provided", "and", "defines", "the", "callback", "handler", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L2143-L2208
20,113
evrythng/evrythng.js
dist/evrythng.js
_fillAction
function _fillAction(entity, actionObj, actionType) { if (!(entity instanceof Scope) && !entity.id) { throw new Error('This entity does not have an ID.'); } var ret = actionObj; if (Utils.isArray(actionObj)) { ret = actionObj.map(function (singleAction) { return _fillAction(entity, singleAction, actionType); }); } else { ret.type = actionType !== 'all' && actionType || actionObj.type || ''; _addEntityIdentifier(entity, ret); } return ret; }
javascript
function _fillAction(entity, actionObj, actionType) { if (!(entity instanceof Scope) && !entity.id) { throw new Error('This entity does not have an ID.'); } var ret = actionObj; if (Utils.isArray(actionObj)) { ret = actionObj.map(function (singleAction) { return _fillAction(entity, singleAction, actionType); }); } else { ret.type = actionType !== 'all' && actionType || actionObj.type || ''; _addEntityIdentifier(entity, ret); } return ret; }
[ "function", "_fillAction", "(", "entity", ",", "actionObj", ",", "actionType", ")", "{", "if", "(", "!", "(", "entity", "instanceof", "Scope", ")", "&&", "!", "entity", ".", "id", ")", "{", "throw", "new", "Error", "(", "'This entity does not have an ID.'", ")", ";", "}", "var", "ret", "=", "actionObj", ";", "if", "(", "Utils", ".", "isArray", "(", "actionObj", ")", ")", "{", "ret", "=", "actionObj", ".", "map", "(", "function", "(", "singleAction", ")", "{", "return", "_fillAction", "(", "entity", ",", "singleAction", ",", "actionType", ")", ";", "}", ")", ";", "}", "else", "{", "ret", ".", "type", "=", "actionType", "!==", "'all'", "&&", "actionType", "||", "actionObj", ".", "type", "||", "''", ";", "_addEntityIdentifier", "(", "entity", ",", "ret", ")", ";", "}", "return", "ret", ";", "}" ]
Set the Entity ID of the entity receiving the action as well as the specified action type in the action data.
[ "Set", "the", "Entity", "ID", "of", "the", "entity", "receiving", "the", "action", "as", "well", "as", "the", "specified", "action", "type", "in", "the", "action", "data", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3160-L3180
20,114
evrythng/evrythng.js
dist/evrythng.js
_useBrowserGeolocation
function _useBrowserGeolocation(options) { return (options && options.geolocation !== undefined)? options.geolocation : EVT.settings.geolocation; }
javascript
function _useBrowserGeolocation(options) { return (options && options.geolocation !== undefined)? options.geolocation : EVT.settings.geolocation; }
[ "function", "_useBrowserGeolocation", "(", "options", ")", "{", "return", "(", "options", "&&", "options", ".", "geolocation", "!==", "undefined", ")", "?", "options", ".", "geolocation", ":", "EVT", ".", "settings", ".", "geolocation", ";", "}" ]
Use HTML5 geolocation if explicitly defined in the options or set in the global settings.
[ "Use", "HTML5", "geolocation", "if", "explicitly", "defined", "in", "the", "options", "or", "set", "in", "the", "global", "settings", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3184-L3187
20,115
evrythng/evrythng.js
dist/evrythng.js
function (objData) { // Rename user object argument's *evrythngUser* property to // entity-standard-*id*. var args = arguments; if(objData.evrythngUser){ objData.id = objData.evrythngUser; delete objData.evrythngUser; } args[0] = objData; Entity.apply(this, args); }
javascript
function (objData) { // Rename user object argument's *evrythngUser* property to // entity-standard-*id*. var args = arguments; if(objData.evrythngUser){ objData.id = objData.evrythngUser; delete objData.evrythngUser; } args[0] = objData; Entity.apply(this, args); }
[ "function", "(", "objData", ")", "{", "// Rename user object argument's *evrythngUser* property to", "// entity-standard-*id*.", "var", "args", "=", "arguments", ";", "if", "(", "objData", ".", "evrythngUser", ")", "{", "objData", ".", "id", "=", "objData", ".", "evrythngUser", ";", "delete", "objData", ".", "evrythngUser", ";", "}", "args", "[", "0", "]", "=", "objData", ";", "Entity", ".", "apply", "(", "this", ",", "args", ")", ";", "}" ]
Setup User inheritance from Entity.
[ "Setup", "User", "inheritance", "from", "Entity", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3333-L3345
20,116
evrythng/evrythng.js
dist/evrythng.js
_createAnonymousUser
function _createAnonymousUser() { var $this = this; return EVT.api({ url: this.path, method: 'post', params: { anonymous: true // must be set to create anonymous user }, data: {}, authorization: this.scope.apiKey }).then(function (access) { // Create User Scope return new EVT.User({ id: access.evrythngUser, apiKey: access.evrythngApiKey, type: 'anonymous' }, $this.scope); }); }
javascript
function _createAnonymousUser() { var $this = this; return EVT.api({ url: this.path, method: 'post', params: { anonymous: true // must be set to create anonymous user }, data: {}, authorization: this.scope.apiKey }).then(function (access) { // Create User Scope return new EVT.User({ id: access.evrythngUser, apiKey: access.evrythngApiKey, type: 'anonymous' }, $this.scope); }); }
[ "function", "_createAnonymousUser", "(", ")", "{", "var", "$this", "=", "this", ";", "return", "EVT", ".", "api", "(", "{", "url", ":", "this", ".", "path", ",", "method", ":", "'post'", ",", "params", ":", "{", "anonymous", ":", "true", "// must be set to create anonymous user", "}", ",", "data", ":", "{", "}", ",", "authorization", ":", "this", ".", "scope", ".", "apiKey", "}", ")", ".", "then", "(", "function", "(", "access", ")", "{", "// Create User Scope", "return", "new", "EVT", ".", "User", "(", "{", "id", ":", "access", ".", "evrythngUser", ",", "apiKey", ":", "access", ".", "evrythngApiKey", ",", "type", ":", "'anonymous'", "}", ",", "$this", ".", "scope", ")", ";", "}", ")", ";", "}" ]
Create an anonymous user It's a somewhat different process since anonymous users are created "good to go", they don't need validation.
[ "Create", "an", "anonymous", "user", "It", "s", "a", "somewhat", "different", "process", "since", "anonymous", "users", "are", "created", "good", "to", "go", "they", "don", "t", "need", "validation", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3385-L3404
20,117
evrythng/evrythng.js
dist/evrythng.js
login
function login(options) { // Return promise and resolve once user info is retrieved. return new Promise(function (resolve, reject) { FB.login(function (response) { /*response = authResponse + status*/ _getUser(response).then(function (userResponse) { if(userResponse.user) { /*userResponse = authResponse + status + user*/ resolve(userResponse); } else { // Reject login promise if the user canceled the FB login. reject(userResponse); } }); }, options); }); }
javascript
function login(options) { // Return promise and resolve once user info is retrieved. return new Promise(function (resolve, reject) { FB.login(function (response) { /*response = authResponse + status*/ _getUser(response).then(function (userResponse) { if(userResponse.user) { /*userResponse = authResponse + status + user*/ resolve(userResponse); } else { // Reject login promise if the user canceled the FB login. reject(userResponse); } }); }, options); }); }
[ "function", "login", "(", "options", ")", "{", "// Return promise and resolve once user info is retrieved.", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "FB", ".", "login", "(", "function", "(", "response", ")", "{", "/*response = authResponse + status*/", "_getUser", "(", "response", ")", ".", "then", "(", "function", "(", "userResponse", ")", "{", "if", "(", "userResponse", ".", "user", ")", "{", "/*userResponse = authResponse + status + user*/", "resolve", "(", "userResponse", ")", ";", "}", "else", "{", "// Reject login promise if the user canceled the FB login.", "reject", "(", "userResponse", ")", ";", "}", "}", ")", ";", "}", ",", "options", ")", ";", "}", ")", ";", "}" ]
Invoke standard Facebook login popup, using specified options.
[ "Invoke", "standard", "Facebook", "login", "popup", "using", "specified", "options", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3611-L3638
20,118
evrythng/evrythng.js
dist/evrythng.js
_getUser
function _getUser(response) { if(response.status == 'connected') { // Return a Promise for the response with user details. return new Promise(function (resolve) { // Until here, `response` was FB's auth response. Here // we start to build bigger response by appending the Facebook's // user info in the `user` property. FB.api('/me', { fields: [ 'id', 'first_name', 'last_name' , 'gender', 'link', 'picture', 'locale', 'name', 'timezone', 'updated_time', 'verified' ].toString() }, function (userInfo) { resolve(Utils.extend(response, { user: userInfo })); }); }); }else{ // Return an already resolved promise. return new Promise(function (resolve) { resolve(response); }); } }
javascript
function _getUser(response) { if(response.status == 'connected') { // Return a Promise for the response with user details. return new Promise(function (resolve) { // Until here, `response` was FB's auth response. Here // we start to build bigger response by appending the Facebook's // user info in the `user` property. FB.api('/me', { fields: [ 'id', 'first_name', 'last_name' , 'gender', 'link', 'picture', 'locale', 'name', 'timezone', 'updated_time', 'verified' ].toString() }, function (userInfo) { resolve(Utils.extend(response, { user: userInfo })); }); }); }else{ // Return an already resolved promise. return new Promise(function (resolve) { resolve(response); }); } }
[ "function", "_getUser", "(", "response", ")", "{", "if", "(", "response", ".", "status", "==", "'connected'", ")", "{", "// Return a Promise for the response with user details.", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "// Until here, `response` was FB's auth response. Here", "// we start to build bigger response by appending the Facebook's", "// user info in the `user` property.", "FB", ".", "api", "(", "'/me'", ",", "{", "fields", ":", "[", "'id'", ",", "'first_name'", ",", "'last_name'", ",", "'gender'", ",", "'link'", ",", "'picture'", ",", "'locale'", ",", "'name'", ",", "'timezone'", ",", "'updated_time'", ",", "'verified'", "]", ".", "toString", "(", ")", "}", ",", "function", "(", "userInfo", ")", "{", "resolve", "(", "Utils", ".", "extend", "(", "response", ",", "{", "user", ":", "userInfo", "}", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "// Return an already resolved promise.", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "resolve", "(", "response", ")", ";", "}", ")", ";", "}", "}" ]
Fetch user info from Facebook if user is successfully connected.
[ "Fetch", "user", "info", "from", "Facebook", "if", "user", "is", "successfully", "connected", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3649-L3688
20,119
evrythng/evrythng.js
dist/evrythng.js
authFacebook
function authFacebook(response) { var $this = this; return EVT.api({ url: '/auth/facebook', method: 'post', data: { access: { token: response.authResponse.accessToken } }, authorization: this.apiKey }).then(function (access) { // Create User Scope with the user information and Api Key returned // from the REST API. var user = new EVT.User({ id: access.evrythngUser, apiKey: access.evrythngApiKey }, $this); // Fetch user dto from the platform and then // return initial response // TODO: Introduce proper read when DEV-190 merged return EVT.api({ url: '/users/' + user.id, authorization: user.apiKey }).then(function(userDetails) { // Prepare resolve object. Move Facebook user data to // 'user.facebook' object Utils.extend(user, { facebook: response.user }, true); // Merge user data from the platform to User Scope Utils.extend(user, userDetails, true); response.user = user; return response; }); }); }
javascript
function authFacebook(response) { var $this = this; return EVT.api({ url: '/auth/facebook', method: 'post', data: { access: { token: response.authResponse.accessToken } }, authorization: this.apiKey }).then(function (access) { // Create User Scope with the user information and Api Key returned // from the REST API. var user = new EVT.User({ id: access.evrythngUser, apiKey: access.evrythngApiKey }, $this); // Fetch user dto from the platform and then // return initial response // TODO: Introduce proper read when DEV-190 merged return EVT.api({ url: '/users/' + user.id, authorization: user.apiKey }).then(function(userDetails) { // Prepare resolve object. Move Facebook user data to // 'user.facebook' object Utils.extend(user, { facebook: response.user }, true); // Merge user data from the platform to User Scope Utils.extend(user, userDetails, true); response.user = user; return response; }); }); }
[ "function", "authFacebook", "(", "response", ")", "{", "var", "$this", "=", "this", ";", "return", "EVT", ".", "api", "(", "{", "url", ":", "'/auth/facebook'", ",", "method", ":", "'post'", ",", "data", ":", "{", "access", ":", "{", "token", ":", "response", ".", "authResponse", ".", "accessToken", "}", "}", ",", "authorization", ":", "this", ".", "apiKey", "}", ")", ".", "then", "(", "function", "(", "access", ")", "{", "// Create User Scope with the user information and Api Key returned", "// from the REST API.", "var", "user", "=", "new", "EVT", ".", "User", "(", "{", "id", ":", "access", ".", "evrythngUser", ",", "apiKey", ":", "access", ".", "evrythngApiKey", "}", ",", "$this", ")", ";", "// Fetch user dto from the platform and then", "// return initial response", "// TODO: Introduce proper read when DEV-190 merged", "return", "EVT", ".", "api", "(", "{", "url", ":", "'/users/'", "+", "user", ".", "id", ",", "authorization", ":", "user", ".", "apiKey", "}", ")", ".", "then", "(", "function", "(", "userDetails", ")", "{", "// Prepare resolve object. Move Facebook user data to", "// 'user.facebook' object", "Utils", ".", "extend", "(", "user", ",", "{", "facebook", ":", "response", ".", "user", "}", ",", "true", ")", ";", "// Merge user data from the platform to User Scope", "Utils", ".", "extend", "(", "user", ",", "userDetails", ",", "true", ")", ";", "response", ".", "user", "=", "user", ";", "return", "response", ";", "}", ")", ";", "}", ")", ";", "}" ]
Send authentication request with the Facebook auth token. This method is used on explicit login and when Facebook is initialized in the `EVT.App` constructor.
[ "Send", "authentication", "request", "with", "the", "Facebook", "auth", "token", ".", "This", "method", "is", "used", "on", "explicit", "login", "and", "when", "Facebook", "is", "initialized", "in", "the", "EVT", ".", "App", "constructor", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3868-L3908
20,120
evrythng/evrythng.js
dist/evrythng.js
_authEvrythng
function _authEvrythng(credentials) { var $this = this; return EVT.api({ url: '/auth/evrythng', method: 'post', data: credentials, authorization: this.apiKey }).then(function (access) { // Once it is authenticated, get this user information as well. return EVT.api({ url: '/users/' + access.evrythngUser, authorization: access.evrythngApiKey }).then(function (userInfo) { // Keep nested success handler because we also need the *access* // object returned form the previous call to create the User Scope. var userObj = Utils.extend(userInfo, { id: access.evrythngUser, apiKey: access.evrythngApiKey }); // Create User Scope var user = new EVT.User(userObj, $this); return { user: user }; }); }); }
javascript
function _authEvrythng(credentials) { var $this = this; return EVT.api({ url: '/auth/evrythng', method: 'post', data: credentials, authorization: this.apiKey }).then(function (access) { // Once it is authenticated, get this user information as well. return EVT.api({ url: '/users/' + access.evrythngUser, authorization: access.evrythngApiKey }).then(function (userInfo) { // Keep nested success handler because we also need the *access* // object returned form the previous call to create the User Scope. var userObj = Utils.extend(userInfo, { id: access.evrythngUser, apiKey: access.evrythngApiKey }); // Create User Scope var user = new EVT.User(userObj, $this); return { user: user }; }); }); }
[ "function", "_authEvrythng", "(", "credentials", ")", "{", "var", "$this", "=", "this", ";", "return", "EVT", ".", "api", "(", "{", "url", ":", "'/auth/evrythng'", ",", "method", ":", "'post'", ",", "data", ":", "credentials", ",", "authorization", ":", "this", ".", "apiKey", "}", ")", ".", "then", "(", "function", "(", "access", ")", "{", "// Once it is authenticated, get this user information as well.", "return", "EVT", ".", "api", "(", "{", "url", ":", "'/users/'", "+", "access", ".", "evrythngUser", ",", "authorization", ":", "access", ".", "evrythngApiKey", "}", ")", ".", "then", "(", "function", "(", "userInfo", ")", "{", "// Keep nested success handler because we also need the *access*", "// object returned form the previous call to create the User Scope.", "var", "userObj", "=", "Utils", ".", "extend", "(", "userInfo", ",", "{", "id", ":", "access", ".", "evrythngUser", ",", "apiKey", ":", "access", ".", "evrythngApiKey", "}", ")", ";", "// Create User Scope", "var", "user", "=", "new", "EVT", ".", "User", "(", "userObj", ",", "$this", ")", ";", "return", "{", "user", ":", "user", "}", ";", "}", ")", ";", "}", ")", ";", "}" ]
Send authentication request using Evrythng credentials.
[ "Send", "authentication", "request", "using", "Evrythng", "credentials", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3911-L3942
20,121
evrythng/evrythng.js
dist/evrythng.js
_logoutFacebook
function _logoutFacebook(successCallback, errorCallback) { var $this = this; return Facebook.logout().then(function () { // If successful (always), also logout from Evrythng. return _logoutEvrythng.call($this, successCallback, errorCallback); }); }
javascript
function _logoutFacebook(successCallback, errorCallback) { var $this = this; return Facebook.logout().then(function () { // If successful (always), also logout from Evrythng. return _logoutEvrythng.call($this, successCallback, errorCallback); }); }
[ "function", "_logoutFacebook", "(", "successCallback", ",", "errorCallback", ")", "{", "var", "$this", "=", "this", ";", "return", "Facebook", ".", "logout", "(", ")", ".", "then", "(", "function", "(", ")", "{", "// If successful (always), also logout from Evrythng.", "return", "_logoutEvrythng", ".", "call", "(", "$this", ",", "successCallback", ",", "errorCallback", ")", ";", "}", ")", ";", "}" ]
Logging out with Facebook, logs out out from Facebook and also from Evrythng.
[ "Logging", "out", "with", "Facebook", "logs", "out", "out", "from", "Facebook", "and", "also", "from", "Evrythng", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L3973-L3982
20,122
evrythng/evrythng.js
dist/evrythng.js
readProduct
function readProduct() { if (!this.product) { throw new Error('Thng does not have a product.'); } if (!this.resource) { throw new Error('Thng does not have a resource.'); } return this.resource.scope.product(this.product).read(); }
javascript
function readProduct() { if (!this.product) { throw new Error('Thng does not have a product.'); } if (!this.resource) { throw new Error('Thng does not have a resource.'); } return this.resource.scope.product(this.product).read(); }
[ "function", "readProduct", "(", ")", "{", "if", "(", "!", "this", ".", "product", ")", "{", "throw", "new", "Error", "(", "'Thng does not have a product.'", ")", ";", "}", "if", "(", "!", "this", ".", "resource", ")", "{", "throw", "new", "Error", "(", "'Thng does not have a resource.'", ")", ";", "}", "return", "this", ".", "resource", ".", "scope", ".", "product", "(", "this", ".", "product", ")", ".", "read", "(", ")", ";", "}" ]
When not using `fetchCascade`, this method allows to easily fetch the Product entity of this Thng. It fowards the call to this thng's scope's product resource.
[ "When", "not", "using", "fetchCascade", "this", "method", "allows", "to", "easily", "fetch", "the", "Product", "entity", "of", "this", "Thng", ".", "It", "fowards", "the", "call", "to", "this", "thng", "s", "scope", "s", "product", "resource", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L4406-L4417
20,123
evrythng/evrythng.js
dist/evrythng.js
_normalizeArguments
function _normalizeArguments(obj) { var args = arguments; if (!obj || Utils.isFunction(obj)) { args = Array.prototype.slice.call(arguments, 0); args.unshift({}); } // Split full path (/actions/_custom) - we get three parts: // 1) empty, 2) root path and 3) encoded action type name var url = this.path.split('/'); args[0].url = '/' + url[1]; args[0].params = Utils.extend(args[0].params, { filter: { name: decodeURIComponent(url[2]) } }); return args; }
javascript
function _normalizeArguments(obj) { var args = arguments; if (!obj || Utils.isFunction(obj)) { args = Array.prototype.slice.call(arguments, 0); args.unshift({}); } // Split full path (/actions/_custom) - we get three parts: // 1) empty, 2) root path and 3) encoded action type name var url = this.path.split('/'); args[0].url = '/' + url[1]; args[0].params = Utils.extend(args[0].params, { filter: { name: decodeURIComponent(url[2]) } }); return args; }
[ "function", "_normalizeArguments", "(", "obj", ")", "{", "var", "args", "=", "arguments", ";", "if", "(", "!", "obj", "||", "Utils", ".", "isFunction", "(", "obj", ")", ")", "{", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "args", ".", "unshift", "(", "{", "}", ")", ";", "}", "// Split full path (/actions/_custom) - we get three parts:", "// 1) empty, 2) root path and 3) encoded action type name", "var", "url", "=", "this", ".", "path", ".", "split", "(", "'/'", ")", ";", "args", "[", "0", "]", ".", "url", "=", "'/'", "+", "url", "[", "1", "]", ";", "args", "[", "0", "]", ".", "params", "=", "Utils", ".", "extend", "(", "args", "[", "0", "]", ".", "params", ",", "{", "filter", ":", "{", "name", ":", "decodeURIComponent", "(", "url", "[", "2", "]", ")", "}", "}", ")", ";", "return", "args", ";", "}" ]
Normalize arguments for single request. Override resource url to use action types root path and use name filter. Extend params if user defines other params.
[ "Normalize", "arguments", "for", "single", "request", ".", "Override", "resource", "url", "to", "use", "action", "types", "root", "path", "and", "use", "name", "filter", ".", "Extend", "params", "if", "user", "defines", "other", "params", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L4479-L4499
20,124
evrythng/evrythng.js
dist/evrythng.js
thng
function thng(id) { // To create nested Resources, the collection itself needs // a resource. if(!this.resource) { throw new Error('This Entity does not have a Resource.'); } var path = this.resource.path + '/thngs'; return Resource.constructorFactory(path, EVT.Entity.Thng) .call(this.resource.scope, id); }
javascript
function thng(id) { // To create nested Resources, the collection itself needs // a resource. if(!this.resource) { throw new Error('This Entity does not have a Resource.'); } var path = this.resource.path + '/thngs'; return Resource.constructorFactory(path, EVT.Entity.Thng) .call(this.resource.scope, id); }
[ "function", "thng", "(", "id", ")", "{", "// To create nested Resources, the collection itself needs", "// a resource.", "if", "(", "!", "this", ".", "resource", ")", "{", "throw", "new", "Error", "(", "'This Entity does not have a Resource.'", ")", ";", "}", "var", "path", "=", "this", ".", "resource", ".", "path", "+", "'/thngs'", ";", "return", "Resource", ".", "constructorFactory", "(", "path", ",", "EVT", ".", "Entity", ".", "Thng", ")", ".", "call", "(", "this", ".", "resource", ".", "scope", ",", "id", ")", ";", "}" ]
Custom nested resource constructor for Thngs of a Collection.
[ "Custom", "nested", "resource", "constructor", "for", "Thngs", "of", "a", "Collection", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L4577-L4589
20,125
evrythng/evrythng.js
dist/evrythng.js
collection
function collection(id) { if(!this.resource) { throw new Error('This Entity does not have a Resource.'); } var path = this.resource.path + '/collections'; return Resource.constructorFactory(path, EVT.Entity.Collection) .call(this.resource.scope, id); }
javascript
function collection(id) { if(!this.resource) { throw new Error('This Entity does not have a Resource.'); } var path = this.resource.path + '/collections'; return Resource.constructorFactory(path, EVT.Entity.Collection) .call(this.resource.scope, id); }
[ "function", "collection", "(", "id", ")", "{", "if", "(", "!", "this", ".", "resource", ")", "{", "throw", "new", "Error", "(", "'This Entity does not have a Resource.'", ")", ";", "}", "var", "path", "=", "this", ".", "resource", ".", "path", "+", "'/collections'", ";", "return", "Resource", ".", "constructorFactory", "(", "path", ",", "EVT", ".", "Entity", ".", "Collection", ")", ".", "call", "(", "this", ".", "resource", ".", "scope", ",", "id", ")", ";", "}" ]
Custom nested resource constructor for Collections of a Collection.
[ "Custom", "nested", "resource", "constructor", "for", "Collections", "of", "a", "Collection", "." ]
6fd022b2b37836de4cf517493cef2d93d645be53
https://github.com/evrythng/evrythng.js/blob/6fd022b2b37836de4cf517493cef2d93d645be53/dist/evrythng.js#L4592-L4601
20,126
Pagawa/PgwBrowser
pgwbrowser.js
function() { var userAgent = pgwBrowser.userAgent.toLowerCase(); // Check browser type for (i in browserData) { var browserRegExp = new RegExp(browserData[i].identifier.toLowerCase()); var browserRegExpResult = browserRegExp.exec(userAgent); if (browserRegExpResult != null && browserRegExpResult[1]) { pgwBrowser.browser.name = browserData[i].name; pgwBrowser.browser.group = browserData[i].group; // Check version if (browserData[i].versionIdentifier) { var versionRegExp = new RegExp(browserData[i].versionIdentifier.toLowerCase()); var versionRegExpResult = versionRegExp.exec(userAgent); if (versionRegExpResult != null && versionRegExpResult[1]) { setBrowserVersion(versionRegExpResult[1]); } } else { setBrowserVersion(browserRegExpResult[1]); } break; } } return true; }
javascript
function() { var userAgent = pgwBrowser.userAgent.toLowerCase(); // Check browser type for (i in browserData) { var browserRegExp = new RegExp(browserData[i].identifier.toLowerCase()); var browserRegExpResult = browserRegExp.exec(userAgent); if (browserRegExpResult != null && browserRegExpResult[1]) { pgwBrowser.browser.name = browserData[i].name; pgwBrowser.browser.group = browserData[i].group; // Check version if (browserData[i].versionIdentifier) { var versionRegExp = new RegExp(browserData[i].versionIdentifier.toLowerCase()); var versionRegExpResult = versionRegExp.exec(userAgent); if (versionRegExpResult != null && versionRegExpResult[1]) { setBrowserVersion(versionRegExpResult[1]); } } else { setBrowserVersion(browserRegExpResult[1]); } break; } } return true; }
[ "function", "(", ")", "{", "var", "userAgent", "=", "pgwBrowser", ".", "userAgent", ".", "toLowerCase", "(", ")", ";", "// Check browser type", "for", "(", "i", "in", "browserData", ")", "{", "var", "browserRegExp", "=", "new", "RegExp", "(", "browserData", "[", "i", "]", ".", "identifier", ".", "toLowerCase", "(", ")", ")", ";", "var", "browserRegExpResult", "=", "browserRegExp", ".", "exec", "(", "userAgent", ")", ";", "if", "(", "browserRegExpResult", "!=", "null", "&&", "browserRegExpResult", "[", "1", "]", ")", "{", "pgwBrowser", ".", "browser", ".", "name", "=", "browserData", "[", "i", "]", ".", "name", ";", "pgwBrowser", ".", "browser", ".", "group", "=", "browserData", "[", "i", "]", ".", "group", ";", "// Check version", "if", "(", "browserData", "[", "i", "]", ".", "versionIdentifier", ")", "{", "var", "versionRegExp", "=", "new", "RegExp", "(", "browserData", "[", "i", "]", ".", "versionIdentifier", ".", "toLowerCase", "(", ")", ")", ";", "var", "versionRegExpResult", "=", "versionRegExp", ".", "exec", "(", "userAgent", ")", ";", "if", "(", "versionRegExpResult", "!=", "null", "&&", "versionRegExpResult", "[", "1", "]", ")", "{", "setBrowserVersion", "(", "versionRegExpResult", "[", "1", "]", ")", ";", "}", "}", "else", "{", "setBrowserVersion", "(", "browserRegExpResult", "[", "1", "]", ")", ";", "}", "break", ";", "}", "}", "return", "true", ";", "}" ]
Set browser data
[ "Set", "browser", "data" ]
b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c
https://github.com/Pagawa/PgwBrowser/blob/b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c/pgwbrowser.js#L75-L105
20,127
Pagawa/PgwBrowser
pgwbrowser.js
function(version) { var splitVersion = version.split('.', 2); pgwBrowser.browser.fullVersion = version; // Major version if (splitVersion[0]) { pgwBrowser.browser.majorVersion = parseInt(splitVersion[0]); } // Minor version if (splitVersion[1]) { pgwBrowser.browser.minorVersion = parseInt(splitVersion[1]); } return true; }
javascript
function(version) { var splitVersion = version.split('.', 2); pgwBrowser.browser.fullVersion = version; // Major version if (splitVersion[0]) { pgwBrowser.browser.majorVersion = parseInt(splitVersion[0]); } // Minor version if (splitVersion[1]) { pgwBrowser.browser.minorVersion = parseInt(splitVersion[1]); } return true; }
[ "function", "(", "version", ")", "{", "var", "splitVersion", "=", "version", ".", "split", "(", "'.'", ",", "2", ")", ";", "pgwBrowser", ".", "browser", ".", "fullVersion", "=", "version", ";", "// Major version", "if", "(", "splitVersion", "[", "0", "]", ")", "{", "pgwBrowser", ".", "browser", ".", "majorVersion", "=", "parseInt", "(", "splitVersion", "[", "0", "]", ")", ";", "}", "// Minor version", "if", "(", "splitVersion", "[", "1", "]", ")", "{", "pgwBrowser", ".", "browser", ".", "minorVersion", "=", "parseInt", "(", "splitVersion", "[", "1", "]", ")", ";", "}", "return", "true", ";", "}" ]
Set browser version
[ "Set", "browser", "version" ]
b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c
https://github.com/Pagawa/PgwBrowser/blob/b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c/pgwbrowser.js#L108-L123
20,128
Pagawa/PgwBrowser
pgwbrowser.js
function() { var userAgent = pgwBrowser.userAgent.toLowerCase(); // Check browser type for (i in osData) { var osRegExp = new RegExp(osData[i].identifier.toLowerCase()); var osRegExpResult = osRegExp.exec(userAgent); if (osRegExpResult != null) { pgwBrowser.os.name = osData[i].name; pgwBrowser.os.group = osData[i].group; // Version defined if (osData[i].version) { setOsVersion(osData[i].version, (osData[i].versionSeparator) ? osData[i].versionSeparator : '.'); // Version detected } else if (osRegExpResult[1]) { setOsVersion(osRegExpResult[1], (osData[i].versionSeparator) ? osData[i].versionSeparator : '.'); // Version identifier } else if (osData[i].versionIdentifier) { var versionRegExp = new RegExp(osData[i].versionIdentifier.toLowerCase()); var versionRegExpResult = versionRegExp.exec(userAgent); if (versionRegExpResult != null && versionRegExpResult[1]) { setOsVersion(versionRegExpResult[1], (osData[i].versionSeparator) ? osData[i].versionSeparator : '.'); } } break; } } return true; }
javascript
function() { var userAgent = pgwBrowser.userAgent.toLowerCase(); // Check browser type for (i in osData) { var osRegExp = new RegExp(osData[i].identifier.toLowerCase()); var osRegExpResult = osRegExp.exec(userAgent); if (osRegExpResult != null) { pgwBrowser.os.name = osData[i].name; pgwBrowser.os.group = osData[i].group; // Version defined if (osData[i].version) { setOsVersion(osData[i].version, (osData[i].versionSeparator) ? osData[i].versionSeparator : '.'); // Version detected } else if (osRegExpResult[1]) { setOsVersion(osRegExpResult[1], (osData[i].versionSeparator) ? osData[i].versionSeparator : '.'); // Version identifier } else if (osData[i].versionIdentifier) { var versionRegExp = new RegExp(osData[i].versionIdentifier.toLowerCase()); var versionRegExpResult = versionRegExp.exec(userAgent); if (versionRegExpResult != null && versionRegExpResult[1]) { setOsVersion(versionRegExpResult[1], (osData[i].versionSeparator) ? osData[i].versionSeparator : '.'); } } break; } } return true; }
[ "function", "(", ")", "{", "var", "userAgent", "=", "pgwBrowser", ".", "userAgent", ".", "toLowerCase", "(", ")", ";", "// Check browser type", "for", "(", "i", "in", "osData", ")", "{", "var", "osRegExp", "=", "new", "RegExp", "(", "osData", "[", "i", "]", ".", "identifier", ".", "toLowerCase", "(", ")", ")", ";", "var", "osRegExpResult", "=", "osRegExp", ".", "exec", "(", "userAgent", ")", ";", "if", "(", "osRegExpResult", "!=", "null", ")", "{", "pgwBrowser", ".", "os", ".", "name", "=", "osData", "[", "i", "]", ".", "name", ";", "pgwBrowser", ".", "os", ".", "group", "=", "osData", "[", "i", "]", ".", "group", ";", "// Version defined", "if", "(", "osData", "[", "i", "]", ".", "version", ")", "{", "setOsVersion", "(", "osData", "[", "i", "]", ".", "version", ",", "(", "osData", "[", "i", "]", ".", "versionSeparator", ")", "?", "osData", "[", "i", "]", ".", "versionSeparator", ":", "'.'", ")", ";", "// Version detected", "}", "else", "if", "(", "osRegExpResult", "[", "1", "]", ")", "{", "setOsVersion", "(", "osRegExpResult", "[", "1", "]", ",", "(", "osData", "[", "i", "]", ".", "versionSeparator", ")", "?", "osData", "[", "i", "]", ".", "versionSeparator", ":", "'.'", ")", ";", "// Version identifier", "}", "else", "if", "(", "osData", "[", "i", "]", ".", "versionIdentifier", ")", "{", "var", "versionRegExp", "=", "new", "RegExp", "(", "osData", "[", "i", "]", ".", "versionIdentifier", ".", "toLowerCase", "(", ")", ")", ";", "var", "versionRegExpResult", "=", "versionRegExp", ".", "exec", "(", "userAgent", ")", ";", "if", "(", "versionRegExpResult", "!=", "null", "&&", "versionRegExpResult", "[", "1", "]", ")", "{", "setOsVersion", "(", "versionRegExpResult", "[", "1", "]", ",", "(", "osData", "[", "i", "]", ".", "versionSeparator", ")", "?", "osData", "[", "i", "]", ".", "versionSeparator", ":", "'.'", ")", ";", "}", "}", "break", ";", "}", "}", "return", "true", ";", "}" ]
Set OS data
[ "Set", "OS", "data" ]
b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c
https://github.com/Pagawa/PgwBrowser/blob/b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c/pgwbrowser.js#L126-L161
20,129
Pagawa/PgwBrowser
pgwbrowser.js
function(version, separator) { if (separator.substr(0, 1) == '[') { var splitVersion = version.split(new RegExp(separator, 'g'), 2); } else { var splitVersion = version.split(separator, 2); } if (separator != '.') { version = version.replace(new RegExp(separator, 'g'), '.'); } pgwBrowser.os.fullVersion = version; // Major version if (splitVersion[0]) { pgwBrowser.os.majorVersion = parseInt(splitVersion[0]); } // Minor version if (splitVersion[1]) { pgwBrowser.os.minorVersion = parseInt(splitVersion[1]); } return true; }
javascript
function(version, separator) { if (separator.substr(0, 1) == '[') { var splitVersion = version.split(new RegExp(separator, 'g'), 2); } else { var splitVersion = version.split(separator, 2); } if (separator != '.') { version = version.replace(new RegExp(separator, 'g'), '.'); } pgwBrowser.os.fullVersion = version; // Major version if (splitVersion[0]) { pgwBrowser.os.majorVersion = parseInt(splitVersion[0]); } // Minor version if (splitVersion[1]) { pgwBrowser.os.minorVersion = parseInt(splitVersion[1]); } return true; }
[ "function", "(", "version", ",", "separator", ")", "{", "if", "(", "separator", ".", "substr", "(", "0", ",", "1", ")", "==", "'['", ")", "{", "var", "splitVersion", "=", "version", ".", "split", "(", "new", "RegExp", "(", "separator", ",", "'g'", ")", ",", "2", ")", ";", "}", "else", "{", "var", "splitVersion", "=", "version", ".", "split", "(", "separator", ",", "2", ")", ";", "}", "if", "(", "separator", "!=", "'.'", ")", "{", "version", "=", "version", ".", "replace", "(", "new", "RegExp", "(", "separator", ",", "'g'", ")", ",", "'.'", ")", ";", "}", "pgwBrowser", ".", "os", ".", "fullVersion", "=", "version", ";", "// Major version", "if", "(", "splitVersion", "[", "0", "]", ")", "{", "pgwBrowser", ".", "os", ".", "majorVersion", "=", "parseInt", "(", "splitVersion", "[", "0", "]", ")", ";", "}", "// Minor version", "if", "(", "splitVersion", "[", "1", "]", ")", "{", "pgwBrowser", ".", "os", ".", "minorVersion", "=", "parseInt", "(", "splitVersion", "[", "1", "]", ")", ";", "}", "return", "true", ";", "}" ]
Set OS version
[ "Set", "OS", "version" ]
b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c
https://github.com/Pagawa/PgwBrowser/blob/b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c/pgwbrowser.js#L164-L188
20,130
Pagawa/PgwBrowser
pgwbrowser.js
function(init) { pgwBrowser.viewport.width = $(window).width(); pgwBrowser.viewport.height = $(window).height(); // Resize triggers if (typeof init == 'undefined') { if (resizeEvent == null) { $(window).trigger('PgwBrowser::StartResizing'); } else { clearTimeout(resizeEvent); } resizeEvent = setTimeout(function() { $(window).trigger('PgwBrowser::StopResizing'); clearTimeout(resizeEvent); resizeEvent = null; }, 300); } return true; }
javascript
function(init) { pgwBrowser.viewport.width = $(window).width(); pgwBrowser.viewport.height = $(window).height(); // Resize triggers if (typeof init == 'undefined') { if (resizeEvent == null) { $(window).trigger('PgwBrowser::StartResizing'); } else { clearTimeout(resizeEvent); } resizeEvent = setTimeout(function() { $(window).trigger('PgwBrowser::StopResizing'); clearTimeout(resizeEvent); resizeEvent = null; }, 300); } return true; }
[ "function", "(", "init", ")", "{", "pgwBrowser", ".", "viewport", ".", "width", "=", "$", "(", "window", ")", ".", "width", "(", ")", ";", "pgwBrowser", ".", "viewport", ".", "height", "=", "$", "(", "window", ")", ".", "height", "(", ")", ";", "// Resize triggers", "if", "(", "typeof", "init", "==", "'undefined'", ")", "{", "if", "(", "resizeEvent", "==", "null", ")", "{", "$", "(", "window", ")", ".", "trigger", "(", "'PgwBrowser::StartResizing'", ")", ";", "}", "else", "{", "clearTimeout", "(", "resizeEvent", ")", ";", "}", "resizeEvent", "=", "setTimeout", "(", "function", "(", ")", "{", "$", "(", "window", ")", ".", "trigger", "(", "'PgwBrowser::StopResizing'", ")", ";", "clearTimeout", "(", "resizeEvent", ")", ";", "resizeEvent", "=", "null", ";", "}", ",", "300", ")", ";", "}", "return", "true", ";", "}" ]
Set viewport size
[ "Set", "viewport", "size" ]
b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c
https://github.com/Pagawa/PgwBrowser/blob/b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c/pgwbrowser.js#L191-L211
20,131
Pagawa/PgwBrowser
pgwbrowser.js
function() { if (typeof window.orientation == 'undefined') { if (pgwBrowser.viewport.width >= pgwBrowser.viewport.height) { pgwBrowser.viewport.orientation = 'landscape'; } else { pgwBrowser.viewport.orientation = 'portrait'; } } else { switch(window.orientation) { case -90: case 90: pgwBrowser.viewport.orientation = 'landscape'; break; default: pgwBrowser.viewport.orientation = 'portrait'; break; } } // Orientation trigger $(window).trigger('PgwBrowser::OrientationChange'); return true; }
javascript
function() { if (typeof window.orientation == 'undefined') { if (pgwBrowser.viewport.width >= pgwBrowser.viewport.height) { pgwBrowser.viewport.orientation = 'landscape'; } else { pgwBrowser.viewport.orientation = 'portrait'; } } else { switch(window.orientation) { case -90: case 90: pgwBrowser.viewport.orientation = 'landscape'; break; default: pgwBrowser.viewport.orientation = 'portrait'; break; } } // Orientation trigger $(window).trigger('PgwBrowser::OrientationChange'); return true; }
[ "function", "(", ")", "{", "if", "(", "typeof", "window", ".", "orientation", "==", "'undefined'", ")", "{", "if", "(", "pgwBrowser", ".", "viewport", ".", "width", ">=", "pgwBrowser", ".", "viewport", ".", "height", ")", "{", "pgwBrowser", ".", "viewport", ".", "orientation", "=", "'landscape'", ";", "}", "else", "{", "pgwBrowser", ".", "viewport", ".", "orientation", "=", "'portrait'", ";", "}", "}", "else", "{", "switch", "(", "window", ".", "orientation", ")", "{", "case", "-", "90", ":", "case", "90", ":", "pgwBrowser", ".", "viewport", ".", "orientation", "=", "'landscape'", ";", "break", ";", "default", ":", "pgwBrowser", ".", "viewport", ".", "orientation", "=", "'portrait'", ";", "break", ";", "}", "}", "// Orientation trigger", "$", "(", "window", ")", ".", "trigger", "(", "'PgwBrowser::OrientationChange'", ")", ";", "return", "true", ";", "}" ]
Set viewport orientation
[ "Set", "viewport", "orientation" ]
b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c
https://github.com/Pagawa/PgwBrowser/blob/b9e6ded2a53fde09ce910b8a3ff2ce7e8e86e26c/pgwbrowser.js#L214-L239
20,132
pelias/labels
labelSchema.js
getFirstProperty
function getFirstProperty(fields) { return function(record) { for (var i = 0; i < fields.length; i++) { var fieldValue = record[fields[i]]; if (!_.isEmpty(fieldValue)) { return fieldValue[0]; } } }; }
javascript
function getFirstProperty(fields) { return function(record) { for (var i = 0; i < fields.length; i++) { var fieldValue = record[fields[i]]; if (!_.isEmpty(fieldValue)) { return fieldValue[0]; } } }; }
[ "function", "getFirstProperty", "(", "fields", ")", "{", "return", "function", "(", "record", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fields", ".", "length", ";", "i", "++", ")", "{", "var", "fieldValue", "=", "record", "[", "fields", "[", "i", "]", "]", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "fieldValue", ")", ")", "{", "return", "fieldValue", "[", "0", "]", ";", "}", "}", "}", ";", "}" ]
find the first field of record that has a non-empty value that's not already in labelParts
[ "find", "the", "first", "field", "of", "record", "that", "has", "a", "non", "-", "empty", "value", "that", "s", "not", "already", "in", "labelParts" ]
ccf37c5da217131b889587b10ef90e418b840a89
https://github.com/pelias/labels/blob/ccf37c5da217131b889587b10ef90e418b840a89/labelSchema.js#L4-L17
20,133
pelias/labels
labelSchema.js
getUSADependencyOrCountryValue
function getUSADependencyOrCountryValue(record) { if ('dependency' === record.layer && !_.isEmpty(record.dependency)) { return record.dependency[0]; } else if ('country' === record.layer && !_.isEmpty(record.country)) { return record.country[0]; } if (!_.isEmpty(record.dependency_a)) { return record.dependency_a[0]; } else if (!_.isEmpty(record.dependency)) { return record.dependency[0]; } return record.country_a[0]; }
javascript
function getUSADependencyOrCountryValue(record) { if ('dependency' === record.layer && !_.isEmpty(record.dependency)) { return record.dependency[0]; } else if ('country' === record.layer && !_.isEmpty(record.country)) { return record.country[0]; } if (!_.isEmpty(record.dependency_a)) { return record.dependency_a[0]; } else if (!_.isEmpty(record.dependency)) { return record.dependency[0]; } return record.country_a[0]; }
[ "function", "getUSADependencyOrCountryValue", "(", "record", ")", "{", "if", "(", "'dependency'", "===", "record", ".", "layer", "&&", "!", "_", ".", "isEmpty", "(", "record", ".", "dependency", ")", ")", "{", "return", "record", ".", "dependency", "[", "0", "]", ";", "}", "else", "if", "(", "'country'", "===", "record", ".", "layer", "&&", "!", "_", ".", "isEmpty", "(", "record", ".", "country", ")", ")", "{", "return", "record", ".", "country", "[", "0", "]", ";", "}", "if", "(", "!", "_", ".", "isEmpty", "(", "record", ".", "dependency_a", ")", ")", "{", "return", "record", ".", "dependency_a", "[", "0", "]", ";", "}", "else", "if", "(", "!", "_", ".", "isEmpty", "(", "record", ".", "dependency", ")", ")", "{", "return", "record", ".", "dependency", "[", "0", "]", ";", "}", "return", "record", ".", "country_a", "[", "0", "]", ";", "}" ]
this function generates the last field of the labels for US records 1. use dependency name if layer is dependency, eg - Puerto Rico 2. use country name if layer is country, eg - United States 3. use dependency abbreviation if applicable, eg - San Juan, PR 4. use dependency name if no abbreviation, eg - San Juan, Puerto Rico 5. use country abbreviation, eg - Lancaster, PA, USA
[ "this", "function", "generates", "the", "last", "field", "of", "the", "labels", "for", "US", "records", "1", ".", "use", "dependency", "name", "if", "layer", "is", "dependency", "eg", "-", "Puerto", "Rico", "2", ".", "use", "country", "name", "if", "layer", "is", "country", "eg", "-", "United", "States", "3", ".", "use", "dependency", "abbreviation", "if", "applicable", "eg", "-", "San", "Juan", "PR", "4", ".", "use", "dependency", "name", "if", "no", "abbreviation", "eg", "-", "San", "Juan", "Puerto", "Rico", "5", ".", "use", "country", "abbreviation", "eg", "-", "Lancaster", "PA", "USA" ]
ccf37c5da217131b889587b10ef90e418b840a89
https://github.com/pelias/labels/blob/ccf37c5da217131b889587b10ef90e418b840a89/labelSchema.js#L52-L66
20,134
electerious/Rosid
src/deliver.js
function(bs, event, filePath) { const fileName = path.parse(filePath).base const fileExtension = path.extname(filePath) // Ignore change when filePath is junk if (junk.is(fileName) === true) return // Flush the cache no matter what event was send by Chokidar. // This ensures that we serve the latest files when the user reloads the site. cache.flush(filePath) const styleExtensions = [ '.css', '.scss', '.sass', '.less' ] // Reload stylesheets when the file extension is a known style extension if (styleExtensions.includes(fileExtension) === true) return bs.reload('*.css') const imageExtensions = [ '.png', '.jpg', '.jpeg', '.svg', '.gif', '.webp' ] // Reload images when the file extension is a known image extension supported by Browsersync if (imageExtensions.includes(fileExtension) === true) return bs.reload(`*${ fileExtension }`) bs.reload() }
javascript
function(bs, event, filePath) { const fileName = path.parse(filePath).base const fileExtension = path.extname(filePath) // Ignore change when filePath is junk if (junk.is(fileName) === true) return // Flush the cache no matter what event was send by Chokidar. // This ensures that we serve the latest files when the user reloads the site. cache.flush(filePath) const styleExtensions = [ '.css', '.scss', '.sass', '.less' ] // Reload stylesheets when the file extension is a known style extension if (styleExtensions.includes(fileExtension) === true) return bs.reload('*.css') const imageExtensions = [ '.png', '.jpg', '.jpeg', '.svg', '.gif', '.webp' ] // Reload images when the file extension is a known image extension supported by Browsersync if (imageExtensions.includes(fileExtension) === true) return bs.reload(`*${ fileExtension }`) bs.reload() }
[ "function", "(", "bs", ",", "event", ",", "filePath", ")", "{", "const", "fileName", "=", "path", ".", "parse", "(", "filePath", ")", ".", "base", "const", "fileExtension", "=", "path", ".", "extname", "(", "filePath", ")", "// Ignore change when filePath is junk", "if", "(", "junk", ".", "is", "(", "fileName", ")", "===", "true", ")", "return", "// Flush the cache no matter what event was send by Chokidar.", "// This ensures that we serve the latest files when the user reloads the site.", "cache", ".", "flush", "(", "filePath", ")", "const", "styleExtensions", "=", "[", "'.css'", ",", "'.scss'", ",", "'.sass'", ",", "'.less'", "]", "// Reload stylesheets when the file extension is a known style extension", "if", "(", "styleExtensions", ".", "includes", "(", "fileExtension", ")", "===", "true", ")", "return", "bs", ".", "reload", "(", "'*.css'", ")", "const", "imageExtensions", "=", "[", "'.png'", ",", "'.jpg'", ",", "'.jpeg'", ",", "'.svg'", ",", "'.gif'", ",", "'.webp'", "]", "// Reload images when the file extension is a known image extension supported by Browsersync", "if", "(", "imageExtensions", ".", "includes", "(", "fileExtension", ")", "===", "true", ")", "return", "bs", ".", "reload", "(", "`", "${", "fileExtension", "}", "`", ")", "bs", ".", "reload", "(", ")", "}" ]
Flushes the cache and reloads the site. Should be executed when a file gets updated. @param {Object} bs - Browsersync instance. @param {String} event - Event sent by Chokidar. @param {String} filePath - File affected by event (relative). @returns {?*}
[ "Flushes", "the", "cache", "and", "reloads", "the", "site", ".", "Should", "be", "executed", "when", "a", "file", "gets", "updated", "." ]
1c79742f03463957524341bb953e98d7ae587f94
https://github.com/electerious/Rosid/blob/1c79742f03463957524341bb953e98d7ae587f94/src/deliver.js#L48-L84
20,135
electerious/Rosid
src/copy.js
function(routes, customFiles) { // Always ignore the following files const ignoredFiles = [ '**/CVS', '**/.git', '**/.svn', '**/.hg', '**/.lock-wscript', '**/.wafpickle-N' ] // Extract the path out of the routes const ignoredRoutes = routes.map((route) => route.path) // Return all ignored files return [ ...ignoredFiles, ...ignoredRoutes, ...customFiles ] }
javascript
function(routes, customFiles) { // Always ignore the following files const ignoredFiles = [ '**/CVS', '**/.git', '**/.svn', '**/.hg', '**/.lock-wscript', '**/.wafpickle-N' ] // Extract the path out of the routes const ignoredRoutes = routes.map((route) => route.path) // Return all ignored files return [ ...ignoredFiles, ...ignoredRoutes, ...customFiles ] }
[ "function", "(", "routes", ",", "customFiles", ")", "{", "// Always ignore the following files", "const", "ignoredFiles", "=", "[", "'**/CVS'", ",", "'**/.git'", ",", "'**/.svn'", ",", "'**/.hg'", ",", "'**/.lock-wscript'", ",", "'**/.wafpickle-N'", "]", "// Extract the path out of the routes", "const", "ignoredRoutes", "=", "routes", ".", "map", "(", "(", "route", ")", "=>", "route", ".", "path", ")", "// Return all ignored files", "return", "[", "...", "ignoredFiles", ",", "...", "ignoredRoutes", ",", "...", "customFiles", "]", "}" ]
Get a list of files which should not be copied. @param {Array} routes - Array of route configurations. @param {Array} customFiles - Array of user-defined globs. @returns {Array} ignoredFiles
[ "Get", "a", "list", "of", "files", "which", "should", "not", "be", "copied", "." ]
1c79742f03463957524341bb953e98d7ae587f94
https://github.com/electerious/Rosid/blob/1c79742f03463957524341bb953e98d7ae587f94/src/copy.js#L15-L37
20,136
BridgeAR/safe-stable-stringify
stable.js
stringifyReplacerArr
function stringifyReplacerArr (key, value, stack, replacer) { var i, res // If the value has a toJSON method, call it to obtain a replacement value. if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') { value = value.toJSON(key) } switch (typeof value) { case 'object': if (value === null) { return 'null' } for (i = 0; i < stack.length; i++) { if (stack[i] === value) { return '"[Circular]"' } } if (Array.isArray(value)) { if (value.length === 0) { return '[]' } stack.push(value) res = '[' // Use null as placeholder for non-JSON values. for (i = 0; i < value.length - 1; i++) { const tmp = stringifyReplacerArr(i, value[i], stack, replacer) res += tmp !== undefined ? tmp : 'null' res += ',' } const tmp = stringifyReplacerArr(i, value[i], stack, replacer) res += tmp !== undefined ? tmp : 'null' res += ']' stack.pop() return res } if (replacer.length === 0) { return '{}' } stack.push(value) res = '{' var separator = '' for (i = 0; i < replacer.length; i++) { if (typeof replacer[i] === 'string' || typeof replacer[i] === 'number') { key = replacer[i] const tmp = stringifyReplacerArr(key, value[key], stack, replacer) if (tmp !== undefined) { res += `${separator}"${strEscape(key)}":${tmp}` separator = ',' } } } res += '}' stack.pop() return res case 'string': return `"${strEscape(value)}"` case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null' case 'boolean': return value === true ? 'true' : 'false' } }
javascript
function stringifyReplacerArr (key, value, stack, replacer) { var i, res // If the value has a toJSON method, call it to obtain a replacement value. if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') { value = value.toJSON(key) } switch (typeof value) { case 'object': if (value === null) { return 'null' } for (i = 0; i < stack.length; i++) { if (stack[i] === value) { return '"[Circular]"' } } if (Array.isArray(value)) { if (value.length === 0) { return '[]' } stack.push(value) res = '[' // Use null as placeholder for non-JSON values. for (i = 0; i < value.length - 1; i++) { const tmp = stringifyReplacerArr(i, value[i], stack, replacer) res += tmp !== undefined ? tmp : 'null' res += ',' } const tmp = stringifyReplacerArr(i, value[i], stack, replacer) res += tmp !== undefined ? tmp : 'null' res += ']' stack.pop() return res } if (replacer.length === 0) { return '{}' } stack.push(value) res = '{' var separator = '' for (i = 0; i < replacer.length; i++) { if (typeof replacer[i] === 'string' || typeof replacer[i] === 'number') { key = replacer[i] const tmp = stringifyReplacerArr(key, value[key], stack, replacer) if (tmp !== undefined) { res += `${separator}"${strEscape(key)}":${tmp}` separator = ',' } } } res += '}' stack.pop() return res case 'string': return `"${strEscape(value)}"` case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null' case 'boolean': return value === true ? 'true' : 'false' } }
[ "function", "stringifyReplacerArr", "(", "key", ",", "value", ",", "stack", ",", "replacer", ")", "{", "var", "i", ",", "res", "// If the value has a toJSON method, call it to obtain a replacement value.", "if", "(", "typeof", "value", "===", "'object'", "&&", "value", "!==", "null", "&&", "typeof", "value", ".", "toJSON", "===", "'function'", ")", "{", "value", "=", "value", ".", "toJSON", "(", "key", ")", "}", "switch", "(", "typeof", "value", ")", "{", "case", "'object'", ":", "if", "(", "value", "===", "null", ")", "{", "return", "'null'", "}", "for", "(", "i", "=", "0", ";", "i", "<", "stack", ".", "length", ";", "i", "++", ")", "{", "if", "(", "stack", "[", "i", "]", "===", "value", ")", "{", "return", "'\"[Circular]\"'", "}", "}", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "if", "(", "value", ".", "length", "===", "0", ")", "{", "return", "'[]'", "}", "stack", ".", "push", "(", "value", ")", "res", "=", "'['", "// Use null as placeholder for non-JSON values.", "for", "(", "i", "=", "0", ";", "i", "<", "value", ".", "length", "-", "1", ";", "i", "++", ")", "{", "const", "tmp", "=", "stringifyReplacerArr", "(", "i", ",", "value", "[", "i", "]", ",", "stack", ",", "replacer", ")", "res", "+=", "tmp", "!==", "undefined", "?", "tmp", ":", "'null'", "res", "+=", "','", "}", "const", "tmp", "=", "stringifyReplacerArr", "(", "i", ",", "value", "[", "i", "]", ",", "stack", ",", "replacer", ")", "res", "+=", "tmp", "!==", "undefined", "?", "tmp", ":", "'null'", "res", "+=", "']'", "stack", ".", "pop", "(", ")", "return", "res", "}", "if", "(", "replacer", ".", "length", "===", "0", ")", "{", "return", "'{}'", "}", "stack", ".", "push", "(", "value", ")", "res", "=", "'{'", "var", "separator", "=", "''", "for", "(", "i", "=", "0", ";", "i", "<", "replacer", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "replacer", "[", "i", "]", "===", "'string'", "||", "typeof", "replacer", "[", "i", "]", "===", "'number'", ")", "{", "key", "=", "replacer", "[", "i", "]", "const", "tmp", "=", "stringifyReplacerArr", "(", "key", ",", "value", "[", "key", "]", ",", "stack", ",", "replacer", ")", "if", "(", "tmp", "!==", "undefined", ")", "{", "res", "+=", "`", "${", "separator", "}", "${", "strEscape", "(", "key", ")", "}", "${", "tmp", "}", "`", "separator", "=", "','", "}", "}", "}", "res", "+=", "'}'", "stack", ".", "pop", "(", ")", "return", "res", "case", "'string'", ":", "return", "`", "${", "strEscape", "(", "value", ")", "}", "`", "case", "'number'", ":", "// JSON numbers must be finite. Encode non-finite numbers as null.", "return", "isFinite", "(", "value", ")", "?", "String", "(", "value", ")", ":", "'null'", "case", "'boolean'", ":", "return", "value", "===", "true", "?", "'true'", ":", "'false'", "}", "}" ]
Supports only the replacer option
[ "Supports", "only", "the", "replacer", "option" ]
22674d03b32159b6c5ff05918356ecccefa047dc
https://github.com/BridgeAR/safe-stable-stringify/blob/22674d03b32159b6c5ff05918356ecccefa047dc/stable.js#L350-L413
20,137
BridgeAR/safe-stable-stringify
stable.js
stringifySimple
function stringifySimple (key, value, stack) { var i, res switch (typeof value) { case 'object': if (value === null) { return 'null' } if (typeof value.toJSON === 'function') { value = value.toJSON(key) // Prevent calling `toJSON` again if (typeof value !== 'object') { return stringifySimple(key, value, stack) } if (value === null) { return 'null' } } for (i = 0; i < stack.length; i++) { if (stack[i] === value) { return '"[Circular]"' } } if (Array.isArray(value)) { if (value.length === 0) { return '[]' } stack.push(value) res = '[' // Use null as placeholder for non-JSON values. for (i = 0; i < value.length - 1; i++) { const tmp = stringifySimple(i, value[i], stack) res += tmp !== undefined ? tmp : 'null' res += ',' } const tmp = stringifySimple(i, value[i], stack) res += tmp !== undefined ? tmp : 'null' res += ']' stack.pop() return res } const keys = insertSort(Object.keys(value)) if (keys.length === 0) { return '{}' } stack.push(value) var separator = '' res = '{' for (i = 0; i < keys.length; i++) { key = keys[i] const tmp = stringifySimple(key, value[key], stack) if (tmp !== undefined) { res += `${separator}"${strEscape(key)}":${tmp}` separator = ',' } } res += '}' stack.pop() return res case 'string': return `"${strEscape(value)}"` case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. // Convert the numbers implicit to a string instead of explicit. return isFinite(value) ? String(value) : 'null' case 'boolean': return value === true ? 'true' : 'false' } }
javascript
function stringifySimple (key, value, stack) { var i, res switch (typeof value) { case 'object': if (value === null) { return 'null' } if (typeof value.toJSON === 'function') { value = value.toJSON(key) // Prevent calling `toJSON` again if (typeof value !== 'object') { return stringifySimple(key, value, stack) } if (value === null) { return 'null' } } for (i = 0; i < stack.length; i++) { if (stack[i] === value) { return '"[Circular]"' } } if (Array.isArray(value)) { if (value.length === 0) { return '[]' } stack.push(value) res = '[' // Use null as placeholder for non-JSON values. for (i = 0; i < value.length - 1; i++) { const tmp = stringifySimple(i, value[i], stack) res += tmp !== undefined ? tmp : 'null' res += ',' } const tmp = stringifySimple(i, value[i], stack) res += tmp !== undefined ? tmp : 'null' res += ']' stack.pop() return res } const keys = insertSort(Object.keys(value)) if (keys.length === 0) { return '{}' } stack.push(value) var separator = '' res = '{' for (i = 0; i < keys.length; i++) { key = keys[i] const tmp = stringifySimple(key, value[key], stack) if (tmp !== undefined) { res += `${separator}"${strEscape(key)}":${tmp}` separator = ',' } } res += '}' stack.pop() return res case 'string': return `"${strEscape(value)}"` case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. // Convert the numbers implicit to a string instead of explicit. return isFinite(value) ? String(value) : 'null' case 'boolean': return value === true ? 'true' : 'false' } }
[ "function", "stringifySimple", "(", "key", ",", "value", ",", "stack", ")", "{", "var", "i", ",", "res", "switch", "(", "typeof", "value", ")", "{", "case", "'object'", ":", "if", "(", "value", "===", "null", ")", "{", "return", "'null'", "}", "if", "(", "typeof", "value", ".", "toJSON", "===", "'function'", ")", "{", "value", "=", "value", ".", "toJSON", "(", "key", ")", "// Prevent calling `toJSON` again", "if", "(", "typeof", "value", "!==", "'object'", ")", "{", "return", "stringifySimple", "(", "key", ",", "value", ",", "stack", ")", "}", "if", "(", "value", "===", "null", ")", "{", "return", "'null'", "}", "}", "for", "(", "i", "=", "0", ";", "i", "<", "stack", ".", "length", ";", "i", "++", ")", "{", "if", "(", "stack", "[", "i", "]", "===", "value", ")", "{", "return", "'\"[Circular]\"'", "}", "}", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "if", "(", "value", ".", "length", "===", "0", ")", "{", "return", "'[]'", "}", "stack", ".", "push", "(", "value", ")", "res", "=", "'['", "// Use null as placeholder for non-JSON values.", "for", "(", "i", "=", "0", ";", "i", "<", "value", ".", "length", "-", "1", ";", "i", "++", ")", "{", "const", "tmp", "=", "stringifySimple", "(", "i", ",", "value", "[", "i", "]", ",", "stack", ")", "res", "+=", "tmp", "!==", "undefined", "?", "tmp", ":", "'null'", "res", "+=", "','", "}", "const", "tmp", "=", "stringifySimple", "(", "i", ",", "value", "[", "i", "]", ",", "stack", ")", "res", "+=", "tmp", "!==", "undefined", "?", "tmp", ":", "'null'", "res", "+=", "']'", "stack", ".", "pop", "(", ")", "return", "res", "}", "const", "keys", "=", "insertSort", "(", "Object", ".", "keys", "(", "value", ")", ")", "if", "(", "keys", ".", "length", "===", "0", ")", "{", "return", "'{}'", "}", "stack", ".", "push", "(", "value", ")", "var", "separator", "=", "''", "res", "=", "'{'", "for", "(", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "key", "=", "keys", "[", "i", "]", "const", "tmp", "=", "stringifySimple", "(", "key", ",", "value", "[", "key", "]", ",", "stack", ")", "if", "(", "tmp", "!==", "undefined", ")", "{", "res", "+=", "`", "${", "separator", "}", "${", "strEscape", "(", "key", ")", "}", "${", "tmp", "}", "`", "separator", "=", "','", "}", "}", "res", "+=", "'}'", "stack", ".", "pop", "(", ")", "return", "res", "case", "'string'", ":", "return", "`", "${", "strEscape", "(", "value", ")", "}", "`", "case", "'number'", ":", "// JSON numbers must be finite. Encode non-finite numbers as null.", "// Convert the numbers implicit to a string instead of explicit.", "return", "isFinite", "(", "value", ")", "?", "String", "(", "value", ")", ":", "'null'", "case", "'boolean'", ":", "return", "value", "===", "true", "?", "'true'", ":", "'false'", "}", "}" ]
Simple without any options
[ "Simple", "without", "any", "options" ]
22674d03b32159b6c5ff05918356ecccefa047dc
https://github.com/BridgeAR/safe-stable-stringify/blob/22674d03b32159b6c5ff05918356ecccefa047dc/stable.js#L482-L551
20,138
douban/rexxar-web
lib/utils.js
callUri
function callUri(uri) { var iframe = document.createElement('iframe'); iframe.src = uri; iframe.style.display = 'none'; document.documentElement.appendChild(iframe); setTimeout(function () { return document.documentElement.removeChild(iframe); }, 0); }
javascript
function callUri(uri) { var iframe = document.createElement('iframe'); iframe.src = uri; iframe.style.display = 'none'; document.documentElement.appendChild(iframe); setTimeout(function () { return document.documentElement.removeChild(iframe); }, 0); }
[ "function", "callUri", "(", "uri", ")", "{", "var", "iframe", "=", "document", ".", "createElement", "(", "'iframe'", ")", ";", "iframe", ".", "src", "=", "uri", ";", "iframe", ".", "style", ".", "display", "=", "'none'", ";", "document", ".", "documentElement", ".", "appendChild", "(", "iframe", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "return", "document", ".", "documentElement", ".", "removeChild", "(", "iframe", ")", ";", "}", ",", "0", ")", ";", "}" ]
Go to uri @param {string} uri
[ "Go", "to", "uri" ]
1978aed357369debe6eee7ebd8cb9ee69b451145
https://github.com/douban/rexxar-web/blob/1978aed357369debe6eee7ebd8cb9ee69b451145/lib/utils.js#L95-L103
20,139
ethjs/ethjs-unit
src/index.js
getValueOfUnit
function getValueOfUnit(unitInput) { const unit = unitInput ? unitInput.toLowerCase() : 'ether'; var unitValue = unitMap[unit]; // eslint-disable-line if (typeof unitValue !== 'string') { throw new Error(`[ethjs-unit] the unit provided ${unitInput} doesn't exists, please use the one of the following units ${JSON.stringify(unitMap, null, 2)}`); } return new BN(unitValue, 10); }
javascript
function getValueOfUnit(unitInput) { const unit = unitInput ? unitInput.toLowerCase() : 'ether'; var unitValue = unitMap[unit]; // eslint-disable-line if (typeof unitValue !== 'string') { throw new Error(`[ethjs-unit] the unit provided ${unitInput} doesn't exists, please use the one of the following units ${JSON.stringify(unitMap, null, 2)}`); } return new BN(unitValue, 10); }
[ "function", "getValueOfUnit", "(", "unitInput", ")", "{", "const", "unit", "=", "unitInput", "?", "unitInput", ".", "toLowerCase", "(", ")", ":", "'ether'", ";", "var", "unitValue", "=", "unitMap", "[", "unit", "]", ";", "// eslint-disable-line", "if", "(", "typeof", "unitValue", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "`", "${", "unitInput", "}", "${", "JSON", ".", "stringify", "(", "unitMap", ",", "null", ",", "2", ")", "}", "`", ")", ";", "}", "return", "new", "BN", "(", "unitValue", ",", "10", ")", ";", "}" ]
Returns value of unit in Wei @method getValueOfUnit @param {String} unit the unit to convert to, default ether @returns {BigNumber} value of the unit (in Wei) @throws error if the unit is not correct:w
[ "Returns", "value", "of", "unit", "in", "Wei" ]
35d870eae1c32c652da88837a71e252a63a83ebb
https://github.com/ethjs/ethjs-unit/blob/35d870eae1c32c652da88837a71e252a63a83ebb/src/index.js#L54-L63
20,140
TeamWertarbyte/material-ui-toggle-icon
src/ToggleIcon.js
ToggleIcon
function ToggleIcon (props) { const { classes, offIcon, onIcon, on, ...other } = props return ( <div className={classes.root} {...other}> {React.cloneElement(offIcon, { className: classes.offIcon, style: { ...clipPath(on ? 'polygon(0% 0%, 0% 0%, 0% 0%)' : 'polygon(0% 200%, 0% 0%, 200% 0%)'), visibility: !on || clipPathSupported() ? 'visible' : 'hidden' } })} {React.cloneElement(onIcon, { className: classes.onIcon, style: { ...clipPath(on ? 'polygon(100% -100%, 100% 100%, -100% 100%)' : 'polygon(100% 100%, 100% 100%, 100% 100%)'), visibility: on || clipPathSupported() ? 'visible' : 'hidden' } })} </div> ) }
javascript
function ToggleIcon (props) { const { classes, offIcon, onIcon, on, ...other } = props return ( <div className={classes.root} {...other}> {React.cloneElement(offIcon, { className: classes.offIcon, style: { ...clipPath(on ? 'polygon(0% 0%, 0% 0%, 0% 0%)' : 'polygon(0% 200%, 0% 0%, 200% 0%)'), visibility: !on || clipPathSupported() ? 'visible' : 'hidden' } })} {React.cloneElement(onIcon, { className: classes.onIcon, style: { ...clipPath(on ? 'polygon(100% -100%, 100% 100%, -100% 100%)' : 'polygon(100% 100%, 100% 100%, 100% 100%)'), visibility: on || clipPathSupported() ? 'visible' : 'hidden' } })} </div> ) }
[ "function", "ToggleIcon", "(", "props", ")", "{", "const", "{", "classes", ",", "offIcon", ",", "onIcon", ",", "on", ",", "...", "other", "}", "=", "props", "return", "(", "<", "div", "className", "=", "{", "classes", ".", "root", "}", "{", "...", "other", "}", ">", "\n ", "{", "React", ".", "cloneElement", "(", "offIcon", ",", "{", "className", ":", "classes", ".", "offIcon", ",", "style", ":", "{", "...", "clipPath", "(", "on", "?", "'polygon(0% 0%, 0% 0%, 0% 0%)'", ":", "'polygon(0% 200%, 0% 0%, 200% 0%)'", ")", ",", "visibility", ":", "!", "on", "||", "clipPathSupported", "(", ")", "?", "'visible'", ":", "'hidden'", "}", "}", ")", "}", "\n ", "{", "React", ".", "cloneElement", "(", "onIcon", ",", "{", "className", ":", "classes", ".", "onIcon", ",", "style", ":", "{", "...", "clipPath", "(", "on", "?", "'polygon(100% -100%, 100% 100%, -100% 100%)'", ":", "'polygon(100% 100%, 100% 100%, 100% 100%)'", ")", ",", "visibility", ":", "on", "||", "clipPathSupported", "(", ")", "?", "'visible'", ":", "'hidden'", "}", "}", ")", "}", "\n ", "<", "/", "div", ">", ")", "}" ]
An animated toggle icon.
[ "An", "animated", "toggle", "icon", "." ]
d3ad445735228ad05765b4479f96ef63dca5c7e8
https://github.com/TeamWertarbyte/material-ui-toggle-icon/blob/d3ad445735228ad05765b4479f96ef63dca5c7e8/src/ToggleIcon.js#L39-L66
20,141
mapbox/tiletype
index.js
type
function type(buffer) { if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47 && buffer[4] === 0x0D && buffer[5] === 0x0A && buffer[6] === 0x1A && buffer[7] === 0x0A) { return 'png'; } else if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[buffer.length - 2] === 0xFF && buffer[buffer.length - 1] === 0xD9) { return 'jpg'; } else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38 && (buffer[4] === 0x39 || buffer[4] === 0x37) && buffer[5] === 0x61) { return 'gif'; } else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 && buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) { return 'webp'; // deflate: recklessly assumes contents are PBF. } else if (buffer[0] === 0x78 && buffer[1] === 0x9C) { return 'pbf'; // gzip: recklessly assumes contents are PBF. } else if (buffer[0] === 0x1F && buffer[1] === 0x8B) { return 'pbf'; } return false; }
javascript
function type(buffer) { if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47 && buffer[4] === 0x0D && buffer[5] === 0x0A && buffer[6] === 0x1A && buffer[7] === 0x0A) { return 'png'; } else if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[buffer.length - 2] === 0xFF && buffer[buffer.length - 1] === 0xD9) { return 'jpg'; } else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38 && (buffer[4] === 0x39 || buffer[4] === 0x37) && buffer[5] === 0x61) { return 'gif'; } else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 && buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) { return 'webp'; // deflate: recklessly assumes contents are PBF. } else if (buffer[0] === 0x78 && buffer[1] === 0x9C) { return 'pbf'; // gzip: recklessly assumes contents are PBF. } else if (buffer[0] === 0x1F && buffer[1] === 0x8B) { return 'pbf'; } return false; }
[ "function", "type", "(", "buffer", ")", "{", "if", "(", "buffer", "[", "0", "]", "===", "0x89", "&&", "buffer", "[", "1", "]", "===", "0x50", "&&", "buffer", "[", "2", "]", "===", "0x4E", "&&", "buffer", "[", "3", "]", "===", "0x47", "&&", "buffer", "[", "4", "]", "===", "0x0D", "&&", "buffer", "[", "5", "]", "===", "0x0A", "&&", "buffer", "[", "6", "]", "===", "0x1A", "&&", "buffer", "[", "7", "]", "===", "0x0A", ")", "{", "return", "'png'", ";", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0xFF", "&&", "buffer", "[", "1", "]", "===", "0xD8", "&&", "buffer", "[", "buffer", ".", "length", "-", "2", "]", "===", "0xFF", "&&", "buffer", "[", "buffer", ".", "length", "-", "1", "]", "===", "0xD9", ")", "{", "return", "'jpg'", ";", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0x47", "&&", "buffer", "[", "1", "]", "===", "0x49", "&&", "buffer", "[", "2", "]", "===", "0x46", "&&", "buffer", "[", "3", "]", "===", "0x38", "&&", "(", "buffer", "[", "4", "]", "===", "0x39", "||", "buffer", "[", "4", "]", "===", "0x37", ")", "&&", "buffer", "[", "5", "]", "===", "0x61", ")", "{", "return", "'gif'", ";", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0x52", "&&", "buffer", "[", "1", "]", "===", "0x49", "&&", "buffer", "[", "2", "]", "===", "0x46", "&&", "buffer", "[", "3", "]", "===", "0x46", "&&", "buffer", "[", "8", "]", "===", "0x57", "&&", "buffer", "[", "9", "]", "===", "0x45", "&&", "buffer", "[", "10", "]", "===", "0x42", "&&", "buffer", "[", "11", "]", "===", "0x50", ")", "{", "return", "'webp'", ";", "// deflate: recklessly assumes contents are PBF.", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0x78", "&&", "buffer", "[", "1", "]", "===", "0x9C", ")", "{", "return", "'pbf'", ";", "// gzip: recklessly assumes contents are PBF.", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0x1F", "&&", "buffer", "[", "1", "]", "===", "0x8B", ")", "{", "return", "'pbf'", ";", "}", "return", "false", ";", "}" ]
Given a buffer of unknown data, return either a format as an extension string or false if the type cannot be determined. Potential options are: * png * pbf * jpg * webp @param {Buffer} buffer input @returns {String|boolean} identifier
[ "Given", "a", "buffer", "of", "unknown", "data", "return", "either", "a", "format", "as", "an", "extension", "string", "or", "false", "if", "the", "type", "cannot", "be", "determined", "." ]
cbb803ffaa24f8035c5a464a44139025979d644f
https://github.com/mapbox/tiletype/blob/cbb803ffaa24f8035c5a464a44139025979d644f/index.js#L20-L43
20,142
mapbox/tiletype
index.js
headers
function headers(buffer) { var head = {}; if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47 && buffer[4] === 0x0D && buffer[5] === 0x0A && buffer[6] === 0x1A && buffer[7] === 0x0A) { head['Content-Type'] = 'image/png'; } else if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[buffer.length - 2] === 0xFF && buffer[buffer.length - 1] === 0xD9) { head['Content-Type'] = 'image/jpeg'; } else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38 && (buffer[4] === 0x39 || buffer[4] === 0x37) && buffer[5] === 0x61) { head['Content-Type'] = 'image/gif'; } else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 && buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) { head['Content-Type'] = 'image/webp'; // deflate: recklessly assumes contents are PBF. } else if (buffer[0] === 0x78 && buffer[1] === 0x9C) { head['Content-Type'] = 'application/x-protobuf'; head['Content-Encoding'] = 'deflate'; // gzip: recklessly assumes contents are PBF. } else if (buffer[0] === 0x1F && buffer[1] === 0x8B) { head['Content-Type'] = 'application/x-protobuf'; head['Content-Encoding'] = 'gzip'; } return head; }
javascript
function headers(buffer) { var head = {}; if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47 && buffer[4] === 0x0D && buffer[5] === 0x0A && buffer[6] === 0x1A && buffer[7] === 0x0A) { head['Content-Type'] = 'image/png'; } else if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[buffer.length - 2] === 0xFF && buffer[buffer.length - 1] === 0xD9) { head['Content-Type'] = 'image/jpeg'; } else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38 && (buffer[4] === 0x39 || buffer[4] === 0x37) && buffer[5] === 0x61) { head['Content-Type'] = 'image/gif'; } else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 && buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) { head['Content-Type'] = 'image/webp'; // deflate: recklessly assumes contents are PBF. } else if (buffer[0] === 0x78 && buffer[1] === 0x9C) { head['Content-Type'] = 'application/x-protobuf'; head['Content-Encoding'] = 'deflate'; // gzip: recklessly assumes contents are PBF. } else if (buffer[0] === 0x1F && buffer[1] === 0x8B) { head['Content-Type'] = 'application/x-protobuf'; head['Content-Encoding'] = 'gzip'; } return head; }
[ "function", "headers", "(", "buffer", ")", "{", "var", "head", "=", "{", "}", ";", "if", "(", "buffer", "[", "0", "]", "===", "0x89", "&&", "buffer", "[", "1", "]", "===", "0x50", "&&", "buffer", "[", "2", "]", "===", "0x4E", "&&", "buffer", "[", "3", "]", "===", "0x47", "&&", "buffer", "[", "4", "]", "===", "0x0D", "&&", "buffer", "[", "5", "]", "===", "0x0A", "&&", "buffer", "[", "6", "]", "===", "0x1A", "&&", "buffer", "[", "7", "]", "===", "0x0A", ")", "{", "head", "[", "'Content-Type'", "]", "=", "'image/png'", ";", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0xFF", "&&", "buffer", "[", "1", "]", "===", "0xD8", "&&", "buffer", "[", "buffer", ".", "length", "-", "2", "]", "===", "0xFF", "&&", "buffer", "[", "buffer", ".", "length", "-", "1", "]", "===", "0xD9", ")", "{", "head", "[", "'Content-Type'", "]", "=", "'image/jpeg'", ";", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0x47", "&&", "buffer", "[", "1", "]", "===", "0x49", "&&", "buffer", "[", "2", "]", "===", "0x46", "&&", "buffer", "[", "3", "]", "===", "0x38", "&&", "(", "buffer", "[", "4", "]", "===", "0x39", "||", "buffer", "[", "4", "]", "===", "0x37", ")", "&&", "buffer", "[", "5", "]", "===", "0x61", ")", "{", "head", "[", "'Content-Type'", "]", "=", "'image/gif'", ";", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0x52", "&&", "buffer", "[", "1", "]", "===", "0x49", "&&", "buffer", "[", "2", "]", "===", "0x46", "&&", "buffer", "[", "3", "]", "===", "0x46", "&&", "buffer", "[", "8", "]", "===", "0x57", "&&", "buffer", "[", "9", "]", "===", "0x45", "&&", "buffer", "[", "10", "]", "===", "0x42", "&&", "buffer", "[", "11", "]", "===", "0x50", ")", "{", "head", "[", "'Content-Type'", "]", "=", "'image/webp'", ";", "// deflate: recklessly assumes contents are PBF.", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0x78", "&&", "buffer", "[", "1", "]", "===", "0x9C", ")", "{", "head", "[", "'Content-Type'", "]", "=", "'application/x-protobuf'", ";", "head", "[", "'Content-Encoding'", "]", "=", "'deflate'", ";", "// gzip: recklessly assumes contents are PBF.", "}", "else", "if", "(", "buffer", "[", "0", "]", "===", "0x1F", "&&", "buffer", "[", "1", "]", "===", "0x8B", ")", "{", "head", "[", "'Content-Type'", "]", "=", "'application/x-protobuf'", ";", "head", "[", "'Content-Encoding'", "]", "=", "'gzip'", ";", "}", "return", "head", ";", "}" ]
Return headers - Content-Type and Content-Encoding - for a response containing this kind of image. @param {Buffer} buffer input @returns {Object} headers
[ "Return", "headers", "-", "Content", "-", "Type", "and", "Content", "-", "Encoding", "-", "for", "a", "response", "containing", "this", "kind", "of", "image", "." ]
cbb803ffaa24f8035c5a464a44139025979d644f
https://github.com/mapbox/tiletype/blob/cbb803ffaa24f8035c5a464a44139025979d644f/index.js#L52-L78
20,143
jonschlinkert/delete-empty
index.js
isEmpty
function isEmpty(files, dir, acc, opts) { var filter = opts.filter || isGarbageFile; for (const file of files) { const fp = path.join(dir, file); if (opts.dryRun && acc.indexOf(fp) !== -1) { continue; } if (filter(fp) === false) { return false; } } return true; }
javascript
function isEmpty(files, dir, acc, opts) { var filter = opts.filter || isGarbageFile; for (const file of files) { const fp = path.join(dir, file); if (opts.dryRun && acc.indexOf(fp) !== -1) { continue; } if (filter(fp) === false) { return false; } } return true; }
[ "function", "isEmpty", "(", "files", ",", "dir", ",", "acc", ",", "opts", ")", "{", "var", "filter", "=", "opts", ".", "filter", "||", "isGarbageFile", ";", "for", "(", "const", "file", "of", "files", ")", "{", "const", "fp", "=", "path", ".", "join", "(", "dir", ",", "file", ")", ";", "if", "(", "opts", ".", "dryRun", "&&", "acc", ".", "indexOf", "(", "fp", ")", "!==", "-", "1", ")", "{", "continue", ";", "}", "if", "(", "filter", "(", "fp", ")", "===", "false", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Return true if the given `files` array has zero length or only includes unwanted files.
[ "Return", "true", "if", "the", "given", "files", "array", "has", "zero", "length", "or", "only", "includes", "unwanted", "files", "." ]
2c7a5ea748a171c21b2bdba62b52bb7d951b7072
https://github.com/jonschlinkert/delete-empty/blob/2c7a5ea748a171c21b2bdba62b52bb7d951b7072/index.js#L126-L139
20,144
lepture/nico
lib/writers/core.js
postCompareFunc
function postCompareFunc(a, b) { var sortType = option.get('sorttype'); var diff = new Date(a.meta.pubdate) - new Date(b.meta.pubdate); return sortType === 'asc' ? diff : -diff; }
javascript
function postCompareFunc(a, b) { var sortType = option.get('sorttype'); var diff = new Date(a.meta.pubdate) - new Date(b.meta.pubdate); return sortType === 'asc' ? diff : -diff; }
[ "function", "postCompareFunc", "(", "a", ",", "b", ")", "{", "var", "sortType", "=", "option", ".", "get", "(", "'sorttype'", ")", ";", "var", "diff", "=", "new", "Date", "(", "a", ".", "meta", ".", "pubdate", ")", "-", "new", "Date", "(", "b", ".", "meta", ".", "pubdate", ")", ";", "return", "sortType", "===", "'asc'", "?", "diff", ":", "-", "diff", ";", "}" ]
compare two posts by pubdate
[ "compare", "two", "posts", "by", "pubdate" ]
e40be28e48aeb88e03ea07edb0ee1d48a9da74b5
https://github.com/lepture/nico/blob/e40be28e48aeb88e03ea07edb0ee1d48a9da74b5/lib/writers/core.js#L350-L354
20,145
FGRibreau/check-build
src/interface/_utils.js
downloadDistantOrLoad
function downloadDistantOrLoad(fileUrl, f) { if (!fileUrl || !_.isString(fileUrl)) { return f(); } var filename = path.basename(url.parse(fileUrl).path); debug('downloading %s -> %s', fileUrl, filename); request({ url: fileUrl }, function (err, resp, body) { if (err) { return f(err); } if (resp.statusCode < 200 || resp.statusCode >= 300) { return f(new Error('Invalid HTTP Status code "' + resp.statusCode + '" for "' + fileUrl + '"')); } fs.writeFileSync(path.resolve(process.cwd(), filename), body); f(); }); }
javascript
function downloadDistantOrLoad(fileUrl, f) { if (!fileUrl || !_.isString(fileUrl)) { return f(); } var filename = path.basename(url.parse(fileUrl).path); debug('downloading %s -> %s', fileUrl, filename); request({ url: fileUrl }, function (err, resp, body) { if (err) { return f(err); } if (resp.statusCode < 200 || resp.statusCode >= 300) { return f(new Error('Invalid HTTP Status code "' + resp.statusCode + '" for "' + fileUrl + '"')); } fs.writeFileSync(path.resolve(process.cwd(), filename), body); f(); }); }
[ "function", "downloadDistantOrLoad", "(", "fileUrl", ",", "f", ")", "{", "if", "(", "!", "fileUrl", "||", "!", "_", ".", "isString", "(", "fileUrl", ")", ")", "{", "return", "f", "(", ")", ";", "}", "var", "filename", "=", "path", ".", "basename", "(", "url", ".", "parse", "(", "fileUrl", ")", ".", "path", ")", ";", "debug", "(", "'downloading %s -> %s'", ",", "fileUrl", ",", "filename", ")", ";", "request", "(", "{", "url", ":", "fileUrl", "}", ",", "function", "(", "err", ",", "resp", ",", "body", ")", "{", "if", "(", "err", ")", "{", "return", "f", "(", "err", ")", ";", "}", "if", "(", "resp", ".", "statusCode", "<", "200", "||", "resp", ".", "statusCode", ">=", "300", ")", "{", "return", "f", "(", "new", "Error", "(", "'Invalid HTTP Status code \"'", "+", "resp", ".", "statusCode", "+", "'\" for \"'", "+", "fileUrl", "+", "'\"'", ")", ")", ";", "}", "fs", ".", "writeFileSync", "(", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "filename", ")", ",", "body", ")", ";", "f", "(", ")", ";", "}", ")", ";", "}" ]
Download a distant file based on `url` and then call `f`, or directly call `f` @param {string|falsy} url @param {function} f(err)
[ "Download", "a", "distant", "file", "based", "on", "url", "and", "then", "call", "f", "or", "directly", "call", "f" ]
057a5a119e0dcea0878ad5756effeba54fa1e241
https://github.com/FGRibreau/check-build/blob/057a5a119e0dcea0878ad5756effeba54fa1e241/src/interface/_utils.js#L20-L44
20,146
FGRibreau/check-build
src/interface/_utils.js
extendConf
function extendConf(conf, f) { if (_.isArray(conf.extends)) { async.reduce(conf.extends, conf, function(res, filePath, cb) { loadCheckbuildConf(filePath, function(err, conf) { /** * Do almost like _.defaultsDeep, but without merging arrays */ function defaultsDeep(config, defaults) { if (_.isPlainObject(config)) { return _.mapValues(_.defaults(config, defaults), function(val, index) { return defaultsDeep(_.get(config, index), _.get(defaults, index)); }); } return config || defaults; } cb(err, defaultsDeep(res, conf)); }); }, f); } else { f(null, conf); } }
javascript
function extendConf(conf, f) { if (_.isArray(conf.extends)) { async.reduce(conf.extends, conf, function(res, filePath, cb) { loadCheckbuildConf(filePath, function(err, conf) { /** * Do almost like _.defaultsDeep, but without merging arrays */ function defaultsDeep(config, defaults) { if (_.isPlainObject(config)) { return _.mapValues(_.defaults(config, defaults), function(val, index) { return defaultsDeep(_.get(config, index), _.get(defaults, index)); }); } return config || defaults; } cb(err, defaultsDeep(res, conf)); }); }, f); } else { f(null, conf); } }
[ "function", "extendConf", "(", "conf", ",", "f", ")", "{", "if", "(", "_", ".", "isArray", "(", "conf", ".", "extends", ")", ")", "{", "async", ".", "reduce", "(", "conf", ".", "extends", ",", "conf", ",", "function", "(", "res", ",", "filePath", ",", "cb", ")", "{", "loadCheckbuildConf", "(", "filePath", ",", "function", "(", "err", ",", "conf", ")", "{", "/**\n * Do almost like _.defaultsDeep, but without merging arrays\n */", "function", "defaultsDeep", "(", "config", ",", "defaults", ")", "{", "if", "(", "_", ".", "isPlainObject", "(", "config", ")", ")", "{", "return", "_", ".", "mapValues", "(", "_", ".", "defaults", "(", "config", ",", "defaults", ")", ",", "function", "(", "val", ",", "index", ")", "{", "return", "defaultsDeep", "(", "_", ".", "get", "(", "config", ",", "index", ")", ",", "_", ".", "get", "(", "defaults", ",", "index", ")", ")", ";", "}", ")", ";", "}", "return", "config", "||", "defaults", ";", "}", "cb", "(", "err", ",", "defaultsDeep", "(", "res", ",", "conf", ")", ")", ";", "}", ")", ";", "}", ",", "f", ")", ";", "}", "else", "{", "f", "(", "null", ",", "conf", ")", ";", "}", "}" ]
Load and apply extends
[ "Load", "and", "apply", "extends" ]
057a5a119e0dcea0878ad5756effeba54fa1e241
https://github.com/FGRibreau/check-build/blob/057a5a119e0dcea0878ad5756effeba54fa1e241/src/interface/_utils.js#L68-L91
20,147
FGRibreau/check-build
src/interface/_utils.js
defaultsDeep
function defaultsDeep(config, defaults) { if (_.isPlainObject(config)) { return _.mapValues(_.defaults(config, defaults), function(val, index) { return defaultsDeep(_.get(config, index), _.get(defaults, index)); }); } return config || defaults; }
javascript
function defaultsDeep(config, defaults) { if (_.isPlainObject(config)) { return _.mapValues(_.defaults(config, defaults), function(val, index) { return defaultsDeep(_.get(config, index), _.get(defaults, index)); }); } return config || defaults; }
[ "function", "defaultsDeep", "(", "config", ",", "defaults", ")", "{", "if", "(", "_", ".", "isPlainObject", "(", "config", ")", ")", "{", "return", "_", ".", "mapValues", "(", "_", ".", "defaults", "(", "config", ",", "defaults", ")", ",", "function", "(", "val", ",", "index", ")", "{", "return", "defaultsDeep", "(", "_", ".", "get", "(", "config", ",", "index", ")", ",", "_", ".", "get", "(", "defaults", ",", "index", ")", ")", ";", "}", ")", ";", "}", "return", "config", "||", "defaults", ";", "}" ]
Do almost like _.defaultsDeep, but without merging arrays
[ "Do", "almost", "like", "_", ".", "defaultsDeep", "but", "without", "merging", "arrays" ]
057a5a119e0dcea0878ad5756effeba54fa1e241
https://github.com/FGRibreau/check-build/blob/057a5a119e0dcea0878ad5756effeba54fa1e241/src/interface/_utils.js#L75-L83
20,148
lepture/nico
lib/sdk/post.js
function(key) { var bits = key.split('.'); var value = item; for (var i = 0; i < bits.length; i++) { value = value[bits[i]]; if (!value) return ''; } if (!value) return ''; if (typeof value === 'function') value = value(); if (typeof value === 'number' && value < 10) { return '0' + value; } return value; }
javascript
function(key) { var bits = key.split('.'); var value = item; for (var i = 0; i < bits.length; i++) { value = value[bits[i]]; if (!value) return ''; } if (!value) return ''; if (typeof value === 'function') value = value(); if (typeof value === 'number' && value < 10) { return '0' + value; } return value; }
[ "function", "(", "key", ")", "{", "var", "bits", "=", "key", ".", "split", "(", "'.'", ")", ";", "var", "value", "=", "item", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "bits", ".", "length", ";", "i", "++", ")", "{", "value", "=", "value", "[", "bits", "[", "i", "]", "]", ";", "if", "(", "!", "value", ")", "return", "''", ";", "}", "if", "(", "!", "value", ")", "return", "''", ";", "if", "(", "typeof", "value", "===", "'function'", ")", "value", "=", "value", "(", ")", ";", "if", "(", "typeof", "value", "===", "'number'", "&&", "value", "<", "10", ")", "{", "return", "'0'", "+", "value", ";", "}", "return", "value", ";", "}" ]
generate the destination of a post via permalink style
[ "generate", "the", "destination", "of", "a", "post", "via", "permalink", "style" ]
e40be28e48aeb88e03ea07edb0ee1d48a9da74b5
https://github.com/lepture/nico/blob/e40be28e48aeb88e03ea07edb0ee1d48a9da74b5/lib/sdk/post.js#L15-L28
20,149
dial-once/node-bunnymq
src/modules/retrocompat-config.js
oldConfigNames
function oldConfigNames(config) { const configuration = Object.assign({}, config); if (configuration.amqpUrl) { configuration.host = configuration.amqpUrl; } if (configuration.amqpPrefetch) { configuration.prefetch = configuration.amqpPrefetch; } if (configuration.amqpRequeue) { configuration.requeue = configuration.amqpRequeue; } if (configuration.amqpTimeout) { configuration.timeout = configuration.amqpTimeout; } return configuration; }
javascript
function oldConfigNames(config) { const configuration = Object.assign({}, config); if (configuration.amqpUrl) { configuration.host = configuration.amqpUrl; } if (configuration.amqpPrefetch) { configuration.prefetch = configuration.amqpPrefetch; } if (configuration.amqpRequeue) { configuration.requeue = configuration.amqpRequeue; } if (configuration.amqpTimeout) { configuration.timeout = configuration.amqpTimeout; } return configuration; }
[ "function", "oldConfigNames", "(", "config", ")", "{", "const", "configuration", "=", "Object", ".", "assign", "(", "{", "}", ",", "config", ")", ";", "if", "(", "configuration", ".", "amqpUrl", ")", "{", "configuration", ".", "host", "=", "configuration", ".", "amqpUrl", ";", "}", "if", "(", "configuration", ".", "amqpPrefetch", ")", "{", "configuration", ".", "prefetch", "=", "configuration", ".", "amqpPrefetch", ";", "}", "if", "(", "configuration", ".", "amqpRequeue", ")", "{", "configuration", ".", "requeue", "=", "configuration", ".", "amqpRequeue", ";", "}", "if", "(", "configuration", ".", "amqpTimeout", ")", "{", "configuration", ".", "timeout", "=", "configuration", ".", "amqpTimeout", ";", "}", "return", "configuration", ";", "}" ]
deprecated configuration property names
[ "deprecated", "configuration", "property", "names" ]
f31bed9ecea98fa55081dbb018777351d58e33f3
https://github.com/dial-once/node-bunnymq/blob/f31bed9ecea98fa55081dbb018777351d58e33f3/src/modules/retrocompat-config.js#L2-L20
20,150
dial-once/node-bunnymq
src/modules/retrocompat-config.js
envVars
function envVars(config) { const configuration = Object.assign({}, config); if (process.env.AMQP_URL && !configuration.host) { configuration.host = process.env.AMQP_URL; } if (process.env.LOCAL_QUEUE && !configuration.consumerSuffix) { configuration.consumerSuffix = process.env.LOCAL_QUEUE; } if (process.env.AMQP_DEBUG && !configuration.transport) { configuration.transport = console; } return configuration; }
javascript
function envVars(config) { const configuration = Object.assign({}, config); if (process.env.AMQP_URL && !configuration.host) { configuration.host = process.env.AMQP_URL; } if (process.env.LOCAL_QUEUE && !configuration.consumerSuffix) { configuration.consumerSuffix = process.env.LOCAL_QUEUE; } if (process.env.AMQP_DEBUG && !configuration.transport) { configuration.transport = console; } return configuration; }
[ "function", "envVars", "(", "config", ")", "{", "const", "configuration", "=", "Object", ".", "assign", "(", "{", "}", ",", "config", ")", ";", "if", "(", "process", ".", "env", ".", "AMQP_URL", "&&", "!", "configuration", ".", "host", ")", "{", "configuration", ".", "host", "=", "process", ".", "env", ".", "AMQP_URL", ";", "}", "if", "(", "process", ".", "env", ".", "LOCAL_QUEUE", "&&", "!", "configuration", ".", "consumerSuffix", ")", "{", "configuration", ".", "consumerSuffix", "=", "process", ".", "env", ".", "LOCAL_QUEUE", ";", "}", "if", "(", "process", ".", "env", ".", "AMQP_DEBUG", "&&", "!", "configuration", ".", "transport", ")", "{", "configuration", ".", "transport", "=", "console", ";", "}", "return", "configuration", ";", "}" ]
deprecated env vars to configure the module
[ "deprecated", "env", "vars", "to", "configure", "the", "module" ]
f31bed9ecea98fa55081dbb018777351d58e33f3
https://github.com/dial-once/node-bunnymq/blob/f31bed9ecea98fa55081dbb018777351d58e33f3/src/modules/retrocompat-config.js#L23-L38
20,151
STRML/react-router-component
lib/environment/PathnameEnvironment.js
PathnameEnvironment
function PathnameEnvironment() { this.onPopState = this.onPopState.bind(this); this.useHistoryApi = !!(window.history && window.history.pushState && window.history.replaceState); Environment.call(this); }
javascript
function PathnameEnvironment() { this.onPopState = this.onPopState.bind(this); this.useHistoryApi = !!(window.history && window.history.pushState && window.history.replaceState); Environment.call(this); }
[ "function", "PathnameEnvironment", "(", ")", "{", "this", ".", "onPopState", "=", "this", ".", "onPopState", ".", "bind", "(", "this", ")", ";", "this", ".", "useHistoryApi", "=", "!", "!", "(", "window", ".", "history", "&&", "window", ".", "history", ".", "pushState", "&&", "window", ".", "history", ".", "replaceState", ")", ";", "Environment", ".", "call", "(", "this", ")", ";", "}" ]
Routing environment which routes by `location.pathname`.
[ "Routing", "environment", "which", "routes", "by", "location", ".", "pathname", "." ]
ba8e79b779e6c5b59de45605fa921a7876d1c8da
https://github.com/STRML/react-router-component/blob/ba8e79b779e6c5b59de45605fa921a7876d1c8da/lib/environment/PathnameEnvironment.js#L8-L14
20,152
STRML/react-router-component
lib/environment/LocalStorageKeyEnvironment.js
LocalStorageKeyEnvironment
function LocalStorageKeyEnvironment(key) { this.key = key; var store = this.onStorage = this.onStorage.bind(this); var storage; try { storage = window.localStorage; storage.setItem(key, storage.getItem(key)); } catch (e) { storage = null; } this.storage = storage || { data: {}, getItem: function(itemKey) {return this.data[itemKey]; }, setItem: function(itemKey, val) { this.data[itemKey] = val; clearTimeout(this.storeEvent); this.storeEvent = setTimeout(store, 1); } }; Environment.call(this); }
javascript
function LocalStorageKeyEnvironment(key) { this.key = key; var store = this.onStorage = this.onStorage.bind(this); var storage; try { storage = window.localStorage; storage.setItem(key, storage.getItem(key)); } catch (e) { storage = null; } this.storage = storage || { data: {}, getItem: function(itemKey) {return this.data[itemKey]; }, setItem: function(itemKey, val) { this.data[itemKey] = val; clearTimeout(this.storeEvent); this.storeEvent = setTimeout(store, 1); } }; Environment.call(this); }
[ "function", "LocalStorageKeyEnvironment", "(", "key", ")", "{", "this", ".", "key", "=", "key", ";", "var", "store", "=", "this", ".", "onStorage", "=", "this", ".", "onStorage", ".", "bind", "(", "this", ")", ";", "var", "storage", ";", "try", "{", "storage", "=", "window", ".", "localStorage", ";", "storage", ".", "setItem", "(", "key", ",", "storage", ".", "getItem", "(", "key", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "storage", "=", "null", ";", "}", "this", ".", "storage", "=", "storage", "||", "{", "data", ":", "{", "}", ",", "getItem", ":", "function", "(", "itemKey", ")", "{", "return", "this", ".", "data", "[", "itemKey", "]", ";", "}", ",", "setItem", ":", "function", "(", "itemKey", ",", "val", ")", "{", "this", ".", "data", "[", "itemKey", "]", "=", "val", ";", "clearTimeout", "(", "this", ".", "storeEvent", ")", ";", "this", ".", "storeEvent", "=", "setTimeout", "(", "store", ",", "1", ")", ";", "}", "}", ";", "Environment", ".", "call", "(", "this", ")", ";", "}" ]
Routing environment which stores routing state in localStorage.
[ "Routing", "environment", "which", "stores", "routing", "state", "in", "localStorage", "." ]
ba8e79b779e6c5b59de45605fa921a7876d1c8da
https://github.com/STRML/react-router-component/blob/ba8e79b779e6c5b59de45605fa921a7876d1c8da/lib/environment/LocalStorageKeyEnvironment.js#L8-L31
20,153
STRML/react-router-component
lib/matchRoutes.js
matchRoutes
function matchRoutes(routes, path, query, routerURLPatternOptions) { var match, page, notFound, queryObj = query, urlPatternOptions; if (!Array.isArray(routes)) { routes = [routes]; } path = path.split('?'); var pathToMatch = path[0]; var queryString = path[1]; if (queryString) { queryObj = qs.parse(queryString); } for (var i = 0, len = routes.length; i < len; i++) { var current = routes[i]; // Simply skip null or undefined to allow ternaries in route definitions if (!current) continue; invariant( current.props.handler !== undefined && current.props.path !== undefined, "Router should contain either Route or NotFound components as routes"); if (current.props.path) { // Allow passing compiler options to url-pattern, see // https://github.com/snd/url-pattern#customize-the-pattern-syntax // Note that this blows up if you provide an empty object on a regex path urlPatternOptions = null; if (Array.isArray(current.props.urlPatternOptions) || current.props.path instanceof RegExp) { // If an array is passed, it takes precedence - assumed these are regexp keys urlPatternOptions = current.props.urlPatternOptions; } else if (routerURLPatternOptions || current.props.urlPatternOptions) { urlPatternOptions = assign({}, routerURLPatternOptions, current.props.urlPatternOptions); } // matchKeys is deprecated // FIXME remove this block in next minor version if(current.props.matchKeys) { urlPatternOptions = current.props.matchKeys; warning(false, '`matchKeys` is deprecated; please use the prop `urlPatternOptions` instead. See the CHANGELOG for details.'); } var cacheKey = current.props.path + (urlPatternOptions ? JSON.stringify(urlPatternOptions) : ''); var pattern = patternCache[cacheKey]; if (!pattern) { pattern = patternCache[cacheKey] = new URLPattern(current.props.path, urlPatternOptions); } if (!page) { match = pattern.match(pathToMatch); if (match) { page = current; } // Backcompat fix in 0.27: regexes in url-pattern no longer return {_: matches} if (match && current.props.path instanceof RegExp && !match._ && Array.isArray(match)) { match = {_: match}; } // Backcompat fix; url-pattern removed the array wrapper on wildcards if (match && match._ != null && !Array.isArray(match._)) { match._ = [match._]; } } } if (!notFound && current.props.path === null) { notFound = current; } } return new Match( pathToMatch, page ? page : notFound ? notFound : null, match, queryObj, (urlPatternOptions || {}).namedSegmentValueDecoders ); }
javascript
function matchRoutes(routes, path, query, routerURLPatternOptions) { var match, page, notFound, queryObj = query, urlPatternOptions; if (!Array.isArray(routes)) { routes = [routes]; } path = path.split('?'); var pathToMatch = path[0]; var queryString = path[1]; if (queryString) { queryObj = qs.parse(queryString); } for (var i = 0, len = routes.length; i < len; i++) { var current = routes[i]; // Simply skip null or undefined to allow ternaries in route definitions if (!current) continue; invariant( current.props.handler !== undefined && current.props.path !== undefined, "Router should contain either Route or NotFound components as routes"); if (current.props.path) { // Allow passing compiler options to url-pattern, see // https://github.com/snd/url-pattern#customize-the-pattern-syntax // Note that this blows up if you provide an empty object on a regex path urlPatternOptions = null; if (Array.isArray(current.props.urlPatternOptions) || current.props.path instanceof RegExp) { // If an array is passed, it takes precedence - assumed these are regexp keys urlPatternOptions = current.props.urlPatternOptions; } else if (routerURLPatternOptions || current.props.urlPatternOptions) { urlPatternOptions = assign({}, routerURLPatternOptions, current.props.urlPatternOptions); } // matchKeys is deprecated // FIXME remove this block in next minor version if(current.props.matchKeys) { urlPatternOptions = current.props.matchKeys; warning(false, '`matchKeys` is deprecated; please use the prop `urlPatternOptions` instead. See the CHANGELOG for details.'); } var cacheKey = current.props.path + (urlPatternOptions ? JSON.stringify(urlPatternOptions) : ''); var pattern = patternCache[cacheKey]; if (!pattern) { pattern = patternCache[cacheKey] = new URLPattern(current.props.path, urlPatternOptions); } if (!page) { match = pattern.match(pathToMatch); if (match) { page = current; } // Backcompat fix in 0.27: regexes in url-pattern no longer return {_: matches} if (match && current.props.path instanceof RegExp && !match._ && Array.isArray(match)) { match = {_: match}; } // Backcompat fix; url-pattern removed the array wrapper on wildcards if (match && match._ != null && !Array.isArray(match._)) { match._ = [match._]; } } } if (!notFound && current.props.path === null) { notFound = current; } } return new Match( pathToMatch, page ? page : notFound ? notFound : null, match, queryObj, (urlPatternOptions || {}).namedSegmentValueDecoders ); }
[ "function", "matchRoutes", "(", "routes", ",", "path", ",", "query", ",", "routerURLPatternOptions", ")", "{", "var", "match", ",", "page", ",", "notFound", ",", "queryObj", "=", "query", ",", "urlPatternOptions", ";", "if", "(", "!", "Array", ".", "isArray", "(", "routes", ")", ")", "{", "routes", "=", "[", "routes", "]", ";", "}", "path", "=", "path", ".", "split", "(", "'?'", ")", ";", "var", "pathToMatch", "=", "path", "[", "0", "]", ";", "var", "queryString", "=", "path", "[", "1", "]", ";", "if", "(", "queryString", ")", "{", "queryObj", "=", "qs", ".", "parse", "(", "queryString", ")", ";", "}", "for", "(", "var", "i", "=", "0", ",", "len", "=", "routes", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "current", "=", "routes", "[", "i", "]", ";", "// Simply skip null or undefined to allow ternaries in route definitions", "if", "(", "!", "current", ")", "continue", ";", "invariant", "(", "current", ".", "props", ".", "handler", "!==", "undefined", "&&", "current", ".", "props", ".", "path", "!==", "undefined", ",", "\"Router should contain either Route or NotFound components as routes\"", ")", ";", "if", "(", "current", ".", "props", ".", "path", ")", "{", "// Allow passing compiler options to url-pattern, see", "// https://github.com/snd/url-pattern#customize-the-pattern-syntax", "// Note that this blows up if you provide an empty object on a regex path", "urlPatternOptions", "=", "null", ";", "if", "(", "Array", ".", "isArray", "(", "current", ".", "props", ".", "urlPatternOptions", ")", "||", "current", ".", "props", ".", "path", "instanceof", "RegExp", ")", "{", "// If an array is passed, it takes precedence - assumed these are regexp keys", "urlPatternOptions", "=", "current", ".", "props", ".", "urlPatternOptions", ";", "}", "else", "if", "(", "routerURLPatternOptions", "||", "current", ".", "props", ".", "urlPatternOptions", ")", "{", "urlPatternOptions", "=", "assign", "(", "{", "}", ",", "routerURLPatternOptions", ",", "current", ".", "props", ".", "urlPatternOptions", ")", ";", "}", "// matchKeys is deprecated", "// FIXME remove this block in next minor version", "if", "(", "current", ".", "props", ".", "matchKeys", ")", "{", "urlPatternOptions", "=", "current", ".", "props", ".", "matchKeys", ";", "warning", "(", "false", ",", "'`matchKeys` is deprecated; please use the prop `urlPatternOptions` instead. See the CHANGELOG for details.'", ")", ";", "}", "var", "cacheKey", "=", "current", ".", "props", ".", "path", "+", "(", "urlPatternOptions", "?", "JSON", ".", "stringify", "(", "urlPatternOptions", ")", ":", "''", ")", ";", "var", "pattern", "=", "patternCache", "[", "cacheKey", "]", ";", "if", "(", "!", "pattern", ")", "{", "pattern", "=", "patternCache", "[", "cacheKey", "]", "=", "new", "URLPattern", "(", "current", ".", "props", ".", "path", ",", "urlPatternOptions", ")", ";", "}", "if", "(", "!", "page", ")", "{", "match", "=", "pattern", ".", "match", "(", "pathToMatch", ")", ";", "if", "(", "match", ")", "{", "page", "=", "current", ";", "}", "// Backcompat fix in 0.27: regexes in url-pattern no longer return {_: matches}", "if", "(", "match", "&&", "current", ".", "props", ".", "path", "instanceof", "RegExp", "&&", "!", "match", ".", "_", "&&", "Array", ".", "isArray", "(", "match", ")", ")", "{", "match", "=", "{", "_", ":", "match", "}", ";", "}", "// Backcompat fix; url-pattern removed the array wrapper on wildcards", "if", "(", "match", "&&", "match", ".", "_", "!=", "null", "&&", "!", "Array", ".", "isArray", "(", "match", ".", "_", ")", ")", "{", "match", ".", "_", "=", "[", "match", ".", "_", "]", ";", "}", "}", "}", "if", "(", "!", "notFound", "&&", "current", ".", "props", ".", "path", "===", "null", ")", "{", "notFound", "=", "current", ";", "}", "}", "return", "new", "Match", "(", "pathToMatch", ",", "page", "?", "page", ":", "notFound", "?", "notFound", ":", "null", ",", "match", ",", "queryObj", ",", "(", "urlPatternOptions", "||", "{", "}", ")", ".", "namedSegmentValueDecoders", ")", ";", "}" ]
Match routes against a path @param {Array.<Route>} routes Available Routes. @param {String} path Path to match. @param {Object} [query] A parsed query-string object. (from a parent Match) @param {[Object|Array]} [routerURLPatternOptions] URLPattern options from parent router (and its parent and so on).
[ "Match", "routes", "against", "a", "path" ]
ba8e79b779e6c5b59de45605fa921a7876d1c8da
https://github.com/STRML/react-router-component/blob/ba8e79b779e6c5b59de45605fa921a7876d1c8da/lib/matchRoutes.js#L21-L101
20,154
STRML/react-router-component
lib/Router.js
createRouter
function createRouter(name, component) { return CreateReactClass({ mixins: [RouterMixin, RouteRenderingMixin], displayName: name, propTypes: { component: PropTypes.oneOfType([ PropTypes.string, PropTypes.element, PropTypes.func ]) }, getRoutes: function(props) { return props.children; }, getDefaultProps: function() { return { component: component }; }, render: function() { // Render the Route's handler. var handler = this.renderRouteHandler(); if (!this.props.component) { return handler; } else { // Pass all props except this component to the Router (containing div/body) and the children, // which are swapped out by the route handler. var props = assign({}, this.props); props = omit(props, PROP_KEYS); return React.createElement(this.props.component, props, handler); } } }); }
javascript
function createRouter(name, component) { return CreateReactClass({ mixins: [RouterMixin, RouteRenderingMixin], displayName: name, propTypes: { component: PropTypes.oneOfType([ PropTypes.string, PropTypes.element, PropTypes.func ]) }, getRoutes: function(props) { return props.children; }, getDefaultProps: function() { return { component: component }; }, render: function() { // Render the Route's handler. var handler = this.renderRouteHandler(); if (!this.props.component) { return handler; } else { // Pass all props except this component to the Router (containing div/body) and the children, // which are swapped out by the route handler. var props = assign({}, this.props); props = omit(props, PROP_KEYS); return React.createElement(this.props.component, props, handler); } } }); }
[ "function", "createRouter", "(", "name", ",", "component", ")", "{", "return", "CreateReactClass", "(", "{", "mixins", ":", "[", "RouterMixin", ",", "RouteRenderingMixin", "]", ",", "displayName", ":", "name", ",", "propTypes", ":", "{", "component", ":", "PropTypes", ".", "oneOfType", "(", "[", "PropTypes", ".", "string", ",", "PropTypes", ".", "element", ",", "PropTypes", ".", "func", "]", ")", "}", ",", "getRoutes", ":", "function", "(", "props", ")", "{", "return", "props", ".", "children", ";", "}", ",", "getDefaultProps", ":", "function", "(", ")", "{", "return", "{", "component", ":", "component", "}", ";", "}", ",", "render", ":", "function", "(", ")", "{", "// Render the Route's handler.", "var", "handler", "=", "this", ".", "renderRouteHandler", "(", ")", ";", "if", "(", "!", "this", ".", "props", ".", "component", ")", "{", "return", "handler", ";", "}", "else", "{", "// Pass all props except this component to the Router (containing div/body) and the children,", "// which are swapped out by the route handler.", "var", "props", "=", "assign", "(", "{", "}", ",", "this", ".", "props", ")", ";", "props", "=", "omit", "(", "props", ",", "PROP_KEYS", ")", ";", "return", "React", ".", "createElement", "(", "this", ".", "props", ".", "component", ",", "props", ",", "handler", ")", ";", "}", "}", "}", ")", ";", "}" ]
Create a new router class @param {String} name @param {ReactComponent} component
[ "Create", "a", "new", "router", "class" ]
ba8e79b779e6c5b59de45605fa921a7876d1c8da
https://github.com/STRML/react-router-component/blob/ba8e79b779e6c5b59de45605fa921a7876d1c8da/lib/Router.js#L22-L63
20,155
swipely/aviator
src/request.js
function () { var parts; if (!this.queryString) return; parts = this.queryString.replace('?','').split('&'); each(parts, function (part) { var key = decodeURIComponent( part.split('=')[0] ), val = decodeURIComponent( part.split('=')[1] ); if ( part.indexOf( '=' ) === -1 ) return; this._applyQueryParam( key, val ); }, this); }
javascript
function () { var parts; if (!this.queryString) return; parts = this.queryString.replace('?','').split('&'); each(parts, function (part) { var key = decodeURIComponent( part.split('=')[0] ), val = decodeURIComponent( part.split('=')[1] ); if ( part.indexOf( '=' ) === -1 ) return; this._applyQueryParam( key, val ); }, this); }
[ "function", "(", ")", "{", "var", "parts", ";", "if", "(", "!", "this", ".", "queryString", ")", "return", ";", "parts", "=", "this", ".", "queryString", ".", "replace", "(", "'?'", ",", "''", ")", ".", "split", "(", "'&'", ")", ";", "each", "(", "parts", ",", "function", "(", "part", ")", "{", "var", "key", "=", "decodeURIComponent", "(", "part", ".", "split", "(", "'='", ")", "[", "0", "]", ")", ",", "val", "=", "decodeURIComponent", "(", "part", ".", "split", "(", "'='", ")", "[", "1", "]", ")", ";", "if", "(", "part", ".", "indexOf", "(", "'='", ")", "===", "-", "1", ")", "return", ";", "this", ".", "_applyQueryParam", "(", "key", ",", "val", ")", ";", "}", ",", "this", ")", ";", "}" ]
Splits the query string by '&'. Splits each part by '='. Passes the key and value for each part to _applyQueryParam @method _extractQueryParamsFromQueryString @private
[ "Splits", "the", "query", "string", "by", "&", ".", "Splits", "each", "part", "by", "=", ".", "Passes", "the", "key", "and", "value", "for", "each", "part", "to", "_applyQueryParam" ]
bde7b631cb9d24288e56681f050da3ec0d12c84a
https://github.com/swipely/aviator/blob/bde7b631cb9d24288e56681f050da3ec0d12c84a/src/request.js#L54-L70
20,156
swipely/aviator
src/navigator.js
function (nextRequest) { var exit, target, method; while(this._exits.length) { exit = this._exits.pop(); target = exit.target; method = exit.method; if (!(method in target)) { throw new Error("Can't call exit " + method + ' on target when changing uri to ' + request.uri); } target[method].call(target, nextRequest); } }
javascript
function (nextRequest) { var exit, target, method; while(this._exits.length) { exit = this._exits.pop(); target = exit.target; method = exit.method; if (!(method in target)) { throw new Error("Can't call exit " + method + ' on target when changing uri to ' + request.uri); } target[method].call(target, nextRequest); } }
[ "function", "(", "nextRequest", ")", "{", "var", "exit", ",", "target", ",", "method", ";", "while", "(", "this", ".", "_exits", ".", "length", ")", "{", "exit", "=", "this", ".", "_exits", ".", "pop", "(", ")", ";", "target", "=", "exit", ".", "target", ";", "method", "=", "exit", ".", "method", ";", "if", "(", "!", "(", "method", "in", "target", ")", ")", "{", "throw", "new", "Error", "(", "\"Can't call exit \"", "+", "method", "+", "' on target when changing uri to '", "+", "request", ".", "uri", ")", ";", "}", "target", "[", "method", "]", ".", "call", "(", "target", ",", "nextRequest", ")", ";", "}", "}" ]
pop of any exits function and invoke them @method _invokeExits @param {Request} nextRequest @protected
[ "pop", "of", "any", "exits", "function", "and", "invoke", "them" ]
bde7b631cb9d24288e56681f050da3ec0d12c84a
https://github.com/swipely/aviator/blob/bde7b631cb9d24288e56681f050da3ec0d12c84a/src/navigator.js#L363-L377
20,157
swipely/aviator
src/navigator.js
function (request, options) { var action, target, method, emitter; while (this._actions.length) { action = this._actions.shift(); target = action.target; method = action.method; emitter = new ActionEmitter; if (!(method in target)) { throw new Error("Can't call action " + method + ' on target for uri ' + request.uri); } this._emitters.push(emitter); target[method].call(target, request, options, emitter); } }
javascript
function (request, options) { var action, target, method, emitter; while (this._actions.length) { action = this._actions.shift(); target = action.target; method = action.method; emitter = new ActionEmitter; if (!(method in target)) { throw new Error("Can't call action " + method + ' on target for uri ' + request.uri); } this._emitters.push(emitter); target[method].call(target, request, options, emitter); } }
[ "function", "(", "request", ",", "options", ")", "{", "var", "action", ",", "target", ",", "method", ",", "emitter", ";", "while", "(", "this", ".", "_actions", ".", "length", ")", "{", "action", "=", "this", ".", "_actions", ".", "shift", "(", ")", ";", "target", "=", "action", ".", "target", ";", "method", "=", "action", ".", "method", ";", "emitter", "=", "new", "ActionEmitter", ";", "if", "(", "!", "(", "method", "in", "target", ")", ")", "{", "throw", "new", "Error", "(", "\"Can't call action \"", "+", "method", "+", "' on target for uri '", "+", "request", ".", "uri", ")", ";", "}", "this", ".", "_emitters", ".", "push", "(", "emitter", ")", ";", "target", "[", "method", "]", ".", "call", "(", "target", ",", "request", ",", "options", ",", "emitter", ")", ";", "}", "}" ]
invoke all actions with request and options @method _invokeActions @param {Request} request @param {Object} options @protected
[ "invoke", "all", "actions", "with", "request", "and", "options" ]
bde7b631cb9d24288e56681f050da3ec0d12c84a
https://github.com/swipely/aviator/blob/bde7b631cb9d24288e56681f050da3ec0d12c84a/src/navigator.js#L387-L404
20,158
eight04/angular-datetime
lib/factory.js
fixDay
function fixDay(days) { var s = [], i; for (i = 1; i < days.length; i++) { s.push(days[i]); } s.push(days[0]); return s; }
javascript
function fixDay(days) { var s = [], i; for (i = 1; i < days.length; i++) { s.push(days[i]); } s.push(days[0]); return s; }
[ "function", "fixDay", "(", "days", ")", "{", "var", "s", "=", "[", "]", ",", "i", ";", "for", "(", "i", "=", "1", ";", "i", "<", "days", ".", "length", ";", "i", "++", ")", "{", "s", ".", "push", "(", "days", "[", "i", "]", ")", ";", "}", "s", ".", "push", "(", "days", "[", "0", "]", ")", ";", "return", "s", ";", "}" ]
Push Sunday to the end
[ "Push", "Sunday", "to", "the", "end" ]
81d26b45453f181d53fb173c4a82c4d5d6ad785c
https://github.com/eight04/angular-datetime/blob/81d26b45453f181d53fb173c4a82c4d5d6ad785c/lib/factory.js#L300-L307
20,159
eight04/angular-datetime
lib/factory.js
createTokens
function createTokens(format) { var tokens = [], pos = 0, match; while ((match = tokenRE.exec(format))) { if (match.index > pos) { // doesn't match any token, static string tokens.push(angular.extend({ value: format.substring(pos, match.index) }, definedTokens.string)); pos = match.index; } if (match.index == pos) { if (match[1]) { // sss tokens.push(angular.extend({ value: match[1] }, definedTokens.string)); tokens.push(definedTokens.sss); } else if (match[2]) { // escaped string tokens.push(angular.extend({ value: match[2].replace("''", "'") }, definedTokens.string)); } else if (definedTokens[match[0]].name == "timezone") { // static timezone var tz = SYS_TIMEZONE; if (definedTokens[match[0]].colon) { tz = insertColon(tz); } tokens.push(angular.extend({ value: tz }, definedTokens[match[0]])); } else { // other tokens tokens.push(definedTokens[match[0]]); } pos = tokenRE.lastIndex; } } if (pos < format.length) { tokens.push(angular.extend({ value: format.substring(pos) }, definedTokens.string)); } return tokens; }
javascript
function createTokens(format) { var tokens = [], pos = 0, match; while ((match = tokenRE.exec(format))) { if (match.index > pos) { // doesn't match any token, static string tokens.push(angular.extend({ value: format.substring(pos, match.index) }, definedTokens.string)); pos = match.index; } if (match.index == pos) { if (match[1]) { // sss tokens.push(angular.extend({ value: match[1] }, definedTokens.string)); tokens.push(definedTokens.sss); } else if (match[2]) { // escaped string tokens.push(angular.extend({ value: match[2].replace("''", "'") }, definedTokens.string)); } else if (definedTokens[match[0]].name == "timezone") { // static timezone var tz = SYS_TIMEZONE; if (definedTokens[match[0]].colon) { tz = insertColon(tz); } tokens.push(angular.extend({ value: tz }, definedTokens[match[0]])); } else { // other tokens tokens.push(definedTokens[match[0]]); } pos = tokenRE.lastIndex; } } if (pos < format.length) { tokens.push(angular.extend({ value: format.substring(pos) }, definedTokens.string)); } return tokens; }
[ "function", "createTokens", "(", "format", ")", "{", "var", "tokens", "=", "[", "]", ",", "pos", "=", "0", ",", "match", ";", "while", "(", "(", "match", "=", "tokenRE", ".", "exec", "(", "format", ")", ")", ")", "{", "if", "(", "match", ".", "index", ">", "pos", ")", "{", "// doesn't match any token, static string", "tokens", ".", "push", "(", "angular", ".", "extend", "(", "{", "value", ":", "format", ".", "substring", "(", "pos", ",", "match", ".", "index", ")", "}", ",", "definedTokens", ".", "string", ")", ")", ";", "pos", "=", "match", ".", "index", ";", "}", "if", "(", "match", ".", "index", "==", "pos", ")", "{", "if", "(", "match", "[", "1", "]", ")", "{", "// sss", "tokens", ".", "push", "(", "angular", ".", "extend", "(", "{", "value", ":", "match", "[", "1", "]", "}", ",", "definedTokens", ".", "string", ")", ")", ";", "tokens", ".", "push", "(", "definedTokens", ".", "sss", ")", ";", "}", "else", "if", "(", "match", "[", "2", "]", ")", "{", "// escaped string", "tokens", ".", "push", "(", "angular", ".", "extend", "(", "{", "value", ":", "match", "[", "2", "]", ".", "replace", "(", "\"''\"", ",", "\"'\"", ")", "}", ",", "definedTokens", ".", "string", ")", ")", ";", "}", "else", "if", "(", "definedTokens", "[", "match", "[", "0", "]", "]", ".", "name", "==", "\"timezone\"", ")", "{", "// static timezone", "var", "tz", "=", "SYS_TIMEZONE", ";", "if", "(", "definedTokens", "[", "match", "[", "0", "]", "]", ".", "colon", ")", "{", "tz", "=", "insertColon", "(", "tz", ")", ";", "}", "tokens", ".", "push", "(", "angular", ".", "extend", "(", "{", "value", ":", "tz", "}", ",", "definedTokens", "[", "match", "[", "0", "]", "]", ")", ")", ";", "}", "else", "{", "// other tokens", "tokens", ".", "push", "(", "definedTokens", "[", "match", "[", "0", "]", "]", ")", ";", "}", "pos", "=", "tokenRE", ".", "lastIndex", ";", "}", "}", "if", "(", "pos", "<", "format", ".", "length", ")", "{", "tokens", ".", "push", "(", "angular", ".", "extend", "(", "{", "value", ":", "format", ".", "substring", "(", "pos", ")", "}", ",", "definedTokens", ".", "string", ")", ")", ";", "}", "return", "tokens", ";", "}" ]
Split format into multiple tokens
[ "Split", "format", "into", "multiple", "tokens" ]
81d26b45453f181d53fb173c4a82c4d5d6ad785c
https://github.com/eight04/angular-datetime/blob/81d26b45453f181d53fb173c4a82c4d5d6ad785c/lib/factory.js#L310-L360
20,160
eight04/angular-datetime
lib/factory.js
setDay
function setDay(date, day) { // we don't want to change month when changing date var month = date.getMonth(), diff = day - (date.getDay() || 7); // move to correct date date.setDate(date.getDate() + diff); // check month if (date.getMonth() != month) { if (diff > 0) { date.setDate(date.getDate() - 7); } else { date.setDate(date.getDate() + 7); } } }
javascript
function setDay(date, day) { // we don't want to change month when changing date var month = date.getMonth(), diff = day - (date.getDay() || 7); // move to correct date date.setDate(date.getDate() + diff); // check month if (date.getMonth() != month) { if (diff > 0) { date.setDate(date.getDate() - 7); } else { date.setDate(date.getDate() + 7); } } }
[ "function", "setDay", "(", "date", ",", "day", ")", "{", "// we don't want to change month when changing date", "var", "month", "=", "date", ".", "getMonth", "(", ")", ",", "diff", "=", "day", "-", "(", "date", ".", "getDay", "(", ")", "||", "7", ")", ";", "// move to correct date", "date", ".", "setDate", "(", "date", ".", "getDate", "(", ")", "+", "diff", ")", ";", "// check month", "if", "(", "date", ".", "getMonth", "(", ")", "!=", "month", ")", "{", "if", "(", "diff", ">", "0", ")", "{", "date", ".", "setDate", "(", "date", ".", "getDate", "(", ")", "-", "7", ")", ";", "}", "else", "{", "date", ".", "setDate", "(", "date", ".", "getDate", "(", ")", "+", "7", ")", ";", "}", "}", "}" ]
set the proper date value matching the weekday
[ "set", "the", "proper", "date", "value", "matching", "the", "weekday" ]
81d26b45453f181d53fb173c4a82c4d5d6ad785c
https://github.com/eight04/angular-datetime/blob/81d26b45453f181d53fb173c4a82c4d5d6ad785c/lib/factory.js#L378-L392
20,161
croquiscom/cormo
lib/types.js
_toCORMOType
function _toCORMOType(type) { if (typeof type === 'string') { const type_string = type.toLowerCase(); if (/^string\((\d+)\)$/.test(type_string)) { return new CormoTypesString(Number(RegExp.$1)); } switch (type_string) { case 'string': return new CormoTypesString(); case 'number': return new CormoTypesNumber(); case 'boolean': return new CormoTypesBoolean(); case 'integer': return new CormoTypesInteger(); case 'geopoint': return new CormoTypesGeoPoint(); case 'date': return new CormoTypesDate(); case 'object': return new CormoTypesObject(); case 'recordid': return new CormoTypesRecordID(); case 'text': return new CormoTypesText(); } throw new Error(`unknown type: ${type}`); } else if (type === String) { return new CormoTypesString(); } else if (type === Number) { return new CormoTypesNumber(); } else if (type === Boolean) { return new CormoTypesBoolean(); } else if (type === Date) { return new CormoTypesDate(); } else if (type === Object) { return new CormoTypesObject(); } if (typeof type === 'function') { return new type(); } return type; }
javascript
function _toCORMOType(type) { if (typeof type === 'string') { const type_string = type.toLowerCase(); if (/^string\((\d+)\)$/.test(type_string)) { return new CormoTypesString(Number(RegExp.$1)); } switch (type_string) { case 'string': return new CormoTypesString(); case 'number': return new CormoTypesNumber(); case 'boolean': return new CormoTypesBoolean(); case 'integer': return new CormoTypesInteger(); case 'geopoint': return new CormoTypesGeoPoint(); case 'date': return new CormoTypesDate(); case 'object': return new CormoTypesObject(); case 'recordid': return new CormoTypesRecordID(); case 'text': return new CormoTypesText(); } throw new Error(`unknown type: ${type}`); } else if (type === String) { return new CormoTypesString(); } else if (type === Number) { return new CormoTypesNumber(); } else if (type === Boolean) { return new CormoTypesBoolean(); } else if (type === Date) { return new CormoTypesDate(); } else if (type === Object) { return new CormoTypesObject(); } if (typeof type === 'function') { return new type(); } return type; }
[ "function", "_toCORMOType", "(", "type", ")", "{", "if", "(", "typeof", "type", "===", "'string'", ")", "{", "const", "type_string", "=", "type", ".", "toLowerCase", "(", ")", ";", "if", "(", "/", "^string\\((\\d+)\\)$", "/", ".", "test", "(", "type_string", ")", ")", "{", "return", "new", "CormoTypesString", "(", "Number", "(", "RegExp", ".", "$1", ")", ")", ";", "}", "switch", "(", "type_string", ")", "{", "case", "'string'", ":", "return", "new", "CormoTypesString", "(", ")", ";", "case", "'number'", ":", "return", "new", "CormoTypesNumber", "(", ")", ";", "case", "'boolean'", ":", "return", "new", "CormoTypesBoolean", "(", ")", ";", "case", "'integer'", ":", "return", "new", "CormoTypesInteger", "(", ")", ";", "case", "'geopoint'", ":", "return", "new", "CormoTypesGeoPoint", "(", ")", ";", "case", "'date'", ":", "return", "new", "CormoTypesDate", "(", ")", ";", "case", "'object'", ":", "return", "new", "CormoTypesObject", "(", ")", ";", "case", "'recordid'", ":", "return", "new", "CormoTypesRecordID", "(", ")", ";", "case", "'text'", ":", "return", "new", "CormoTypesText", "(", ")", ";", "}", "throw", "new", "Error", "(", "`", "${", "type", "}", "`", ")", ";", "}", "else", "if", "(", "type", "===", "String", ")", "{", "return", "new", "CormoTypesString", "(", ")", ";", "}", "else", "if", "(", "type", "===", "Number", ")", "{", "return", "new", "CormoTypesNumber", "(", ")", ";", "}", "else", "if", "(", "type", "===", "Boolean", ")", "{", "return", "new", "CormoTypesBoolean", "(", ")", ";", "}", "else", "if", "(", "type", "===", "Date", ")", "{", "return", "new", "CormoTypesDate", "(", ")", ";", "}", "else", "if", "(", "type", "===", "Object", ")", "{", "return", "new", "CormoTypesObject", "(", ")", ";", "}", "if", "(", "typeof", "type", "===", "'function'", ")", "{", "return", "new", "type", "(", ")", ";", "}", "return", "type", ";", "}" ]
Converts JavaScript built-in class to CORMO type @private
[ "Converts", "JavaScript", "built", "-", "in", "class", "to", "CORMO", "type" ]
176971becaa6d6db729d35a2e3d2bf1f44f763b5
https://github.com/croquiscom/cormo/blob/176971becaa6d6db729d35a2e3d2bf1f44f763b5/lib/types.js#L71-L118
20,162
croquiscom/cormo
lib/util/index.js
getLeafOfPath
function getLeafOfPath(obj, path, create_object = true) { const parts = Array.isArray(path) ? path.slice(0) : path.split('.'); const last = parts.pop(); if (parts.length > 0) { if (create_object !== false) { for (const part of parts) { obj = obj[part] || (obj[part] = {}); } } else { for (const part of parts) { obj = obj[part]; if (!obj) { return [undefined, undefined]; } } } } return [obj, last]; }
javascript
function getLeafOfPath(obj, path, create_object = true) { const parts = Array.isArray(path) ? path.slice(0) : path.split('.'); const last = parts.pop(); if (parts.length > 0) { if (create_object !== false) { for (const part of parts) { obj = obj[part] || (obj[part] = {}); } } else { for (const part of parts) { obj = obj[part]; if (!obj) { return [undefined, undefined]; } } } } return [obj, last]; }
[ "function", "getLeafOfPath", "(", "obj", ",", "path", ",", "create_object", "=", "true", ")", "{", "const", "parts", "=", "Array", ".", "isArray", "(", "path", ")", "?", "path", ".", "slice", "(", "0", ")", ":", "path", ".", "split", "(", "'.'", ")", ";", "const", "last", "=", "parts", ".", "pop", "(", ")", ";", "if", "(", "parts", ".", "length", ">", "0", ")", "{", "if", "(", "create_object", "!==", "false", ")", "{", "for", "(", "const", "part", "of", "parts", ")", "{", "obj", "=", "obj", "[", "part", "]", "||", "(", "obj", "[", "part", "]", "=", "{", "}", ")", ";", "}", "}", "else", "{", "for", "(", "const", "part", "of", "parts", ")", "{", "obj", "=", "obj", "[", "part", "]", ";", "if", "(", "!", "obj", ")", "{", "return", "[", "undefined", ",", "undefined", "]", ";", "}", "}", "}", "}", "return", "[", "obj", ",", "last", "]", ";", "}" ]
Returns leaf object and last part. e.g.) (obj, 'a.b.c') -> [ obj.a.b, 'c' ] @memberOf util tslint:disable-next-line:max-line-length
[ "Returns", "leaf", "object", "and", "last", "part", "." ]
176971becaa6d6db729d35a2e3d2bf1f44f763b5
https://github.com/croquiscom/cormo/blob/176971becaa6d6db729d35a2e3d2bf1f44f763b5/lib/util/index.js#L15-L34
20,163
croquiscom/cormo
lib/util/index.js
getPropertyOfPath
function getPropertyOfPath(obj, path) { const [child, last] = getLeafOfPath(obj, path, false); return child && last ? child[last] : undefined; }
javascript
function getPropertyOfPath(obj, path) { const [child, last] = getLeafOfPath(obj, path, false); return child && last ? child[last] : undefined; }
[ "function", "getPropertyOfPath", "(", "obj", ",", "path", ")", "{", "const", "[", "child", ",", "last", "]", "=", "getLeafOfPath", "(", "obj", ",", "path", ",", "false", ")", ";", "return", "child", "&&", "last", "?", "child", "[", "last", "]", ":", "undefined", ";", "}" ]
Gets a value of object by path @memberOf util
[ "Gets", "a", "value", "of", "object", "by", "path" ]
176971becaa6d6db729d35a2e3d2bf1f44f763b5
https://github.com/croquiscom/cormo/blob/176971becaa6d6db729d35a2e3d2bf1f44f763b5/lib/util/index.js#L40-L43
20,164
croquiscom/cormo
lib/util/index.js
setPropertyOfPath
function setPropertyOfPath(obj, path, value) { const [child, last] = getLeafOfPath(obj, path); if (child && last) { child[last] = value; } }
javascript
function setPropertyOfPath(obj, path, value) { const [child, last] = getLeafOfPath(obj, path); if (child && last) { child[last] = value; } }
[ "function", "setPropertyOfPath", "(", "obj", ",", "path", ",", "value", ")", "{", "const", "[", "child", ",", "last", "]", "=", "getLeafOfPath", "(", "obj", ",", "path", ")", ";", "if", "(", "child", "&&", "last", ")", "{", "child", "[", "last", "]", "=", "value", ";", "}", "}" ]
Sets a value to object by path @memberOf util
[ "Sets", "a", "value", "to", "object", "by", "path" ]
176971becaa6d6db729d35a2e3d2bf1f44f763b5
https://github.com/croquiscom/cormo/blob/176971becaa6d6db729d35a2e3d2bf1f44f763b5/lib/util/index.js#L49-L54
20,165
jonschlinkert/copy
index.js
copy
function copy(patterns, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({cwd: process.cwd()}, options); opts.cwd = path.resolve(opts.cwd); patterns = utils.arrayify(patterns); if (!utils.hasGlob(patterns)) { copyEach(patterns, dir, opts, cb); return; } opts.patterns = patterns; if (!opts.srcBase) { opts.srcBase = path.resolve(opts.cwd, utils.parent(patterns)); } utils.glob(patterns, opts, function(err, files) { if (err) { cb(err); return; } copyEach(files, dir, opts, cb); }); }
javascript
function copy(patterns, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({cwd: process.cwd()}, options); opts.cwd = path.resolve(opts.cwd); patterns = utils.arrayify(patterns); if (!utils.hasGlob(patterns)) { copyEach(patterns, dir, opts, cb); return; } opts.patterns = patterns; if (!opts.srcBase) { opts.srcBase = path.resolve(opts.cwd, utils.parent(patterns)); } utils.glob(patterns, opts, function(err, files) { if (err) { cb(err); return; } copyEach(files, dir, opts, cb); }); }
[ "function", "copy", "(", "patterns", ",", "dir", ",", "options", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "return", "invalid", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "cb", "=", "options", ";", "options", "=", "{", "}", ";", "}", "var", "opts", "=", "utils", ".", "extend", "(", "{", "cwd", ":", "process", ".", "cwd", "(", ")", "}", ",", "options", ")", ";", "opts", ".", "cwd", "=", "path", ".", "resolve", "(", "opts", ".", "cwd", ")", ";", "patterns", "=", "utils", ".", "arrayify", "(", "patterns", ")", ";", "if", "(", "!", "utils", ".", "hasGlob", "(", "patterns", ")", ")", "{", "copyEach", "(", "patterns", ",", "dir", ",", "opts", ",", "cb", ")", ";", "return", ";", "}", "opts", ".", "patterns", "=", "patterns", ";", "if", "(", "!", "opts", ".", "srcBase", ")", "{", "opts", ".", "srcBase", "=", "path", ".", "resolve", "(", "opts", ".", "cwd", ",", "utils", ".", "parent", "(", "patterns", ")", ")", ";", "}", "utils", ".", "glob", "(", "patterns", ",", "opts", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "return", ";", "}", "copyEach", "(", "files", ",", "dir", ",", "opts", ",", "cb", ")", ";", "}", ")", ";", "}" ]
Copy a filepath, vinyl file, array of files, or glob of files to the given destination `directory`, with `options` and callback function that exposes `err` and the array of vinyl files that are created by the copy operation. ```js copy('*.js', 'dist', function(err, file) { // exposes the vinyl `file` created when the file is copied }); ``` @param {String|Object|Array} `patterns` Filepath(s), vinyl file(s) or glob of files. @param {String} `dir` Destination directory @param {Object|Function} `options` or callback function @param {Function} `cb` Callback function if no options are specified @api public
[ "Copy", "a", "filepath", "vinyl", "file", "array", "of", "files", "or", "glob", "of", "files", "to", "the", "given", "destination", "directory", "with", "options", "and", "callback", "function", "that", "exposes", "err", "and", "the", "array", "of", "vinyl", "files", "that", "are", "created", "by", "the", "copy", "operation", "." ]
6e1d95722a2bf539abbfba768df774817156a573
https://github.com/jonschlinkert/copy/blob/6e1d95722a2bf539abbfba768df774817156a573/index.js#L27-L59
20,166
jonschlinkert/copy
index.js
copyEach
function copyEach(files, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({}, options); if (typeof opts.cwd === 'undefined') { opts.cwd = process.cwd(); } if (!opts.srcBase && opts.patterns) { opts.srcBase = path.resolve(opts.cwd, utils.parent(opts.patterns)); } utils.each(files, function(filename, next) { var filepath = path.resolve(opts.cwd, filename); if (utils.isDirectory(filepath)) { next() return; } copyOne(filepath, dir, opts, next); }, function(err, arr) { if (err) { cb(err); return; } cb(null, arr.filter(Boolean)); }); }
javascript
function copyEach(files, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({}, options); if (typeof opts.cwd === 'undefined') { opts.cwd = process.cwd(); } if (!opts.srcBase && opts.patterns) { opts.srcBase = path.resolve(opts.cwd, utils.parent(opts.patterns)); } utils.each(files, function(filename, next) { var filepath = path.resolve(opts.cwd, filename); if (utils.isDirectory(filepath)) { next() return; } copyOne(filepath, dir, opts, next); }, function(err, arr) { if (err) { cb(err); return; } cb(null, arr.filter(Boolean)); }); }
[ "function", "copyEach", "(", "files", ",", "dir", ",", "options", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "return", "invalid", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "cb", "=", "options", ";", "options", "=", "{", "}", ";", "}", "var", "opts", "=", "utils", ".", "extend", "(", "{", "}", ",", "options", ")", ";", "if", "(", "typeof", "opts", ".", "cwd", "===", "'undefined'", ")", "{", "opts", ".", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "}", "if", "(", "!", "opts", ".", "srcBase", "&&", "opts", ".", "patterns", ")", "{", "opts", ".", "srcBase", "=", "path", ".", "resolve", "(", "opts", ".", "cwd", ",", "utils", ".", "parent", "(", "opts", ".", "patterns", ")", ")", ";", "}", "utils", ".", "each", "(", "files", ",", "function", "(", "filename", ",", "next", ")", "{", "var", "filepath", "=", "path", ".", "resolve", "(", "opts", ".", "cwd", ",", "filename", ")", ";", "if", "(", "utils", ".", "isDirectory", "(", "filepath", ")", ")", "{", "next", "(", ")", "return", ";", "}", "copyOne", "(", "filepath", ",", "dir", ",", "opts", ",", "next", ")", ";", "}", ",", "function", "(", "err", ",", "arr", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "return", ";", "}", "cb", "(", "null", ",", "arr", ".", "filter", "(", "Boolean", ")", ")", ";", "}", ")", ";", "}" ]
Copy an array of files to the given destination `directory`, with `options` and callback function that exposes `err` and the array of vinyl files that are created by the copy operation. ```js copy.each(['foo.txt', 'bar.txt', 'baz.txt'], 'dist', function(err, files) { // exposes the vinyl `files` created when the files are copied }); ``` @name .copy.each @param {Array} `files` Filepaths or vinyl files. @param {String} `dir` Destination directory @param {Object|Function} `options` or callback function @param {Function} `cb` Callback function if no options are specified @api public
[ "Copy", "an", "array", "of", "files", "to", "the", "given", "destination", "directory", "with", "options", "and", "callback", "function", "that", "exposes", "err", "and", "the", "array", "of", "vinyl", "files", "that", "are", "created", "by", "the", "copy", "operation", "." ]
6e1d95722a2bf539abbfba768df774817156a573
https://github.com/jonschlinkert/copy/blob/6e1d95722a2bf539abbfba768df774817156a573/index.js#L79-L112
20,167
jonschlinkert/copy
index.js
copyOne
function copyOne(file, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({}, options); if (typeof opts.cwd === 'undefined') { opts.cwd = process.cwd(); } if (typeof file === 'string') { file = path.resolve(opts.cwd, file); } if (!opts.srcBase && opts.patterns) { opts.srcBase = path.resolve(opts.cwd, utils.parent(opts.patterns)); } toDest(dir, file, opts, function(err, out) { if (err) { cb(err); return; } base(file, out.path, opts, function(err) { if (err) { cb(err); return; } cb(null, out); }); }); }
javascript
function copyOne(file, dir, options, cb) { if (arguments.length < 3) { return invalid.apply(null, arguments); } if (typeof options === 'function') { cb = options; options = {}; } var opts = utils.extend({}, options); if (typeof opts.cwd === 'undefined') { opts.cwd = process.cwd(); } if (typeof file === 'string') { file = path.resolve(opts.cwd, file); } if (!opts.srcBase && opts.patterns) { opts.srcBase = path.resolve(opts.cwd, utils.parent(opts.patterns)); } toDest(dir, file, opts, function(err, out) { if (err) { cb(err); return; } base(file, out.path, opts, function(err) { if (err) { cb(err); return; } cb(null, out); }); }); }
[ "function", "copyOne", "(", "file", ",", "dir", ",", "options", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "return", "invalid", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "cb", "=", "options", ";", "options", "=", "{", "}", ";", "}", "var", "opts", "=", "utils", ".", "extend", "(", "{", "}", ",", "options", ")", ";", "if", "(", "typeof", "opts", ".", "cwd", "===", "'undefined'", ")", "{", "opts", ".", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "}", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "file", "=", "path", ".", "resolve", "(", "opts", ".", "cwd", ",", "file", ")", ";", "}", "if", "(", "!", "opts", ".", "srcBase", "&&", "opts", ".", "patterns", ")", "{", "opts", ".", "srcBase", "=", "path", ".", "resolve", "(", "opts", ".", "cwd", ",", "utils", ".", "parent", "(", "opts", ".", "patterns", ")", ")", ";", "}", "toDest", "(", "dir", ",", "file", ",", "opts", ",", "function", "(", "err", ",", "out", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "return", ";", "}", "base", "(", "file", ",", "out", ".", "path", ",", "opts", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "return", ";", "}", "cb", "(", "null", ",", "out", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Copy a single `file` to the given `dest` directory, using the specified options and callback function. ```js copy.one('foo.txt', 'dist', function(err, file) { if (err) throw err; // exposes the vinyl `file` that is created when the file is copied }); ``` @name .copy.one @param {String|Object} `file` Filepath or vinyl file @param {String} `dir` Destination directory @param {Object|Function} `options` or callback function @param {Function} `cb` Callback function if no options are specified @api public
[ "Copy", "a", "single", "file", "to", "the", "given", "dest", "directory", "using", "the", "specified", "options", "and", "callback", "function", "." ]
6e1d95722a2bf539abbfba768df774817156a573
https://github.com/jonschlinkert/copy/blob/6e1d95722a2bf539abbfba768df774817156a573/index.js#L132-L169
20,168
jonschlinkert/copy
lib/base.js
copyBase
function copyBase(src, dest, options, callback) { if (typeof options !== 'object') { callback = options; options = {}; } if (arguments.length < 3) { return invalid.apply(null, arguments); } var fs = utils.fs; // graceful-fs (lazyily required) var opts = utils.extend({overwrite: true}, options); var cb = once(callback); var listener = once(ws); src = path.resolve(src); var rs = fs.createReadStream(src) .on('error', handleError('read', src, opts, cb)) .once('readable', listener) .on('end', listener); function ws() { mkdir(dest, function(err) { if (err) return cb(err); rs.pipe(fs.createWriteStream(dest, writeOpts(opts)) .on('error', handleError('write', dest, opts, cb)) .on('close', handleClose(src, dest, cb))); }); } }
javascript
function copyBase(src, dest, options, callback) { if (typeof options !== 'object') { callback = options; options = {}; } if (arguments.length < 3) { return invalid.apply(null, arguments); } var fs = utils.fs; // graceful-fs (lazyily required) var opts = utils.extend({overwrite: true}, options); var cb = once(callback); var listener = once(ws); src = path.resolve(src); var rs = fs.createReadStream(src) .on('error', handleError('read', src, opts, cb)) .once('readable', listener) .on('end', listener); function ws() { mkdir(dest, function(err) { if (err) return cb(err); rs.pipe(fs.createWriteStream(dest, writeOpts(opts)) .on('error', handleError('write', dest, opts, cb)) .on('close', handleClose(src, dest, cb))); }); } }
[ "function", "copyBase", "(", "src", ",", "dest", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "!==", "'object'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "return", "invalid", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "var", "fs", "=", "utils", ".", "fs", ";", "// graceful-fs (lazyily required)", "var", "opts", "=", "utils", ".", "extend", "(", "{", "overwrite", ":", "true", "}", ",", "options", ")", ";", "var", "cb", "=", "once", "(", "callback", ")", ";", "var", "listener", "=", "once", "(", "ws", ")", ";", "src", "=", "path", ".", "resolve", "(", "src", ")", ";", "var", "rs", "=", "fs", ".", "createReadStream", "(", "src", ")", ".", "on", "(", "'error'", ",", "handleError", "(", "'read'", ",", "src", ",", "opts", ",", "cb", ")", ")", ".", "once", "(", "'readable'", ",", "listener", ")", ".", "on", "(", "'end'", ",", "listener", ")", ";", "function", "ws", "(", ")", "{", "mkdir", "(", "dest", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "rs", ".", "pipe", "(", "fs", ".", "createWriteStream", "(", "dest", ",", "writeOpts", "(", "opts", ")", ")", ".", "on", "(", "'error'", ",", "handleError", "(", "'write'", ",", "dest", ",", "opts", ",", "cb", ")", ")", ".", "on", "(", "'close'", ",", "handleClose", "(", "src", ",", "dest", ",", "cb", ")", ")", ")", ";", "}", ")", ";", "}", "}" ]
Copy a file from `src` to `dest` @param {String} `src` Source filepath @param {String} `dest` Destination filepath @param {Object} `options` @param {Function} `cb` Callback function @api public
[ "Copy", "a", "file", "from", "src", "to", "dest" ]
6e1d95722a2bf539abbfba768df774817156a573
https://github.com/jonschlinkert/copy/blob/6e1d95722a2bf539abbfba768df774817156a573/lib/base.js#L18-L47
20,169
jonschlinkert/copy
lib/base.js
writeOpts
function writeOpts(opts) { return utils.extend({ flags: opts.flags || (opts.overwrite ? 'w' : 'wx') }, opts); }
javascript
function writeOpts(opts) { return utils.extend({ flags: opts.flags || (opts.overwrite ? 'w' : 'wx') }, opts); }
[ "function", "writeOpts", "(", "opts", ")", "{", "return", "utils", ".", "extend", "(", "{", "flags", ":", "opts", ".", "flags", "||", "(", "opts", ".", "overwrite", "?", "'w'", ":", "'wx'", ")", "}", ",", "opts", ")", ";", "}" ]
Normalize write options @param {Object} `opts` @return {Object}
[ "Normalize", "write", "options" ]
6e1d95722a2bf539abbfba768df774817156a573
https://github.com/jonschlinkert/copy/blob/6e1d95722a2bf539abbfba768df774817156a573/lib/base.js#L56-L60
20,170
jonschlinkert/copy
lib/base.js
mkdir
function mkdir(dest, cb) { var dir = path.dirname(path.resolve(dest)); utils.mkdirp(dir, function(err) { if (err && err.code !== 'EEXIST') { err.message = formatError('mkdirp cannot create directory', dir, err); return cb(new Error(err)); } cb(); }); }
javascript
function mkdir(dest, cb) { var dir = path.dirname(path.resolve(dest)); utils.mkdirp(dir, function(err) { if (err && err.code !== 'EEXIST') { err.message = formatError('mkdirp cannot create directory', dir, err); return cb(new Error(err)); } cb(); }); }
[ "function", "mkdir", "(", "dest", ",", "cb", ")", "{", "var", "dir", "=", "path", ".", "dirname", "(", "path", ".", "resolve", "(", "dest", ")", ")", ";", "utils", ".", "mkdirp", "(", "dir", ",", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "err", ".", "code", "!==", "'EEXIST'", ")", "{", "err", ".", "message", "=", "formatError", "(", "'mkdirp cannot create directory'", ",", "dir", ",", "err", ")", ";", "return", "cb", "(", "new", "Error", "(", "err", ")", ")", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}" ]
Ensure that a directory exists before trying to write to it. @param {String} `dest` @param {Function} `cb` Callback function
[ "Ensure", "that", "a", "directory", "exists", "before", "trying", "to", "write", "to", "it", "." ]
6e1d95722a2bf539abbfba768df774817156a573
https://github.com/jonschlinkert/copy/blob/6e1d95722a2bf539abbfba768df774817156a573/lib/base.js#L69-L78
20,171
jonschlinkert/copy
lib/base.js
handleError
function handleError(type, filepath, opts, cb) { return function(err) { switch (type) { case 'read': if (err.code === 'ENOENT') { err.message = formatError('file does not exist', filepath, err); } else { err.message = formatError('cannot read file', filepath, err); } break; case 'write': if (!opts.overwrite && err.code === 'EEXIST') { return cb(); } err.message = formatError('cannot write to', filepath, err); break; } cb(err); }; }
javascript
function handleError(type, filepath, opts, cb) { return function(err) { switch (type) { case 'read': if (err.code === 'ENOENT') { err.message = formatError('file does not exist', filepath, err); } else { err.message = formatError('cannot read file', filepath, err); } break; case 'write': if (!opts.overwrite && err.code === 'EEXIST') { return cb(); } err.message = formatError('cannot write to', filepath, err); break; } cb(err); }; }
[ "function", "handleError", "(", "type", ",", "filepath", ",", "opts", ",", "cb", ")", "{", "return", "function", "(", "err", ")", "{", "switch", "(", "type", ")", "{", "case", "'read'", ":", "if", "(", "err", ".", "code", "===", "'ENOENT'", ")", "{", "err", ".", "message", "=", "formatError", "(", "'file does not exist'", ",", "filepath", ",", "err", ")", ";", "}", "else", "{", "err", ".", "message", "=", "formatError", "(", "'cannot read file'", ",", "filepath", ",", "err", ")", ";", "}", "break", ";", "case", "'write'", ":", "if", "(", "!", "opts", ".", "overwrite", "&&", "err", ".", "code", "===", "'EEXIST'", ")", "{", "return", "cb", "(", ")", ";", "}", "err", ".", "message", "=", "formatError", "(", "'cannot write to'", ",", "filepath", ",", "err", ")", ";", "break", ";", "}", "cb", "(", "err", ")", ";", "}", ";", "}" ]
Handle errors with custom message formatting. @param {String} `type` types are "read" or "write" @param {String} `filepath` filepath that caused the error @param {Object} `options` @param {Function} `cb` callback function
[ "Handle", "errors", "with", "custom", "message", "formatting", "." ]
6e1d95722a2bf539abbfba768df774817156a573
https://github.com/jonschlinkert/copy/blob/6e1d95722a2bf539abbfba768df774817156a573/lib/base.js#L102-L121
20,172
jonschlinkert/copy
lib/invalid.js
invalidArgs
function invalidArgs(src, dest, options, cb) { // get the callback so we can give the correct errors // when src or dest is missing if (typeof dest === 'function') cb = dest; if (typeof src === 'function') cb = src; if (typeof cb !== 'function') { throw new TypeError('expected callback to be a function'); } if (typeof src !== 'string') { return cb(new TypeError('expected "src" to be a string')); } if (typeof dest !== 'string') { return cb(new TypeError('expected "dest" to be a string')); } }
javascript
function invalidArgs(src, dest, options, cb) { // get the callback so we can give the correct errors // when src or dest is missing if (typeof dest === 'function') cb = dest; if (typeof src === 'function') cb = src; if (typeof cb !== 'function') { throw new TypeError('expected callback to be a function'); } if (typeof src !== 'string') { return cb(new TypeError('expected "src" to be a string')); } if (typeof dest !== 'string') { return cb(new TypeError('expected "dest" to be a string')); } }
[ "function", "invalidArgs", "(", "src", ",", "dest", ",", "options", ",", "cb", ")", "{", "// get the callback so we can give the correct errors", "// when src or dest is missing", "if", "(", "typeof", "dest", "===", "'function'", ")", "cb", "=", "dest", ";", "if", "(", "typeof", "src", "===", "'function'", ")", "cb", "=", "src", ";", "if", "(", "typeof", "cb", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'expected callback to be a function'", ")", ";", "}", "if", "(", "typeof", "src", "!==", "'string'", ")", "{", "return", "cb", "(", "new", "TypeError", "(", "'expected \"src\" to be a string'", ")", ")", ";", "}", "if", "(", "typeof", "dest", "!==", "'string'", ")", "{", "return", "cb", "(", "new", "TypeError", "(", "'expected \"dest\" to be a string'", ")", ")", ";", "}", "}" ]
Handle errors for invalid arguments @param {String} `src` @param {String} `dest` @param {Object} `options` @param {Function} `cb` (if async)
[ "Handle", "errors", "for", "invalid", "arguments" ]
6e1d95722a2bf539abbfba768df774817156a573
https://github.com/jonschlinkert/copy/blob/6e1d95722a2bf539abbfba768df774817156a573/lib/invalid.js#L12-L26
20,173
plotly/plotly-nodejs
index.js
parseRes
function parseRes (res, cb) { var body = ''; if ('setEncoding' in res) res.setEncoding('utf-8'); res.on('data', function (data) { body += data; if (body.length > 1e10) { // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ res.connection.destroy(); res.writeHead(413, {'Content-Type': 'text/plain'}); res.end('req body too large'); return cb(new Error('body overflow')); } }); res.on('end', function () { cb(null, body); }); }
javascript
function parseRes (res, cb) { var body = ''; if ('setEncoding' in res) res.setEncoding('utf-8'); res.on('data', function (data) { body += data; if (body.length > 1e10) { // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ res.connection.destroy(); res.writeHead(413, {'Content-Type': 'text/plain'}); res.end('req body too large'); return cb(new Error('body overflow')); } }); res.on('end', function () { cb(null, body); }); }
[ "function", "parseRes", "(", "res", ",", "cb", ")", "{", "var", "body", "=", "''", ";", "if", "(", "'setEncoding'", "in", "res", ")", "res", ".", "setEncoding", "(", "'utf-8'", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "body", "+=", "data", ";", "if", "(", "body", ".", "length", ">", "1e10", ")", "{", "// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ", "res", ".", "connection", ".", "destroy", "(", ")", ";", "res", ".", "writeHead", "(", "413", ",", "{", "'Content-Type'", ":", "'text/plain'", "}", ")", ";", "res", ".", "end", "(", "'req body too large'", ")", ";", "return", "cb", "(", "new", "Error", "(", "'body overflow'", ")", ")", ";", "}", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "cb", "(", "null", ",", "body", ")", ";", "}", ")", ";", "}" ]
response parse helper fn
[ "response", "parse", "helper", "fn" ]
874e89b77fc37cd96a3ef4a6f3265fb54c0f3abd
https://github.com/plotly/plotly-nodejs/blob/874e89b77fc37cd96a3ef4a6f3265fb54c0f3abd/index.js#L305-L324
20,174
doowb/layouts
index.js
layouts
function layouts(file, layoutCollection, options, transformFn) { if (typeOf(file) !== 'object') { throw new TypeError('expected file to be an object'); } if (typeOf(layoutCollection) !== 'object' && !(layoutCollection instanceof Map)) { throw new TypeError('expected layouts collection to be an object'); } if (typeOf(file.contents) !== 'buffer') { throw new TypeError('expected file.contents to be a buffer'); } if (typeof options === 'function') { transformFn = options; options = null; } const opts = Object.assign({ tagname: 'body' }, options, file.options); const regex = createDelimiterRegex(opts); let name = getLayoutName(file, opts); let layout; let n = 0; if (!name) return file; define(file, 'layoutStack', file.layoutStack || []); // recursively resolve layouts while ((layout = getLayout(layoutCollection, name))) { if (inHistory(file, layout, opts)) break; // if a function is passed, call it on the file before resolving the next layout if (typeof transformFn === 'function') { transformFn(file, layout); } file.layoutStack.push(layout); name = resolveLayout(file, layout, opts, regex, name); n++; } if (n === 0) { let filename = file.relative || file.path; throw new Error(`layout "${name}" is defined on "${filename}" but cannot be found`); } return file; }
javascript
function layouts(file, layoutCollection, options, transformFn) { if (typeOf(file) !== 'object') { throw new TypeError('expected file to be an object'); } if (typeOf(layoutCollection) !== 'object' && !(layoutCollection instanceof Map)) { throw new TypeError('expected layouts collection to be an object'); } if (typeOf(file.contents) !== 'buffer') { throw new TypeError('expected file.contents to be a buffer'); } if (typeof options === 'function') { transformFn = options; options = null; } const opts = Object.assign({ tagname: 'body' }, options, file.options); const regex = createDelimiterRegex(opts); let name = getLayoutName(file, opts); let layout; let n = 0; if (!name) return file; define(file, 'layoutStack', file.layoutStack || []); // recursively resolve layouts while ((layout = getLayout(layoutCollection, name))) { if (inHistory(file, layout, opts)) break; // if a function is passed, call it on the file before resolving the next layout if (typeof transformFn === 'function') { transformFn(file, layout); } file.layoutStack.push(layout); name = resolveLayout(file, layout, opts, regex, name); n++; } if (n === 0) { let filename = file.relative || file.path; throw new Error(`layout "${name}" is defined on "${filename}" but cannot be found`); } return file; }
[ "function", "layouts", "(", "file", ",", "layoutCollection", ",", "options", ",", "transformFn", ")", "{", "if", "(", "typeOf", "(", "file", ")", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'expected file to be an object'", ")", ";", "}", "if", "(", "typeOf", "(", "layoutCollection", ")", "!==", "'object'", "&&", "!", "(", "layoutCollection", "instanceof", "Map", ")", ")", "{", "throw", "new", "TypeError", "(", "'expected layouts collection to be an object'", ")", ";", "}", "if", "(", "typeOf", "(", "file", ".", "contents", ")", "!==", "'buffer'", ")", "{", "throw", "new", "TypeError", "(", "'expected file.contents to be a buffer'", ")", ";", "}", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "transformFn", "=", "options", ";", "options", "=", "null", ";", "}", "const", "opts", "=", "Object", ".", "assign", "(", "{", "tagname", ":", "'body'", "}", ",", "options", ",", "file", ".", "options", ")", ";", "const", "regex", "=", "createDelimiterRegex", "(", "opts", ")", ";", "let", "name", "=", "getLayoutName", "(", "file", ",", "opts", ")", ";", "let", "layout", ";", "let", "n", "=", "0", ";", "if", "(", "!", "name", ")", "return", "file", ";", "define", "(", "file", ",", "'layoutStack'", ",", "file", ".", "layoutStack", "||", "[", "]", ")", ";", "// recursively resolve layouts", "while", "(", "(", "layout", "=", "getLayout", "(", "layoutCollection", ",", "name", ")", ")", ")", "{", "if", "(", "inHistory", "(", "file", ",", "layout", ",", "opts", ")", ")", "break", ";", "// if a function is passed, call it on the file before resolving the next layout", "if", "(", "typeof", "transformFn", "===", "'function'", ")", "{", "transformFn", "(", "file", ",", "layout", ")", ";", "}", "file", ".", "layoutStack", ".", "push", "(", "layout", ")", ";", "name", "=", "resolveLayout", "(", "file", ",", "layout", ",", "opts", ",", "regex", ",", "name", ")", ";", "n", "++", ";", "}", "if", "(", "n", "===", "0", ")", "{", "let", "filename", "=", "file", ".", "relative", "||", "file", ".", "path", ";", "throw", "new", "Error", "(", "`", "${", "name", "}", "${", "filename", "}", "`", ")", ";", "}", "return", "file", ";", "}" ]
Apply a layout from the `layouts` collection to `file.contents`. Layouts will be recursively applied until a layout is not defined by the returned file. @param {Object} `file` File object. This can be a plain object or vinyl file. @param {Object} `layoutCollection` Collection of file objects to use as layouts. @param {Object} `options` @return {Object} Returns the original file object with layout(s) applied.
[ "Apply", "a", "layout", "from", "the", "layouts", "collection", "to", "file", ".", "contents", ".", "Layouts", "will", "be", "recursively", "applied", "until", "a", "layout", "is", "not", "defined", "by", "the", "returned", "file", "." ]
7671e2a0d826d27d84a9077ed483b60cbefd237d
https://github.com/doowb/layouts/blob/7671e2a0d826d27d84a9077ed483b60cbefd237d/index.js#L16-L64
20,175
doowb/layouts
index.js
resolveLayout
function resolveLayout(file, layout, options, regex, name) { if (typeOf(layout.contents) !== 'buffer') { throw new Error('expected layout.contents to be a buffer'); } // reset lastIndex, since regex is cached regex.lastIndex = 0; const layoutString = toString(layout, options); if (!regex.test(layoutString)) { throw new Error(`cannot find tag "${regex.source}" in layout "${name}"`); } const fileString = toString(file, options); let str; if (options.preserveWhitespace === true) { const re = new RegExp('(?:^(\\s+))?' + regex.source, 'gm'); let lines; str = layoutString.replace(re, function(m, whitespace) { if (whitespace) { lines = lines || fileString.split('\n'); // only split once, JIT return lines.map(line => whitespace + line).join('\n'); } return fileString; }); } else { str = Buffer.from(layoutString.replace(regex, () => fileString)); } file.contents = Buffer.from(str); return getLayoutName(layout, options); }
javascript
function resolveLayout(file, layout, options, regex, name) { if (typeOf(layout.contents) !== 'buffer') { throw new Error('expected layout.contents to be a buffer'); } // reset lastIndex, since regex is cached regex.lastIndex = 0; const layoutString = toString(layout, options); if (!regex.test(layoutString)) { throw new Error(`cannot find tag "${regex.source}" in layout "${name}"`); } const fileString = toString(file, options); let str; if (options.preserveWhitespace === true) { const re = new RegExp('(?:^(\\s+))?' + regex.source, 'gm'); let lines; str = layoutString.replace(re, function(m, whitespace) { if (whitespace) { lines = lines || fileString.split('\n'); // only split once, JIT return lines.map(line => whitespace + line).join('\n'); } return fileString; }); } else { str = Buffer.from(layoutString.replace(regex, () => fileString)); } file.contents = Buffer.from(str); return getLayoutName(layout, options); }
[ "function", "resolveLayout", "(", "file", ",", "layout", ",", "options", ",", "regex", ",", "name", ")", "{", "if", "(", "typeOf", "(", "layout", ".", "contents", ")", "!==", "'buffer'", ")", "{", "throw", "new", "Error", "(", "'expected layout.contents to be a buffer'", ")", ";", "}", "// reset lastIndex, since regex is cached", "regex", ".", "lastIndex", "=", "0", ";", "const", "layoutString", "=", "toString", "(", "layout", ",", "options", ")", ";", "if", "(", "!", "regex", ".", "test", "(", "layoutString", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "regex", ".", "source", "}", "${", "name", "}", "`", ")", ";", "}", "const", "fileString", "=", "toString", "(", "file", ",", "options", ")", ";", "let", "str", ";", "if", "(", "options", ".", "preserveWhitespace", "===", "true", ")", "{", "const", "re", "=", "new", "RegExp", "(", "'(?:^(\\\\s+))?'", "+", "regex", ".", "source", ",", "'gm'", ")", ";", "let", "lines", ";", "str", "=", "layoutString", ".", "replace", "(", "re", ",", "function", "(", "m", ",", "whitespace", ")", "{", "if", "(", "whitespace", ")", "{", "lines", "=", "lines", "||", "fileString", ".", "split", "(", "'\\n'", ")", ";", "// only split once, JIT", "return", "lines", ".", "map", "(", "line", "=>", "whitespace", "+", "line", ")", ".", "join", "(", "'\\n'", ")", ";", "}", "return", "fileString", ";", "}", ")", ";", "}", "else", "{", "str", "=", "Buffer", ".", "from", "(", "layoutString", ".", "replace", "(", "regex", ",", "(", ")", "=>", "fileString", ")", ")", ";", "}", "file", ".", "contents", "=", "Buffer", ".", "from", "(", "str", ")", ";", "return", "getLayoutName", "(", "layout", ",", "options", ")", ";", "}" ]
Apply the current layout, and resolve the name of the next layout to apply.
[ "Apply", "the", "current", "layout", "and", "resolve", "the", "name", "of", "the", "next", "layout", "to", "apply", "." ]
7671e2a0d826d27d84a9077ed483b60cbefd237d
https://github.com/doowb/layouts/blob/7671e2a0d826d27d84a9077ed483b60cbefd237d/index.js#L70-L104
20,176
doowb/layouts
index.js
getLayoutName
function getLayoutName(file, options) { const defaultLayout = options.defaultLayout; const prop = options.layoutProp || 'layout'; const name = file[prop]; if (typeof name === 'undefined' || name === true || name === defaultLayout) { return defaultLayout; } if (!name || ['false', 'null', 'nil', 'none', 'undefined'].includes(name.toLowerCase())) { return false; } return name; }
javascript
function getLayoutName(file, options) { const defaultLayout = options.defaultLayout; const prop = options.layoutProp || 'layout'; const name = file[prop]; if (typeof name === 'undefined' || name === true || name === defaultLayout) { return defaultLayout; } if (!name || ['false', 'null', 'nil', 'none', 'undefined'].includes(name.toLowerCase())) { return false; } return name; }
[ "function", "getLayoutName", "(", "file", ",", "options", ")", "{", "const", "defaultLayout", "=", "options", ".", "defaultLayout", ";", "const", "prop", "=", "options", ".", "layoutProp", "||", "'layout'", ";", "const", "name", "=", "file", "[", "prop", "]", ";", "if", "(", "typeof", "name", "===", "'undefined'", "||", "name", "===", "true", "||", "name", "===", "defaultLayout", ")", "{", "return", "defaultLayout", ";", "}", "if", "(", "!", "name", "||", "[", "'false'", ",", "'null'", ",", "'nil'", ",", "'none'", ",", "'undefined'", "]", ".", "includes", "(", "name", ".", "toLowerCase", "(", ")", ")", ")", "{", "return", "false", ";", "}", "return", "name", ";", "}" ]
Get the name of the layout to use. @param {Object} `file` @param {Object} `options` @return {String|Null} Returns the name of the layout to use or `false`
[ "Get", "the", "name", "of", "the", "layout", "to", "use", "." ]
7671e2a0d826d27d84a9077ed483b60cbefd237d
https://github.com/doowb/layouts/blob/7671e2a0d826d27d84a9077ed483b60cbefd237d/index.js#L113-L124
20,177
doowb/layouts
index.js
inHistory
function inHistory(file, layout, options) { return !options.disableHistory && file.layoutStack.indexOf(layout) !== -1; }
javascript
function inHistory(file, layout, options) { return !options.disableHistory && file.layoutStack.indexOf(layout) !== -1; }
[ "function", "inHistory", "(", "file", ",", "layout", ",", "options", ")", "{", "return", "!", "options", ".", "disableHistory", "&&", "file", ".", "layoutStack", ".", "indexOf", "(", "layout", ")", "!==", "-", "1", ";", "}" ]
Returns true if `name` is in the layout `history`
[ "Returns", "true", "if", "name", "is", "in", "the", "layout", "history" ]
7671e2a0d826d27d84a9077ed483b60cbefd237d
https://github.com/doowb/layouts/blob/7671e2a0d826d27d84a9077ed483b60cbefd237d/index.js#L130-L132
20,178
doowb/layouts
index.js
getLayout
function getLayout(collection, name) { if (!name) return; if (collection instanceof Map) { for (const [key, view] of collection) { if (name === key) { return view; } if (!view.path) continue; if (!view.hasPath) { return getView(collection, name); } if (view.hasPath(name)) { return view; } } return; } for (const key of Object.keys(collection)) { const view = collection[key]; if (name === key) { return view; } if (!view.path) continue; if (!view.hasPath) { return getView(collection, name); } if (view.hasPath(name)) { return view; } } }
javascript
function getLayout(collection, name) { if (!name) return; if (collection instanceof Map) { for (const [key, view] of collection) { if (name === key) { return view; } if (!view.path) continue; if (!view.hasPath) { return getView(collection, name); } if (view.hasPath(name)) { return view; } } return; } for (const key of Object.keys(collection)) { const view = collection[key]; if (name === key) { return view; } if (!view.path) continue; if (!view.hasPath) { return getView(collection, name); } if (view.hasPath(name)) { return view; } } }
[ "function", "getLayout", "(", "collection", ",", "name", ")", "{", "if", "(", "!", "name", ")", "return", ";", "if", "(", "collection", "instanceof", "Map", ")", "{", "for", "(", "const", "[", "key", ",", "view", "]", "of", "collection", ")", "{", "if", "(", "name", "===", "key", ")", "{", "return", "view", ";", "}", "if", "(", "!", "view", ".", "path", ")", "continue", ";", "if", "(", "!", "view", ".", "hasPath", ")", "{", "return", "getView", "(", "collection", ",", "name", ")", ";", "}", "if", "(", "view", ".", "hasPath", "(", "name", ")", ")", "{", "return", "view", ";", "}", "}", "return", ";", "}", "for", "(", "const", "key", "of", "Object", ".", "keys", "(", "collection", ")", ")", "{", "const", "view", "=", "collection", "[", "key", "]", ";", "if", "(", "name", "===", "key", ")", "{", "return", "view", ";", "}", "if", "(", "!", "view", ".", "path", ")", "continue", ";", "if", "(", "!", "view", ".", "hasPath", ")", "{", "return", "getView", "(", "collection", ",", "name", ")", ";", "}", "if", "(", "view", ".", "hasPath", "(", "name", ")", ")", "{", "return", "view", ";", "}", "}", "}" ]
Gets the layout to use from the given collection
[ "Gets", "the", "layout", "to", "use", "from", "the", "given", "collection" ]
7671e2a0d826d27d84a9077ed483b60cbefd237d
https://github.com/doowb/layouts/blob/7671e2a0d826d27d84a9077ed483b60cbefd237d/index.js#L138-L169
20,179
doowb/layouts
index.js
createDelimiterRegex
function createDelimiterRegex(options) { const opts = Object.assign({}, options); let tagname = options.tagname; let layoutDelims = options.delims || options.layoutDelims || `{% (${tagname}) %}`; let key = tagname; if (layoutDelims) key += layoutDelims.toString(); if (layouts.memo.has(key)) { return layouts.memo.get(key); } if (layoutDelims instanceof RegExp) { layouts.memo.set(key, layoutDelims); return layoutDelims; } if (Array.isArray(layoutDelims)) { layoutDelims = `${opts.layoutDelims[0]} (${tagname}) ${opts.layoutDelims[1]}`; } if (typeof layoutDelims !== 'string') { throw new TypeError('expected options.layoutDelims to be a string, array or regex'); } const regex = new RegExp(layoutDelims, 'g'); layouts.memo.set(key, regex); return regex; }
javascript
function createDelimiterRegex(options) { const opts = Object.assign({}, options); let tagname = options.tagname; let layoutDelims = options.delims || options.layoutDelims || `{% (${tagname}) %}`; let key = tagname; if (layoutDelims) key += layoutDelims.toString(); if (layouts.memo.has(key)) { return layouts.memo.get(key); } if (layoutDelims instanceof RegExp) { layouts.memo.set(key, layoutDelims); return layoutDelims; } if (Array.isArray(layoutDelims)) { layoutDelims = `${opts.layoutDelims[0]} (${tagname}) ${opts.layoutDelims[1]}`; } if (typeof layoutDelims !== 'string') { throw new TypeError('expected options.layoutDelims to be a string, array or regex'); } const regex = new RegExp(layoutDelims, 'g'); layouts.memo.set(key, regex); return regex; }
[ "function", "createDelimiterRegex", "(", "options", ")", "{", "const", "opts", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "let", "tagname", "=", "options", ".", "tagname", ";", "let", "layoutDelims", "=", "options", ".", "delims", "||", "options", ".", "layoutDelims", "||", "`", "${", "tagname", "}", "`", ";", "let", "key", "=", "tagname", ";", "if", "(", "layoutDelims", ")", "key", "+=", "layoutDelims", ".", "toString", "(", ")", ";", "if", "(", "layouts", ".", "memo", ".", "has", "(", "key", ")", ")", "{", "return", "layouts", ".", "memo", ".", "get", "(", "key", ")", ";", "}", "if", "(", "layoutDelims", "instanceof", "RegExp", ")", "{", "layouts", ".", "memo", ".", "set", "(", "key", ",", "layoutDelims", ")", ";", "return", "layoutDelims", ";", "}", "if", "(", "Array", ".", "isArray", "(", "layoutDelims", ")", ")", "{", "layoutDelims", "=", "`", "${", "opts", ".", "layoutDelims", "[", "0", "]", "}", "${", "tagname", "}", "${", "opts", ".", "layoutDelims", "[", "1", "]", "}", "`", ";", "}", "if", "(", "typeof", "layoutDelims", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'expected options.layoutDelims to be a string, array or regex'", ")", ";", "}", "const", "regex", "=", "new", "RegExp", "(", "layoutDelims", ",", "'g'", ")", ";", "layouts", ".", "memo", ".", "set", "(", "key", ",", "regex", ")", ";", "return", "regex", ";", "}" ]
Creates a regular expression to use for matching delimiters, based on the given options.
[ "Creates", "a", "regular", "expression", "to", "use", "for", "matching", "delimiters", "based", "on", "the", "given", "options", "." ]
7671e2a0d826d27d84a9077ed483b60cbefd237d
https://github.com/doowb/layouts/blob/7671e2a0d826d27d84a9077ed483b60cbefd237d/index.js#L176-L203
20,180
doowb/layouts
index.js
define
function define(obj, key, val) { Reflect.defineProperty(obj, key, { configurable: true, enumerable: false, writeable: true, value: val }); }
javascript
function define(obj, key, val) { Reflect.defineProperty(obj, key, { configurable: true, enumerable: false, writeable: true, value: val }); }
[ "function", "define", "(", "obj", ",", "key", ",", "val", ")", "{", "Reflect", ".", "defineProperty", "(", "obj", ",", "key", ",", "{", "configurable", ":", "true", ",", "enumerable", ":", "false", ",", "writeable", ":", "true", ",", "value", ":", "val", "}", ")", ";", "}" ]
Add a non-enumerable property to `obj`
[ "Add", "a", "non", "-", "enumerable", "property", "to", "obj" ]
7671e2a0d826d27d84a9077ed483b60cbefd237d
https://github.com/doowb/layouts/blob/7671e2a0d826d27d84a9077ed483b60cbefd237d/index.js#L219-L226
20,181
adonisjs/adonis-websocket
clusterPubSub.js
workerIterator
function workerIterator (callback) { Object.keys(cluster.workers).forEach((index) => callback(cluster.workers[index])) }
javascript
function workerIterator (callback) { Object.keys(cluster.workers).forEach((index) => callback(cluster.workers[index])) }
[ "function", "workerIterator", "(", "callback", ")", "{", "Object", ".", "keys", "(", "cluster", ".", "workers", ")", ".", "forEach", "(", "(", "index", ")", "=>", "callback", "(", "cluster", ".", "workers", "[", "index", "]", ")", ")", "}" ]
Calls a callback by looping over cluster workers @method worketIterator @param {Function} callback @return {void}
[ "Calls", "a", "callback", "by", "looping", "over", "cluster", "workers" ]
1d99b9ad81322a4197dcf2ed638f5bd071cf3842
https://github.com/adonisjs/adonis-websocket/blob/1d99b9ad81322a4197dcf2ed638f5bd071cf3842/clusterPubSub.js#L24-L26
20,182
adonisjs/adonis-websocket
clusterPubSub.js
deliverMessage
function deliverMessage (message) { workerIterator((worker) => { if (this.process.pid === worker.process.pid) { return } debug('delivering message to %s', worker.process.pid) worker.send(message) }) }
javascript
function deliverMessage (message) { workerIterator((worker) => { if (this.process.pid === worker.process.pid) { return } debug('delivering message to %s', worker.process.pid) worker.send(message) }) }
[ "function", "deliverMessage", "(", "message", ")", "{", "workerIterator", "(", "(", "worker", ")", "=>", "{", "if", "(", "this", ".", "process", ".", "pid", "===", "worker", ".", "process", ".", "pid", ")", "{", "return", "}", "debug", "(", "'delivering message to %s'", ",", "worker", ".", "process", ".", "pid", ")", "worker", ".", "send", "(", "message", ")", "}", ")", "}" ]
Delivers the message to all the cluster workers, apart from the one that sends the message @method deliverMessage @param {String} message @return {void}
[ "Delivers", "the", "message", "to", "all", "the", "cluster", "workers", "apart", "from", "the", "one", "that", "sends", "the", "message" ]
1d99b9ad81322a4197dcf2ed638f5bd071cf3842
https://github.com/adonisjs/adonis-websocket/blob/1d99b9ad81322a4197dcf2ed638f5bd071cf3842/clusterPubSub.js#L38-L46
20,183
adonisjs/adonis-websocket
src/ClusterHop/receiver.js
deliverMessage
function deliverMessage (handle, topic, payload) { if (handle === 'broadcast') { const channel = ChannelsManager.resolve(topic) if (!channel) { return debug('broadcast topic %s cannot be handled by any channel', topic) } channel.clusterBroadcast(topic, payload) return } debug('dropping packet, since %s handle is not allowed', handle) }
javascript
function deliverMessage (handle, topic, payload) { if (handle === 'broadcast') { const channel = ChannelsManager.resolve(topic) if (!channel) { return debug('broadcast topic %s cannot be handled by any channel', topic) } channel.clusterBroadcast(topic, payload) return } debug('dropping packet, since %s handle is not allowed', handle) }
[ "function", "deliverMessage", "(", "handle", ",", "topic", ",", "payload", ")", "{", "if", "(", "handle", "===", "'broadcast'", ")", "{", "const", "channel", "=", "ChannelsManager", ".", "resolve", "(", "topic", ")", "if", "(", "!", "channel", ")", "{", "return", "debug", "(", "'broadcast topic %s cannot be handled by any channel'", ",", "topic", ")", "}", "channel", ".", "clusterBroadcast", "(", "topic", ",", "payload", ")", "return", "}", "debug", "(", "'dropping packet, since %s handle is not allowed'", ",", "handle", ")", "}" ]
Delivers the message from process to the channel @method deliverMessage @param {String} handle @param {String} topic @param {String} payload @return {void}
[ "Delivers", "the", "message", "from", "process", "to", "the", "channel" ]
1d99b9ad81322a4197dcf2ed638f5bd071cf3842
https://github.com/adonisjs/adonis-websocket/blob/1d99b9ad81322a4197dcf2ed638f5bd071cf3842/src/ClusterHop/receiver.js#L26-L39
20,184
OptimalBits/dolphin
index.js
getMachineEnv
function getMachineEnv(machine) { var child = require('child_process'); var result = child.spawnSync('docker-machine', ['env', machine]); if (result.status === 0) { var str = result.stdout.toString(); var expr = str .replace(new RegExp('export ', 'g'), 'envs.') .split('\n') .filter(function (line) { return line[0] !== '#'; }).join(';') var envs = {}; eval(expr); return envs; } else { throw Error(result.stderr) } }
javascript
function getMachineEnv(machine) { var child = require('child_process'); var result = child.spawnSync('docker-machine', ['env', machine]); if (result.status === 0) { var str = result.stdout.toString(); var expr = str .replace(new RegExp('export ', 'g'), 'envs.') .split('\n') .filter(function (line) { return line[0] !== '#'; }).join(';') var envs = {}; eval(expr); return envs; } else { throw Error(result.stderr) } }
[ "function", "getMachineEnv", "(", "machine", ")", "{", "var", "child", "=", "require", "(", "'child_process'", ")", ";", "var", "result", "=", "child", ".", "spawnSync", "(", "'docker-machine'", ",", "[", "'env'", ",", "machine", "]", ")", ";", "if", "(", "result", ".", "status", "===", "0", ")", "{", "var", "str", "=", "result", ".", "stdout", ".", "toString", "(", ")", ";", "var", "expr", "=", "str", ".", "replace", "(", "new", "RegExp", "(", "'export '", ",", "'g'", ")", ",", "'envs.'", ")", ".", "split", "(", "'\\n'", ")", ".", "filter", "(", "function", "(", "line", ")", "{", "return", "line", "[", "0", "]", "!==", "'#'", ";", "}", ")", ".", "join", "(", "';'", ")", "var", "envs", "=", "{", "}", ";", "eval", "(", "expr", ")", ";", "return", "envs", ";", "}", "else", "{", "throw", "Error", "(", "result", ".", "stderr", ")", "}", "}" ]
Returns the env vars for the given docker machine.
[ "Returns", "the", "env", "vars", "for", "the", "given", "docker", "machine", "." ]
2dad4fce41eaf0ac706ba4c3b0c3798b05bd1211
https://github.com/OptimalBits/dolphin/blob/2dad4fce41eaf0ac706ba4c3b0c3798b05bd1211/index.js#L345-L364
20,185
capriza/node-busmq
lib/channel.js
Channel
function Channel(bus, name, local, remote) { events.EventEmitter.call(this); this.bus = bus; this.name = name; this.type = 'channel'; this.id = 'bus:channel:' + name; this.logger = bus.logger.withTag(name); this.local = local || 'local'; this.remote = remote || 'remote'; this.handlers = { '1': this._onRemoteConnect, '2': this._onMessage, '3': this._onRemoteDisconnect, '4': this._onEnd } }
javascript
function Channel(bus, name, local, remote) { events.EventEmitter.call(this); this.bus = bus; this.name = name; this.type = 'channel'; this.id = 'bus:channel:' + name; this.logger = bus.logger.withTag(name); this.local = local || 'local'; this.remote = remote || 'remote'; this.handlers = { '1': this._onRemoteConnect, '2': this._onMessage, '3': this._onRemoteDisconnect, '4': this._onEnd } }
[ "function", "Channel", "(", "bus", ",", "name", ",", "local", ",", "remote", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "bus", "=", "bus", ";", "this", ".", "name", "=", "name", ";", "this", ".", "type", "=", "'channel'", ";", "this", ".", "id", "=", "'bus:channel:'", "+", "name", ";", "this", ".", "logger", "=", "bus", ".", "logger", ".", "withTag", "(", "name", ")", ";", "this", ".", "local", "=", "local", "||", "'local'", ";", "this", ".", "remote", "=", "remote", "||", "'remote'", ";", "this", ".", "handlers", "=", "{", "'1'", ":", "this", ".", "_onRemoteConnect", ",", "'2'", ":", "this", ".", "_onMessage", ",", "'3'", ":", "this", ".", "_onRemoteDisconnect", ",", "'4'", ":", "this", ".", "_onEnd", "}", "}" ]
Creates a new bi-directional message channel between two endpoints utilizing message queues. @param bus @param name @param local @param remote @constructor
[ "Creates", "a", "new", "bi", "-", "directional", "message", "channel", "between", "two", "endpoints", "utilizing", "message", "queues", "." ]
c66b130f959be54d0c5b1f1060d5737ef4a642d3
https://github.com/capriza/node-busmq/blob/c66b130f959be54d0c5b1f1060d5737ef4a642d3/lib/channel.js#L15-L31
20,186
capriza/node-busmq
lib/bus.js
function(err, resp) { if (err) { _this.emit('error', 'failed to upload script ' + script.name + ' to redis: ' + err); return; } else { // cluster will send back the hash as many times as there are nodes script.hash = Array.isArray(resp) ? resp[0] : resp; } if (--dones === 0) { _this.online = true; _this.logger.isDebug() && _this.logger.debug("bus is online"); _this.emit('online'); } }
javascript
function(err, resp) { if (err) { _this.emit('error', 'failed to upload script ' + script.name + ' to redis: ' + err); return; } else { // cluster will send back the hash as many times as there are nodes script.hash = Array.isArray(resp) ? resp[0] : resp; } if (--dones === 0) { _this.online = true; _this.logger.isDebug() && _this.logger.debug("bus is online"); _this.emit('online'); } }
[ "function", "(", "err", ",", "resp", ")", "{", "if", "(", "err", ")", "{", "_this", ".", "emit", "(", "'error'", ",", "'failed to upload script '", "+", "script", ".", "name", "+", "' to redis: '", "+", "err", ")", ";", "return", ";", "}", "else", "{", "// cluster will send back the hash as many times as there are nodes", "script", ".", "hash", "=", "Array", ".", "isArray", "(", "resp", ")", "?", "resp", "[", "0", "]", ":", "resp", ";", "}", "if", "(", "--", "dones", "===", "0", ")", "{", "_this", ".", "online", "=", "true", ";", "_this", ".", "logger", ".", "isDebug", "(", ")", "&&", "_this", ".", "logger", ".", "debug", "(", "\"bus is online\"", ")", ";", "_this", ".", "emit", "(", "'online'", ")", ";", "}", "}" ]
send the script to redis
[ "send", "the", "script", "to", "redis" ]
c66b130f959be54d0c5b1f1060d5737ef4a642d3
https://github.com/capriza/node-busmq/blob/c66b130f959be54d0c5b1f1060d5737ef4a642d3/lib/bus.js#L369-L383
20,187
capriza/node-busmq
lib/connection.js
Connection
function Connection(index, bus) { events.EventEmitter.call(this); this.setMaxListeners(0); // remove limit on listeners this.index = index; this.id = bus.id + ":connection:" + index; this.urls = bus.options.redis; this.redisOptions = bus.options.redisOptions || {}; this.layout = bus.options.layout; this.driver = bus.driver; this._logger = bus.logger.withTag(this.id); this.connected = false; this.ready = 0; this.pendingCommands = []; this.subscribers = {}; }
javascript
function Connection(index, bus) { events.EventEmitter.call(this); this.setMaxListeners(0); // remove limit on listeners this.index = index; this.id = bus.id + ":connection:" + index; this.urls = bus.options.redis; this.redisOptions = bus.options.redisOptions || {}; this.layout = bus.options.layout; this.driver = bus.driver; this._logger = bus.logger.withTag(this.id); this.connected = false; this.ready = 0; this.pendingCommands = []; this.subscribers = {}; }
[ "function", "Connection", "(", "index", ",", "bus", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "setMaxListeners", "(", "0", ")", ";", "// remove limit on listeners", "this", ".", "index", "=", "index", ";", "this", ".", "id", "=", "bus", ".", "id", "+", "\":connection:\"", "+", "index", ";", "this", ".", "urls", "=", "bus", ".", "options", ".", "redis", ";", "this", ".", "redisOptions", "=", "bus", ".", "options", ".", "redisOptions", "||", "{", "}", ";", "this", ".", "layout", "=", "bus", ".", "options", ".", "layout", ";", "this", ".", "driver", "=", "bus", ".", "driver", ";", "this", ".", "_logger", "=", "bus", ".", "logger", ".", "withTag", "(", "this", ".", "id", ")", ";", "this", ".", "connected", "=", "false", ";", "this", ".", "ready", "=", "0", ";", "this", ".", "pendingCommands", "=", "[", "]", ";", "this", ".", "subscribers", "=", "{", "}", ";", "}" ]
A connection to redis. Connects to redis with a write connection and a read connection. The write connection is used to emit commands to redis. The read connection is used to listen for events. This is required because once a connection is used to wait for events it cannot be used to issue further requests. @param index the index of the connection within the hosting bus @param bus the bus object using the connection @constructor
[ "A", "connection", "to", "redis", ".", "Connects", "to", "redis", "with", "a", "write", "connection", "and", "a", "read", "connection", ".", "The", "write", "connection", "is", "used", "to", "emit", "commands", "to", "redis", ".", "The", "read", "connection", "is", "used", "to", "listen", "for", "events", ".", "This", "is", "required", "because", "once", "a", "connection", "is", "used", "to", "wait", "for", "events", "it", "cannot", "be", "used", "to", "issue", "further", "requests", "." ]
c66b130f959be54d0c5b1f1060d5737ef4a642d3
https://github.com/capriza/node-busmq/blob/c66b130f959be54d0c5b1f1060d5737ef4a642d3/lib/connection.js#L33-L47
20,188
capriza/node-busmq
lib/wsmux.js
WSMuxChannel
function WSMuxChannel(id, mux) { EventEmitter.call(this); this.id = id; this.mux = mux; this.closed = false; this.url = this.mux.url; // websocket-stream relies on this method this.__defineGetter__('readyState', function() { return this.mux._readyState(); }); // hooks for websocket-stream var _this = this; this.on('open', function() { _this.onopen && _this.onopen.apply(_this, arguments); }); this.on('close', function() { _this.onclose && _this.onclose.apply(_this, arguments); }); this.on('error', function() { _this.onerror && _this.onerror.apply(_this, arguments); }); this.on('message', function() { arguments[0] = {data: arguments[0]} _this.onmessage && _this.onmessage.apply(_this, arguments); }); }
javascript
function WSMuxChannel(id, mux) { EventEmitter.call(this); this.id = id; this.mux = mux; this.closed = false; this.url = this.mux.url; // websocket-stream relies on this method this.__defineGetter__('readyState', function() { return this.mux._readyState(); }); // hooks for websocket-stream var _this = this; this.on('open', function() { _this.onopen && _this.onopen.apply(_this, arguments); }); this.on('close', function() { _this.onclose && _this.onclose.apply(_this, arguments); }); this.on('error', function() { _this.onerror && _this.onerror.apply(_this, arguments); }); this.on('message', function() { arguments[0] = {data: arguments[0]} _this.onmessage && _this.onmessage.apply(_this, arguments); }); }
[ "function", "WSMuxChannel", "(", "id", ",", "mux", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "id", "=", "id", ";", "this", ".", "mux", "=", "mux", ";", "this", ".", "closed", "=", "false", ";", "this", ".", "url", "=", "this", ".", "mux", ".", "url", ";", "// websocket-stream relies on this method", "this", ".", "__defineGetter__", "(", "'readyState'", ",", "function", "(", ")", "{", "return", "this", ".", "mux", ".", "_readyState", "(", ")", ";", "}", ")", ";", "// hooks for websocket-stream", "var", "_this", "=", "this", ";", "this", ".", "on", "(", "'open'", ",", "function", "(", ")", "{", "_this", ".", "onopen", "&&", "_this", ".", "onopen", ".", "apply", "(", "_this", ",", "arguments", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "_this", ".", "onclose", "&&", "_this", ".", "onclose", ".", "apply", "(", "_this", ",", "arguments", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'error'", ",", "function", "(", ")", "{", "_this", ".", "onerror", "&&", "_this", ".", "onerror", ".", "apply", "(", "_this", ",", "arguments", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'message'", ",", "function", "(", ")", "{", "arguments", "[", "0", "]", "=", "{", "data", ":", "arguments", "[", "0", "]", "}", "_this", ".", "onmessage", "&&", "_this", ".", "onmessage", ".", "apply", "(", "_this", ",", "arguments", ")", ";", "}", ")", ";", "}" ]
A channel on a mulitplexed websocket @param id the id of the channel @param mux the parent websocket multiplexer @constructor
[ "A", "channel", "on", "a", "mulitplexed", "websocket" ]
c66b130f959be54d0c5b1f1060d5737ef4a642d3
https://github.com/capriza/node-busmq/blob/c66b130f959be54d0c5b1f1060d5737ef4a642d3/lib/wsmux.js#L18-L48
20,189
capriza/node-busmq
lib/wspool.js
WSPool
function WSPool(bus, options) { events.EventEmitter.call(this); this.setMaxListeners(0); this.bus = bus; this.logger = bus.logger.withTag(bus.id+':wspool'); this.closed = false; this.pool = {}; this.notificationChannels = {}; this.options = options || {}; this.options.secret = this.options.secret || 'notsosecret'; if (!this.options.poolSize || this.options.poolSize <= 0) { this.options.poolSize = 10; } this.options.replaceDelay = this.options.replaceDelay || 5000; this.options.urls = this.options.urls || []; this._setupPool(); }
javascript
function WSPool(bus, options) { events.EventEmitter.call(this); this.setMaxListeners(0); this.bus = bus; this.logger = bus.logger.withTag(bus.id+':wspool'); this.closed = false; this.pool = {}; this.notificationChannels = {}; this.options = options || {}; this.options.secret = this.options.secret || 'notsosecret'; if (!this.options.poolSize || this.options.poolSize <= 0) { this.options.poolSize = 10; } this.options.replaceDelay = this.options.replaceDelay || 5000; this.options.urls = this.options.urls || []; this._setupPool(); }
[ "function", "WSPool", "(", "bus", ",", "options", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "setMaxListeners", "(", "0", ")", ";", "this", ".", "bus", "=", "bus", ";", "this", ".", "logger", "=", "bus", ".", "logger", ".", "withTag", "(", "bus", ".", "id", "+", "':wspool'", ")", ";", "this", ".", "closed", "=", "false", ";", "this", ".", "pool", "=", "{", "}", ";", "this", ".", "notificationChannels", "=", "{", "}", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "options", ".", "secret", "=", "this", ".", "options", ".", "secret", "||", "'notsosecret'", ";", "if", "(", "!", "this", ".", "options", ".", "poolSize", "||", "this", ".", "options", ".", "poolSize", "<=", "0", ")", "{", "this", ".", "options", ".", "poolSize", "=", "10", ";", "}", "this", ".", "options", ".", "replaceDelay", "=", "this", ".", "options", ".", "replaceDelay", "||", "5000", ";", "this", ".", "options", ".", "urls", "=", "this", ".", "options", ".", "urls", "||", "[", "]", ";", "this", ".", "_setupPool", "(", ")", ";", "}" ]
A pool of websockets that keeps a minimum of open websockets to a list of bus federation servers @param bus the bus owning this pool @param options additional options @constructor
[ "A", "pool", "of", "websockets", "that", "keeps", "a", "minimum", "of", "open", "websockets", "to", "a", "list", "of", "bus", "federation", "servers" ]
c66b130f959be54d0c5b1f1060d5737ef4a642d3
https://github.com/capriza/node-busmq/blob/c66b130f959be54d0c5b1f1060d5737ef4a642d3/lib/wspool.js#L12-L32
20,190
capriza/node-busmq
lib/service.js
Service
function Service(bus, name) { events.EventEmitter.call(this); this.bus = bus; this.name = name; this.logger = bus.logger.withTag(name); this.type = "service"; this.id = "service:" + name; this.replyTo = this.id + ":replyTo:" + crypto.randomBytes(8).toString("hex"); this.pendingReplies = {}; this.requesters = {}; this.inflight = 0; }
javascript
function Service(bus, name) { events.EventEmitter.call(this); this.bus = bus; this.name = name; this.logger = bus.logger.withTag(name); this.type = "service"; this.id = "service:" + name; this.replyTo = this.id + ":replyTo:" + crypto.randomBytes(8).toString("hex"); this.pendingReplies = {}; this.requesters = {}; this.inflight = 0; }
[ "function", "Service", "(", "bus", ",", "name", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "bus", "=", "bus", ";", "this", ".", "name", "=", "name", ";", "this", ".", "logger", "=", "bus", ".", "logger", ".", "withTag", "(", "name", ")", ";", "this", ".", "type", "=", "\"service\"", ";", "this", ".", "id", "=", "\"service:\"", "+", "name", ";", "this", ".", "replyTo", "=", "this", ".", "id", "+", "\":replyTo:\"", "+", "crypto", ".", "randomBytes", "(", "8", ")", ".", "toString", "(", "\"hex\"", ")", ";", "this", ".", "pendingReplies", "=", "{", "}", ";", "this", ".", "requesters", "=", "{", "}", ";", "this", ".", "inflight", "=", "0", ";", "}" ]
Creates a new service endpoint utilizing message queues @param bus @param name the service name @constructor
[ "Creates", "a", "new", "service", "endpoint", "utilizing", "message", "queues" ]
c66b130f959be54d0c5b1f1060d5737ef4a642d3
https://github.com/capriza/node-busmq/blob/c66b130f959be54d0c5b1f1060d5737ef4a642d3/lib/service.js#L15-L26
20,191
structured-log/structured-log
dist/structured-log.es6.js
LogEvent
function LogEvent(timestamp, level, messageTemplate, properties, error) { this.timestamp = timestamp; this.level = level; this.messageTemplate = messageTemplate; this.properties = properties || {}; this.error = error || null; }
javascript
function LogEvent(timestamp, level, messageTemplate, properties, error) { this.timestamp = timestamp; this.level = level; this.messageTemplate = messageTemplate; this.properties = properties || {}; this.error = error || null; }
[ "function", "LogEvent", "(", "timestamp", ",", "level", ",", "messageTemplate", ",", "properties", ",", "error", ")", "{", "this", ".", "timestamp", "=", "timestamp", ";", "this", ".", "level", "=", "level", ";", "this", ".", "messageTemplate", "=", "messageTemplate", ";", "this", ".", "properties", "=", "properties", "||", "{", "}", ";", "this", ".", "error", "=", "error", "||", "null", ";", "}" ]
Creates a new log event instance.
[ "Creates", "a", "new", "log", "event", "instance", "." ]
7c05f737316f62f32775b2fd2f0d69fb207978bd
https://github.com/structured-log/structured-log/blob/7c05f737316f62f32775b2fd2f0d69fb207978bd/dist/structured-log.es6.js#L53-L59
20,192
structured-log/structured-log
dist/structured-log.es6.js
MessageTemplate
function MessageTemplate(messageTemplate) { if (messageTemplate === null || !messageTemplate.length) { throw new Error('Argument "messageTemplate" is required.'); } this.raw = messageTemplate; this.tokens = this.tokenize(messageTemplate); }
javascript
function MessageTemplate(messageTemplate) { if (messageTemplate === null || !messageTemplate.length) { throw new Error('Argument "messageTemplate" is required.'); } this.raw = messageTemplate; this.tokens = this.tokenize(messageTemplate); }
[ "function", "MessageTemplate", "(", "messageTemplate", ")", "{", "if", "(", "messageTemplate", "===", "null", "||", "!", "messageTemplate", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Argument \"messageTemplate\" is required.'", ")", ";", "}", "this", ".", "raw", "=", "messageTemplate", ";", "this", ".", "tokens", "=", "this", ".", "tokenize", "(", "messageTemplate", ")", ";", "}" ]
Creates a new MessageTemplate instance with the given template.
[ "Creates", "a", "new", "MessageTemplate", "instance", "with", "the", "given", "template", "." ]
7c05f737316f62f32775b2fd2f0d69fb207978bd
https://github.com/structured-log/structured-log/blob/7c05f737316f62f32775b2fd2f0d69fb207978bd/dist/structured-log.es6.js#L71-L77
20,193
structured-log/structured-log
dist/structured-log.es6.js
Logger
function Logger(pipeline, suppressErrors) { this.suppressErrors = true; this.pipeline = pipeline; this.suppressErrors = typeof suppressErrors === 'undefined' || suppressErrors; }
javascript
function Logger(pipeline, suppressErrors) { this.suppressErrors = true; this.pipeline = pipeline; this.suppressErrors = typeof suppressErrors === 'undefined' || suppressErrors; }
[ "function", "Logger", "(", "pipeline", ",", "suppressErrors", ")", "{", "this", ".", "suppressErrors", "=", "true", ";", "this", ".", "pipeline", "=", "pipeline", ";", "this", ".", "suppressErrors", "=", "typeof", "suppressErrors", "===", "'undefined'", "||", "suppressErrors", ";", "}" ]
Creates a new logger instance using the specified pipeline.
[ "Creates", "a", "new", "logger", "instance", "using", "the", "specified", "pipeline", "." ]
7c05f737316f62f32775b2fd2f0d69fb207978bd
https://github.com/structured-log/structured-log/blob/7c05f737316f62f32775b2fd2f0d69fb207978bd/dist/structured-log.es6.js#L213-L217
20,194
ghinda/css-toggle-switch
bower_components/foundation-sites/js/foundation.util.box.js
ImNotTouchingYou
function ImNotTouchingYou(element, parent, lrOnly, tbOnly, ignoreBottom) { return OverlapArea(element, parent, lrOnly, tbOnly, ignoreBottom) === 0; }
javascript
function ImNotTouchingYou(element, parent, lrOnly, tbOnly, ignoreBottom) { return OverlapArea(element, parent, lrOnly, tbOnly, ignoreBottom) === 0; }
[ "function", "ImNotTouchingYou", "(", "element", ",", "parent", ",", "lrOnly", ",", "tbOnly", ",", "ignoreBottom", ")", "{", "return", "OverlapArea", "(", "element", ",", "parent", ",", "lrOnly", ",", "tbOnly", ",", "ignoreBottom", ")", "===", "0", ";", "}" ]
Compares the dimensions of an element to a container and determines collision events with container. @function @param {jQuery} element - jQuery object to test for collisions. @param {jQuery} parent - jQuery object to use as bounding container. @param {Boolean} lrOnly - set to true to check left and right values only. @param {Boolean} tbOnly - set to true to check top and bottom values only. @default if no parent object passed, detects collisions with `window`. @returns {Boolean} - true if collision free, false if a collision in any direction.
[ "Compares", "the", "dimensions", "of", "an", "element", "to", "a", "container", "and", "determines", "collision", "events", "with", "container", "." ]
9c7e7f167407d1ae07f660f62b4b4172ecd97ff8
https://github.com/ghinda/css-toggle-switch/blob/9c7e7f167407d1ae07f660f62b4b4172ecd97ff8/bower_components/foundation-sites/js/foundation.util.box.js#L24-L26
20,195
ghinda/css-toggle-switch
bower_components/foundation-sites/js/foundation.util.box.js
GetDimensions
function GetDimensions(elem, test){ elem = elem.length ? elem[0] : elem; if (elem === window || elem === document) { throw new Error("I'm sorry, Dave. I'm afraid I can't do that."); } var rect = elem.getBoundingClientRect(), parRect = elem.parentNode.getBoundingClientRect(), winRect = document.body.getBoundingClientRect(), winY = window.pageYOffset, winX = window.pageXOffset; return { width: rect.width, height: rect.height, offset: { top: rect.top + winY, left: rect.left + winX }, parentDims: { width: parRect.width, height: parRect.height, offset: { top: parRect.top + winY, left: parRect.left + winX } }, windowDims: { width: winRect.width, height: winRect.height, offset: { top: winY, left: winX } } } }
javascript
function GetDimensions(elem, test){ elem = elem.length ? elem[0] : elem; if (elem === window || elem === document) { throw new Error("I'm sorry, Dave. I'm afraid I can't do that."); } var rect = elem.getBoundingClientRect(), parRect = elem.parentNode.getBoundingClientRect(), winRect = document.body.getBoundingClientRect(), winY = window.pageYOffset, winX = window.pageXOffset; return { width: rect.width, height: rect.height, offset: { top: rect.top + winY, left: rect.left + winX }, parentDims: { width: parRect.width, height: parRect.height, offset: { top: parRect.top + winY, left: parRect.left + winX } }, windowDims: { width: winRect.width, height: winRect.height, offset: { top: winY, left: winX } } } }
[ "function", "GetDimensions", "(", "elem", ",", "test", ")", "{", "elem", "=", "elem", ".", "length", "?", "elem", "[", "0", "]", ":", "elem", ";", "if", "(", "elem", "===", "window", "||", "elem", "===", "document", ")", "{", "throw", "new", "Error", "(", "\"I'm sorry, Dave. I'm afraid I can't do that.\"", ")", ";", "}", "var", "rect", "=", "elem", ".", "getBoundingClientRect", "(", ")", ",", "parRect", "=", "elem", ".", "parentNode", ".", "getBoundingClientRect", "(", ")", ",", "winRect", "=", "document", ".", "body", ".", "getBoundingClientRect", "(", ")", ",", "winY", "=", "window", ".", "pageYOffset", ",", "winX", "=", "window", ".", "pageXOffset", ";", "return", "{", "width", ":", "rect", ".", "width", ",", "height", ":", "rect", ".", "height", ",", "offset", ":", "{", "top", ":", "rect", ".", "top", "+", "winY", ",", "left", ":", "rect", ".", "left", "+", "winX", "}", ",", "parentDims", ":", "{", "width", ":", "parRect", ".", "width", ",", "height", ":", "parRect", ".", "height", ",", "offset", ":", "{", "top", ":", "parRect", ".", "top", "+", "winY", ",", "left", ":", "parRect", ".", "left", "+", "winX", "}", "}", ",", "windowDims", ":", "{", "width", ":", "winRect", ".", "width", ",", "height", ":", "winRect", ".", "height", ",", "offset", ":", "{", "top", ":", "winY", ",", "left", ":", "winX", "}", "}", "}", "}" ]
Uses native methods to return an object of dimension values. @function @param {jQuery || HTML} element - jQuery object or DOM element for which to get the dimensions. Can be any element other that document or window. @returns {Object} - nested object of integer pixel values TODO - if element is window, return only those values.
[ "Uses", "native", "methods", "to", "return", "an", "object", "of", "dimension", "values", "." ]
9c7e7f167407d1ae07f660f62b4b4172ecd97ff8
https://github.com/ghinda/css-toggle-switch/blob/9c7e7f167407d1ae07f660f62b4b4172ecd97ff8/bower_components/foundation-sites/js/foundation.util.box.js#L69-L106
20,196
ghinda/css-toggle-switch
bower_components/qunit/reporter/html.js
hideHandler
function hideHandler( e ) { var inContainer = moduleFilter.contains( e.target ); if ( e.keyCode === 27 || !inContainer ) { if ( e.keyCode === 27 && inContainer ) { moduleSearch.focus(); } dropDown.style.display = "none"; removeEvent( document, "click", hideHandler ); removeEvent( document, "keydown", hideHandler ); moduleSearch.value = ""; searchInput(); } }
javascript
function hideHandler( e ) { var inContainer = moduleFilter.contains( e.target ); if ( e.keyCode === 27 || !inContainer ) { if ( e.keyCode === 27 && inContainer ) { moduleSearch.focus(); } dropDown.style.display = "none"; removeEvent( document, "click", hideHandler ); removeEvent( document, "keydown", hideHandler ); moduleSearch.value = ""; searchInput(); } }
[ "function", "hideHandler", "(", "e", ")", "{", "var", "inContainer", "=", "moduleFilter", ".", "contains", "(", "e", ".", "target", ")", ";", "if", "(", "e", ".", "keyCode", "===", "27", "||", "!", "inContainer", ")", "{", "if", "(", "e", ".", "keyCode", "===", "27", "&&", "inContainer", ")", "{", "moduleSearch", ".", "focus", "(", ")", ";", "}", "dropDown", ".", "style", ".", "display", "=", "\"none\"", ";", "removeEvent", "(", "document", ",", "\"click\"", ",", "hideHandler", ")", ";", "removeEvent", "(", "document", ",", "\"keydown\"", ",", "hideHandler", ")", ";", "moduleSearch", ".", "value", "=", "\"\"", ";", "searchInput", "(", ")", ";", "}", "}" ]
Hide on Escape keydown or outside-container click
[ "Hide", "on", "Escape", "keydown", "or", "outside", "-", "container", "click" ]
9c7e7f167407d1ae07f660f62b4b4172ecd97ff8
https://github.com/ghinda/css-toggle-switch/blob/9c7e7f167407d1ae07f660f62b4b4172ecd97ff8/bower_components/qunit/reporter/html.js#L394-L407
20,197
ghinda/css-toggle-switch
bower_components/qunit/reporter/html.js
searchInput
function searchInput() { var i, item, searchText = moduleSearch.value.toLowerCase(), listItems = dropDownList.children; for ( i = 0; i < listItems.length; i++ ) { item = listItems[ i ]; if ( !searchText || item.textContent.toLowerCase().indexOf( searchText ) > -1 ) { item.style.display = ""; } else { item.style.display = "none"; } } }
javascript
function searchInput() { var i, item, searchText = moduleSearch.value.toLowerCase(), listItems = dropDownList.children; for ( i = 0; i < listItems.length; i++ ) { item = listItems[ i ]; if ( !searchText || item.textContent.toLowerCase().indexOf( searchText ) > -1 ) { item.style.display = ""; } else { item.style.display = "none"; } } }
[ "function", "searchInput", "(", ")", "{", "var", "i", ",", "item", ",", "searchText", "=", "moduleSearch", ".", "value", ".", "toLowerCase", "(", ")", ",", "listItems", "=", "dropDownList", ".", "children", ";", "for", "(", "i", "=", "0", ";", "i", "<", "listItems", ".", "length", ";", "i", "++", ")", "{", "item", "=", "listItems", "[", "i", "]", ";", "if", "(", "!", "searchText", "||", "item", ".", "textContent", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "searchText", ")", ">", "-", "1", ")", "{", "item", ".", "style", ".", "display", "=", "\"\"", ";", "}", "else", "{", "item", ".", "style", ".", "display", "=", "\"none\"", ";", "}", "}", "}" ]
Processes module search box input
[ "Processes", "module", "search", "box", "input" ]
9c7e7f167407d1ae07f660f62b4b4172ecd97ff8
https://github.com/ghinda/css-toggle-switch/blob/9c7e7f167407d1ae07f660f62b4b4172ecd97ff8/bower_components/qunit/reporter/html.js#L411-L424
20,198
ghinda/css-toggle-switch
bower_components/foundation-sites/js/foundation.sticky.js
emCalc
function emCalc(em) { return parseInt(window.getComputedStyle(document.body, null).fontSize, 10) * em; }
javascript
function emCalc(em) { return parseInt(window.getComputedStyle(document.body, null).fontSize, 10) * em; }
[ "function", "emCalc", "(", "em", ")", "{", "return", "parseInt", "(", "window", ".", "getComputedStyle", "(", "document", ".", "body", ",", "null", ")", ".", "fontSize", ",", "10", ")", "*", "em", ";", "}" ]
Helper function to calculate em values @param Number {em} - number of em's to calculate into pixels
[ "Helper", "function", "to", "calculate", "em", "values" ]
9c7e7f167407d1ae07f660f62b4b4172ecd97ff8
https://github.com/ghinda/css-toggle-switch/blob/9c7e7f167407d1ae07f660f62b4b4172ecd97ff8/bower_components/foundation-sites/js/foundation.sticky.js#L503-L505
20,199
ghinda/css-toggle-switch
bower_components/qunit/qunit/qunit.js
indent
function indent(extra) { if (!this.multiline) { return ""; } var chr = this.indentChar; if (this.HTML) { chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;"); } return new Array(this.depth + (extra || 0)).join(chr); }
javascript
function indent(extra) { if (!this.multiline) { return ""; } var chr = this.indentChar; if (this.HTML) { chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;"); } return new Array(this.depth + (extra || 0)).join(chr); }
[ "function", "indent", "(", "extra", ")", "{", "if", "(", "!", "this", ".", "multiline", ")", "{", "return", "\"\"", ";", "}", "var", "chr", "=", "this", ".", "indentChar", ";", "if", "(", "this", ".", "HTML", ")", "{", "chr", "=", "chr", ".", "replace", "(", "/", "\\t", "/", "g", ",", "\" \"", ")", ".", "replace", "(", "/", " ", "/", "g", ",", "\"&#160;\"", ")", ";", "}", "return", "new", "Array", "(", "this", ".", "depth", "+", "(", "extra", "||", "0", ")", ")", ".", "join", "(", "chr", ")", ";", "}" ]
Extra can be a number, shortcut for increasing-calling-decreasing
[ "Extra", "can", "be", "a", "number", "shortcut", "for", "increasing", "-", "calling", "-", "decreasing" ]
9c7e7f167407d1ae07f660f62b4b4172ecd97ff8
https://github.com/ghinda/css-toggle-switch/blob/9c7e7f167407d1ae07f660f62b4b4172ecd97ff8/bower_components/qunit/qunit/qunit.js#L782-L791