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
47,200
mikesamuel/pug-plugin-trusted-types
packages/plugin/index.js
apply
function apply(x) { const policyPathLength = policyPath.length; policyPath[policyPathLength] = x; if (Array.isArray(x)) { for (let i = 0, len = x.length; i < len; ++i) { policyPath[policyPathLength + 1] = i; apply(x[i]); } } else if (x && typeof x === 'object') { for (const key of Object.getOwnPropertyNames(x)) { policyPath[policyPathLength + 1] = key; const valueType = typeof policy[key]; if (valueType === 'function') { policy[key](x[key]); } else if (valueType === 'object') { const policyMember = policy[key][x[key]]; if (typeof policyMember === 'function') { policyMember(x); } } if (key === 'test' || key === 'expr') { checkCodeDoesNotInterfere(x, key, true); } apply(x[key]); } } policyPath.length = policyPathLength; }
javascript
function apply(x) { const policyPathLength = policyPath.length; policyPath[policyPathLength] = x; if (Array.isArray(x)) { for (let i = 0, len = x.length; i < len; ++i) { policyPath[policyPathLength + 1] = i; apply(x[i]); } } else if (x && typeof x === 'object') { for (const key of Object.getOwnPropertyNames(x)) { policyPath[policyPathLength + 1] = key; const valueType = typeof policy[key]; if (valueType === 'function') { policy[key](x[key]); } else if (valueType === 'object') { const policyMember = policy[key][x[key]]; if (typeof policyMember === 'function') { policyMember(x); } } if (key === 'test' || key === 'expr') { checkCodeDoesNotInterfere(x, key, true); } apply(x[key]); } } policyPath.length = policyPathLength; }
[ "function", "apply", "(", "x", ")", "{", "const", "policyPathLength", "=", "policyPath", ".", "length", ";", "policyPath", "[", "policyPathLength", "]", "=", "x", ";", "if", "(", "Array", ".", "isArray", "(", "x", ")", ")", "{", "for", "(", "let", "i", "=", "0", ",", "len", "=", "x", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "policyPath", "[", "policyPathLength", "+", "1", "]", "=", "i", ";", "apply", "(", "x", "[", "i", "]", ")", ";", "}", "}", "else", "if", "(", "x", "&&", "typeof", "x", "===", "'object'", ")", "{", "for", "(", "const", "key", "of", "Object", ".", "getOwnPropertyNames", "(", "x", ")", ")", "{", "policyPath", "[", "policyPathLength", "+", "1", "]", "=", "key", ";", "const", "valueType", "=", "typeof", "policy", "[", "key", "]", ";", "if", "(", "valueType", "===", "'function'", ")", "{", "policy", "[", "key", "]", "(", "x", "[", "key", "]", ")", ";", "}", "else", "if", "(", "valueType", "===", "'object'", ")", "{", "const", "policyMember", "=", "policy", "[", "key", "]", "[", "x", "[", "key", "]", "]", ";", "if", "(", "typeof", "policyMember", "===", "'function'", ")", "{", "policyMember", "(", "x", ")", ";", "}", "}", "if", "(", "key", "===", "'test'", "||", "key", "===", "'expr'", ")", "{", "checkCodeDoesNotInterfere", "(", "x", ",", "key", ",", "true", ")", ";", "}", "apply", "(", "x", "[", "key", "]", ")", ";", "}", "}", "policyPath", ".", "length", "=", "policyPathLength", ";", "}" ]
Walk the AST applying the policy
[ "Walk", "the", "AST", "applying", "the", "policy" ]
772c5aa30ca27d46dfddd654d7a60f16fa4519d6
https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L570-L597
47,201
theThings/jailed-node
lib/Plugin.js
Plugin
function Plugin(script, _interface, options) { this._script = script this._options = options || {} this._initialInterface = _interface || {} this._connect() }
javascript
function Plugin(script, _interface, options) { this._script = script this._options = options || {} this._initialInterface = _interface || {} this._connect() }
[ "function", "Plugin", "(", "script", ",", "_interface", ",", "options", ")", "{", "this", ".", "_script", "=", "script", "this", ".", "_options", "=", "options", "||", "{", "}", "this", ".", "_initialInterface", "=", "_interface", "||", "{", "}", "this", ".", "_connect", "(", ")", "}" ]
Plugin constructor, represents a plugin initialized by a script with the given path @param {String} url of a plugin source @param {Object} _interface to provide for the plugin
[ "Plugin", "constructor", "represents", "a", "plugin", "initialized", "by", "a", "script", "with", "the", "given", "path" ]
6e453d97e74fbd1c0b27b982084f6fd7c1aa0173
https://github.com/theThings/jailed-node/blob/6e453d97e74fbd1c0b27b982084f6fd7c1aa0173/lib/Plugin.js#L18-L23
47,202
aeroith/epub-metadata-parser
lib/epub-metadata-parser.js
function (arr) { var jsonData = {}; _.forEach(arr, function (elem) { var keys = Object.keys(elem); _.forEach(keys, function (key) { var value = elem[key]; jsonData[key] = value; }); }) return jsonData; }
javascript
function (arr) { var jsonData = {}; _.forEach(arr, function (elem) { var keys = Object.keys(elem); _.forEach(keys, function (key) { var value = elem[key]; jsonData[key] = value; }); }) return jsonData; }
[ "function", "(", "arr", ")", "{", "var", "jsonData", "=", "{", "}", ";", "_", ".", "forEach", "(", "arr", ",", "function", "(", "elem", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "elem", ")", ";", "_", ".", "forEach", "(", "keys", ",", "function", "(", "key", ")", "{", "var", "value", "=", "elem", "[", "key", "]", ";", "jsonData", "[", "key", "]", "=", "value", ";", "}", ")", ";", "}", ")", "return", "jsonData", ";", "}" ]
a helper function to convert an array to json object
[ "a", "helper", "function", "to", "convert", "an", "array", "to", "json", "object" ]
e52e5066967ba8c8a0f86d2768416ab407d05e47
https://github.com/aeroith/epub-metadata-parser/blob/e52e5066967ba8c8a0f86d2768416ab407d05e47/lib/epub-metadata-parser.js#L165-L175
47,203
gribnoysup/nfield-api
index.js
bindAPI
function bindAPI (self, api, fnName) { return api[fnName].bind(self, self.__REQUEST_OPTIONS, self.__CREDENTIALS, self.__TOKEN); }
javascript
function bindAPI (self, api, fnName) { return api[fnName].bind(self, self.__REQUEST_OPTIONS, self.__CREDENTIALS, self.__TOKEN); }
[ "function", "bindAPI", "(", "self", ",", "api", ",", "fnName", ")", "{", "return", "api", "[", "fnName", "]", ".", "bind", "(", "self", ",", "self", ".", "__REQUEST_OPTIONS", ",", "self", ".", "__CREDENTIALS", ",", "self", ".", "__TOKEN", ")", ";", "}" ]
A little wrapper for easy binding API functions to ConnectedInstance
[ "A", "little", "wrapper", "for", "easy", "binding", "API", "functions", "to", "ConnectedInstance" ]
fcd635255fad2fc483d0e9045ecf7faba04378d9
https://github.com/gribnoysup/nfield-api/blob/fcd635255fad2fc483d0e9045ecf7faba04378d9/index.js#L10-L12
47,204
gribnoysup/nfield-api
index.js
ConnectedInstance
function ConnectedInstance (requestOptions, authToken, credentials) { this.__REQUEST_OPTIONS = requestOptions; this.__TOKEN = authToken; this.__CREDENTIALS = credentials; this.SurveyFieldwork = { status : bindAPI(this, API, 'statusSurveyFieldwork'), start : bindAPI(this, API, 'startSurveyFieldwork'), stop : bindAPI(this, API, 'stopSurveyFieldwork') }; this.DefaultTexts = { get : bindAPI(this, API, 'getDefaultTexts') }; this.SurveyTranslations = { get : bindAPI(this, API, 'getSurveyTranslations'), add : bindAPI(this, API, 'addSurveyTranslations'), update : bindAPI(this, API, 'updateSurveyTranslations'), remove : bindAPI(this, API, 'removeSurveyTranslations') }; this.SurveyLanguages = { get : bindAPI(this, API, 'getSurveyLanguages'), add : bindAPI(this, API, 'addSurveyLanguages'), update : bindAPI(this, API, 'updateSurveyLanguages'), remove : bindAPI(this, API, 'removeSurveyLanguages') }; this.SurveySettings = { get : bindAPI(this, API, 'getSurveySettings'), update : bindAPI(this, API, 'updateSurveySettings') }; this.SurveyScript = { get : bindAPI(this, API, 'getSurveyScript'), update : bindAPI(this, API, 'updateSurveyScript') }; this.SurveyData = { request : bindAPI(this, API, 'requestSurveyData') }; this.Surveys = { get : bindAPI(this, API, 'getSurveys'), add : bindAPI(this, API, 'addSurveys'), update : bindAPI(this, API, 'updateSurveys'), remove : bindAPI(this, API, 'removeSurveys') }; this.SurveyPublish = { get : bindAPI(this, API, 'getSurveyPublish'), update : bindAPI(this, API, 'updateSurveyPublish') }; this.BackgroundTasks = { get : bindAPI(this, API, 'getBackgroundTasks') }; this.InterviewQuality = { get : bindAPI(this, API, 'getInterviewQuality'), update : bindAPI(this, API, 'updateInterviewQuality') }; }
javascript
function ConnectedInstance (requestOptions, authToken, credentials) { this.__REQUEST_OPTIONS = requestOptions; this.__TOKEN = authToken; this.__CREDENTIALS = credentials; this.SurveyFieldwork = { status : bindAPI(this, API, 'statusSurveyFieldwork'), start : bindAPI(this, API, 'startSurveyFieldwork'), stop : bindAPI(this, API, 'stopSurveyFieldwork') }; this.DefaultTexts = { get : bindAPI(this, API, 'getDefaultTexts') }; this.SurveyTranslations = { get : bindAPI(this, API, 'getSurveyTranslations'), add : bindAPI(this, API, 'addSurveyTranslations'), update : bindAPI(this, API, 'updateSurveyTranslations'), remove : bindAPI(this, API, 'removeSurveyTranslations') }; this.SurveyLanguages = { get : bindAPI(this, API, 'getSurveyLanguages'), add : bindAPI(this, API, 'addSurveyLanguages'), update : bindAPI(this, API, 'updateSurveyLanguages'), remove : bindAPI(this, API, 'removeSurveyLanguages') }; this.SurveySettings = { get : bindAPI(this, API, 'getSurveySettings'), update : bindAPI(this, API, 'updateSurveySettings') }; this.SurveyScript = { get : bindAPI(this, API, 'getSurveyScript'), update : bindAPI(this, API, 'updateSurveyScript') }; this.SurveyData = { request : bindAPI(this, API, 'requestSurveyData') }; this.Surveys = { get : bindAPI(this, API, 'getSurveys'), add : bindAPI(this, API, 'addSurveys'), update : bindAPI(this, API, 'updateSurveys'), remove : bindAPI(this, API, 'removeSurveys') }; this.SurveyPublish = { get : bindAPI(this, API, 'getSurveyPublish'), update : bindAPI(this, API, 'updateSurveyPublish') }; this.BackgroundTasks = { get : bindAPI(this, API, 'getBackgroundTasks') }; this.InterviewQuality = { get : bindAPI(this, API, 'getInterviewQuality'), update : bindAPI(this, API, 'updateInterviewQuality') }; }
[ "function", "ConnectedInstance", "(", "requestOptions", ",", "authToken", ",", "credentials", ")", "{", "this", ".", "__REQUEST_OPTIONS", "=", "requestOptions", ";", "this", ".", "__TOKEN", "=", "authToken", ";", "this", ".", "__CREDENTIALS", "=", "credentials", ";", "this", ".", "SurveyFieldwork", "=", "{", "status", ":", "bindAPI", "(", "this", ",", "API", ",", "'statusSurveyFieldwork'", ")", ",", "start", ":", "bindAPI", "(", "this", ",", "API", ",", "'startSurveyFieldwork'", ")", ",", "stop", ":", "bindAPI", "(", "this", ",", "API", ",", "'stopSurveyFieldwork'", ")", "}", ";", "this", ".", "DefaultTexts", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getDefaultTexts'", ")", "}", ";", "this", ".", "SurveyTranslations", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getSurveyTranslations'", ")", ",", "add", ":", "bindAPI", "(", "this", ",", "API", ",", "'addSurveyTranslations'", ")", ",", "update", ":", "bindAPI", "(", "this", ",", "API", ",", "'updateSurveyTranslations'", ")", ",", "remove", ":", "bindAPI", "(", "this", ",", "API", ",", "'removeSurveyTranslations'", ")", "}", ";", "this", ".", "SurveyLanguages", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getSurveyLanguages'", ")", ",", "add", ":", "bindAPI", "(", "this", ",", "API", ",", "'addSurveyLanguages'", ")", ",", "update", ":", "bindAPI", "(", "this", ",", "API", ",", "'updateSurveyLanguages'", ")", ",", "remove", ":", "bindAPI", "(", "this", ",", "API", ",", "'removeSurveyLanguages'", ")", "}", ";", "this", ".", "SurveySettings", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getSurveySettings'", ")", ",", "update", ":", "bindAPI", "(", "this", ",", "API", ",", "'updateSurveySettings'", ")", "}", ";", "this", ".", "SurveyScript", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getSurveyScript'", ")", ",", "update", ":", "bindAPI", "(", "this", ",", "API", ",", "'updateSurveyScript'", ")", "}", ";", "this", ".", "SurveyData", "=", "{", "request", ":", "bindAPI", "(", "this", ",", "API", ",", "'requestSurveyData'", ")", "}", ";", "this", ".", "Surveys", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getSurveys'", ")", ",", "add", ":", "bindAPI", "(", "this", ",", "API", ",", "'addSurveys'", ")", ",", "update", ":", "bindAPI", "(", "this", ",", "API", ",", "'updateSurveys'", ")", ",", "remove", ":", "bindAPI", "(", "this", ",", "API", ",", "'removeSurveys'", ")", "}", ";", "this", ".", "SurveyPublish", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getSurveyPublish'", ")", ",", "update", ":", "bindAPI", "(", "this", ",", "API", ",", "'updateSurveyPublish'", ")", "}", ";", "this", ".", "BackgroundTasks", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getBackgroundTasks'", ")", "}", ";", "this", ".", "InterviewQuality", "=", "{", "get", ":", "bindAPI", "(", "this", ",", "API", ",", "'getInterviewQuality'", ")", ",", "update", ":", "bindAPI", "(", "this", ",", "API", ",", "'updateInterviewQuality'", ")", "}", ";", "}" ]
Creates an instance of object, connected to Nfield API @constructor
[ "Creates", "an", "instance", "of", "object", "connected", "to", "Nfield", "API" ]
fcd635255fad2fc483d0e9045ecf7faba04378d9
https://github.com/gribnoysup/nfield-api/blob/fcd635255fad2fc483d0e9045ecf7faba04378d9/index.js#L18-L82
47,205
gribnoysup/nfield-api
index.js
NfieldClient
function NfieldClient (defOptions) { var defaultRequestCliOptions = { baseUrl : 'https://api.nfieldmr.com/' }; extend(true, defaultRequestCliOptions, defOptions); /** * Sign In api method provided strait with NfieldCliend instance because it doesn't need authentication */ this.SignIn = API.signIn.bind(null, defaultRequestCliOptions); /** * Returns a new instance of NfieldClient with new request parameters */ this.defaults = function defaults (options) { if (typeof options !== 'object') throw new TypeError('`options` must be an object with request parameters'); return new NfieldClient(options); }; /** * Connects NfieldClient to API * Returns ConnectedInstance */ this.connect = function connect (credentials, callback) { var token = {}; var promise; if (typeof credentials === 'function') callback = credentials; promise = API.signIn(defaultRequestCliOptions, credentials).then(function (data) { if (data[0].statusCode !== 200) { throw new Error(`${data[0].statusCode}: ${data[0].body.Message}`); } else { token = { AuthenticationToken : data[0].body.AuthenticationToken, Timestamp : Date.now() }; return new ConnectedInstance(defaultRequestCliOptions, token, credentials); } }).nodeify(callback); return promise; }; }
javascript
function NfieldClient (defOptions) { var defaultRequestCliOptions = { baseUrl : 'https://api.nfieldmr.com/' }; extend(true, defaultRequestCliOptions, defOptions); /** * Sign In api method provided strait with NfieldCliend instance because it doesn't need authentication */ this.SignIn = API.signIn.bind(null, defaultRequestCliOptions); /** * Returns a new instance of NfieldClient with new request parameters */ this.defaults = function defaults (options) { if (typeof options !== 'object') throw new TypeError('`options` must be an object with request parameters'); return new NfieldClient(options); }; /** * Connects NfieldClient to API * Returns ConnectedInstance */ this.connect = function connect (credentials, callback) { var token = {}; var promise; if (typeof credentials === 'function') callback = credentials; promise = API.signIn(defaultRequestCliOptions, credentials).then(function (data) { if (data[0].statusCode !== 200) { throw new Error(`${data[0].statusCode}: ${data[0].body.Message}`); } else { token = { AuthenticationToken : data[0].body.AuthenticationToken, Timestamp : Date.now() }; return new ConnectedInstance(defaultRequestCliOptions, token, credentials); } }).nodeify(callback); return promise; }; }
[ "function", "NfieldClient", "(", "defOptions", ")", "{", "var", "defaultRequestCliOptions", "=", "{", "baseUrl", ":", "'https://api.nfieldmr.com/'", "}", ";", "extend", "(", "true", ",", "defaultRequestCliOptions", ",", "defOptions", ")", ";", "/**\n * Sign In api method provided strait with NfieldCliend instance because it doesn't need authentication\n */", "this", ".", "SignIn", "=", "API", ".", "signIn", ".", "bind", "(", "null", ",", "defaultRequestCliOptions", ")", ";", "/**\n * Returns a new instance of NfieldClient with new request parameters\n */", "this", ".", "defaults", "=", "function", "defaults", "(", "options", ")", "{", "if", "(", "typeof", "options", "!==", "'object'", ")", "throw", "new", "TypeError", "(", "'`options` must be an object with request parameters'", ")", ";", "return", "new", "NfieldClient", "(", "options", ")", ";", "}", ";", "/**\n * Connects NfieldClient to API\n * Returns ConnectedInstance\n */", "this", ".", "connect", "=", "function", "connect", "(", "credentials", ",", "callback", ")", "{", "var", "token", "=", "{", "}", ";", "var", "promise", ";", "if", "(", "typeof", "credentials", "===", "'function'", ")", "callback", "=", "credentials", ";", "promise", "=", "API", ".", "signIn", "(", "defaultRequestCliOptions", ",", "credentials", ")", ".", "then", "(", "function", "(", "data", ")", "{", "if", "(", "data", "[", "0", "]", ".", "statusCode", "!==", "200", ")", "{", "throw", "new", "Error", "(", "`", "${", "data", "[", "0", "]", ".", "statusCode", "}", "${", "data", "[", "0", "]", ".", "body", ".", "Message", "}", "`", ")", ";", "}", "else", "{", "token", "=", "{", "AuthenticationToken", ":", "data", "[", "0", "]", ".", "body", ".", "AuthenticationToken", ",", "Timestamp", ":", "Date", ".", "now", "(", ")", "}", ";", "return", "new", "ConnectedInstance", "(", "defaultRequestCliOptions", ",", "token", ",", "credentials", ")", ";", "}", "}", ")", ".", "nodeify", "(", "callback", ")", ";", "return", "promise", ";", "}", ";", "}" ]
Creates NfieldClient object @constructor
[ "Creates", "NfieldClient", "object" ]
fcd635255fad2fc483d0e9045ecf7faba04378d9
https://github.com/gribnoysup/nfield-api/blob/fcd635255fad2fc483d0e9045ecf7faba04378d9/index.js#L88-L135
47,206
alexyoung/pop
lib/server.js
server
function server() { // TODO: Show require express error var express = require('express') , app = express(); app.configure(function() { app.use(express.static(siteBuilder.outputRoot)); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); // Map missing trailing slashes for posts app.get('*', function(req, res) { var postPath = siteBuilder.outputRoot + req.url + '/'; // TODO: Security if (req.url.match(/[^/]$/) && existsSync(postPath)) { res.redirect(req.url + '/'); } else { res.send('404'); } }); app.listen(siteBuilder.config.port); log.info('Listening on port', siteBuilder.config.port); }
javascript
function server() { // TODO: Show require express error var express = require('express') , app = express(); app.configure(function() { app.use(express.static(siteBuilder.outputRoot)); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); // Map missing trailing slashes for posts app.get('*', function(req, res) { var postPath = siteBuilder.outputRoot + req.url + '/'; // TODO: Security if (req.url.match(/[^/]$/) && existsSync(postPath)) { res.redirect(req.url + '/'); } else { res.send('404'); } }); app.listen(siteBuilder.config.port); log.info('Listening on port', siteBuilder.config.port); }
[ "function", "server", "(", ")", "{", "// TODO: Show require express error", "var", "express", "=", "require", "(", "'express'", ")", ",", "app", "=", "express", "(", ")", ";", "app", ".", "configure", "(", "function", "(", ")", "{", "app", ".", "use", "(", "express", ".", "static", "(", "siteBuilder", ".", "outputRoot", ")", ")", ";", "app", ".", "use", "(", "express", ".", "errorHandler", "(", "{", "dumpExceptions", ":", "true", ",", "showStack", ":", "true", "}", ")", ")", ";", "}", ")", ";", "// Map missing trailing slashes for posts", "app", ".", "get", "(", "'*'", ",", "function", "(", "req", ",", "res", ")", "{", "var", "postPath", "=", "siteBuilder", ".", "outputRoot", "+", "req", ".", "url", "+", "'/'", ";", "// TODO: Security", "if", "(", "req", ".", "url", ".", "match", "(", "/", "[^/]$", "/", ")", "&&", "existsSync", "(", "postPath", ")", ")", "{", "res", ".", "redirect", "(", "req", ".", "url", "+", "'/'", ")", ";", "}", "else", "{", "res", ".", "send", "(", "'404'", ")", ";", "}", "}", ")", ";", "app", ".", "listen", "(", "siteBuilder", ".", "config", ".", "port", ")", ";", "log", ".", "info", "(", "'Listening on port'", ",", "siteBuilder", ".", "config", ".", "port", ")", ";", "}" ]
Instantiates and runs the Express server.
[ "Instantiates", "and", "runs", "the", "Express", "server", "." ]
8a0b3f2605cb58e8ae6b34f1373dde00610e9858
https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/server.js#L18-L41
47,207
edus44/express-deliver
lib/response/error.js
normalizeError
function normalizeError(err,pools){ if (!(err instanceof Error)){ err = new Error(err) } if (!err._isException){ //Iterate over exceptionPools finding error match for(let i=0;i<pools.length;i++){ let exception = pools[i]._convert(err) if (exception) return exception } } return err }
javascript
function normalizeError(err,pools){ if (!(err instanceof Error)){ err = new Error(err) } if (!err._isException){ //Iterate over exceptionPools finding error match for(let i=0;i<pools.length;i++){ let exception = pools[i]._convert(err) if (exception) return exception } } return err }
[ "function", "normalizeError", "(", "err", ",", "pools", ")", "{", "if", "(", "!", "(", "err", "instanceof", "Error", ")", ")", "{", "err", "=", "new", "Error", "(", "err", ")", "}", "if", "(", "!", "err", ".", "_isException", ")", "{", "//Iterate over exceptionPools finding error match", "for", "(", "let", "i", "=", "0", ";", "i", "<", "pools", ".", "length", ";", "i", "++", ")", "{", "let", "exception", "=", "pools", "[", "i", "]", ".", "_convert", "(", "err", ")", "if", "(", "exception", ")", "return", "exception", "}", "}", "return", "err", "}" ]
Tries to always return an expressDeliver exception @param {any} err @param {Array<ExceptionPool>} pools @return {Exception}
[ "Tries", "to", "always", "return", "an", "expressDeliver", "exception" ]
895abfaf2e5e48a00b4fef943dccaffcbf244780
https://github.com/edus44/express-deliver/blob/895abfaf2e5e48a00b4fef943dccaffcbf244780/lib/response/error.js#L31-L44
47,208
edus44/express-deliver
lib/response/error.js
defaultTransformError
function defaultTransformError(err,req){ let body = { code: err.code, message: err.message, data: err.data, } if (req._expressDeliverOptions.printErrorStack===true){ body.stack = err.stack } if (err.name == 'InternalError' && req._expressDeliverOptions.printInternalErrorData!==true){ delete body.data } return { status:false, error:body } }
javascript
function defaultTransformError(err,req){ let body = { code: err.code, message: err.message, data: err.data, } if (req._expressDeliverOptions.printErrorStack===true){ body.stack = err.stack } if (err.name == 'InternalError' && req._expressDeliverOptions.printInternalErrorData!==true){ delete body.data } return { status:false, error:body } }
[ "function", "defaultTransformError", "(", "err", ",", "req", ")", "{", "let", "body", "=", "{", "code", ":", "err", ".", "code", ",", "message", ":", "err", ".", "message", ",", "data", ":", "err", ".", "data", ",", "}", "if", "(", "req", ".", "_expressDeliverOptions", ".", "printErrorStack", "===", "true", ")", "{", "body", ".", "stack", "=", "err", ".", "stack", "}", "if", "(", "err", ".", "name", "==", "'InternalError'", "&&", "req", ".", "_expressDeliverOptions", ".", "printInternalErrorData", "!==", "true", ")", "{", "delete", "body", ".", "data", "}", "return", "{", "status", ":", "false", ",", "error", ":", "body", "}", "}" ]
Default error response transformation @param {Exception} err @param {Request} req @return {Object}
[ "Default", "error", "response", "transformation" ]
895abfaf2e5e48a00b4fef943dccaffcbf244780
https://github.com/edus44/express-deliver/blob/895abfaf2e5e48a00b4fef943dccaffcbf244780/lib/response/error.js#L68-L87
47,209
pumpumba/Influsion-back-end
machinepack-youtubenodemachines/youtubeAPICalls.js
getChannel
function getChannel(auth, youtube, channelID, callback) { youtube.channels.list( // Call the Youtube API { auth: auth, part: "snippet, statistics", order: "date", id: channelID, maxResults: 1 // Integer 0-50, default 5 }, function(err, res) { if (err) { console.log("The API returned an error: " + err); } else { if (res.data.items[0] !== undefined) { // Check if a result was found var formatedChannel = formatChannelJson(res.data.items[0]) // Format the recieved JSON object callback(formatedChannel); } else { callback([]); } } } ); }
javascript
function getChannel(auth, youtube, channelID, callback) { youtube.channels.list( // Call the Youtube API { auth: auth, part: "snippet, statistics", order: "date", id: channelID, maxResults: 1 // Integer 0-50, default 5 }, function(err, res) { if (err) { console.log("The API returned an error: " + err); } else { if (res.data.items[0] !== undefined) { // Check if a result was found var formatedChannel = formatChannelJson(res.data.items[0]) // Format the recieved JSON object callback(formatedChannel); } else { callback([]); } } } ); }
[ "function", "getChannel", "(", "auth", ",", "youtube", ",", "channelID", ",", "callback", ")", "{", "youtube", ".", "channels", ".", "list", "(", "// Call the Youtube API", "{", "auth", ":", "auth", ",", "part", ":", "\"snippet, statistics\"", ",", "order", ":", "\"date\"", ",", "id", ":", "channelID", ",", "maxResults", ":", "1", "// Integer 0-50, default 5", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "\"The API returned an error: \"", "+", "err", ")", ";", "}", "else", "{", "if", "(", "res", ".", "data", ".", "items", "[", "0", "]", "!==", "undefined", ")", "{", "// Check if a result was found", "var", "formatedChannel", "=", "formatChannelJson", "(", "res", ".", "data", ".", "items", "[", "0", "]", ")", "// Format the recieved JSON object", "callback", "(", "formatedChannel", ")", ";", "}", "else", "{", "callback", "(", "[", "]", ")", ";", "}", "}", "}", ")", ";", "}" ]
Get a Youtube channel via channel ID
[ "Get", "a", "Youtube", "channel", "via", "channel", "ID" ]
68ba7a42e415f08eb16551b564ee384011e1918e
https://github.com/pumpumba/Influsion-back-end/blob/68ba7a42e415f08eb16551b564ee384011e1918e/machinepack-youtubenodemachines/youtubeAPICalls.js#L31-L53
47,210
pumpumba/Influsion-back-end
machinepack-youtubenodemachines/youtubeAPICalls.js
getChannelUsername
function getChannelUsername(auth, youtube, username, callback) { youtube.channels.list( // Call the Youtube API { auth: auth, part: "snippet, statistics", order: "date", forUsername: username, maxResults: 1 // Integer 0-50, default 5 }, function(err, res) { if (err) { console.log("The API returned an error: " + err); } else { if (res.data.items[0] !== undefined) { // Check if a result was found var formatedChannel = formatChannelJson(res.data.items[0]) // Format the recieved JSON object callback(formatedChannel); } else { callback([]); } } } ); }
javascript
function getChannelUsername(auth, youtube, username, callback) { youtube.channels.list( // Call the Youtube API { auth: auth, part: "snippet, statistics", order: "date", forUsername: username, maxResults: 1 // Integer 0-50, default 5 }, function(err, res) { if (err) { console.log("The API returned an error: " + err); } else { if (res.data.items[0] !== undefined) { // Check if a result was found var formatedChannel = formatChannelJson(res.data.items[0]) // Format the recieved JSON object callback(formatedChannel); } else { callback([]); } } } ); }
[ "function", "getChannelUsername", "(", "auth", ",", "youtube", ",", "username", ",", "callback", ")", "{", "youtube", ".", "channels", ".", "list", "(", "// Call the Youtube API", "{", "auth", ":", "auth", ",", "part", ":", "\"snippet, statistics\"", ",", "order", ":", "\"date\"", ",", "forUsername", ":", "username", ",", "maxResults", ":", "1", "// Integer 0-50, default 5", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "\"The API returned an error: \"", "+", "err", ")", ";", "}", "else", "{", "if", "(", "res", ".", "data", ".", "items", "[", "0", "]", "!==", "undefined", ")", "{", "// Check if a result was found", "var", "formatedChannel", "=", "formatChannelJson", "(", "res", ".", "data", ".", "items", "[", "0", "]", ")", "// Format the recieved JSON object", "callback", "(", "formatedChannel", ")", ";", "}", "else", "{", "callback", "(", "[", "]", ")", ";", "}", "}", "}", ")", ";", "}" ]
Get a Youtube channel via channel name
[ "Get", "a", "Youtube", "channel", "via", "channel", "name" ]
68ba7a42e415f08eb16551b564ee384011e1918e
https://github.com/pumpumba/Influsion-back-end/blob/68ba7a42e415f08eb16551b564ee384011e1918e/machinepack-youtubenodemachines/youtubeAPICalls.js#L56-L78
47,211
pumpumba/Influsion-back-end
machinepack-youtubenodemachines/youtubeAPICalls.js
getVideos
function getVideos(auth, youtube, channel_id, count, callback) { youtube.search.list( // Call the Youtube API { auth: auth, part: "snippet", order: "date", maxResults : count, //integer 0-50, default 5 channelId: channel_id }, function(err, res) { if (err) { console.log("The API returned an error: " + err); } else { if (res.data.items !== undefined) { // Check if a result was found getVideoStatistics(auth, youtube, res.data.items, count, callback); // Get video statistics } else { callback([]); } } }); }
javascript
function getVideos(auth, youtube, channel_id, count, callback) { youtube.search.list( // Call the Youtube API { auth: auth, part: "snippet", order: "date", maxResults : count, //integer 0-50, default 5 channelId: channel_id }, function(err, res) { if (err) { console.log("The API returned an error: " + err); } else { if (res.data.items !== undefined) { // Check if a result was found getVideoStatistics(auth, youtube, res.data.items, count, callback); // Get video statistics } else { callback([]); } } }); }
[ "function", "getVideos", "(", "auth", ",", "youtube", ",", "channel_id", ",", "count", ",", "callback", ")", "{", "youtube", ".", "search", ".", "list", "(", "// Call the Youtube API", "{", "auth", ":", "auth", ",", "part", ":", "\"snippet\"", ",", "order", ":", "\"date\"", ",", "maxResults", ":", "count", ",", "//integer 0-50, default 5", "channelId", ":", "channel_id", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "\"The API returned an error: \"", "+", "err", ")", ";", "}", "else", "{", "if", "(", "res", ".", "data", ".", "items", "!==", "undefined", ")", "{", "// Check if a result was found", "getVideoStatistics", "(", "auth", ",", "youtube", ",", "res", ".", "data", ".", "items", ",", "count", ",", "callback", ")", ";", "// Get video statistics", "}", "else", "{", "callback", "(", "[", "]", ")", ";", "}", "}", "}", ")", ";", "}" ]
Get Youtube videos via channel ID
[ "Get", "Youtube", "videos", "via", "channel", "ID" ]
68ba7a42e415f08eb16551b564ee384011e1918e
https://github.com/pumpumba/Influsion-back-end/blob/68ba7a42e415f08eb16551b564ee384011e1918e/machinepack-youtubenodemachines/youtubeAPICalls.js#L106-L126
47,212
pumpumba/Influsion-back-end
machinepack-youtubenodemachines/youtubeAPICalls.js
getVideoStatistics
function getVideoStatistics(auth, youtube, items, count, callback) { // Convert the video ID:s of the provided videos to the appropriate format var IDs = ""; if (Array.isArray(items)) { for (var i = 0; i < items.length; i++) { if (i != 0) { IDs += ", " } IDs += items[i].id.videoId; } } youtube.videos.list( // Call the Youtube API { auth: auth, part: "statistics", id: IDs, maxResults: count //integer 0-50, default 5 }, function(err, res) { if (err) { console.log("The API returned an error: " + err); } else { var formatedVideos = formatVideosJson(items, res.data.items); // Format the recieved JSON object filled with videos callback(formatedVideos); } }); }
javascript
function getVideoStatistics(auth, youtube, items, count, callback) { // Convert the video ID:s of the provided videos to the appropriate format var IDs = ""; if (Array.isArray(items)) { for (var i = 0; i < items.length; i++) { if (i != 0) { IDs += ", " } IDs += items[i].id.videoId; } } youtube.videos.list( // Call the Youtube API { auth: auth, part: "statistics", id: IDs, maxResults: count //integer 0-50, default 5 }, function(err, res) { if (err) { console.log("The API returned an error: " + err); } else { var formatedVideos = formatVideosJson(items, res.data.items); // Format the recieved JSON object filled with videos callback(formatedVideos); } }); }
[ "function", "getVideoStatistics", "(", "auth", ",", "youtube", ",", "items", ",", "count", ",", "callback", ")", "{", "// Convert the video ID:s of the provided videos to the appropriate format", "var", "IDs", "=", "\"\"", ";", "if", "(", "Array", ".", "isArray", "(", "items", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "!=", "0", ")", "{", "IDs", "+=", "\", \"", "}", "IDs", "+=", "items", "[", "i", "]", ".", "id", ".", "videoId", ";", "}", "}", "youtube", ".", "videos", ".", "list", "(", "// Call the Youtube API", "{", "auth", ":", "auth", ",", "part", ":", "\"statistics\"", ",", "id", ":", "IDs", ",", "maxResults", ":", "count", "//integer 0-50, default 5", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "\"The API returned an error: \"", "+", "err", ")", ";", "}", "else", "{", "var", "formatedVideos", "=", "formatVideosJson", "(", "items", ",", "res", ".", "data", ".", "items", ")", ";", "// Format the recieved JSON object filled with videos", "callback", "(", "formatedVideos", ")", ";", "}", "}", ")", ";", "}" ]
Get video statistics
[ "Get", "video", "statistics" ]
68ba7a42e415f08eb16551b564ee384011e1918e
https://github.com/pumpumba/Influsion-back-end/blob/68ba7a42e415f08eb16551b564ee384011e1918e/machinepack-youtubenodemachines/youtubeAPICalls.js#L129-L157
47,213
pumpumba/Influsion-back-end
machinepack-youtubenodemachines/youtubeAPICalls.js
formatVideosJson
function formatVideosJson(videos, statistics) { var formatedVideos = [] if (Array.isArray(videos)) { for (var i = 0; i < videos.length; i++) { var video = { "platform": "Youtube", "channel_id": videos[i].snippet.channelId, "channel_url": "", "channel_title": videos[i].snippet.channelTitle, "video_id": videos[i].id.videoId, "video_url": "", "video_embeded_url": "", "video_title": videos[i].snippet.title, "video_description": videos[i].snippet.description, "video_created_at": (new Date(videos[i].snippet.publishedAt).toISOString()), "video_thumbnail_url": videos[i].snippet.thumbnails.high.url, "video_view_count": "", "video_like_count": "", "video_dislike_count": "", "video_comment_count": "" }; video.channel_url = "https://www.youtube.com/channel/" + video.channel_id; video.video_url = "https://www.youtube.com/watch?v=" + video.video_id; video.video_embeded_url = "https://www.youtube.com/embed/" + video.video_id; formatedVideos.push(video); } } // Add statistics if (Array.isArray(statistics)) { for (var i = 0; i < statistics.length; i++) { formatedVideos[i].video_view_count = statistics[i].statistics.viewCount; formatedVideos[i].video_like_count = statistics[i].statistics.likeCount; formatedVideos[i].video_dislike_count = statistics[i].statistics.dislikeCount; formatedVideos[i].video_comment_count = statistics[i].statistics.commentCount; } } return formatedVideos; }
javascript
function formatVideosJson(videos, statistics) { var formatedVideos = [] if (Array.isArray(videos)) { for (var i = 0; i < videos.length; i++) { var video = { "platform": "Youtube", "channel_id": videos[i].snippet.channelId, "channel_url": "", "channel_title": videos[i].snippet.channelTitle, "video_id": videos[i].id.videoId, "video_url": "", "video_embeded_url": "", "video_title": videos[i].snippet.title, "video_description": videos[i].snippet.description, "video_created_at": (new Date(videos[i].snippet.publishedAt).toISOString()), "video_thumbnail_url": videos[i].snippet.thumbnails.high.url, "video_view_count": "", "video_like_count": "", "video_dislike_count": "", "video_comment_count": "" }; video.channel_url = "https://www.youtube.com/channel/" + video.channel_id; video.video_url = "https://www.youtube.com/watch?v=" + video.video_id; video.video_embeded_url = "https://www.youtube.com/embed/" + video.video_id; formatedVideos.push(video); } } // Add statistics if (Array.isArray(statistics)) { for (var i = 0; i < statistics.length; i++) { formatedVideos[i].video_view_count = statistics[i].statistics.viewCount; formatedVideos[i].video_like_count = statistics[i].statistics.likeCount; formatedVideos[i].video_dislike_count = statistics[i].statistics.dislikeCount; formatedVideos[i].video_comment_count = statistics[i].statistics.commentCount; } } return formatedVideos; }
[ "function", "formatVideosJson", "(", "videos", ",", "statistics", ")", "{", "var", "formatedVideos", "=", "[", "]", "if", "(", "Array", ".", "isArray", "(", "videos", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "videos", ".", "length", ";", "i", "++", ")", "{", "var", "video", "=", "{", "\"platform\"", ":", "\"Youtube\"", ",", "\"channel_id\"", ":", "videos", "[", "i", "]", ".", "snippet", ".", "channelId", ",", "\"channel_url\"", ":", "\"\"", ",", "\"channel_title\"", ":", "videos", "[", "i", "]", ".", "snippet", ".", "channelTitle", ",", "\"video_id\"", ":", "videos", "[", "i", "]", ".", "id", ".", "videoId", ",", "\"video_url\"", ":", "\"\"", ",", "\"video_embeded_url\"", ":", "\"\"", ",", "\"video_title\"", ":", "videos", "[", "i", "]", ".", "snippet", ".", "title", ",", "\"video_description\"", ":", "videos", "[", "i", "]", ".", "snippet", ".", "description", ",", "\"video_created_at\"", ":", "(", "new", "Date", "(", "videos", "[", "i", "]", ".", "snippet", ".", "publishedAt", ")", ".", "toISOString", "(", ")", ")", ",", "\"video_thumbnail_url\"", ":", "videos", "[", "i", "]", ".", "snippet", ".", "thumbnails", ".", "high", ".", "url", ",", "\"video_view_count\"", ":", "\"\"", ",", "\"video_like_count\"", ":", "\"\"", ",", "\"video_dislike_count\"", ":", "\"\"", ",", "\"video_comment_count\"", ":", "\"\"", "}", ";", "video", ".", "channel_url", "=", "\"https://www.youtube.com/channel/\"", "+", "video", ".", "channel_id", ";", "video", ".", "video_url", "=", "\"https://www.youtube.com/watch?v=\"", "+", "video", ".", "video_id", ";", "video", ".", "video_embeded_url", "=", "\"https://www.youtube.com/embed/\"", "+", "video", ".", "video_id", ";", "formatedVideos", ".", "push", "(", "video", ")", ";", "}", "}", "// Add statistics", "if", "(", "Array", ".", "isArray", "(", "statistics", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "statistics", ".", "length", ";", "i", "++", ")", "{", "formatedVideos", "[", "i", "]", ".", "video_view_count", "=", "statistics", "[", "i", "]", ".", "statistics", ".", "viewCount", ";", "formatedVideos", "[", "i", "]", ".", "video_like_count", "=", "statistics", "[", "i", "]", ".", "statistics", ".", "likeCount", ";", "formatedVideos", "[", "i", "]", ".", "video_dislike_count", "=", "statistics", "[", "i", "]", ".", "statistics", ".", "dislikeCount", ";", "formatedVideos", "[", "i", "]", ".", "video_comment_count", "=", "statistics", "[", "i", "]", ".", "statistics", ".", "commentCount", ";", "}", "}", "return", "formatedVideos", ";", "}" ]
Format the JSON object containing the video data
[ "Format", "the", "JSON", "object", "containing", "the", "video", "data" ]
68ba7a42e415f08eb16551b564ee384011e1918e
https://github.com/pumpumba/Influsion-back-end/blob/68ba7a42e415f08eb16551b564ee384011e1918e/machinepack-youtubenodemachines/youtubeAPICalls.js#L190-L231
47,214
nicjansma/breakup.js
lib/breakup.js
function() { // run iterator for this item iterator(arr[current], function(err) { // check for any errors with this element if (err) { callback(err, yielded); } else { // move onto the next element current++; if (current === arr.length) { // all done callback(null, yielded); } else { var now = +(new Date()); // check if we need to take a break at all if (now > endTime) { // reset start and end time startTime = now; endTime = startTime + workTime; yielded = true; // prioritize setImmediate if (immediate) { immediate(function() { iterate(); }); } else { // if we're not doing an immediate yield, also add yield time endTime += yieldTime; setTimeout(function() { iterate(); }, yieldTime); } } else { // work on the next item immediately iterate(); } } } }); }
javascript
function() { // run iterator for this item iterator(arr[current], function(err) { // check for any errors with this element if (err) { callback(err, yielded); } else { // move onto the next element current++; if (current === arr.length) { // all done callback(null, yielded); } else { var now = +(new Date()); // check if we need to take a break at all if (now > endTime) { // reset start and end time startTime = now; endTime = startTime + workTime; yielded = true; // prioritize setImmediate if (immediate) { immediate(function() { iterate(); }); } else { // if we're not doing an immediate yield, also add yield time endTime += yieldTime; setTimeout(function() { iterate(); }, yieldTime); } } else { // work on the next item immediately iterate(); } } } }); }
[ "function", "(", ")", "{", "// run iterator for this item", "iterator", "(", "arr", "[", "current", "]", ",", "function", "(", "err", ")", "{", "// check for any errors with this element", "if", "(", "err", ")", "{", "callback", "(", "err", ",", "yielded", ")", ";", "}", "else", "{", "// move onto the next element", "current", "++", ";", "if", "(", "current", "===", "arr", ".", "length", ")", "{", "// all done", "callback", "(", "null", ",", "yielded", ")", ";", "}", "else", "{", "var", "now", "=", "+", "(", "new", "Date", "(", ")", ")", ";", "// check if we need to take a break at all", "if", "(", "now", ">", "endTime", ")", "{", "// reset start and end time", "startTime", "=", "now", ";", "endTime", "=", "startTime", "+", "workTime", ";", "yielded", "=", "true", ";", "// prioritize setImmediate", "if", "(", "immediate", ")", "{", "immediate", "(", "function", "(", ")", "{", "iterate", "(", ")", ";", "}", ")", ";", "}", "else", "{", "// if we're not doing an immediate yield, also add yield time", "endTime", "+=", "yieldTime", ";", "setTimeout", "(", "function", "(", ")", "{", "iterate", "(", ")", ";", "}", ",", "yieldTime", ")", ";", "}", "}", "else", "{", "// work on the next item immediately", "iterate", "(", ")", ";", "}", "}", "}", "}", ")", ";", "}" ]
Iteration loop function. Called once for each element
[ "Iteration", "loop", "function", ".", "Called", "once", "for", "each", "element" ]
d87a35514301ca150109979b814b9a5fc205079c
https://github.com/nicjansma/breakup.js/blob/d87a35514301ca150109979b814b9a5fc205079c/lib/breakup.js#L117-L161
47,215
reworkcss/rework-plugin-at2x
index.js
combineMediaQuery
function combineMediaQuery(base, additional) { var finalQuery = []; base.forEach(function(b) { additional.forEach(function(a) { finalQuery.push(b + ' and ' + a); }); }); return finalQuery.join(', '); }
javascript
function combineMediaQuery(base, additional) { var finalQuery = []; base.forEach(function(b) { additional.forEach(function(a) { finalQuery.push(b + ' and ' + a); }); }); return finalQuery.join(', '); }
[ "function", "combineMediaQuery", "(", "base", ",", "additional", ")", "{", "var", "finalQuery", "=", "[", "]", ";", "base", ".", "forEach", "(", "function", "(", "b", ")", "{", "additional", ".", "forEach", "(", "function", "(", "a", ")", "{", "finalQuery", ".", "push", "(", "b", "+", "' and '", "+", "a", ")", ";", "}", ")", ";", "}", ")", ";", "return", "finalQuery", ".", "join", "(", "', '", ")", ";", "}" ]
Combines existing media query with 2x media query.
[ "Combines", "existing", "media", "query", "with", "2x", "media", "query", "." ]
404b240e69f7ee3814f100e877732d7281c178d7
https://github.com/reworkcss/rework-plugin-at2x/blob/404b240e69f7ee3814f100e877732d7281c178d7/index.js#L109-L117
47,216
BlackWaspTech/wasp-graphql
src/query.js
query
function query(url, init) { // Reject if user provided no arguments if (!url || typeof url !== 'string') { return Promise.reject( "Expected a non-empty string for 'url' but received: " + typeof url ); } // Reject if user provided an invalid second argument if (!init) { return Promise.reject( "Expected an object or a non-empty string for 'init' but received: " + typeof init ); } // The user can just pass in a query string directly; however, if they // pass in an object instead, we need to validate the properties. if (typeof init !== 'string') { // Reject if there's no valid fields or body parameter if ( typeof init !== 'object' || init.constructor === Array || ((!init.fields || typeof init.fields !== 'string') && (!init.body || typeof init.body !== 'string')) ) { return Promise.reject( "Expected a string for 'init.fields' or 'init.body' but received: " + typeof init ); } } try { var fetchOptions = configureFetch(init); } catch (err) { return Promise.reject(err); } // Reject if something went wrong with building the request if (!fetchOptions) { return Promise.reject( setTypeError( 'Something went wrong when setting the fetch options: ' + JSON.stringify(fetchOptions) ) ); } return fetch(url, fetchOptions); }
javascript
function query(url, init) { // Reject if user provided no arguments if (!url || typeof url !== 'string') { return Promise.reject( "Expected a non-empty string for 'url' but received: " + typeof url ); } // Reject if user provided an invalid second argument if (!init) { return Promise.reject( "Expected an object or a non-empty string for 'init' but received: " + typeof init ); } // The user can just pass in a query string directly; however, if they // pass in an object instead, we need to validate the properties. if (typeof init !== 'string') { // Reject if there's no valid fields or body parameter if ( typeof init !== 'object' || init.constructor === Array || ((!init.fields || typeof init.fields !== 'string') && (!init.body || typeof init.body !== 'string')) ) { return Promise.reject( "Expected a string for 'init.fields' or 'init.body' but received: " + typeof init ); } } try { var fetchOptions = configureFetch(init); } catch (err) { return Promise.reject(err); } // Reject if something went wrong with building the request if (!fetchOptions) { return Promise.reject( setTypeError( 'Something went wrong when setting the fetch options: ' + JSON.stringify(fetchOptions) ) ); } return fetch(url, fetchOptions); }
[ "function", "query", "(", "url", ",", "init", ")", "{", "// Reject if user provided no arguments\r", "if", "(", "!", "url", "||", "typeof", "url", "!==", "'string'", ")", "{", "return", "Promise", ".", "reject", "(", "\"Expected a non-empty string for 'url' but received: \"", "+", "typeof", "url", ")", ";", "}", "// Reject if user provided an invalid second argument\r", "if", "(", "!", "init", ")", "{", "return", "Promise", ".", "reject", "(", "\"Expected an object or a non-empty string for 'init' but received: \"", "+", "typeof", "init", ")", ";", "}", "// The user can just pass in a query string directly; however, if they\r", "// pass in an object instead, we need to validate the properties.\r", "if", "(", "typeof", "init", "!==", "'string'", ")", "{", "// Reject if there's no valid fields or body parameter\r", "if", "(", "typeof", "init", "!==", "'object'", "||", "init", ".", "constructor", "===", "Array", "||", "(", "(", "!", "init", ".", "fields", "||", "typeof", "init", ".", "fields", "!==", "'string'", ")", "&&", "(", "!", "init", ".", "body", "||", "typeof", "init", ".", "body", "!==", "'string'", ")", ")", ")", "{", "return", "Promise", ".", "reject", "(", "\"Expected a string for 'init.fields' or 'init.body' but received: \"", "+", "typeof", "init", ")", ";", "}", "}", "try", "{", "var", "fetchOptions", "=", "configureFetch", "(", "init", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "// Reject if something went wrong with building the request\r", "if", "(", "!", "fetchOptions", ")", "{", "return", "Promise", ".", "reject", "(", "setTypeError", "(", "'Something went wrong when setting the fetch options: '", "+", "JSON", ".", "stringify", "(", "fetchOptions", ")", ")", ")", ";", "}", "return", "fetch", "(", "url", ",", "fetchOptions", ")", ";", "}" ]
Provides a thin, GQL-compliant wrapper over the Fetch API. Syntax: query(url, init) @param {string} url - The url for the intended resource @param {(string|Object)} init - Can be a string of fields or a configuration object @param {string} [init.fields] - GQL fields: Will be added to the body of the request @param {Object} [init.variables] - GQL variables: Will be added to the body of the request // For additional valid arguments, see the Fetch API: // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch Default init properties @param {string} [init.method='POST'] @param {Object} [init.headers={ 'Content-Type': 'application/json', 'Accept': 'application/json' }] @returns {Promise}
[ "Provides", "a", "thin", "GQL", "-", "compliant", "wrapper", "over", "the", "Fetch", "API", "." ]
5857b82b6eda9bb5dea5f0a881cd910b1bb3944a
https://github.com/BlackWaspTech/wasp-graphql/blob/5857b82b6eda9bb5dea5f0a881cd910b1bb3944a/src/query.js#L24-L74
47,217
quorrajs/Positron
lib/http/request.js
function (key, defaultValue) { var body = self.body || {}; var query = self.query || {}; if (null != body[key]) return body[key]; if (null != query[key]) return query[key]; return defaultValue; }
javascript
function (key, defaultValue) { var body = self.body || {}; var query = self.query || {}; if (null != body[key]) return body[key]; if (null != query[key]) return query[key]; return defaultValue; }
[ "function", "(", "key", ",", "defaultValue", ")", "{", "var", "body", "=", "self", ".", "body", "||", "{", "}", ";", "var", "query", "=", "self", ".", "query", "||", "{", "}", ";", "if", "(", "null", "!=", "body", "[", "key", "]", ")", "return", "body", "[", "key", "]", ";", "if", "(", "null", "!=", "query", "[", "key", "]", ")", "return", "query", "[", "key", "]", ";", "return", "defaultValue", ";", "}" ]
Return the value of a request input param `name` when present or `defaultValue`. - Checks body params, ex: id=12, {"id":12} - Checks query string params, ex: ?id=12 To utilize request bodies, `req.body` should be an object. This can be done by enabling the `bodyParser` middleware. @param {String} key @param {*} defaultValue @return {String}
[ "Return", "the", "value", "of", "a", "request", "input", "param", "name", "when", "present", "or", "defaultValue", "." ]
a4bad5a5f581743d1885405c11ae26600fb957af
https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/http/request.js#L227-L233
47,218
quorrajs/Positron
lib/http/request.js
function (key) { var keys = Array.isArray(key) ? key : arguments; for (var i = 0; i < keys.length; i++) { if (isEmptyString(keys[i])) return false; } return true; }
javascript
function (key) { var keys = Array.isArray(key) ? key : arguments; for (var i = 0; i < keys.length; i++) { if (isEmptyString(keys[i])) return false; } return true; }
[ "function", "(", "key", ")", "{", "var", "keys", "=", "Array", ".", "isArray", "(", "key", ")", "?", "key", ":", "arguments", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "if", "(", "isEmptyString", "(", "keys", "[", "i", "]", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determine if the request contains a non-empty value for an input item. @param {String|Array} key @return bool
[ "Determine", "if", "the", "request", "contains", "a", "non", "-", "empty", "value", "for", "an", "input", "item", "." ]
a4bad5a5f581743d1885405c11ae26600fb957af
https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/http/request.js#L241-L249
47,219
quorrajs/Positron
lib/http/request.js
function (key) { var keys = Array.isArray(key) ? key : arguments; var input = self.input.all(); var results = {}; for (var i = 0; i < keys.length; i++) { results[keys[i]] = input[keys[i]]; } return results; }
javascript
function (key) { var keys = Array.isArray(key) ? key : arguments; var input = self.input.all(); var results = {}; for (var i = 0; i < keys.length; i++) { results[keys[i]] = input[keys[i]]; } return results; }
[ "function", "(", "key", ")", "{", "var", "keys", "=", "Array", ".", "isArray", "(", "key", ")", "?", "key", ":", "arguments", ";", "var", "input", "=", "self", ".", "input", ".", "all", "(", ")", ";", "var", "results", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "results", "[", "keys", "[", "i", "]", "]", "=", "input", "[", "keys", "[", "i", "]", "]", ";", "}", "return", "results", ";", "}" ]
Get a subset of the items from the input data. @param {Array|String} key @return {Array}
[ "Get", "a", "subset", "of", "the", "items", "from", "the", "input", "data", "." ]
a4bad5a5f581743d1885405c11ae26600fb957af
https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/http/request.js#L265-L276
47,220
quorrajs/Positron
lib/http/request.js
function (filter, keys) { if (self.session) { var flash = isset(filter) ? self.input[filter](keys) : self.input.all(); self.session.flash('_old_input', flash); } }
javascript
function (filter, keys) { if (self.session) { var flash = isset(filter) ? self.input[filter](keys) : self.input.all(); self.session.flash('_old_input', flash); } }
[ "function", "(", "filter", ",", "keys", ")", "{", "if", "(", "self", ".", "session", ")", "{", "var", "flash", "=", "isset", "(", "filter", ")", "?", "self", ".", "input", "[", "filter", "]", "(", "keys", ")", ":", "self", ".", "input", ".", "all", "(", ")", ";", "self", ".", "session", ".", "flash", "(", "'_old_input'", ",", "flash", ")", ";", "}", "}" ]
Flash the input for the current request to the session. @param {String} filter @param {Object} keys
[ "Flash", "the", "input", "for", "the", "current", "request", "to", "the", "session", "." ]
a4bad5a5f581743d1885405c11ae26600fb957af
https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/http/request.js#L283-L289
47,221
quorrajs/Positron
lib/http/request.js
function (key, defaultValue) { var input = self.session.get('_old_input', []); // Input that is flashed to the session can be easily retrieved by the // developer, making repopulating old forms and the like much more // convenient, since the request's previous input is available. if (key) { return isset(input[key]) ? input[key] : defaultValue; } else { return input; } }
javascript
function (key, defaultValue) { var input = self.session.get('_old_input', []); // Input that is flashed to the session can be easily retrieved by the // developer, making repopulating old forms and the like much more // convenient, since the request's previous input is available. if (key) { return isset(input[key]) ? input[key] : defaultValue; } else { return input; } }
[ "function", "(", "key", ",", "defaultValue", ")", "{", "var", "input", "=", "self", ".", "session", ".", "get", "(", "'_old_input'", ",", "[", "]", ")", ";", "// Input that is flashed to the session can be easily retrieved by the", "// developer, making repopulating old forms and the like much more", "// convenient, since the request's previous input is available.", "if", "(", "key", ")", "{", "return", "isset", "(", "input", "[", "key", "]", ")", "?", "input", "[", "key", "]", ":", "defaultValue", ";", "}", "else", "{", "return", "input", ";", "}", "}" ]
Retrieve an old input item. @param {String} key @param {*} defaultValue @return {*}
[ "Retrieve", "an", "old", "input", "item", "." ]
a4bad5a5f581743d1885405c11ae26600fb957af
https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/http/request.js#L338-L349
47,222
quorrajs/Positron
lib/http/request.js
function (key) { if (self.files) { return self.files[key] ? self.files[key] : null; } }
javascript
function (key) { if (self.files) { return self.files[key] ? self.files[key] : null; } }
[ "function", "(", "key", ")", "{", "if", "(", "self", ".", "files", ")", "{", "return", "self", ".", "files", "[", "key", "]", "?", "self", ".", "files", "[", "key", "]", ":", "null", ";", "}", "}" ]
Retrieve a file from the request. @param {String} key @return {*}
[ "Retrieve", "a", "file", "from", "the", "request", "." ]
a4bad5a5f581743d1885405c11ae26600fb957af
https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/http/request.js#L356-L360
47,223
edloidas/roll-parser
src/object/Result.js
Result
function Result( notation, value, rolls ) { this.notation = notation; this.value = value; this.rolls = rolls; }
javascript
function Result( notation, value, rolls ) { this.notation = notation; this.value = value; this.rolls = rolls; }
[ "function", "Result", "(", "notation", ",", "value", ",", "rolls", ")", "{", "this", ".", "notation", "=", "notation", ";", "this", ".", "value", "=", "value", ";", "this", ".", "rolls", "=", "rolls", ";", "}" ]
A class that represents a dice roll result @class @classdesc A class that represents a dice roll result @since v2.0.0 @param {String} notation - A roll notation @param {Number} value - A numeric representation of roll result, like total summ or success count @param {Array} rolls - An array of rolls dome @see Roll @see WodRoll
[ "A", "class", "that", "represents", "a", "dice", "roll", "result" ]
38912b298edb0a4d67ba1c796d7ac159ebaf7901
https://github.com/edloidas/roll-parser/blob/38912b298edb0a4d67ba1c796d7ac159ebaf7901/src/object/Result.js#L13-L17
47,224
Holixus/nano-md5
md5.js
bytesToWords
function bytesToWords(bytes) { var bytes_count = bytes.length, bits_count = bytes_count << 3, words = new Uint32Array((bytes_count + 64) >>> 6 << 4); for (var i = 0, n = bytes.length; i < n; ++i) words[i >>> 2] |= bytes.charCodeAt(i) << ((i & 3) << 3); words[bytes_count >> 2] |= 0x80 << (bits_count & 31); // append "1" bit to message words[words.length - 2] = bits_count; return words; }
javascript
function bytesToWords(bytes) { var bytes_count = bytes.length, bits_count = bytes_count << 3, words = new Uint32Array((bytes_count + 64) >>> 6 << 4); for (var i = 0, n = bytes.length; i < n; ++i) words[i >>> 2] |= bytes.charCodeAt(i) << ((i & 3) << 3); words[bytes_count >> 2] |= 0x80 << (bits_count & 31); // append "1" bit to message words[words.length - 2] = bits_count; return words; }
[ "function", "bytesToWords", "(", "bytes", ")", "{", "var", "bytes_count", "=", "bytes", ".", "length", ",", "bits_count", "=", "bytes_count", "<<", "3", ",", "words", "=", "new", "Uint32Array", "(", "(", "bytes_count", "+", "64", ")", ">>>", "6", "<<", "4", ")", ";", "for", "(", "var", "i", "=", "0", ",", "n", "=", "bytes", ".", "length", ";", "i", "<", "n", ";", "++", "i", ")", "words", "[", "i", ">>>", "2", "]", "|=", "bytes", ".", "charCodeAt", "(", "i", ")", "<<", "(", "(", "i", "&", "3", ")", "<<", "3", ")", ";", "words", "[", "bytes_count", ">>", "2", "]", "|=", "0x80", "<<", "(", "bits_count", "&", "31", ")", ";", "// append \"1\" bit to message", "words", "[", "words", ".", "length", "-", "2", "]", "=", "bits_count", ";", "return", "words", ";", "}" ]
converts bytes string to 32-bits words array padded with "1" and zeros and bits_length for MD5 message buffer
[ "converts", "bytes", "string", "to", "32", "-", "bits", "words", "array", "padded", "with", "1", "and", "zeros", "and", "bits_length", "for", "MD5", "message", "buffer" ]
058964cfeb6d9c14b0a20c1122f83e1d6b8870f1
https://github.com/Holixus/nano-md5/blob/058964cfeb6d9c14b0a20c1122f83e1d6b8870f1/md5.js#L43-L52
47,225
clux/tiebreaker
tiebreaker.js
Id
function Id(s, r, m, isSimple) { this.s = s; this.r = r; this.m = m; Object.defineProperty(this, '_simple', { value: isSimple }); }
javascript
function Id(s, r, m, isSimple) { this.s = s; this.r = r; this.m = m; Object.defineProperty(this, '_simple', { value: isSimple }); }
[ "function", "Id", "(", "s", ",", "r", ",", "m", ",", "isSimple", ")", "{", "this", ".", "s", "=", "s", ";", "this", ".", "r", "=", "r", ";", "this", ".", "m", "=", "m", ";", "Object", ".", "defineProperty", "(", "this", ",", "'_simple'", ",", "{", "value", ":", "isSimple", "}", ")", ";", "}" ]
for grouped breakers
[ "for", "grouped", "breakers" ]
ef5809b6016b544b4d2cbbdaebf73d6aff36a63c
https://github.com/clux/tiebreaker/blob/ef5809b6016b544b4d2cbbdaebf73d6aff36a63c/tiebreaker.js#L6-L13
47,226
clux/tiebreaker
tiebreaker.js
function (seedAry, match) { var res = $.replicate(seedAry.length, []); seedAry.forEach(function (xps, x) { // NB: while we are not writing 1-1 from seedAry to res, we are always // making sure not to overwrite what we had in previous iterations if (xps.indexOf(match.p[0]) < 0) { res[x] = res[x].concat(xps); return; } // always tieCompute match because only strict mode has guaranteed non-ties var sorted = $.zip(match.p, match.m).sort(Base.compareZip); Base.matchTieCompute(sorted, 0, function (p, pos) { res[x+pos-1].push(p); }); }); return res; }
javascript
function (seedAry, match) { var res = $.replicate(seedAry.length, []); seedAry.forEach(function (xps, x) { // NB: while we are not writing 1-1 from seedAry to res, we are always // making sure not to overwrite what we had in previous iterations if (xps.indexOf(match.p[0]) < 0) { res[x] = res[x].concat(xps); return; } // always tieCompute match because only strict mode has guaranteed non-ties var sorted = $.zip(match.p, match.m).sort(Base.compareZip); Base.matchTieCompute(sorted, 0, function (p, pos) { res[x+pos-1].push(p); }); }); return res; }
[ "function", "(", "seedAry", ",", "match", ")", "{", "var", "res", "=", "$", ".", "replicate", "(", "seedAry", ".", "length", ",", "[", "]", ")", ";", "seedAry", ".", "forEach", "(", "function", "(", "xps", ",", "x", ")", "{", "// NB: while we are not writing 1-1 from seedAry to res, we are always", "// making sure not to overwrite what we had in previous iterations", "if", "(", "xps", ".", "indexOf", "(", "match", ".", "p", "[", "0", "]", ")", "<", "0", ")", "{", "res", "[", "x", "]", "=", "res", "[", "x", "]", ".", "concat", "(", "xps", ")", ";", "return", ";", "}", "// always tieCompute match because only strict mode has guaranteed non-ties", "var", "sorted", "=", "$", ".", "zip", "(", "match", ".", "p", ",", "match", ".", "m", ")", ".", "sort", "(", "Base", ".", "compareZip", ")", ";", "Base", ".", "matchTieCompute", "(", "sorted", ",", "0", ",", "function", "(", "p", ",", "pos", ")", "{", "res", "[", "x", "+", "pos", "-", "1", "]", ".", "push", "(", "p", ")", ";", "}", ")", ";", "}", ")", ";", "return", "res", ";", "}" ]
split up the posAry entried cluster found in corresponding within section breakers
[ "split", "up", "the", "posAry", "entried", "cluster", "found", "in", "corresponding", "within", "section", "breakers" ]
ef5809b6016b544b4d2cbbdaebf73d6aff36a63c
https://github.com/clux/tiebreaker/blob/ef5809b6016b544b4d2cbbdaebf73d6aff36a63c/tiebreaker.js#L107-L123
47,227
feedhenry-raincatcher/raincatcher-angularjs
packages/angularjs-workorder/lib/workorder-list/workorder-list-controller.js
WorkorderListController
function WorkorderListController($scope, workorderService, workorderFlowService, $q, workorderStatusService) { var self = this; var _workorders = []; self.workorders = []; function refreshWorkorders() { // Needs $q.when to trigger angular's change detection workorderService.list().then(function(workorders) { _workorders = workorders; self.updateFilter(); }); } refreshWorkorders(); self.selectWorkorder = function(event, workorder) { workorderFlowService.workorderSelected(workorder); event.preventDefault(); event.stopPropagation(); }; self.isWorkorderShown = function(workorder) { return self.shownWorkorder === workorder; }; self.applyFilter = function(term) { self.term = term; self.updateFilter(); }; self.updateFilter = _.debounce(function() { $scope.$apply(function() { if (!self.term) { return self.workorders = _workorders; } if (self.term.length > 3) { var term = self.term.toLowerCase(); self.workorders = _workorders.filter(function(workflow) { return String(workflow.title).toLowerCase().indexOf(term) !== -1 || String(workflow.id).indexOf(term) !== -1; }); } }); }, 300); self.getColorIcon = function(workorder) { if (!workorder || !workorder.status) { return workorderStatusService.getStatusIconColor('').statusColor; } else { return workorderStatusService.getStatusIconColor(workorder.status).statusColor; } }; self.setupEventListenerHandlers = function() { workorderService.on('create', function(workorder) { _workorders.push(workorder); self.updateFilter(); }); workorderService.on('remove', function(workorder) { _.remove(_workorders, function(w) { return w.id === workorder.id; }); self.updateFilter(); }); workorderService.on('update', function(workorder) { var idx = _.findIndex(_workorders, function(w) { return w.id === workorder.id; }); _workorders.splice(idx, 1, workorder); self.updateFilter(); }); }; if (workorderService.on) { self.setupEventListenerHandlers(); } else if (workorderService.subscribeToDatasetUpdates) { // use the single method to update workorders via sync workorderService.subscribeToDatasetUpdates(refreshWorkorders); } }
javascript
function WorkorderListController($scope, workorderService, workorderFlowService, $q, workorderStatusService) { var self = this; var _workorders = []; self.workorders = []; function refreshWorkorders() { // Needs $q.when to trigger angular's change detection workorderService.list().then(function(workorders) { _workorders = workorders; self.updateFilter(); }); } refreshWorkorders(); self.selectWorkorder = function(event, workorder) { workorderFlowService.workorderSelected(workorder); event.preventDefault(); event.stopPropagation(); }; self.isWorkorderShown = function(workorder) { return self.shownWorkorder === workorder; }; self.applyFilter = function(term) { self.term = term; self.updateFilter(); }; self.updateFilter = _.debounce(function() { $scope.$apply(function() { if (!self.term) { return self.workorders = _workorders; } if (self.term.length > 3) { var term = self.term.toLowerCase(); self.workorders = _workorders.filter(function(workflow) { return String(workflow.title).toLowerCase().indexOf(term) !== -1 || String(workflow.id).indexOf(term) !== -1; }); } }); }, 300); self.getColorIcon = function(workorder) { if (!workorder || !workorder.status) { return workorderStatusService.getStatusIconColor('').statusColor; } else { return workorderStatusService.getStatusIconColor(workorder.status).statusColor; } }; self.setupEventListenerHandlers = function() { workorderService.on('create', function(workorder) { _workorders.push(workorder); self.updateFilter(); }); workorderService.on('remove', function(workorder) { _.remove(_workorders, function(w) { return w.id === workorder.id; }); self.updateFilter(); }); workorderService.on('update', function(workorder) { var idx = _.findIndex(_workorders, function(w) { return w.id === workorder.id; }); _workorders.splice(idx, 1, workorder); self.updateFilter(); }); }; if (workorderService.on) { self.setupEventListenerHandlers(); } else if (workorderService.subscribeToDatasetUpdates) { // use the single method to update workorders via sync workorderService.subscribeToDatasetUpdates(refreshWorkorders); } }
[ "function", "WorkorderListController", "(", "$scope", ",", "workorderService", ",", "workorderFlowService", ",", "$q", ",", "workorderStatusService", ")", "{", "var", "self", "=", "this", ";", "var", "_workorders", "=", "[", "]", ";", "self", ".", "workorders", "=", "[", "]", ";", "function", "refreshWorkorders", "(", ")", "{", "// Needs $q.when to trigger angular's change detection", "workorderService", ".", "list", "(", ")", ".", "then", "(", "function", "(", "workorders", ")", "{", "_workorders", "=", "workorders", ";", "self", ".", "updateFilter", "(", ")", ";", "}", ")", ";", "}", "refreshWorkorders", "(", ")", ";", "self", ".", "selectWorkorder", "=", "function", "(", "event", ",", "workorder", ")", "{", "workorderFlowService", ".", "workorderSelected", "(", "workorder", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "event", ".", "stopPropagation", "(", ")", ";", "}", ";", "self", ".", "isWorkorderShown", "=", "function", "(", "workorder", ")", "{", "return", "self", ".", "shownWorkorder", "===", "workorder", ";", "}", ";", "self", ".", "applyFilter", "=", "function", "(", "term", ")", "{", "self", ".", "term", "=", "term", ";", "self", ".", "updateFilter", "(", ")", ";", "}", ";", "self", ".", "updateFilter", "=", "_", ".", "debounce", "(", "function", "(", ")", "{", "$scope", ".", "$apply", "(", "function", "(", ")", "{", "if", "(", "!", "self", ".", "term", ")", "{", "return", "self", ".", "workorders", "=", "_workorders", ";", "}", "if", "(", "self", ".", "term", ".", "length", ">", "3", ")", "{", "var", "term", "=", "self", ".", "term", ".", "toLowerCase", "(", ")", ";", "self", ".", "workorders", "=", "_workorders", ".", "filter", "(", "function", "(", "workflow", ")", "{", "return", "String", "(", "workflow", ".", "title", ")", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "term", ")", "!==", "-", "1", "||", "String", "(", "workflow", ".", "id", ")", ".", "indexOf", "(", "term", ")", "!==", "-", "1", ";", "}", ")", ";", "}", "}", ")", ";", "}", ",", "300", ")", ";", "self", ".", "getColorIcon", "=", "function", "(", "workorder", ")", "{", "if", "(", "!", "workorder", "||", "!", "workorder", ".", "status", ")", "{", "return", "workorderStatusService", ".", "getStatusIconColor", "(", "''", ")", ".", "statusColor", ";", "}", "else", "{", "return", "workorderStatusService", ".", "getStatusIconColor", "(", "workorder", ".", "status", ")", ".", "statusColor", ";", "}", "}", ";", "self", ".", "setupEventListenerHandlers", "=", "function", "(", ")", "{", "workorderService", ".", "on", "(", "'create'", ",", "function", "(", "workorder", ")", "{", "_workorders", ".", "push", "(", "workorder", ")", ";", "self", ".", "updateFilter", "(", ")", ";", "}", ")", ";", "workorderService", ".", "on", "(", "'remove'", ",", "function", "(", "workorder", ")", "{", "_", ".", "remove", "(", "_workorders", ",", "function", "(", "w", ")", "{", "return", "w", ".", "id", "===", "workorder", ".", "id", ";", "}", ")", ";", "self", ".", "updateFilter", "(", ")", ";", "}", ")", ";", "workorderService", ".", "on", "(", "'update'", ",", "function", "(", "workorder", ")", "{", "var", "idx", "=", "_", ".", "findIndex", "(", "_workorders", ",", "function", "(", "w", ")", "{", "return", "w", ".", "id", "===", "workorder", ".", "id", ";", "}", ")", ";", "_workorders", ".", "splice", "(", "idx", ",", "1", ",", "workorder", ")", ";", "self", ".", "updateFilter", "(", ")", ";", "}", ")", ";", "}", ";", "if", "(", "workorderService", ".", "on", ")", "{", "self", ".", "setupEventListenerHandlers", "(", ")", ";", "}", "else", "if", "(", "workorderService", ".", "subscribeToDatasetUpdates", ")", "{", "// use the single method to update workorders via sync", "workorderService", ".", "subscribeToDatasetUpdates", "(", "refreshWorkorders", ")", ";", "}", "}" ]
Controller for listing Workorders @constructor
[ "Controller", "for", "listing", "Workorders" ]
b394689227901e18871ad9edd0ec226c5e6839e1
https://github.com/feedhenry-raincatcher/raincatcher-angularjs/blob/b394689227901e18871ad9edd0ec226c5e6839e1/packages/angularjs-workorder/lib/workorder-list/workorder-list-controller.js#L10-L93
47,228
jaymell/nodeCf
src/utils.js
fileExists
async function fileExists(f) { debug(`fileExists called with: ${JSON.stringify(arguments)}`); try { await fs.statAsync(f); return f; } catch (e) { throw e; } }
javascript
async function fileExists(f) { debug(`fileExists called with: ${JSON.stringify(arguments)}`); try { await fs.statAsync(f); return f; } catch (e) { throw e; } }
[ "async", "function", "fileExists", "(", "f", ")", "{", "debug", "(", "`", "${", "JSON", ".", "stringify", "(", "arguments", ")", "}", "`", ")", ";", "try", "{", "await", "fs", ".", "statAsync", "(", "f", ")", ";", "return", "f", ";", "}", "catch", "(", "e", ")", "{", "throw", "e", ";", "}", "}" ]
return filename if exists, else throw
[ "return", "filename", "if", "exists", "else", "throw" ]
d0f499a1b0adf5c810c33698a66ef16db6bc590d
https://github.com/jaymell/nodeCf/blob/d0f499a1b0adf5c810c33698a66ef16db6bc590d/src/utils.js#L8-L16
47,229
jaymell/nodeCf
src/utils.js
execTasks
async function execTasks(tasks, taskType) { debug(`execTasks: called for ${taskType}`); if (!(_.isEmpty(tasks))) { if (taskType) console.log(`running ${taskType}...`); const output = await Promise.mapSeries(tasks, async(task) => { const result = await execTask(task); if (_.isString(result.stdout) && (!_.isEmpty(result.stdout))) console.log(result.stdout.trim()); if (_.isString(result.stderr) && (!_.isEmpty(result.stderr))) console.log(result.stderr.trim()); return result; }); return output; } debug("execTasks: nothing to do; resolving"); return; }
javascript
async function execTasks(tasks, taskType) { debug(`execTasks: called for ${taskType}`); if (!(_.isEmpty(tasks))) { if (taskType) console.log(`running ${taskType}...`); const output = await Promise.mapSeries(tasks, async(task) => { const result = await execTask(task); if (_.isString(result.stdout) && (!_.isEmpty(result.stdout))) console.log(result.stdout.trim()); if (_.isString(result.stderr) && (!_.isEmpty(result.stderr))) console.log(result.stderr.trim()); return result; }); return output; } debug("execTasks: nothing to do; resolving"); return; }
[ "async", "function", "execTasks", "(", "tasks", ",", "taskType", ")", "{", "debug", "(", "`", "${", "taskType", "}", "`", ")", ";", "if", "(", "!", "(", "_", ".", "isEmpty", "(", "tasks", ")", ")", ")", "{", "if", "(", "taskType", ")", "console", ".", "log", "(", "`", "${", "taskType", "}", "`", ")", ";", "const", "output", "=", "await", "Promise", ".", "mapSeries", "(", "tasks", ",", "async", "(", "task", ")", "=>", "{", "const", "result", "=", "await", "execTask", "(", "task", ")", ";", "if", "(", "_", ".", "isString", "(", "result", ".", "stdout", ")", "&&", "(", "!", "_", ".", "isEmpty", "(", "result", ".", "stdout", ")", ")", ")", "console", ".", "log", "(", "result", ".", "stdout", ".", "trim", "(", ")", ")", ";", "if", "(", "_", ".", "isString", "(", "result", ".", "stderr", ")", "&&", "(", "!", "_", ".", "isEmpty", "(", "result", ".", "stderr", ")", ")", ")", "console", ".", "log", "(", "result", ".", "stderr", ".", "trim", "(", ")", ")", ";", "return", "result", ";", "}", ")", ";", "return", "output", ";", "}", "debug", "(", "\"execTasks: nothing to do; resolving\"", ")", ";", "return", ";", "}" ]
exec list of tasks, print stdout and stderr for each
[ "exec", "list", "of", "tasks", "print", "stdout", "and", "stderr", "for", "each" ]
d0f499a1b0adf5c810c33698a66ef16db6bc590d
https://github.com/jaymell/nodeCf/blob/d0f499a1b0adf5c810c33698a66ef16db6bc590d/src/utils.js#L30-L46
47,230
edloidas/roll-parser
src/object/Roll.js
Roll
function Roll( dice = 20, count = 1, modifier = 0 ) { this.dice = positiveInteger( dice ); this.count = positiveInteger( count ); this.modifier = normalizeInteger( modifier ); }
javascript
function Roll( dice = 20, count = 1, modifier = 0 ) { this.dice = positiveInteger( dice ); this.count = positiveInteger( count ); this.modifier = normalizeInteger( modifier ); }
[ "function", "Roll", "(", "dice", "=", "20", ",", "count", "=", "1", ",", "modifier", "=", "0", ")", "{", "this", ".", "dice", "=", "positiveInteger", "(", "dice", ")", ";", "this", ".", "count", "=", "positiveInteger", "(", "count", ")", ";", "this", ".", "modifier", "=", "normalizeInteger", "(", "modifier", ")", ";", "}" ]
A class that represents a dice roll from D&D setting @class @classdesc A class that represents a dice roll from D&D setting @since v2.0.0 @param {Number} dice - A number of dice faces @param {Number} count - A number of dices @param {Number} modifier - A modifier, that should be added/sustracted from result @see WodRoll
[ "A", "class", "that", "represents", "a", "dice", "roll", "from", "D&D", "setting" ]
38912b298edb0a4d67ba1c796d7ac159ebaf7901
https://github.com/edloidas/roll-parser/blob/38912b298edb0a4d67ba1c796d7ac159ebaf7901/src/object/Roll.js#L16-L20
47,231
YannickBochatay/JSYG
dist/JSYG.js
function(mtx) { if (mtx && typeof mtx == "object" && mtx.mtx) mtx = mtx.mtx; if (!mtx) return new Point(this.x,this.y); var point = svg.createSVGPoint(); point.x = this.x; point.y = this.y; point = point.matrixTransform(mtx); return new this.constructor(point.x,point.y); }
javascript
function(mtx) { if (mtx && typeof mtx == "object" && mtx.mtx) mtx = mtx.mtx; if (!mtx) return new Point(this.x,this.y); var point = svg.createSVGPoint(); point.x = this.x; point.y = this.y; point = point.matrixTransform(mtx); return new this.constructor(point.x,point.y); }
[ "function", "(", "mtx", ")", "{", "if", "(", "mtx", "&&", "typeof", "mtx", "==", "\"object\"", "&&", "mtx", ".", "mtx", ")", "mtx", "=", "mtx", ".", "mtx", ";", "if", "(", "!", "mtx", ")", "return", "new", "Point", "(", "this", ".", "x", ",", "this", ".", "y", ")", ";", "var", "point", "=", "svg", ".", "createSVGPoint", "(", ")", ";", "point", ".", "x", "=", "this", ".", "x", ";", "point", ".", "y", "=", "this", ".", "y", ";", "point", "=", "point", ".", "matrixTransform", "(", "mtx", ")", ";", "return", "new", "this", ".", "constructor", "(", "point", ".", "x", ",", "point", ".", "y", ")", ";", "}" ]
Applique une matrice de transformation @param mtx instance de JSYG.Matrix (ou SVGMatrix) @returns nouvelle instance
[ "Applique", "une", "matrice", "de", "transformation" ]
b32a5368b57498b51c0c8261cf9a682e5ed6ff11
https://github.com/YannickBochatay/JSYG/blob/b32a5368b57498b51c0c8261cf9a682e5ed6ff11/dist/JSYG.js#L623-L634
47,232
YannickBochatay/JSYG
dist/JSYG.js
Matrix
function Matrix(arg) { if (arg && arguments.length === 1) { if (arg instanceof window.SVGMatrix) this.mtx = arg.scale(1); else if (arg instanceof Matrix) this.mtx = arg.mtx.scale(1); else if (typeof arg == "string") return Matrix.parse(arg); else throw new Error(arg+" : argument incorrect pour Matrix."); } else { this.mtx = svg && svg.createSVGMatrix(); if (arguments.length === 6) { var a = arguments, that = this; ['a','b','c','d','e','f'].forEach(function(prop,ind){ that[prop] = a[ind]; }); } } }
javascript
function Matrix(arg) { if (arg && arguments.length === 1) { if (arg instanceof window.SVGMatrix) this.mtx = arg.scale(1); else if (arg instanceof Matrix) this.mtx = arg.mtx.scale(1); else if (typeof arg == "string") return Matrix.parse(arg); else throw new Error(arg+" : argument incorrect pour Matrix."); } else { this.mtx = svg && svg.createSVGMatrix(); if (arguments.length === 6) { var a = arguments, that = this; ['a','b','c','d','e','f'].forEach(function(prop,ind){ that[prop] = a[ind]; }); } } }
[ "function", "Matrix", "(", "arg", ")", "{", "if", "(", "arg", "&&", "arguments", ".", "length", "===", "1", ")", "{", "if", "(", "arg", "instanceof", "window", ".", "SVGMatrix", ")", "this", ".", "mtx", "=", "arg", ".", "scale", "(", "1", ")", ";", "else", "if", "(", "arg", "instanceof", "Matrix", ")", "this", ".", "mtx", "=", "arg", ".", "mtx", ".", "scale", "(", "1", ")", ";", "else", "if", "(", "typeof", "arg", "==", "\"string\"", ")", "return", "Matrix", ".", "parse", "(", "arg", ")", ";", "else", "throw", "new", "Error", "(", "arg", "+", "\" : argument incorrect pour Matrix.\"", ")", ";", "}", "else", "{", "this", ".", "mtx", "=", "svg", "&&", "svg", ".", "createSVGMatrix", "(", ")", ";", "if", "(", "arguments", ".", "length", "===", "6", ")", "{", "var", "a", "=", "arguments", ",", "that", "=", "this", ";", "[", "'a'", ",", "'b'", ",", "'c'", ",", "'d'", ",", "'e'", ",", "'f'", "]", ".", "forEach", "(", "function", "(", "prop", ",", "ind", ")", "{", "that", "[", "prop", "]", "=", "a", "[", "ind", "]", ";", "}", ")", ";", "}", "}", "}" ]
Constructeur de matrices @param arg optionnel, si défini reprend les coefficients de l'argument. arg peut être une instance de SVGMatrix (DOM SVG) ou de Matrix. On peut également passer 6 arguments numériques pour définir chacun des coefficients. @returns {Matrix}
[ "Constructeur", "de", "matrices" ]
b32a5368b57498b51c0c8261cf9a682e5ed6ff11
https://github.com/YannickBochatay/JSYG/blob/b32a5368b57498b51c0c8261cf9a682e5ed6ff11/dist/JSYG.js#L766-L781
47,233
YannickBochatay/JSYG
dist/JSYG.js
function(str,tag,content) { return str.replace(regexpTag(tag),function(str,p1,p2) { content && content.push(p2); return ''; }); }
javascript
function(str,tag,content) { return str.replace(regexpTag(tag),function(str,p1,p2) { content && content.push(p2); return ''; }); }
[ "function", "(", "str", ",", "tag", ",", "content", ")", "{", "return", "str", ".", "replace", "(", "regexpTag", "(", "tag", ")", ",", "function", "(", "str", ",", "p1", ",", "p2", ")", "{", "content", "&&", "content", ".", "push", "(", "p2", ")", ";", "return", "''", ";", "}", ")", ";", "}" ]
Retire les balises et leur contenu @param {String} str chaîne à analyser @param {String} tag nom de la balise à supprimer @param {Array} content tableau qui sera rempli par le contenu des balises trouvées (les tableaux passent par référence) @@returns {String}
[ "Retire", "les", "balises", "et", "leur", "contenu" ]
b32a5368b57498b51c0c8261cf9a682e5ed6ff11
https://github.com/YannickBochatay/JSYG/blob/b32a5368b57498b51c0c8261cf9a682e5ed6ff11/dist/JSYG.js#L1405-L1407
47,234
alexyoung/pop
lib/filters.js
function(data) { data = data.replace(/{% highlight ([^ ]*) %}/g, '<pre class="prettyprint lang-$1">'); data = data.replace(/{% endhighlight %}/g, '</pre>'); return data; }
javascript
function(data) { data = data.replace(/{% highlight ([^ ]*) %}/g, '<pre class="prettyprint lang-$1">'); data = data.replace(/{% endhighlight %}/g, '</pre>'); return data; }
[ "function", "(", "data", ")", "{", "data", "=", "data", ".", "replace", "(", "/", "{% highlight ([^ ]*) %}", "/", "g", ",", "'<pre class=\"prettyprint lang-$1\">'", ")", ";", "data", "=", "data", ".", "replace", "(", "/", "{% endhighlight %}", "/", "g", ",", "'</pre>'", ")", ";", "return", "data", ";", "}" ]
Replaces liquid tag highlight directives with prettyprint HTML tags. @param {String} The text for a post @return {String}
[ "Replaces", "liquid", "tag", "highlight", "directives", "with", "prettyprint", "HTML", "tags", "." ]
8a0b3f2605cb58e8ae6b34f1373dde00610e9858
https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/filters.js#L14-L18
47,235
gagle/node-argp
lib/argp.js
function (){ if (!instance._once) return; //Uncache the files ["index.js", "command.js", "argp.js", "body.js", "error.js", "wrap.js"] .forEach (function (filename){ delete require.cache[__dirname + path.sep + filename]; }); //The user may have a reference to the instance so it should be freed, eg. //var p = argp.createParser (). If the user doesn't free the instance, eg. //p = null, it will retain an empty object, {} for (var p in instance){ delete instance[p]; } instance.__proto__ = null; delete instance.constructor; }
javascript
function (){ if (!instance._once) return; //Uncache the files ["index.js", "command.js", "argp.js", "body.js", "error.js", "wrap.js"] .forEach (function (filename){ delete require.cache[__dirname + path.sep + filename]; }); //The user may have a reference to the instance so it should be freed, eg. //var p = argp.createParser (). If the user doesn't free the instance, eg. //p = null, it will retain an empty object, {} for (var p in instance){ delete instance[p]; } instance.__proto__ = null; delete instance.constructor; }
[ "function", "(", ")", "{", "if", "(", "!", "instance", ".", "_once", ")", "return", ";", "//Uncache the files", "[", "\"index.js\"", ",", "\"command.js\"", ",", "\"argp.js\"", ",", "\"body.js\"", ",", "\"error.js\"", ",", "\"wrap.js\"", "]", ".", "forEach", "(", "function", "(", "filename", ")", "{", "delete", "require", ".", "cache", "[", "__dirname", "+", "path", ".", "sep", "+", "filename", "]", ";", "}", ")", ";", "//The user may have a reference to the instance so it should be freed, eg.", "//var p = argp.createParser (). If the user doesn't free the instance, eg.", "//p = null, it will retain an empty object, {}", "for", "(", "var", "p", "in", "instance", ")", "{", "delete", "instance", "[", "p", "]", ";", "}", "instance", ".", "__proto__", "=", "null", ";", "delete", "instance", ".", "constructor", ";", "}" ]
The Argp and Command instances execute this code
[ "The", "Argp", "and", "Command", "instances", "execute", "this", "code" ]
e4a5a018c0b9fa8b370498c085e20fe8ff9fad5b
https://github.com/gagle/node-argp/blob/e4a5a018c0b9fa8b370498c085e20fe8ff9fad5b/lib/argp.js#L992-L1009
47,236
feedhenry-raincatcher/raincatcher-angularjs
packages/angularjs-workflow/lib/workflow-process/workflow-process-begin/workflow-process-begin-controller.js
WorkflowProcessBeginController
function WorkflowProcessBeginController($state, workorderService, wfmService, $stateParams) { var self = this; var workorderId = $stateParams.workorderId; workorderService.read(workorderId).then(function(workorder) { self.workorder = workorder; self.workflow = workorder.workflow; self.results = workorder.results; self.started = !wfmService.isNew(self.workorder); self.completed = wfmService.isCompleted(self.workorder); }); self.getStepForResult = function(result) { return wfmService.getStepForResult(result, self.workorder); }; self.begin = function() { wfmService.begin(self.workorder) .then(function() { $state.go('app.workflowProcess.steps', { workorderId: workorderId }); }) .catch(console.error.bind(console)); }; }
javascript
function WorkflowProcessBeginController($state, workorderService, wfmService, $stateParams) { var self = this; var workorderId = $stateParams.workorderId; workorderService.read(workorderId).then(function(workorder) { self.workorder = workorder; self.workflow = workorder.workflow; self.results = workorder.results; self.started = !wfmService.isNew(self.workorder); self.completed = wfmService.isCompleted(self.workorder); }); self.getStepForResult = function(result) { return wfmService.getStepForResult(result, self.workorder); }; self.begin = function() { wfmService.begin(self.workorder) .then(function() { $state.go('app.workflowProcess.steps', { workorderId: workorderId }); }) .catch(console.error.bind(console)); }; }
[ "function", "WorkflowProcessBeginController", "(", "$state", ",", "workorderService", ",", "wfmService", ",", "$stateParams", ")", "{", "var", "self", "=", "this", ";", "var", "workorderId", "=", "$stateParams", ".", "workorderId", ";", "workorderService", ".", "read", "(", "workorderId", ")", ".", "then", "(", "function", "(", "workorder", ")", "{", "self", ".", "workorder", "=", "workorder", ";", "self", ".", "workflow", "=", "workorder", ".", "workflow", ";", "self", ".", "results", "=", "workorder", ".", "results", ";", "self", ".", "started", "=", "!", "wfmService", ".", "isNew", "(", "self", ".", "workorder", ")", ";", "self", ".", "completed", "=", "wfmService", ".", "isCompleted", "(", "self", ".", "workorder", ")", ";", "}", ")", ";", "self", ".", "getStepForResult", "=", "function", "(", "result", ")", "{", "return", "wfmService", ".", "getStepForResult", "(", "result", ",", "self", ".", "workorder", ")", ";", "}", ";", "self", ".", "begin", "=", "function", "(", ")", "{", "wfmService", ".", "begin", "(", "self", ".", "workorder", ")", ".", "then", "(", "function", "(", ")", "{", "$state", ".", "go", "(", "'app.workflowProcess.steps'", ",", "{", "workorderId", ":", "workorderId", "}", ")", ";", "}", ")", ".", "catch", "(", "console", ".", "error", ".", "bind", "(", "console", ")", ")", ";", "}", ";", "}" ]
Controller for starting a workflow process. @param $state @param workflowService @param $stateParams @param $timeout @constructor
[ "Controller", "for", "starting", "a", "workflow", "process", "." ]
b394689227901e18871ad9edd0ec226c5e6839e1
https://github.com/feedhenry-raincatcher/raincatcher-angularjs/blob/b394689227901e18871ad9edd0ec226c5e6839e1/packages/angularjs-workflow/lib/workflow-process/workflow-process-begin/workflow-process-begin-controller.js#L12-L37
47,237
yaxia/json-edm-parser
parser.js
function (token, value) { var self = this; var emitString = false; function additionalEmit(additionalKey, additionalValue) { var oldKey = self.internalParser.key; self.internalParser.key = additionalKey; self.internalParser.onValue(additionalValue); self.internalParser.key = oldKey; } if (token === JsonParser.C.STRING || token === JsonParser.C.NUMBER || token === JsonParser.C.TRUE || token === JsonParser.C.FALSE || token === JsonParser.C.NULL) { // Parser will emit value in these cases if (typeof value === 'number' && this.internalParser.string.indexOf('.') != -1 && parseInt(this.internalParser.string) === value && this.internalParser.mode !== JsonParser.C.ARRAY) { var typeKey = this.internalParser.key + '@odata.type'; if (this.internalParser.value) { this.internalParser.value[typeKey] = 'Edm.Double'; } additionalEmit(typeKey, 'Edm.Double'); // Determine whether return raw string to avoid losing precision emitString = this.internalParser.string !== value.toString(); } } if (emitString) { this.originalOnToken.call(this.internalParser, token, this.internalParser.string); } else { this.originalOnToken.call(this.internalParser, token, value); } }
javascript
function (token, value) { var self = this; var emitString = false; function additionalEmit(additionalKey, additionalValue) { var oldKey = self.internalParser.key; self.internalParser.key = additionalKey; self.internalParser.onValue(additionalValue); self.internalParser.key = oldKey; } if (token === JsonParser.C.STRING || token === JsonParser.C.NUMBER || token === JsonParser.C.TRUE || token === JsonParser.C.FALSE || token === JsonParser.C.NULL) { // Parser will emit value in these cases if (typeof value === 'number' && this.internalParser.string.indexOf('.') != -1 && parseInt(this.internalParser.string) === value && this.internalParser.mode !== JsonParser.C.ARRAY) { var typeKey = this.internalParser.key + '@odata.type'; if (this.internalParser.value) { this.internalParser.value[typeKey] = 'Edm.Double'; } additionalEmit(typeKey, 'Edm.Double'); // Determine whether return raw string to avoid losing precision emitString = this.internalParser.string !== value.toString(); } } if (emitString) { this.originalOnToken.call(this.internalParser, token, this.internalParser.string); } else { this.originalOnToken.call(this.internalParser, token, value); } }
[ "function", "(", "token", ",", "value", ")", "{", "var", "self", "=", "this", ";", "var", "emitString", "=", "false", ";", "function", "additionalEmit", "(", "additionalKey", ",", "additionalValue", ")", "{", "var", "oldKey", "=", "self", ".", "internalParser", ".", "key", ";", "self", ".", "internalParser", ".", "key", "=", "additionalKey", ";", "self", ".", "internalParser", ".", "onValue", "(", "additionalValue", ")", ";", "self", ".", "internalParser", ".", "key", "=", "oldKey", ";", "}", "if", "(", "token", "===", "JsonParser", ".", "C", ".", "STRING", "||", "token", "===", "JsonParser", ".", "C", ".", "NUMBER", "||", "token", "===", "JsonParser", ".", "C", ".", "TRUE", "||", "token", "===", "JsonParser", ".", "C", ".", "FALSE", "||", "token", "===", "JsonParser", ".", "C", ".", "NULL", ")", "{", "// Parser will emit value in these cases", "if", "(", "typeof", "value", "===", "'number'", "&&", "this", ".", "internalParser", ".", "string", ".", "indexOf", "(", "'.'", ")", "!=", "-", "1", "&&", "parseInt", "(", "this", ".", "internalParser", ".", "string", ")", "===", "value", "&&", "this", ".", "internalParser", ".", "mode", "!==", "JsonParser", ".", "C", ".", "ARRAY", ")", "{", "var", "typeKey", "=", "this", ".", "internalParser", ".", "key", "+", "'@odata.type'", ";", "if", "(", "this", ".", "internalParser", ".", "value", ")", "{", "this", ".", "internalParser", ".", "value", "[", "typeKey", "]", "=", "'Edm.Double'", ";", "}", "additionalEmit", "(", "typeKey", ",", "'Edm.Double'", ")", ";", "// Determine whether return raw string to avoid losing precision", "emitString", "=", "this", ".", "internalParser", ".", "string", "!==", "value", ".", "toString", "(", ")", ";", "}", "}", "if", "(", "emitString", ")", "{", "this", ".", "originalOnToken", ".", "call", "(", "this", ".", "internalParser", ",", "token", ",", "this", ".", "internalParser", ".", "string", ")", ";", "}", "else", "{", "this", ".", "originalOnToken", ".", "call", "(", "this", ".", "internalParser", ",", "token", ",", "value", ")", ";", "}", "}" ]
Handles the EDM types in the JSON object 1. Number will be treated as Edm.Int32 by default 2. Literal value 1.0 will be treated as Edm.Double 3. Others will be handled according to the literal value
[ "Handles", "the", "EDM", "types", "in", "the", "JSON", "object", "1", ".", "Number", "will", "be", "treated", "as", "Edm", ".", "Int32", "by", "default", "2", ".", "Literal", "value", "1", ".", "0", "will", "be", "treated", "as", "Edm", ".", "Double", "3", ".", "Others", "will", "be", "handled", "according", "to", "the", "literal", "value" ]
b50508e0e2bf85f97a1ac281ed1f1425ad769816
https://github.com/yaxia/json-edm-parser/blob/b50508e0e2bf85f97a1ac281ed1f1425ad769816/parser.js#L47-L82
47,238
theThings/jailed-node
lib/JailedSite.js
JailedSite
function JailedSite(connection) { this._interface = {} this._remote = null this._remoteUpdateHandler = function() { } this._getInterfaceHandler = function() { } this._interfaceSetAsRemoteHandler = function() { } this._disconnectHandler = function() { } this._store = new ReferenceStore var _this = this this._connection = connection this._connection.onMessage( function(data) { _this._processMessage(data) } ) this._connection.onDisconnect( function(m) { _this._disconnectHandler(m) } ) }
javascript
function JailedSite(connection) { this._interface = {} this._remote = null this._remoteUpdateHandler = function() { } this._getInterfaceHandler = function() { } this._interfaceSetAsRemoteHandler = function() { } this._disconnectHandler = function() { } this._store = new ReferenceStore var _this = this this._connection = connection this._connection.onMessage( function(data) { _this._processMessage(data) } ) this._connection.onDisconnect( function(m) { _this._disconnectHandler(m) } ) }
[ "function", "JailedSite", "(", "connection", ")", "{", "this", ".", "_interface", "=", "{", "}", "this", ".", "_remote", "=", "null", "this", ".", "_remoteUpdateHandler", "=", "function", "(", ")", "{", "}", "this", ".", "_getInterfaceHandler", "=", "function", "(", ")", "{", "}", "this", ".", "_interfaceSetAsRemoteHandler", "=", "function", "(", ")", "{", "}", "this", ".", "_disconnectHandler", "=", "function", "(", ")", "{", "}", "this", ".", "_store", "=", "new", "ReferenceStore", "var", "_this", "=", "this", "this", ".", "_connection", "=", "connection", "this", ".", "_connection", ".", "onMessage", "(", "function", "(", "data", ")", "{", "_this", ".", "_processMessage", "(", "data", ")", "}", ")", "this", ".", "_connection", ".", "onDisconnect", "(", "function", "(", "m", ")", "{", "_this", ".", "_disconnectHandler", "(", "m", ")", "}", ")", "}" ]
JailedSite object represents a single site in the communication protocol between the application and the plugin @param {Object} connection a special object allowing to send and receive messages from the opposite site (basically it should only provide send() and onMessage() methods)
[ "JailedSite", "object", "represents", "a", "single", "site", "in", "the", "communication", "protocol", "between", "the", "application", "and", "the", "plugin" ]
6e453d97e74fbd1c0b27b982084f6fd7c1aa0173
https://github.com/theThings/jailed-node/blob/6e453d97e74fbd1c0b27b982084f6fd7c1aa0173/lib/JailedSite.js#L15-L41
47,239
edloidas/roll-parser
src/converter.js
convertToAnyRoll
function convertToAnyRoll( object = {}) { const { again, success, fail } = object || {}; if ( isAbsent( again ) && isAbsent( success ) && isAbsent( fail )) { return convertToRoll( object ); } // else return convertToWodRoll( object ); }
javascript
function convertToAnyRoll( object = {}) { const { again, success, fail } = object || {}; if ( isAbsent( again ) && isAbsent( success ) && isAbsent( fail )) { return convertToRoll( object ); } // else return convertToWodRoll( object ); }
[ "function", "convertToAnyRoll", "(", "object", "=", "{", "}", ")", "{", "const", "{", "again", ",", "success", ",", "fail", "}", "=", "object", "||", "{", "}", ";", "if", "(", "isAbsent", "(", "again", ")", "&&", "isAbsent", "(", "success", ")", "&&", "isAbsent", "(", "fail", ")", ")", "{", "return", "convertToRoll", "(", "object", ")", ";", "}", "// else", "return", "convertToWodRoll", "(", "object", ")", ";", "}" ]
Converts any arguments to `Roll` or `WodRoll` object. If passed argument has `again`, `success` or `fail` property, the function will return `WodRoll`. Otherwise, `Roll` will be returned. @func @alias convert @since v2.1.0 @param {Object} object - `Roll`, `WodRoll` or similar object. @return {Roll|WodRoll} Result of converion. @example convert({ dice: 6 }); //=> new Roll( 6 ) convert({ modifier: 6 }); //=> new Roll( undefined, undefined, 6 ) convert({ dice: 10, count: 5, success: 5 }); //=> new WodRoll( 10, 5, undefined, 5 )
[ "Converts", "any", "arguments", "to", "Roll", "or", "WodRoll", "object", ".", "If", "passed", "argument", "has", "again", "success", "or", "fail", "property", "the", "function", "will", "return", "WodRoll", ".", "Otherwise", "Roll", "will", "be", "returned", "." ]
38912b298edb0a4d67ba1c796d7ac159ebaf7901
https://github.com/edloidas/roll-parser/blob/38912b298edb0a4d67ba1c796d7ac159ebaf7901/src/converter.js#L32-L39
47,240
nightswapping/ng-image-upload
dist/ng-image-upload-template-in.js
imageFilter
function imageFilter (item /*{File|FileLikeObject}*/, options) { var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|'; if ('|jpg|png|jpeg|bmp|gif|'.indexOf(type) === -1) { var err = new Error('File extension not supported (' + type + ')'); vm.onUploadFinished(err); throw err; } return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; }
javascript
function imageFilter (item /*{File|FileLikeObject}*/, options) { var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|'; if ('|jpg|png|jpeg|bmp|gif|'.indexOf(type) === -1) { var err = new Error('File extension not supported (' + type + ')'); vm.onUploadFinished(err); throw err; } return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; }
[ "function", "imageFilter", "(", "item", "/*{File|FileLikeObject}*/", ",", "options", ")", "{", "var", "type", "=", "'|'", "+", "item", ".", "type", ".", "slice", "(", "item", ".", "type", ".", "lastIndexOf", "(", "'/'", ")", "+", "1", ")", "+", "'|'", ";", "if", "(", "'|jpg|png|jpeg|bmp|gif|'", ".", "indexOf", "(", "type", ")", "===", "-", "1", ")", "{", "var", "err", "=", "new", "Error", "(", "'File extension not supported ('", "+", "type", "+", "')'", ")", ";", "vm", ".", "onUploadFinished", "(", "err", ")", ";", "throw", "err", ";", "}", "return", "'|jpg|png|jpeg|bmp|gif|'", ".", "indexOf", "(", "type", ")", "!==", "-", "1", ";", "}" ]
Set up filters to check that images should be uploaded before uploading them Filters out the items that are not pictures
[ "Set", "up", "filters", "to", "check", "that", "images", "should", "be", "uploaded", "before", "uploading", "them", "Filters", "out", "the", "items", "that", "are", "not", "pictures" ]
fd23bdc436651c3caff1917524c461bd7d2482ea
https://github.com/nightswapping/ng-image-upload/blob/fd23bdc436651c3caff1917524c461bd7d2482ea/dist/ng-image-upload-template-in.js#L37-L46
47,241
nightswapping/ng-image-upload
dist/ng-image-upload-template-in.js
sizeFilter
function sizeFilter (item /*{File|FileLikeObject}*/, options) { var size = item.size, // Use passed size limit or default to 10MB sizeLimit = vm.sizeLimit || 10 * 1000 * 1000; if (size > sizeLimit) { var err = new Error('File too big (' + size + ')'); vm.onUploadFinished(err); throw err; } return size < sizeLimit; }
javascript
function sizeFilter (item /*{File|FileLikeObject}*/, options) { var size = item.size, // Use passed size limit or default to 10MB sizeLimit = vm.sizeLimit || 10 * 1000 * 1000; if (size > sizeLimit) { var err = new Error('File too big (' + size + ')'); vm.onUploadFinished(err); throw err; } return size < sizeLimit; }
[ "function", "sizeFilter", "(", "item", "/*{File|FileLikeObject}*/", ",", "options", ")", "{", "var", "size", "=", "item", ".", "size", ",", "// Use passed size limit or default to 10MB", "sizeLimit", "=", "vm", ".", "sizeLimit", "||", "10", "*", "1000", "*", "1000", ";", "if", "(", "size", ">", "sizeLimit", ")", "{", "var", "err", "=", "new", "Error", "(", "'File too big ('", "+", "size", "+", "')'", ")", ";", "vm", ".", "onUploadFinished", "(", "err", ")", ";", "throw", "err", ";", "}", "return", "size", "<", "sizeLimit", ";", "}" ]
Filters out images that are larger than the specified or default limit
[ "Filters", "out", "images", "that", "are", "larger", "than", "the", "specified", "or", "default", "limit" ]
fd23bdc436651c3caff1917524c461bd7d2482ea
https://github.com/nightswapping/ng-image-upload/blob/fd23bdc436651c3caff1917524c461bd7d2482ea/dist/ng-image-upload-template-in.js#L49-L59
47,242
nightswapping/ng-image-upload
dist/ng-image-upload-template-in.js
onLoad
function onLoad(event) { var img = new Image(); img.onload = utils.getDimensions(canvas, vm.$storage); img.src = event.target.result; }
javascript
function onLoad(event) { var img = new Image(); img.onload = utils.getDimensions(canvas, vm.$storage); img.src = event.target.result; }
[ "function", "onLoad", "(", "event", ")", "{", "var", "img", "=", "new", "Image", "(", ")", ";", "img", ".", "onload", "=", "utils", ".", "getDimensions", "(", "canvas", ",", "vm", ".", "$storage", ")", ";", "img", ".", "src", "=", "event", ".", "target", ".", "result", ";", "}" ]
Wait for the reader to be loaded to get the right img.src
[ "Wait", "for", "the", "reader", "to", "be", "loaded", "to", "get", "the", "right", "img", ".", "src" ]
fd23bdc436651c3caff1917524c461bd7d2482ea
https://github.com/nightswapping/ng-image-upload/blob/fd23bdc436651c3caff1917524c461bd7d2482ea/dist/ng-image-upload-template-in.js#L131-L135
47,243
nightswapping/ng-image-upload
dist/ng-image-upload-template-in.js
function(file) { var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; }
javascript
function(file) { var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; }
[ "function", "(", "file", ")", "{", "var", "type", "=", "'|'", "+", "file", ".", "type", ".", "slice", "(", "file", ".", "type", ".", "lastIndexOf", "(", "'/'", ")", "+", "1", ")", "+", "'|'", ";", "return", "'|jpg|png|jpeg|bmp|gif|'", ".", "indexOf", "(", "type", ")", "!==", "-", "1", ";", "}" ]
Checks if the item is jpg, png, jpeg, bmp or a gif
[ "Checks", "if", "the", "item", "is", "jpg", "png", "jpeg", "bmp", "or", "a", "gif" ]
fd23bdc436651c3caff1917524c461bd7d2482ea
https://github.com/nightswapping/ng-image-upload/blob/fd23bdc436651c3caff1917524c461bd7d2482ea/dist/ng-image-upload-template-in.js#L301-L304
47,244
nightswapping/ng-image-upload
dist/ng-image-upload-template-in.js
function(dataURI) { var binary = atob(dataURI.split(',')[1]); var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([ new Uint8Array(array) ], { type: mimeString }); }
javascript
function(dataURI) { var binary = atob(dataURI.split(',')[1]); var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([ new Uint8Array(array) ], { type: mimeString }); }
[ "function", "(", "dataURI", ")", "{", "var", "binary", "=", "atob", "(", "dataURI", ".", "split", "(", "','", ")", "[", "1", "]", ")", ";", "var", "mimeString", "=", "dataURI", ".", "split", "(", "','", ")", "[", "0", "]", ".", "split", "(", "':'", ")", "[", "1", "]", ".", "split", "(", "';'", ")", "[", "0", "]", ";", "var", "array", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "binary", ".", "length", ";", "i", "++", ")", "{", "array", ".", "push", "(", "binary", ".", "charCodeAt", "(", "i", ")", ")", ";", "}", "return", "new", "Blob", "(", "[", "new", "Uint8Array", "(", "array", ")", "]", ",", "{", "type", ":", "mimeString", "}", ")", ";", "}" ]
Turns the Data URI into a blob so it can be sent over to the server
[ "Turns", "the", "Data", "URI", "into", "a", "blob", "so", "it", "can", "be", "sent", "over", "to", "the", "server" ]
fd23bdc436651c3caff1917524c461bd7d2482ea
https://github.com/nightswapping/ng-image-upload/blob/fd23bdc436651c3caff1917524c461bd7d2482ea/dist/ng-image-upload-template-in.js#L308-L318
47,245
rlivsey/fireplace
addon/model/promise-model.js
observePromise
function observePromise(proxy, promise) { promise.then(value => { set(proxy, 'isFulfilled', true); value._settingFromFirebase = true; set(proxy, 'content', value); value._settingFromFirebase = false; }, reason => { set(proxy, 'isRejected', true); set(proxy, 'reason', reason); // don't re-throw, as we are merely observing }); }
javascript
function observePromise(proxy, promise) { promise.then(value => { set(proxy, 'isFulfilled', true); value._settingFromFirebase = true; set(proxy, 'content', value); value._settingFromFirebase = false; }, reason => { set(proxy, 'isRejected', true); set(proxy, 'reason', reason); // don't re-throw, as we are merely observing }); }
[ "function", "observePromise", "(", "proxy", ",", "promise", ")", "{", "promise", ".", "then", "(", "value", "=>", "{", "set", "(", "proxy", ",", "'isFulfilled'", ",", "true", ")", ";", "value", ".", "_settingFromFirebase", "=", "true", ";", "set", "(", "proxy", ",", "'content'", ",", "value", ")", ";", "value", ".", "_settingFromFirebase", "=", "false", ";", "}", ",", "reason", "=>", "{", "set", "(", "proxy", ",", "'isRejected'", ",", "true", ")", ";", "set", "(", "proxy", ",", "'reason'", ",", "reason", ")", ";", "// don't re-throw, as we are merely observing", "}", ")", ";", "}" ]
reimplemented private method from Ember, but with setting _settingFromFirebase so we can avoid extra saves down the line
[ "reimplemented", "private", "method", "from", "Ember", "but", "with", "setting", "_settingFromFirebase", "so", "we", "can", "avoid", "extra", "saves", "down", "the", "line" ]
76cb3288dd99fd420b03547322b64b169caf595c
https://github.com/rlivsey/fireplace/blob/76cb3288dd99fd420b03547322b64b169caf595c/addon/model/promise-model.js#L10-L21
47,246
open-nata/apkparser
src/index.js
parse
async function parse(apkPath, target = `${os.tmpdir()}/apktoolDecodes`) { const cmd = `java -jar ${apktoolPath} d ${apkPath} -f -o ${target}` await shell(cmd) const MainfestFilePath = `${target}/AndroidManifest.xml` const doc = await parseManifest(MainfestFilePath) return parseDoc(doc) }
javascript
async function parse(apkPath, target = `${os.tmpdir()}/apktoolDecodes`) { const cmd = `java -jar ${apktoolPath} d ${apkPath} -f -o ${target}` await shell(cmd) const MainfestFilePath = `${target}/AndroidManifest.xml` const doc = await parseManifest(MainfestFilePath) return parseDoc(doc) }
[ "async", "function", "parse", "(", "apkPath", ",", "target", "=", "`", "${", "os", ".", "tmpdir", "(", ")", "}", "`", ")", "{", "const", "cmd", "=", "`", "${", "apktoolPath", "}", "${", "apkPath", "}", "${", "target", "}", "`", "await", "shell", "(", "cmd", ")", "const", "MainfestFilePath", "=", "`", "${", "target", "}", "`", "const", "doc", "=", "await", "parseManifest", "(", "MainfestFilePath", ")", "return", "parseDoc", "(", "doc", ")", "}" ]
parse apk and return manifest @param {String} apkPath apk path @param {String} target target extract dir, default to ${os.tmpdir()}/apktoolDecodes @return {Promise} resolve manifest
[ "parse", "apk", "and", "return", "manifest" ]
ca1e7bfc67ecaf094316d1cf949d88b84fd9928d
https://github.com/open-nata/apkparser/blob/ca1e7bfc67ecaf094316d1cf949d88b84fd9928d/src/index.js#L98-L104
47,247
VisionistInc/jibe
lib/models/Room.js
uniquenessValidator
function uniquenessValidator(values) { if (values.presentAuthors) { values = values.presentAuthors; } values.sort(); for (var i = 0; i < values.length - 1; i++) { if (values[i] === values[i+1]) { // can throw error or return false // error allows supplying more detail throw new Error('Duplicate value [' + values[i] + '] found in Room.presentAuthors'); } } return true; }
javascript
function uniquenessValidator(values) { if (values.presentAuthors) { values = values.presentAuthors; } values.sort(); for (var i = 0; i < values.length - 1; i++) { if (values[i] === values[i+1]) { // can throw error or return false // error allows supplying more detail throw new Error('Duplicate value [' + values[i] + '] found in Room.presentAuthors'); } } return true; }
[ "function", "uniquenessValidator", "(", "values", ")", "{", "if", "(", "values", ".", "presentAuthors", ")", "{", "values", "=", "values", ".", "presentAuthors", ";", "}", "values", ".", "sort", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "values", ".", "length", "-", "1", ";", "i", "++", ")", "{", "if", "(", "values", "[", "i", "]", "===", "values", "[", "i", "+", "1", "]", ")", "{", "// can throw error or return false", "// error allows supplying more detail", "throw", "new", "Error", "(", "'Duplicate value ['", "+", "values", "[", "i", "]", "+", "'] found in Room.presentAuthors'", ")", ";", "}", "}", "return", "true", ";", "}" ]
are all values unique?
[ "are", "all", "values", "unique?" ]
3a154c0d86a3bcf8980c5104daec099ec738a4e0
https://github.com/VisionistInc/jibe/blob/3a154c0d86a3bcf8980c5104daec099ec738a4e0/lib/models/Room.js#L59-L74
47,248
alexyoung/pop
lib/pop.js
loadConfig
function loadConfig() { var root = process.cwd() , config = readConfig(path.join(root, '_config.json')); config.root = root; return config; }
javascript
function loadConfig() { var root = process.cwd() , config = readConfig(path.join(root, '_config.json')); config.root = root; return config; }
[ "function", "loadConfig", "(", ")", "{", "var", "root", "=", "process", ".", "cwd", "(", ")", ",", "config", "=", "readConfig", "(", "path", ".", "join", "(", "root", ",", "'_config.json'", ")", ")", ";", "config", ".", "root", "=", "root", ";", "return", "config", ";", "}" ]
Loads the config script and sets the local variable. @return {Object} Config object
[ "Loads", "the", "config", "script", "and", "sets", "the", "local", "variable", "." ]
8a0b3f2605cb58e8ae6b34f1373dde00610e9858
https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/pop.js#L23-L28
47,249
alexyoung/pop
lib/pop.js
loadConfigAndGenerateSite
function loadConfigAndGenerateSite(useServer, port) { var config = loadConfig(); if (port) config.port = port; generateSite(config, useServer); }
javascript
function loadConfigAndGenerateSite(useServer, port) { var config = loadConfig(); if (port) config.port = port; generateSite(config, useServer); }
[ "function", "loadConfigAndGenerateSite", "(", "useServer", ",", "port", ")", "{", "var", "config", "=", "loadConfig", "(", ")", ";", "if", "(", "port", ")", "config", ".", "port", "=", "port", ";", "generateSite", "(", "config", ",", "useServer", ")", ";", "}" ]
Loads configuration then runs `generateSite`. @params {Boolean} Use a HTTP sever?
[ "Loads", "configuration", "then", "runs", "generateSite", "." ]
8a0b3f2605cb58e8ae6b34f1373dde00610e9858
https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/pop.js#L35-L39
47,250
alexyoung/pop
lib/pop.js
generateSite
function generateSite(config, useServer) { var fileMap = new FileMap(config) , siteBuilder = new SiteBuilder(config) , server = require(__dirname + '/server')(siteBuilder); fileMap.walk(); fileMap.on('ready', function() { siteBuilder.fileMap = fileMap; siteBuilder.build(); }); siteBuilder.once('ready', function() { if (useServer) { server.run(); server.watch(); } }); return siteBuilder; }
javascript
function generateSite(config, useServer) { var fileMap = new FileMap(config) , siteBuilder = new SiteBuilder(config) , server = require(__dirname + '/server')(siteBuilder); fileMap.walk(); fileMap.on('ready', function() { siteBuilder.fileMap = fileMap; siteBuilder.build(); }); siteBuilder.once('ready', function() { if (useServer) { server.run(); server.watch(); } }); return siteBuilder; }
[ "function", "generateSite", "(", "config", ",", "useServer", ")", "{", "var", "fileMap", "=", "new", "FileMap", "(", "config", ")", ",", "siteBuilder", "=", "new", "SiteBuilder", "(", "config", ")", ",", "server", "=", "require", "(", "__dirname", "+", "'/server'", ")", "(", "siteBuilder", ")", ";", "fileMap", ".", "walk", "(", ")", ";", "fileMap", ".", "on", "(", "'ready'", ",", "function", "(", ")", "{", "siteBuilder", ".", "fileMap", "=", "fileMap", ";", "siteBuilder", ".", "build", "(", ")", ";", "}", ")", ";", "siteBuilder", ".", "once", "(", "'ready'", ",", "function", "(", ")", "{", "if", "(", "useServer", ")", "{", "server", ".", "run", "(", ")", ";", "server", ".", "watch", "(", ")", ";", "}", "}", ")", ";", "return", "siteBuilder", ";", "}" ]
Runs `FileMap` and `SiteBuilder` based on the config. @params {Object} Configuration options @params {Boolean} Use a HTTP sever? @return {SiteBuilder} A `SiteBuilder` instance
[ "Runs", "FileMap", "and", "SiteBuilder", "based", "on", "the", "config", "." ]
8a0b3f2605cb58e8ae6b34f1373dde00610e9858
https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/pop.js#L48-L67
47,251
krundru/webdriver-runner
lib/util.js
saveScreenshot
function saveScreenshot(driver, dir, testTitle) { const data = driver.takeScreenshot() const fileName = testTitle.replace(/[^a-zA-Z0-9]/g, '_') .concat('_') .concat(new Date().getTime()) .concat('.png') const fullPath = path.resolve(dir, fileName) fs.writeFileSync(fullPath, data, 'base64') reportOutput({ type: 'image', name: fileName, file: fullPath }) }
javascript
function saveScreenshot(driver, dir, testTitle) { const data = driver.takeScreenshot() const fileName = testTitle.replace(/[^a-zA-Z0-9]/g, '_') .concat('_') .concat(new Date().getTime()) .concat('.png') const fullPath = path.resolve(dir, fileName) fs.writeFileSync(fullPath, data, 'base64') reportOutput({ type: 'image', name: fileName, file: fullPath }) }
[ "function", "saveScreenshot", "(", "driver", ",", "dir", ",", "testTitle", ")", "{", "const", "data", "=", "driver", ".", "takeScreenshot", "(", ")", "const", "fileName", "=", "testTitle", ".", "replace", "(", "/", "[^a-zA-Z0-9]", "/", "g", ",", "'_'", ")", ".", "concat", "(", "'_'", ")", ".", "concat", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", ".", "concat", "(", "'.png'", ")", "const", "fullPath", "=", "path", ".", "resolve", "(", "dir", ",", "fileName", ")", "fs", ".", "writeFileSync", "(", "fullPath", ",", "data", ",", "'base64'", ")", "reportOutput", "(", "{", "type", ":", "'image'", ",", "name", ":", "fileName", ",", "file", ":", "fullPath", "}", ")", "}" ]
Saves current screenshot from driver. fileName is resolved from testTitle and saved under given directory. And the same is reported to test-result report with `image` type. Ex: if (this.currentTest.state !== 'failed') { wdUtil.saveScreenshot(driver, './', this.currentTest.title) } @param {Driver} driver sync'ed webdriver @param {String} dir directory under which screenshot will be stored @param {String} testTitle current test title for resolving fileName
[ "Saves", "current", "screenshot", "from", "driver", ".", "fileName", "is", "resolved", "from", "testTitle", "and", "saved", "under", "given", "directory", "." ]
fb9db651966f546d0f6864b317475f805db86a12
https://github.com/krundru/webdriver-runner/blob/fb9db651966f546d0f6864b317475f805db86a12/lib/util.js#L19-L33
47,252
cjoudrey/wobot
lib/bot.js
function() { var self = this; self.jabber.on('data', function(buffer) { console.log(' IN > ' + buffer.toString()); }); var origSend = this.jabber.send; self.jabber.send = function(stanza) { console.log(' OUT > ' + stanza); return origSend.call(self.jabber, stanza); }; }
javascript
function() { var self = this; self.jabber.on('data', function(buffer) { console.log(' IN > ' + buffer.toString()); }); var origSend = this.jabber.send; self.jabber.send = function(stanza) { console.log(' OUT > ' + stanza); return origSend.call(self.jabber, stanza); }; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "self", ".", "jabber", ".", "on", "(", "'data'", ",", "function", "(", "buffer", ")", "{", "console", ".", "log", "(", "' IN > '", "+", "buffer", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "var", "origSend", "=", "this", ".", "jabber", ".", "send", ";", "self", ".", "jabber", ".", "send", "=", "function", "(", "stanza", ")", "{", "console", ".", "log", "(", "' OUT > '", "+", "stanza", ")", ";", "return", "origSend", ".", "call", "(", "self", ".", "jabber", ",", "stanza", ")", ";", "}", ";", "}" ]
Helper function that overrides the XMPP `send` method to allow incoming and outgoing debugging.
[ "Helper", "function", "that", "overrides", "the", "XMPP", "send", "method", "to", "allow", "incoming", "and", "outgoing", "debugging", "." ]
7f044ec5e02a0707c637ce9bf5d77028796cda39
https://github.com/cjoudrey/wobot/blob/7f044ec5e02a0707c637ce9bf5d77028796cda39/lib/bot.js#L38-L50
47,253
cjoudrey/wobot
lib/bot.js
function() { var self = this; this.setAvailability('chat'); this.keepalive = setInterval(function() { self.jabber.send(new xmpp.Message({})); self.emit('ping'); }, 30000); // load our profile to get name this.getProfile(function(err, data) { if (err) { // This isn't technically a stream error which is what the `error` // event usually represents, but we want to treat a profile fetch // error as a fatal error and disconnect the bot. self.emit('error', null, 'Unable to get profile info: ' + err, null); return; } // now that we have our name we can let rooms be joined self.name = data.fn; // this is the name used to @mention us self.mention_name = data.nickname; self.emit('connect'); }); }
javascript
function() { var self = this; this.setAvailability('chat'); this.keepalive = setInterval(function() { self.jabber.send(new xmpp.Message({})); self.emit('ping'); }, 30000); // load our profile to get name this.getProfile(function(err, data) { if (err) { // This isn't technically a stream error which is what the `error` // event usually represents, but we want to treat a profile fetch // error as a fatal error and disconnect the bot. self.emit('error', null, 'Unable to get profile info: ' + err, null); return; } // now that we have our name we can let rooms be joined self.name = data.fn; // this is the name used to @mention us self.mention_name = data.nickname; self.emit('connect'); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "this", ".", "setAvailability", "(", "'chat'", ")", ";", "this", ".", "keepalive", "=", "setInterval", "(", "function", "(", ")", "{", "self", ".", "jabber", ".", "send", "(", "new", "xmpp", ".", "Message", "(", "{", "}", ")", ")", ";", "self", ".", "emit", "(", "'ping'", ")", ";", "}", ",", "30000", ")", ";", "// load our profile to get name", "this", ".", "getProfile", "(", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "// This isn't technically a stream error which is what the `error`", "// event usually represents, but we want to treat a profile fetch", "// error as a fatal error and disconnect the bot.", "self", ".", "emit", "(", "'error'", ",", "null", ",", "'Unable to get profile info: '", "+", "err", ",", "null", ")", ";", "return", ";", "}", "// now that we have our name we can let rooms be joined", "self", ".", "name", "=", "data", ".", "fn", ";", "// this is the name used to @mention us", "self", ".", "mention_name", "=", "data", ".", "nickname", ";", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "}" ]
Whenever an XMPP connection is made, this function is responsible for triggering the `connect` event and starting the 30s anti-idle. It will also set the availability of the bot to `chat`.
[ "Whenever", "an", "XMPP", "connection", "is", "made", "this", "function", "is", "responsible", "for", "triggering", "the", "connect", "event", "and", "starting", "the", "30s", "anti", "-", "idle", ".", "It", "will", "also", "set", "the", "availability", "of", "the", "bot", "to", "chat", "." ]
7f044ec5e02a0707c637ce9bf5d77028796cda39
https://github.com/cjoudrey/wobot/blob/7f044ec5e02a0707c637ce9bf5d77028796cda39/lib/bot.js#L61-L88
47,254
cjoudrey/wobot
lib/bot.js
function(stanza) { this.emit('data', stanza); if (stanza.is('message') && stanza.attrs.type === 'groupchat') { var body = stanza.getChildText('body'); if (!body) return; // Ignore chat history if (stanza.getChild('delay')) return; var fromJid = new xmpp.JID(stanza.attrs.from); var fromChannel = fromJid.bare().toString(); var fromNick = fromJid.resource; // Ignore our own messages if (fromNick === this.name) return; this.emit('message', fromChannel, fromNick, body); } else if (stanza.is('message') && stanza.attrs.type === 'chat') { // Message without body is probably a typing notification var body = stanza.getChildText('body'); if (!body) return; var fromJid = new xmpp.JID(stanza.attrs.from); this.emit('privateMessage', fromJid.bare().toString(), body); } else if (stanza.is('message') && !stanza.attrs.type) { // TODO: It'd be great if we could have some sort of xpath-based listener // so we could just watch for '/message/x/invite' stanzas instead of // doing all this manual getChild nonsense. var x = stanza.getChild('x', 'http://jabber.org/protocol/muc#user'); if (!x) return; var invite = x.getChild('invite'); if (!invite) return; var reason = invite.getChildText('reason'); var inviteRoom = new xmpp.JID(stanza.attrs.from); var inviteSender = new xmpp.JID(invite.attrs.from); this.emit('invite', inviteRoom.bare(), inviteSender.bare(), reason); } else if (stanza.is('iq')) { // Handle a response to an IQ request var event_id = 'iq:' + stanza.attrs.id; if (stanza.attrs.type === 'result') { this.emit(event_id, null, stanza); } else { // IQ error response // ex: http://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-result var condition = 'unknown'; var error_elem = stanza.getChild('error'); if (error_elem) { condition = error_elem.children[0].name; } this.emit(event_id, condition, stanza); } } }
javascript
function(stanza) { this.emit('data', stanza); if (stanza.is('message') && stanza.attrs.type === 'groupchat') { var body = stanza.getChildText('body'); if (!body) return; // Ignore chat history if (stanza.getChild('delay')) return; var fromJid = new xmpp.JID(stanza.attrs.from); var fromChannel = fromJid.bare().toString(); var fromNick = fromJid.resource; // Ignore our own messages if (fromNick === this.name) return; this.emit('message', fromChannel, fromNick, body); } else if (stanza.is('message') && stanza.attrs.type === 'chat') { // Message without body is probably a typing notification var body = stanza.getChildText('body'); if (!body) return; var fromJid = new xmpp.JID(stanza.attrs.from); this.emit('privateMessage', fromJid.bare().toString(), body); } else if (stanza.is('message') && !stanza.attrs.type) { // TODO: It'd be great if we could have some sort of xpath-based listener // so we could just watch for '/message/x/invite' stanzas instead of // doing all this manual getChild nonsense. var x = stanza.getChild('x', 'http://jabber.org/protocol/muc#user'); if (!x) return; var invite = x.getChild('invite'); if (!invite) return; var reason = invite.getChildText('reason'); var inviteRoom = new xmpp.JID(stanza.attrs.from); var inviteSender = new xmpp.JID(invite.attrs.from); this.emit('invite', inviteRoom.bare(), inviteSender.bare(), reason); } else if (stanza.is('iq')) { // Handle a response to an IQ request var event_id = 'iq:' + stanza.attrs.id; if (stanza.attrs.type === 'result') { this.emit(event_id, null, stanza); } else { // IQ error response // ex: http://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-result var condition = 'unknown'; var error_elem = stanza.getChild('error'); if (error_elem) { condition = error_elem.children[0].name; } this.emit(event_id, condition, stanza); } } }
[ "function", "(", "stanza", ")", "{", "this", ".", "emit", "(", "'data'", ",", "stanza", ")", ";", "if", "(", "stanza", ".", "is", "(", "'message'", ")", "&&", "stanza", ".", "attrs", ".", "type", "===", "'groupchat'", ")", "{", "var", "body", "=", "stanza", ".", "getChildText", "(", "'body'", ")", ";", "if", "(", "!", "body", ")", "return", ";", "// Ignore chat history", "if", "(", "stanza", ".", "getChild", "(", "'delay'", ")", ")", "return", ";", "var", "fromJid", "=", "new", "xmpp", ".", "JID", "(", "stanza", ".", "attrs", ".", "from", ")", ";", "var", "fromChannel", "=", "fromJid", ".", "bare", "(", ")", ".", "toString", "(", ")", ";", "var", "fromNick", "=", "fromJid", ".", "resource", ";", "// Ignore our own messages", "if", "(", "fromNick", "===", "this", ".", "name", ")", "return", ";", "this", ".", "emit", "(", "'message'", ",", "fromChannel", ",", "fromNick", ",", "body", ")", ";", "}", "else", "if", "(", "stanza", ".", "is", "(", "'message'", ")", "&&", "stanza", ".", "attrs", ".", "type", "===", "'chat'", ")", "{", "// Message without body is probably a typing notification", "var", "body", "=", "stanza", ".", "getChildText", "(", "'body'", ")", ";", "if", "(", "!", "body", ")", "return", ";", "var", "fromJid", "=", "new", "xmpp", ".", "JID", "(", "stanza", ".", "attrs", ".", "from", ")", ";", "this", ".", "emit", "(", "'privateMessage'", ",", "fromJid", ".", "bare", "(", ")", ".", "toString", "(", ")", ",", "body", ")", ";", "}", "else", "if", "(", "stanza", ".", "is", "(", "'message'", ")", "&&", "!", "stanza", ".", "attrs", ".", "type", ")", "{", "// TODO: It'd be great if we could have some sort of xpath-based listener", "// so we could just watch for '/message/x/invite' stanzas instead of", "// doing all this manual getChild nonsense.", "var", "x", "=", "stanza", ".", "getChild", "(", "'x'", ",", "'http://jabber.org/protocol/muc#user'", ")", ";", "if", "(", "!", "x", ")", "return", ";", "var", "invite", "=", "x", ".", "getChild", "(", "'invite'", ")", ";", "if", "(", "!", "invite", ")", "return", ";", "var", "reason", "=", "invite", ".", "getChildText", "(", "'reason'", ")", ";", "var", "inviteRoom", "=", "new", "xmpp", ".", "JID", "(", "stanza", ".", "attrs", ".", "from", ")", ";", "var", "inviteSender", "=", "new", "xmpp", ".", "JID", "(", "invite", ".", "attrs", ".", "from", ")", ";", "this", ".", "emit", "(", "'invite'", ",", "inviteRoom", ".", "bare", "(", ")", ",", "inviteSender", ".", "bare", "(", ")", ",", "reason", ")", ";", "}", "else", "if", "(", "stanza", ".", "is", "(", "'iq'", ")", ")", "{", "// Handle a response to an IQ request", "var", "event_id", "=", "'iq:'", "+", "stanza", ".", "attrs", ".", "id", ";", "if", "(", "stanza", ".", "attrs", ".", "type", "===", "'result'", ")", "{", "this", ".", "emit", "(", "event_id", ",", "null", ",", "stanza", ")", ";", "}", "else", "{", "// IQ error response", "// ex: http://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-result", "var", "condition", "=", "'unknown'", ";", "var", "error_elem", "=", "stanza", ".", "getChild", "(", "'error'", ")", ";", "if", "(", "error_elem", ")", "{", "condition", "=", "error_elem", ".", "children", "[", "0", "]", ".", "name", ";", "}", "this", ".", "emit", "(", "event_id", ",", "condition", ",", "stanza", ")", ";", "}", "}", "}" ]
This function is responsible for handling incoming XMPP messages. The `data` event will be triggered with the message for custom XMPP handling. The bot will parse the message and trigger the `message` event when it is a group chat message or the `privateMessage` event when it is a private message.
[ "This", "function", "is", "responsible", "for", "handling", "incoming", "XMPP", "messages", ".", "The", "data", "event", "will", "be", "triggered", "with", "the", "message", "for", "custom", "XMPP", "handling", ".", "The", "bot", "will", "parse", "the", "message", "and", "trigger", "the", "message", "event", "when", "it", "is", "a", "group", "chat", "message", "or", "the", "privateMessage", "event", "when", "it", "is", "a", "private", "message", "." ]
7f044ec5e02a0707c637ce9bf5d77028796cda39
https://github.com/cjoudrey/wobot/blob/7f044ec5e02a0707c637ce9bf5d77028796cda39/lib/bot.js#L97-L153
47,255
SLaks/csrf-crypto
csrf-crypto.js
getCookieToken
function getCookieToken(res) { var value = res.req.cookies[cookieName(res.req)]; if (!value) return false; var parts = value.split('|'); // If the existing cookie is invalid, reject it. if (parts.length !== 3) return false; // If the user data doesn't match this request's user, reject the cookie if (parts[1] !== getUserData(res.req)) return false; var hasher = crypto.createHmac(options.algorithm, cookieKey); hasher.update(parts[0]); hasher.update("|"); // Don't confuse longer or shorter userDatas hasher.update(parts[1]); // If the hash doesn't match, reject the cookie if (parts[2] !== hasher.digest('base64')) return false; return parts[0]; }
javascript
function getCookieToken(res) { var value = res.req.cookies[cookieName(res.req)]; if (!value) return false; var parts = value.split('|'); // If the existing cookie is invalid, reject it. if (parts.length !== 3) return false; // If the user data doesn't match this request's user, reject the cookie if (parts[1] !== getUserData(res.req)) return false; var hasher = crypto.createHmac(options.algorithm, cookieKey); hasher.update(parts[0]); hasher.update("|"); // Don't confuse longer or shorter userDatas hasher.update(parts[1]); // If the hash doesn't match, reject the cookie if (parts[2] !== hasher.digest('base64')) return false; return parts[0]; }
[ "function", "getCookieToken", "(", "res", ")", "{", "var", "value", "=", "res", ".", "req", ".", "cookies", "[", "cookieName", "(", "res", ".", "req", ")", "]", ";", "if", "(", "!", "value", ")", "return", "false", ";", "var", "parts", "=", "value", ".", "split", "(", "'|'", ")", ";", "// If the existing cookie is invalid, reject it.", "if", "(", "parts", ".", "length", "!==", "3", ")", "return", "false", ";", "// If the user data doesn't match this request's user, reject the cookie", "if", "(", "parts", "[", "1", "]", "!==", "getUserData", "(", "res", ".", "req", ")", ")", "return", "false", ";", "var", "hasher", "=", "crypto", ".", "createHmac", "(", "options", ".", "algorithm", ",", "cookieKey", ")", ";", "hasher", ".", "update", "(", "parts", "[", "0", "]", ")", ";", "hasher", ".", "update", "(", "\"|\"", ")", ";", "// Don't confuse longer or shorter userDatas", "hasher", ".", "update", "(", "parts", "[", "1", "]", ")", ";", "// If the hash doesn't match, reject the cookie", "if", "(", "parts", "[", "2", "]", "!==", "hasher", ".", "digest", "(", "'base64'", ")", ")", "return", "false", ";", "return", "parts", "[", "0", "]", ";", "}" ]
Private function that finds an existing cookie token and returns its salt value
[ "Private", "function", "that", "finds", "an", "existing", "cookie", "token", "and", "returns", "its", "salt", "value" ]
d6b7cfa76652be74d3692b2080ad668b08556892
https://github.com/SLaks/csrf-crypto/blob/d6b7cfa76652be74d3692b2080ad668b08556892/csrf-crypto.js#L96-L121
47,256
SLaks/csrf-crypto
csrf-crypto.js
getFormToken
function getFormToken() { /*jshint validthis:true */ if (this._csrfFormToken) return this._csrfFormToken; checkSecure(this.req); var cookieToken = getCookieToken(this) || createCookie(this); var salt = base64Random(saltSize); var hasher = crypto.createHmac(options.algorithm, formKey); hasher.update(cookieToken); hasher.update("|"); hasher.update(salt); this._csrfFormToken = salt + "|" + hasher.digest('base64'); return this._csrfFormToken; }
javascript
function getFormToken() { /*jshint validthis:true */ if (this._csrfFormToken) return this._csrfFormToken; checkSecure(this.req); var cookieToken = getCookieToken(this) || createCookie(this); var salt = base64Random(saltSize); var hasher = crypto.createHmac(options.algorithm, formKey); hasher.update(cookieToken); hasher.update("|"); hasher.update(salt); this._csrfFormToken = salt + "|" + hasher.digest('base64'); return this._csrfFormToken; }
[ "function", "getFormToken", "(", ")", "{", "/*jshint validthis:true */", "if", "(", "this", ".", "_csrfFormToken", ")", "return", "this", ".", "_csrfFormToken", ";", "checkSecure", "(", "this", ".", "req", ")", ";", "var", "cookieToken", "=", "getCookieToken", "(", "this", ")", "||", "createCookie", "(", "this", ")", ";", "var", "salt", "=", "base64Random", "(", "saltSize", ")", ";", "var", "hasher", "=", "crypto", ".", "createHmac", "(", "options", ".", "algorithm", ",", "formKey", ")", ";", "hasher", ".", "update", "(", "cookieToken", ")", ";", "hasher", ".", "update", "(", "\"|\"", ")", ";", "hasher", ".", "update", "(", "salt", ")", ";", "this", ".", "_csrfFormToken", "=", "salt", "+", "\"|\"", "+", "hasher", ".", "digest", "(", "'base64'", ")", ";", "return", "this", ".", "_csrfFormToken", ";", "}" ]
Gets a new form token for the current response. This function must be called on the response object. @returns {String} An opaque token to include with new requests.
[ "Gets", "a", "new", "form", "token", "for", "the", "current", "response", ".", "This", "function", "must", "be", "called", "on", "the", "response", "object", "." ]
d6b7cfa76652be74d3692b2080ad668b08556892
https://github.com/SLaks/csrf-crypto/blob/d6b7cfa76652be74d3692b2080ad668b08556892/csrf-crypto.js#L140-L156
47,257
SLaks/csrf-crypto
csrf-crypto.js
verifyFormToken
function verifyFormToken(formToken) { /*jshint validthis:true */ checkSecure(this); // If we already cached this token, we know that it's valid. // If we validate two different tokens for the same request, // this won't incorrectly skip the second one. if (this.res._csrfFormToken && this.res._csrfFormToken === formToken) return true; this._csrfChecked = true; if (!formToken) return false; var cookieToken = getCookieToken(this.res); if (!cookieToken) return false; var parts = formToken.split('|'); // If the token is invalid, reject it. if (parts.length !== 2) return false; var hasher = crypto.createHmac(options.algorithm, formKey); hasher.update(cookieToken); hasher.update("|"); // Don't confuse longer or shorter tokens hasher.update(parts[0]); // If the hash doesn't match, reject the token if (parts[1] !== hasher.digest('base64')) return false; // If we have a valid token, reuse it for this request // instead of generating a new one. (saves crypto ops) if (!this.res._csrfFormToken) this.res._csrfFormToken = formToken; return true; }
javascript
function verifyFormToken(formToken) { /*jshint validthis:true */ checkSecure(this); // If we already cached this token, we know that it's valid. // If we validate two different tokens for the same request, // this won't incorrectly skip the second one. if (this.res._csrfFormToken && this.res._csrfFormToken === formToken) return true; this._csrfChecked = true; if (!formToken) return false; var cookieToken = getCookieToken(this.res); if (!cookieToken) return false; var parts = formToken.split('|'); // If the token is invalid, reject it. if (parts.length !== 2) return false; var hasher = crypto.createHmac(options.algorithm, formKey); hasher.update(cookieToken); hasher.update("|"); // Don't confuse longer or shorter tokens hasher.update(parts[0]); // If the hash doesn't match, reject the token if (parts[1] !== hasher.digest('base64')) return false; // If we have a valid token, reuse it for this request // instead of generating a new one. (saves crypto ops) if (!this.res._csrfFormToken) this.res._csrfFormToken = formToken; return true; }
[ "function", "verifyFormToken", "(", "formToken", ")", "{", "/*jshint validthis:true */", "checkSecure", "(", "this", ")", ";", "// If we already cached this token, we know that it's valid.", "// If we validate two different tokens for the same request,", "// this won't incorrectly skip the second one.", "if", "(", "this", ".", "res", ".", "_csrfFormToken", "&&", "this", ".", "res", ".", "_csrfFormToken", "===", "formToken", ")", "return", "true", ";", "this", ".", "_csrfChecked", "=", "true", ";", "if", "(", "!", "formToken", ")", "return", "false", ";", "var", "cookieToken", "=", "getCookieToken", "(", "this", ".", "res", ")", ";", "if", "(", "!", "cookieToken", ")", "return", "false", ";", "var", "parts", "=", "formToken", ".", "split", "(", "'|'", ")", ";", "// If the token is invalid, reject it.", "if", "(", "parts", ".", "length", "!==", "2", ")", "return", "false", ";", "var", "hasher", "=", "crypto", ".", "createHmac", "(", "options", ".", "algorithm", ",", "formKey", ")", ";", "hasher", ".", "update", "(", "cookieToken", ")", ";", "hasher", ".", "update", "(", "\"|\"", ")", ";", "// Don't confuse longer or shorter tokens", "hasher", ".", "update", "(", "parts", "[", "0", "]", ")", ";", "// If the hash doesn't match, reject the token", "if", "(", "parts", "[", "1", "]", "!==", "hasher", ".", "digest", "(", "'base64'", ")", ")", "return", "false", ";", "// If we have a valid token, reuse it for this request", "// instead of generating a new one. (saves crypto ops)", "if", "(", "!", "this", ".", "res", ".", "_csrfFormToken", ")", "this", ".", "res", ".", "_csrfFormToken", "=", "formToken", ";", "return", "true", ";", "}" ]
Verifies a form token submitted with the current request. This function must be called on the request object. @returns {Boolean} True if the form token matches the cookie in the request.
[ "Verifies", "a", "form", "token", "submitted", "with", "the", "current", "request", ".", "This", "function", "must", "be", "called", "on", "the", "request", "object", "." ]
d6b7cfa76652be74d3692b2080ad668b08556892
https://github.com/SLaks/csrf-crypto/blob/d6b7cfa76652be74d3692b2080ad668b08556892/csrf-crypto.js#L164-L201
47,258
jaymell/nodeCf
src/nodeCf.js
getTemplateFile
async function getTemplateFile(templateDir, stackName) { const f = await Promise.any( _.map(['.yml', '.yaml', '.json', ''], async(ext) => await utils.fileExists(`${path.join(templateDir, stackName)}${ext}`))); if (f) { return f; } throw new Error(`Stack template "${stackName}" not found!`); }
javascript
async function getTemplateFile(templateDir, stackName) { const f = await Promise.any( _.map(['.yml', '.yaml', '.json', ''], async(ext) => await utils.fileExists(`${path.join(templateDir, stackName)}${ext}`))); if (f) { return f; } throw new Error(`Stack template "${stackName}" not found!`); }
[ "async", "function", "getTemplateFile", "(", "templateDir", ",", "stackName", ")", "{", "const", "f", "=", "await", "Promise", ".", "any", "(", "_", ".", "map", "(", "[", "'.yml'", ",", "'.yaml'", ",", "'.json'", ",", "''", "]", ",", "async", "(", "ext", ")", "=>", "await", "utils", ".", "fileExists", "(", "`", "${", "path", ".", "join", "(", "templateDir", ",", "stackName", ")", "}", "${", "ext", "}", "`", ")", ")", ")", ";", "if", "(", "f", ")", "{", "return", "f", ";", "}", "throw", "new", "Error", "(", "`", "${", "stackName", "}", "`", ")", ";", "}" ]
look for template having multiple possible file extensions
[ "look", "for", "template", "having", "multiple", "possible", "file", "extensions" ]
d0f499a1b0adf5c810c33698a66ef16db6bc590d
https://github.com/jaymell/nodeCf/blob/d0f499a1b0adf5c810c33698a66ef16db6bc590d/src/nodeCf.js#L239-L247
47,259
fti-technology/node-skytap
lib/skytap.js
Skytap
function Skytap () { this.audit = new Audit(this); this.environments = new Environments(this); this.ips = new Ips(this); this.networks = new Networks(this); this.projects = new Projects(this); this.templates = new Templates(this); this.usage = new Usage(this); this.users = new Users(this); this.vms = new Vms(this); this.vpns = new Vpns(this); this.getArgs = function getArgs() { return _.clone(this._config); }; }
javascript
function Skytap () { this.audit = new Audit(this); this.environments = new Environments(this); this.ips = new Ips(this); this.networks = new Networks(this); this.projects = new Projects(this); this.templates = new Templates(this); this.usage = new Usage(this); this.users = new Users(this); this.vms = new Vms(this); this.vpns = new Vpns(this); this.getArgs = function getArgs() { return _.clone(this._config); }; }
[ "function", "Skytap", "(", ")", "{", "this", ".", "audit", "=", "new", "Audit", "(", "this", ")", ";", "this", ".", "environments", "=", "new", "Environments", "(", "this", ")", ";", "this", ".", "ips", "=", "new", "Ips", "(", "this", ")", ";", "this", ".", "networks", "=", "new", "Networks", "(", "this", ")", ";", "this", ".", "projects", "=", "new", "Projects", "(", "this", ")", ";", "this", ".", "templates", "=", "new", "Templates", "(", "this", ")", ";", "this", ".", "usage", "=", "new", "Usage", "(", "this", ")", ";", "this", ".", "users", "=", "new", "Users", "(", "this", ")", ";", "this", ".", "vms", "=", "new", "Vms", "(", "this", ")", ";", "this", ".", "vpns", "=", "new", "Vpns", "(", "this", ")", ";", "this", ".", "getArgs", "=", "function", "getArgs", "(", ")", "{", "return", "_", ".", "clone", "(", "this", ".", "_config", ")", ";", "}", ";", "}" ]
Skytap API Library @param {Object} config
[ "Skytap", "API", "Library" ]
1d5af43ee26aabfebe52627ea09f291c99923a49
https://github.com/fti-technology/node-skytap/blob/1d5af43ee26aabfebe52627ea09f291c99923a49/lib/skytap.js#L23-L38
47,260
goliney/coderoom
lib/utils.js
readTemplate
function readTemplate() { return fs.readFileSync(path.resolve.apply(null, [__dirname, settings.paths.templates, ...arguments]), 'utf8'); }
javascript
function readTemplate() { return fs.readFileSync(path.resolve.apply(null, [__dirname, settings.paths.templates, ...arguments]), 'utf8'); }
[ "function", "readTemplate", "(", ")", "{", "return", "fs", ".", "readFileSync", "(", "path", ".", "resolve", ".", "apply", "(", "null", ",", "[", "__dirname", ",", "settings", ".", "paths", ".", "templates", ",", "...", "arguments", "]", ")", ",", "'utf8'", ")", ";", "}" ]
Synchronously read file from templates folder. @param {...string} variative number of paths that form relative path to template @returns {string}
[ "Synchronously", "read", "file", "from", "templates", "folder", "." ]
a8c30d45ae724dfc87348ffba5474cf62c10911c
https://github.com/goliney/coderoom/blob/a8c30d45ae724dfc87348ffba5474cf62c10911c/lib/utils.js#L27-L29
47,261
YR/component
src/index.js
shouldBeStateless
function shouldBeStateless(definition, preferStateless) { if (!preferStateless) { return false; } if (runtime.isServer && (definition.getChildContext === undefined && definition.init === undefined)) { return true; } // Not stateless if contains anything more than render and static properties for (const prop in definition) { if (prop !== 'render' && !~STATIC_KEYS.indexOf(prop)) { return false; } } return true; }
javascript
function shouldBeStateless(definition, preferStateless) { if (!preferStateless) { return false; } if (runtime.isServer && (definition.getChildContext === undefined && definition.init === undefined)) { return true; } // Not stateless if contains anything more than render and static properties for (const prop in definition) { if (prop !== 'render' && !~STATIC_KEYS.indexOf(prop)) { return false; } } return true; }
[ "function", "shouldBeStateless", "(", "definition", ",", "preferStateless", ")", "{", "if", "(", "!", "preferStateless", ")", "{", "return", "false", ";", "}", "if", "(", "runtime", ".", "isServer", "&&", "(", "definition", ".", "getChildContext", "===", "undefined", "&&", "definition", ".", "init", "===", "undefined", ")", ")", "{", "return", "true", ";", "}", "// Not stateless if contains anything more than render and static properties", "for", "(", "const", "prop", "in", "definition", ")", "{", "if", "(", "prop", "!==", "'render'", "&&", "!", "~", "STATIC_KEYS", ".", "indexOf", "(", "prop", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Determine if 'definition' is stateless @param {Object} definition @param {Boolean} preferStateless @returns {Boolean}
[ "Determine", "if", "definition", "is", "stateless" ]
688a381f9478f75aed00032cae78df3f20d3a6dd
https://github.com/YR/component/blob/688a381f9478f75aed00032cae78df3f20d3a6dd/src/index.js#L98-L115
47,262
freshout-dev/thulium
etc/EJS/ejs_fulljslint.js
quit
function quit(m, l, ch) { throw { name: 'JSLintError', line: l, character: ch, message: m + " (" + Math.floor((l / lines.length) * 100) + "% scanned)." }; }
javascript
function quit(m, l, ch) { throw { name: 'JSLintError', line: l, character: ch, message: m + " (" + Math.floor((l / lines.length) * 100) + "% scanned)." }; }
[ "function", "quit", "(", "m", ",", "l", ",", "ch", ")", "{", "throw", "{", "name", ":", "'JSLintError'", ",", "line", ":", "l", ",", "character", ":", "ch", ",", "message", ":", "m", "+", "\" (\"", "+", "Math", ".", "floor", "(", "(", "l", "/", "lines", ".", "length", ")", "*", "100", ")", "+", "\"% scanned).\"", "}", ";", "}" ]
Produce an error warning.
[ "Produce", "an", "error", "warning", "." ]
ba3173e700fbe810ce13063e7ad46e9b05bb49e7
https://github.com/freshout-dev/thulium/blob/ba3173e700fbe810ce13063e7ad46e9b05bb49e7/etc/EJS/ejs_fulljslint.js#L560-L568
47,263
freshout-dev/thulium
etc/EJS/ejs_fulljslint.js
parse
function parse(rbp, initial) { var left; var o; if (nexttoken.id === '(end)') { error("Unexpected early end of program.", token); } advance(); if (option.adsafe && token.value === 'ADSAFE') { if (nexttoken.id !== '.' || !(peek(0).identifier) || peek(1).id !== '(') { warning('ADsafe violation.', token); } } if (initial) { anonname = 'anonymous'; funct['(verb)'] = token.value; } if (initial && token.fud) { left = token.fud(); } else { if (token.nud) { o = token.exps; left = token.nud(); } else { if (nexttoken.type === '(number)' && token.id === '.') { warning( "A leading decimal point can be confused with a dot: '.{a}'.", token, nexttoken.value); advance(); return token; } else { error("Expected an identifier and instead saw '{a}'.", token, token.id); } } while (rbp < nexttoken.lbp) { o = nexttoken.exps; advance(); if (token.led) { left = token.led(left); } else { error("Expected an operator and instead saw '{a}'.", token, token.id); } } if (initial && !o) { warning( "Expected an assignment or function call and instead saw an expression.", token); } } if (!option.evil && left && left.value === 'eval') { warning("eval is evil.", left); } return left; }
javascript
function parse(rbp, initial) { var left; var o; if (nexttoken.id === '(end)') { error("Unexpected early end of program.", token); } advance(); if (option.adsafe && token.value === 'ADSAFE') { if (nexttoken.id !== '.' || !(peek(0).identifier) || peek(1).id !== '(') { warning('ADsafe violation.', token); } } if (initial) { anonname = 'anonymous'; funct['(verb)'] = token.value; } if (initial && token.fud) { left = token.fud(); } else { if (token.nud) { o = token.exps; left = token.nud(); } else { if (nexttoken.type === '(number)' && token.id === '.') { warning( "A leading decimal point can be confused with a dot: '.{a}'.", token, nexttoken.value); advance(); return token; } else { error("Expected an identifier and instead saw '{a}'.", token, token.id); } } while (rbp < nexttoken.lbp) { o = nexttoken.exps; advance(); if (token.led) { left = token.led(left); } else { error("Expected an operator and instead saw '{a}'.", token, token.id); } } if (initial && !o) { warning( "Expected an assignment or function call and instead saw an expression.", token); } } if (!option.evil && left && left.value === 'eval') { warning("eval is evil.", left); } return left; }
[ "function", "parse", "(", "rbp", ",", "initial", ")", "{", "var", "left", ";", "var", "o", ";", "if", "(", "nexttoken", ".", "id", "===", "'(end)'", ")", "{", "error", "(", "\"Unexpected early end of program.\"", ",", "token", ")", ";", "}", "advance", "(", ")", ";", "if", "(", "option", ".", "adsafe", "&&", "token", ".", "value", "===", "'ADSAFE'", ")", "{", "if", "(", "nexttoken", ".", "id", "!==", "'.'", "||", "!", "(", "peek", "(", "0", ")", ".", "identifier", ")", "||", "peek", "(", "1", ")", ".", "id", "!==", "'('", ")", "{", "warning", "(", "'ADsafe violation.'", ",", "token", ")", ";", "}", "}", "if", "(", "initial", ")", "{", "anonname", "=", "'anonymous'", ";", "funct", "[", "'(verb)'", "]", "=", "token", ".", "value", ";", "}", "if", "(", "initial", "&&", "token", ".", "fud", ")", "{", "left", "=", "token", ".", "fud", "(", ")", ";", "}", "else", "{", "if", "(", "token", ".", "nud", ")", "{", "o", "=", "token", ".", "exps", ";", "left", "=", "token", ".", "nud", "(", ")", ";", "}", "else", "{", "if", "(", "nexttoken", ".", "type", "===", "'(number)'", "&&", "token", ".", "id", "===", "'.'", ")", "{", "warning", "(", "\"A leading decimal point can be confused with a dot: '.{a}'.\"", ",", "token", ",", "nexttoken", ".", "value", ")", ";", "advance", "(", ")", ";", "return", "token", ";", "}", "else", "{", "error", "(", "\"Expected an identifier and instead saw '{a}'.\"", ",", "token", ",", "token", ".", "id", ")", ";", "}", "}", "while", "(", "rbp", "<", "nexttoken", ".", "lbp", ")", "{", "o", "=", "nexttoken", ".", "exps", ";", "advance", "(", ")", ";", "if", "(", "token", ".", "led", ")", "{", "left", "=", "token", ".", "led", "(", "left", ")", ";", "}", "else", "{", "error", "(", "\"Expected an operator and instead saw '{a}'.\"", ",", "token", ",", "token", ".", "id", ")", ";", "}", "}", "if", "(", "initial", "&&", "!", "o", ")", "{", "warning", "(", "\"Expected an assignment or function call and instead saw an expression.\"", ",", "token", ")", ";", "}", "}", "if", "(", "!", "option", ".", "evil", "&&", "left", "&&", "left", ".", "value", "===", "'eval'", ")", "{", "warning", "(", "\"eval is evil.\"", ",", "left", ")", ";", "}", "return", "left", ";", "}" ]
.nud Null denotation .fud First null denotation .led Left denotation lbp Left binding power rbp Right binding power They are key to the parsing method called Top Down Operator Precedence.
[ ".", "nud", "Null", "denotation", ".", "fud", "First", "null", "denotation", ".", "led", "Left", "denotation", "lbp", "Left", "binding", "power", "rbp", "Right", "binding", "power", "They", "are", "key", "to", "the", "parsing", "method", "called", "Top", "Down", "Operator", "Precedence", "." ]
ba3173e700fbe810ce13063e7ad46e9b05bb49e7
https://github.com/freshout-dev/thulium/blob/ba3173e700fbe810ce13063e7ad46e9b05bb49e7/etc/EJS/ejs_fulljslint.js#L1428-L1483
47,264
freshout-dev/thulium
etc/EJS/ejs_fulljslint.js
symbol
function symbol(s, p) { var x = syntax[s]; if (!x || typeof x !== 'object') { syntax[s] = x = { id: s, lbp: p, value: s }; } return x; }
javascript
function symbol(s, p) { var x = syntax[s]; if (!x || typeof x !== 'object') { syntax[s] = x = { id: s, lbp: p, value: s }; } return x; }
[ "function", "symbol", "(", "s", ",", "p", ")", "{", "var", "x", "=", "syntax", "[", "s", "]", ";", "if", "(", "!", "x", "||", "typeof", "x", "!==", "'object'", ")", "{", "syntax", "[", "s", "]", "=", "x", "=", "{", "id", ":", "s", ",", "lbp", ":", "p", ",", "value", ":", "s", "}", ";", "}", "return", "x", ";", "}" ]
Parasitic constructors for making the symbols that will be inherited by tokens.
[ "Parasitic", "constructors", "for", "making", "the", "symbols", "that", "will", "be", "inherited", "by", "tokens", "." ]
ba3173e700fbe810ce13063e7ad46e9b05bb49e7
https://github.com/freshout-dev/thulium/blob/ba3173e700fbe810ce13063e7ad46e9b05bb49e7/etc/EJS/ejs_fulljslint.js#L1543-L1553
47,265
freshout-dev/thulium
etc/EJS/ejs_fulljslint.js
function (s, o) { if (o) { if (o.adsafe) { o.browser = false; o.debug = false; o.eqeqeq = true; o.evil = false; o.forin = false; o.on = false; o.rhino = false; o.undef = true; o.widget = false; } option = o; } else { option = {}; } globals = option.adsafe ? {} : object(standard); JSLINT.errors = []; global = object(globals); scope = global; funct = {'(global)': true, '(name)': '(global)', '(scope)': scope}; functions = []; src = false; xmode = false; xtype = ''; stack = null; member = {}; membersOnly = null; implied = {}; inblock = false; lookahead = []; indent = 0; jsonmode = false; warnings = 0; lex.init(s); prereg = true; prevtoken = token = nexttoken = syntax['(begin)']; populateGlobals(); try { advance(); if (nexttoken.value.charAt(0) === '<') { xml(); } else if (nexttoken.id === '{' || nexttoken.id === '[') { option.laxbreak = true; jsonmode = true; jsonValue(); } else { statements(); } advance('(end)'); } catch (e) { if (e) { JSLINT.errors.push({ reason : e.message, line : e.line || nexttoken.line, character : e.character || nexttoken.from }, null); } } return JSLINT.errors.length === 0; }
javascript
function (s, o) { if (o) { if (o.adsafe) { o.browser = false; o.debug = false; o.eqeqeq = true; o.evil = false; o.forin = false; o.on = false; o.rhino = false; o.undef = true; o.widget = false; } option = o; } else { option = {}; } globals = option.adsafe ? {} : object(standard); JSLINT.errors = []; global = object(globals); scope = global; funct = {'(global)': true, '(name)': '(global)', '(scope)': scope}; functions = []; src = false; xmode = false; xtype = ''; stack = null; member = {}; membersOnly = null; implied = {}; inblock = false; lookahead = []; indent = 0; jsonmode = false; warnings = 0; lex.init(s); prereg = true; prevtoken = token = nexttoken = syntax['(begin)']; populateGlobals(); try { advance(); if (nexttoken.value.charAt(0) === '<') { xml(); } else if (nexttoken.id === '{' || nexttoken.id === '[') { option.laxbreak = true; jsonmode = true; jsonValue(); } else { statements(); } advance('(end)'); } catch (e) { if (e) { JSLINT.errors.push({ reason : e.message, line : e.line || nexttoken.line, character : e.character || nexttoken.from }, null); } } return JSLINT.errors.length === 0; }
[ "function", "(", "s", ",", "o", ")", "{", "if", "(", "o", ")", "{", "if", "(", "o", ".", "adsafe", ")", "{", "o", ".", "browser", "=", "false", ";", "o", ".", "debug", "=", "false", ";", "o", ".", "eqeqeq", "=", "true", ";", "o", ".", "evil", "=", "false", ";", "o", ".", "forin", "=", "false", ";", "o", ".", "on", "=", "false", ";", "o", ".", "rhino", "=", "false", ";", "o", ".", "undef", "=", "true", ";", "o", ".", "widget", "=", "false", ";", "}", "option", "=", "o", ";", "}", "else", "{", "option", "=", "{", "}", ";", "}", "globals", "=", "option", ".", "adsafe", "?", "{", "}", ":", "object", "(", "standard", ")", ";", "JSLINT", ".", "errors", "=", "[", "]", ";", "global", "=", "object", "(", "globals", ")", ";", "scope", "=", "global", ";", "funct", "=", "{", "'(global)'", ":", "true", ",", "'(name)'", ":", "'(global)'", ",", "'(scope)'", ":", "scope", "}", ";", "functions", "=", "[", "]", ";", "src", "=", "false", ";", "xmode", "=", "false", ";", "xtype", "=", "''", ";", "stack", "=", "null", ";", "member", "=", "{", "}", ";", "membersOnly", "=", "null", ";", "implied", "=", "{", "}", ";", "inblock", "=", "false", ";", "lookahead", "=", "[", "]", ";", "indent", "=", "0", ";", "jsonmode", "=", "false", ";", "warnings", "=", "0", ";", "lex", ".", "init", "(", "s", ")", ";", "prereg", "=", "true", ";", "prevtoken", "=", "token", "=", "nexttoken", "=", "syntax", "[", "'(begin)'", "]", ";", "populateGlobals", "(", ")", ";", "try", "{", "advance", "(", ")", ";", "if", "(", "nexttoken", ".", "value", ".", "charAt", "(", "0", ")", "===", "'<'", ")", "{", "xml", "(", ")", ";", "}", "else", "if", "(", "nexttoken", ".", "id", "===", "'{'", "||", "nexttoken", ".", "id", "===", "'['", ")", "{", "option", ".", "laxbreak", "=", "true", ";", "jsonmode", "=", "true", ";", "jsonValue", "(", ")", ";", "}", "else", "{", "statements", "(", ")", ";", "}", "advance", "(", "'(end)'", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ")", "{", "JSLINT", ".", "errors", ".", "push", "(", "{", "reason", ":", "e", ".", "message", ",", "line", ":", "e", ".", "line", "||", "nexttoken", ".", "line", ",", "character", ":", "e", ".", "character", "||", "nexttoken", ".", "from", "}", ",", "null", ")", ";", "}", "}", "return", "JSLINT", ".", "errors", ".", "length", "===", "0", ";", "}" ]
The actual JSLINT function itself.
[ "The", "actual", "JSLINT", "function", "itself", "." ]
ba3173e700fbe810ce13063e7ad46e9b05bb49e7
https://github.com/freshout-dev/thulium/blob/ba3173e700fbe810ce13063e7ad46e9b05bb49e7/etc/EJS/ejs_fulljslint.js#L3584-L3647
47,266
angular-translate/angular-translate-extractor
index.js
function (objSrc, objDest) { if (_.isObject(objDest)) { Object.getOwnPropertyNames(objDest).forEach(function (index) { if (_.isObject(objDest[index])) { objDest[index] = _recurseExtend(objSrc[index], objDest[index]); } else { objDest[index] = objSrc && objSrc[index] ? objSrc[index] : ''; } }); } return _.cloneDeep(objDest); }
javascript
function (objSrc, objDest) { if (_.isObject(objDest)) { Object.getOwnPropertyNames(objDest).forEach(function (index) { if (_.isObject(objDest[index])) { objDest[index] = _recurseExtend(objSrc[index], objDest[index]); } else { objDest[index] = objSrc && objSrc[index] ? objSrc[index] : ''; } }); } return _.cloneDeep(objDest); }
[ "function", "(", "objSrc", ",", "objDest", ")", "{", "if", "(", "_", ".", "isObject", "(", "objDest", ")", ")", "{", "Object", ".", "getOwnPropertyNames", "(", "objDest", ")", ".", "forEach", "(", "function", "(", "index", ")", "{", "if", "(", "_", ".", "isObject", "(", "objDest", "[", "index", "]", ")", ")", "{", "objDest", "[", "index", "]", "=", "_recurseExtend", "(", "objSrc", "[", "index", "]", ",", "objDest", "[", "index", "]", ")", ";", "}", "else", "{", "objDest", "[", "index", "]", "=", "objSrc", "&&", "objSrc", "[", "index", "]", "?", "objSrc", "[", "index", "]", ":", "''", ";", "}", "}", ")", ";", "}", "return", "_", ".", "cloneDeep", "(", "objDest", ")", ";", "}" ]
Merge recursively objDest into objSrc
[ "Merge", "recursively", "objDest", "into", "objSrc" ]
e635405c8061df6594660fcb8c7f83927687c99e
https://github.com/angular-translate/angular-translate-extractor/blob/e635405c8061df6594660fcb8c7f83927687c99e/index.js#L299-L311
47,267
teux/webpack-koa-middleware
index.js
sendStats
function sendStats(socket, stats, force) { if (!socket || !stats) return; if (!force && stats && stats.assets && stats.assets.every(function (asset) { return !asset.emitted; })) return; socket.emit("hash", stats.hash); if (stats.errors.length > 0) socket.emit("errors", stats.errors); else if (stats.warnings.length > 0) socket.emit("warnings", stats.warnings); else socket.emit("ok"); }
javascript
function sendStats(socket, stats, force) { if (!socket || !stats) return; if (!force && stats && stats.assets && stats.assets.every(function (asset) { return !asset.emitted; })) return; socket.emit("hash", stats.hash); if (stats.errors.length > 0) socket.emit("errors", stats.errors); else if (stats.warnings.length > 0) socket.emit("warnings", stats.warnings); else socket.emit("ok"); }
[ "function", "sendStats", "(", "socket", ",", "stats", ",", "force", ")", "{", "if", "(", "!", "socket", "||", "!", "stats", ")", "return", ";", "if", "(", "!", "force", "&&", "stats", "&&", "stats", ".", "assets", "&&", "stats", ".", "assets", ".", "every", "(", "function", "(", "asset", ")", "{", "return", "!", "asset", ".", "emitted", ";", "}", ")", ")", "return", ";", "socket", ".", "emit", "(", "\"hash\"", ",", "stats", ".", "hash", ")", ";", "if", "(", "stats", ".", "errors", ".", "length", ">", "0", ")", "socket", ".", "emit", "(", "\"errors\"", ",", "stats", ".", "errors", ")", ";", "else", "if", "(", "stats", ".", "warnings", ".", "length", ">", "0", ")", "socket", ".", "emit", "(", "\"warnings\"", ",", "stats", ".", "warnings", ")", ";", "else", "socket", ".", "emit", "(", "\"ok\"", ")", ";", "}" ]
Sends signals and stats in socket @param {WebSocket} socket @param {Object} stats Webpack generated stats @param {Boolean} force
[ "Sends", "signals", "and", "stats", "in", "socket" ]
557a979eb7b6dd0da40dadc465bc45024aadc20b
https://github.com/teux/webpack-koa-middleware/blob/557a979eb7b6dd0da40dadc465bc45024aadc20b/index.js#L42-L54
47,268
teux/webpack-koa-middleware
index.js
function (url) { return new Promise(function (resolve, reject) { middleware(new MockReq(url), new MockRes(url, resolve), reject); }); }
javascript
function (url) { return new Promise(function (resolve, reject) { middleware(new MockReq(url), new MockRes(url, resolve), reject); }); }
[ "function", "(", "url", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "middleware", "(", "new", "MockReq", "(", "url", ")", ",", "new", "MockRes", "(", "url", ",", "resolve", ")", ",", "reject", ")", ";", "}", ")", ";", "}" ]
Calls webpack middleware in express manner. @param {String} url @returns {Promise}
[ "Calls", "webpack", "middleware", "in", "express", "manner", "." ]
557a979eb7b6dd0da40dadc465bc45024aadc20b
https://github.com/teux/webpack-koa-middleware/blob/557a979eb7b6dd0da40dadc465bc45024aadc20b/index.js#L99-L103
47,269
alexyoung/pop
lib/site_builder.js
SiteBuilder
function SiteBuilder(config, fileMap) { this.config = config; this.root = config.root; var helperFile = path.join(this.root, '_lib', 'helpers.js'); if (existsSync(helperFile)) { userHelpers = require(helperFile); } var filterFile = path.join(this.root, '_lib', 'filters.js'); if (existsSync(filterFile)) { userFilters = require(filterFile); } var postFilterFile = path.join(this.root, '_lib', 'post-filters.js'); if (existsSync(postFilterFile)) { userPostFilters = require(postFilterFile); } this.outputRoot = config.output; this.fileMap = fileMap; this.posts = []; this.helpers = helpers; this.events = new EventEmitter(); this.includes = {}; this.loadPlugins(); }
javascript
function SiteBuilder(config, fileMap) { this.config = config; this.root = config.root; var helperFile = path.join(this.root, '_lib', 'helpers.js'); if (existsSync(helperFile)) { userHelpers = require(helperFile); } var filterFile = path.join(this.root, '_lib', 'filters.js'); if (existsSync(filterFile)) { userFilters = require(filterFile); } var postFilterFile = path.join(this.root, '_lib', 'post-filters.js'); if (existsSync(postFilterFile)) { userPostFilters = require(postFilterFile); } this.outputRoot = config.output; this.fileMap = fileMap; this.posts = []; this.helpers = helpers; this.events = new EventEmitter(); this.includes = {}; this.loadPlugins(); }
[ "function", "SiteBuilder", "(", "config", ",", "fileMap", ")", "{", "this", ".", "config", "=", "config", ";", "this", ".", "root", "=", "config", ".", "root", ";", "var", "helperFile", "=", "path", ".", "join", "(", "this", ".", "root", ",", "'_lib'", ",", "'helpers.js'", ")", ";", "if", "(", "existsSync", "(", "helperFile", ")", ")", "{", "userHelpers", "=", "require", "(", "helperFile", ")", ";", "}", "var", "filterFile", "=", "path", ".", "join", "(", "this", ".", "root", ",", "'_lib'", ",", "'filters.js'", ")", ";", "if", "(", "existsSync", "(", "filterFile", ")", ")", "{", "userFilters", "=", "require", "(", "filterFile", ")", ";", "}", "var", "postFilterFile", "=", "path", ".", "join", "(", "this", ".", "root", ",", "'_lib'", ",", "'post-filters.js'", ")", ";", "if", "(", "existsSync", "(", "postFilterFile", ")", ")", "{", "userPostFilters", "=", "require", "(", "postFilterFile", ")", ";", "}", "this", ".", "outputRoot", "=", "config", ".", "output", ";", "this", ".", "fileMap", "=", "fileMap", ";", "this", ".", "posts", "=", "[", "]", ";", "this", ".", "helpers", "=", "helpers", ";", "this", ".", "events", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "includes", "=", "{", "}", ";", "this", ".", "loadPlugins", "(", ")", ";", "}" ]
Initialize `SiteBuilder` with a config object and `FileMap`. @param {Object} Config options @param {FileMap} A `FileMap` object @api public
[ "Initialize", "SiteBuilder", "with", "a", "config", "object", "and", "FileMap", "." ]
8a0b3f2605cb58e8ae6b34f1373dde00610e9858
https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/site_builder.js#L35-L62
47,270
JanitorTechnology/selfapi
selfapi.js
API
function API (parameters) { // Own API resource prefix (e.g. '/resource'). this.path = parameters.path || null; // Own documentation. this.title = parameters.title || null; this.description = parameters.description || null; // Own test setup functions. this.beforeEachTest = parameters.beforeEachTest || null; this.afterEachTest = parameters.afterEachTest || null; // Parent API resource (or root server app). this.parent = parameters.parent || null; // API sub-resources (API instances) by relative path (e.g. '/subresource'). this.children = {}; // Own request handlers (handler parameters) by method (e.g. 'post'). this.handlers = {}; }
javascript
function API (parameters) { // Own API resource prefix (e.g. '/resource'). this.path = parameters.path || null; // Own documentation. this.title = parameters.title || null; this.description = parameters.description || null; // Own test setup functions. this.beforeEachTest = parameters.beforeEachTest || null; this.afterEachTest = parameters.afterEachTest || null; // Parent API resource (or root server app). this.parent = parameters.parent || null; // API sub-resources (API instances) by relative path (e.g. '/subresource'). this.children = {}; // Own request handlers (handler parameters) by method (e.g. 'post'). this.handlers = {}; }
[ "function", "API", "(", "parameters", ")", "{", "// Own API resource prefix (e.g. '/resource').", "this", ".", "path", "=", "parameters", ".", "path", "||", "null", ";", "// Own documentation.", "this", ".", "title", "=", "parameters", ".", "title", "||", "null", ";", "this", ".", "description", "=", "parameters", ".", "description", "||", "null", ";", "// Own test setup functions.", "this", ".", "beforeEachTest", "=", "parameters", ".", "beforeEachTest", "||", "null", ";", "this", ".", "afterEachTest", "=", "parameters", ".", "afterEachTest", "||", "null", ";", "// Parent API resource (or root server app).", "this", ".", "parent", "=", "parameters", ".", "parent", "||", "null", ";", "// API sub-resources (API instances) by relative path (e.g. '/subresource').", "this", ".", "children", "=", "{", "}", ";", "// Own request handlers (handler parameters) by method (e.g. 'post').", "this", ".", "handlers", "=", "{", "}", ";", "}" ]
Simple, self-documenting and self-testing API system.
[ "Simple", "self", "-", "documenting", "and", "self", "-", "testing", "API", "system", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L15-L35
47,271
JanitorTechnology/selfapi
selfapi.js
function (method, path, parameters) { if (!this.parent) { return; } var fullPath = normalizePath(path, this.path); this.parent.exportHandler(method, fullPath, parameters); }
javascript
function (method, path, parameters) { if (!this.parent) { return; } var fullPath = normalizePath(path, this.path); this.parent.exportHandler(method, fullPath, parameters); }
[ "function", "(", "method", ",", "path", ",", "parameters", ")", "{", "if", "(", "!", "this", ".", "parent", ")", "{", "return", ";", "}", "var", "fullPath", "=", "normalizePath", "(", "path", ",", "this", ".", "path", ")", ";", "this", ".", "parent", ".", "exportHandler", "(", "method", ",", "fullPath", ",", "parameters", ")", ";", "}" ]
Backpropagate a new request handler up the API resource tree in order to register it at the root.
[ "Backpropagate", "a", "new", "request", "handler", "up", "the", "API", "resource", "tree", "in", "order", "to", "register", "it", "at", "the", "root", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L106-L112
47,272
JanitorTechnology/selfapi
selfapi.js
function (baseUrl, callback) { var self = this; var tests = []; // Export own request handler examples as test functions. for (var method in self.handlers) { var handler = self.handlers[method]; if (!handler.examples) { throw ( 'Handler ' + method.toUpperCase() + ' ' + this.path + ' does not have examples!' ); } handler.examples.forEach(function (example) { var test = self.testHandlerExample.bind(self, baseUrl, method, handler, example); tests.push(test); }); } // Don't hang when there are no children. var pendingChildren = Object.keys(self.children).length; if (pendingChildren === 0) { callback(tests); return; } // Export children's request handler test functions recursively. var childBaseUrl = url.parse(String(baseUrl)); childBaseUrl.pathname = normalizePath(self.path, childBaseUrl.pathname); childBaseUrl = url.format(childBaseUrl); for (var path in self.children) { self.children[path].exportAllTests(childBaseUrl, function (childTests) { tests = tests.concat(childTests); pendingChildren--; if (pendingChildren === 0) { callback(tests); } }); } }
javascript
function (baseUrl, callback) { var self = this; var tests = []; // Export own request handler examples as test functions. for (var method in self.handlers) { var handler = self.handlers[method]; if (!handler.examples) { throw ( 'Handler ' + method.toUpperCase() + ' ' + this.path + ' does not have examples!' ); } handler.examples.forEach(function (example) { var test = self.testHandlerExample.bind(self, baseUrl, method, handler, example); tests.push(test); }); } // Don't hang when there are no children. var pendingChildren = Object.keys(self.children).length; if (pendingChildren === 0) { callback(tests); return; } // Export children's request handler test functions recursively. var childBaseUrl = url.parse(String(baseUrl)); childBaseUrl.pathname = normalizePath(self.path, childBaseUrl.pathname); childBaseUrl = url.format(childBaseUrl); for (var path in self.children) { self.children[path].exportAllTests(childBaseUrl, function (childTests) { tests = tests.concat(childTests); pendingChildren--; if (pendingChildren === 0) { callback(tests); } }); } }
[ "function", "(", "baseUrl", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "tests", "=", "[", "]", ";", "// Export own request handler examples as test functions.", "for", "(", "var", "method", "in", "self", ".", "handlers", ")", "{", "var", "handler", "=", "self", ".", "handlers", "[", "method", "]", ";", "if", "(", "!", "handler", ".", "examples", ")", "{", "throw", "(", "'Handler '", "+", "method", ".", "toUpperCase", "(", ")", "+", "' '", "+", "this", ".", "path", "+", "' does not have examples!'", ")", ";", "}", "handler", ".", "examples", ".", "forEach", "(", "function", "(", "example", ")", "{", "var", "test", "=", "self", ".", "testHandlerExample", ".", "bind", "(", "self", ",", "baseUrl", ",", "method", ",", "handler", ",", "example", ")", ";", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "}", "// Don't hang when there are no children.", "var", "pendingChildren", "=", "Object", ".", "keys", "(", "self", ".", "children", ")", ".", "length", ";", "if", "(", "pendingChildren", "===", "0", ")", "{", "callback", "(", "tests", ")", ";", "return", ";", "}", "// Export children's request handler test functions recursively.", "var", "childBaseUrl", "=", "url", ".", "parse", "(", "String", "(", "baseUrl", ")", ")", ";", "childBaseUrl", ".", "pathname", "=", "normalizePath", "(", "self", ".", "path", ",", "childBaseUrl", ".", "pathname", ")", ";", "childBaseUrl", "=", "url", ".", "format", "(", "childBaseUrl", ")", ";", "for", "(", "var", "path", "in", "self", ".", "children", ")", "{", "self", ".", "children", "[", "path", "]", ".", "exportAllTests", "(", "childBaseUrl", ",", "function", "(", "childTests", ")", "{", "tests", "=", "tests", ".", "concat", "(", "childTests", ")", ";", "pendingChildren", "--", ";", "if", "(", "pendingChildren", "===", "0", ")", "{", "callback", "(", "tests", ")", ";", "}", "}", ")", ";", "}", "}" ]
Export all request handler examples as self-test functions.
[ "Export", "all", "request", "handler", "examples", "as", "self", "-", "test", "functions", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L129-L169
47,273
JanitorTechnology/selfapi
selfapi.js
function (baseUrl) { var fullUrl = url.parse(String(baseUrl || '/')); fullUrl.pathname = normalizePath(this.path, fullUrl.pathname); fullUrl = url.format(fullUrl); var routes = {}; Object.keys(this.children).forEach(function (child) { routes[child.replace(/^\//, '')] = nodepath.join(fullUrl, child); }); return routes; }
javascript
function (baseUrl) { var fullUrl = url.parse(String(baseUrl || '/')); fullUrl.pathname = normalizePath(this.path, fullUrl.pathname); fullUrl = url.format(fullUrl); var routes = {}; Object.keys(this.children).forEach(function (child) { routes[child.replace(/^\//, '')] = nodepath.join(fullUrl, child); }); return routes; }
[ "function", "(", "baseUrl", ")", "{", "var", "fullUrl", "=", "url", ".", "parse", "(", "String", "(", "baseUrl", "||", "'/'", ")", ")", ";", "fullUrl", ".", "pathname", "=", "normalizePath", "(", "this", ".", "path", ",", "fullUrl", ".", "pathname", ")", ";", "fullUrl", "=", "url", ".", "format", "(", "fullUrl", ")", ";", "var", "routes", "=", "{", "}", ";", "Object", ".", "keys", "(", "this", ".", "children", ")", ".", "forEach", "(", "function", "(", "child", ")", "{", "routes", "[", "child", ".", "replace", "(", "/", "^\\/", "/", ",", "''", ")", "]", "=", "nodepath", ".", "join", "(", "fullUrl", ",", "child", ")", ";", "}", ")", ";", "return", "routes", ";", "}" ]
Build index routes.
[ "Build", "index", "routes", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L394-L404
47,274
JanitorTechnology/selfapi
selfapi.js
function (basePath, anchors) { var fullPath = normalizePath(this.path, basePath) || '/'; anchors = anchors || []; function getAnchor (title) { var anchor = String(title).toLowerCase() .replace(/[\s\-]+/g, ' ') .replace(/[^a-z0-9 ]/g, '') .trim() .replace(/ /g, '-'); if (anchors.indexOf(anchor) > -1) { var i = 2; while (anchors.indexOf(anchor + '-' + i) > -1) { i++; } anchor += '-' + i; } anchors.push(anchor); return anchor; } var html = ''; if (this.title) { html += '<h1 id="' + getAnchor(this.title) + '">' + this.title + '</h1>\n'; } if (this.description) { html += '<p>' + this.description.replace(/\n/g, '<br>') + '</p>\n'; } // Export own request handlers. for (var method in this.handlers) { var handler = this.handlers[method]; var title = handler.title || '(no title)'; html += '<h2 id="' + getAnchor(title) + '">' + title + '</h2>\n'; html += '<pre>' + method.toUpperCase() + ' ' + fullPath + '</pre>\n'; if (handler.description) { html += '<p>' + handler.description.replace(/\n/g, '<br>') + '</p>\n'; } if (handler.examples && handler.examples.length > 0) { var example = handler.examples[0]; var request = example.request || {}; if (request.urlParameters || request.headers || request.body) { html += '<h3>Input</h3>\n<pre>'; var exampleURL = method.toUpperCase() + ' ' + fullPath; if (request.urlParameters) { exampleURL = replaceUrlParameters(exampleURL, request.urlParameters); } html += exampleURL + '\n'; var requestHeaders = request.headers || {}; for (var header in requestHeaders) { html += header + ': ' + requestHeaders[header] + '\n'; } if (request.body) { html += '\n' + jsonStringifyIfObject(request.body).trim() + '\n'; } html += '</pre>\n'; } var response = example.response || {}; var hasResponseStatus = isExplicitExample(response.status); var hasResponseBody = isExplicitExample(response.body); if (hasResponseStatus || response.headers || hasResponseBody) { html += '<h3>Response</h3>\n<pre>'; if (hasResponseStatus) { var message = http.STATUS_CODES[response.status]; html += 'Status: ' + response.status + ' ' + message + '\n'; } var responseHeaders = response.headers || {}; for (var header in responseHeaders) { var headerValue = responseHeaders[header]; if (isExplicitExample(headerValue)) { html += header + ': ' + headerValue + '\n'; } } if (hasResponseBody) { if (hasResponseStatus || Object.keys(responseHeaders).length > 0) { html += '\n'; } html += jsonStringifyIfObject(response.body).trim() + '\n'; } html += '</pre>\n'; } // TODO Document all unique possible status codes? // TODO Document all request parameters? } } // Export children's request handlers recursively. for (var path in this.children) { var child = this.children[path]; html += child.toHTML(fullPath, anchors); } return html; }
javascript
function (basePath, anchors) { var fullPath = normalizePath(this.path, basePath) || '/'; anchors = anchors || []; function getAnchor (title) { var anchor = String(title).toLowerCase() .replace(/[\s\-]+/g, ' ') .replace(/[^a-z0-9 ]/g, '') .trim() .replace(/ /g, '-'); if (anchors.indexOf(anchor) > -1) { var i = 2; while (anchors.indexOf(anchor + '-' + i) > -1) { i++; } anchor += '-' + i; } anchors.push(anchor); return anchor; } var html = ''; if (this.title) { html += '<h1 id="' + getAnchor(this.title) + '">' + this.title + '</h1>\n'; } if (this.description) { html += '<p>' + this.description.replace(/\n/g, '<br>') + '</p>\n'; } // Export own request handlers. for (var method in this.handlers) { var handler = this.handlers[method]; var title = handler.title || '(no title)'; html += '<h2 id="' + getAnchor(title) + '">' + title + '</h2>\n'; html += '<pre>' + method.toUpperCase() + ' ' + fullPath + '</pre>\n'; if (handler.description) { html += '<p>' + handler.description.replace(/\n/g, '<br>') + '</p>\n'; } if (handler.examples && handler.examples.length > 0) { var example = handler.examples[0]; var request = example.request || {}; if (request.urlParameters || request.headers || request.body) { html += '<h3>Input</h3>\n<pre>'; var exampleURL = method.toUpperCase() + ' ' + fullPath; if (request.urlParameters) { exampleURL = replaceUrlParameters(exampleURL, request.urlParameters); } html += exampleURL + '\n'; var requestHeaders = request.headers || {}; for (var header in requestHeaders) { html += header + ': ' + requestHeaders[header] + '\n'; } if (request.body) { html += '\n' + jsonStringifyIfObject(request.body).trim() + '\n'; } html += '</pre>\n'; } var response = example.response || {}; var hasResponseStatus = isExplicitExample(response.status); var hasResponseBody = isExplicitExample(response.body); if (hasResponseStatus || response.headers || hasResponseBody) { html += '<h3>Response</h3>\n<pre>'; if (hasResponseStatus) { var message = http.STATUS_CODES[response.status]; html += 'Status: ' + response.status + ' ' + message + '\n'; } var responseHeaders = response.headers || {}; for (var header in responseHeaders) { var headerValue = responseHeaders[header]; if (isExplicitExample(headerValue)) { html += header + ': ' + headerValue + '\n'; } } if (hasResponseBody) { if (hasResponseStatus || Object.keys(responseHeaders).length > 0) { html += '\n'; } html += jsonStringifyIfObject(response.body).trim() + '\n'; } html += '</pre>\n'; } // TODO Document all unique possible status codes? // TODO Document all request parameters? } } // Export children's request handlers recursively. for (var path in this.children) { var child = this.children[path]; html += child.toHTML(fullPath, anchors); } return html; }
[ "function", "(", "basePath", ",", "anchors", ")", "{", "var", "fullPath", "=", "normalizePath", "(", "this", ".", "path", ",", "basePath", ")", "||", "'/'", ";", "anchors", "=", "anchors", "||", "[", "]", ";", "function", "getAnchor", "(", "title", ")", "{", "var", "anchor", "=", "String", "(", "title", ")", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "[\\s\\-]+", "/", "g", ",", "' '", ")", ".", "replace", "(", "/", "[^a-z0-9 ]", "/", "g", ",", "''", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", " ", "/", "g", ",", "'-'", ")", ";", "if", "(", "anchors", ".", "indexOf", "(", "anchor", ")", ">", "-", "1", ")", "{", "var", "i", "=", "2", ";", "while", "(", "anchors", ".", "indexOf", "(", "anchor", "+", "'-'", "+", "i", ")", ">", "-", "1", ")", "{", "i", "++", ";", "}", "anchor", "+=", "'-'", "+", "i", ";", "}", "anchors", ".", "push", "(", "anchor", ")", ";", "return", "anchor", ";", "}", "var", "html", "=", "''", ";", "if", "(", "this", ".", "title", ")", "{", "html", "+=", "'<h1 id=\"'", "+", "getAnchor", "(", "this", ".", "title", ")", "+", "'\">'", "+", "this", ".", "title", "+", "'</h1>\\n'", ";", "}", "if", "(", "this", ".", "description", ")", "{", "html", "+=", "'<p>'", "+", "this", ".", "description", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'<br>'", ")", "+", "'</p>\\n'", ";", "}", "// Export own request handlers.", "for", "(", "var", "method", "in", "this", ".", "handlers", ")", "{", "var", "handler", "=", "this", ".", "handlers", "[", "method", "]", ";", "var", "title", "=", "handler", ".", "title", "||", "'(no title)'", ";", "html", "+=", "'<h2 id=\"'", "+", "getAnchor", "(", "title", ")", "+", "'\">'", "+", "title", "+", "'</h2>\\n'", ";", "html", "+=", "'<pre>'", "+", "method", ".", "toUpperCase", "(", ")", "+", "' '", "+", "fullPath", "+", "'</pre>\\n'", ";", "if", "(", "handler", ".", "description", ")", "{", "html", "+=", "'<p>'", "+", "handler", ".", "description", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'<br>'", ")", "+", "'</p>\\n'", ";", "}", "if", "(", "handler", ".", "examples", "&&", "handler", ".", "examples", ".", "length", ">", "0", ")", "{", "var", "example", "=", "handler", ".", "examples", "[", "0", "]", ";", "var", "request", "=", "example", ".", "request", "||", "{", "}", ";", "if", "(", "request", ".", "urlParameters", "||", "request", ".", "headers", "||", "request", ".", "body", ")", "{", "html", "+=", "'<h3>Input</h3>\\n<pre>'", ";", "var", "exampleURL", "=", "method", ".", "toUpperCase", "(", ")", "+", "' '", "+", "fullPath", ";", "if", "(", "request", ".", "urlParameters", ")", "{", "exampleURL", "=", "replaceUrlParameters", "(", "exampleURL", ",", "request", ".", "urlParameters", ")", ";", "}", "html", "+=", "exampleURL", "+", "'\\n'", ";", "var", "requestHeaders", "=", "request", ".", "headers", "||", "{", "}", ";", "for", "(", "var", "header", "in", "requestHeaders", ")", "{", "html", "+=", "header", "+", "': '", "+", "requestHeaders", "[", "header", "]", "+", "'\\n'", ";", "}", "if", "(", "request", ".", "body", ")", "{", "html", "+=", "'\\n'", "+", "jsonStringifyIfObject", "(", "request", ".", "body", ")", ".", "trim", "(", ")", "+", "'\\n'", ";", "}", "html", "+=", "'</pre>\\n'", ";", "}", "var", "response", "=", "example", ".", "response", "||", "{", "}", ";", "var", "hasResponseStatus", "=", "isExplicitExample", "(", "response", ".", "status", ")", ";", "var", "hasResponseBody", "=", "isExplicitExample", "(", "response", ".", "body", ")", ";", "if", "(", "hasResponseStatus", "||", "response", ".", "headers", "||", "hasResponseBody", ")", "{", "html", "+=", "'<h3>Response</h3>\\n<pre>'", ";", "if", "(", "hasResponseStatus", ")", "{", "var", "message", "=", "http", ".", "STATUS_CODES", "[", "response", ".", "status", "]", ";", "html", "+=", "'Status: '", "+", "response", ".", "status", "+", "' '", "+", "message", "+", "'\\n'", ";", "}", "var", "responseHeaders", "=", "response", ".", "headers", "||", "{", "}", ";", "for", "(", "var", "header", "in", "responseHeaders", ")", "{", "var", "headerValue", "=", "responseHeaders", "[", "header", "]", ";", "if", "(", "isExplicitExample", "(", "headerValue", ")", ")", "{", "html", "+=", "header", "+", "': '", "+", "headerValue", "+", "'\\n'", ";", "}", "}", "if", "(", "hasResponseBody", ")", "{", "if", "(", "hasResponseStatus", "||", "Object", ".", "keys", "(", "responseHeaders", ")", ".", "length", ">", "0", ")", "{", "html", "+=", "'\\n'", ";", "}", "html", "+=", "jsonStringifyIfObject", "(", "response", ".", "body", ")", ".", "trim", "(", ")", "+", "'\\n'", ";", "}", "html", "+=", "'</pre>\\n'", ";", "}", "// TODO Document all unique possible status codes?", "// TODO Document all request parameters?", "}", "}", "// Export children's request handlers recursively.", "for", "(", "var", "path", "in", "this", ".", "children", ")", "{", "var", "child", "=", "this", ".", "children", "[", "path", "]", ";", "html", "+=", "child", ".", "toHTML", "(", "fullPath", ",", "anchors", ")", ";", "}", "return", "html", ";", "}" ]
Export API documentation as HTML.
[ "Export", "API", "documentation", "as", "HTML", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L407-L505
47,275
JanitorTechnology/selfapi
selfapi.js
function (basePath) { var fullPath = normalizePath(this.path, basePath) || '/'; var markdown = ''; if (this.title) { markdown += '# ' + this.title + '\n\n'; } if (this.description) { markdown += this.description + '\n\n'; } // Export own request handlers. for (var method in this.handlers) { var handler = this.handlers[method]; markdown += '## ' + (handler.title || '(no title)') + '\n\n'; markdown += ' ' + method.toUpperCase() + ' ' + fullPath + '\n\n'; if (handler.description) { markdown += handler.description + '\n\n'; } if (handler.examples && handler.examples.length > 0) { var example = handler.examples[0]; var request = example.request || {}; if (request.urlParameters || request.headers || request.body) { markdown += '### Example input:\n\n'; var exampleURL = ' ' + method.toUpperCase() + ' ' + fullPath; if (request.urlParameters) { exampleURL = replaceUrlParameters(exampleURL, request.urlParameters); } markdown += exampleURL + '\n'; var requestHeaders = request.headers || {}; for (var header in requestHeaders) { markdown += ' ' + header + ': ' + requestHeaders[header] + '\n'; } if (request.body) { var requestBody = ' ' + jsonStringifyIfObject(request.body) .trim().replace(/\n/g, '\n '); markdown += ' \n' + requestBody + '\n'; } markdown += '\n'; } var response = example.response || {}; var hasResponseStatus = isExplicitExample(response.status); var hasResponseBody = isExplicitExample(response.body); if (hasResponseStatus || response.headers || hasResponseBody) { markdown += '### Example response:\n\n'; if (hasResponseStatus) { var message = http.STATUS_CODES[response.status]; markdown += ' Status: ' + response.status + ' ' + message + '\n'; } var responseHeaders = response.headers || {}; for (var header in responseHeaders) { var value = responseHeaders[header]; if (isExplicitExample(value)) { markdown += ' ' + header + ': ' + value + '\n'; } } if (hasResponseBody) { if (hasResponseStatus || Object.keys(responseHeaders).length > 0) { markdown += ' \n'; } markdown += ' ' + jsonStringifyIfObject(response.body).trim() .replace(/\n/g, '\n ') + '\n'; } markdown += '\n'; } // TODO Document all unique possible status codes? // TODO Document all request parameters? } } // Export children's request handlers recursively. for (var path in this.children) { var child = this.children[path]; markdown += child.toMarkdown(fullPath); } return markdown; }
javascript
function (basePath) { var fullPath = normalizePath(this.path, basePath) || '/'; var markdown = ''; if (this.title) { markdown += '# ' + this.title + '\n\n'; } if (this.description) { markdown += this.description + '\n\n'; } // Export own request handlers. for (var method in this.handlers) { var handler = this.handlers[method]; markdown += '## ' + (handler.title || '(no title)') + '\n\n'; markdown += ' ' + method.toUpperCase() + ' ' + fullPath + '\n\n'; if (handler.description) { markdown += handler.description + '\n\n'; } if (handler.examples && handler.examples.length > 0) { var example = handler.examples[0]; var request = example.request || {}; if (request.urlParameters || request.headers || request.body) { markdown += '### Example input:\n\n'; var exampleURL = ' ' + method.toUpperCase() + ' ' + fullPath; if (request.urlParameters) { exampleURL = replaceUrlParameters(exampleURL, request.urlParameters); } markdown += exampleURL + '\n'; var requestHeaders = request.headers || {}; for (var header in requestHeaders) { markdown += ' ' + header + ': ' + requestHeaders[header] + '\n'; } if (request.body) { var requestBody = ' ' + jsonStringifyIfObject(request.body) .trim().replace(/\n/g, '\n '); markdown += ' \n' + requestBody + '\n'; } markdown += '\n'; } var response = example.response || {}; var hasResponseStatus = isExplicitExample(response.status); var hasResponseBody = isExplicitExample(response.body); if (hasResponseStatus || response.headers || hasResponseBody) { markdown += '### Example response:\n\n'; if (hasResponseStatus) { var message = http.STATUS_CODES[response.status]; markdown += ' Status: ' + response.status + ' ' + message + '\n'; } var responseHeaders = response.headers || {}; for (var header in responseHeaders) { var value = responseHeaders[header]; if (isExplicitExample(value)) { markdown += ' ' + header + ': ' + value + '\n'; } } if (hasResponseBody) { if (hasResponseStatus || Object.keys(responseHeaders).length > 0) { markdown += ' \n'; } markdown += ' ' + jsonStringifyIfObject(response.body).trim() .replace(/\n/g, '\n ') + '\n'; } markdown += '\n'; } // TODO Document all unique possible status codes? // TODO Document all request parameters? } } // Export children's request handlers recursively. for (var path in this.children) { var child = this.children[path]; markdown += child.toMarkdown(fullPath); } return markdown; }
[ "function", "(", "basePath", ")", "{", "var", "fullPath", "=", "normalizePath", "(", "this", ".", "path", ",", "basePath", ")", "||", "'/'", ";", "var", "markdown", "=", "''", ";", "if", "(", "this", ".", "title", ")", "{", "markdown", "+=", "'# '", "+", "this", ".", "title", "+", "'\\n\\n'", ";", "}", "if", "(", "this", ".", "description", ")", "{", "markdown", "+=", "this", ".", "description", "+", "'\\n\\n'", ";", "}", "// Export own request handlers.", "for", "(", "var", "method", "in", "this", ".", "handlers", ")", "{", "var", "handler", "=", "this", ".", "handlers", "[", "method", "]", ";", "markdown", "+=", "'## '", "+", "(", "handler", ".", "title", "||", "'(no title)'", ")", "+", "'\\n\\n'", ";", "markdown", "+=", "' '", "+", "method", ".", "toUpperCase", "(", ")", "+", "' '", "+", "fullPath", "+", "'\\n\\n'", ";", "if", "(", "handler", ".", "description", ")", "{", "markdown", "+=", "handler", ".", "description", "+", "'\\n\\n'", ";", "}", "if", "(", "handler", ".", "examples", "&&", "handler", ".", "examples", ".", "length", ">", "0", ")", "{", "var", "example", "=", "handler", ".", "examples", "[", "0", "]", ";", "var", "request", "=", "example", ".", "request", "||", "{", "}", ";", "if", "(", "request", ".", "urlParameters", "||", "request", ".", "headers", "||", "request", ".", "body", ")", "{", "markdown", "+=", "'### Example input:\\n\\n'", ";", "var", "exampleURL", "=", "' '", "+", "method", ".", "toUpperCase", "(", ")", "+", "' '", "+", "fullPath", ";", "if", "(", "request", ".", "urlParameters", ")", "{", "exampleURL", "=", "replaceUrlParameters", "(", "exampleURL", ",", "request", ".", "urlParameters", ")", ";", "}", "markdown", "+=", "exampleURL", "+", "'\\n'", ";", "var", "requestHeaders", "=", "request", ".", "headers", "||", "{", "}", ";", "for", "(", "var", "header", "in", "requestHeaders", ")", "{", "markdown", "+=", "' '", "+", "header", "+", "': '", "+", "requestHeaders", "[", "header", "]", "+", "'\\n'", ";", "}", "if", "(", "request", ".", "body", ")", "{", "var", "requestBody", "=", "' '", "+", "jsonStringifyIfObject", "(", "request", ".", "body", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'\\n '", ")", ";", "markdown", "+=", "' \\n'", "+", "requestBody", "+", "'\\n'", ";", "}", "markdown", "+=", "'\\n'", ";", "}", "var", "response", "=", "example", ".", "response", "||", "{", "}", ";", "var", "hasResponseStatus", "=", "isExplicitExample", "(", "response", ".", "status", ")", ";", "var", "hasResponseBody", "=", "isExplicitExample", "(", "response", ".", "body", ")", ";", "if", "(", "hasResponseStatus", "||", "response", ".", "headers", "||", "hasResponseBody", ")", "{", "markdown", "+=", "'### Example response:\\n\\n'", ";", "if", "(", "hasResponseStatus", ")", "{", "var", "message", "=", "http", ".", "STATUS_CODES", "[", "response", ".", "status", "]", ";", "markdown", "+=", "' Status: '", "+", "response", ".", "status", "+", "' '", "+", "message", "+", "'\\n'", ";", "}", "var", "responseHeaders", "=", "response", ".", "headers", "||", "{", "}", ";", "for", "(", "var", "header", "in", "responseHeaders", ")", "{", "var", "value", "=", "responseHeaders", "[", "header", "]", ";", "if", "(", "isExplicitExample", "(", "value", ")", ")", "{", "markdown", "+=", "' '", "+", "header", "+", "': '", "+", "value", "+", "'\\n'", ";", "}", "}", "if", "(", "hasResponseBody", ")", "{", "if", "(", "hasResponseStatus", "||", "Object", ".", "keys", "(", "responseHeaders", ")", ".", "length", ">", "0", ")", "{", "markdown", "+=", "' \\n'", ";", "}", "markdown", "+=", "' '", "+", "jsonStringifyIfObject", "(", "response", ".", "body", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'\\n '", ")", "+", "'\\n'", ";", "}", "markdown", "+=", "'\\n'", ";", "}", "// TODO Document all unique possible status codes?", "// TODO Document all request parameters?", "}", "}", "// Export children's request handlers recursively.", "for", "(", "var", "path", "in", "this", ".", "children", ")", "{", "var", "child", "=", "this", ".", "children", "[", "path", "]", ";", "markdown", "+=", "child", ".", "toMarkdown", "(", "fullPath", ")", ";", "}", "return", "markdown", ";", "}" ]
Export API documentation as Markdown.
[ "Export", "API", "documentation", "as", "Markdown", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L508-L589
47,276
JanitorTechnology/selfapi
selfapi.js
isServerApp
function isServerApp (app) { return !!(app && (app.use || app.handle) && app.get && app.post); }
javascript
function isServerApp (app) { return !!(app && (app.use || app.handle) && app.get && app.post); }
[ "function", "isServerApp", "(", "app", ")", "{", "return", "!", "!", "(", "app", "&&", "(", "app", ".", "use", "||", "app", ".", "handle", ")", "&&", "app", ".", "get", "&&", "app", ".", "post", ")", ";", "}" ]
Detect if `app` is an express-like server.
[ "Detect", "if", "app", "is", "an", "express", "-", "like", "server", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L608-L610
47,277
JanitorTechnology/selfapi
selfapi.js
getHandlerExporter
function getHandlerExporter (app) { if (!isServerApp(app)) { return null; } // `app` is an express-like server app. return function (method, path, parameters) { // Support restify. if (method === 'del' && ('delete' in app)) { method = 'delete'; } app[method](path, parameters.handler); }; }
javascript
function getHandlerExporter (app) { if (!isServerApp(app)) { return null; } // `app` is an express-like server app. return function (method, path, parameters) { // Support restify. if (method === 'del' && ('delete' in app)) { method = 'delete'; } app[method](path, parameters.handler); }; }
[ "function", "getHandlerExporter", "(", "app", ")", "{", "if", "(", "!", "isServerApp", "(", "app", ")", ")", "{", "return", "null", ";", "}", "// `app` is an express-like server app.", "return", "function", "(", "method", ",", "path", ",", "parameters", ")", "{", "// Support restify.", "if", "(", "method", "===", "'del'", "&&", "(", "'delete'", "in", "app", ")", ")", "{", "method", "=", "'delete'", ";", "}", "app", "[", "method", "]", "(", "path", ",", "parameters", ".", "handler", ")", ";", "}", ";", "}" ]
Try to create a handler exporter function for a given server app.
[ "Try", "to", "create", "a", "handler", "exporter", "function", "for", "a", "given", "server", "app", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L613-L626
47,278
JanitorTechnology/selfapi
selfapi.js
jsonStringifyWithFunctions
function jsonStringifyWithFunctions (value) { function replacer (key, value) { if (typeof value === 'function') { // Stringify this function, and slightly minify it. value = String(value).replace(/\s+/g, ' '); } return options.jsonStringifyReplacer(key, value); } return JSON.stringify(value, replacer, options.jsonStringifySpaces); }
javascript
function jsonStringifyWithFunctions (value) { function replacer (key, value) { if (typeof value === 'function') { // Stringify this function, and slightly minify it. value = String(value).replace(/\s+/g, ' '); } return options.jsonStringifyReplacer(key, value); } return JSON.stringify(value, replacer, options.jsonStringifySpaces); }
[ "function", "jsonStringifyWithFunctions", "(", "value", ")", "{", "function", "replacer", "(", "key", ",", "value", ")", "{", "if", "(", "typeof", "value", "===", "'function'", ")", "{", "// Stringify this function, and slightly minify it.", "value", "=", "String", "(", "value", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "' '", ")", ";", "}", "return", "options", ".", "jsonStringifyReplacer", "(", "key", ",", "value", ")", ";", "}", "return", "JSON", ".", "stringify", "(", "value", ",", "replacer", ",", "options", ".", "jsonStringifySpaces", ")", ";", "}" ]
Stringify everything, including Function bodies.
[ "Stringify", "everything", "including", "Function", "bodies", "." ]
8d6bbea299c9a8acef92a9c476b941660d0ef982
https://github.com/JanitorTechnology/selfapi/blob/8d6bbea299c9a8acef92a9c476b941660d0ef982/selfapi.js#L651-L660
47,279
3rd-Eden/shrinkwrap
module.js
Module
function Module(data, range, depth) { this._id = data.name +'@'+ range; // An unique id that identifies this module. this.released = data.released; // The date this version go released. this.licenses = data.licenses; // The licensing. this.version = data.version; // The version of the module. this.author = data._npmUser || {}; // Author of the release. this.latest = data.latest; // What the latest version is of the module. this.required = range; // Which range we required to find this module. this.name = data.name; // The name of the module. this.parents = []; // Modules that depend on this version. this.dependent = []; // Modules that depend on this version. this.depth = depth; // The depth of the dependency nesting. }
javascript
function Module(data, range, depth) { this._id = data.name +'@'+ range; // An unique id that identifies this module. this.released = data.released; // The date this version go released. this.licenses = data.licenses; // The licensing. this.version = data.version; // The version of the module. this.author = data._npmUser || {}; // Author of the release. this.latest = data.latest; // What the latest version is of the module. this.required = range; // Which range we required to find this module. this.name = data.name; // The name of the module. this.parents = []; // Modules that depend on this version. this.dependent = []; // Modules that depend on this version. this.depth = depth; // The depth of the dependency nesting. }
[ "function", "Module", "(", "data", ",", "range", ",", "depth", ")", "{", "this", ".", "_id", "=", "data", ".", "name", "+", "'@'", "+", "range", ";", "// An unique id that identifies this module.", "this", ".", "released", "=", "data", ".", "released", ";", "// The date this version go released.", "this", ".", "licenses", "=", "data", ".", "licenses", ";", "// The licensing.", "this", ".", "version", "=", "data", ".", "version", ";", "// The version of the module.", "this", ".", "author", "=", "data", ".", "_npmUser", "||", "{", "}", ";", "// Author of the release.", "this", ".", "latest", "=", "data", ".", "latest", ";", "// What the latest version is of the module.", "this", ".", "required", "=", "range", ";", "// Which range we required to find this module.", "this", ".", "name", "=", "data", ".", "name", ";", "// The name of the module.", "this", ".", "parents", "=", "[", "]", ";", "// Modules that depend on this version.", "this", ".", "dependent", "=", "[", "]", ";", "// Modules that depend on this version.", "this", ".", "depth", "=", "depth", ";", "// The depth of the dependency nesting.", "}" ]
The representation of a single module. @constructor @param {Object} data The module data. @param {String} range The semver range used to get this version. @param {Number} depth How deeply nested was this module. @api private
[ "The", "representation", "of", "a", "single", "module", "." ]
60e0004e4092896e9ba6bd0d83bdc22a973812da
https://github.com/3rd-Eden/shrinkwrap/blob/60e0004e4092896e9ba6bd0d83bdc22a973812da/module.js#L14-L26
47,280
dominictarr/level-scuttlebutt
index.js
checkOld
function checkOld (id, ts) { return false if(sources[id] && sources[id] >= ts) return true sources[id] = ts }
javascript
function checkOld (id, ts) { return false if(sources[id] && sources[id] >= ts) return true sources[id] = ts }
[ "function", "checkOld", "(", "id", ",", "ts", ")", "{", "return", "false", "if", "(", "sources", "[", "id", "]", "&&", "sources", "[", "id", "]", ">=", "ts", ")", "return", "true", "sources", "[", "id", "]", "=", "ts", "}" ]
WHY DID I DO THIS? - remove this and it works. but it seems to be problem with r-array...
[ "WHY", "DID", "I", "DO", "THIS?", "-", "remove", "this", "and", "it", "works", ".", "but", "it", "seems", "to", "be", "problem", "with", "r", "-", "array", "..." ]
fe0f9b68579b391e6995a5ca250ebc54a7fa93a3
https://github.com/dominictarr/level-scuttlebutt/blob/fe0f9b68579b391e6995a5ca250ebc54a7fa93a3/index.js#L39-L43
47,281
dominictarr/level-scuttlebutt
index.js
onUpdate
function onUpdate (update) { var value = update[0], ts = update[1], id = update[2] insertBatch (id, key, ts, JSON.stringify(value), scuttlebutt) }
javascript
function onUpdate (update) { var value = update[0], ts = update[1], id = update[2] insertBatch (id, key, ts, JSON.stringify(value), scuttlebutt) }
[ "function", "onUpdate", "(", "update", ")", "{", "var", "value", "=", "update", "[", "0", "]", ",", "ts", "=", "update", "[", "1", "]", ",", "id", "=", "update", "[", "2", "]", "insertBatch", "(", "id", ",", "key", ",", "ts", ",", "JSON", ".", "stringify", "(", "value", ")", ",", "scuttlebutt", ")", "}" ]
write the update twice, the first time, to store the document. maybe change scuttlebutt so that value is always a string? If i write a bunch of batches, will they come out in order? because I think updates are expected in order, or it will break.
[ "write", "the", "update", "twice", "the", "first", "time", "to", "store", "the", "document", ".", "maybe", "change", "scuttlebutt", "so", "that", "value", "is", "always", "a", "string?", "If", "i", "write", "a", "bunch", "of", "batches", "will", "they", "come", "out", "in", "order?", "because", "I", "think", "updates", "are", "expected", "in", "order", "or", "it", "will", "break", "." ]
fe0f9b68579b391e6995a5ca250ebc54a7fa93a3
https://github.com/dominictarr/level-scuttlebutt/blob/fe0f9b68579b391e6995a5ca250ebc54a7fa93a3/index.js#L188-L191
47,282
sfrdmn/node-route-order
index.js
freeVariableWeight
function freeVariableWeight(sliced) { return sliced.reduce(function(acc, part, i) { // If is bound part if (!/^:.+$/.test(part)) { // Weight is positively correlated to indexes of bound parts acc += Math.pow(i + 1, sliced.length) } return acc }, 0) }
javascript
function freeVariableWeight(sliced) { return sliced.reduce(function(acc, part, i) { // If is bound part if (!/^:.+$/.test(part)) { // Weight is positively correlated to indexes of bound parts acc += Math.pow(i + 1, sliced.length) } return acc }, 0) }
[ "function", "freeVariableWeight", "(", "sliced", ")", "{", "return", "sliced", ".", "reduce", "(", "function", "(", "acc", ",", "part", ",", "i", ")", "{", "// If is bound part", "if", "(", "!", "/", "^:.+$", "/", ".", "test", "(", "part", ")", ")", "{", "// Weight is positively correlated to indexes of bound parts", "acc", "+=", "Math", ".", "pow", "(", "i", "+", "1", ",", "sliced", ".", "length", ")", "}", "return", "acc", "}", ",", "0", ")", "}" ]
Takes a sliced path and returns an integer representing the "weight" of its free variables. More specific routes are heavier Intuitively: when a free variable is at the base of a path e.g. '/:resource', this is more generic than '/resourceName/:id' and thus has a lower weight Weight can only be used to compare paths of the same depth
[ "Takes", "a", "sliced", "path", "and", "returns", "an", "integer", "representing", "the", "weight", "of", "its", "free", "variables", ".", "More", "specific", "routes", "are", "heavier" ]
b0d695a3096968729b38e045cd9f7dc03148da6d
https://github.com/sfrdmn/node-route-order/blob/b0d695a3096968729b38e045cd9f7dc03148da6d/index.js#L54-L63
47,283
theThings/jailed-node
lib/Connection.js
BasicConnection
function BasicConnection() { var _this = this this._disconnected = false this._messageHandler = function() { } this._disconnectHandler = function() { } var childArgs = [] process.execArgv.forEach(function(arg) { if (arg.indexOf('--debug-brk') !== -1) { var _debugPort = parseInt(arg.substr(12)) + 1 debug('Child process debugger listening on port %d', _debugPort) childArgs.push('--debug-brk=' + _debugPort) } }) this._process = child_process.fork(__dirname + '/../sandbox/sandbox.js', childArgs) this._startHeartBeat() this._process.on('message', function(data) { var m = codec.decode(data); debug('Recibing message: %j', m) _this._messageHandler(m) }) this._process.on('exit', function(m) { debug('Exit process: %j', m) _this._stopHeartBeat() _this._disconnected = true _this._disconnectHandler(m) }) }
javascript
function BasicConnection() { var _this = this this._disconnected = false this._messageHandler = function() { } this._disconnectHandler = function() { } var childArgs = [] process.execArgv.forEach(function(arg) { if (arg.indexOf('--debug-brk') !== -1) { var _debugPort = parseInt(arg.substr(12)) + 1 debug('Child process debugger listening on port %d', _debugPort) childArgs.push('--debug-brk=' + _debugPort) } }) this._process = child_process.fork(__dirname + '/../sandbox/sandbox.js', childArgs) this._startHeartBeat() this._process.on('message', function(data) { var m = codec.decode(data); debug('Recibing message: %j', m) _this._messageHandler(m) }) this._process.on('exit', function(m) { debug('Exit process: %j', m) _this._stopHeartBeat() _this._disconnected = true _this._disconnectHandler(m) }) }
[ "function", "BasicConnection", "(", ")", "{", "var", "_this", "=", "this", "this", ".", "_disconnected", "=", "false", "this", ".", "_messageHandler", "=", "function", "(", ")", "{", "}", "this", ".", "_disconnectHandler", "=", "function", "(", ")", "{", "}", "var", "childArgs", "=", "[", "]", "process", ".", "execArgv", ".", "forEach", "(", "function", "(", "arg", ")", "{", "if", "(", "arg", ".", "indexOf", "(", "'--debug-brk'", ")", "!==", "-", "1", ")", "{", "var", "_debugPort", "=", "parseInt", "(", "arg", ".", "substr", "(", "12", ")", ")", "+", "1", "debug", "(", "'Child process debugger listening on port %d'", ",", "_debugPort", ")", "childArgs", ".", "push", "(", "'--debug-brk='", "+", "_debugPort", ")", "}", "}", ")", "this", ".", "_process", "=", "child_process", ".", "fork", "(", "__dirname", "+", "'/../sandbox/sandbox.js'", ",", "childArgs", ")", "this", ".", "_startHeartBeat", "(", ")", "this", ".", "_process", ".", "on", "(", "'message'", ",", "function", "(", "data", ")", "{", "var", "m", "=", "codec", ".", "decode", "(", "data", ")", ";", "debug", "(", "'Recibing message: %j'", ",", "m", ")", "_this", ".", "_messageHandler", "(", "m", ")", "}", ")", "this", ".", "_process", ".", "on", "(", "'exit'", ",", "function", "(", "m", ")", "{", "debug", "(", "'Exit process: %j'", ",", "m", ")", "_this", ".", "_stopHeartBeat", "(", ")", "_this", ".", "_disconnected", "=", "true", "_this", ".", "_disconnectHandler", "(", "m", ")", "}", ")", "}" ]
Platform-dependent implementation of the BasicConnection object, initializes the plugin site and provides the basic messaging-based connection with it For Node.js the plugin is created as a forked process
[ "Platform", "-", "dependent", "implementation", "of", "the", "BasicConnection", "object", "initializes", "the", "plugin", "site", "and", "provides", "the", "basic", "messaging", "-", "based", "connection", "with", "it" ]
6e453d97e74fbd1c0b27b982084f6fd7c1aa0173
https://github.com/theThings/jailed-node/blob/6e453d97e74fbd1c0b27b982084f6fd7c1aa0173/lib/Connection.js#L21-L56
47,284
thlorenz/6bit-encoder
6bit-encoder.js
decode2
function decode2(s) { assert.equal(s.length, 2) const [ upper, lower ] = s return (decode(upper) << 6) | decode(lower) }
javascript
function decode2(s) { assert.equal(s.length, 2) const [ upper, lower ] = s return (decode(upper) << 6) | decode(lower) }
[ "function", "decode2", "(", "s", ")", "{", "assert", ".", "equal", "(", "s", ".", "length", ",", "2", ")", "const", "[", "upper", ",", "lower", "]", "=", "s", "return", "(", "decode", "(", "upper", ")", "<<", "6", ")", "|", "decode", "(", "lower", ")", "}" ]
Decodes two chars into a 12 bit number @name decode2 @param {String} s the chars to decode @returns {Number} a 12 bit number
[ "Decodes", "two", "chars", "into", "a", "12", "bit", "number" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L82-L86
47,285
thlorenz/6bit-encoder
6bit-encoder.js
decode3
function decode3(s) { assert.equal(s.length, 3) const [ upper, mid, lower ] = s return (decode(upper) << 12) | (decode(mid) << 6) | decode(lower) }
javascript
function decode3(s) { assert.equal(s.length, 3) const [ upper, mid, lower ] = s return (decode(upper) << 12) | (decode(mid) << 6) | decode(lower) }
[ "function", "decode3", "(", "s", ")", "{", "assert", ".", "equal", "(", "s", ".", "length", ",", "3", ")", "const", "[", "upper", ",", "mid", ",", "lower", "]", "=", "s", "return", "(", "decode", "(", "upper", ")", "<<", "12", ")", "|", "(", "decode", "(", "mid", ")", "<<", "6", ")", "|", "decode", "(", "lower", ")", "}" ]
Decodes three chars into an 18 bit number @name decode3 @param {String} s the chars to decode @returns {Number} an 18 bit number
[ "Decodes", "three", "chars", "into", "an", "18", "bit", "number" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L96-L100
47,286
thlorenz/6bit-encoder
6bit-encoder.js
decode4
function decode4(s) { assert.equal(s.length, 4) const [ upper, belowUpper, aboveLower, lower ] = s return (decode(upper) << 18) | (decode(belowUpper) << 12) | (decode(aboveLower) << 6) | decode(lower) }
javascript
function decode4(s) { assert.equal(s.length, 4) const [ upper, belowUpper, aboveLower, lower ] = s return (decode(upper) << 18) | (decode(belowUpper) << 12) | (decode(aboveLower) << 6) | decode(lower) }
[ "function", "decode4", "(", "s", ")", "{", "assert", ".", "equal", "(", "s", ".", "length", ",", "4", ")", "const", "[", "upper", ",", "belowUpper", ",", "aboveLower", ",", "lower", "]", "=", "s", "return", "(", "decode", "(", "upper", ")", "<<", "18", ")", "|", "(", "decode", "(", "belowUpper", ")", "<<", "12", ")", "|", "(", "decode", "(", "aboveLower", ")", "<<", "6", ")", "|", "decode", "(", "lower", ")", "}" ]
Decodes four chars into an 24 bit number @name decode4 @param {String} s the chars to decode @returns {Number} a 24 bit number
[ "Decodes", "four", "chars", "into", "an", "24", "bit", "number" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L110-L115
47,287
thlorenz/6bit-encoder
6bit-encoder.js
decode5
function decode5(s) { assert.equal(s.length, 5) const [ upper, belowUpper, mid, aboveLower, lower ] = s return (decode(upper) << 24) | (decode(belowUpper) << 18) | (decode(mid) << 12) | (decode(aboveLower) << 6) | decode(lower) }
javascript
function decode5(s) { assert.equal(s.length, 5) const [ upper, belowUpper, mid, aboveLower, lower ] = s return (decode(upper) << 24) | (decode(belowUpper) << 18) | (decode(mid) << 12) | (decode(aboveLower) << 6) | decode(lower) }
[ "function", "decode5", "(", "s", ")", "{", "assert", ".", "equal", "(", "s", ".", "length", ",", "5", ")", "const", "[", "upper", ",", "belowUpper", ",", "mid", ",", "aboveLower", ",", "lower", "]", "=", "s", "return", "(", "decode", "(", "upper", ")", "<<", "24", ")", "|", "(", "decode", "(", "belowUpper", ")", "<<", "18", ")", "|", "(", "decode", "(", "mid", ")", "<<", "12", ")", "|", "(", "decode", "(", "aboveLower", ")", "<<", "6", ")", "|", "decode", "(", "lower", ")", "}" ]
Decodes five chars into an 30 bit number @name decode5 @param {String} s the chars to decode @returns {Number} a 30 bit number
[ "Decodes", "five", "chars", "into", "an", "30", "bit", "number" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L125-L130
47,288
thlorenz/6bit-encoder
6bit-encoder.js
encode2
function encode2(n) { assert(0 <= n && n <= 0xfff, ENCODE_OUTOFBOUNDS + n) // 12 bits -> 2 digits const lower = isolate(n, 0, 6) const upper = isolate(n, 6, 6) return encode(upper) + encode(lower) }
javascript
function encode2(n) { assert(0 <= n && n <= 0xfff, ENCODE_OUTOFBOUNDS + n) // 12 bits -> 2 digits const lower = isolate(n, 0, 6) const upper = isolate(n, 6, 6) return encode(upper) + encode(lower) }
[ "function", "encode2", "(", "n", ")", "{", "assert", "(", "0", "<=", "n", "&&", "n", "<=", "0xfff", ",", "ENCODE_OUTOFBOUNDS", "+", "n", ")", "// 12 bits -> 2 digits", "const", "lower", "=", "isolate", "(", "n", ",", "0", ",", "6", ")", "const", "upper", "=", "isolate", "(", "n", ",", "6", ",", "6", ")", "return", "encode", "(", "upper", ")", "+", "encode", "(", "lower", ")", "}" ]
Encodes a 12 bit number into two URL safe chars @name encode2 @param {Number} n a 12 bit number @returns {String} the chars
[ "Encodes", "a", "12", "bit", "number", "into", "two", "URL", "safe", "chars" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L154-L160
47,289
thlorenz/6bit-encoder
6bit-encoder.js
encode3
function encode3(n) { assert(0 <= n && n <= 0x3ffff, ENCODE_OUTOFBOUNDS + n) // 18 bits -> 3 digits const lower = isolate(n, 0, 6) const mid = isolate(n, 6, 6) const upper = isolate(n, 12, 6) return encode(upper) + encode(mid) + encode(lower) }
javascript
function encode3(n) { assert(0 <= n && n <= 0x3ffff, ENCODE_OUTOFBOUNDS + n) // 18 bits -> 3 digits const lower = isolate(n, 0, 6) const mid = isolate(n, 6, 6) const upper = isolate(n, 12, 6) return encode(upper) + encode(mid) + encode(lower) }
[ "function", "encode3", "(", "n", ")", "{", "assert", "(", "0", "<=", "n", "&&", "n", "<=", "0x3ffff", ",", "ENCODE_OUTOFBOUNDS", "+", "n", ")", "// 18 bits -> 3 digits", "const", "lower", "=", "isolate", "(", "n", ",", "0", ",", "6", ")", "const", "mid", "=", "isolate", "(", "n", ",", "6", ",", "6", ")", "const", "upper", "=", "isolate", "(", "n", ",", "12", ",", "6", ")", "return", "encode", "(", "upper", ")", "+", "encode", "(", "mid", ")", "+", "encode", "(", "lower", ")", "}" ]
Encodes a 18 bit number into three URL safe chars @name encode3 @param {Number} n a 18 bit number @returns {String} the chars
[ "Encodes", "a", "18", "bit", "number", "into", "three", "URL", "safe", "chars" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L170-L177
47,290
thlorenz/6bit-encoder
6bit-encoder.js
encode4
function encode4(n) { assert(0 <= n && n <= 0xffffff, ENCODE_OUTOFBOUNDS + n) // 24 bits -> 4 digits const lower = isolate(n, 0, 6) const aboveLower = isolate(n, 6, 6) const belowUpper = isolate(n, 12, 6) const upper = isolate(n, 18, 6) return encode(upper) + encode(belowUpper) + encode(aboveLower) + encode(lower) }
javascript
function encode4(n) { assert(0 <= n && n <= 0xffffff, ENCODE_OUTOFBOUNDS + n) // 24 bits -> 4 digits const lower = isolate(n, 0, 6) const aboveLower = isolate(n, 6, 6) const belowUpper = isolate(n, 12, 6) const upper = isolate(n, 18, 6) return encode(upper) + encode(belowUpper) + encode(aboveLower) + encode(lower) }
[ "function", "encode4", "(", "n", ")", "{", "assert", "(", "0", "<=", "n", "&&", "n", "<=", "0xffffff", ",", "ENCODE_OUTOFBOUNDS", "+", "n", ")", "// 24 bits -> 4 digits", "const", "lower", "=", "isolate", "(", "n", ",", "0", ",", "6", ")", "const", "aboveLower", "=", "isolate", "(", "n", ",", "6", ",", "6", ")", "const", "belowUpper", "=", "isolate", "(", "n", ",", "12", ",", "6", ")", "const", "upper", "=", "isolate", "(", "n", ",", "18", ",", "6", ")", "return", "encode", "(", "upper", ")", "+", "encode", "(", "belowUpper", ")", "+", "encode", "(", "aboveLower", ")", "+", "encode", "(", "lower", ")", "}" ]
Encodes a 24 bit number into four URL safe chars @name encode4 @param {Number} n a 24 bit number @returns {String} the chars
[ "Encodes", "a", "24", "bit", "number", "into", "four", "URL", "safe", "chars" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L187-L196
47,291
thlorenz/6bit-encoder
6bit-encoder.js
encode5
function encode5(n) { assert(0 <= n && n <= 0x3fffffff, ENCODE_OUTOFBOUNDS + n) // 30 bits -> 5 digits const lower = isolate(n, 0, 6) const aboveLower = isolate(n, 6, 6) const mid = isolate(n, 12, 6) const belowUpper = isolate(n, 18, 6) const upper = isolate(n, 24, 6) return encode(upper) + encode(belowUpper) + encode(mid) + encode(aboveLower) + encode(lower) }
javascript
function encode5(n) { assert(0 <= n && n <= 0x3fffffff, ENCODE_OUTOFBOUNDS + n) // 30 bits -> 5 digits const lower = isolate(n, 0, 6) const aboveLower = isolate(n, 6, 6) const mid = isolate(n, 12, 6) const belowUpper = isolate(n, 18, 6) const upper = isolate(n, 24, 6) return encode(upper) + encode(belowUpper) + encode(mid) + encode(aboveLower) + encode(lower) }
[ "function", "encode5", "(", "n", ")", "{", "assert", "(", "0", "<=", "n", "&&", "n", "<=", "0x3fffffff", ",", "ENCODE_OUTOFBOUNDS", "+", "n", ")", "// 30 bits -> 5 digits", "const", "lower", "=", "isolate", "(", "n", ",", "0", ",", "6", ")", "const", "aboveLower", "=", "isolate", "(", "n", ",", "6", ",", "6", ")", "const", "mid", "=", "isolate", "(", "n", ",", "12", ",", "6", ")", "const", "belowUpper", "=", "isolate", "(", "n", ",", "18", ",", "6", ")", "const", "upper", "=", "isolate", "(", "n", ",", "24", ",", "6", ")", "return", "encode", "(", "upper", ")", "+", "encode", "(", "belowUpper", ")", "+", "encode", "(", "mid", ")", "+", "encode", "(", "aboveLower", ")", "+", "encode", "(", "lower", ")", "}" ]
Encodes a 30 bit number into five URL safe chars @name encode5 @param {Number} n a 30 bit number @returns {String} the chars
[ "Encodes", "a", "30", "bit", "number", "into", "five", "URL", "safe", "chars" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L206-L216
47,292
thlorenz/6bit-encoder
6bit-encoder.js
decodeFor
function decodeFor(n) { return ( n === 1 ? decode : n === 2 ? decode2 : n === 3 ? decode3 : n === 4 ? decode4 : decode5 ) }
javascript
function decodeFor(n) { return ( n === 1 ? decode : n === 2 ? decode2 : n === 3 ? decode3 : n === 4 ? decode4 : decode5 ) }
[ "function", "decodeFor", "(", "n", ")", "{", "return", "(", "n", "===", "1", "?", "decode", ":", "n", "===", "2", "?", "decode2", ":", "n", "===", "3", "?", "decode3", ":", "n", "===", "4", "?", "decode4", ":", "decode5", ")", "}" ]
Get a decode function to decode n chars @name decodeFor @param {Number} n the number of chars to decode @returns {function} the matching decoding function
[ "Get", "a", "decode", "function", "to", "decode", "n", "chars" ]
ea0449137b3c155dcd59bc37c852efa35240dddd
https://github.com/thlorenz/6bit-encoder/blob/ea0449137b3c155dcd59bc37c852efa35240dddd/6bit-encoder.js#L226-L234
47,293
jakubchadim/nightmare-react-utils
src/actions.js
function (selector, done) { this.evaluate_now((selector) => { let element = document.querySelector(selector) if (!element) { return false } for (let key in element) { if (key.startsWith('__reactInternalInstance$')) { return true } } return false }, done, selector) }
javascript
function (selector, done) { this.evaluate_now((selector) => { let element = document.querySelector(selector) if (!element) { return false } for (let key in element) { if (key.startsWith('__reactInternalInstance$')) { return true } } return false }, done, selector) }
[ "function", "(", "selector", ",", "done", ")", "{", "this", ".", "evaluate_now", "(", "(", "selector", ")", "=>", "{", "let", "element", "=", "document", ".", "querySelector", "(", "selector", ")", "if", "(", "!", "element", ")", "{", "return", "false", "}", "for", "(", "let", "key", "in", "element", ")", "{", "if", "(", "key", ".", "startsWith", "(", "'__reactInternalInstance$'", ")", ")", "{", "return", "true", "}", "}", "return", "false", "}", ",", "done", ",", "selector", ")", "}" ]
Check if react element exists @param {String} selector @param {Function} done @return {Boolean}
[ "Check", "if", "react", "element", "exists" ]
b36cf50e0016f59fdd4a53cc57f5b0e239394ce6
https://github.com/jakubchadim/nightmare-react-utils/blob/b36cf50e0016f59fdd4a53cc57f5b0e239394ce6/src/actions.js#L13-L28
47,294
jakubchadim/nightmare-react-utils
src/actions.js
function (selector, done) { this.evaluate_now((selector) => { let element = document.querySelector(selector) if (!element) { return null } for (let key in element) { if (key.startsWith('__reactInternalInstance$')) { const compInternals = element[key]._currentElement const compWrapper = compInternals._owner const {props, state, context} = compWrapper._instance return { props, state, context } } } return null }, done, selector) }
javascript
function (selector, done) { this.evaluate_now((selector) => { let element = document.querySelector(selector) if (!element) { return null } for (let key in element) { if (key.startsWith('__reactInternalInstance$')) { const compInternals = element[key]._currentElement const compWrapper = compInternals._owner const {props, state, context} = compWrapper._instance return { props, state, context } } } return null }, done, selector) }
[ "function", "(", "selector", ",", "done", ")", "{", "this", ".", "evaluate_now", "(", "(", "selector", ")", "=>", "{", "let", "element", "=", "document", ".", "querySelector", "(", "selector", ")", "if", "(", "!", "element", ")", "{", "return", "null", "}", "for", "(", "let", "key", "in", "element", ")", "{", "if", "(", "key", ".", "startsWith", "(", "'__reactInternalInstance$'", ")", ")", "{", "const", "compInternals", "=", "element", "[", "key", "]", ".", "_currentElement", "const", "compWrapper", "=", "compInternals", ".", "_owner", "const", "{", "props", ",", "state", ",", "context", "}", "=", "compWrapper", ".", "_instance", "return", "{", "props", ",", "state", ",", "context", "}", "}", "}", "return", "null", "}", ",", "done", ",", "selector", ")", "}" ]
Find react element by selector and return his values @param {String} selector @param {Function} done @return {{state: Object, props: Object, context: Object}}
[ "Find", "react", "element", "by", "selector", "and", "return", "his", "values" ]
b36cf50e0016f59fdd4a53cc57f5b0e239394ce6
https://github.com/jakubchadim/nightmare-react-utils/blob/b36cf50e0016f59fdd4a53cc57f5b0e239394ce6/src/actions.js#L37-L59
47,295
jakubchadim/nightmare-react-utils
src/actions.js
function (selector, done) { this.evaluate_now((selector) => { let elements = document.querySelectorAll(selector) if (!elements.length) { return [] } elements = [].slice.call(elements) // Convert to array return elements.map(element => { for (let key in element) { if (key.startsWith('__reactInternalInstance$')) { const compInternals = element[key]._currentElement const compWrapper = compInternals._owner const {props, state, context} = compWrapper._instance return { props, state, context } } } }).filter(e => e != null) }, done, selector) }
javascript
function (selector, done) { this.evaluate_now((selector) => { let elements = document.querySelectorAll(selector) if (!elements.length) { return [] } elements = [].slice.call(elements) // Convert to array return elements.map(element => { for (let key in element) { if (key.startsWith('__reactInternalInstance$')) { const compInternals = element[key]._currentElement const compWrapper = compInternals._owner const {props, state, context} = compWrapper._instance return { props, state, context } } } }).filter(e => e != null) }, done, selector) }
[ "function", "(", "selector", ",", "done", ")", "{", "this", ".", "evaluate_now", "(", "(", "selector", ")", "=>", "{", "let", "elements", "=", "document", ".", "querySelectorAll", "(", "selector", ")", "if", "(", "!", "elements", ".", "length", ")", "{", "return", "[", "]", "}", "elements", "=", "[", "]", ".", "slice", ".", "call", "(", "elements", ")", "// Convert to array", "return", "elements", ".", "map", "(", "element", "=>", "{", "for", "(", "let", "key", "in", "element", ")", "{", "if", "(", "key", ".", "startsWith", "(", "'__reactInternalInstance$'", ")", ")", "{", "const", "compInternals", "=", "element", "[", "key", "]", ".", "_currentElement", "const", "compWrapper", "=", "compInternals", ".", "_owner", "const", "{", "props", ",", "state", ",", "context", "}", "=", "compWrapper", ".", "_instance", "return", "{", "props", ",", "state", ",", "context", "}", "}", "}", "}", ")", ".", "filter", "(", "e", "=>", "e", "!=", "null", ")", "}", ",", "done", ",", "selector", ")", "}" ]
Find all react elements by selector and return their values @param {String} selector @param {Function} done @return {Array}
[ "Find", "all", "react", "elements", "by", "selector", "and", "return", "their", "values" ]
b36cf50e0016f59fdd4a53cc57f5b0e239394ce6
https://github.com/jakubchadim/nightmare-react-utils/blob/b36cf50e0016f59fdd4a53cc57f5b0e239394ce6/src/actions.js#L68-L92
47,296
jakubchadim/nightmare-react-utils
src/actions.js
waitfn
function waitfn () { const softTimeout = this.timeout || null const callback = this.callback let executionTimer let softTimeoutTimer let self = arguments[0] let args = sliced(arguments) let done = args[args.length - 1] let timeoutTimer = setTimeout(function () { clearTimeout(executionTimer) clearTimeout(softTimeoutTimer) done(new Error(`.wait() timed out after ${self.options.waitTimeout}msec`)) }, self.options.waitTimeout) return tick.apply(this, arguments) function tick (self, fn) { if (softTimeout) { softTimeoutTimer = setTimeout(function () { clearTimeout(executionTimer) clearTimeout(timeoutTimer) done() }, softTimeout) } let waitDone = function (err, result) { if (callback) { result = callback(result) } if (result) { clearTimeout(timeoutTimer) clearTimeout(softTimeoutTimer) return done() } else if (err) { clearTimeout(timeoutTimer) clearTimeout(softTimeoutTimer) return done(err) } else { executionTimer = setTimeout(function () { tick.apply(self, args) }, self.options.pollInterval) } } let newArgs = [fn, waitDone].concat(args.slice(2, -1)) self.evaluate_now.apply(self, newArgs) } }
javascript
function waitfn () { const softTimeout = this.timeout || null const callback = this.callback let executionTimer let softTimeoutTimer let self = arguments[0] let args = sliced(arguments) let done = args[args.length - 1] let timeoutTimer = setTimeout(function () { clearTimeout(executionTimer) clearTimeout(softTimeoutTimer) done(new Error(`.wait() timed out after ${self.options.waitTimeout}msec`)) }, self.options.waitTimeout) return tick.apply(this, arguments) function tick (self, fn) { if (softTimeout) { softTimeoutTimer = setTimeout(function () { clearTimeout(executionTimer) clearTimeout(timeoutTimer) done() }, softTimeout) } let waitDone = function (err, result) { if (callback) { result = callback(result) } if (result) { clearTimeout(timeoutTimer) clearTimeout(softTimeoutTimer) return done() } else if (err) { clearTimeout(timeoutTimer) clearTimeout(softTimeoutTimer) return done(err) } else { executionTimer = setTimeout(function () { tick.apply(self, args) }, self.options.pollInterval) } } let newArgs = [fn, waitDone].concat(args.slice(2, -1)) self.evaluate_now.apply(self, newArgs) } }
[ "function", "waitfn", "(", ")", "{", "const", "softTimeout", "=", "this", ".", "timeout", "||", "null", "const", "callback", "=", "this", ".", "callback", "let", "executionTimer", "let", "softTimeoutTimer", "let", "self", "=", "arguments", "[", "0", "]", "let", "args", "=", "sliced", "(", "arguments", ")", "let", "done", "=", "args", "[", "args", ".", "length", "-", "1", "]", "let", "timeoutTimer", "=", "setTimeout", "(", "function", "(", ")", "{", "clearTimeout", "(", "executionTimer", ")", "clearTimeout", "(", "softTimeoutTimer", ")", "done", "(", "new", "Error", "(", "`", "${", "self", ".", "options", ".", "waitTimeout", "}", "`", ")", ")", "}", ",", "self", ".", "options", ".", "waitTimeout", ")", "return", "tick", ".", "apply", "(", "this", ",", "arguments", ")", "function", "tick", "(", "self", ",", "fn", ")", "{", "if", "(", "softTimeout", ")", "{", "softTimeoutTimer", "=", "setTimeout", "(", "function", "(", ")", "{", "clearTimeout", "(", "executionTimer", ")", "clearTimeout", "(", "timeoutTimer", ")", "done", "(", ")", "}", ",", "softTimeout", ")", "}", "let", "waitDone", "=", "function", "(", "err", ",", "result", ")", "{", "if", "(", "callback", ")", "{", "result", "=", "callback", "(", "result", ")", "}", "if", "(", "result", ")", "{", "clearTimeout", "(", "timeoutTimer", ")", "clearTimeout", "(", "softTimeoutTimer", ")", "return", "done", "(", ")", "}", "else", "if", "(", "err", ")", "{", "clearTimeout", "(", "timeoutTimer", ")", "clearTimeout", "(", "softTimeoutTimer", ")", "return", "done", "(", "err", ")", "}", "else", "{", "executionTimer", "=", "setTimeout", "(", "function", "(", ")", "{", "tick", ".", "apply", "(", "self", ",", "args", ")", "}", ",", "self", ".", "options", ".", "pollInterval", ")", "}", "}", "let", "newArgs", "=", "[", "fn", ",", "waitDone", "]", ".", "concat", "(", "args", ".", "slice", "(", "2", ",", "-", "1", ")", ")", "self", ".", "evaluate_now", ".", "apply", "(", "self", ",", "newArgs", ")", "}", "}" ]
Wait until evaluated function returns true. @param {Nightmare} self @param {Function} fn @param {...} args @param {Function} done
[ "Wait", "until", "evaluated", "function", "returns", "true", "." ]
b36cf50e0016f59fdd4a53cc57f5b0e239394ce6
https://github.com/jakubchadim/nightmare-react-utils/blob/b36cf50e0016f59fdd4a53cc57f5b0e239394ce6/src/actions.js#L146-L193
47,297
jakubchadim/nightmare-react-utils
src/actions.js
waitelem
function waitelem (self, selector, done) { let elementPresent eval('elementPresent = function() {' + // eslint-disable-line ` var element = document.querySelector('${selector}');` + ' if (!element) { return null }' + ' for (let key in element) {' + ' if (key.startsWith(\'__reactInternalInstance$\')) {' + ' const compInternals = element[key]._currentElement;' + ' const compWrapper = compInternals._owner;' + ' const {props, state, context} = compWrapper._instance;' + ' return {props, state, context}' + ' }' + ' }' + ' return null;' + '}') waitfn.apply(this, [self, elementPresent, done]) }
javascript
function waitelem (self, selector, done) { let elementPresent eval('elementPresent = function() {' + // eslint-disable-line ` var element = document.querySelector('${selector}');` + ' if (!element) { return null }' + ' for (let key in element) {' + ' if (key.startsWith(\'__reactInternalInstance$\')) {' + ' const compInternals = element[key]._currentElement;' + ' const compWrapper = compInternals._owner;' + ' const {props, state, context} = compWrapper._instance;' + ' return {props, state, context}' + ' }' + ' }' + ' return null;' + '}') waitfn.apply(this, [self, elementPresent, done]) }
[ "function", "waitelem", "(", "self", ",", "selector", ",", "done", ")", "{", "let", "elementPresent", "eval", "(", "'elementPresent = function() {'", "+", "// eslint-disable-line", "`", "${", "selector", "}", "`", "+", "' if (!element) { return null }'", "+", "' for (let key in element) {'", "+", "' if (key.startsWith(\\'__reactInternalInstance$\\')) {'", "+", "' const compInternals = element[key]._currentElement;'", "+", "' const compWrapper = compInternals._owner;'", "+", "' const {props, state, context} = compWrapper._instance;'", "+", "' return {props, state, context}'", "+", "' }'", "+", "' }'", "+", "' return null;'", "+", "'}'", ")", "waitfn", ".", "apply", "(", "this", ",", "[", "self", ",", "elementPresent", ",", "done", "]", ")", "}" ]
Wait for a specified selector to exist. @param {Nightmare} self @param {String} selector @param {Function} done
[ "Wait", "for", "a", "specified", "selector", "to", "exist", "." ]
b36cf50e0016f59fdd4a53cc57f5b0e239394ce6
https://github.com/jakubchadim/nightmare-react-utils/blob/b36cf50e0016f59fdd4a53cc57f5b0e239394ce6/src/actions.js#L202-L218
47,298
VisionistInc/jibe
app.js
function(io) { // chat routes router.use('/chat', chatRoutes); // ops routes router.use('/ops', opsRoutes); // ShareJS built-in REST routes router.use('/docs', shareRoutes); if(io) { io.of('/chat').on('connection', chatHandler); } router.use('/lib', express.static(path.join(__dirname, '/node_modules'))); router.use(express.static(path.join(__dirname, '/public'))); return router; }
javascript
function(io) { // chat routes router.use('/chat', chatRoutes); // ops routes router.use('/ops', opsRoutes); // ShareJS built-in REST routes router.use('/docs', shareRoutes); if(io) { io.of('/chat').on('connection', chatHandler); } router.use('/lib', express.static(path.join(__dirname, '/node_modules'))); router.use(express.static(path.join(__dirname, '/public'))); return router; }
[ "function", "(", "io", ")", "{", "// chat routes", "router", ".", "use", "(", "'/chat'", ",", "chatRoutes", ")", ";", "// ops routes", "router", ".", "use", "(", "'/ops'", ",", "opsRoutes", ")", ";", "// ShareJS built-in REST routes", "router", ".", "use", "(", "'/docs'", ",", "shareRoutes", ")", ";", "if", "(", "io", ")", "{", "io", ".", "of", "(", "'/chat'", ")", ".", "on", "(", "'connection'", ",", "chatHandler", ")", ";", "}", "router", ".", "use", "(", "'/lib'", ",", "express", ".", "static", "(", "path", ".", "join", "(", "__dirname", ",", "'/node_modules'", ")", ")", ")", ";", "router", ".", "use", "(", "express", ".", "static", "(", "path", ".", "join", "(", "__dirname", ",", "'/public'", ")", ")", ")", ";", "return", "router", ";", "}" ]
This function creates and returns an Express 4 Router. As a side effect, creates the necessary socket channels using the given socketIO object. Example usage: var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); var jibe = require('jibe'); app.use(jibe(io).router); app.use(jibe.browserChannelMiddleware);
[ "This", "function", "creates", "and", "returns", "an", "Express", "4", "Router", "." ]
3a154c0d86a3bcf8980c5104daec099ec738a4e0
https://github.com/VisionistInc/jibe/blob/3a154c0d86a3bcf8980c5104daec099ec738a4e0/app.js#L62-L80
47,299
oscmejia/libs
lib/libs/format.js
decimal
function decimal(_num, _precision) { // If _num is undefined, assing 0 if(_num === undefined) _num = 0; // If _precision is undefined, assigned 2 if(_precision === undefined) _num = 2; n = Math.abs(_num); var sign = ''; if(_num < 0) sign = '-'; return sign + n.toFixed(_precision); }
javascript
function decimal(_num, _precision) { // If _num is undefined, assing 0 if(_num === undefined) _num = 0; // If _precision is undefined, assigned 2 if(_precision === undefined) _num = 2; n = Math.abs(_num); var sign = ''; if(_num < 0) sign = '-'; return sign + n.toFixed(_precision); }
[ "function", "decimal", "(", "_num", ",", "_precision", ")", "{", "// If _num is undefined, assing 0\t", "if", "(", "_num", "===", "undefined", ")", "_num", "=", "0", ";", "// If _precision is undefined, assigned 2", "if", "(", "_precision", "===", "undefined", ")", "_num", "=", "2", ";", "n", "=", "Math", ".", "abs", "(", "_num", ")", ";", "var", "sign", "=", "''", ";", "if", "(", "_num", "<", "0", ")", "sign", "=", "'-'", ";", "return", "sign", "+", "n", ".", "toFixed", "(", "_precision", ")", ";", "}" ]
Returns a string of a number with the given presicion. @param {Number} _num @param {int} _precision @api public
[ "Returns", "a", "string", "of", "a", "number", "with", "the", "given", "presicion", "." ]
81f8654af6ee922963e6cc3f6cda96ffa75142cf
https://github.com/oscmejia/libs/blob/81f8654af6ee922963e6cc3f6cda96ffa75142cf/lib/libs/format.js#L25-L40