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
partition
stringclasses
1 value
dcodeIO/PSON
src/PSON/ProgressivePair.js
function(dict, options) { Pair.call(this); this.encoder = new Encoder(dict, true, options); this.decoder = new Decoder(dict, true, options); }
javascript
function(dict, options) { Pair.call(this); this.encoder = new Encoder(dict, true, options); this.decoder = new Decoder(dict, true, options); }
[ "function", "(", "dict", ",", "options", ")", "{", "Pair", ".", "call", "(", "this", ")", ";", "this", ".", "encoder", "=", "new", "Encoder", "(", "dict", ",", "true", ",", "options", ")", ";", "this", ".", "decoder", "=", "new", "Decoder", "(", "dict", ",", "true", ",", "options", ")", ";", "}" ]
Constructs a new progressive PSON encoder and decoder pair. @exports PSON.ProgressivePair @class A progressive PSON encoder and decoder pair. @param {Array.<string>=} dict Initial dictionary @param {Object.<string,*>=} options Options @constructor @extends PSON.Pair
[ "Constructs", "a", "new", "progressive", "PSON", "encoder", "and", "decoder", "pair", "." ]
be3bb7c10260c4bf7d57aec57e98937d950e938d
https://github.com/dcodeIO/PSON/blob/be3bb7c10260c4bf7d57aec57e98937d950e938d/src/PSON/ProgressivePair.js#L15-L20
train
dcodeIO/PSON
dist/PSON.js
function(dict, progressive, options) { /** * Dictionary hash. * @type {Object.<string,number>} */ this.dict = {}; /** * Next dictionary index. * @type {number} */ this.next = 0; if (dict && Array.isArray(dict)) { while (this.next < dict.length) { this.dict[dict[this.next]] = this.next++; } } /** * Whether the encoder is progressive or static. * @type {boolean} */ this.progressive = !!progressive; /** * Options. * @type {Object.<string,*>} */ this.options = options || {}; }
javascript
function(dict, progressive, options) { /** * Dictionary hash. * @type {Object.<string,number>} */ this.dict = {}; /** * Next dictionary index. * @type {number} */ this.next = 0; if (dict && Array.isArray(dict)) { while (this.next < dict.length) { this.dict[dict[this.next]] = this.next++; } } /** * Whether the encoder is progressive or static. * @type {boolean} */ this.progressive = !!progressive; /** * Options. * @type {Object.<string,*>} */ this.options = options || {}; }
[ "function", "(", "dict", ",", "progressive", ",", "options", ")", "{", "this", ".", "dict", "=", "{", "}", ";", "this", ".", "next", "=", "0", ";", "if", "(", "dict", "&&", "Array", ".", "isArray", "(", "dict", ")", ")", "{", "while", "(", "this", ".", "next", "<", "dict", ".", "length", ")", "{", "this", ".", "dict", "[", "dict", "[", "this", ".", "next", "]", "]", "=", "this", ".", "next", "++", ";", "}", "}", "this", ".", "progressive", "=", "!", "!", "progressive", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "}" ]
Constructs a new PSON Encoder. @exports PSON.Encoder @class A PSON Encoder. @param {Array.<string>=} dict Initial dictionary @param {boolean} progressive Whether this is a progressive or a static encoder @param {Object.<string,*>=} options Options @constructor
[ "Constructs", "a", "new", "PSON", "Encoder", "." ]
be3bb7c10260c4bf7d57aec57e98937d950e938d
https://github.com/dcodeIO/PSON/blob/be3bb7c10260c4bf7d57aec57e98937d950e938d/dist/PSON.js#L103-L133
train
dcodeIO/PSON
dist/PSON.js
function(dict, progressive, options) { /** * Dictionary array. * @type {Array.<string>} */ this.dict = (dict && Array.isArray(dict)) ? dict : []; /** * Whether this is a progressive or a static decoder. * @type {boolean} */ this.progressive = !!progressive; /** * Options. * @type {Object.<string,*>} */ this.options = options || {}; }
javascript
function(dict, progressive, options) { /** * Dictionary array. * @type {Array.<string>} */ this.dict = (dict && Array.isArray(dict)) ? dict : []; /** * Whether this is a progressive or a static decoder. * @type {boolean} */ this.progressive = !!progressive; /** * Options. * @type {Object.<string,*>} */ this.options = options || {}; }
[ "function", "(", "dict", ",", "progressive", ",", "options", ")", "{", "this", ".", "dict", "=", "(", "dict", "&&", "Array", ".", "isArray", "(", "dict", ")", ")", "?", "dict", ":", "[", "]", ";", "this", ".", "progressive", "=", "!", "!", "progressive", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "}" ]
Constructs a new PSON Decoder. @exports PSON.Decoder @class A PSON Decoder. @param {Array.<string>} dict Initial dictionary values @param {boolean} progressive Whether this is a progressive or a static decoder @param {Object.<string,*>=} options Options @constructor
[ "Constructs", "a", "new", "PSON", "Decoder", "." ]
be3bb7c10260c4bf7d57aec57e98937d950e938d
https://github.com/dcodeIO/PSON/blob/be3bb7c10260c4bf7d57aec57e98937d950e938d/dist/PSON.js#L298-L317
train
kalabox/kalabox
docs/js/extra.js
determineSelectedBranch
function determineSelectedBranch() { var branch = 'stable', path = window.location.pathname; // path is like /en/<branch>/<lang>/build/ -> extract 'lang' // split[0] is an '' because the path starts with the separator branch = path.split('/')[2]; return branch; }
javascript
function determineSelectedBranch() { var branch = 'stable', path = window.location.pathname; // path is like /en/<branch>/<lang>/build/ -> extract 'lang' // split[0] is an '' because the path starts with the separator branch = path.split('/')[2]; return branch; }
[ "function", "determineSelectedBranch", "(", ")", "{", "var", "branch", "=", "'stable'", ",", "path", "=", "window", ".", "location", ".", "pathname", ";", "branch", "=", "path", ".", "split", "(", "'/'", ")", "[", "2", "]", ";", "return", "branch", ";", "}" ]
Analyzes the URL of the current page to find out what the selected GitHub branch is. It's usually part of the location path. The code needs to distinguish between running MkDocs standalone and docs served from RTD. If no valid branch could be determined 'dev' returned. @returns GitHub branch name
[ "Analyzes", "the", "URL", "of", "the", "current", "page", "to", "find", "out", "what", "the", "selected", "GitHub", "branch", "is", ".", "It", "s", "usually", "part", "of", "the", "location", "path", ".", "The", "code", "needs", "to", "distinguish", "between", "running", "MkDocs", "standalone", "and", "docs", "served", "from", "RTD", ".", "If", "no", "valid", "branch", "could", "be", "determined", "dev", "returned", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/docs/js/extra.js#L32-L38
train
kalabox/kalabox
lib/app/registry.js
appsAreEqual
function appsAreEqual(x, y) { function pp(o) { return JSON.stringify(o); } var xs = pp(x); var ys = pp(y); return xs === ys; }
javascript
function appsAreEqual(x, y) { function pp(o) { return JSON.stringify(o); } var xs = pp(x); var ys = pp(y); return xs === ys; }
[ "function", "appsAreEqual", "(", "x", ",", "y", ")", "{", "function", "pp", "(", "o", ")", "{", "return", "JSON", ".", "stringify", "(", "o", ")", ";", "}", "var", "xs", "=", "pp", "(", "x", ")", ";", "var", "ys", "=", "pp", "(", "y", ")", ";", "return", "xs", "===", "ys", ";", "}" ]
Returns true if two apps are equal.
[ "Returns", "true", "if", "two", "apps", "are", "equal", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L31-L38
train
kalabox/kalabox
lib/app/registry.js
existsInCache
function existsInCache(x, cache) { var found = _.find(cache, function(y) { return appsAreEqual(x, y); }); return !!found; }
javascript
function existsInCache(x, cache) { var found = _.find(cache, function(y) { return appsAreEqual(x, y); }); return !!found; }
[ "function", "existsInCache", "(", "x", ",", "cache", ")", "{", "var", "found", "=", "_", ".", "find", "(", "cache", ",", "function", "(", "y", ")", "{", "return", "appsAreEqual", "(", "x", ",", "y", ")", ";", "}", ")", ";", "return", "!", "!", "found", ";", "}" ]
Returns true if app already exists in cache.
[ "Returns", "true", "if", "app", "already", "exists", "in", "cache", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L41-L46
train
kalabox/kalabox
lib/app/registry.js
function(app) { if (!appCache.good) { appCache.good = []; } if (!existsInCache(app, appCache.good)) { appCache.good.push(app); } }
javascript
function(app) { if (!appCache.good) { appCache.good = []; } if (!existsInCache(app, appCache.good)) { appCache.good.push(app); } }
[ "function", "(", "app", ")", "{", "if", "(", "!", "appCache", ".", "good", ")", "{", "appCache", ".", "good", "=", "[", "]", ";", "}", "if", "(", "!", "existsInCache", "(", "app", ",", "appCache", ".", "good", ")", ")", "{", "appCache", ".", "good", ".", "push", "(", "app", ")", ";", "}", "}" ]
Cache an appDir by appName in data store.
[ "Cache", "an", "appDir", "by", "appName", "in", "data", "store", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L49-L56
train
kalabox/kalabox
lib/app/registry.js
function(app) { if (!appCache.bad) { appCache.bad = []; } if (!existsInCache(app, appCache.bad)) { appCache.bad.push(app); } }
javascript
function(app) { if (!appCache.bad) { appCache.bad = []; } if (!existsInCache(app, appCache.bad)) { appCache.bad.push(app); } }
[ "function", "(", "app", ")", "{", "if", "(", "!", "appCache", ".", "bad", ")", "{", "appCache", ".", "bad", "=", "[", "]", ";", "}", "if", "(", "!", "existsInCache", "(", "app", ",", "appCache", ".", "bad", ")", ")", "{", "appCache", ".", "bad", ".", "push", "(", "app", ")", ";", "}", "}" ]
Cache an appDir by appName in bad app data store.
[ "Cache", "an", "appDir", "by", "appName", "in", "bad", "app", "data", "store", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L59-L66
train
kalabox/kalabox
lib/app/registry.js
function() { var globalConfig = getGlobalConfig(); // Read contents of app registry file. return Promise.fromNode(function(cb) { fs.readFile(globalConfig.appRegistry, {encoding: 'utf8'}, cb); }) // Parse contents and return app dirs. .then(function(data) { var json = JSON.parse(data); if (json) { return json; } else { return []; } }) // Handle no entry error. .catch(function(err) { if (err.code === 'ENOENT') { return []; } else { throw err; } }); }
javascript
function() { var globalConfig = getGlobalConfig(); // Read contents of app registry file. return Promise.fromNode(function(cb) { fs.readFile(globalConfig.appRegistry, {encoding: 'utf8'}, cb); }) // Parse contents and return app dirs. .then(function(data) { var json = JSON.parse(data); if (json) { return json; } else { return []; } }) // Handle no entry error. .catch(function(err) { if (err.code === 'ENOENT') { return []; } else { throw err; } }); }
[ "function", "(", ")", "{", "var", "globalConfig", "=", "getGlobalConfig", "(", ")", ";", "return", "Promise", ".", "fromNode", "(", "function", "(", "cb", ")", "{", "fs", ".", "readFile", "(", "globalConfig", ".", "appRegistry", ",", "{", "encoding", ":", "'utf8'", "}", ",", "cb", ")", ";", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "var", "json", "=", "JSON", ".", "parse", "(", "data", ")", ";", "if", "(", "json", ")", "{", "return", "json", ";", "}", "else", "{", "return", "[", "]", ";", "}", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "'ENOENT'", ")", "{", "return", "[", "]", ";", "}", "else", "{", "throw", "err", ";", "}", "}", ")", ";", "}" ]
Read from app registry file.
[ "Read", "from", "app", "registry", "file", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L79-L104
train
kalabox/kalabox
lib/app/registry.js
function(apps) { var filepath = getGlobalConfig().appRegistry; var tempFilepath = filepath + '.tmp'; // Write to temp file. return Promise.fromNode(function(cb) { fs.writeFile(tempFilepath, JSON.stringify(apps), cb); log.debug(format('Setting app registry with %j', apps)); }) // Rename temp file to normal file. .then(function() { return Promise.fromNode(function(cb) { fs.rename(tempFilepath, filepath, cb); }); }); }
javascript
function(apps) { var filepath = getGlobalConfig().appRegistry; var tempFilepath = filepath + '.tmp'; // Write to temp file. return Promise.fromNode(function(cb) { fs.writeFile(tempFilepath, JSON.stringify(apps), cb); log.debug(format('Setting app registry with %j', apps)); }) // Rename temp file to normal file. .then(function() { return Promise.fromNode(function(cb) { fs.rename(tempFilepath, filepath, cb); }); }); }
[ "function", "(", "apps", ")", "{", "var", "filepath", "=", "getGlobalConfig", "(", ")", ".", "appRegistry", ";", "var", "tempFilepath", "=", "filepath", "+", "'.tmp'", ";", "return", "Promise", ".", "fromNode", "(", "function", "(", "cb", ")", "{", "fs", ".", "writeFile", "(", "tempFilepath", ",", "JSON", ".", "stringify", "(", "apps", ")", ",", "cb", ")", ";", "log", ".", "debug", "(", "format", "(", "'Setting app registry with %j'", ",", "apps", ")", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "Promise", ".", "fromNode", "(", "function", "(", "cb", ")", "{", "fs", ".", "rename", "(", "tempFilepath", ",", "filepath", ",", "cb", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Rewrite the app registry file.
[ "Rewrite", "the", "app", "registry", "file", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L107-L125
train
kalabox/kalabox
lib/app/registry.js
function(app) { var filepath = path.join(app.dir, APP_CONFIG_FILENAME); // Read contents of file. return Promise.fromNode(function(cb) { fs.readFile(filepath, {encoding: 'utf8'}, cb); }) // Handle no entry error. .catch(function(err) { if (err.code === 'ENOENT') { cacheBadApp(app); } else { throw new VError(err, 'Failed to load config: %s', filepath); } }) // Return appName. .then(function(data) { var json = util.yaml.dataToJson(data); if (!json) { return null; } else if (!json.name) { log.debug(format('Does NOT contain %s property!', filepath)); return null; } else if (json.name === app.name) { cacheApp(app); return app; } else if (json.name !== app.name) { cacheBadApp(app); return null; } else { return null; } }); }
javascript
function(app) { var filepath = path.join(app.dir, APP_CONFIG_FILENAME); // Read contents of file. return Promise.fromNode(function(cb) { fs.readFile(filepath, {encoding: 'utf8'}, cb); }) // Handle no entry error. .catch(function(err) { if (err.code === 'ENOENT') { cacheBadApp(app); } else { throw new VError(err, 'Failed to load config: %s', filepath); } }) // Return appName. .then(function(data) { var json = util.yaml.dataToJson(data); if (!json) { return null; } else if (!json.name) { log.debug(format('Does NOT contain %s property!', filepath)); return null; } else if (json.name === app.name) { cacheApp(app); return app; } else if (json.name !== app.name) { cacheBadApp(app); return null; } else { return null; } }); }
[ "function", "(", "app", ")", "{", "var", "filepath", "=", "path", ".", "join", "(", "app", ".", "dir", ",", "APP_CONFIG_FILENAME", ")", ";", "return", "Promise", ".", "fromNode", "(", "function", "(", "cb", ")", "{", "fs", ".", "readFile", "(", "filepath", ",", "{", "encoding", ":", "'utf8'", "}", ",", "cb", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "'ENOENT'", ")", "{", "cacheBadApp", "(", "app", ")", ";", "}", "else", "{", "throw", "new", "VError", "(", "err", ",", "'Failed to load config: %s'", ",", "filepath", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "var", "json", "=", "util", ".", "yaml", ".", "dataToJson", "(", "data", ")", ";", "if", "(", "!", "json", ")", "{", "return", "null", ";", "}", "else", "if", "(", "!", "json", ".", "name", ")", "{", "log", ".", "debug", "(", "format", "(", "'Does NOT contain %s property!'", ",", "filepath", ")", ")", ";", "return", "null", ";", "}", "else", "if", "(", "json", ".", "name", "===", "app", ".", "name", ")", "{", "cacheApp", "(", "app", ")", ";", "return", "app", ";", "}", "else", "if", "(", "json", ".", "name", "!==", "app", ".", "name", ")", "{", "cacheBadApp", "(", "app", ")", ";", "return", "null", ";", "}", "else", "{", "return", "null", ";", "}", "}", ")", ";", "}" ]
Given an app, inspect it and return the appName.
[ "Given", "an", "app", "inspect", "it", "and", "return", "the", "appName", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L128-L167
train
kalabox/kalabox
lib/app/registry.js
function() { // Get list of dirs from app registry. return getAppRegistry() // Map app dirs to app names. .then(inspectDirs) .all() .tap(function(appRegistryApps) { log.debug(format('Apps in registry: %j', appRegistryApps)); }); }
javascript
function() { // Get list of dirs from app registry. return getAppRegistry() // Map app dirs to app names. .then(inspectDirs) .all() .tap(function(appRegistryApps) { log.debug(format('Apps in registry: %j', appRegistryApps)); }); }
[ "function", "(", ")", "{", "return", "getAppRegistry", "(", ")", ".", "then", "(", "inspectDirs", ")", ".", "all", "(", ")", ".", "tap", "(", "function", "(", "appRegistryApps", ")", "{", "log", ".", "debug", "(", "format", "(", "'Apps in registry: %j'", ",", "appRegistryApps", ")", ")", ";", "}", ")", ";", "}" ]
Return list of app names from app registry dirs.
[ "Return", "list", "of", "app", "names", "from", "app", "registry", "dirs", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L177-L187
train
kalabox/kalabox
lib/app/registry.js
function(cache) { // Init a promise. return Promise.resolve() .then(function() { if (!_.isEmpty(appCache)) { // Return cached value. return appCache[cache] || []; } else { // Reload and cache app dirs, then get app dir from cache again. return list() .then(function() { return appCache[cache] || []; }); } }); }
javascript
function(cache) { // Init a promise. return Promise.resolve() .then(function() { if (!_.isEmpty(appCache)) { // Return cached value. return appCache[cache] || []; } else { // Reload and cache app dirs, then get app dir from cache again. return list() .then(function() { return appCache[cache] || []; }); } }); }
[ "function", "(", "cache", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "_", ".", "isEmpty", "(", "appCache", ")", ")", "{", "return", "appCache", "[", "cache", "]", "||", "[", "]", ";", "}", "else", "{", "return", "list", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "appCache", "[", "cache", "]", "||", "[", "]", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Get app helped
[ "Get", "app", "helped" ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L190-L207
train
kalabox/kalabox
src/modules/guiEngine/sites.js
function() { // Get app. return kbox.app.get(self.name) // Ignore errors. .catch(function() {}) .then(function(app) { if (app) { // Return app. return app; } else { // Take a short delay then try again. return $q.delay(5 * 1000) .then(function() { return getApp(); }); } }); }
javascript
function() { // Get app. return kbox.app.get(self.name) // Ignore errors. .catch(function() {}) .then(function(app) { if (app) { // Return app. return app; } else { // Take a short delay then try again. return $q.delay(5 * 1000) .then(function() { return getApp(); }); } }); }
[ "function", "(", ")", "{", "return", "kbox", ".", "app", ".", "get", "(", "self", ".", "name", ")", ".", "catch", "(", "function", "(", ")", "{", "}", ")", ".", "then", "(", "function", "(", "app", ")", "{", "if", "(", "app", ")", "{", "return", "app", ";", "}", "else", "{", "return", "$q", ".", "delay", "(", "5", "*", "1000", ")", ".", "then", "(", "function", "(", ")", "{", "return", "getApp", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Recursive method to get app object.
[ "Recursive", "method", "to", "get", "app", "object", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/src/modules/guiEngine/sites.js#L40-L57
train
kalabox/kalabox
src/modules/dashboard/dashboard.js
reloadSites
function reloadSites() { function reload() { sites.get() .then(function(sites) { $scope.ui.sites = sites; }); } /* * Reload sites mutliple times, because sometimes updates to list of sites * aren't ready immediately. */ // Reload sites immediately. reload(); // Reload sites again after 5 seconds. setTimeout(reload, 1000 * 5); // Reload sites again after 15 seconds. setTimeout(reload, 1000 * 15); }
javascript
function reloadSites() { function reload() { sites.get() .then(function(sites) { $scope.ui.sites = sites; }); } /* * Reload sites mutliple times, because sometimes updates to list of sites * aren't ready immediately. */ // Reload sites immediately. reload(); // Reload sites again after 5 seconds. setTimeout(reload, 1000 * 5); // Reload sites again after 15 seconds. setTimeout(reload, 1000 * 15); }
[ "function", "reloadSites", "(", ")", "{", "function", "reload", "(", ")", "{", "sites", ".", "get", "(", ")", ".", "then", "(", "function", "(", "sites", ")", "{", "$scope", ".", "ui", ".", "sites", "=", "sites", ";", "}", ")", ";", "}", "reload", "(", ")", ";", "setTimeout", "(", "reload", ",", "1000", "*", "5", ")", ";", "setTimeout", "(", "reload", ",", "1000", "*", "15", ")", ";", "}" ]
Helper function for reloading list of sites.
[ "Helper", "function", "for", "reloading", "list", "of", "sites", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/src/modules/dashboard/dashboard.js#L160-L177
train
kalabox/kalabox
lib/create.js
function(task, type) { // Make sure we are going to add a task with a real app if (!get(type)) { // todo: something useful besides silentfail // todo: never forget how funny this was/is/will always be throw new Error('F!'); } // Get the app plugin metadata var app = get(type); // Create the basic task data task.path = ['create', type]; task.category = 'global'; task.description = app.task.description; task.options = parseOptions(app.options, 'task'); // Extract our inquiry var inquiry = _.identity(parseOptions(app.options, 'inquire')); // Add a generic app options to build elsewhere task.options.push({ name: 'dir', kind: 'string', description: 'Creates the app in this directory. Defaults to CWD.', }); // Specify an alternate location to grab the app skeleton task.options.push({ name: 'from', kind: 'string', description: 'Local path to override app skeleton (be careful with this)', }); // The func that this app create task runs task.func = function(done) { // Grab the CLI options that are available var options = this.options; // Filter out interactive questions based on passed in options var questions = kbox.util.cli.filterQuestions(inquiry, options); // Launch the inquiry inquirer.prompt(questions, function(answers) { // Add the create type to the results object // NOTE: the create type can be different than the // type found in the config aka config.type = php but // answers._type = drupal7 answers._type = type; // Create the app return createApp(app, _.merge({}, options, answers)) // Return. .nodeify(done); }); }; }
javascript
function(task, type) { // Make sure we are going to add a task with a real app if (!get(type)) { // todo: something useful besides silentfail // todo: never forget how funny this was/is/will always be throw new Error('F!'); } // Get the app plugin metadata var app = get(type); // Create the basic task data task.path = ['create', type]; task.category = 'global'; task.description = app.task.description; task.options = parseOptions(app.options, 'task'); // Extract our inquiry var inquiry = _.identity(parseOptions(app.options, 'inquire')); // Add a generic app options to build elsewhere task.options.push({ name: 'dir', kind: 'string', description: 'Creates the app in this directory. Defaults to CWD.', }); // Specify an alternate location to grab the app skeleton task.options.push({ name: 'from', kind: 'string', description: 'Local path to override app skeleton (be careful with this)', }); // The func that this app create task runs task.func = function(done) { // Grab the CLI options that are available var options = this.options; // Filter out interactive questions based on passed in options var questions = kbox.util.cli.filterQuestions(inquiry, options); // Launch the inquiry inquirer.prompt(questions, function(answers) { // Add the create type to the results object // NOTE: the create type can be different than the // type found in the config aka config.type = php but // answers._type = drupal7 answers._type = type; // Create the app return createApp(app, _.merge({}, options, answers)) // Return. .nodeify(done); }); }; }
[ "function", "(", "task", ",", "type", ")", "{", "if", "(", "!", "get", "(", "type", ")", ")", "{", "throw", "new", "Error", "(", "'F!'", ")", ";", "}", "var", "app", "=", "get", "(", "type", ")", ";", "task", ".", "path", "=", "[", "'create'", ",", "type", "]", ";", "task", ".", "category", "=", "'global'", ";", "task", ".", "description", "=", "app", ".", "task", ".", "description", ";", "task", ".", "options", "=", "parseOptions", "(", "app", ".", "options", ",", "'task'", ")", ";", "var", "inquiry", "=", "_", ".", "identity", "(", "parseOptions", "(", "app", ".", "options", ",", "'inquire'", ")", ")", ";", "task", ".", "options", ".", "push", "(", "{", "name", ":", "'dir'", ",", "kind", ":", "'string'", ",", "description", ":", "'Creates the app in this directory. Defaults to CWD.'", ",", "}", ")", ";", "task", ".", "options", ".", "push", "(", "{", "name", ":", "'from'", ",", "kind", ":", "'string'", ",", "description", ":", "'Local path to override app skeleton (be careful with this)'", ",", "}", ")", ";", "task", ".", "func", "=", "function", "(", "done", ")", "{", "var", "options", "=", "this", ".", "options", ";", "var", "questions", "=", "kbox", ".", "util", ".", "cli", ".", "filterQuestions", "(", "inquiry", ",", "options", ")", ";", "inquirer", ".", "prompt", "(", "questions", ",", "function", "(", "answers", ")", "{", "answers", ".", "_type", "=", "type", ";", "return", "createApp", "(", "app", ",", "_", ".", "merge", "(", "{", "}", ",", "options", ",", "answers", ")", ")", ".", "nodeify", "(", "done", ")", ";", "}", ")", ";", "}", ";", "}" ]
Assembles create.add metadata and builds a task to create a certain kind of app. @memberof create @static @method @arg {Object} task - A kbox task object. @arg {string} appName - The name of the kind of app to be created. @example // Task to create kalabox apps kbox.tasks.add(function(task) { kbox.create.buildTask(task, 'frontpage98'); });
[ "Assembles", "create", ".", "add", "metadata", "and", "builds", "a", "task", "to", "create", "a", "certain", "kind", "of", "app", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/create.js#L415-L476
train
kalabox/kalabox
lib/core/tasks.js
function(node, path) { // Validate. if (!isBranch(node)) { assert(false); } if (path.length === 0) { assert(false); } // Partition head and tail. var hd = path[0]; var tl = path.slice(1); // Find a child of node that matches path. var cursor = _.find(node.children, function(obj) { return getName(obj) === hd; }); // Conflicting tasks exist in task tree. if (cursor && isTask(cursor)) { throw new Error('Task already exists: ' + task.path.join(' -> ')); } // Continue. if (tl.length === 0) { // We are at the end of the path. task.path = [hd]; if (cursor) { addChild(cursor, task); } else { addChild(node, task); } return; } else { // We are NOT at the end of the path. if (!cursor) { cursor = createBranch(hd); addChild(node, cursor); } return rec(cursor, tl); } }
javascript
function(node, path) { // Validate. if (!isBranch(node)) { assert(false); } if (path.length === 0) { assert(false); } // Partition head and tail. var hd = path[0]; var tl = path.slice(1); // Find a child of node that matches path. var cursor = _.find(node.children, function(obj) { return getName(obj) === hd; }); // Conflicting tasks exist in task tree. if (cursor && isTask(cursor)) { throw new Error('Task already exists: ' + task.path.join(' -> ')); } // Continue. if (tl.length === 0) { // We are at the end of the path. task.path = [hd]; if (cursor) { addChild(cursor, task); } else { addChild(node, task); } return; } else { // We are NOT at the end of the path. if (!cursor) { cursor = createBranch(hd); addChild(node, cursor); } return rec(cursor, tl); } }
[ "function", "(", "node", ",", "path", ")", "{", "if", "(", "!", "isBranch", "(", "node", ")", ")", "{", "assert", "(", "false", ")", ";", "}", "if", "(", "path", ".", "length", "===", "0", ")", "{", "assert", "(", "false", ")", ";", "}", "var", "hd", "=", "path", "[", "0", "]", ";", "var", "tl", "=", "path", ".", "slice", "(", "1", ")", ";", "var", "cursor", "=", "_", ".", "find", "(", "node", ".", "children", ",", "function", "(", "obj", ")", "{", "return", "getName", "(", "obj", ")", "===", "hd", ";", "}", ")", ";", "if", "(", "cursor", "&&", "isTask", "(", "cursor", ")", ")", "{", "throw", "new", "Error", "(", "'Task already exists: '", "+", "task", ".", "path", ".", "join", "(", "' -> '", ")", ")", ";", "}", "if", "(", "tl", ".", "length", "===", "0", ")", "{", "task", ".", "path", "=", "[", "hd", "]", ";", "if", "(", "cursor", ")", "{", "addChild", "(", "cursor", ",", "task", ")", ";", "}", "else", "{", "addChild", "(", "node", ",", "task", ")", ";", "}", "return", ";", "}", "else", "{", "if", "(", "!", "cursor", ")", "{", "cursor", "=", "createBranch", "(", "hd", ")", ";", "addChild", "(", "node", ",", "cursor", ")", ";", "}", "return", "rec", "(", "cursor", ",", "tl", ")", ";", "}", "}" ]
Recursive function for placing task in task tree.
[ "Recursive", "function", "for", "placing", "task", "in", "task", "tree", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/core/tasks.js#L221-L279
train
kalabox/kalabox
lib/core/tasks.js
function(node, payload) { if (payload.length === 0) { // Reached end of argv path, so return current node. node.argv = { payload: payload, options: argv.options, rawOptions: argv.rawOptions }; return node; } else if (isTask(node)) { // A task has been found along the argv path, so return it. node.argv = { payload: payload, options: argv.options, rawOptions: argv.rawOptions }; return node; } else if (isBranch(node)) { // Get the head of the argv path. var hd = payload[0]; var tl = payload.slice(1); // Find a child of node branch that matches hd. var child = findChild(node, hd); if (child) { // Update the argv path and then recurse with child that was found. return rec(child, tl); } else { // No matching child was found, it's a dead search so return null. return null; } } else { // This should never happen. assert(false); } }
javascript
function(node, payload) { if (payload.length === 0) { // Reached end of argv path, so return current node. node.argv = { payload: payload, options: argv.options, rawOptions: argv.rawOptions }; return node; } else if (isTask(node)) { // A task has been found along the argv path, so return it. node.argv = { payload: payload, options: argv.options, rawOptions: argv.rawOptions }; return node; } else if (isBranch(node)) { // Get the head of the argv path. var hd = payload[0]; var tl = payload.slice(1); // Find a child of node branch that matches hd. var child = findChild(node, hd); if (child) { // Update the argv path and then recurse with child that was found. return rec(child, tl); } else { // No matching child was found, it's a dead search so return null. return null; } } else { // This should never happen. assert(false); } }
[ "function", "(", "node", ",", "payload", ")", "{", "if", "(", "payload", ".", "length", "===", "0", ")", "{", "node", ".", "argv", "=", "{", "payload", ":", "payload", ",", "options", ":", "argv", ".", "options", ",", "rawOptions", ":", "argv", ".", "rawOptions", "}", ";", "return", "node", ";", "}", "else", "if", "(", "isTask", "(", "node", ")", ")", "{", "node", ".", "argv", "=", "{", "payload", ":", "payload", ",", "options", ":", "argv", ".", "options", ",", "rawOptions", ":", "argv", ".", "rawOptions", "}", ";", "return", "node", ";", "}", "else", "if", "(", "isBranch", "(", "node", ")", ")", "{", "var", "hd", "=", "payload", "[", "0", "]", ";", "var", "tl", "=", "payload", ".", "slice", "(", "1", ")", ";", "var", "child", "=", "findChild", "(", "node", ",", "hd", ")", ";", "if", "(", "child", ")", "{", "return", "rec", "(", "child", ",", "tl", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}", "else", "{", "assert", "(", "false", ")", ";", "}", "}" ]
Recursive function for searching the task tree.
[ "Recursive", "function", "for", "searching", "the", "task", "tree", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/core/tasks.js#L659-L709
train
kalabox/kalabox
lib/core/tasks.js
function(node) { if (isTask(node)) { // This is a task so do nothing. return [node]; } else if (isBranch(node)) { // Concat map children with a recMap. node.children = _.flatten(_.map(node.children, recMap)); // Sort children. node.children.sort(compareBranchOrTask); // Resolve duplicate named children. // Group children by name. var nameMap = _.groupBy(node.children, getName); // Resolve conflicts. node.children = _.map(_.values(nameMap), function(children) { if (children.length === 1) { // No conflicts so just return head of array. return children[0]; } else { // Resolve conflict by finding a single node with the override flag. var overrides = _.filter(children, function(child) { return child.__override; }); if (overrides.length === 1) { // Conflict resolved. return overrides[0]; } else { // Conflict can not be resolved, throw an error. throw new Error('Conflicting task names can not be resolved: ' + pp(children)); } } }); if (getName(node) === appName) { // Replace this node with this nodes children. _.each(node.children, function(child) { // Mark each child with an override flag so we can resolve conflicts. child.__override = true; }); return node.children; } else { // Just return. return [node]; } } else { // This should never happen. assert(false); } }
javascript
function(node) { if (isTask(node)) { // This is a task so do nothing. return [node]; } else if (isBranch(node)) { // Concat map children with a recMap. node.children = _.flatten(_.map(node.children, recMap)); // Sort children. node.children.sort(compareBranchOrTask); // Resolve duplicate named children. // Group children by name. var nameMap = _.groupBy(node.children, getName); // Resolve conflicts. node.children = _.map(_.values(nameMap), function(children) { if (children.length === 1) { // No conflicts so just return head of array. return children[0]; } else { // Resolve conflict by finding a single node with the override flag. var overrides = _.filter(children, function(child) { return child.__override; }); if (overrides.length === 1) { // Conflict resolved. return overrides[0]; } else { // Conflict can not be resolved, throw an error. throw new Error('Conflicting task names can not be resolved: ' + pp(children)); } } }); if (getName(node) === appName) { // Replace this node with this nodes children. _.each(node.children, function(child) { // Mark each child with an override flag so we can resolve conflicts. child.__override = true; }); return node.children; } else { // Just return. return [node]; } } else { // This should never happen. assert(false); } }
[ "function", "(", "node", ")", "{", "if", "(", "isTask", "(", "node", ")", ")", "{", "return", "[", "node", "]", ";", "}", "else", "if", "(", "isBranch", "(", "node", ")", ")", "{", "node", ".", "children", "=", "_", ".", "flatten", "(", "_", ".", "map", "(", "node", ".", "children", ",", "recMap", ")", ")", ";", "node", ".", "children", ".", "sort", "(", "compareBranchOrTask", ")", ";", "var", "nameMap", "=", "_", ".", "groupBy", "(", "node", ".", "children", ",", "getName", ")", ";", "node", ".", "children", "=", "_", ".", "map", "(", "_", ".", "values", "(", "nameMap", ")", ",", "function", "(", "children", ")", "{", "if", "(", "children", ".", "length", "===", "1", ")", "{", "return", "children", "[", "0", "]", ";", "}", "else", "{", "var", "overrides", "=", "_", ".", "filter", "(", "children", ",", "function", "(", "child", ")", "{", "return", "child", ".", "__override", ";", "}", ")", ";", "if", "(", "overrides", ".", "length", "===", "1", ")", "{", "return", "overrides", "[", "0", "]", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Conflicting task names can not be resolved: '", "+", "pp", "(", "children", ")", ")", ";", "}", "}", "}", ")", ";", "if", "(", "getName", "(", "node", ")", "===", "appName", ")", "{", "_", ".", "each", "(", "node", ".", "children", ",", "function", "(", "child", ")", "{", "child", ".", "__override", "=", "true", ";", "}", ")", ";", "return", "node", ".", "children", ";", "}", "else", "{", "return", "[", "node", "]", ";", "}", "}", "else", "{", "assert", "(", "false", ")", ";", "}", "}" ]
Recursively map branch to get the cli look we want.
[ "Recursively", "map", "branch", "to", "get", "the", "cli", "look", "we", "want", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/core/tasks.js#L911-L985
train
kalabox/kalabox
lib/core/tasks.js
function(node, lines, parentName, depth) { // Default depth. if (_.isUndefined(depth)) { depth = 0; } // Default parentName. if (_.isUndefined(parentName)) { parentName = 'root'; } if (isTask(node)) { // This is a task so add to lines and nothing further. lines.push({ depth: depth, name: getName(node), parentName: parentName, description: node.description }); } else if (isBranch(node)) { lines.push({ depth: depth, name: getName(node), parentName: parentName }); node.children.forEach(function(child) { recAdd(child, lines, getName(node), depth + 1); }); } else { // This should never happen. assert(false); } }
javascript
function(node, lines, parentName, depth) { // Default depth. if (_.isUndefined(depth)) { depth = 0; } // Default parentName. if (_.isUndefined(parentName)) { parentName = 'root'; } if (isTask(node)) { // This is a task so add to lines and nothing further. lines.push({ depth: depth, name: getName(node), parentName: parentName, description: node.description }); } else if (isBranch(node)) { lines.push({ depth: depth, name: getName(node), parentName: parentName }); node.children.forEach(function(child) { recAdd(child, lines, getName(node), depth + 1); }); } else { // This should never happen. assert(false); } }
[ "function", "(", "node", ",", "lines", ",", "parentName", ",", "depth", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "depth", ")", ")", "{", "depth", "=", "0", ";", "}", "if", "(", "_", ".", "isUndefined", "(", "parentName", ")", ")", "{", "parentName", "=", "'root'", ";", "}", "if", "(", "isTask", "(", "node", ")", ")", "{", "lines", ".", "push", "(", "{", "depth", ":", "depth", ",", "name", ":", "getName", "(", "node", ")", ",", "parentName", ":", "parentName", ",", "description", ":", "node", ".", "description", "}", ")", ";", "}", "else", "if", "(", "isBranch", "(", "node", ")", ")", "{", "lines", ".", "push", "(", "{", "depth", ":", "depth", ",", "name", ":", "getName", "(", "node", ")", ",", "parentName", ":", "parentName", "}", ")", ";", "node", ".", "children", ".", "forEach", "(", "function", "(", "child", ")", "{", "recAdd", "(", "child", ",", "lines", ",", "getName", "(", "node", ")", ",", "depth", "+", "1", ")", ";", "}", ")", ";", "}", "else", "{", "assert", "(", "false", ")", ";", "}", "}" ]
Recursively build list of lines.
[ "Recursively", "build", "list", "of", "lines", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/core/tasks.js#L988-L1028
train
kalabox/kalabox
lib/util/shell.js
getEnvironment
function getEnvironment(opts) { if (opts.app) { // Merge app env over the process env and return. var processEnv = _.cloneDeep(process.env); var appEnv = opts.app.env.getEnv(); return _.merge(processEnv, appEnv); } else { // Just use process env. return process.env; } }
javascript
function getEnvironment(opts) { if (opts.app) { // Merge app env over the process env and return. var processEnv = _.cloneDeep(process.env); var appEnv = opts.app.env.getEnv(); return _.merge(processEnv, appEnv); } else { // Just use process env. return process.env; } }
[ "function", "getEnvironment", "(", "opts", ")", "{", "if", "(", "opts", ".", "app", ")", "{", "var", "processEnv", "=", "_", ".", "cloneDeep", "(", "process", ".", "env", ")", ";", "var", "appEnv", "=", "opts", ".", "app", ".", "env", ".", "getEnv", "(", ")", ";", "return", "_", ".", "merge", "(", "processEnv", ",", "appEnv", ")", ";", "}", "else", "{", "return", "process", ".", "env", ";", "}", "}" ]
Get an env object to inject into child process.
[ "Get", "an", "env", "object", "to", "inject", "into", "child", "process", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/util/shell.js#L26-L36
train
kalabox/kalabox
lib/integrations.js
function(name, fn) { try { // Create options. var opts = createInternals(name, fn); // Create new integration instance. var newIntegration = new Integration(opts); // Get key to register with. var key = newIntegration.name; // Ensure this integration isn't already registered. if (integrations[key]) { throw new Error('Integration already exists: ' + key); } // Register integration. integrations[key] = newIntegration; // Return integration. return newIntegration; } catch (err) { // Wrap errors. throw new VError(err, 'Error creating new integration: ' + name); } }
javascript
function(name, fn) { try { // Create options. var opts = createInternals(name, fn); // Create new integration instance. var newIntegration = new Integration(opts); // Get key to register with. var key = newIntegration.name; // Ensure this integration isn't already registered. if (integrations[key]) { throw new Error('Integration already exists: ' + key); } // Register integration. integrations[key] = newIntegration; // Return integration. return newIntegration; } catch (err) { // Wrap errors. throw new VError(err, 'Error creating new integration: ' + name); } }
[ "function", "(", "name", ",", "fn", ")", "{", "try", "{", "var", "opts", "=", "createInternals", "(", "name", ",", "fn", ")", ";", "var", "newIntegration", "=", "new", "Integration", "(", "opts", ")", ";", "var", "key", "=", "newIntegration", ".", "name", ";", "if", "(", "integrations", "[", "key", "]", ")", "{", "throw", "new", "Error", "(", "'Integration already exists: '", "+", "key", ")", ";", "}", "integrations", "[", "key", "]", "=", "newIntegration", ";", "return", "newIntegration", ";", "}", "catch", "(", "err", ")", "{", "throw", "new", "VError", "(", "err", ",", "'Error creating new integration: '", "+", "name", ")", ";", "}", "}" ]
Create new integration class instance and register with singleton map. @memberof integrations
[ "Create", "new", "integration", "class", "instance", "and", "register", "with", "singleton", "map", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/integrations.js#L49-L69
train
kalabox/kalabox
lib/integrations.js
function(name) { if (name) { // Find integration by name. var result = integrations[name]; if (!result) { throw new Error('Integration does not exist: ' + name); } return result; } else { // Return entire singleton integration map. return integrations; } }
javascript
function(name) { if (name) { // Find integration by name. var result = integrations[name]; if (!result) { throw new Error('Integration does not exist: ' + name); } return result; } else { // Return entire singleton integration map. return integrations; } }
[ "function", "(", "name", ")", "{", "if", "(", "name", ")", "{", "var", "result", "=", "integrations", "[", "name", "]", ";", "if", "(", "!", "result", ")", "{", "throw", "new", "Error", "(", "'Integration does not exist: '", "+", "name", ")", ";", "}", "return", "result", ";", "}", "else", "{", "return", "integrations", ";", "}", "}" ]
Return list of integrations, or if a name is given, just return the integration registered under that name. @memberof integrations
[ "Return", "list", "of", "integrations", "or", "if", "a", "name", "is", "given", "just", "return", "the", "integration", "registered", "under", "that", "name", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/integrations.js#L76-L88
train
kalabox/kalabox
lib/app.js
rec
function rec(counter) { // Format next app name to check for. var name = counter ? util.format(opts.template, appName, counter) : appName; // Check if app name exists. return exists(name) .then(function(exists) { // App name already exists. if (exists) { // We've checked for a reasonable amount of app names without finding // one so just return original app name. if (counter > 255) { return appName; // Recurse with an incremented counter. } else if (!counter) { return rec(1); // Recurse with an incremented counter. } else { return rec(counter + 1); } // App name does NOT already exist, we found it! } else { return name; } }); }
javascript
function rec(counter) { // Format next app name to check for. var name = counter ? util.format(opts.template, appName, counter) : appName; // Check if app name exists. return exists(name) .then(function(exists) { // App name already exists. if (exists) { // We've checked for a reasonable amount of app names without finding // one so just return original app name. if (counter > 255) { return appName; // Recurse with an incremented counter. } else if (!counter) { return rec(1); // Recurse with an incremented counter. } else { return rec(counter + 1); } // App name does NOT already exist, we found it! } else { return name; } }); }
[ "function", "rec", "(", "counter", ")", "{", "var", "name", "=", "counter", "?", "util", ".", "format", "(", "opts", ".", "template", ",", "appName", ",", "counter", ")", ":", "appName", ";", "return", "exists", "(", "name", ")", ".", "then", "(", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "if", "(", "counter", ">", "255", ")", "{", "return", "appName", ";", "}", "else", "if", "(", "!", "counter", ")", "{", "return", "rec", "(", "1", ")", ";", "}", "else", "{", "return", "rec", "(", "counter", "+", "1", ")", ";", "}", "}", "else", "{", "return", "name", ";", "}", "}", ")", ";", "}" ]
Recursive function for finding unique app name.
[ "Recursive", "function", "for", "finding", "unique", "app", "name", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app.js#L453-L479
train
kalabox/kalabox
src/modules/guiEngine/recloop.js
rec
function rec() { // Start a new promise. return Promise.fromNode(function(cb) { // Apply jitter to interval to get next timeout duration. var duration = applyJitter(opts.jitter, opts.interval); // Init a timeout. setTimeout(function() { // Run handler function. return $q.try(fn) // Handle errors. .catch(function(err) { return errorHandler(err); }) // Resolve promise. .nodeify(cb); }, duration); }) // Recurse unless top flag has been set. .then(function() { if (!stopFlag) { return rec(); } }); }
javascript
function rec() { // Start a new promise. return Promise.fromNode(function(cb) { // Apply jitter to interval to get next timeout duration. var duration = applyJitter(opts.jitter, opts.interval); // Init a timeout. setTimeout(function() { // Run handler function. return $q.try(fn) // Handle errors. .catch(function(err) { return errorHandler(err); }) // Resolve promise. .nodeify(cb); }, duration); }) // Recurse unless top flag has been set. .then(function() { if (!stopFlag) { return rec(); } }); }
[ "function", "rec", "(", ")", "{", "return", "Promise", ".", "fromNode", "(", "function", "(", "cb", ")", "{", "var", "duration", "=", "applyJitter", "(", "opts", ".", "jitter", ",", "opts", ".", "interval", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "return", "$q", ".", "try", "(", "fn", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "errorHandler", "(", "err", ")", ";", "}", ")", ".", "nodeify", "(", "cb", ")", ";", "}", ",", "duration", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "stopFlag", ")", "{", "return", "rec", "(", ")", ";", "}", "}", ")", ";", "}" ]
Recursive function.
[ "Recursive", "function", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/src/modules/guiEngine/recloop.js#L39-L62
train
robwierzbowski/grunt-build-control
tasks/build_control.js
assignTokens
function assignTokens () { var sourceBranch = shelljs.exec('git rev-parse --abbrev-ref HEAD', {silent: true}); var sourceCommit = shelljs.exec('git rev-parse --short HEAD', {silent: true}); if (sourceBranch.code === 0) { tokens.branch = sourceBranch.output.replace(/\n/g, ''); } if (sourceCommit.code === 0) { tokens.commit = sourceCommit.output.replace(/\n/g, ''); } if (shelljs.test('-f', 'package.json', {silent: true})) { tokens.name = JSON.parse(fs.readFileSync('package.json', 'utf8')).name; } else { tokens.name = process.cwd().split('/').pop(); } }
javascript
function assignTokens () { var sourceBranch = shelljs.exec('git rev-parse --abbrev-ref HEAD', {silent: true}); var sourceCommit = shelljs.exec('git rev-parse --short HEAD', {silent: true}); if (sourceBranch.code === 0) { tokens.branch = sourceBranch.output.replace(/\n/g, ''); } if (sourceCommit.code === 0) { tokens.commit = sourceCommit.output.replace(/\n/g, ''); } if (shelljs.test('-f', 'package.json', {silent: true})) { tokens.name = JSON.parse(fs.readFileSync('package.json', 'utf8')).name; } else { tokens.name = process.cwd().split('/').pop(); } }
[ "function", "assignTokens", "(", ")", "{", "var", "sourceBranch", "=", "shelljs", ".", "exec", "(", "'git rev-parse --abbrev-ref HEAD'", ",", "{", "silent", ":", "true", "}", ")", ";", "var", "sourceCommit", "=", "shelljs", ".", "exec", "(", "'git rev-parse --short HEAD'", ",", "{", "silent", ":", "true", "}", ")", ";", "if", "(", "sourceBranch", ".", "code", "===", "0", ")", "{", "tokens", ".", "branch", "=", "sourceBranch", ".", "output", ".", "replace", "(", "/", "\\n", "/", "g", ",", "''", ")", ";", "}", "if", "(", "sourceCommit", ".", "code", "===", "0", ")", "{", "tokens", ".", "commit", "=", "sourceCommit", ".", "output", ".", "replace", "(", "/", "\\n", "/", "g", ",", "''", ")", ";", "}", "if", "(", "shelljs", ".", "test", "(", "'-f'", ",", "'package.json'", ",", "{", "silent", ":", "true", "}", ")", ")", "{", "tokens", ".", "name", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "'package.json'", ",", "'utf8'", ")", ")", ".", "name", ";", "}", "else", "{", "tokens", ".", "name", "=", "process", ".", "cwd", "(", ")", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", ";", "}", "}" ]
Assign %token% values if available
[ "Assign", "%token%", "values", "if", "available" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L152-L168
train
robwierzbowski/grunt-build-control
tasks/build_control.js
initGit
function initGit () { if (!fs.existsSync(path.join(gruntDir, options.dir, '.git'))) { log.subhead('Creating git repository in "' + options.dir + '".'); execWrap('git init'); } }
javascript
function initGit () { if (!fs.existsSync(path.join(gruntDir, options.dir, '.git'))) { log.subhead('Creating git repository in "' + options.dir + '".'); execWrap('git init'); } }
[ "function", "initGit", "(", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "gruntDir", ",", "options", ".", "dir", ",", "'.git'", ")", ")", ")", "{", "log", ".", "subhead", "(", "'Creating git repository in \"'", "+", "options", ".", "dir", "+", "'\".'", ")", ";", "execWrap", "(", "'git init'", ")", ";", "}", "}" ]
Initialize git repo if one doesn't exist
[ "Initialize", "git", "repo", "if", "one", "doesn", "t", "exist" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L180-L186
train
robwierzbowski/grunt-build-control
tasks/build_control.js
initRemote
function initRemote () { remoteName = "remote-" + crypto.createHash('md5').update(options.remote).digest('hex').substring(0, 6); if (shelljs.exec('git remote', {silent: true}).output.indexOf(remoteName) === -1) { log.subhead('Creating remote.'); execWrap('git remote add ' + remoteName + ' ' + options.remote); } }
javascript
function initRemote () { remoteName = "remote-" + crypto.createHash('md5').update(options.remote).digest('hex').substring(0, 6); if (shelljs.exec('git remote', {silent: true}).output.indexOf(remoteName) === -1) { log.subhead('Creating remote.'); execWrap('git remote add ' + remoteName + ' ' + options.remote); } }
[ "function", "initRemote", "(", ")", "{", "remoteName", "=", "\"remote-\"", "+", "crypto", ".", "createHash", "(", "'md5'", ")", ".", "update", "(", "options", ".", "remote", ")", ".", "digest", "(", "'hex'", ")", ".", "substring", "(", "0", ",", "6", ")", ";", "if", "(", "shelljs", ".", "exec", "(", "'git remote'", ",", "{", "silent", ":", "true", "}", ")", ".", "output", ".", "indexOf", "(", "remoteName", ")", "===", "-", "1", ")", "{", "log", ".", "subhead", "(", "'Creating remote.'", ")", ";", "execWrap", "(", "'git remote add '", "+", "remoteName", "+", "' '", "+", "options", ".", "remote", ")", ";", "}", "}" ]
Create a named remote if one doesn't exist
[ "Create", "a", "named", "remote", "if", "one", "doesn", "t", "exist" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L198-L205
train
robwierzbowski/grunt-build-control
tasks/build_control.js
gitFetch
function gitFetch (dest) { var branch = (options.remoteBranch || options.branch) + (dest ? ':' + options.branch : ''); log.subhead('Fetching "' + options.branch + '" ' + (options.shallowFetch ? 'files' : 'history') + ' from ' + options.remote + '.'); // `--update-head-ok` allows fetch on a branch with uncommited changes execWrap('git fetch --update-head-ok ' + progress + depth + remoteName + ' ' + branch, false, true); }
javascript
function gitFetch (dest) { var branch = (options.remoteBranch || options.branch) + (dest ? ':' + options.branch : ''); log.subhead('Fetching "' + options.branch + '" ' + (options.shallowFetch ? 'files' : 'history') + ' from ' + options.remote + '.'); // `--update-head-ok` allows fetch on a branch with uncommited changes execWrap('git fetch --update-head-ok ' + progress + depth + remoteName + ' ' + branch, false, true); }
[ "function", "gitFetch", "(", "dest", ")", "{", "var", "branch", "=", "(", "options", ".", "remoteBranch", "||", "options", ".", "branch", ")", "+", "(", "dest", "?", "':'", "+", "options", ".", "branch", ":", "''", ")", ";", "log", ".", "subhead", "(", "'Fetching \"'", "+", "options", ".", "branch", "+", "'\" '", "+", "(", "options", ".", "shallowFetch", "?", "'files'", ":", "'history'", ")", "+", "' from '", "+", "options", ".", "remote", "+", "'.'", ")", ";", "execWrap", "(", "'git fetch --update-head-ok '", "+", "progress", "+", "depth", "+", "remoteName", "+", "' '", "+", "branch", ",", "false", ",", "true", ")", ";", "}" ]
Fetch remote refs to a specific branch, equivalent to a pull without checkout
[ "Fetch", "remote", "refs", "to", "a", "specific", "branch", "equivalent", "to", "a", "pull", "without", "checkout" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L238-L244
train
robwierzbowski/grunt-build-control
tasks/build_control.js
gitTrack
function gitTrack () { var remoteBranch = options.remoteBranch || options.branch; if (shelljs.exec('git config branch.' + options.branch + '.remote', {silent: true}).output.replace(/\n/g, '') !== remoteName) { execWrap('git branch --set-upstream-to=' + remoteName + '/' + remoteBranch + ' ' + options.branch); } }
javascript
function gitTrack () { var remoteBranch = options.remoteBranch || options.branch; if (shelljs.exec('git config branch.' + options.branch + '.remote', {silent: true}).output.replace(/\n/g, '') !== remoteName) { execWrap('git branch --set-upstream-to=' + remoteName + '/' + remoteBranch + ' ' + options.branch); } }
[ "function", "gitTrack", "(", ")", "{", "var", "remoteBranch", "=", "options", ".", "remoteBranch", "||", "options", ".", "branch", ";", "if", "(", "shelljs", ".", "exec", "(", "'git config branch.'", "+", "options", ".", "branch", "+", "'.remote'", ",", "{", "silent", ":", "true", "}", ")", ".", "output", ".", "replace", "(", "/", "\\n", "/", "g", ",", "''", ")", "!==", "remoteName", ")", "{", "execWrap", "(", "'git branch --set-upstream-to='", "+", "remoteName", "+", "'/'", "+", "remoteBranch", "+", "' '", "+", "options", ".", "branch", ")", ";", "}", "}" ]
Set branch to track remote
[ "Set", "branch", "to", "track", "remote" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L257-L262
train
robwierzbowski/grunt-build-control
tasks/build_control.js
gitCommit
function gitCommit () { var message = options.message .replace(/%sourceName%/g, tokens.name) .replace(/%sourceCommit%/g, tokens.commit) .replace(/%sourceBranch%/g, tokens.branch); // If there are no changes, skip commit if (shelljs.exec('git status --porcelain', {silent: true}).output === '') { log.subhead('No changes to your branch. Skipping commit.'); return; } log.subhead('Committing changes to "' + options.branch + '".'); execWrap('git add -A .'); // generate commit message var commitFile = 'commitFile-' + crypto.createHash('md5').update(message).digest('hex').substring(0, 6); fs.writeFileSync(commitFile, message); execWrap('git commit --file=' + commitFile); fs.unlinkSync(commitFile); }
javascript
function gitCommit () { var message = options.message .replace(/%sourceName%/g, tokens.name) .replace(/%sourceCommit%/g, tokens.commit) .replace(/%sourceBranch%/g, tokens.branch); // If there are no changes, skip commit if (shelljs.exec('git status --porcelain', {silent: true}).output === '') { log.subhead('No changes to your branch. Skipping commit.'); return; } log.subhead('Committing changes to "' + options.branch + '".'); execWrap('git add -A .'); // generate commit message var commitFile = 'commitFile-' + crypto.createHash('md5').update(message).digest('hex').substring(0, 6); fs.writeFileSync(commitFile, message); execWrap('git commit --file=' + commitFile); fs.unlinkSync(commitFile); }
[ "function", "gitCommit", "(", ")", "{", "var", "message", "=", "options", ".", "message", ".", "replace", "(", "/", "%sourceName%", "/", "g", ",", "tokens", ".", "name", ")", ".", "replace", "(", "/", "%sourceCommit%", "/", "g", ",", "tokens", ".", "commit", ")", ".", "replace", "(", "/", "%sourceBranch%", "/", "g", ",", "tokens", ".", "branch", ")", ";", "if", "(", "shelljs", ".", "exec", "(", "'git status --porcelain'", ",", "{", "silent", ":", "true", "}", ")", ".", "output", "===", "''", ")", "{", "log", ".", "subhead", "(", "'No changes to your branch. Skipping commit.'", ")", ";", "return", ";", "}", "log", ".", "subhead", "(", "'Committing changes to \"'", "+", "options", ".", "branch", "+", "'\".'", ")", ";", "execWrap", "(", "'git add -A .'", ")", ";", "var", "commitFile", "=", "'commitFile-'", "+", "crypto", ".", "createHash", "(", "'md5'", ")", ".", "update", "(", "message", ")", ".", "digest", "(", "'hex'", ")", ".", "substring", "(", "0", ",", "6", ")", ";", "fs", ".", "writeFileSync", "(", "commitFile", ",", "message", ")", ";", "execWrap", "(", "'git commit --file='", "+", "commitFile", ")", ";", "fs", ".", "unlinkSync", "(", "commitFile", ")", ";", "}" ]
Stage and commit to a branch
[ "Stage", "and", "commit", "to", "a", "branch" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L265-L287
train
robwierzbowski/grunt-build-control
tasks/build_control.js
gitTag
function gitTag () { // If the tag exists, skip tagging if (shelljs.exec('git ls-remote --tags --exit-code ' + remoteName + ' ' + options.tag, {silent: true}).code === 0) { log.subhead('The tag "' + options.tag + '" already exists on remote. Skipping tagging.'); return; } log.subhead('Tagging the local repository with ' + options.tag); execWrap('git tag ' + options.tag); }
javascript
function gitTag () { // If the tag exists, skip tagging if (shelljs.exec('git ls-remote --tags --exit-code ' + remoteName + ' ' + options.tag, {silent: true}).code === 0) { log.subhead('The tag "' + options.tag + '" already exists on remote. Skipping tagging.'); return; } log.subhead('Tagging the local repository with ' + options.tag); execWrap('git tag ' + options.tag); }
[ "function", "gitTag", "(", ")", "{", "if", "(", "shelljs", ".", "exec", "(", "'git ls-remote --tags --exit-code '", "+", "remoteName", "+", "' '", "+", "options", ".", "tag", ",", "{", "silent", ":", "true", "}", ")", ".", "code", "===", "0", ")", "{", "log", ".", "subhead", "(", "'The tag \"'", "+", "options", ".", "tag", "+", "'\" already exists on remote. Skipping tagging.'", ")", ";", "return", ";", "}", "log", ".", "subhead", "(", "'Tagging the local repository with '", "+", "options", ".", "tag", ")", ";", "execWrap", "(", "'git tag '", "+", "options", ".", "tag", ")", ";", "}" ]
Tag local branch
[ "Tag", "local", "branch" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L290-L299
train
robwierzbowski/grunt-build-control
tasks/build_control.js
gitPush
function gitPush () { var branch = options.branch; var withForce = options.force ? ' --force ' : ''; if (options.remoteBranch) branch += ':' + options.remoteBranch; log.subhead('Pushing ' + options.branch + ' to ' + options.remote + withForce); execWrap('git push ' + withForce + remoteName + ' ' + branch, false, true); if (options.tag) { execWrap('git push ' + remoteName + ' ' + options.tag); } }
javascript
function gitPush () { var branch = options.branch; var withForce = options.force ? ' --force ' : ''; if (options.remoteBranch) branch += ':' + options.remoteBranch; log.subhead('Pushing ' + options.branch + ' to ' + options.remote + withForce); execWrap('git push ' + withForce + remoteName + ' ' + branch, false, true); if (options.tag) { execWrap('git push ' + remoteName + ' ' + options.tag); } }
[ "function", "gitPush", "(", ")", "{", "var", "branch", "=", "options", ".", "branch", ";", "var", "withForce", "=", "options", ".", "force", "?", "' --force '", ":", "''", ";", "if", "(", "options", ".", "remoteBranch", ")", "branch", "+=", "':'", "+", "options", ".", "remoteBranch", ";", "log", ".", "subhead", "(", "'Pushing '", "+", "options", ".", "branch", "+", "' to '", "+", "options", ".", "remote", "+", "withForce", ")", ";", "execWrap", "(", "'git push '", "+", "withForce", "+", "remoteName", "+", "' '", "+", "branch", ",", "false", ",", "true", ")", ";", "if", "(", "options", ".", "tag", ")", "{", "execWrap", "(", "'git push '", "+", "remoteName", "+", "' '", "+", "options", ".", "tag", ")", ";", "}", "}" ]
Push branch to remote
[ "Push", "branch", "to", "remote" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L302-L314
train
ncuillery/angular-breadcrumb
release/angular-breadcrumb.js
function(state) { // Check if state has explicit parent OR we try guess parent from its name var parent = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1]; var isObjectParent = typeof parent === "object"; // if parent is a object reference, then extract the name return isObjectParent ? parent.name : parent; }
javascript
function(state) { // Check if state has explicit parent OR we try guess parent from its name var parent = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1]; var isObjectParent = typeof parent === "object"; // if parent is a object reference, then extract the name return isObjectParent ? parent.name : parent; }
[ "function", "(", "state", ")", "{", "var", "parent", "=", "state", ".", "parent", "||", "(", "/", "^(.+)\\.[^.]+$", "/", ".", "exec", "(", "state", ".", "name", ")", "||", "[", "]", ")", "[", "1", "]", ";", "var", "isObjectParent", "=", "typeof", "parent", "===", "\"object\"", ";", "return", "isObjectParent", "?", "parent", ".", "name", ":", "parent", ";", "}" ]
Get the parent state
[ "Get", "the", "parent", "state" ]
301df6351f9272347ad3bd4b75f51a4d245dd2ef
https://github.com/ncuillery/angular-breadcrumb/blob/301df6351f9272347ad3bd4b75f51a4d245dd2ef/release/angular-breadcrumb.js#L61-L67
train
ncuillery/angular-breadcrumb
release/angular-breadcrumb.js
function(chain, stateRef) { var conf, parentParams, ref = parseStateRef(stateRef), force = false, skip = false; for(var i=0, l=chain.length; i<l; i+=1) { if (chain[i].name === ref.state) { return; } } conf = $state.get(ref.state); // Get breadcrumb options if(conf.ncyBreadcrumb) { if(conf.ncyBreadcrumb.force){ force = true; } if(conf.ncyBreadcrumb.skip){ skip = true; } } if((!conf.abstract || $$options.includeAbstract || force) && !skip) { if(ref.paramExpr) { parentParams = $lastViewScope.$eval(ref.paramExpr); } conf.ncyBreadcrumbLink = $state.href(ref.state, parentParams || $stateParams || {}); conf.ncyBreadcrumbStateRef = stateRef; chain.unshift(conf); } }
javascript
function(chain, stateRef) { var conf, parentParams, ref = parseStateRef(stateRef), force = false, skip = false; for(var i=0, l=chain.length; i<l; i+=1) { if (chain[i].name === ref.state) { return; } } conf = $state.get(ref.state); // Get breadcrumb options if(conf.ncyBreadcrumb) { if(conf.ncyBreadcrumb.force){ force = true; } if(conf.ncyBreadcrumb.skip){ skip = true; } } if((!conf.abstract || $$options.includeAbstract || force) && !skip) { if(ref.paramExpr) { parentParams = $lastViewScope.$eval(ref.paramExpr); } conf.ncyBreadcrumbLink = $state.href(ref.state, parentParams || $stateParams || {}); conf.ncyBreadcrumbStateRef = stateRef; chain.unshift(conf); } }
[ "function", "(", "chain", ",", "stateRef", ")", "{", "var", "conf", ",", "parentParams", ",", "ref", "=", "parseStateRef", "(", "stateRef", ")", ",", "force", "=", "false", ",", "skip", "=", "false", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "chain", ".", "length", ";", "i", "<", "l", ";", "i", "+=", "1", ")", "{", "if", "(", "chain", "[", "i", "]", ".", "name", "===", "ref", ".", "state", ")", "{", "return", ";", "}", "}", "conf", "=", "$state", ".", "get", "(", "ref", ".", "state", ")", ";", "if", "(", "conf", ".", "ncyBreadcrumb", ")", "{", "if", "(", "conf", ".", "ncyBreadcrumb", ".", "force", ")", "{", "force", "=", "true", ";", "}", "if", "(", "conf", ".", "ncyBreadcrumb", ".", "skip", ")", "{", "skip", "=", "true", ";", "}", "}", "if", "(", "(", "!", "conf", ".", "abstract", "||", "$$options", ".", "includeAbstract", "||", "force", ")", "&&", "!", "skip", ")", "{", "if", "(", "ref", ".", "paramExpr", ")", "{", "parentParams", "=", "$lastViewScope", ".", "$eval", "(", "ref", ".", "paramExpr", ")", ";", "}", "conf", ".", "ncyBreadcrumbLink", "=", "$state", ".", "href", "(", "ref", ".", "state", ",", "parentParams", "||", "$stateParams", "||", "{", "}", ")", ";", "conf", ".", "ncyBreadcrumbStateRef", "=", "stateRef", ";", "chain", ".", "unshift", "(", "conf", ")", ";", "}", "}" ]
Add the state in the chain if not already in and if not abstract
[ "Add", "the", "state", "in", "the", "chain", "if", "not", "already", "in", "and", "if", "not", "abstract" ]
301df6351f9272347ad3bd4b75f51a4d245dd2ef
https://github.com/ncuillery/angular-breadcrumb/blob/301df6351f9272347ad3bd4b75f51a4d245dd2ef/release/angular-breadcrumb.js#L70-L98
train
ncuillery/angular-breadcrumb
release/angular-breadcrumb.js
function(stateRef) { var ref = parseStateRef(stateRef), conf = $state.get(ref.state); if(conf.ncyBreadcrumb && conf.ncyBreadcrumb.parent) { // Handle the "parent" property of the breadcrumb, override the parent/child relation of the state var isFunction = typeof conf.ncyBreadcrumb.parent === 'function'; var parentStateRef = isFunction ? conf.ncyBreadcrumb.parent($lastViewScope) : conf.ncyBreadcrumb.parent; if(parentStateRef) { return parentStateRef; } } return $$parentState(conf); }
javascript
function(stateRef) { var ref = parseStateRef(stateRef), conf = $state.get(ref.state); if(conf.ncyBreadcrumb && conf.ncyBreadcrumb.parent) { // Handle the "parent" property of the breadcrumb, override the parent/child relation of the state var isFunction = typeof conf.ncyBreadcrumb.parent === 'function'; var parentStateRef = isFunction ? conf.ncyBreadcrumb.parent($lastViewScope) : conf.ncyBreadcrumb.parent; if(parentStateRef) { return parentStateRef; } } return $$parentState(conf); }
[ "function", "(", "stateRef", ")", "{", "var", "ref", "=", "parseStateRef", "(", "stateRef", ")", ",", "conf", "=", "$state", ".", "get", "(", "ref", ".", "state", ")", ";", "if", "(", "conf", ".", "ncyBreadcrumb", "&&", "conf", ".", "ncyBreadcrumb", ".", "parent", ")", "{", "var", "isFunction", "=", "typeof", "conf", ".", "ncyBreadcrumb", ".", "parent", "===", "'function'", ";", "var", "parentStateRef", "=", "isFunction", "?", "conf", ".", "ncyBreadcrumb", ".", "parent", "(", "$lastViewScope", ")", ":", "conf", ".", "ncyBreadcrumb", ".", "parent", ";", "if", "(", "parentStateRef", ")", "{", "return", "parentStateRef", ";", "}", "}", "return", "$$parentState", "(", "conf", ")", ";", "}" ]
Get the state for the parent step in the breadcrumb
[ "Get", "the", "state", "for", "the", "parent", "step", "in", "the", "breadcrumb" ]
301df6351f9272347ad3bd4b75f51a4d245dd2ef
https://github.com/ncuillery/angular-breadcrumb/blob/301df6351f9272347ad3bd4b75f51a4d245dd2ef/release/angular-breadcrumb.js#L101-L115
train
MathieuLoutre/grunt-aws-s3
tasks/aws_s3.js
function (params) { return _.every(_.keys(params), function (key) { return _.contains(put_params, key); }); }
javascript
function (params) { return _.every(_.keys(params), function (key) { return _.contains(put_params, key); }); }
[ "function", "(", "params", ")", "{", "return", "_", ".", "every", "(", "_", ".", "keys", "(", "params", ")", ",", "function", "(", "key", ")", "{", "return", "_", ".", "contains", "(", "put_params", ",", "key", ")", ";", "}", ")", ";", "}" ]
Checks that all params are in put_params
[ "Checks", "that", "all", "params", "are", "in", "put_params" ]
7ebcdd6287da7c2cbee772d763d6648d259a62a1
https://github.com/MathieuLoutre/grunt-aws-s3/blob/7ebcdd6287da7c2cbee772d763d6648d259a62a1/tasks/aws_s3.js#L82-L87
train
MathieuLoutre/grunt-aws-s3
tasks/aws_s3.js
function (key, dest) { var path; if (_.last(dest) === '/') { // if the path string is a directory, remove it from the key path = key.replace(dest, ''); } else if (key.replace(dest, '') === '') { path = _.last(key.split('/')); } else { path = key; } return path; }
javascript
function (key, dest) { var path; if (_.last(dest) === '/') { // if the path string is a directory, remove it from the key path = key.replace(dest, ''); } else if (key.replace(dest, '') === '') { path = _.last(key.split('/')); } else { path = key; } return path; }
[ "function", "(", "key", ",", "dest", ")", "{", "var", "path", ";", "if", "(", "_", ".", "last", "(", "dest", ")", "===", "'/'", ")", "{", "path", "=", "key", ".", "replace", "(", "dest", ",", "''", ")", ";", "}", "else", "if", "(", "key", ".", "replace", "(", "dest", ",", "''", ")", "===", "''", ")", "{", "path", "=", "_", ".", "last", "(", "key", ".", "split", "(", "'/'", ")", ")", ";", "}", "else", "{", "path", "=", "key", ";", "}", "return", "path", ";", "}" ]
Get the key URL relative to a path string
[ "Get", "the", "key", "URL", "relative", "to", "a", "path", "string" ]
7ebcdd6287da7c2cbee772d763d6648d259a62a1
https://github.com/MathieuLoutre/grunt-aws-s3/blob/7ebcdd6287da7c2cbee772d763d6648d259a62a1/tasks/aws_s3.js#L102-L118
train
MathieuLoutre/grunt-aws-s3
tasks/aws_s3.js
function (options, callback) { fs.stat(options.file_path, function (err, stats) { if (err) { callback(err); } else { var local_date = new Date(stats.mtime).getTime(); var server_date = new Date(options.server_date).getTime(); if (options.compare_date === 'newer') { callback(null, local_date > server_date); } else { callback(null, local_date < server_date); } } }); }
javascript
function (options, callback) { fs.stat(options.file_path, function (err, stats) { if (err) { callback(err); } else { var local_date = new Date(stats.mtime).getTime(); var server_date = new Date(options.server_date).getTime(); if (options.compare_date === 'newer') { callback(null, local_date > server_date); } else { callback(null, local_date < server_date); } } }); }
[ "function", "(", "options", ",", "callback", ")", "{", "fs", ".", "stat", "(", "options", ".", "file_path", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "{", "var", "local_date", "=", "new", "Date", "(", "stats", ".", "mtime", ")", ".", "getTime", "(", ")", ";", "var", "server_date", "=", "new", "Date", "(", "options", ".", "server_date", ")", ".", "getTime", "(", ")", ";", "if", "(", "options", ".", "compare_date", "===", "'newer'", ")", "{", "callback", "(", "null", ",", "local_date", ">", "server_date", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "local_date", "<", "server_date", ")", ";", "}", "}", "}", ")", ";", "}" ]
Checks that local file is 'date_compare' than server file
[ "Checks", "that", "local", "file", "is", "date_compare", "than", "server", "file" ]
7ebcdd6287da7c2cbee772d763d6648d259a62a1
https://github.com/MathieuLoutre/grunt-aws-s3/blob/7ebcdd6287da7c2cbee772d763d6648d259a62a1/tasks/aws_s3.js#L146-L165
train
cytoscape/cytoscape.js-cose-bilkent
src/Layout/index.js
function() { if (options.fit) { options.cy.fit(options.eles.nodes(), options.padding); } if (!ready) { ready = true; self.cy.one('layoutready', options.ready); self.cy.trigger({type: 'layoutready', layout: self}); } }
javascript
function() { if (options.fit) { options.cy.fit(options.eles.nodes(), options.padding); } if (!ready) { ready = true; self.cy.one('layoutready', options.ready); self.cy.trigger({type: 'layoutready', layout: self}); } }
[ "function", "(", ")", "{", "if", "(", "options", ".", "fit", ")", "{", "options", ".", "cy", ".", "fit", "(", "options", ".", "eles", ".", "nodes", "(", ")", ",", "options", ".", "padding", ")", ";", "}", "if", "(", "!", "ready", ")", "{", "ready", "=", "true", ";", "self", ".", "cy", ".", "one", "(", "'layoutready'", ",", "options", ".", "ready", ")", ";", "self", ".", "cy", ".", "trigger", "(", "{", "type", ":", "'layoutready'", ",", "layout", ":", "self", "}", ")", ";", "}", "}" ]
Thigs to perform after nodes are repositioned on screen
[ "Thigs", "to", "perform", "after", "nodes", "are", "repositioned", "on", "screen" ]
8834b05101daf241ba75ea4a84b703fffec5cbc5
https://github.com/cytoscape/cytoscape.js-cose-bilkent/blob/8834b05101daf241ba75ea4a84b703fffec5cbc5/src/Layout/index.js#L186-L196
train
telehash/telehash-js
ext/stream.class.js
ChannelStream
function ChannelStream(chan, encoding){ if(!encoding) encoding = 'binary'; if(typeof chan != 'object' || !chan.isChannel) { log.warn('invalid channel passed to streamize'); return false; } var allowHalfOpen = (chan.type === "thtp") ? true : false; Duplex.call(this,{allowHalfOpen: allowHalfOpen, objectMode:true}) this.on('finish',function(){ chan.send({json:{end:true}}); }); this.on('error',function(err){ if(err == chan.err) return; // ignore our own generated errors chan.send({json:{err:err.toString()}}); }); var stream = this this.on('pipe', function(from){ from.on('end',function(){ stream.end() }) }) chan.receiving = chan_to_stream(this); this._chan = chan; this._encoding = encoding; return this; }
javascript
function ChannelStream(chan, encoding){ if(!encoding) encoding = 'binary'; if(typeof chan != 'object' || !chan.isChannel) { log.warn('invalid channel passed to streamize'); return false; } var allowHalfOpen = (chan.type === "thtp") ? true : false; Duplex.call(this,{allowHalfOpen: allowHalfOpen, objectMode:true}) this.on('finish',function(){ chan.send({json:{end:true}}); }); this.on('error',function(err){ if(err == chan.err) return; // ignore our own generated errors chan.send({json:{err:err.toString()}}); }); var stream = this this.on('pipe', function(from){ from.on('end',function(){ stream.end() }) }) chan.receiving = chan_to_stream(this); this._chan = chan; this._encoding = encoding; return this; }
[ "function", "ChannelStream", "(", "chan", ",", "encoding", ")", "{", "if", "(", "!", "encoding", ")", "encoding", "=", "'binary'", ";", "if", "(", "typeof", "chan", "!=", "'object'", "||", "!", "chan", ".", "isChannel", ")", "{", "log", ".", "warn", "(", "'invalid channel passed to streamize'", ")", ";", "return", "false", ";", "}", "var", "allowHalfOpen", "=", "(", "chan", ".", "type", "===", "\"thtp\"", ")", "?", "true", ":", "false", ";", "Duplex", ".", "call", "(", "this", ",", "{", "allowHalfOpen", ":", "allowHalfOpen", ",", "objectMode", ":", "true", "}", ")", "this", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "chan", ".", "send", "(", "{", "json", ":", "{", "end", ":", "true", "}", "}", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "if", "(", "err", "==", "chan", ".", "err", ")", "return", ";", "chan", ".", "send", "(", "{", "json", ":", "{", "err", ":", "err", ".", "toString", "(", ")", "}", "}", ")", ";", "}", ")", ";", "var", "stream", "=", "this", "this", ".", "on", "(", "'pipe'", ",", "function", "(", "from", ")", "{", "from", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "stream", ".", "end", "(", ")", "}", ")", "}", ")", "chan", ".", "receiving", "=", "chan_to_stream", "(", "this", ")", ";", "this", ".", "_chan", "=", "chan", ";", "this", ".", "_encoding", "=", "encoding", ";", "return", "this", ";", "}" ]
ChannelStream impliments a Duplex stream API over Telehash channels. for Duplex stream usage, consult core node docs. for an idea of how you might expand upon streams within the Telehash ecosystem, see thtp @class ChannelStream @constructor @param {Channel} channel - a Telehash channel (generated by e3x) @param {stringa} encoding - 'binary' or 'json' @return {Stream}
[ "ChannelStream", "impliments", "a", "Duplex", "stream", "API", "over", "Telehash", "channels", ".", "for", "Duplex", "stream", "usage", "consult", "core", "node", "docs", ".", "for", "an", "idea", "of", "how", "you", "might", "expand", "upon", "streams", "within", "the", "Telehash", "ecosystem", "see", "thtp" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/ext/stream.class.js#L17-L51
train
telehash/telehash-js
ext/chat.js
fail
function fail(err, cbErr) { if(!err) return; // only catch errors log.warn('chat fail',err); chat.err = err; // TODO error inbox/outbox if(typeof cbErr == 'function') cbErr(err); readyUp(err); }
javascript
function fail(err, cbErr) { if(!err) return; // only catch errors log.warn('chat fail',err); chat.err = err; // TODO error inbox/outbox if(typeof cbErr == 'function') cbErr(err); readyUp(err); }
[ "function", "fail", "(", "err", ",", "cbErr", ")", "{", "if", "(", "!", "err", ")", "return", ";", "log", ".", "warn", "(", "'chat fail'", ",", "err", ")", ";", "chat", ".", "err", "=", "err", ";", "if", "(", "typeof", "cbErr", "==", "'function'", ")", "cbErr", "(", "err", ")", ";", "readyUp", "(", "err", ")", ";", "}" ]
internal fail handler
[ "internal", "fail", "handler" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/ext/chat.js#L79-L87
train
telehash/telehash-js
ext/chat.js
stamp
function stamp() { if(!chat.seq) return fail('chat history overflow, please restart'); var id = lib.hashname.siphash(mesh.hashname, chat.secret); for(var i = 0; i < chat.seq; i++) id = lib.hashname.siphash(id.key,id); chat.seq--; return lib.base32.encode(id); }
javascript
function stamp() { if(!chat.seq) return fail('chat history overflow, please restart'); var id = lib.hashname.siphash(mesh.hashname, chat.secret); for(var i = 0; i < chat.seq; i++) id = lib.hashname.siphash(id.key,id); chat.seq--; return lib.base32.encode(id); }
[ "function", "stamp", "(", ")", "{", "if", "(", "!", "chat", ".", "seq", ")", "return", "fail", "(", "'chat history overflow, please restart'", ")", ";", "var", "id", "=", "lib", ".", "hashname", ".", "siphash", "(", "mesh", ".", "hashname", ",", "chat", ".", "secret", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "chat", ".", "seq", ";", "i", "++", ")", "id", "=", "lib", ".", "hashname", ".", "siphash", "(", "id", ".", "key", ",", "id", ")", ";", "chat", ".", "seq", "--", ";", "return", "lib", ".", "base32", ".", "encode", "(", "id", ")", ";", "}" ]
internal message id generator
[ "internal", "message", "id", "generator" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/ext/chat.js#L90-L97
train
telehash/telehash-js
ext/chat.js
sync
function sync(id) { if(id == last.json.id) return; // bottoms up, send older first sync(lib.base32.encode(lib.hashname.siphash(mesh.hashname, lib.base32.decode(id)))); stream.write(chat.messages[id]); }
javascript
function sync(id) { if(id == last.json.id) return; // bottoms up, send older first sync(lib.base32.encode(lib.hashname.siphash(mesh.hashname, lib.base32.decode(id)))); stream.write(chat.messages[id]); }
[ "function", "sync", "(", "id", ")", "{", "if", "(", "id", "==", "last", ".", "json", ".", "id", ")", "return", ";", "sync", "(", "lib", ".", "base32", ".", "encode", "(", "lib", ".", "hashname", ".", "siphash", "(", "mesh", ".", "hashname", ",", "lib", ".", "base32", ".", "decode", "(", "id", ")", ")", ")", ")", ";", "stream", ".", "write", "(", "chat", ".", "messages", "[", "id", "]", ")", ";", "}" ]
send any messages since the last they saw
[ "send", "any", "messages", "since", "the", "last", "they", "saw" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/ext/chat.js#L169-L175
train
telehash/telehash-js
bin/chat.js
rlog
function rlog() { process.stdout.clearLine(); process.stdout.cursorTo(0); console.log.apply(console, arguments); rl.prompt(); }
javascript
function rlog() { process.stdout.clearLine(); process.stdout.cursorTo(0); console.log.apply(console, arguments); rl.prompt(); }
[ "function", "rlog", "(", ")", "{", "process", ".", "stdout", ".", "clearLine", "(", ")", ";", "process", ".", "stdout", ".", "cursorTo", "(", "0", ")", ";", "console", ".", "log", ".", "apply", "(", "console", ",", "arguments", ")", ";", "rl", ".", "prompt", "(", ")", ";", "}" ]
clear readline then log
[ "clear", "readline", "then", "log" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/bin/chat.js#L49-L55
train
telehash/telehash-js
lib/util/json.js
loadMeshJSON
function loadMeshJSON(mesh,hashname, args){ // add/get json store var json = mesh.json_store[hashname]; if(!json) json = mesh.json_store[hashname] = {hashname:hashname,paths:[],keys:{}}; if(args.keys) json.keys = args.keys; // only know a single csid/key if(args.csid && args.key) { json.keys[args.csid] = args.key; } // make sure no buffers Object.keys(json.keys).forEach(function(csid){ if(Buffer.isBuffer(json.keys[csid])) json.keys[csid] = base32.encode(json.keys[csid]); }); return json; }
javascript
function loadMeshJSON(mesh,hashname, args){ // add/get json store var json = mesh.json_store[hashname]; if(!json) json = mesh.json_store[hashname] = {hashname:hashname,paths:[],keys:{}}; if(args.keys) json.keys = args.keys; // only know a single csid/key if(args.csid && args.key) { json.keys[args.csid] = args.key; } // make sure no buffers Object.keys(json.keys).forEach(function(csid){ if(Buffer.isBuffer(json.keys[csid])) json.keys[csid] = base32.encode(json.keys[csid]); }); return json; }
[ "function", "loadMeshJSON", "(", "mesh", ",", "hashname", ",", "args", ")", "{", "var", "json", "=", "mesh", ".", "json_store", "[", "hashname", "]", ";", "if", "(", "!", "json", ")", "json", "=", "mesh", ".", "json_store", "[", "hashname", "]", "=", "{", "hashname", ":", "hashname", ",", "paths", ":", "[", "]", ",", "keys", ":", "{", "}", "}", ";", "if", "(", "args", ".", "keys", ")", "json", ".", "keys", "=", "args", ".", "keys", ";", "if", "(", "args", ".", "csid", "&&", "args", ".", "key", ")", "{", "json", ".", "keys", "[", "args", ".", "csid", "]", "=", "args", ".", "key", ";", "}", "Object", ".", "keys", "(", "json", ".", "keys", ")", ".", "forEach", "(", "function", "(", "csid", ")", "{", "if", "(", "Buffer", ".", "isBuffer", "(", "json", ".", "keys", "[", "csid", "]", ")", ")", "json", ".", "keys", "[", "csid", "]", "=", "base32", ".", "encode", "(", "json", ".", "keys", "[", "csid", "]", ")", ";", "}", ")", ";", "return", "json", ";", "}" ]
load a hashname and other parameters into our json format @param {hashname} hn @param {object} args - a hash with key, keys, and csid params @return {object} json - the populated json
[ "load", "a", "hashname", "and", "other", "parameters", "into", "our", "json", "format" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/lib/util/json.js#L15-L37
train
telehash/telehash-js
lib/mesh.class.js
ready
function ready(err, mesh) { // links can be passed in if(Array.isArray(args.links)) args.links.forEach(function forEachLinkArg(linkArg){ if(linkArg.hashname == mesh.hashname) return; // ignore ourselves, happens mesh.link(linkArg); }); cbMesh(err,mesh); }
javascript
function ready(err, mesh) { // links can be passed in if(Array.isArray(args.links)) args.links.forEach(function forEachLinkArg(linkArg){ if(linkArg.hashname == mesh.hashname) return; // ignore ourselves, happens mesh.link(linkArg); }); cbMesh(err,mesh); }
[ "function", "ready", "(", "err", ",", "mesh", ")", "{", "if", "(", "Array", ".", "isArray", "(", "args", ".", "links", ")", ")", "args", ".", "links", ".", "forEach", "(", "function", "forEachLinkArg", "(", "linkArg", ")", "{", "if", "(", "linkArg", ".", "hashname", "==", "mesh", ".", "hashname", ")", "return", ";", "mesh", ".", "link", "(", "linkArg", ")", ";", "}", ")", ";", "cbMesh", "(", "err", ",", "mesh", ")", ";", "}" ]
after extensions have run, load any other arguments
[ "after", "extensions", "have", "run", "load", "any", "other", "arguments" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/lib/mesh.class.js#L89-L99
train
telehash/telehash-js
index.js
loaded
function loaded(err) { if(err) { log.error(err); cbMesh(err); return false; } return telehash.mesh(args, function(err, mesh){ if(!mesh) return cbMesh(err); // sync links automatically to file whenever they change if(linksFile) mesh.linked(function(json, str){ log.debug('syncing links json',linksFile,str.length); fs.writeFileSync(linksFile, str); }); cbMesh(err, mesh); }); }
javascript
function loaded(err) { if(err) { log.error(err); cbMesh(err); return false; } return telehash.mesh(args, function(err, mesh){ if(!mesh) return cbMesh(err); // sync links automatically to file whenever they change if(linksFile) mesh.linked(function(json, str){ log.debug('syncing links json',linksFile,str.length); fs.writeFileSync(linksFile, str); }); cbMesh(err, mesh); }); }
[ "function", "loaded", "(", "err", ")", "{", "if", "(", "err", ")", "{", "log", ".", "error", "(", "err", ")", ";", "cbMesh", "(", "err", ")", ";", "return", "false", ";", "}", "return", "telehash", ".", "mesh", "(", "args", ",", "function", "(", "err", ",", "mesh", ")", "{", "if", "(", "!", "mesh", ")", "return", "cbMesh", "(", "err", ")", ";", "if", "(", "linksFile", ")", "mesh", ".", "linked", "(", "function", "(", "json", ",", "str", ")", "{", "log", ".", "debug", "(", "'syncing links json'", ",", "linksFile", ",", "str", ".", "length", ")", ";", "fs", ".", "writeFileSync", "(", "linksFile", ",", "str", ")", ";", "}", ")", ";", "cbMesh", "(", "err", ",", "mesh", ")", ";", "}", ")", ";", "}" ]
set up some node-specific things after the mesh is created
[ "set", "up", "some", "node", "-", "specific", "things", "after", "the", "mesh", "is", "created" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/index.js#L23-L43
train
telehash/telehash-js
lib/util/handshake.js
handshake_collect
function handshake_collect(mesh, id, handshake, pipe, message) { handshake = handshake_bootstrap(handshake); if (!handshake) return false; var valid = handshake_validate(id,handshake, message, mesh); if (!valid) return false; // get all from cache w/ matching at, by type var types = handshake_types(handshake, id); // bail unless we have a link if(!types.link) { log.debug('handshakes w/ no link yet',id,types); return false; } // build a from json container var from = handshake_from(handshake, pipe, types.link) // if we already linked this hashname, just update w/ the new info if(mesh.index[from.hashname]) { log.debug('refresh link handshake') from.sync = false; // tell .link to not auto-sync! return mesh.link(from); } else { } log.debug('untrusted hashname',from); from.received = {packet:types.link._message, pipe:pipe} // optimization hints as link args from.handshake = types; // include all handshakes if(mesh.accept) mesh.accept(from); return false; }
javascript
function handshake_collect(mesh, id, handshake, pipe, message) { handshake = handshake_bootstrap(handshake); if (!handshake) return false; var valid = handshake_validate(id,handshake, message, mesh); if (!valid) return false; // get all from cache w/ matching at, by type var types = handshake_types(handshake, id); // bail unless we have a link if(!types.link) { log.debug('handshakes w/ no link yet',id,types); return false; } // build a from json container var from = handshake_from(handshake, pipe, types.link) // if we already linked this hashname, just update w/ the new info if(mesh.index[from.hashname]) { log.debug('refresh link handshake') from.sync = false; // tell .link to not auto-sync! return mesh.link(from); } else { } log.debug('untrusted hashname',from); from.received = {packet:types.link._message, pipe:pipe} // optimization hints as link args from.handshake = types; // include all handshakes if(mesh.accept) mesh.accept(from); return false; }
[ "function", "handshake_collect", "(", "mesh", ",", "id", ",", "handshake", ",", "pipe", ",", "message", ")", "{", "handshake", "=", "handshake_bootstrap", "(", "handshake", ")", ";", "if", "(", "!", "handshake", ")", "return", "false", ";", "var", "valid", "=", "handshake_validate", "(", "id", ",", "handshake", ",", "message", ",", "mesh", ")", ";", "if", "(", "!", "valid", ")", "return", "false", ";", "var", "types", "=", "handshake_types", "(", "handshake", ",", "id", ")", ";", "if", "(", "!", "types", ".", "link", ")", "{", "log", ".", "debug", "(", "'handshakes w/ no link yet'", ",", "id", ",", "types", ")", ";", "return", "false", ";", "}", "var", "from", "=", "handshake_from", "(", "handshake", ",", "pipe", ",", "types", ".", "link", ")", "if", "(", "mesh", ".", "index", "[", "from", ".", "hashname", "]", ")", "{", "log", ".", "debug", "(", "'refresh link handshake'", ")", "from", ".", "sync", "=", "false", ";", "return", "mesh", ".", "link", "(", "from", ")", ";", "}", "else", "{", "}", "log", ".", "debug", "(", "'untrusted hashname'", ",", "from", ")", ";", "from", ".", "received", "=", "{", "packet", ":", "types", ".", "link", ".", "_message", ",", "pipe", ":", "pipe", "}", "from", ".", "handshake", "=", "types", ";", "if", "(", "mesh", ".", "accept", ")", "mesh", ".", "accept", "(", "from", ")", ";", "return", "false", ";", "}" ]
collect incoming handshakes to accept them @param {object} id @param {handshake} handshake @param {pipe} pipe @param {Buffer} message
[ "collect", "incoming", "handshakes", "to", "accept", "them" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/lib/util/handshake.js#L26-L65
train
telehash/telehash-js
lib/util/receive.js
bouncer
function bouncer(err) { if(!err) return; var json = {err:err}; json.c = inner.json.c; log.debug('bouncing open',json); link.x.send({json:json}); }
javascript
function bouncer(err) { if(!err) return; var json = {err:err}; json.c = inner.json.c; log.debug('bouncing open',json); link.x.send({json:json}); }
[ "function", "bouncer", "(", "err", ")", "{", "if", "(", "!", "err", ")", "return", ";", "var", "json", "=", "{", "err", ":", "err", "}", ";", "json", ".", "c", "=", "inner", ".", "json", ".", "c", ";", "log", ".", "debug", "(", "'bouncing open'", ",", "json", ")", ";", "link", ".", "x", ".", "send", "(", "{", "json", ":", "json", "}", ")", ";", "}" ]
error utility for any open handler problems
[ "error", "utility", "for", "any", "open", "handler", "problems" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/lib/util/receive.js#L91-L98
train
telehash/telehash-js
ext/peer.js
peer_send
function peer_send(packet, link, cbSend) { var router = mesh.index[to]; if(!router) return cbSend('cannot peer to an unknown router: '+pipe.to); if(!router.x) return cbSend('cannot peer yet via this router: '+pipe.to); if(!link) return cbSend('requires link'); // no packet means try to send our keys if(!packet) { Object.keys(mesh.keys).forEach(function(csid){ if(link.csid && link.csid != csid) return; // if we know the csid, only send that key var json = {type:'peer',peer:link.hashname,c:router.x.cid()}; var body = lob.encode(hashname.intermediates(mesh.keys), hashname.key(csid, mesh.keys)); var attach = lob.encode({type:'link', csid:csid}, body); log.debug('sending peer key to',router.hashname,json,csid); router.x.send({json:json,body:attach}); }); return; } // if it's an encrypted channel packet, pass through direct to router if(packet.head.length == 0) return router.x.sending(packet); // otherwise we're always creating a new peer channel to carry the request var json = {type:'peer',peer:link.hashname,c:router.x.cid()}; var body = lob.encode(packet); log.debug('sending peer handshake to',router.hashname,json,body); router.x.send({json:json,body:body}); cbSend(); }
javascript
function peer_send(packet, link, cbSend) { var router = mesh.index[to]; if(!router) return cbSend('cannot peer to an unknown router: '+pipe.to); if(!router.x) return cbSend('cannot peer yet via this router: '+pipe.to); if(!link) return cbSend('requires link'); // no packet means try to send our keys if(!packet) { Object.keys(mesh.keys).forEach(function(csid){ if(link.csid && link.csid != csid) return; // if we know the csid, only send that key var json = {type:'peer',peer:link.hashname,c:router.x.cid()}; var body = lob.encode(hashname.intermediates(mesh.keys), hashname.key(csid, mesh.keys)); var attach = lob.encode({type:'link', csid:csid}, body); log.debug('sending peer key to',router.hashname,json,csid); router.x.send({json:json,body:attach}); }); return; } // if it's an encrypted channel packet, pass through direct to router if(packet.head.length == 0) return router.x.sending(packet); // otherwise we're always creating a new peer channel to carry the request var json = {type:'peer',peer:link.hashname,c:router.x.cid()}; var body = lob.encode(packet); log.debug('sending peer handshake to',router.hashname,json,body); router.x.send({json:json,body:body}); cbSend(); }
[ "function", "peer_send", "(", "packet", ",", "link", ",", "cbSend", ")", "{", "var", "router", "=", "mesh", ".", "index", "[", "to", "]", ";", "if", "(", "!", "router", ")", "return", "cbSend", "(", "'cannot peer to an unknown router: '", "+", "pipe", ".", "to", ")", ";", "if", "(", "!", "router", ".", "x", ")", "return", "cbSend", "(", "'cannot peer yet via this router: '", "+", "pipe", ".", "to", ")", ";", "if", "(", "!", "link", ")", "return", "cbSend", "(", "'requires link'", ")", ";", "if", "(", "!", "packet", ")", "{", "Object", ".", "keys", "(", "mesh", ".", "keys", ")", ".", "forEach", "(", "function", "(", "csid", ")", "{", "if", "(", "link", ".", "csid", "&&", "link", ".", "csid", "!=", "csid", ")", "return", ";", "var", "json", "=", "{", "type", ":", "'peer'", ",", "peer", ":", "link", ".", "hashname", ",", "c", ":", "router", ".", "x", ".", "cid", "(", ")", "}", ";", "var", "body", "=", "lob", ".", "encode", "(", "hashname", ".", "intermediates", "(", "mesh", ".", "keys", ")", ",", "hashname", ".", "key", "(", "csid", ",", "mesh", ".", "keys", ")", ")", ";", "var", "attach", "=", "lob", ".", "encode", "(", "{", "type", ":", "'link'", ",", "csid", ":", "csid", "}", ",", "body", ")", ";", "log", ".", "debug", "(", "'sending peer key to'", ",", "router", ".", "hashname", ",", "json", ",", "csid", ")", ";", "router", ".", "x", ".", "send", "(", "{", "json", ":", "json", ",", "body", ":", "attach", "}", ")", ";", "}", ")", ";", "return", ";", "}", "if", "(", "packet", ".", "head", ".", "length", "==", "0", ")", "return", "router", ".", "x", ".", "sending", "(", "packet", ")", ";", "var", "json", "=", "{", "type", ":", "'peer'", ",", "peer", ":", "link", ".", "hashname", ",", "c", ":", "router", ".", "x", ".", "cid", "(", ")", "}", ";", "var", "body", "=", "lob", ".", "encode", "(", "packet", ")", ";", "log", ".", "debug", "(", "'sending peer handshake to'", ",", "router", ".", "hashname", ",", "json", ",", "body", ")", ";", "router", ".", "x", ".", "send", "(", "{", "json", ":", "json", ",", "body", ":", "body", "}", ")", ";", "cbSend", "(", ")", ";", "}" ]
handle any peer delivery through the router
[ "handle", "any", "peer", "delivery", "through", "the", "router" ]
a9c9fa2a909382c0dc57c190e682198e21d1c96a
https://github.com/telehash/telehash-js/blob/a9c9fa2a909382c0dc57c190e682198e21d1c96a/ext/peer.js#L28-L58
train
christopherthielen/ui-router-extras
release/modular/ct-ui-router-extras.sticky.js
mapInactives
function mapInactives() { var mappedStates = {}; angular.forEach(inactiveStates, function (state, name) { var stickyAncestors = getStickyStateStack(state); for (var i = 0; i < stickyAncestors.length; i++) { var parent = stickyAncestors[i].parent; mappedStates[parent.name] = mappedStates[parent.name] || []; mappedStates[parent.name].push(state); } if (mappedStates['']) { // This is necessary to compute Transition.inactives when there are sticky states are children to root state. mappedStates['__inactives'] = mappedStates['']; // jshint ignore:line } }); return mappedStates; }
javascript
function mapInactives() { var mappedStates = {}; angular.forEach(inactiveStates, function (state, name) { var stickyAncestors = getStickyStateStack(state); for (var i = 0; i < stickyAncestors.length; i++) { var parent = stickyAncestors[i].parent; mappedStates[parent.name] = mappedStates[parent.name] || []; mappedStates[parent.name].push(state); } if (mappedStates['']) { // This is necessary to compute Transition.inactives when there are sticky states are children to root state. mappedStates['__inactives'] = mappedStates['']; // jshint ignore:line } }); return mappedStates; }
[ "function", "mapInactives", "(", ")", "{", "var", "mappedStates", "=", "{", "}", ";", "angular", ".", "forEach", "(", "inactiveStates", ",", "function", "(", "state", ",", "name", ")", "{", "var", "stickyAncestors", "=", "getStickyStateStack", "(", "state", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "stickyAncestors", ".", "length", ";", "i", "++", ")", "{", "var", "parent", "=", "stickyAncestors", "[", "i", "]", ".", "parent", ";", "mappedStates", "[", "parent", ".", "name", "]", "=", "mappedStates", "[", "parent", ".", "name", "]", "||", "[", "]", ";", "mappedStates", "[", "parent", ".", "name", "]", ".", "push", "(", "state", ")", ";", "}", "if", "(", "mappedStates", "[", "''", "]", ")", "{", "mappedStates", "[", "'__inactives'", "]", "=", "mappedStates", "[", "''", "]", ";", "}", "}", ")", ";", "return", "mappedStates", ";", "}" ]
Each inactive states is either a sticky state, or a child of a sticky state. This function finds the closest ancestor sticky state, then find that state's parent. Map all inactive states to their closest parent-to-sticky state.
[ "Each", "inactive", "states", "is", "either", "a", "sticky", "state", "or", "a", "child", "of", "a", "sticky", "state", ".", "This", "function", "finds", "the", "closest", "ancestor", "sticky", "state", "then", "find", "that", "state", "s", "parent", ".", "Map", "all", "inactive", "states", "to", "their", "closest", "parent", "-", "to", "-", "sticky", "state", "." ]
9ac225e8f137a4f5811595e817a39b58d1cd5625
https://github.com/christopherthielen/ui-router-extras/blob/9ac225e8f137a4f5811595e817a39b58d1cd5625/release/modular/ct-ui-router-extras.sticky.js#L47-L62
train
christopherthielen/ui-router-extras
release/modular/ct-ui-router-extras.sticky.js
getStickyStateStack
function getStickyStateStack(state) { var stack = []; if (!state) return stack; do { if (state.sticky) stack.push(state); state = state.parent; } while (state); stack.reverse(); return stack; }
javascript
function getStickyStateStack(state) { var stack = []; if (!state) return stack; do { if (state.sticky) stack.push(state); state = state.parent; } while (state); stack.reverse(); return stack; }
[ "function", "getStickyStateStack", "(", "state", ")", "{", "var", "stack", "=", "[", "]", ";", "if", "(", "!", "state", ")", "return", "stack", ";", "do", "{", "if", "(", "state", ".", "sticky", ")", "stack", ".", "push", "(", "state", ")", ";", "state", "=", "state", ".", "parent", ";", "}", "while", "(", "state", ")", ";", "stack", ".", "reverse", "(", ")", ";", "return", "stack", ";", "}" ]
Given a state, returns all ancestor states which are sticky. Walks up the view's state's ancestry tree and locates each ancestor state which is marked as sticky. Returns an array populated with only those ancestor sticky states.
[ "Given", "a", "state", "returns", "all", "ancestor", "states", "which", "are", "sticky", ".", "Walks", "up", "the", "view", "s", "state", "s", "ancestry", "tree", "and", "locates", "each", "ancestor", "state", "which", "is", "marked", "as", "sticky", ".", "Returns", "an", "array", "populated", "with", "only", "those", "ancestor", "sticky", "states", "." ]
9ac225e8f137a4f5811595e817a39b58d1cd5625
https://github.com/christopherthielen/ui-router-extras/blob/9ac225e8f137a4f5811595e817a39b58d1cd5625/release/modular/ct-ui-router-extras.sticky.js#L79-L88
train
christopherthielen/ui-router-extras
release/modular/ct-ui-router-extras.sticky.js
function (state) { // Keep locals around. inactiveStates[state.self.name] = state; // Notify states they are being Inactivated (i.e., a different // sticky state tree is now active). state.self.status = 'inactive'; if (state.self.onInactivate) $injector.invoke(state.self.onInactivate, state.self, state.locals.globals); }
javascript
function (state) { // Keep locals around. inactiveStates[state.self.name] = state; // Notify states they are being Inactivated (i.e., a different // sticky state tree is now active). state.self.status = 'inactive'; if (state.self.onInactivate) $injector.invoke(state.self.onInactivate, state.self, state.locals.globals); }
[ "function", "(", "state", ")", "{", "inactiveStates", "[", "state", ".", "self", ".", "name", "]", "=", "state", ";", "state", ".", "self", ".", "status", "=", "'inactive'", ";", "if", "(", "state", ".", "self", ".", "onInactivate", ")", "$injector", ".", "invoke", "(", "state", ".", "self", ".", "onInactivate", ",", "state", ".", "self", ",", "state", ".", "locals", ".", "globals", ")", ";", "}" ]
Adds a state to the inactivated sticky state registry.
[ "Adds", "a", "state", "to", "the", "inactivated", "sticky", "state", "registry", "." ]
9ac225e8f137a4f5811595e817a39b58d1cd5625
https://github.com/christopherthielen/ui-router-extras/blob/9ac225e8f137a4f5811595e817a39b58d1cd5625/release/modular/ct-ui-router-extras.sticky.js#L302-L310
train
christopherthielen/ui-router-extras
release/modular/ct-ui-router-extras.sticky.js
function (exiting, exitQueue, onExit) { var exitingNames = {}; angular.forEach(exitQueue, function (state) { exitingNames[state.self.name] = true; }); angular.forEach(inactiveStates, function (inactiveExiting, name) { // TODO: Might need to run the inactivations in the proper depth-first order? if (!exitingNames[name] && inactiveExiting.includes[exiting.name]) { if (DEBUG) $log.debug("Exiting " + name + " because it's a substate of " + exiting.name + " and wasn't found in ", exitingNames); if (inactiveExiting.self.onExit) $injector.invoke(inactiveExiting.self.onExit, inactiveExiting.self, inactiveExiting.locals.globals); angular.forEach(inactiveExiting.locals, function(localval, key) { delete inactivePseudoState.locals[key]; }); inactiveExiting.locals = null; inactiveExiting.self.status = 'exited'; delete inactiveStates[name]; } }); if (onExit) $injector.invoke(onExit, exiting.self, exiting.locals.globals); exiting.locals = null; exiting.self.status = 'exited'; delete inactiveStates[exiting.self.name]; }
javascript
function (exiting, exitQueue, onExit) { var exitingNames = {}; angular.forEach(exitQueue, function (state) { exitingNames[state.self.name] = true; }); angular.forEach(inactiveStates, function (inactiveExiting, name) { // TODO: Might need to run the inactivations in the proper depth-first order? if (!exitingNames[name] && inactiveExiting.includes[exiting.name]) { if (DEBUG) $log.debug("Exiting " + name + " because it's a substate of " + exiting.name + " and wasn't found in ", exitingNames); if (inactiveExiting.self.onExit) $injector.invoke(inactiveExiting.self.onExit, inactiveExiting.self, inactiveExiting.locals.globals); angular.forEach(inactiveExiting.locals, function(localval, key) { delete inactivePseudoState.locals[key]; }); inactiveExiting.locals = null; inactiveExiting.self.status = 'exited'; delete inactiveStates[name]; } }); if (onExit) $injector.invoke(onExit, exiting.self, exiting.locals.globals); exiting.locals = null; exiting.self.status = 'exited'; delete inactiveStates[exiting.self.name]; }
[ "function", "(", "exiting", ",", "exitQueue", ",", "onExit", ")", "{", "var", "exitingNames", "=", "{", "}", ";", "angular", ".", "forEach", "(", "exitQueue", ",", "function", "(", "state", ")", "{", "exitingNames", "[", "state", ".", "self", ".", "name", "]", "=", "true", ";", "}", ")", ";", "angular", ".", "forEach", "(", "inactiveStates", ",", "function", "(", "inactiveExiting", ",", "name", ")", "{", "if", "(", "!", "exitingNames", "[", "name", "]", "&&", "inactiveExiting", ".", "includes", "[", "exiting", ".", "name", "]", ")", "{", "if", "(", "DEBUG", ")", "$log", ".", "debug", "(", "\"Exiting \"", "+", "name", "+", "\" because it's a substate of \"", "+", "exiting", ".", "name", "+", "\" and wasn't found in \"", ",", "exitingNames", ")", ";", "if", "(", "inactiveExiting", ".", "self", ".", "onExit", ")", "$injector", ".", "invoke", "(", "inactiveExiting", ".", "self", ".", "onExit", ",", "inactiveExiting", ".", "self", ",", "inactiveExiting", ".", "locals", ".", "globals", ")", ";", "angular", ".", "forEach", "(", "inactiveExiting", ".", "locals", ",", "function", "(", "localval", ",", "key", ")", "{", "delete", "inactivePseudoState", ".", "locals", "[", "key", "]", ";", "}", ")", ";", "inactiveExiting", ".", "locals", "=", "null", ";", "inactiveExiting", ".", "self", ".", "status", "=", "'exited'", ";", "delete", "inactiveStates", "[", "name", "]", ";", "}", "}", ")", ";", "if", "(", "onExit", ")", "$injector", ".", "invoke", "(", "onExit", ",", "exiting", ".", "self", ",", "exiting", ".", "locals", ".", "globals", ")", ";", "exiting", ".", "locals", "=", "null", ";", "exiting", ".", "self", ".", "status", "=", "'exited'", ";", "delete", "inactiveStates", "[", "exiting", ".", "self", ".", "name", "]", ";", "}" ]
Exits all inactivated descendant substates when the ancestor state is exited. When transitionTo is exiting a state, this function is called with the state being exited. It checks the registry of inactivated states for descendants of the exited state and also exits those descendants. It then removes the locals and de-registers the state from the inactivated registry.
[ "Exits", "all", "inactivated", "descendant", "substates", "when", "the", "ancestor", "state", "is", "exited", ".", "When", "transitionTo", "is", "exiting", "a", "state", "this", "function", "is", "called", "with", "the", "state", "being", "exited", ".", "It", "checks", "the", "registry", "of", "inactivated", "states", "for", "descendants", "of", "the", "exited", "state", "and", "also", "exits", "those", "descendants", ".", "It", "then", "removes", "the", "locals", "and", "de", "-", "registers", "the", "state", "from", "the", "inactivated", "registry", "." ]
9ac225e8f137a4f5811595e817a39b58d1cd5625
https://github.com/christopherthielen/ui-router-extras/blob/9ac225e8f137a4f5811595e817a39b58d1cd5625/release/modular/ct-ui-router-extras.sticky.js#L327-L353
train
christopherthielen/ui-router-extras
release/modular/ct-ui-router-extras.sticky.js
function (entering, params, onEnter, updateParams) { var inactivatedState = getInactivatedState(entering); if (inactivatedState && (updateParams || !getInactivatedState(entering, params))) { var savedLocals = entering.locals; this.stateExiting(inactivatedState); entering.locals = savedLocals; } entering.self.status = 'entered'; if (onEnter) $injector.invoke(onEnter, entering.self, entering.locals.globals); }
javascript
function (entering, params, onEnter, updateParams) { var inactivatedState = getInactivatedState(entering); if (inactivatedState && (updateParams || !getInactivatedState(entering, params))) { var savedLocals = entering.locals; this.stateExiting(inactivatedState); entering.locals = savedLocals; } entering.self.status = 'entered'; if (onEnter) $injector.invoke(onEnter, entering.self, entering.locals.globals); }
[ "function", "(", "entering", ",", "params", ",", "onEnter", ",", "updateParams", ")", "{", "var", "inactivatedState", "=", "getInactivatedState", "(", "entering", ")", ";", "if", "(", "inactivatedState", "&&", "(", "updateParams", "||", "!", "getInactivatedState", "(", "entering", ",", "params", ")", ")", ")", "{", "var", "savedLocals", "=", "entering", ".", "locals", ";", "this", ".", "stateExiting", "(", "inactivatedState", ")", ";", "entering", ".", "locals", "=", "savedLocals", ";", "}", "entering", ".", "self", ".", "status", "=", "'entered'", ";", "if", "(", "onEnter", ")", "$injector", ".", "invoke", "(", "onEnter", ",", "entering", ".", "self", ",", "entering", ".", "locals", ".", "globals", ")", ";", "}" ]
Removes a previously inactivated state from the inactive sticky state registry
[ "Removes", "a", "previously", "inactivated", "state", "from", "the", "inactive", "sticky", "state", "registry" ]
9ac225e8f137a4f5811595e817a39b58d1cd5625
https://github.com/christopherthielen/ui-router-extras/blob/9ac225e8f137a4f5811595e817a39b58d1cd5625/release/modular/ct-ui-router-extras.sticky.js#L356-L367
train
christopherthielen/ui-router-extras
release/modular/ct-ui-router-extras.sticky.js
SurrogateState
function SurrogateState(type) { return { resolve: { }, locals: { globals: root && root.locals && root.locals.globals }, views: { }, self: { }, params: { }, ownParams: ( versionHeuristics.hasParamSet ? { $$equals: function() { return true; } } : []), surrogateType: type }; }
javascript
function SurrogateState(type) { return { resolve: { }, locals: { globals: root && root.locals && root.locals.globals }, views: { }, self: { }, params: { }, ownParams: ( versionHeuristics.hasParamSet ? { $$equals: function() { return true; } } : []), surrogateType: type }; }
[ "function", "SurrogateState", "(", "type", ")", "{", "return", "{", "resolve", ":", "{", "}", ",", "locals", ":", "{", "globals", ":", "root", "&&", "root", ".", "locals", "&&", "root", ".", "locals", ".", "globals", "}", ",", "views", ":", "{", "}", ",", "self", ":", "{", "}", ",", "params", ":", "{", "}", ",", "ownParams", ":", "(", "versionHeuristics", ".", "hasParamSet", "?", "{", "$$equals", ":", "function", "(", ")", "{", "return", "true", ";", "}", "}", ":", "[", "]", ")", ",", "surrogateType", ":", "type", "}", ";", "}" ]
Creates a blank surrogate state
[ "Creates", "a", "blank", "surrogate", "state" ]
9ac225e8f137a4f5811595e817a39b58d1cd5625
https://github.com/christopherthielen/ui-router-extras/blob/9ac225e8f137a4f5811595e817a39b58d1cd5625/release/modular/ct-ui-router-extras.sticky.js#L460-L472
train
christopherthielen/ui-router-extras
release/modular/ct-ui-router-extras.core.js
protoKeys
function protoKeys(object, ignoreKeys) { var result = []; for (var key in object) { if (!ignoreKeys || ignoreKeys.indexOf(key) === -1) result.push(key); } return result; }
javascript
function protoKeys(object, ignoreKeys) { var result = []; for (var key in object) { if (!ignoreKeys || ignoreKeys.indexOf(key) === -1) result.push(key); } return result; }
[ "function", "protoKeys", "(", "object", ",", "ignoreKeys", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "key", "in", "object", ")", "{", "if", "(", "!", "ignoreKeys", "||", "ignoreKeys", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "result", ".", "push", "(", "key", ")", ";", "}", "return", "result", ";", "}" ]
like objectKeys, but includes keys from prototype chain. @param object the object whose prototypal keys will be returned @param ignoreKeys an array of keys to ignore Duplicates code in UI-Router common.js
[ "like", "objectKeys", "but", "includes", "keys", "from", "prototype", "chain", "." ]
9ac225e8f137a4f5811595e817a39b58d1cd5625
https://github.com/christopherthielen/ui-router-extras/blob/9ac225e8f137a4f5811595e817a39b58d1cd5625/release/modular/ct-ui-router-extras.core.js#L103-L110
train
stealjs/steal-cordova
lib/steal-cordova.js
function(opts){ var buildPath = (opts && opts.path) || this.options.path; assert(!!buildPath, "Path needs to be provided"); var p = path.resolve(buildPath); var stealCordova = this; return new Promise(function(resolve, reject){ fse.exists(p, function(doesExist){ if(doesExist) { resolve(); } else { stealCordova.init(opts) .then(function() { resolve(); }) .catch(reject); } }); }); }
javascript
function(opts){ var buildPath = (opts && opts.path) || this.options.path; assert(!!buildPath, "Path needs to be provided"); var p = path.resolve(buildPath); var stealCordova = this; return new Promise(function(resolve, reject){ fse.exists(p, function(doesExist){ if(doesExist) { resolve(); } else { stealCordova.init(opts) .then(function() { resolve(); }) .catch(reject); } }); }); }
[ "function", "(", "opts", ")", "{", "var", "buildPath", "=", "(", "opts", "&&", "opts", ".", "path", ")", "||", "this", ".", "options", ".", "path", ";", "assert", "(", "!", "!", "buildPath", ",", "\"Path needs to be provided\"", ")", ";", "var", "p", "=", "path", ".", "resolve", "(", "buildPath", ")", ";", "var", "stealCordova", "=", "this", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fse", ".", "exists", "(", "p", ",", "function", "(", "doesExist", ")", "{", "if", "(", "doesExist", ")", "{", "resolve", "(", ")", ";", "}", "else", "{", "stealCordova", ".", "init", "(", "opts", ")", ".", "then", "(", "function", "(", ")", "{", "resolve", "(", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Only initialize if it hasn't already been.
[ "Only", "initialize", "if", "it", "hasn", "t", "already", "been", "." ]
f4e704eead4133afa0585ea2ecad439d089086ee
https://github.com/stealjs/steal-cordova/blob/f4e704eead4133afa0585ea2ecad439d089086ee/lib/steal-cordova.js#L38-L58
train
synacor/preact-context-provider
src/index.js
assign
function assign(obj, props) { for (let i in props) { if (props.hasOwnProperty(i)) { obj[i] = props[i]; } } return obj; }
javascript
function assign(obj, props) { for (let i in props) { if (props.hasOwnProperty(i)) { obj[i] = props[i]; } } return obj; }
[ "function", "assign", "(", "obj", ",", "props", ")", "{", "for", "(", "let", "i", "in", "props", ")", "{", "if", "(", "props", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "obj", "[", "i", "]", "=", "props", "[", "i", "]", ";", "}", "}", "return", "obj", ";", "}" ]
A simpler Object.assign @private
[ "A", "simpler", "Object", ".", "assign" ]
fb0677932c7126f5095ce5eb19c96136ac131f9f
https://github.com/synacor/preact-context-provider/blob/fb0677932c7126f5095ce5eb19c96136ac131f9f/src/index.js#L50-L57
train
synacor/preact-context-provider
src/index.js
deepAssign
function deepAssign(target, source) { //if they aren't both objects, use target if it is defined (null/0/false/etc. are OK), otherwise use source if (!(target && source && typeof target==='object' && typeof source==='object')) { return typeof target !== 'undefined' ? target : source; } let out = assign({}, target); for (let i in source) { if (source.hasOwnProperty(i)) { out[i] = deepAssign(target[i], source[i]); } } return out; }
javascript
function deepAssign(target, source) { //if they aren't both objects, use target if it is defined (null/0/false/etc. are OK), otherwise use source if (!(target && source && typeof target==='object' && typeof source==='object')) { return typeof target !== 'undefined' ? target : source; } let out = assign({}, target); for (let i in source) { if (source.hasOwnProperty(i)) { out[i] = deepAssign(target[i], source[i]); } } return out; }
[ "function", "deepAssign", "(", "target", ",", "source", ")", "{", "if", "(", "!", "(", "target", "&&", "source", "&&", "typeof", "target", "===", "'object'", "&&", "typeof", "source", "===", "'object'", ")", ")", "{", "return", "typeof", "target", "!==", "'undefined'", "?", "target", ":", "source", ";", "}", "let", "out", "=", "assign", "(", "{", "}", ",", "target", ")", ";", "for", "(", "let", "i", "in", "source", ")", "{", "if", "(", "source", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "out", "[", "i", "]", "=", "deepAssign", "(", "target", "[", "i", "]", ",", "source", "[", "i", "]", ")", ";", "}", "}", "return", "out", ";", "}" ]
Recursively copy keys from `source` to `target`, skipping truthy values already in `target` so parent values can block child values @private
[ "Recursively", "copy", "keys", "from", "source", "to", "target", "skipping", "truthy", "values", "already", "in", "target", "so", "parent", "values", "can", "block", "child", "values" ]
fb0677932c7126f5095ce5eb19c96136ac131f9f
https://github.com/synacor/preact-context-provider/blob/fb0677932c7126f5095ce5eb19c96136ac131f9f/src/index.js#L63-L76
train
jonashartmann/webcam-directive
app/scripts/webcam.js
onSuccess
function onSuccess(stream) { videoStream = stream; if (window.hasModernUserMedia) { videoElem.srcObject = stream; } else if (navigator.mozGetUserMedia) { // Firefox supports a src object videoElem.mozSrcObject = stream; } else { var vendorURL = window.URL || window.webkitURL; videoElem.src = vendorURL.createObjectURL(stream); } /* Start playing the video to show the stream from the webcam */ videoElem.play(); $scope.config.video = videoElem; /* Call custom callback */ if ($scope.onStream) { $scope.onStream({stream: stream}); } }
javascript
function onSuccess(stream) { videoStream = stream; if (window.hasModernUserMedia) { videoElem.srcObject = stream; } else if (navigator.mozGetUserMedia) { // Firefox supports a src object videoElem.mozSrcObject = stream; } else { var vendorURL = window.URL || window.webkitURL; videoElem.src = vendorURL.createObjectURL(stream); } /* Start playing the video to show the stream from the webcam */ videoElem.play(); $scope.config.video = videoElem; /* Call custom callback */ if ($scope.onStream) { $scope.onStream({stream: stream}); } }
[ "function", "onSuccess", "(", "stream", ")", "{", "videoStream", "=", "stream", ";", "if", "(", "window", ".", "hasModernUserMedia", ")", "{", "videoElem", ".", "srcObject", "=", "stream", ";", "}", "else", "if", "(", "navigator", ".", "mozGetUserMedia", ")", "{", "videoElem", ".", "mozSrcObject", "=", "stream", ";", "}", "else", "{", "var", "vendorURL", "=", "window", ".", "URL", "||", "window", ".", "webkitURL", ";", "videoElem", ".", "src", "=", "vendorURL", ".", "createObjectURL", "(", "stream", ")", ";", "}", "videoElem", ".", "play", "(", ")", ";", "$scope", ".", "config", ".", "video", "=", "videoElem", ";", "if", "(", "$scope", ".", "onStream", ")", "{", "$scope", ".", "onStream", "(", "{", "stream", ":", "stream", "}", ")", ";", "}", "}" ]
called when camera stream is loaded
[ "called", "when", "camera", "stream", "is", "loaded" ]
46988cdd0ce74b8bd624984c22c591a2388ef00e
https://github.com/jonashartmann/webcam-directive/blob/46988cdd0ce74b8bd624984c22c591a2388ef00e/app/scripts/webcam.js#L87-L108
train
jonashartmann/webcam-directive
app/scripts/webcam.js
onFailure
function onFailure(err) { _removeDOMElement(placeholder); if (console && console.debug) { console.debug('The following error occured: ', err); } /* Call custom callback */ if ($scope.onError) { $scope.onError({err:err}); } return; }
javascript
function onFailure(err) { _removeDOMElement(placeholder); if (console && console.debug) { console.debug('The following error occured: ', err); } /* Call custom callback */ if ($scope.onError) { $scope.onError({err:err}); } return; }
[ "function", "onFailure", "(", "err", ")", "{", "_removeDOMElement", "(", "placeholder", ")", ";", "if", "(", "console", "&&", "console", ".", "debug", ")", "{", "console", ".", "debug", "(", "'The following error occured: '", ",", "err", ")", ";", "}", "if", "(", "$scope", ".", "onError", ")", "{", "$scope", ".", "onError", "(", "{", "err", ":", "err", "}", ")", ";", "}", "return", ";", "}" ]
called when any error happens
[ "called", "when", "any", "error", "happens" ]
46988cdd0ce74b8bd624984c22c591a2388ef00e
https://github.com/jonashartmann/webcam-directive/blob/46988cdd0ce74b8bd624984c22c591a2388ef00e/app/scripts/webcam.js#L111-L123
train
compact/angular-bootstrap-lightbox
dist/angular-bootstrap-lightbox.js
function (dimensions, fullScreenMode) { var w = dimensions.width; var h = dimensions.height; var minW = dimensions.minWidth; var minH = dimensions.minHeight; var maxW = dimensions.maxWidth; var maxH = dimensions.maxHeight; var displayW = w; var displayH = h; if (!fullScreenMode) { // resize the image if it is too small if (w < minW && h < minH) { // the image is both too thin and short, so compare the aspect ratios to // determine whether to min the width or height if (w / h > maxW / maxH) { displayH = minH; displayW = Math.round(w * minH / h); } else { displayW = minW; displayH = Math.round(h * minW / w); } } else if (w < minW) { // the image is too thin displayW = minW; displayH = Math.round(h * minW / w); } else if (h < minH) { // the image is too short displayH = minH; displayW = Math.round(w * minH / h); } // resize the image if it is too large if (w > maxW && h > maxH) { // the image is both too tall and wide, so compare the aspect ratios // to determine whether to max the width or height if (w / h > maxW / maxH) { displayW = maxW; displayH = Math.round(h * maxW / w); } else { displayH = maxH; displayW = Math.round(w * maxH / h); } } else if (w > maxW) { // the image is too wide displayW = maxW; displayH = Math.round(h * maxW / w); } else if (h > maxH) { // the image is too tall displayH = maxH; displayW = Math.round(w * maxH / h); } } else { // full screen mode var ratio = Math.min(maxW / w, maxH / h); var zoomedW = Math.round(w * ratio); var zoomedH = Math.round(h * ratio); displayW = Math.max(minW, zoomedW); displayH = Math.max(minH, zoomedH); } return { 'width': displayW || 0, 'height': displayH || 0 // NaN is possible when dimensions.width is 0 }; }
javascript
function (dimensions, fullScreenMode) { var w = dimensions.width; var h = dimensions.height; var minW = dimensions.minWidth; var minH = dimensions.minHeight; var maxW = dimensions.maxWidth; var maxH = dimensions.maxHeight; var displayW = w; var displayH = h; if (!fullScreenMode) { // resize the image if it is too small if (w < minW && h < minH) { // the image is both too thin and short, so compare the aspect ratios to // determine whether to min the width or height if (w / h > maxW / maxH) { displayH = minH; displayW = Math.round(w * minH / h); } else { displayW = minW; displayH = Math.round(h * minW / w); } } else if (w < minW) { // the image is too thin displayW = minW; displayH = Math.round(h * minW / w); } else if (h < minH) { // the image is too short displayH = minH; displayW = Math.round(w * minH / h); } // resize the image if it is too large if (w > maxW && h > maxH) { // the image is both too tall and wide, so compare the aspect ratios // to determine whether to max the width or height if (w / h > maxW / maxH) { displayW = maxW; displayH = Math.round(h * maxW / w); } else { displayH = maxH; displayW = Math.round(w * maxH / h); } } else if (w > maxW) { // the image is too wide displayW = maxW; displayH = Math.round(h * maxW / w); } else if (h > maxH) { // the image is too tall displayH = maxH; displayW = Math.round(w * maxH / h); } } else { // full screen mode var ratio = Math.min(maxW / w, maxH / h); var zoomedW = Math.round(w * ratio); var zoomedH = Math.round(h * ratio); displayW = Math.max(minW, zoomedW); displayH = Math.max(minH, zoomedH); } return { 'width': displayW || 0, 'height': displayH || 0 // NaN is possible when dimensions.width is 0 }; }
[ "function", "(", "dimensions", ",", "fullScreenMode", ")", "{", "var", "w", "=", "dimensions", ".", "width", ";", "var", "h", "=", "dimensions", ".", "height", ";", "var", "minW", "=", "dimensions", ".", "minWidth", ";", "var", "minH", "=", "dimensions", ".", "minHeight", ";", "var", "maxW", "=", "dimensions", ".", "maxWidth", ";", "var", "maxH", "=", "dimensions", ".", "maxHeight", ";", "var", "displayW", "=", "w", ";", "var", "displayH", "=", "h", ";", "if", "(", "!", "fullScreenMode", ")", "{", "if", "(", "w", "<", "minW", "&&", "h", "<", "minH", ")", "{", "if", "(", "w", "/", "h", ">", "maxW", "/", "maxH", ")", "{", "displayH", "=", "minH", ";", "displayW", "=", "Math", ".", "round", "(", "w", "*", "minH", "/", "h", ")", ";", "}", "else", "{", "displayW", "=", "minW", ";", "displayH", "=", "Math", ".", "round", "(", "h", "*", "minW", "/", "w", ")", ";", "}", "}", "else", "if", "(", "w", "<", "minW", ")", "{", "displayW", "=", "minW", ";", "displayH", "=", "Math", ".", "round", "(", "h", "*", "minW", "/", "w", ")", ";", "}", "else", "if", "(", "h", "<", "minH", ")", "{", "displayH", "=", "minH", ";", "displayW", "=", "Math", ".", "round", "(", "w", "*", "minH", "/", "h", ")", ";", "}", "if", "(", "w", ">", "maxW", "&&", "h", ">", "maxH", ")", "{", "if", "(", "w", "/", "h", ">", "maxW", "/", "maxH", ")", "{", "displayW", "=", "maxW", ";", "displayH", "=", "Math", ".", "round", "(", "h", "*", "maxW", "/", "w", ")", ";", "}", "else", "{", "displayH", "=", "maxH", ";", "displayW", "=", "Math", ".", "round", "(", "w", "*", "maxH", "/", "h", ")", ";", "}", "}", "else", "if", "(", "w", ">", "maxW", ")", "{", "displayW", "=", "maxW", ";", "displayH", "=", "Math", ".", "round", "(", "h", "*", "maxW", "/", "w", ")", ";", "}", "else", "if", "(", "h", ">", "maxH", ")", "{", "displayH", "=", "maxH", ";", "displayW", "=", "Math", ".", "round", "(", "w", "*", "maxH", "/", "h", ")", ";", "}", "}", "else", "{", "var", "ratio", "=", "Math", ".", "min", "(", "maxW", "/", "w", ",", "maxH", "/", "h", ")", ";", "var", "zoomedW", "=", "Math", ".", "round", "(", "w", "*", "ratio", ")", ";", "var", "zoomedH", "=", "Math", ".", "round", "(", "h", "*", "ratio", ")", ";", "displayW", "=", "Math", ".", "max", "(", "minW", ",", "zoomedW", ")", ";", "displayH", "=", "Math", ".", "max", "(", "minH", ",", "zoomedH", ")", ";", "}", "return", "{", "'width'", ":", "displayW", "||", "0", ",", "'height'", ":", "displayH", "||", "0", "}", ";", "}" ]
Calculate the dimensions to display the image. The max dimensions override the min dimensions if they conflict.
[ "Calculate", "the", "dimensions", "to", "display", "the", "image", ".", "The", "max", "dimensions", "override", "the", "min", "dimensions", "if", "they", "conflict", "." ]
1d194e2c79d9d2667ef2ff5ba299f60d7d63d0eb
https://github.com/compact/angular-bootstrap-lightbox/blob/1d194e2c79d9d2667ef2ff5ba299f60d7d63d0eb/dist/angular-bootstrap-lightbox.js#L534-L602
train
compact/angular-bootstrap-lightbox
dist/angular-bootstrap-lightbox.js
function () { // get the window dimensions var windowWidth = $window.innerWidth; var windowHeight = $window.innerHeight; // calculate the max/min dimensions for the image var imageDimensionLimits = Lightbox.calculateImageDimensionLimits({ 'windowWidth': windowWidth, 'windowHeight': windowHeight, 'imageWidth': imageWidth, 'imageHeight': imageHeight }); // calculate the dimensions to display the image var imageDisplayDimensions = calculateImageDisplayDimensions( angular.extend({ 'width': imageWidth, 'height': imageHeight, 'minWidth': 1, 'minHeight': 1, 'maxWidth': 3000, 'maxHeight': 3000, }, imageDimensionLimits), Lightbox.fullScreenMode ); // calculate the dimensions of the modal container var modalDimensions = Lightbox.calculateModalDimensions({ 'windowWidth': windowWidth, 'windowHeight': windowHeight, 'imageDisplayWidth': imageDisplayDimensions.width, 'imageDisplayHeight': imageDisplayDimensions.height }); // resize the image element.css({ 'width': imageDisplayDimensions.width + 'px', 'height': imageDisplayDimensions.height + 'px' }); // setting the height on .modal-dialog does not expand the div with the // background, which is .modal-content angular.element( document.querySelector('.lightbox-modal .modal-dialog') ).css({ 'width': formatDimension(modalDimensions.width) }); // .modal-content has no width specified; if we set the width on // .modal-content and not on .modal-dialog, .modal-dialog retains its // default width of 600px and that places .modal-content off center angular.element( document.querySelector('.lightbox-modal .modal-content') ).css({ 'height': formatDimension(modalDimensions.height) }); }
javascript
function () { // get the window dimensions var windowWidth = $window.innerWidth; var windowHeight = $window.innerHeight; // calculate the max/min dimensions for the image var imageDimensionLimits = Lightbox.calculateImageDimensionLimits({ 'windowWidth': windowWidth, 'windowHeight': windowHeight, 'imageWidth': imageWidth, 'imageHeight': imageHeight }); // calculate the dimensions to display the image var imageDisplayDimensions = calculateImageDisplayDimensions( angular.extend({ 'width': imageWidth, 'height': imageHeight, 'minWidth': 1, 'minHeight': 1, 'maxWidth': 3000, 'maxHeight': 3000, }, imageDimensionLimits), Lightbox.fullScreenMode ); // calculate the dimensions of the modal container var modalDimensions = Lightbox.calculateModalDimensions({ 'windowWidth': windowWidth, 'windowHeight': windowHeight, 'imageDisplayWidth': imageDisplayDimensions.width, 'imageDisplayHeight': imageDisplayDimensions.height }); // resize the image element.css({ 'width': imageDisplayDimensions.width + 'px', 'height': imageDisplayDimensions.height + 'px' }); // setting the height on .modal-dialog does not expand the div with the // background, which is .modal-content angular.element( document.querySelector('.lightbox-modal .modal-dialog') ).css({ 'width': formatDimension(modalDimensions.width) }); // .modal-content has no width specified; if we set the width on // .modal-content and not on .modal-dialog, .modal-dialog retains its // default width of 600px and that places .modal-content off center angular.element( document.querySelector('.lightbox-modal .modal-content') ).css({ 'height': formatDimension(modalDimensions.height) }); }
[ "function", "(", ")", "{", "var", "windowWidth", "=", "$window", ".", "innerWidth", ";", "var", "windowHeight", "=", "$window", ".", "innerHeight", ";", "var", "imageDimensionLimits", "=", "Lightbox", ".", "calculateImageDimensionLimits", "(", "{", "'windowWidth'", ":", "windowWidth", ",", "'windowHeight'", ":", "windowHeight", ",", "'imageWidth'", ":", "imageWidth", ",", "'imageHeight'", ":", "imageHeight", "}", ")", ";", "var", "imageDisplayDimensions", "=", "calculateImageDisplayDimensions", "(", "angular", ".", "extend", "(", "{", "'width'", ":", "imageWidth", ",", "'height'", ":", "imageHeight", ",", "'minWidth'", ":", "1", ",", "'minHeight'", ":", "1", ",", "'maxWidth'", ":", "3000", ",", "'maxHeight'", ":", "3000", ",", "}", ",", "imageDimensionLimits", ")", ",", "Lightbox", ".", "fullScreenMode", ")", ";", "var", "modalDimensions", "=", "Lightbox", ".", "calculateModalDimensions", "(", "{", "'windowWidth'", ":", "windowWidth", ",", "'windowHeight'", ":", "windowHeight", ",", "'imageDisplayWidth'", ":", "imageDisplayDimensions", ".", "width", ",", "'imageDisplayHeight'", ":", "imageDisplayDimensions", ".", "height", "}", ")", ";", "element", ".", "css", "(", "{", "'width'", ":", "imageDisplayDimensions", ".", "width", "+", "'px'", ",", "'height'", ":", "imageDisplayDimensions", ".", "height", "+", "'px'", "}", ")", ";", "angular", ".", "element", "(", "document", ".", "querySelector", "(", "'.lightbox-modal .modal-dialog'", ")", ")", ".", "css", "(", "{", "'width'", ":", "formatDimension", "(", "modalDimensions", ".", "width", ")", "}", ")", ";", "angular", ".", "element", "(", "document", ".", "querySelector", "(", "'.lightbox-modal .modal-content'", ")", ")", ".", "css", "(", "{", "'height'", ":", "formatDimension", "(", "modalDimensions", ".", "height", ")", "}", ")", ";", "}" ]
resize the img element and the containing modal
[ "resize", "the", "img", "element", "and", "the", "containing", "modal" ]
1d194e2c79d9d2667ef2ff5ba299f60d7d63d0eb
https://github.com/compact/angular-bootstrap-lightbox/blob/1d194e2c79d9d2667ef2ff5ba299f60d7d63d0eb/dist/angular-bootstrap-lightbox.js#L616-L672
train
box/viewer.js
src/js/components/layout-vertical.js
function () { var state = this.state, currentPage = state.pages[state.currentPage - 1], rowIndex = currentPage.rowIndex, nextRow = state.rows[rowIndex + 1]; return nextRow && nextRow[0] + 1 || state.currentPage; }
javascript
function () { var state = this.state, currentPage = state.pages[state.currentPage - 1], rowIndex = currentPage.rowIndex, nextRow = state.rows[rowIndex + 1]; return nextRow && nextRow[0] + 1 || state.currentPage; }
[ "function", "(", ")", "{", "var", "state", "=", "this", ".", "state", ",", "currentPage", "=", "state", ".", "pages", "[", "state", ".", "currentPage", "-", "1", "]", ",", "rowIndex", "=", "currentPage", ".", "rowIndex", ",", "nextRow", "=", "state", ".", "rows", "[", "rowIndex", "+", "1", "]", ";", "return", "nextRow", "&&", "nextRow", "[", "0", "]", "+", "1", "||", "state", ".", "currentPage", ";", "}" ]
Calculates the next page @returns {int} The next page number
[ "Calculates", "the", "next", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/src/js/components/layout-vertical.js#L80-L86
train
box/viewer.js
src/js/components/layout-vertical.js
function () { var state = this.state, currentPage = state.pages[state.currentPage - 1], rowIndex = currentPage.rowIndex, prevRow = state.rows[rowIndex - 1]; return prevRow && prevRow[0] + 1 || state.currentPage; }
javascript
function () { var state = this.state, currentPage = state.pages[state.currentPage - 1], rowIndex = currentPage.rowIndex, prevRow = state.rows[rowIndex - 1]; return prevRow && prevRow[0] + 1 || state.currentPage; }
[ "function", "(", ")", "{", "var", "state", "=", "this", ".", "state", ",", "currentPage", "=", "state", ".", "pages", "[", "state", ".", "currentPage", "-", "1", "]", ",", "rowIndex", "=", "currentPage", ".", "rowIndex", ",", "prevRow", "=", "state", ".", "rows", "[", "rowIndex", "-", "1", "]", ";", "return", "prevRow", "&&", "prevRow", "[", "0", "]", "+", "1", "||", "state", ".", "currentPage", ";", "}" ]
Calculates the previous page @returns {int} The previous page number
[ "Calculates", "the", "previous", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/src/js/components/layout-vertical.js#L92-L98
train
box/viewer.js
dist/crocodoc.viewer.js
findCircularDependencies
function findCircularDependencies(componentName, dependencies, path) { var i; path = path || componentName; for (i = 0; i < dependencies.length; ++i) { if (componentName === dependencies[i]) { throw new Error('Circular dependency detected: ' + path + '->' + dependencies[i]); } else if (components[dependencies[i]]) { findCircularDependencies(componentName, components[dependencies[i]].mixins, path + '->' + dependencies[i]); } } }
javascript
function findCircularDependencies(componentName, dependencies, path) { var i; path = path || componentName; for (i = 0; i < dependencies.length; ++i) { if (componentName === dependencies[i]) { throw new Error('Circular dependency detected: ' + path + '->' + dependencies[i]); } else if (components[dependencies[i]]) { findCircularDependencies(componentName, components[dependencies[i]].mixins, path + '->' + dependencies[i]); } } }
[ "function", "findCircularDependencies", "(", "componentName", ",", "dependencies", ",", "path", ")", "{", "var", "i", ";", "path", "=", "path", "||", "componentName", ";", "for", "(", "i", "=", "0", ";", "i", "<", "dependencies", ".", "length", ";", "++", "i", ")", "{", "if", "(", "componentName", "===", "dependencies", "[", "i", "]", ")", "{", "throw", "new", "Error", "(", "'Circular dependency detected: '", "+", "path", "+", "'->'", "+", "dependencies", "[", "i", "]", ")", ";", "}", "else", "if", "(", "components", "[", "dependencies", "[", "i", "]", "]", ")", "{", "findCircularDependencies", "(", "componentName", ",", "components", "[", "dependencies", "[", "i", "]", "]", ".", "mixins", ",", "path", "+", "'->'", "+", "dependencies", "[", "i", "]", ")", ";", "}", "}", "}" ]
Find circular dependencies in component mixins @param {string} componentName The component name that is being added @param {Array} dependencies Array of component mixin dependencies @param {void} path String used to keep track of depencency graph @returns {void}
[ "Find", "circular", "dependencies", "in", "component", "mixins" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L230-L240
train
box/viewer.js
dist/crocodoc.viewer.js
function (name, mixins, creator) { if (mixins instanceof Function) { creator = mixins; mixins = []; } // make sure this component won't cause a circular mixin dependency findCircularDependencies(name, mixins); components[name] = { mixins: mixins, creator: creator }; }
javascript
function (name, mixins, creator) { if (mixins instanceof Function) { creator = mixins; mixins = []; } // make sure this component won't cause a circular mixin dependency findCircularDependencies(name, mixins); components[name] = { mixins: mixins, creator: creator }; }
[ "function", "(", "name", ",", "mixins", ",", "creator", ")", "{", "if", "(", "mixins", "instanceof", "Function", ")", "{", "creator", "=", "mixins", ";", "mixins", "=", "[", "]", ";", "}", "findCircularDependencies", "(", "name", ",", "mixins", ")", ";", "components", "[", "name", "]", "=", "{", "mixins", ":", "mixins", ",", "creator", ":", "creator", "}", ";", "}" ]
Register a new component @param {string} name The (unique) name of the component @param {Array} mixins Array of component names to instantiate and pass as mixinable objects to the creator method @param {Function} creator Factory function used to create an instance of the component @returns {void}
[ "Register", "a", "new", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L298-L309
train
box/viewer.js
dist/crocodoc.viewer.js
function (name, scope) { var component = components[name]; if (component) { var args = []; for (var i = 0; i < component.mixins.length; ++i) { args.push(this.createComponent(component.mixins[i], scope)); } args.unshift(scope); return component.creator.apply(component.creator, args); } return null; }
javascript
function (name, scope) { var component = components[name]; if (component) { var args = []; for (var i = 0; i < component.mixins.length; ++i) { args.push(this.createComponent(component.mixins[i], scope)); } args.unshift(scope); return component.creator.apply(component.creator, args); } return null; }
[ "function", "(", "name", ",", "scope", ")", "{", "var", "component", "=", "components", "[", "name", "]", ";", "if", "(", "component", ")", "{", "var", "args", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "component", ".", "mixins", ".", "length", ";", "++", "i", ")", "{", "args", ".", "push", "(", "this", ".", "createComponent", "(", "component", ".", "mixins", "[", "i", "]", ",", "scope", ")", ")", ";", "}", "args", ".", "unshift", "(", "scope", ")", ";", "return", "component", ".", "creator", ".", "apply", "(", "component", ".", "creator", ",", "args", ")", ";", "}", "return", "null", ";", "}" ]
Create and return an instance of the named component @param {string} name The name of the component to create @param {Crocodoc.Scope} scope The scope object to create the component on @returns {?Object} The component instance or null if the component doesn't exist
[ "Create", "and", "return", "an", "instance", "of", "the", "named", "component" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L317-L330
train
box/viewer.js
dist/crocodoc.viewer.js
function (name) { var utility = utilities[name]; if (utility) { if (!utility.instance) { utility.instance = utility.creator(this); } return utility.instance; } return null; }
javascript
function (name) { var utility = utilities[name]; if (utility) { if (!utility.instance) { utility.instance = utility.creator(this); } return utility.instance; } return null; }
[ "function", "(", "name", ")", "{", "var", "utility", "=", "utilities", "[", "name", "]", ";", "if", "(", "utility", ")", "{", "if", "(", "!", "utility", ".", "instance", ")", "{", "utility", ".", "instance", "=", "utility", ".", "creator", "(", "this", ")", ";", "}", "return", "utility", ".", "instance", ";", "}", "return", "null", ";", "}" ]
Retrieve the named utility @param {string} name The name of the utility to retrieve @returns {?Object} The utility or null if the utility doesn't exist
[ "Retrieve", "the", "named", "utility" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L369-L381
train
box/viewer.js
dist/crocodoc.viewer.js
broadcast
function broadcast(messageName, data) { var i, len, instance, messages; for (i = 0, len = instances.length; i < len; ++i) { instance = instances[i]; if (!instance) { continue; } messages = instance.messages || []; if (util.inArray(messageName, messages) !== -1) { if (util.isFn(instance.onmessage)) { instance.onmessage.call(instance, messageName, data); } } } }
javascript
function broadcast(messageName, data) { var i, len, instance, messages; for (i = 0, len = instances.length; i < len; ++i) { instance = instances[i]; if (!instance) { continue; } messages = instance.messages || []; if (util.inArray(messageName, messages) !== -1) { if (util.isFn(instance.onmessage)) { instance.onmessage.call(instance, messageName, data); } } } }
[ "function", "broadcast", "(", "messageName", ",", "data", ")", "{", "var", "i", ",", "len", ",", "instance", ",", "messages", ";", "for", "(", "i", "=", "0", ",", "len", "=", "instances", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "instance", "=", "instances", "[", "i", "]", ";", "if", "(", "!", "instance", ")", "{", "continue", ";", "}", "messages", "=", "instance", ".", "messages", "||", "[", "]", ";", "if", "(", "util", ".", "inArray", "(", "messageName", ",", "messages", ")", "!==", "-", "1", ")", "{", "if", "(", "util", ".", "isFn", "(", "instance", ".", "onmessage", ")", ")", "{", "instance", ".", "onmessage", ".", "call", "(", "instance", ",", "messageName", ",", "data", ")", ";", "}", "}", "}", "}" ]
Broadcast a message to all components in this scope that have registered a listener for the named message type @param {string} messageName The message name @param {any} data The message data @returns {void} @private
[ "Broadcast", "a", "message", "to", "all", "components", "in", "this", "scope", "that", "have", "registered", "a", "listener", "for", "the", "named", "message", "type" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L414-L429
train
box/viewer.js
dist/crocodoc.viewer.js
destroyComponent
function destroyComponent(instance) { if (util.isFn(instance.destroy) && !instance._destroyed) { instance.destroy(); instance._destroyed = true; } }
javascript
function destroyComponent(instance) { if (util.isFn(instance.destroy) && !instance._destroyed) { instance.destroy(); instance._destroyed = true; } }
[ "function", "destroyComponent", "(", "instance", ")", "{", "if", "(", "util", ".", "isFn", "(", "instance", ".", "destroy", ")", "&&", "!", "instance", ".", "_destroyed", ")", "{", "instance", ".", "destroy", "(", ")", ";", "instance", ".", "_destroyed", "=", "true", ";", "}", "}" ]
Call the destroy method on a component instance if it exists and the instance has not already been destroyed @param {Object} instance The component instance @returns {void}
[ "Call", "the", "destroy", "method", "on", "a", "component", "instance", "if", "it", "exists", "and", "the", "instance", "has", "not", "already", "been", "destroyed" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L452-L457
train
box/viewer.js
dist/crocodoc.viewer.js
buildEventObject
function buildEventObject(type, data) { var isDefaultPrevented = false; return { type: type, data: data, /** * Prevent the default action for this event * @returns {void} */ preventDefault: function () { isDefaultPrevented = true; }, /** * Return true if preventDefault() has been called on this event * @returns {Boolean} */ isDefaultPrevented: function () { return isDefaultPrevented; } }; }
javascript
function buildEventObject(type, data) { var isDefaultPrevented = false; return { type: type, data: data, /** * Prevent the default action for this event * @returns {void} */ preventDefault: function () { isDefaultPrevented = true; }, /** * Return true if preventDefault() has been called on this event * @returns {Boolean} */ isDefaultPrevented: function () { return isDefaultPrevented; } }; }
[ "function", "buildEventObject", "(", "type", ",", "data", ")", "{", "var", "isDefaultPrevented", "=", "false", ";", "return", "{", "type", ":", "type", ",", "data", ":", "data", ",", "preventDefault", ":", "function", "(", ")", "{", "isDefaultPrevented", "=", "true", ";", "}", ",", "isDefaultPrevented", ":", "function", "(", ")", "{", "return", "isDefaultPrevented", ";", "}", "}", ";", "}" ]
Build an event object for the given type and data @param {string} type The event type @param {Object} data The event data @returns {Object} The event object
[ "Build", "an", "event", "object", "for", "the", "given", "type", "and", "data" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L602-L624
train
box/viewer.js
dist/crocodoc.viewer.js
function(type, handler) { var handlers = this._handlers[type], i, len; if (handlers instanceof Array) { if (!handler) { handlers.length = 0; return; } for (i = 0, len = handlers.length; i < len; i++) { if (handlers[i] === handler || handlers[i].handler === handler) { handlers.splice(i, 1); break; } } } }
javascript
function(type, handler) { var handlers = this._handlers[type], i, len; if (handlers instanceof Array) { if (!handler) { handlers.length = 0; return; } for (i = 0, len = handlers.length; i < len; i++) { if (handlers[i] === handler || handlers[i].handler === handler) { handlers.splice(i, 1); break; } } } }
[ "function", "(", "type", ",", "handler", ")", "{", "var", "handlers", "=", "this", ".", "_handlers", "[", "type", "]", ",", "i", ",", "len", ";", "if", "(", "handlers", "instanceof", "Array", ")", "{", "if", "(", "!", "handler", ")", "{", "handlers", ".", "length", "=", "0", ";", "return", ";", "}", "for", "(", "i", "=", "0", ",", "len", "=", "handlers", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "handlers", "[", "i", "]", "===", "handler", "||", "handlers", "[", "i", "]", ".", "handler", "===", "handler", ")", "{", "handlers", ".", "splice", "(", "i", ",", "1", ")", ";", "break", ";", "}", "}", "}", "}" ]
Removes an event handler from a given event. If the handler is not provided, remove all handlers of the given type. @param {string} type The name of the event to remove from. @param {Function} handler The function to remove as a handler. @returns {void}
[ "Removes", "an", "event", "handler", "from", "a", "given", "event", ".", "If", "the", "handler", "is", "not", "provided", "remove", "all", "handlers", "of", "the", "given", "type", "." ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L712-L729
train
box/viewer.js
dist/crocodoc.viewer.js
function(type, handler) { var self = this, proxy = function (event) { self.off(type, proxy); handler.call(self, event); }; proxy.handler = handler; this.on(type, proxy); }
javascript
function(type, handler) { var self = this, proxy = function (event) { self.off(type, proxy); handler.call(self, event); }; proxy.handler = handler; this.on(type, proxy); }
[ "function", "(", "type", ",", "handler", ")", "{", "var", "self", "=", "this", ",", "proxy", "=", "function", "(", "event", ")", "{", "self", ".", "off", "(", "type", ",", "proxy", ")", ";", "handler", ".", "call", "(", "self", ",", "event", ")", ";", "}", ";", "proxy", ".", "handler", "=", "handler", ";", "this", ".", "on", "(", "type", ",", "proxy", ")", ";", "}" ]
Adds a new event handler that should be removed after it's been triggered once. @param {string} type The name of the event to listen for. @param {Function} handler The function to call when the event occurs. @returns {void}
[ "Adds", "a", "new", "event", "handler", "that", "should", "be", "removed", "after", "it", "s", "been", "triggered", "once", "." ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L738-L746
train
box/viewer.js
dist/crocodoc.viewer.js
function() { var url = this.getURL(), $promise = ajax.fetch(url, Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target return $promise.then(processJSONContent).promise({ abort: $promise.abort }); }
javascript
function() { var url = this.getURL(), $promise = ajax.fetch(url, Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target return $promise.then(processJSONContent).promise({ abort: $promise.abort }); }
[ "function", "(", ")", "{", "var", "url", "=", "this", ".", "getURL", "(", ")", ",", "$promise", "=", "ajax", ".", "fetch", "(", "url", ",", "Crocodoc", ".", "ASSET_REQUEST_RETRIES", ")", ";", "return", "$promise", ".", "then", "(", "processJSONContent", ")", ".", "promise", "(", "{", "abort", ":", "$promise", ".", "abort", "}", ")", ";", "}" ]
Retrieve the info.json asset from the server @returns {$.Promise} A promise with an additional abort() method that will abort the XHR request.
[ "Retrieve", "the", "info", ".", "json", "asset", "from", "the", "server" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1065-L1075
train
box/viewer.js
dist/crocodoc.viewer.js
function(objectType, pageNum) { var img = this.getImage(), retries = Crocodoc.ASSET_REQUEST_RETRIES, loaded = false, url = this.getURL(pageNum), $deferred = $.Deferred(); function loadImage() { img.setAttribute('src', url); } function abortImage() { if (img) { img.removeAttribute('src'); } } // add load and error handlers img.onload = function () { loaded = true; $deferred.resolve(img); }; img.onerror = function () { if (retries > 0) { retries--; abortImage(); loadImage(); } else { img = null; loaded = false; $deferred.reject({ error: 'image failed to load', resource: url }); } }; // load the image loadImage(); return $deferred.promise({ abort: function () { if (!loaded) { abortImage(); $deferred.reject(); } } }); }
javascript
function(objectType, pageNum) { var img = this.getImage(), retries = Crocodoc.ASSET_REQUEST_RETRIES, loaded = false, url = this.getURL(pageNum), $deferred = $.Deferred(); function loadImage() { img.setAttribute('src', url); } function abortImage() { if (img) { img.removeAttribute('src'); } } // add load and error handlers img.onload = function () { loaded = true; $deferred.resolve(img); }; img.onerror = function () { if (retries > 0) { retries--; abortImage(); loadImage(); } else { img = null; loaded = false; $deferred.reject({ error: 'image failed to load', resource: url }); } }; // load the image loadImage(); return $deferred.promise({ abort: function () { if (!loaded) { abortImage(); $deferred.reject(); } } }); }
[ "function", "(", "objectType", ",", "pageNum", ")", "{", "var", "img", "=", "this", ".", "getImage", "(", ")", ",", "retries", "=", "Crocodoc", ".", "ASSET_REQUEST_RETRIES", ",", "loaded", "=", "false", ",", "url", "=", "this", ".", "getURL", "(", "pageNum", ")", ",", "$deferred", "=", "$", ".", "Deferred", "(", ")", ";", "function", "loadImage", "(", ")", "{", "img", ".", "setAttribute", "(", "'src'", ",", "url", ")", ";", "}", "function", "abortImage", "(", ")", "{", "if", "(", "img", ")", "{", "img", ".", "removeAttribute", "(", "'src'", ")", ";", "}", "}", "img", ".", "onload", "=", "function", "(", ")", "{", "loaded", "=", "true", ";", "$deferred", ".", "resolve", "(", "img", ")", ";", "}", ";", "img", ".", "onerror", "=", "function", "(", ")", "{", "if", "(", "retries", ">", "0", ")", "{", "retries", "--", ";", "abortImage", "(", ")", ";", "loadImage", "(", ")", ";", "}", "else", "{", "img", "=", "null", ";", "loaded", "=", "false", ";", "$deferred", ".", "reject", "(", "{", "error", ":", "'image failed to load'", ",", "resource", ":", "url", "}", ")", ";", "}", "}", ";", "loadImage", "(", ")", ";", "return", "$deferred", ".", "promise", "(", "{", "abort", ":", "function", "(", ")", "{", "if", "(", "!", "loaded", ")", "{", "abortImage", "(", ")", ";", "$deferred", ".", "reject", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Retrieve the page image asset from the server @param {string} objectType The type of data being requested @param {number} pageNum The page number for which to request the page image @returns {$.Promise} A promise with an additional abort() method that will abort the img request.
[ "Retrieve", "the", "page", "image", "asset", "from", "the", "server" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1105-L1154
train
box/viewer.js
dist/crocodoc.viewer.js
function (pageNum) { var imgPath = util.template(config.template.img, { page: pageNum }); return config.url + imgPath + config.queryString; }
javascript
function (pageNum) { var imgPath = util.template(config.template.img, { page: pageNum }); return config.url + imgPath + config.queryString; }
[ "function", "(", "pageNum", ")", "{", "var", "imgPath", "=", "util", ".", "template", "(", "config", ".", "template", ".", "img", ",", "{", "page", ":", "pageNum", "}", ")", ";", "return", "config", ".", "url", "+", "imgPath", "+", "config", ".", "queryString", ";", "}" ]
Build and return the URL to the PNG asset for the specified page @param {number} pageNum The page number @returns {string} The URL
[ "Build", "and", "return", "the", "URL", "to", "the", "PNG", "asset", "for", "the", "specified", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1161-L1164
train
box/viewer.js
dist/crocodoc.viewer.js
interpolateCSSText
function interpolateCSSText(text, cssText) { // CSS text var stylesheetHTML = '<style>' + cssText + '</style>'; // If using Firefox with no subpx support, add "text-rendering" CSS. // @NOTE(plai): We are not adding this to Chrome because Chrome supports "textLength" // on tspans and because the "text-rendering" property slows Chrome down significantly. // In Firefox, we're waiting on this bug: https://bugzilla.mozilla.org/show_bug.cgi?id=890692 // @TODO: Use feature detection instead (textLength) if (browser.firefox && !subpx.isSubpxSupported()) { stylesheetHTML += '<style>text { text-rendering: geometricPrecision; }</style>'; } // inline the CSS! text = text.replace(inlineCSSRegExp, stylesheetHTML); return text; }
javascript
function interpolateCSSText(text, cssText) { // CSS text var stylesheetHTML = '<style>' + cssText + '</style>'; // If using Firefox with no subpx support, add "text-rendering" CSS. // @NOTE(plai): We are not adding this to Chrome because Chrome supports "textLength" // on tspans and because the "text-rendering" property slows Chrome down significantly. // In Firefox, we're waiting on this bug: https://bugzilla.mozilla.org/show_bug.cgi?id=890692 // @TODO: Use feature detection instead (textLength) if (browser.firefox && !subpx.isSubpxSupported()) { stylesheetHTML += '<style>text { text-rendering: geometricPrecision; }</style>'; } // inline the CSS! text = text.replace(inlineCSSRegExp, stylesheetHTML); return text; }
[ "function", "interpolateCSSText", "(", "text", ",", "cssText", ")", "{", "var", "stylesheetHTML", "=", "'<style>'", "+", "cssText", "+", "'</style>'", ";", "if", "(", "browser", ".", "firefox", "&&", "!", "subpx", ".", "isSubpxSupported", "(", ")", ")", "{", "stylesheetHTML", "+=", "'<style>text { text-rendering: geometricPrecision; }</style>'", ";", "}", "text", "=", "text", ".", "replace", "(", "inlineCSSRegExp", ",", "stylesheetHTML", ")", ";", "return", "text", ";", "}" ]
Interpolate CSS text into the SVG text @param {string} text The SVG text @param {string} cssText The CSS text @returns {string} The full SVG text
[ "Interpolate", "CSS", "text", "into", "the", "SVG", "text" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1198-L1215
train
box/viewer.js
dist/crocodoc.viewer.js
processSVGContent
function processSVGContent(text) { if (destroyed) { return; } var query = config.queryString.replace('&', '&#38;'), dataUrlCount; dataUrlCount = util.countInStr(text, 'xlink:href="data:image'); // remove data:urls from the SVG content if the number exceeds MAX_DATA_URLS if (dataUrlCount > MAX_DATA_URLS) { // remove all data:url images that are smaller than 5KB text = text.replace(/<image[\s\w-_="]*xlink:href="data:image\/[^"]{0,5120}"[^>]*>/ig, ''); } // @TODO: remove this, because we no longer use any external assets in this way // modify external asset urls for absolute path text = text.replace(/href="([^"#:]*)"/g, function (match, group) { return 'href="' + config.url + group + query + '"'; }); return scope.get('stylesheet').then(function (cssText) { return interpolateCSSText(text, cssText); }); }
javascript
function processSVGContent(text) { if (destroyed) { return; } var query = config.queryString.replace('&', '&#38;'), dataUrlCount; dataUrlCount = util.countInStr(text, 'xlink:href="data:image'); // remove data:urls from the SVG content if the number exceeds MAX_DATA_URLS if (dataUrlCount > MAX_DATA_URLS) { // remove all data:url images that are smaller than 5KB text = text.replace(/<image[\s\w-_="]*xlink:href="data:image\/[^"]{0,5120}"[^>]*>/ig, ''); } // @TODO: remove this, because we no longer use any external assets in this way // modify external asset urls for absolute path text = text.replace(/href="([^"#:]*)"/g, function (match, group) { return 'href="' + config.url + group + query + '"'; }); return scope.get('stylesheet').then(function (cssText) { return interpolateCSSText(text, cssText); }); }
[ "function", "processSVGContent", "(", "text", ")", "{", "if", "(", "destroyed", ")", "{", "return", ";", "}", "var", "query", "=", "config", ".", "queryString", ".", "replace", "(", "'&'", ",", "'&#38;'", ")", ",", "dataUrlCount", ";", "dataUrlCount", "=", "util", ".", "countInStr", "(", "text", ",", "'xlink:href=\"data:image'", ")", ";", "if", "(", "dataUrlCount", ">", "MAX_DATA_URLS", ")", "{", "text", "=", "text", ".", "replace", "(", "/", "<image[\\s\\w-_=\"]*xlink:href=\"data:image\\/[^\"]{0,5120}\"[^>]*>", "/", "ig", ",", "''", ")", ";", "}", "text", "=", "text", ".", "replace", "(", "/", "href=\"([^\"#:]*)\"", "/", "g", ",", "function", "(", "match", ",", "group", ")", "{", "return", "'href=\"'", "+", "config", ".", "url", "+", "group", "+", "query", "+", "'\"'", ";", "}", ")", ";", "return", "scope", ".", "get", "(", "'stylesheet'", ")", ".", "then", "(", "function", "(", "cssText", ")", "{", "return", "interpolateCSSText", "(", "text", ",", "cssText", ")", ";", "}", ")", ";", "}" ]
Process SVG text and return the embeddable result @param {string} text The original SVG text @returns {string} The processed SVG text @private
[ "Process", "SVG", "text", "and", "return", "the", "embeddable", "result" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1223-L1247
train
box/viewer.js
dist/crocodoc.viewer.js
function (pageNum) { var svgPath = util.template(config.template.svg, { page: pageNum }); return config.url + svgPath + config.queryString; }
javascript
function (pageNum) { var svgPath = util.template(config.template.svg, { page: pageNum }); return config.url + svgPath + config.queryString; }
[ "function", "(", "pageNum", ")", "{", "var", "svgPath", "=", "util", ".", "template", "(", "config", ".", "template", ".", "svg", ",", "{", "page", ":", "pageNum", "}", ")", ";", "return", "config", ".", "url", "+", "svgPath", "+", "config", ".", "queryString", ";", "}" ]
Build and return the URL to the SVG asset for the specified page @param {number} pageNum The page number @returns {string} The URL
[ "Build", "and", "return", "the", "URL", "to", "the", "SVG", "asset", "for", "the", "specified", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1289-L1292
train
box/viewer.js
dist/crocodoc.viewer.js
processTextContent
function processTextContent(text) { if (destroyed) { return; } // in the text layer, divs are only used for text boxes, so // they should provide an accurate count var numTextBoxes = util.countInStr(text, '<div'); // too many textboxes... don't load this page for performance reasons if (numTextBoxes > MAX_TEXT_BOXES) { return ''; } // remove reference to the styles text = text.replace(/<link rel="stylesheet".*/, ''); return text; }
javascript
function processTextContent(text) { if (destroyed) { return; } // in the text layer, divs are only used for text boxes, so // they should provide an accurate count var numTextBoxes = util.countInStr(text, '<div'); // too many textboxes... don't load this page for performance reasons if (numTextBoxes > MAX_TEXT_BOXES) { return ''; } // remove reference to the styles text = text.replace(/<link rel="stylesheet".*/, ''); return text; }
[ "function", "processTextContent", "(", "text", ")", "{", "if", "(", "destroyed", ")", "{", "return", ";", "}", "var", "numTextBoxes", "=", "util", ".", "countInStr", "(", "text", ",", "'<div'", ")", ";", "if", "(", "numTextBoxes", ">", "MAX_TEXT_BOXES", ")", "{", "return", "''", ";", "}", "text", "=", "text", ".", "replace", "(", "/", "<link rel=\"stylesheet\".*", "/", ",", "''", ")", ";", "return", "text", ";", "}" ]
Process HTML text and return the embeddable result @param {string} text The original HTML text @returns {string} The processed HTML text @private
[ "Process", "HTML", "text", "and", "return", "the", "embeddable", "result" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1322-L1339
train
box/viewer.js
dist/crocodoc.viewer.js
function(objectType, pageNum) { var url = this.getURL(pageNum), $promise; if (cache[pageNum]) { return cache[pageNum]; } $promise = ajax.fetch(url, Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target cache[pageNum] = $promise.then(processTextContent).promise({ abort: function () { $promise.abort(); if (cache) { delete cache[pageNum]; } } }); return cache[pageNum]; }
javascript
function(objectType, pageNum) { var url = this.getURL(pageNum), $promise; if (cache[pageNum]) { return cache[pageNum]; } $promise = ajax.fetch(url, Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target cache[pageNum] = $promise.then(processTextContent).promise({ abort: function () { $promise.abort(); if (cache) { delete cache[pageNum]; } } }); return cache[pageNum]; }
[ "function", "(", "objectType", ",", "pageNum", ")", "{", "var", "url", "=", "this", ".", "getURL", "(", "pageNum", ")", ",", "$promise", ";", "if", "(", "cache", "[", "pageNum", "]", ")", "{", "return", "cache", "[", "pageNum", "]", ";", "}", "$promise", "=", "ajax", ".", "fetch", "(", "url", ",", "Crocodoc", ".", "ASSET_REQUEST_RETRIES", ")", ";", "cache", "[", "pageNum", "]", "=", "$promise", ".", "then", "(", "processTextContent", ")", ".", "promise", "(", "{", "abort", ":", "function", "(", ")", "{", "$promise", ".", "abort", "(", ")", ";", "if", "(", "cache", ")", "{", "delete", "cache", "[", "pageNum", "]", ";", "}", "}", "}", ")", ";", "return", "cache", "[", "pageNum", "]", ";", "}" ]
Retrieve a text asset from the server @param {string} objectType The type of data being requested @param {number} pageNum The page number for which to request the text HTML @returns {$.Promise} A promise with an additional abort() method that will abort the XHR request.
[ "Retrieve", "a", "text", "asset", "from", "the", "server" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1352-L1374
train
box/viewer.js
dist/crocodoc.viewer.js
function (pageNum) { var textPath = util.template(config.template.html, { page: pageNum }); return config.url + textPath + config.queryString; }
javascript
function (pageNum) { var textPath = util.template(config.template.html, { page: pageNum }); return config.url + textPath + config.queryString; }
[ "function", "(", "pageNum", ")", "{", "var", "textPath", "=", "util", ".", "template", "(", "config", ".", "template", ".", "html", ",", "{", "page", ":", "pageNum", "}", ")", ";", "return", "config", ".", "url", "+", "textPath", "+", "config", ".", "queryString", ";", "}" ]
Build and return the URL to the HTML asset for the specified page @param {number} pageNum The page number @returns {string} The URL
[ "Build", "and", "return", "the", "URL", "to", "the", "HTML", "asset", "for", "the", "specified", "page" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1381-L1384
train
box/viewer.js
dist/crocodoc.viewer.js
processStylesheetContent
function processStylesheetContent(text) { // @NOTE: There is a bug in IE that causes the text layer to // not render the font when loaded for a second time (i.e., // destroy and recreate a viewer for the same document), so // namespace the font-family so there is no collision if (browser.ie) { text = text.replace(/font-family:[\s\"\']*([\w-]+)\b/g, '$0-' + config.id); } return text; }
javascript
function processStylesheetContent(text) { // @NOTE: There is a bug in IE that causes the text layer to // not render the font when loaded for a second time (i.e., // destroy and recreate a viewer for the same document), so // namespace the font-family so there is no collision if (browser.ie) { text = text.replace(/font-family:[\s\"\']*([\w-]+)\b/g, '$0-' + config.id); } return text; }
[ "function", "processStylesheetContent", "(", "text", ")", "{", "if", "(", "browser", ".", "ie", ")", "{", "text", "=", "text", ".", "replace", "(", "/", "font-family:[\\s\\\"\\']*([\\w-]+)\\b", "/", "g", ",", "'$0-'", "+", "config", ".", "id", ")", ";", "}", "return", "text", ";", "}" ]
Process stylesheet text and return the embeddable result @param {string} text The original CSS text @returns {string} The processed CSS text @private
[ "Process", "stylesheet", "text", "and", "return", "the", "embeddable", "result" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1411-L1422
train
box/viewer.js
dist/crocodoc.viewer.js
function() { if ($cachedPromise) { return $cachedPromise; } var $promise = ajax.fetch(this.getURL(), Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target $cachedPromise = $promise.then(processStylesheetContent).promise({ abort: function () { $promise.abort(); $cachedPromise = null; } }); return $cachedPromise; }
javascript
function() { if ($cachedPromise) { return $cachedPromise; } var $promise = ajax.fetch(this.getURL(), Crocodoc.ASSET_REQUEST_RETRIES); // @NOTE: promise.then() creates a new promise, which does not copy // custom properties, so we need to create a futher promise and add // an object with the abort method as the new target $cachedPromise = $promise.then(processStylesheetContent).promise({ abort: function () { $promise.abort(); $cachedPromise = null; } }); return $cachedPromise; }
[ "function", "(", ")", "{", "if", "(", "$cachedPromise", ")", "{", "return", "$cachedPromise", ";", "}", "var", "$promise", "=", "ajax", ".", "fetch", "(", "this", ".", "getURL", "(", ")", ",", "Crocodoc", ".", "ASSET_REQUEST_RETRIES", ")", ";", "$cachedPromise", "=", "$promise", ".", "then", "(", "processStylesheetContent", ")", ".", "promise", "(", "{", "abort", ":", "function", "(", ")", "{", "$promise", ".", "abort", "(", ")", ";", "$cachedPromise", "=", "null", ";", "}", "}", ")", ";", "return", "$cachedPromise", ";", "}" ]
Retrieve the stylesheet.css asset from the server @returns {$.Promise} A promise with an additional abort() method that will abort the XHR request.
[ "Retrieve", "the", "stylesheet", ".", "css", "asset", "from", "the", "server" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1433-L1450
train
box/viewer.js
dist/crocodoc.viewer.js
parseOptions
function parseOptions(options) { options = util.extend(true, {}, options || {}); options.method = options.method || 'GET'; options.headers = options.headers || []; options.data = options.data || ''; options.withCredentials = !!options.withCredentials; if (typeof options.data !== 'string') { options.data = $.param(options.data); if (options.method !== 'GET') { options.data = options.data; options.headers.push(['Content-Type', 'application/x-www-form-urlencoded']); } } return options; }
javascript
function parseOptions(options) { options = util.extend(true, {}, options || {}); options.method = options.method || 'GET'; options.headers = options.headers || []; options.data = options.data || ''; options.withCredentials = !!options.withCredentials; if (typeof options.data !== 'string') { options.data = $.param(options.data); if (options.method !== 'GET') { options.data = options.data; options.headers.push(['Content-Type', 'application/x-www-form-urlencoded']); } } return options; }
[ "function", "parseOptions", "(", "options", ")", "{", "options", "=", "util", ".", "extend", "(", "true", ",", "{", "}", ",", "options", "||", "{", "}", ")", ";", "options", ".", "method", "=", "options", ".", "method", "||", "'GET'", ";", "options", ".", "headers", "=", "options", ".", "headers", "||", "[", "]", ";", "options", ".", "data", "=", "options", ".", "data", "||", "''", ";", "options", ".", "withCredentials", "=", "!", "!", "options", ".", "withCredentials", ";", "if", "(", "typeof", "options", ".", "data", "!==", "'string'", ")", "{", "options", ".", "data", "=", "$", ".", "param", "(", "options", ".", "data", ")", ";", "if", "(", "options", ".", "method", "!==", "'GET'", ")", "{", "options", ".", "data", "=", "options", ".", "data", ";", "options", ".", "headers", ".", "push", "(", "[", "'Content-Type'", ",", "'application/x-www-form-urlencoded'", "]", ")", ";", "}", "}", "return", "options", ";", "}" ]
Parse AJAX options @param {Object} options The options @returns {Object} The parsed options
[ "Parse", "AJAX", "options" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1530-L1545
train
box/viewer.js
dist/crocodoc.viewer.js
setHeaders
function setHeaders(req, headers) { var i; for (i = 0; i < headers.length; ++i) { req.setRequestHeader(headers[i][0], headers[i][1]); } }
javascript
function setHeaders(req, headers) { var i; for (i = 0; i < headers.length; ++i) { req.setRequestHeader(headers[i][0], headers[i][1]); } }
[ "function", "setHeaders", "(", "req", ",", "headers", ")", "{", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "headers", ".", "length", ";", "++", "i", ")", "{", "req", ".", "setRequestHeader", "(", "headers", "[", "i", "]", "[", "0", "]", ",", "headers", "[", "i", "]", "[", "1", "]", ")", ";", "}", "}" ]
Set XHR headers @param {XMLHttpRequest} req The request object @param {Array} headers Array of headers to set
[ "Set", "XHR", "headers" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1552-L1557
train
box/viewer.js
dist/crocodoc.viewer.js
doXHR
function doXHR(url, method, data, headers, withCredentials, success, fail) { var req = support.getXHR(); req.open(method, url, true); req.onreadystatechange = function () { var status; if (req.readyState === 4) { // DONE // remove the onreadystatechange handler, // because it could be called again // @NOTE: we replace it with a noop function, because // IE8 will throw an error if the value is not of type // 'function' when using ActiveXObject req.onreadystatechange = function () {}; try { status = req.status; } catch (e) { // NOTE: IE (9?) throws an error when the request is aborted fail(req); return; } // status is 0 for successful local file requests, so assume 200 if (status === 0 && isRequestToLocalFile(url)) { status = 200; } if (isSuccessfulStatusCode(status)) { success(req); } else { fail(req); } } }; setHeaders(req, headers); // this needs to be after the open call and before the send call req.withCredentials = withCredentials; req.send(data); return req; }
javascript
function doXHR(url, method, data, headers, withCredentials, success, fail) { var req = support.getXHR(); req.open(method, url, true); req.onreadystatechange = function () { var status; if (req.readyState === 4) { // DONE // remove the onreadystatechange handler, // because it could be called again // @NOTE: we replace it with a noop function, because // IE8 will throw an error if the value is not of type // 'function' when using ActiveXObject req.onreadystatechange = function () {}; try { status = req.status; } catch (e) { // NOTE: IE (9?) throws an error when the request is aborted fail(req); return; } // status is 0 for successful local file requests, so assume 200 if (status === 0 && isRequestToLocalFile(url)) { status = 200; } if (isSuccessfulStatusCode(status)) { success(req); } else { fail(req); } } }; setHeaders(req, headers); // this needs to be after the open call and before the send call req.withCredentials = withCredentials; req.send(data); return req; }
[ "function", "doXHR", "(", "url", ",", "method", ",", "data", ",", "headers", ",", "withCredentials", ",", "success", ",", "fail", ")", "{", "var", "req", "=", "support", ".", "getXHR", "(", ")", ";", "req", ".", "open", "(", "method", ",", "url", ",", "true", ")", ";", "req", ".", "onreadystatechange", "=", "function", "(", ")", "{", "var", "status", ";", "if", "(", "req", ".", "readyState", "===", "4", ")", "{", "req", ".", "onreadystatechange", "=", "function", "(", ")", "{", "}", ";", "try", "{", "status", "=", "req", ".", "status", ";", "}", "catch", "(", "e", ")", "{", "fail", "(", "req", ")", ";", "return", ";", "}", "if", "(", "status", "===", "0", "&&", "isRequestToLocalFile", "(", "url", ")", ")", "{", "status", "=", "200", ";", "}", "if", "(", "isSuccessfulStatusCode", "(", "status", ")", ")", "{", "success", "(", "req", ")", ";", "}", "else", "{", "fail", "(", "req", ")", ";", "}", "}", "}", ";", "setHeaders", "(", "req", ",", "headers", ")", ";", "req", ".", "withCredentials", "=", "withCredentials", ";", "req", ".", "send", "(", "data", ")", ";", "return", "req", ";", "}" ]
Make an XHR request @param {string} url request URL @param {string} method request method @param {*} data request data to send @param {Array} headers request headers @param {boolean} withCredentials request withCredentials option @param {Function} success success callback function @param {Function} fail fail callback function @returns {XMLHttpRequest} Request object @private
[ "Make", "an", "XHR", "request" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1571-L1611
train
box/viewer.js
dist/crocodoc.viewer.js
doXDR
function doXDR(url, method, data, success, fail) { var req = support.getXDR(); try { req.open(method, url); req.onload = function () { success(req); }; // NOTE: IE (8/9) requires onerror, ontimeout, and onprogress // to be defined when making XDR to https servers req.onerror = function () { fail(req); }; req.ontimeout = function () { fail(req); }; req.onprogress = function () {}; req.send(data); } catch (e) { return fail({ status: 0, statusText: e.message }); } return req; }
javascript
function doXDR(url, method, data, success, fail) { var req = support.getXDR(); try { req.open(method, url); req.onload = function () { success(req); }; // NOTE: IE (8/9) requires onerror, ontimeout, and onprogress // to be defined when making XDR to https servers req.onerror = function () { fail(req); }; req.ontimeout = function () { fail(req); }; req.onprogress = function () {}; req.send(data); } catch (e) { return fail({ status: 0, statusText: e.message }); } return req; }
[ "function", "doXDR", "(", "url", ",", "method", ",", "data", ",", "success", ",", "fail", ")", "{", "var", "req", "=", "support", ".", "getXDR", "(", ")", ";", "try", "{", "req", ".", "open", "(", "method", ",", "url", ")", ";", "req", ".", "onload", "=", "function", "(", ")", "{", "success", "(", "req", ")", ";", "}", ";", "req", ".", "onerror", "=", "function", "(", ")", "{", "fail", "(", "req", ")", ";", "}", ";", "req", ".", "ontimeout", "=", "function", "(", ")", "{", "fail", "(", "req", ")", ";", "}", ";", "req", ".", "onprogress", "=", "function", "(", ")", "{", "}", ";", "req", ".", "send", "(", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "fail", "(", "{", "status", ":", "0", ",", "statusText", ":", "e", ".", "message", "}", ")", ";", "}", "return", "req", ";", "}" ]
Make an XDR request @param {string} url request URL @param {string} method request method @param {*} data request data to send @param {Function} success success callback function @param {Function} fail fail callback function @returns {XDomainRequest} Request object @private
[ "Make", "an", "XDR", "request" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1623-L1641
train
box/viewer.js
dist/crocodoc.viewer.js
function (url, options) { var opt = parseOptions(options), method = opt.method, data = opt.data, headers = opt.headers, withCredentials = opt.withCredentials; if (method === 'GET' && data) { url = urlUtil.appendQueryParams(url, data); data = ''; } /** * Function to call on successful AJAX request * @returns {void} * @private */ function ajaxSuccess(req) { if (util.isFn(opt.success)) { opt.success.call(createRequestWrapper(req)); } return req; } /** * Function to call on failed AJAX request * @returns {void} * @private */ function ajaxFail(req) { if (util.isFn(opt.fail)) { opt.fail.call(createRequestWrapper(req)); } return req; } // is XHR supported at all? if (!support.isXHRSupported()) { return opt.fail({ status: 0, statusText: 'AJAX not supported' }); } // cross-domain request? check if CORS is supported... if (urlUtil.isCrossDomain(url) && !support.isCORSSupported()) { // the browser supports XHR, but not XHR+CORS, so (try to) use XDR return doXDR(url, method, data, ajaxSuccess, ajaxFail); } else { // the browser supports XHR and XHR+CORS, so just do a regular XHR return doXHR(url, method, data, headers, withCredentials, ajaxSuccess, ajaxFail); } }
javascript
function (url, options) { var opt = parseOptions(options), method = opt.method, data = opt.data, headers = opt.headers, withCredentials = opt.withCredentials; if (method === 'GET' && data) { url = urlUtil.appendQueryParams(url, data); data = ''; } /** * Function to call on successful AJAX request * @returns {void} * @private */ function ajaxSuccess(req) { if (util.isFn(opt.success)) { opt.success.call(createRequestWrapper(req)); } return req; } /** * Function to call on failed AJAX request * @returns {void} * @private */ function ajaxFail(req) { if (util.isFn(opt.fail)) { opt.fail.call(createRequestWrapper(req)); } return req; } // is XHR supported at all? if (!support.isXHRSupported()) { return opt.fail({ status: 0, statusText: 'AJAX not supported' }); } // cross-domain request? check if CORS is supported... if (urlUtil.isCrossDomain(url) && !support.isCORSSupported()) { // the browser supports XHR, but not XHR+CORS, so (try to) use XDR return doXDR(url, method, data, ajaxSuccess, ajaxFail); } else { // the browser supports XHR and XHR+CORS, so just do a regular XHR return doXHR(url, method, data, headers, withCredentials, ajaxSuccess, ajaxFail); } }
[ "function", "(", "url", ",", "options", ")", "{", "var", "opt", "=", "parseOptions", "(", "options", ")", ",", "method", "=", "opt", ".", "method", ",", "data", "=", "opt", ".", "data", ",", "headers", "=", "opt", ".", "headers", ",", "withCredentials", "=", "opt", ".", "withCredentials", ";", "if", "(", "method", "===", "'GET'", "&&", "data", ")", "{", "url", "=", "urlUtil", ".", "appendQueryParams", "(", "url", ",", "data", ")", ";", "data", "=", "''", ";", "}", "function", "ajaxSuccess", "(", "req", ")", "{", "if", "(", "util", ".", "isFn", "(", "opt", ".", "success", ")", ")", "{", "opt", ".", "success", ".", "call", "(", "createRequestWrapper", "(", "req", ")", ")", ";", "}", "return", "req", ";", "}", "function", "ajaxFail", "(", "req", ")", "{", "if", "(", "util", ".", "isFn", "(", "opt", ".", "fail", ")", ")", "{", "opt", ".", "fail", ".", "call", "(", "createRequestWrapper", "(", "req", ")", ")", ";", "}", "return", "req", ";", "}", "if", "(", "!", "support", ".", "isXHRSupported", "(", ")", ")", "{", "return", "opt", ".", "fail", "(", "{", "status", ":", "0", ",", "statusText", ":", "'AJAX not supported'", "}", ")", ";", "}", "if", "(", "urlUtil", ".", "isCrossDomain", "(", "url", ")", "&&", "!", "support", ".", "isCORSSupported", "(", ")", ")", "{", "return", "doXDR", "(", "url", ",", "method", ",", "data", ",", "ajaxSuccess", ",", "ajaxFail", ")", ";", "}", "else", "{", "return", "doXHR", "(", "url", ",", "method", ",", "data", ",", "headers", ",", "withCredentials", ",", "ajaxSuccess", ",", "ajaxFail", ")", ";", "}", "}" ]
Make a raw AJAX request @param {string} url request URL @param {Object} [options] AJAX request options @param {string} [options.method] request method, eg. 'GET', 'POST' (defaults to 'GET') @param {Array} [options.headers] request headers (defaults to []) @param {*} [options.data] request data to send (defaults to null) @param {Function} [options.success] success callback function @param {Function} [options.fail] fail callback function @returns {XMLHttpRequest|XDomainRequest} Request object
[ "Make", "a", "raw", "AJAX", "request" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1655-L1707
train
box/viewer.js
dist/crocodoc.viewer.js
ajaxSuccess
function ajaxSuccess(req) { if (util.isFn(opt.success)) { opt.success.call(createRequestWrapper(req)); } return req; }
javascript
function ajaxSuccess(req) { if (util.isFn(opt.success)) { opt.success.call(createRequestWrapper(req)); } return req; }
[ "function", "ajaxSuccess", "(", "req", ")", "{", "if", "(", "util", ".", "isFn", "(", "opt", ".", "success", ")", ")", "{", "opt", ".", "success", ".", "call", "(", "createRequestWrapper", "(", "req", ")", ")", ";", "}", "return", "req", ";", "}" ]
Function to call on successful AJAX request @returns {void} @private
[ "Function", "to", "call", "on", "successful", "AJAX", "request" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1672-L1677
train
box/viewer.js
dist/crocodoc.viewer.js
ajaxFail
function ajaxFail(req) { if (util.isFn(opt.fail)) { opt.fail.call(createRequestWrapper(req)); } return req; }
javascript
function ajaxFail(req) { if (util.isFn(opt.fail)) { opt.fail.call(createRequestWrapper(req)); } return req; }
[ "function", "ajaxFail", "(", "req", ")", "{", "if", "(", "util", ".", "isFn", "(", "opt", ".", "fail", ")", ")", "{", "opt", ".", "fail", ".", "call", "(", "createRequestWrapper", "(", "req", ")", ")", ";", "}", "return", "req", ";", "}" ]
Function to call on failed AJAX request @returns {void} @private
[ "Function", "to", "call", "on", "failed", "AJAX", "request" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1684-L1689
train
box/viewer.js
dist/crocodoc.viewer.js
function (url, retries) { var req, aborted = false, ajax = this, $deferred = $.Deferred(); /** * If there are retries remaining, make another attempt, otherwise * give up and reject the deferred * @param {Object} error The error object * @returns {void} * @private */ function retryOrFail(error) { if (retries > 0) { // if we have retries remaining, make another request retries--; req = request(); } else { // finally give up $deferred.reject(error); } } /** * Make an AJAX request for the asset * @returns {XMLHttpRequest|XDomainRequest} Request object * @private */ function request() { return ajax.request(url, { success: function () { var retryAfter, req; if (!aborted) { req = this.rawRequest; // check status code for 202 if (this.status === 202 && util.isFn(req.getResponseHeader)) { // retry the request retryAfter = parseInt(req.getResponseHeader('retry-after')); if (retryAfter > 0) { setTimeout(request, retryAfter * 1000); return; } } if (this.responseText) { $deferred.resolve(this.responseText); } else { // the response was empty, so consider this a // failed request retryOrFail({ error: 'empty response', status: this.status, resource: url }); } } }, fail: function () { if (!aborted) { retryOrFail({ error: this.statusText, status: this.status, resource: url }); } } }); } req = request(); return $deferred.promise({ abort: function() { aborted = true; req.abort(); } }); }
javascript
function (url, retries) { var req, aborted = false, ajax = this, $deferred = $.Deferred(); /** * If there are retries remaining, make another attempt, otherwise * give up and reject the deferred * @param {Object} error The error object * @returns {void} * @private */ function retryOrFail(error) { if (retries > 0) { // if we have retries remaining, make another request retries--; req = request(); } else { // finally give up $deferred.reject(error); } } /** * Make an AJAX request for the asset * @returns {XMLHttpRequest|XDomainRequest} Request object * @private */ function request() { return ajax.request(url, { success: function () { var retryAfter, req; if (!aborted) { req = this.rawRequest; // check status code for 202 if (this.status === 202 && util.isFn(req.getResponseHeader)) { // retry the request retryAfter = parseInt(req.getResponseHeader('retry-after')); if (retryAfter > 0) { setTimeout(request, retryAfter * 1000); return; } } if (this.responseText) { $deferred.resolve(this.responseText); } else { // the response was empty, so consider this a // failed request retryOrFail({ error: 'empty response', status: this.status, resource: url }); } } }, fail: function () { if (!aborted) { retryOrFail({ error: this.statusText, status: this.status, resource: url }); } } }); } req = request(); return $deferred.promise({ abort: function() { aborted = true; req.abort(); } }); }
[ "function", "(", "url", ",", "retries", ")", "{", "var", "req", ",", "aborted", "=", "false", ",", "ajax", "=", "this", ",", "$deferred", "=", "$", ".", "Deferred", "(", ")", ";", "function", "retryOrFail", "(", "error", ")", "{", "if", "(", "retries", ">", "0", ")", "{", "retries", "--", ";", "req", "=", "request", "(", ")", ";", "}", "else", "{", "$deferred", ".", "reject", "(", "error", ")", ";", "}", "}", "function", "request", "(", ")", "{", "return", "ajax", ".", "request", "(", "url", ",", "{", "success", ":", "function", "(", ")", "{", "var", "retryAfter", ",", "req", ";", "if", "(", "!", "aborted", ")", "{", "req", "=", "this", ".", "rawRequest", ";", "if", "(", "this", ".", "status", "===", "202", "&&", "util", ".", "isFn", "(", "req", ".", "getResponseHeader", ")", ")", "{", "retryAfter", "=", "parseInt", "(", "req", ".", "getResponseHeader", "(", "'retry-after'", ")", ")", ";", "if", "(", "retryAfter", ">", "0", ")", "{", "setTimeout", "(", "request", ",", "retryAfter", "*", "1000", ")", ";", "return", ";", "}", "}", "if", "(", "this", ".", "responseText", ")", "{", "$deferred", ".", "resolve", "(", "this", ".", "responseText", ")", ";", "}", "else", "{", "retryOrFail", "(", "{", "error", ":", "'empty response'", ",", "status", ":", "this", ".", "status", ",", "resource", ":", "url", "}", ")", ";", "}", "}", "}", ",", "fail", ":", "function", "(", ")", "{", "if", "(", "!", "aborted", ")", "{", "retryOrFail", "(", "{", "error", ":", "this", ".", "statusText", ",", "status", ":", "this", ".", "status", ",", "resource", ":", "url", "}", ")", ";", "}", "}", "}", ")", ";", "}", "req", "=", "request", "(", ")", ";", "return", "$deferred", ".", "promise", "(", "{", "abort", ":", "function", "(", ")", "{", "aborted", "=", "true", ";", "req", ".", "abort", "(", ")", ";", "}", "}", ")", ";", "}" ]
Fetch an asset, retrying if necessary @param {string} url A url for the desired asset @param {number} retries The number of times to retry if the request fails @returns {$.Promise} A promise with an additional abort() method that will abort the XHR request.
[ "Fetch", "an", "asset", "retrying", "if", "necessary" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1715-L1793
train
box/viewer.js
dist/crocodoc.viewer.js
request
function request() { return ajax.request(url, { success: function () { var retryAfter, req; if (!aborted) { req = this.rawRequest; // check status code for 202 if (this.status === 202 && util.isFn(req.getResponseHeader)) { // retry the request retryAfter = parseInt(req.getResponseHeader('retry-after')); if (retryAfter > 0) { setTimeout(request, retryAfter * 1000); return; } } if (this.responseText) { $deferred.resolve(this.responseText); } else { // the response was empty, so consider this a // failed request retryOrFail({ error: 'empty response', status: this.status, resource: url }); } } }, fail: function () { if (!aborted) { retryOrFail({ error: this.statusText, status: this.status, resource: url }); } } }); }
javascript
function request() { return ajax.request(url, { success: function () { var retryAfter, req; if (!aborted) { req = this.rawRequest; // check status code for 202 if (this.status === 202 && util.isFn(req.getResponseHeader)) { // retry the request retryAfter = parseInt(req.getResponseHeader('retry-after')); if (retryAfter > 0) { setTimeout(request, retryAfter * 1000); return; } } if (this.responseText) { $deferred.resolve(this.responseText); } else { // the response was empty, so consider this a // failed request retryOrFail({ error: 'empty response', status: this.status, resource: url }); } } }, fail: function () { if (!aborted) { retryOrFail({ error: this.statusText, status: this.status, resource: url }); } } }); }
[ "function", "request", "(", ")", "{", "return", "ajax", ".", "request", "(", "url", ",", "{", "success", ":", "function", "(", ")", "{", "var", "retryAfter", ",", "req", ";", "if", "(", "!", "aborted", ")", "{", "req", "=", "this", ".", "rawRequest", ";", "if", "(", "this", ".", "status", "===", "202", "&&", "util", ".", "isFn", "(", "req", ".", "getResponseHeader", ")", ")", "{", "retryAfter", "=", "parseInt", "(", "req", ".", "getResponseHeader", "(", "'retry-after'", ")", ")", ";", "if", "(", "retryAfter", ">", "0", ")", "{", "setTimeout", "(", "request", ",", "retryAfter", "*", "1000", ")", ";", "return", ";", "}", "}", "if", "(", "this", ".", "responseText", ")", "{", "$deferred", ".", "resolve", "(", "this", ".", "responseText", ")", ";", "}", "else", "{", "retryOrFail", "(", "{", "error", ":", "'empty response'", ",", "status", ":", "this", ".", "status", ",", "resource", ":", "url", "}", ")", ";", "}", "}", "}", ",", "fail", ":", "function", "(", ")", "{", "if", "(", "!", "aborted", ")", "{", "retryOrFail", "(", "{", "error", ":", "this", ".", "statusText", ",", "status", ":", "this", ".", "status", ",", "resource", ":", "url", "}", ")", ";", "}", "}", "}", ")", ";", "}" ]
Make an AJAX request for the asset @returns {XMLHttpRequest|XDomainRequest} Request object @private
[ "Make", "an", "AJAX", "request", "for", "the", "asset" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1744-L1784
train
box/viewer.js
dist/crocodoc.viewer.js
function (list, x, prop) { var val, mid, low = 0, high = list.length; while (low < high) { mid = Math.floor((low + high) / 2); val = prop ? list[mid][prop] : list[mid]; if (val < x) { low = mid + 1; } else { high = mid; } } return low; }
javascript
function (list, x, prop) { var val, mid, low = 0, high = list.length; while (low < high) { mid = Math.floor((low + high) / 2); val = prop ? list[mid][prop] : list[mid]; if (val < x) { low = mid + 1; } else { high = mid; } } return low; }
[ "function", "(", "list", ",", "x", ",", "prop", ")", "{", "var", "val", ",", "mid", ",", "low", "=", "0", ",", "high", "=", "list", ".", "length", ";", "while", "(", "low", "<", "high", ")", "{", "mid", "=", "Math", ".", "floor", "(", "(", "low", "+", "high", ")", "/", "2", ")", ";", "val", "=", "prop", "?", "list", "[", "mid", "]", "[", "prop", "]", ":", "list", "[", "mid", "]", ";", "if", "(", "val", "<", "x", ")", "{", "low", "=", "mid", "+", "1", ";", "}", "else", "{", "high", "=", "mid", ";", "}", "}", "return", "low", ";", "}" ]
Left bistect of list, optionally of property of objects in list @param {Array} list List of items to bisect @param {number} x The number to bisect against @param {string} [prop] Optional property to check on list items instead of using the item itself @returns {int} The index of the bisection
[ "Left", "bistect", "of", "list", "optionally", "of", "property", "of", "objects", "in", "list" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L1873-L1885
train
box/viewer.js
dist/crocodoc.viewer.js
function (wait, fn) { var context, args, timeout, result, previous = 0; function later () { previous = util.now(); timeout = null; result = fn.apply(context, args); } return function throttled() { var now = util.now(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = fn.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }
javascript
function (wait, fn) { var context, args, timeout, result, previous = 0; function later () { previous = util.now(); timeout = null; result = fn.apply(context, args); } return function throttled() { var now = util.now(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = fn.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }
[ "function", "(", "wait", ",", "fn", ")", "{", "var", "context", ",", "args", ",", "timeout", ",", "result", ",", "previous", "=", "0", ";", "function", "later", "(", ")", "{", "previous", "=", "util", ".", "now", "(", ")", ";", "timeout", "=", "null", ";", "result", "=", "fn", ".", "apply", "(", "context", ",", "args", ")", ";", "}", "return", "function", "throttled", "(", ")", "{", "var", "now", "=", "util", ".", "now", "(", ")", ",", "remaining", "=", "wait", "-", "(", "now", "-", "previous", ")", ";", "context", "=", "this", ";", "args", "=", "arguments", ";", "if", "(", "remaining", "<=", "0", ")", "{", "clearTimeout", "(", "timeout", ")", ";", "timeout", "=", "null", ";", "previous", "=", "now", ";", "result", "=", "fn", ".", "apply", "(", "context", ",", "args", ")", ";", "}", "else", "if", "(", "!", "timeout", ")", "{", "timeout", "=", "setTimeout", "(", "later", ",", "remaining", ")", ";", "}", "return", "result", ";", "}", ";", "}" ]
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds @param {int} wait Time to wait between calls in ms @param {Function} fn The function to throttle @returns {Function} The throttled function
[ "Creates", "and", "returns", "a", "new", "throttled", "version", "of", "the", "passed", "function", "that", "when", "invoked", "repeatedly", "will", "only", "actually", "call", "the", "original", "function", "at", "most", "once", "per", "every", "wait", "milliseconds" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2004-L2032
train
box/viewer.js
dist/crocodoc.viewer.js
function (wait, fn) { var context, args, timeout, timestamp, result; function later() { var last = util.now() - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = fn.apply(context, args); context = args = null; } } return function debounced() { context = this; args = arguments; timestamp = util.now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; }
javascript
function (wait, fn) { var context, args, timeout, timestamp, result; function later() { var last = util.now() - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = fn.apply(context, args); context = args = null; } } return function debounced() { context = this; args = arguments; timestamp = util.now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; }
[ "function", "(", "wait", ",", "fn", ")", "{", "var", "context", ",", "args", ",", "timeout", ",", "timestamp", ",", "result", ";", "function", "later", "(", ")", "{", "var", "last", "=", "util", ".", "now", "(", ")", "-", "timestamp", ";", "if", "(", "last", "<", "wait", ")", "{", "timeout", "=", "setTimeout", "(", "later", ",", "wait", "-", "last", ")", ";", "}", "else", "{", "timeout", "=", "null", ";", "result", "=", "fn", ".", "apply", "(", "context", ",", "args", ")", ";", "context", "=", "args", "=", "null", ";", "}", "}", "return", "function", "debounced", "(", ")", "{", "context", "=", "this", ";", "args", "=", "arguments", ";", "timestamp", "=", "util", ".", "now", "(", ")", ";", "if", "(", "!", "timeout", ")", "{", "timeout", "=", "setTimeout", "(", "later", ",", "wait", ")", ";", "}", "return", "result", ";", "}", ";", "}" ]
Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. @param {int} wait Time to wait between calls in ms @param {Function} fn The function to debounced @returns {Function} The debounced function
[ "Creates", "and", "returns", "a", "new", "debounced", "version", "of", "the", "passed", "function", "which", "will", "postpone", "its", "execution", "until", "after", "wait", "milliseconds", "have", "elapsed", "since", "the", "last", "time", "it", "was", "invoked", "." ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2042-L2069
train
box/viewer.js
dist/crocodoc.viewer.js
function (css) { var styleEl = document.createElement('style'), cssTextNode = document.createTextNode(css); try { styleEl.setAttribute('type', 'text/css'); styleEl.appendChild(cssTextNode); } catch (err) { // uhhh IE < 9 } document.getElementsByTagName('head')[0].appendChild(styleEl); return styleEl; }
javascript
function (css) { var styleEl = document.createElement('style'), cssTextNode = document.createTextNode(css); try { styleEl.setAttribute('type', 'text/css'); styleEl.appendChild(cssTextNode); } catch (err) { // uhhh IE < 9 } document.getElementsByTagName('head')[0].appendChild(styleEl); return styleEl; }
[ "function", "(", "css", ")", "{", "var", "styleEl", "=", "document", ".", "createElement", "(", "'style'", ")", ",", "cssTextNode", "=", "document", ".", "createTextNode", "(", "css", ")", ";", "try", "{", "styleEl", ".", "setAttribute", "(", "'type'", ",", "'text/css'", ")", ";", "styleEl", ".", "appendChild", "(", "cssTextNode", ")", ";", "}", "catch", "(", "err", ")", "{", "}", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ".", "appendChild", "(", "styleEl", ")", ";", "return", "styleEl", ";", "}" ]
Insert the given CSS string into the DOM and return the resulting DOMElement @param {string} css The CSS string to insert @returns {Element} The <style> element that was created and inserted
[ "Insert", "the", "given", "CSS", "string", "into", "the", "DOM", "and", "return", "the", "resulting", "DOMElement" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2076-L2087
train