id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
25,300
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'", ";", "// 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", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Rewrite the app registry file.
[ "Rewrite", "the", "app", "registry", "file", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L107-L125
25,301
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", ")", ";", "// 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", ";", "}", "}", ")", ";", "}" ]
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
25,302
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", "(", ")", "{", "// 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", ")", ")", ";", "}", ")", ";", "}" ]
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
25,303
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", ")", "{", "// 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", "]", "||", "[", "]", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Get app helped
[ "Get", "app", "helped" ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/app/registry.js#L190-L207
25,304
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", "(", ")", "{", "// 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", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
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
25,305
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", ";", "}", ")", ";", "}", "/*\n * Reload sites mutliple times, because sometimes updates to list of sites\n * aren't ready immediately.\n */", "// Reload sites immediately.", "reload", "(", ")", ";", "// Reload sites again after 5 seconds.", "setTimeout", "(", "reload", ",", "1000", "*", "5", ")", ";", "// Reload sites again after 15 seconds.", "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
25,306
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", ")", "{", "// 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", ")", ";", "}", ")", ";", "}", ";", "}" ]
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
25,307
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", ")", "{", "// 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", ")", ";", "}", "}" ]
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
25,308
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", ")", "{", "// 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", ")", ";", "}", "}" ]
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
25,309
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", ")", ")", "{", "// 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", ")", ";", "}", "}" ]
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
25,310
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", ")", "{", "// 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", ")", ";", "}", "}" ]
Recursively build list of lines.
[ "Recursively", "build", "list", "of", "lines", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/lib/core/tasks.js#L988-L1028
25,311
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", ")", "{", "// 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", ";", "}", "}" ]
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
25,312
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", "{", "// 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", ")", ";", "}", "}" ]
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
25,313
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", ")", "{", "// 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", ";", "}", "}" ]
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
25,314
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", ")", "{", "// 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", ";", "}", "}", ")", ";", "}" ]
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
25,315
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", "(", ")", "{", "// 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", "(", ")", ";", "}", "}", ")", ";", "}" ]
Recursive function.
[ "Recursive", "function", "." ]
c8d3e66fe33645e5973b138f4b8403f96abe90e8
https://github.com/kalabox/kalabox/blob/c8d3e66fe33645e5973b138f4b8403f96abe90e8/src/modules/guiEngine/recloop.js#L39-L62
25,316
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
25,317
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
25,318
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
25,319
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", "+", "'.'", ")", ";", "// `--update-head-ok` allows fetch on a branch with uncommited changes", "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
25,320
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
25,321
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 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", ")", ";", "}" ]
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
25,322
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 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", ")", ";", "}" ]
Tag local branch
[ "Tag", "local", "branch" ]
cd0086e2ffc613c683ff628c24bbfd2cc0b4c560
https://github.com/robwierzbowski/grunt-build-control/blob/cd0086e2ffc613c683ff628c24bbfd2cc0b4c560/tasks/build_control.js#L290-L299
25,323
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
25,324
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", ")", "{", "// 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", ";", "}" ]
Get the parent state
[ "Get", "the", "parent", "state" ]
301df6351f9272347ad3bd4b75f51a4d245dd2ef
https://github.com/ncuillery/angular-breadcrumb/blob/301df6351f9272347ad3bd4b75f51a4d245dd2ef/release/angular-breadcrumb.js#L61-L67
25,325
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", ")", ";", "// 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", ")", ";", "}", "}" ]
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
25,326
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", ")", "{", "// 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", ")", ";", "}" ]
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
25,327
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
25,328
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", ")", "===", "'/'", ")", "{", "// 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", ";", "}" ]
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
25,329
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
25,330
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
25,331
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", ";", "// 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", ";", "}" ]
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
25,332
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", ";", "// only catch errors", "log", ".", "warn", "(", "'chat fail'", ",", "err", ")", ";", "chat", ".", "err", "=", "err", ";", "// TODO error inbox/outbox", "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
25,333
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
25,334
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", ";", "// bottoms up, send older first", "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
25,335
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
25,336
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", ")", "{", "// 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", ";", "}" ]
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
25,337
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", ")", "{", "// 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", ")", ";", "}" ]
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
25,338
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", ")", ";", "// 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", ")", ";", "}", ")", ";", "}" ]
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
25,339
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", ";", "// 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", ";", "}" ]
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
25,340
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
25,341
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'", ")", ";", "// 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", "(", ")", ";", "}" ]
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
25,342
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", "[", "''", "]", ")", "{", "// 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", ";", "}" ]
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
25,343
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
25,344
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", ")", "{", "// 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", ")", ";", "}" ]
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
25,345
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", ")", "{", "// 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", "]", ";", "}" ]
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
25,346
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
25,347
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
25,348
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
25,349
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
25,350
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
25,351
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 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", ";", "}" ]
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
25,352
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", ")", "{", "// 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", "}", ")", ";", "}", "}" ]
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
25,353
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", ")", ";", "}", "/* Call custom callback */", "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
25,354
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", ")", "{", "// 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", "}", ";", "}" ]
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
25,355
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", "(", ")", "{", "// 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", ")", "}", ")", ";", "}" ]
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
25,356
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
25,357
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
25,358
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
25,359
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", "=", "[", "]", ";", "}", "// make sure this component won't cause a circular mixin dependency", "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
25,360
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
25,361
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
25,362
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
25,363
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
25,364
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", ",", "/**\n * Prevent the default action for this event\n * @returns {void}\n */", "preventDefault", ":", "function", "(", ")", "{", "isDefaultPrevented", "=", "true", ";", "}", ",", "/**\n * Return true if preventDefault() has been called on this event\n * @returns {Boolean}\n */", "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
25,365
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
25,366
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
25,367
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", ")", ";", "// @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", "}", ")", ";", "}" ]
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
25,368
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'", ")", ";", "}", "}", "// 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", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
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
25,369
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
25,370
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", ")", "{", "// 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", ";", "}" ]
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
25,371
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'", ")", ";", "// 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", ")", ";", "}", ")", ";", "}" ]
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
25,372
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
25,373
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", ";", "}", "// 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", ";", "}" ]
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
25,374
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", ")", ";", "// @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", "]", ";", "}" ]
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
25,375
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
25,376
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", ")", "{", "// @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", ";", "}" ]
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
25,377
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", ")", ";", "// @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", ";", "}" ]
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
25,378
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
25,379
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
25,380
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", ")", "{", "// 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", ";", "}" ]
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
25,381
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", ")", ";", "}", ";", "// 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", ";", "}" ]
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
25,382
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", "=", "''", ";", "}", "/**\n * Function to call on successful AJAX request\n * @returns {void}\n * @private\n */", "function", "ajaxSuccess", "(", "req", ")", "{", "if", "(", "util", ".", "isFn", "(", "opt", ".", "success", ")", ")", "{", "opt", ".", "success", ".", "call", "(", "createRequestWrapper", "(", "req", ")", ")", ";", "}", "return", "req", ";", "}", "/**\n * Function to call on failed AJAX request\n * @returns {void}\n * @private\n */", "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", ")", ";", "}", "}" ]
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
25,383
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
25,384
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
25,385
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", "(", ")", ";", "/**\n * If there are retries remaining, make another attempt, otherwise\n * give up and reject the deferred\n * @param {Object} error The error object\n * @returns {void}\n * @private\n */", "function", "retryOrFail", "(", "error", ")", "{", "if", "(", "retries", ">", "0", ")", "{", "// if we have retries remaining, make another request", "retries", "--", ";", "req", "=", "request", "(", ")", ";", "}", "else", "{", "// finally give up", "$deferred", ".", "reject", "(", "error", ")", ";", "}", "}", "/**\n * Make an AJAX request for the asset\n * @returns {XMLHttpRequest|XDomainRequest} Request object\n * @private\n */", "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", "(", ")", ";", "}", "}", ")", ";", "}" ]
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
25,386
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", ";", "// 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", "}", ")", ";", "}", "}", "}", ")", ";", "}" ]
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
25,387
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
25,388
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
25,389
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
25,390
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", ")", "{", "// uhhh IE < 9", "}", "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
25,391
box/viewer.js
dist/crocodoc.viewer.js
function (sheet, selector, rule) { var index; if (sheet.insertRule) { return sheet.insertRule(selector + '{' + rule + '}', sheet.cssRules.length); } else { index = sheet.addRule(selector, rule, sheet.rules.length); if (index < 0) { index = sheet.rules.length - 1; } return index; } }
javascript
function (sheet, selector, rule) { var index; if (sheet.insertRule) { return sheet.insertRule(selector + '{' + rule + '}', sheet.cssRules.length); } else { index = sheet.addRule(selector, rule, sheet.rules.length); if (index < 0) { index = sheet.rules.length - 1; } return index; } }
[ "function", "(", "sheet", ",", "selector", ",", "rule", ")", "{", "var", "index", ";", "if", "(", "sheet", ".", "insertRule", ")", "{", "return", "sheet", ".", "insertRule", "(", "selector", "+", "'{'", "+", "rule", "+", "'}'", ",", "sheet", ".", "cssRules", ".", "length", ")", ";", "}", "else", "{", "index", "=", "sheet", ".", "addRule", "(", "selector", ",", "rule", ",", "sheet", ".", "rules", ".", "length", ")", ";", "if", "(", "index", "<", "0", ")", "{", "index", "=", "sheet", ".", "rules", ".", "length", "-", "1", ";", "}", "return", "index", ";", "}", "}" ]
Append a CSS rule to the given stylesheet @param {CSSStyleSheet} sheet The stylesheet object @param {string} selector The selector @param {string} rule The rule @returns {int} The index of the new rule
[ "Append", "a", "CSS", "rule", "to", "the", "given", "stylesheet" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2096-L2107
25,392
box/viewer.js
dist/crocodoc.viewer.js
function () { var style, px, testSize = 10000, div = document.createElement('div'); div.style.display = 'block'; div.style.position = 'absolute'; div.style.width = testSize + 'pt'; document.body.appendChild(div); style = util.getComputedStyle(div); if (style && style.width) { px = parseFloat(style.width) / testSize; } else { // @NOTE: there is a bug in Firefox where `getComputedStyle()` // returns null if called in a hidden (`display:none`) iframe // (https://bugzilla.mozilla.org/show_bug.cgi?id=548397), so we // fallback to a default value if this happens. px = DEFAULT_PT2PX_RATIO; } document.body.removeChild(div); return px; }
javascript
function () { var style, px, testSize = 10000, div = document.createElement('div'); div.style.display = 'block'; div.style.position = 'absolute'; div.style.width = testSize + 'pt'; document.body.appendChild(div); style = util.getComputedStyle(div); if (style && style.width) { px = parseFloat(style.width) / testSize; } else { // @NOTE: there is a bug in Firefox where `getComputedStyle()` // returns null if called in a hidden (`display:none`) iframe // (https://bugzilla.mozilla.org/show_bug.cgi?id=548397), so we // fallback to a default value if this happens. px = DEFAULT_PT2PX_RATIO; } document.body.removeChild(div); return px; }
[ "function", "(", ")", "{", "var", "style", ",", "px", ",", "testSize", "=", "10000", ",", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "div", ".", "style", ".", "display", "=", "'block'", ";", "div", ".", "style", ".", "position", "=", "'absolute'", ";", "div", ".", "style", ".", "width", "=", "testSize", "+", "'pt'", ";", "document", ".", "body", ".", "appendChild", "(", "div", ")", ";", "style", "=", "util", ".", "getComputedStyle", "(", "div", ")", ";", "if", "(", "style", "&&", "style", ".", "width", ")", "{", "px", "=", "parseFloat", "(", "style", ".", "width", ")", "/", "testSize", ";", "}", "else", "{", "// @NOTE: there is a bug in Firefox where `getComputedStyle()`", "// returns null if called in a hidden (`display:none`) iframe", "// (https://bugzilla.mozilla.org/show_bug.cgi?id=548397), so we", "// fallback to a default value if this happens.", "px", "=", "DEFAULT_PT2PX_RATIO", ";", "}", "document", ".", "body", ".", "removeChild", "(", "div", ")", ";", "return", "px", ";", "}" ]
Calculates the size of 1pt in pixels @returns {number} The pixel value
[ "Calculates", "the", "size", "of", "1pt", "in", "pixels" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2161-L2182
25,393
box/viewer.js
dist/crocodoc.viewer.js
function (str, token) { var total = 0, i; while ((i = str.indexOf(token, i) + 1)) { total++; } return total; }
javascript
function (str, token) { var total = 0, i; while ((i = str.indexOf(token, i) + 1)) { total++; } return total; }
[ "function", "(", "str", ",", "token", ")", "{", "var", "total", "=", "0", ",", "i", ";", "while", "(", "(", "i", "=", "str", ".", "indexOf", "(", "token", ",", "i", ")", "+", "1", ")", ")", "{", "total", "++", ";", "}", "return", "total", ";", "}" ]
Count and return the number of occurrences of token in str @param {string} str The string to search @param {string} token The string to search for @returns {int} The number of occurrences
[ "Count", "and", "return", "the", "number", "of", "occurrences", "of", "token", "in", "str" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2190-L2196
25,394
box/viewer.js
dist/crocodoc.viewer.js
function (template, data) { var p; for (p in data) { if (data.hasOwnProperty(p)) { template = template.replace(new RegExp('\\{\\{' + p + '\\}\\}', 'g'), data[p]); } } return template; }
javascript
function (template, data) { var p; for (p in data) { if (data.hasOwnProperty(p)) { template = template.replace(new RegExp('\\{\\{' + p + '\\}\\}', 'g'), data[p]); } } return template; }
[ "function", "(", "template", ",", "data", ")", "{", "var", "p", ";", "for", "(", "p", "in", "data", ")", "{", "if", "(", "data", ".", "hasOwnProperty", "(", "p", ")", ")", "{", "template", "=", "template", ".", "replace", "(", "new", "RegExp", "(", "'\\\\{\\\\{'", "+", "p", "+", "'\\\\}\\\\}'", ",", "'g'", ")", ",", "data", "[", "p", "]", ")", ";", "}", "}", "return", "template", ";", "}" ]
Apply the given data to a template @param {string} template The template @param {Object} data The data to apply to the template @returns {string} The filled template
[ "Apply", "the", "given", "data", "to", "a", "template" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2204-L2212
25,395
box/viewer.js
dist/crocodoc.viewer.js
isSubpixelRenderingSupported
function isSubpixelRenderingSupported() { // Test if subpixel rendering is supported // @NOTE: jQuery.support.leadingWhitespace is apparently false if browser is IE6-8 if (!$.support.leadingWhitespace) { return false; } else { //span #1 - desired font-size: 12.5px var span = $(util.template(TEST_SPAN_TEMPLATE, { size: 12.5 })) .appendTo(document.documentElement).get(0); var fontsize1 = $(span).css('font-size'); var width1 = $(span).width(); $(span).remove(); //span #2 - desired font-size: 12.6px span = $(util.template(TEST_SPAN_TEMPLATE, { size: 12.6 })) .appendTo(document.documentElement).get(0); var fontsize2 = $(span).css('font-size'); var width2 = $(span).width(); $(span).remove(); // is not mobile device? // @NOTE(plai): Mobile WebKit supports subpixel rendering even though the browser fails the following tests. // @NOTE(plai): When modifying these tests, make sure that these tests will work even when the browser zoom is changed. // @TODO(plai): Find a better way of testing for mobile Safari. if (!('ontouchstart' in window)) { //font sizes are the same? (Chrome and Safari will fail this) if (fontsize1 === fontsize2) { return false; } //widths are the same? (Firefox on Windows without GPU will fail this) if (width1 === width2) { return false; } } } return true; }
javascript
function isSubpixelRenderingSupported() { // Test if subpixel rendering is supported // @NOTE: jQuery.support.leadingWhitespace is apparently false if browser is IE6-8 if (!$.support.leadingWhitespace) { return false; } else { //span #1 - desired font-size: 12.5px var span = $(util.template(TEST_SPAN_TEMPLATE, { size: 12.5 })) .appendTo(document.documentElement).get(0); var fontsize1 = $(span).css('font-size'); var width1 = $(span).width(); $(span).remove(); //span #2 - desired font-size: 12.6px span = $(util.template(TEST_SPAN_TEMPLATE, { size: 12.6 })) .appendTo(document.documentElement).get(0); var fontsize2 = $(span).css('font-size'); var width2 = $(span).width(); $(span).remove(); // is not mobile device? // @NOTE(plai): Mobile WebKit supports subpixel rendering even though the browser fails the following tests. // @NOTE(plai): When modifying these tests, make sure that these tests will work even when the browser zoom is changed. // @TODO(plai): Find a better way of testing for mobile Safari. if (!('ontouchstart' in window)) { //font sizes are the same? (Chrome and Safari will fail this) if (fontsize1 === fontsize2) { return false; } //widths are the same? (Firefox on Windows without GPU will fail this) if (width1 === width2) { return false; } } } return true; }
[ "function", "isSubpixelRenderingSupported", "(", ")", "{", "// Test if subpixel rendering is supported", "// @NOTE: jQuery.support.leadingWhitespace is apparently false if browser is IE6-8", "if", "(", "!", "$", ".", "support", ".", "leadingWhitespace", ")", "{", "return", "false", ";", "}", "else", "{", "//span #1 - desired font-size: 12.5px", "var", "span", "=", "$", "(", "util", ".", "template", "(", "TEST_SPAN_TEMPLATE", ",", "{", "size", ":", "12.5", "}", ")", ")", ".", "appendTo", "(", "document", ".", "documentElement", ")", ".", "get", "(", "0", ")", ";", "var", "fontsize1", "=", "$", "(", "span", ")", ".", "css", "(", "'font-size'", ")", ";", "var", "width1", "=", "$", "(", "span", ")", ".", "width", "(", ")", ";", "$", "(", "span", ")", ".", "remove", "(", ")", ";", "//span #2 - desired font-size: 12.6px", "span", "=", "$", "(", "util", ".", "template", "(", "TEST_SPAN_TEMPLATE", ",", "{", "size", ":", "12.6", "}", ")", ")", ".", "appendTo", "(", "document", ".", "documentElement", ")", ".", "get", "(", "0", ")", ";", "var", "fontsize2", "=", "$", "(", "span", ")", ".", "css", "(", "'font-size'", ")", ";", "var", "width2", "=", "$", "(", "span", ")", ".", "width", "(", ")", ";", "$", "(", "span", ")", ".", "remove", "(", ")", ";", "// is not mobile device?", "// @NOTE(plai): Mobile WebKit supports subpixel rendering even though the browser fails the following tests.", "// @NOTE(plai): When modifying these tests, make sure that these tests will work even when the browser zoom is changed.", "// @TODO(plai): Find a better way of testing for mobile Safari.", "if", "(", "!", "(", "'ontouchstart'", "in", "window", ")", ")", "{", "//font sizes are the same? (Chrome and Safari will fail this)", "if", "(", "fontsize1", "===", "fontsize2", ")", "{", "return", "false", ";", "}", "//widths are the same? (Firefox on Windows without GPU will fail this)", "if", "(", "width1", "===", "width2", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Return true if subpixel rendering is supported @returns {Boolean} @private
[ "Return", "true", "if", "subpixel", "rendering", "is", "supported" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2236-L2275
25,396
box/viewer.js
dist/crocodoc.viewer.js
function (el) { if (!subpixelRenderingIsSupported) { if (document.body.style.zoom !== undefined) { var $wrap = $('<div>').addClass(CSS_CLASS_SUBPX_FIX); $(el).wrap($wrap); } } return el; }
javascript
function (el) { if (!subpixelRenderingIsSupported) { if (document.body.style.zoom !== undefined) { var $wrap = $('<div>').addClass(CSS_CLASS_SUBPX_FIX); $(el).wrap($wrap); } } return el; }
[ "function", "(", "el", ")", "{", "if", "(", "!", "subpixelRenderingIsSupported", ")", "{", "if", "(", "document", ".", "body", ".", "style", ".", "zoom", "!==", "undefined", ")", "{", "var", "$wrap", "=", "$", "(", "'<div>'", ")", ".", "addClass", "(", "CSS_CLASS_SUBPX_FIX", ")", ";", "$", "(", "el", ")", ".", "wrap", "(", "$wrap", ")", ";", "}", "}", "return", "el", ";", "}" ]
Apply the subpixel rendering fix to the given element if necessary. @NOTE: Fix is only applied if the "zoom" CSS property exists (ie., this fix is never applied in Firefox) @param {Element} el The element @returns {Element} The element
[ "Apply", "the", "subpixel", "rendering", "fix", "to", "the", "given", "element", "if", "necessary", "." ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2291-L2299
25,397
box/viewer.js
dist/crocodoc.viewer.js
function (url) { var parsedURL = this.parse(url); if (!parsedLocation) { parsedLocation = this.parse(this.getCurrentURL()); } // IE7 does not properly parse relative URLs, so the hostname is empty if (!parsedURL.hostname) { return false; } return parsedURL.protocol !== parsedLocation.protocol || parsedURL.hostname !== parsedLocation.hostname || parsedURL.port !== parsedLocation.port; }
javascript
function (url) { var parsedURL = this.parse(url); if (!parsedLocation) { parsedLocation = this.parse(this.getCurrentURL()); } // IE7 does not properly parse relative URLs, so the hostname is empty if (!parsedURL.hostname) { return false; } return parsedURL.protocol !== parsedLocation.protocol || parsedURL.hostname !== parsedLocation.hostname || parsedURL.port !== parsedLocation.port; }
[ "function", "(", "url", ")", "{", "var", "parsedURL", "=", "this", ".", "parse", "(", "url", ")", ";", "if", "(", "!", "parsedLocation", ")", "{", "parsedLocation", "=", "this", ".", "parse", "(", "this", ".", "getCurrentURL", "(", ")", ")", ";", "}", "// IE7 does not properly parse relative URLs, so the hostname is empty", "if", "(", "!", "parsedURL", ".", "hostname", ")", "{", "return", "false", ";", "}", "return", "parsedURL", ".", "protocol", "!==", "parsedLocation", ".", "protocol", "||", "parsedURL", ".", "hostname", "!==", "parsedLocation", ".", "hostname", "||", "parsedURL", ".", "port", "!==", "parsedLocation", ".", "port", ";", "}" ]
Returns true if the given url is external to the current domain @param {string} url The URL @returns {Boolean} Whether or not the url is external
[ "Returns", "true", "if", "the", "given", "url", "is", "external", "to", "the", "current", "domain" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2465-L2480
25,398
box/viewer.js
dist/crocodoc.viewer.js
function (url) { var parsed = document.createElement('a'), pathname; parsed.href = url; // @NOTE: IE does not automatically parse relative urls, // but requesting href back from the <a> element will return // an absolute URL, which can then be fed back in to get the // expected result. WTF? Yep! if (browser.ie && url !== parsed.href) { url = parsed.href; parsed.href = url; } // @NOTE: IE does not include the preceding '/' in pathname pathname = parsed.pathname; if (!/^\//.test(pathname)) { pathname = '/' + pathname; } return { href: parsed.href, protocol: parsed.protocol, // includes : host: parsed.host, // includes port hostname: parsed.hostname, // does not include port port: parsed.port, pathname: pathname, hash: parsed.hash, // inclues # search: parsed.search // incudes ? }; }
javascript
function (url) { var parsed = document.createElement('a'), pathname; parsed.href = url; // @NOTE: IE does not automatically parse relative urls, // but requesting href back from the <a> element will return // an absolute URL, which can then be fed back in to get the // expected result. WTF? Yep! if (browser.ie && url !== parsed.href) { url = parsed.href; parsed.href = url; } // @NOTE: IE does not include the preceding '/' in pathname pathname = parsed.pathname; if (!/^\//.test(pathname)) { pathname = '/' + pathname; } return { href: parsed.href, protocol: parsed.protocol, // includes : host: parsed.host, // includes port hostname: parsed.hostname, // does not include port port: parsed.port, pathname: pathname, hash: parsed.hash, // inclues # search: parsed.search // incudes ? }; }
[ "function", "(", "url", ")", "{", "var", "parsed", "=", "document", ".", "createElement", "(", "'a'", ")", ",", "pathname", ";", "parsed", ".", "href", "=", "url", ";", "// @NOTE: IE does not automatically parse relative urls,", "// but requesting href back from the <a> element will return", "// an absolute URL, which can then be fed back in to get the", "// expected result. WTF? Yep!", "if", "(", "browser", ".", "ie", "&&", "url", "!==", "parsed", ".", "href", ")", "{", "url", "=", "parsed", ".", "href", ";", "parsed", ".", "href", "=", "url", ";", "}", "// @NOTE: IE does not include the preceding '/' in pathname", "pathname", "=", "parsed", ".", "pathname", ";", "if", "(", "!", "/", "^\\/", "/", ".", "test", "(", "pathname", ")", ")", "{", "pathname", "=", "'/'", "+", "pathname", ";", "}", "return", "{", "href", ":", "parsed", ".", "href", ",", "protocol", ":", "parsed", ".", "protocol", ",", "// includes :", "host", ":", "parsed", ".", "host", ",", "// includes port", "hostname", ":", "parsed", ".", "hostname", ",", "// does not include port", "port", ":", "parsed", ".", "port", ",", "pathname", ":", "pathname", ",", "hash", ":", "parsed", ".", "hash", ",", "// inclues #", "search", ":", "parsed", ".", "search", "// incudes ?", "}", ";", "}" ]
Parse a URL into protocol, host, port, etc @param {string} url The URL to parse @returns {object} The parsed URL parts
[ "Parse", "a", "URL", "into", "protocol", "host", "port", "etc" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2501-L2532
25,399
box/viewer.js
dist/crocodoc.viewer.js
validateConfig
function validateConfig() { var metadata = config.metadata; config.numPages = metadata.numpages; if (!config.pageStart) { config.pageStart = 1; } else if (config.pageStart < 0) { config.pageStart = metadata.numpages + config.pageStart; } config.pageStart = util.clamp(config.pageStart, 1, metadata.numpages); if (!config.pageEnd) { config.pageEnd = metadata.numpages; } else if (config.pageEnd < 0) { config.pageEnd = metadata.numpages + config.pageEnd; } config.pageEnd = util.clamp(config.pageEnd, config.pageStart, metadata.numpages); config.numPages = config.pageEnd - config.pageStart + 1; }
javascript
function validateConfig() { var metadata = config.metadata; config.numPages = metadata.numpages; if (!config.pageStart) { config.pageStart = 1; } else if (config.pageStart < 0) { config.pageStart = metadata.numpages + config.pageStart; } config.pageStart = util.clamp(config.pageStart, 1, metadata.numpages); if (!config.pageEnd) { config.pageEnd = metadata.numpages; } else if (config.pageEnd < 0) { config.pageEnd = metadata.numpages + config.pageEnd; } config.pageEnd = util.clamp(config.pageEnd, config.pageStart, metadata.numpages); config.numPages = config.pageEnd - config.pageStart + 1; }
[ "function", "validateConfig", "(", ")", "{", "var", "metadata", "=", "config", ".", "metadata", ";", "config", ".", "numPages", "=", "metadata", ".", "numpages", ";", "if", "(", "!", "config", ".", "pageStart", ")", "{", "config", ".", "pageStart", "=", "1", ";", "}", "else", "if", "(", "config", ".", "pageStart", "<", "0", ")", "{", "config", ".", "pageStart", "=", "metadata", ".", "numpages", "+", "config", ".", "pageStart", ";", "}", "config", ".", "pageStart", "=", "util", ".", "clamp", "(", "config", ".", "pageStart", ",", "1", ",", "metadata", ".", "numpages", ")", ";", "if", "(", "!", "config", ".", "pageEnd", ")", "{", "config", ".", "pageEnd", "=", "metadata", ".", "numpages", ";", "}", "else", "if", "(", "config", ".", "pageEnd", "<", "0", ")", "{", "config", ".", "pageEnd", "=", "metadata", ".", "numpages", "+", "config", ".", "pageEnd", ";", "}", "config", ".", "pageEnd", "=", "util", ".", "clamp", "(", "config", ".", "pageEnd", ",", "config", ".", "pageStart", ",", "metadata", ".", "numpages", ")", ";", "config", ".", "numPages", "=", "config", ".", "pageEnd", "-", "config", ".", "pageStart", "+", "1", ";", "}" ]
Validates the config options @returns {void} @private
[ "Validates", "the", "config", "options" ]
7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17
https://github.com/box/viewer.js/blob/7d11f2e4b01ef418aeb76efe2c2e5f08950f7c17/dist/crocodoc.viewer.js#L2555-L2571