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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
5,200
catapult-project/catapult
third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js
setupBindings
function setupBindings(inst, templateInfo) { // Setup compound storage, dataHost, and notify listeners let {nodeList, nodeInfoList} = templateInfo; if (nodeInfoList.length) { for (let i=0; i < nodeInfoList.length; i++) { let info = nodeInfoList[i]; let node = nodeList[i]; let bindings = info.bindings; if (bindings) { for (let i=0; i<bindings.length; i++) { let binding = bindings[i]; setupCompoundStorage(node, binding); addNotifyListener(node, inst, binding); } } node.__dataHost = inst; } } }
javascript
function setupBindings(inst, templateInfo) { // Setup compound storage, dataHost, and notify listeners let {nodeList, nodeInfoList} = templateInfo; if (nodeInfoList.length) { for (let i=0; i < nodeInfoList.length; i++) { let info = nodeInfoList[i]; let node = nodeList[i]; let bindings = info.bindings; if (bindings) { for (let i=0; i<bindings.length; i++) { let binding = bindings[i]; setupCompoundStorage(node, binding); addNotifyListener(node, inst, binding); } } node.__dataHost = inst; } } }
[ "function", "setupBindings", "(", "inst", ",", "templateInfo", ")", "{", "// Setup compound storage, dataHost, and notify listeners", "let", "{", "nodeList", ",", "nodeInfoList", "}", "=", "templateInfo", ";", "if", "(", "nodeInfoList", ".", "length", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "nodeInfoList", ".", "length", ";", "i", "++", ")", "{", "let", "info", "=", "nodeInfoList", "[", "i", "]", ";", "let", "node", "=", "nodeList", "[", "i", "]", ";", "let", "bindings", "=", "info", ".", "bindings", ";", "if", "(", "bindings", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "bindings", ".", "length", ";", "i", "++", ")", "{", "let", "binding", "=", "bindings", "[", "i", "]", ";", "setupCompoundStorage", "(", "node", ",", "binding", ")", ";", "addNotifyListener", "(", "node", ",", "inst", ",", "binding", ")", ";", "}", "}", "node", ".", "__dataHost", "=", "inst", ";", "}", "}", "}" ]
Setup compound binding storage structures, notify listeners, and dataHost references onto the bound nodeList. @param {!PropertyEffectsType} inst Instance that bas been previously bound @param {TemplateInfo} templateInfo Template metadata @return {void} @private
[ "Setup", "compound", "binding", "storage", "structures", "notify", "listeners", "and", "dataHost", "references", "onto", "the", "bound", "nodeList", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js#L678-L696
5,201
catapult-project/catapult
third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js
addNotifyListener
function addNotifyListener(node, inst, binding) { if (binding.listenerEvent) { let part = binding.parts[0]; node.addEventListener(binding.listenerEvent, function(e) { handleNotification(e, inst, binding.target, part.source, part.negate); }); } }
javascript
function addNotifyListener(node, inst, binding) { if (binding.listenerEvent) { let part = binding.parts[0]; node.addEventListener(binding.listenerEvent, function(e) { handleNotification(e, inst, binding.target, part.source, part.negate); }); } }
[ "function", "addNotifyListener", "(", "node", ",", "inst", ",", "binding", ")", "{", "if", "(", "binding", ".", "listenerEvent", ")", "{", "let", "part", "=", "binding", ".", "parts", "[", "0", "]", ";", "node", ".", "addEventListener", "(", "binding", ".", "listenerEvent", ",", "function", "(", "e", ")", "{", "handleNotification", "(", "e", ",", "inst", ",", "binding", ".", "target", ",", "part", ".", "source", ",", "part", ".", "negate", ")", ";", "}", ")", ";", "}", "}" ]
Adds a 2-way binding notification event listener to the node specified @param {Object} node Child element to add listener to @param {!PropertyEffectsType} inst Host element instance to handle notification event @param {Binding} binding Binding metadata @return {void} @private
[ "Adds", "a", "2", "-", "way", "binding", "notification", "event", "listener", "to", "the", "node", "specified" ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js#L741-L748
5,202
catapult-project/catapult
third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js
runMethodEffect
function runMethodEffect(inst, property, props, oldProps, info) { // Instances can optionally have a _methodHost which allows redirecting where // to find methods. Currently used by `templatize`. let context = inst._methodHost || inst; let fn = context[info.methodName]; if (fn) { let args = marshalArgs(inst.__data, info.args, property, props); return fn.apply(context, args); } else if (!info.dynamicFn) { console.warn('method `' + info.methodName + '` not defined'); } }
javascript
function runMethodEffect(inst, property, props, oldProps, info) { // Instances can optionally have a _methodHost which allows redirecting where // to find methods. Currently used by `templatize`. let context = inst._methodHost || inst; let fn = context[info.methodName]; if (fn) { let args = marshalArgs(inst.__data, info.args, property, props); return fn.apply(context, args); } else if (!info.dynamicFn) { console.warn('method `' + info.methodName + '` not defined'); } }
[ "function", "runMethodEffect", "(", "inst", ",", "property", ",", "props", ",", "oldProps", ",", "info", ")", "{", "// Instances can optionally have a _methodHost which allows redirecting where", "// to find methods. Currently used by `templatize`.", "let", "context", "=", "inst", ".", "_methodHost", "||", "inst", ";", "let", "fn", "=", "context", "[", "info", ".", "methodName", "]", ";", "if", "(", "fn", ")", "{", "let", "args", "=", "marshalArgs", "(", "inst", ".", "__data", ",", "info", ".", "args", ",", "property", ",", "props", ")", ";", "return", "fn", ".", "apply", "(", "context", ",", "args", ")", ";", "}", "else", "if", "(", "!", "info", ".", "dynamicFn", ")", "{", "console", ".", "warn", "(", "'method `'", "+", "info", ".", "methodName", "+", "'` not defined'", ")", ";", "}", "}" ]
Calls a method with arguments marshaled from properties on the instance based on the method signature contained in the effect metadata. Multi-property observers, computed properties, and inline computing functions call this function to invoke the method, then use the return value accordingly. @param {!PropertyEffectsType} inst The instance the effect will be run on @param {string} property Name of property @param {Object} props Bag of current property changes @param {Object} oldProps Bag of previous values for changed properties @param {?} info Effect metadata @return {*} Returns the return value from the method invocation @private
[ "Calls", "a", "method", "with", "arguments", "marshaled", "from", "properties", "on", "the", "instance", "based", "on", "the", "method", "signature", "contained", "in", "the", "effect", "metadata", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js#L808-L819
5,203
catapult-project/catapult
third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js
literalFromParts
function literalFromParts(parts) { let s = ''; for (let i=0; i<parts.length; i++) { let literal = parts[i].literal; s += literal || ''; } return s; }
javascript
function literalFromParts(parts) { let s = ''; for (let i=0; i<parts.length; i++) { let literal = parts[i].literal; s += literal || ''; } return s; }
[ "function", "literalFromParts", "(", "parts", ")", "{", "let", "s", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "let", "literal", "=", "parts", "[", "i", "]", ".", "literal", ";", "s", "+=", "literal", "||", "''", ";", "}", "return", "s", ";", "}" ]
Create a string from binding parts of all the literal parts @param {!Array<BindingPart>} parts All parts to stringify @return {string} String made from the literal parts
[ "Create", "a", "string", "from", "binding", "parts", "of", "all", "the", "literal", "parts" ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js#L847-L854
5,204
catapult-project/catapult
third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js
parseArgs
function parseArgs(argList, sig) { sig.args = argList.map(function(rawArg) { let arg = parseArg(rawArg); if (!arg.literal) { sig.static = false; } return arg; }, this); return sig; }
javascript
function parseArgs(argList, sig) { sig.args = argList.map(function(rawArg) { let arg = parseArg(rawArg); if (!arg.literal) { sig.static = false; } return arg; }, this); return sig; }
[ "function", "parseArgs", "(", "argList", ",", "sig", ")", "{", "sig", ".", "args", "=", "argList", ".", "map", "(", "function", "(", "rawArg", ")", "{", "let", "arg", "=", "parseArg", "(", "rawArg", ")", ";", "if", "(", "!", "arg", ".", "literal", ")", "{", "sig", ".", "static", "=", "false", ";", "}", "return", "arg", ";", "}", ",", "this", ")", ";", "return", "sig", ";", "}" ]
Parses an array of arguments and sets the `args` property of the supplied signature metadata object. Sets the `static` property to false if any argument is a non-literal. @param {!Array<string>} argList Array of argument names @param {!MethodSignature} sig Method signature metadata object @return {!MethodSignature} The updated signature metadata object @private
[ "Parses", "an", "array", "of", "arguments", "and", "sets", "the", "args", "property", "of", "the", "supplied", "signature", "metadata", "object", ".", "Sets", "the", "static", "property", "to", "false", "if", "any", "argument", "is", "a", "non", "-", "literal", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js#L893-L902
5,205
catapult-project/catapult
third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js
marshalArgs
function marshalArgs(data, args, path, props) { let values = []; for (let i=0, l=args.length; i<l; i++) { let arg = args[i]; let name = arg.name; let v; if (arg.literal) { v = arg.value; } else { if (arg.structured) { v = get$0(data, name); // when data is not stored e.g. `splices` if (v === undefined) { v = props[name]; } } else { v = data[name]; } } if (arg.wildcard) { // Only send the actual path changed info if the change that // caused the observer to run matched the wildcard let baseChanged = (name.indexOf(path + '.') === 0); let matches = (path.indexOf(name) === 0 && !baseChanged); values[i] = { path: matches ? path : name, value: matches ? props[path] : v, base: v }; } else { values[i] = v; } } return values; }
javascript
function marshalArgs(data, args, path, props) { let values = []; for (let i=0, l=args.length; i<l; i++) { let arg = args[i]; let name = arg.name; let v; if (arg.literal) { v = arg.value; } else { if (arg.structured) { v = get$0(data, name); // when data is not stored e.g. `splices` if (v === undefined) { v = props[name]; } } else { v = data[name]; } } if (arg.wildcard) { // Only send the actual path changed info if the change that // caused the observer to run matched the wildcard let baseChanged = (name.indexOf(path + '.') === 0); let matches = (path.indexOf(name) === 0 && !baseChanged); values[i] = { path: matches ? path : name, value: matches ? props[path] : v, base: v }; } else { values[i] = v; } } return values; }
[ "function", "marshalArgs", "(", "data", ",", "args", ",", "path", ",", "props", ")", "{", "let", "values", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "l", "=", "args", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "let", "arg", "=", "args", "[", "i", "]", ";", "let", "name", "=", "arg", ".", "name", ";", "let", "v", ";", "if", "(", "arg", ".", "literal", ")", "{", "v", "=", "arg", ".", "value", ";", "}", "else", "{", "if", "(", "arg", ".", "structured", ")", "{", "v", "=", "get$0", "(", "data", ",", "name", ")", ";", "// when data is not stored e.g. `splices`", "if", "(", "v", "===", "undefined", ")", "{", "v", "=", "props", "[", "name", "]", ";", "}", "}", "else", "{", "v", "=", "data", "[", "name", "]", ";", "}", "}", "if", "(", "arg", ".", "wildcard", ")", "{", "// Only send the actual path changed info if the change that", "// caused the observer to run matched the wildcard", "let", "baseChanged", "=", "(", "name", ".", "indexOf", "(", "path", "+", "'.'", ")", "===", "0", ")", ";", "let", "matches", "=", "(", "path", ".", "indexOf", "(", "name", ")", "===", "0", "&&", "!", "baseChanged", ")", ";", "values", "[", "i", "]", "=", "{", "path", ":", "matches", "?", "path", ":", "name", ",", "value", ":", "matches", "?", "props", "[", "path", "]", ":", "v", ",", "base", ":", "v", "}", ";", "}", "else", "{", "values", "[", "i", "]", "=", "v", ";", "}", "}", "return", "values", ";", "}" ]
Gather the argument values for a method specified in the provided array of argument metadata. The `path` and `value` arguments are used to fill in wildcard descriptor when the method is being called as a result of a path notification. @param {Object} data Instance data storage object to read properties from @param {!Array<!MethodArg>} args Array of argument metadata @param {string} path Property/path name that triggered the method effect @param {Object} props Bag of current property changes @return {Array<*>} Array of argument values @private
[ "Gather", "the", "argument", "values", "for", "a", "method", "specified", "in", "the", "provided", "array", "of", "argument", "metadata", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js#L984-L1018
5,206
catapult-project/catapult
third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js
notifySplice
function notifySplice(inst, array, path, index, addedCount, removed) { notifySplices(inst, array, path, [{ index: index, addedCount: addedCount, removed: removed, object: array, type: 'splice' }]); }
javascript
function notifySplice(inst, array, path, index, addedCount, removed) { notifySplices(inst, array, path, [{ index: index, addedCount: addedCount, removed: removed, object: array, type: 'splice' }]); }
[ "function", "notifySplice", "(", "inst", ",", "array", ",", "path", ",", "index", ",", "addedCount", ",", "removed", ")", "{", "notifySplices", "(", "inst", ",", "array", ",", "path", ",", "[", "{", "index", ":", "index", ",", "addedCount", ":", "addedCount", ",", "removed", ":", "removed", ",", "object", ":", "array", ",", "type", ":", "'splice'", "}", "]", ")", ";", "}" ]
Creates a splice record and sends an array splice notification for the described mutation Note: this implementation only accepts normalized paths @param {!PropertyEffectsType} inst Instance to send notifications to @param {Array} array The array the mutations occurred on @param {string} path The path to the array that was mutated @param {number} index Index at which the array mutation occurred @param {number} addedCount Number of added items @param {Array} removed Array of removed items @return {void} @private
[ "Creates", "a", "splice", "record", "and", "sends", "an", "array", "splice", "notification", "for", "the", "described", "mutation" ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer3/bower_components/polymer/lib/mixins/property-effects.js#L1057-L1065
5,207
catapult-project/catapult
experimental/perf_sheriffing_emailer/api_access.js
getService
function getService(privateKeyDetails) { return OAuth2.createService('PerfDash:' + Session.getActiveUser().getEmail()) // Set the endpoint URL. .setTokenUrl('https://accounts.google.com/o/oauth2/token') // Set the private key and issuer. .setPrivateKey(privateKeyDetails['private_key']) .setIssuer(privateKeyDetails['client_email']) // Set the property store where authorized tokens should be persisted. .setPropertyStore(PropertiesService.getScriptProperties()) // Set the scope. This must match one of the scopes configured during the // setup of domain-wide delegation. .setScope('https://www.googleapis.com/auth/userinfo.email'); }
javascript
function getService(privateKeyDetails) { return OAuth2.createService('PerfDash:' + Session.getActiveUser().getEmail()) // Set the endpoint URL. .setTokenUrl('https://accounts.google.com/o/oauth2/token') // Set the private key and issuer. .setPrivateKey(privateKeyDetails['private_key']) .setIssuer(privateKeyDetails['client_email']) // Set the property store where authorized tokens should be persisted. .setPropertyStore(PropertiesService.getScriptProperties()) // Set the scope. This must match one of the scopes configured during the // setup of domain-wide delegation. .setScope('https://www.googleapis.com/auth/userinfo.email'); }
[ "function", "getService", "(", "privateKeyDetails", ")", "{", "return", "OAuth2", ".", "createService", "(", "'PerfDash:'", "+", "Session", ".", "getActiveUser", "(", ")", ".", "getEmail", "(", ")", ")", "// Set the endpoint URL.", ".", "setTokenUrl", "(", "'https://accounts.google.com/o/oauth2/token'", ")", "// Set the private key and issuer.", ".", "setPrivateKey", "(", "privateKeyDetails", "[", "'private_key'", "]", ")", ".", "setIssuer", "(", "privateKeyDetails", "[", "'client_email'", "]", ")", "// Set the property store where authorized tokens should be persisted.", ".", "setPropertyStore", "(", "PropertiesService", ".", "getScriptProperties", "(", ")", ")", "// Set the scope. This must match one of the scopes configured during the", "// setup of domain-wide delegation.", ".", "setScope", "(", "'https://www.googleapis.com/auth/userinfo.email'", ")", ";", "}" ]
Configures the service. @param {Object} privateKeyDetails Dict with private key and client email.
[ "Configures", "the", "service", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/experimental/perf_sheriffing_emailer/api_access.js#L43-L58
5,208
catapult-project/catapult
experimental/perf_sheriffing_emailer/api_access.js
getPrivateKeyDetailsFromDriveFile
function getPrivateKeyDetailsFromDriveFile(driveFileId) { var file = DriveApp.getFileById(driveFileId); return JSON.parse(file.getAs('application/json').getDataAsString()); }
javascript
function getPrivateKeyDetailsFromDriveFile(driveFileId) { var file = DriveApp.getFileById(driveFileId); return JSON.parse(file.getAs('application/json').getDataAsString()); }
[ "function", "getPrivateKeyDetailsFromDriveFile", "(", "driveFileId", ")", "{", "var", "file", "=", "DriveApp", ".", "getFileById", "(", "driveFileId", ")", ";", "return", "JSON", ".", "parse", "(", "file", ".", "getAs", "(", "'application/json'", ")", ".", "getDataAsString", "(", ")", ")", ";", "}" ]
Parse the private key details from a file stored in Google Drive. @param {string} driveFileId The id of the file in drive to parse.
[ "Parse", "the", "private", "key", "details", "from", "a", "file", "stored", "in", "Google", "Drive", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/experimental/perf_sheriffing_emailer/api_access.js#L64-L67
5,209
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
writeHexString
function writeHexString(bytes, out) { function byteToPaddedHex(b) { let str = b.toString(16).toUpperCase(); if (str.length < 2) { str = '0' + str; } return str; } const kBytesPerLine = 16; // Returns pretty printed kBytesPerLine bytes starting from // bytes[startIndex], in hexdump style format. function formatLine(startIndex) { let result = ' '; // Append a hex formatting of |bytes|. for (let i = 0; i < kBytesPerLine; ++i) { result += ' '; // Add a separator every 8 bytes. if ((i % 8) === 0) { result += ' '; } // Output hex for the byte, or space if no bytes remain. const byteIndex = startIndex + i; if (byteIndex < bytes.length) { result += byteToPaddedHex(bytes[byteIndex]); } else { result += ' '; } } result += ' '; // Append an ASCII formatting of the bytes, where ASCII codes 32 // though 126 display the corresponding characters, nulls are // represented by spaces, and any other character is represented // by a period. for (let i = 0; i < kBytesPerLine; ++i) { const byteIndex = startIndex + i; if (byteIndex >= bytes.length) { break; } const curByte = bytes[byteIndex]; if (curByte >= 0x20 && curByte <= 0x7E) { result += String.fromCharCode(curByte); } else if (curByte === 0x00) { result += ' '; } else { result += '.'; } } return result; } // Output lines for each group of kBytesPerLine bytes. for (let i = 0; i < bytes.length; i += kBytesPerLine) { out.writeLine(formatLine(i)); } }
javascript
function writeHexString(bytes, out) { function byteToPaddedHex(b) { let str = b.toString(16).toUpperCase(); if (str.length < 2) { str = '0' + str; } return str; } const kBytesPerLine = 16; // Returns pretty printed kBytesPerLine bytes starting from // bytes[startIndex], in hexdump style format. function formatLine(startIndex) { let result = ' '; // Append a hex formatting of |bytes|. for (let i = 0; i < kBytesPerLine; ++i) { result += ' '; // Add a separator every 8 bytes. if ((i % 8) === 0) { result += ' '; } // Output hex for the byte, or space if no bytes remain. const byteIndex = startIndex + i; if (byteIndex < bytes.length) { result += byteToPaddedHex(bytes[byteIndex]); } else { result += ' '; } } result += ' '; // Append an ASCII formatting of the bytes, where ASCII codes 32 // though 126 display the corresponding characters, nulls are // represented by spaces, and any other character is represented // by a period. for (let i = 0; i < kBytesPerLine; ++i) { const byteIndex = startIndex + i; if (byteIndex >= bytes.length) { break; } const curByte = bytes[byteIndex]; if (curByte >= 0x20 && curByte <= 0x7E) { result += String.fromCharCode(curByte); } else if (curByte === 0x00) { result += ' '; } else { result += '.'; } } return result; } // Output lines for each group of kBytesPerLine bytes. for (let i = 0; i < bytes.length; i += kBytesPerLine) { out.writeLine(formatLine(i)); } }
[ "function", "writeHexString", "(", "bytes", ",", "out", ")", "{", "function", "byteToPaddedHex", "(", "b", ")", "{", "let", "str", "=", "b", ".", "toString", "(", "16", ")", ".", "toUpperCase", "(", ")", ";", "if", "(", "str", ".", "length", "<", "2", ")", "{", "str", "=", "'0'", "+", "str", ";", "}", "return", "str", ";", "}", "const", "kBytesPerLine", "=", "16", ";", "// Returns pretty printed kBytesPerLine bytes starting from", "// bytes[startIndex], in hexdump style format.", "function", "formatLine", "(", "startIndex", ")", "{", "let", "result", "=", "' '", ";", "// Append a hex formatting of |bytes|.", "for", "(", "let", "i", "=", "0", ";", "i", "<", "kBytesPerLine", ";", "++", "i", ")", "{", "result", "+=", "' '", ";", "// Add a separator every 8 bytes.", "if", "(", "(", "i", "%", "8", ")", "===", "0", ")", "{", "result", "+=", "' '", ";", "}", "// Output hex for the byte, or space if no bytes remain.", "const", "byteIndex", "=", "startIndex", "+", "i", ";", "if", "(", "byteIndex", "<", "bytes", ".", "length", ")", "{", "result", "+=", "byteToPaddedHex", "(", "bytes", "[", "byteIndex", "]", ")", ";", "}", "else", "{", "result", "+=", "' '", ";", "}", "}", "result", "+=", "' '", ";", "// Append an ASCII formatting of the bytes, where ASCII codes 32", "// though 126 display the corresponding characters, nulls are", "// represented by spaces, and any other character is represented", "// by a period.", "for", "(", "let", "i", "=", "0", ";", "i", "<", "kBytesPerLine", ";", "++", "i", ")", "{", "const", "byteIndex", "=", "startIndex", "+", "i", ";", "if", "(", "byteIndex", ">=", "bytes", ".", "length", ")", "{", "break", ";", "}", "const", "curByte", "=", "bytes", "[", "byteIndex", "]", ";", "if", "(", "curByte", ">=", "0x20", "&&", "curByte", "<=", "0x7E", ")", "{", "result", "+=", "String", ".", "fromCharCode", "(", "curByte", ")", ";", "}", "else", "if", "(", "curByte", "===", "0x00", ")", "{", "result", "+=", "' '", ";", "}", "else", "{", "result", "+=", "'.'", ";", "}", "}", "return", "result", ";", "}", "// Output lines for each group of kBytesPerLine bytes.", "for", "(", "let", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "+=", "kBytesPerLine", ")", "{", "out", ".", "writeLine", "(", "formatLine", "(", "i", ")", ")", ";", "}", "}" ]
|bytes| must be an array-like object of bytes. Writes multiple lines to |out| with the hexadecimal characters from |bytes| on the left, in groups of two, and their corresponding ASCII characters on the right. 16 bytes will be placed on each line of the output string, split into two columns of 8.
[ "|bytes|", "must", "be", "an", "array", "-", "like", "object", "of", "bytes", ".", "Writes", "multiple", "lines", "to", "|out|", "with", "the", "hexadecimal", "characters", "from", "|bytes|", "on", "the", "left", "in", "groups", "of", "two", "and", "their", "corresponding", "ASCII", "characters", "on", "the", "right", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L123-L186
5,210
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
writeParameters
function writeParameters(entry, out) { // If headers are in an object, convert them to an array for better // display. entry = reformatHeaders(entry); // Use any parameter writer available for this event type. const paramsWriter = getParameterWriterForEventType(entry.type); const consumedParams = {}; if (paramsWriter) { paramsWriter(entry, out, consumedParams); } // Write any un-consumed parameters. for (const k in entry.params) { if (consumedParams[k]) { continue; } defaultWriteParameter(k, entry.params[k], out); } }
javascript
function writeParameters(entry, out) { // If headers are in an object, convert them to an array for better // display. entry = reformatHeaders(entry); // Use any parameter writer available for this event type. const paramsWriter = getParameterWriterForEventType(entry.type); const consumedParams = {}; if (paramsWriter) { paramsWriter(entry, out, consumedParams); } // Write any un-consumed parameters. for (const k in entry.params) { if (consumedParams[k]) { continue; } defaultWriteParameter(k, entry.params[k], out); } }
[ "function", "writeParameters", "(", "entry", ",", "out", ")", "{", "// If headers are in an object, convert them to an array for better", "// display.", "entry", "=", "reformatHeaders", "(", "entry", ")", ";", "// Use any parameter writer available for this event type.", "const", "paramsWriter", "=", "getParameterWriterForEventType", "(", "entry", ".", "type", ")", ";", "const", "consumedParams", "=", "{", "}", ";", "if", "(", "paramsWriter", ")", "{", "paramsWriter", "(", "entry", ",", "out", ",", "consumedParams", ")", ";", "}", "// Write any un-consumed parameters.", "for", "(", "const", "k", "in", "entry", ".", "params", ")", "{", "if", "(", "consumedParams", "[", "k", "]", ")", "{", "continue", ";", "}", "defaultWriteParameter", "(", "k", ",", "entry", ".", "params", "[", "k", "]", ",", "out", ")", ";", "}", "}" ]
Formats the parameters for |entry| and writes them to |out|. Certain event types have custom pretty printers. Everything else will default to a JSON-like format.
[ "Formats", "the", "parameters", "for", "|entry|", "and", "writes", "them", "to", "|out|", ".", "Certain", "event", "types", "have", "custom", "pretty", "printers", ".", "Everything", "else", "will", "default", "to", "a", "JSON", "-", "like", "format", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L275-L294
5,211
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
getParameterWriterForEventType
function getParameterWriterForEventType(eventType) { switch (eventType) { case EventType.HTTP_TRANSACTION_SEND_REQUEST_HEADERS: case EventType.HTTP_TRANSACTION_SEND_TUNNEL_HEADERS: case EventType.TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS: return writeParamsForRequestHeaders; case EventType.PROXY_CONFIG_CHANGED: return writeParamsForProxyConfigChanged; case EventType.CERT_VERIFIER_JOB: case EventType.SSL_CERTIFICATES_RECEIVED: return writeParamsForCertificates; case EventType.CERT_CT_COMPLIANCE_CHECKED: case EventType.EV_CERT_CT_COMPLIANCE_CHECKED: return writeParamsForCheckedCertificates; } return null; }
javascript
function getParameterWriterForEventType(eventType) { switch (eventType) { case EventType.HTTP_TRANSACTION_SEND_REQUEST_HEADERS: case EventType.HTTP_TRANSACTION_SEND_TUNNEL_HEADERS: case EventType.TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS: return writeParamsForRequestHeaders; case EventType.PROXY_CONFIG_CHANGED: return writeParamsForProxyConfigChanged; case EventType.CERT_VERIFIER_JOB: case EventType.SSL_CERTIFICATES_RECEIVED: return writeParamsForCertificates; case EventType.CERT_CT_COMPLIANCE_CHECKED: case EventType.EV_CERT_CT_COMPLIANCE_CHECKED: return writeParamsForCheckedCertificates; } return null; }
[ "function", "getParameterWriterForEventType", "(", "eventType", ")", "{", "switch", "(", "eventType", ")", "{", "case", "EventType", ".", "HTTP_TRANSACTION_SEND_REQUEST_HEADERS", ":", "case", "EventType", ".", "HTTP_TRANSACTION_SEND_TUNNEL_HEADERS", ":", "case", "EventType", ".", "TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS", ":", "return", "writeParamsForRequestHeaders", ";", "case", "EventType", ".", "PROXY_CONFIG_CHANGED", ":", "return", "writeParamsForProxyConfigChanged", ";", "case", "EventType", ".", "CERT_VERIFIER_JOB", ":", "case", "EventType", ".", "SSL_CERTIFICATES_RECEIVED", ":", "return", "writeParamsForCertificates", ";", "case", "EventType", ".", "CERT_CT_COMPLIANCE_CHECKED", ":", "case", "EventType", ".", "EV_CERT_CT_COMPLIANCE_CHECKED", ":", "return", "writeParamsForCheckedCertificates", ";", "}", "return", "null", ";", "}" ]
Finds a writer to format the parameters for events of type |eventType|. @return {function} The returned function "writer" can be invoked as |writer(entry, writer, consumedParams)|. It will output the parameters of |entry| to |out|, and fill |consumedParams| with the keys of the parameters consumed. If no writer is available for |eventType| then returns null.
[ "Finds", "a", "writer", "to", "format", "the", "parameters", "for", "events", "of", "type", "|eventType|", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L306-L324
5,212
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
tryParseHexToBytes
function tryParseHexToBytes(hexStr) { if ((hexStr.length % 2) !== 0) { return null; } const result = []; for (let i = 0; i < hexStr.length; i += 2) { const value = parseInt(hexStr.substr(i, 2), 16); if (isNaN(value)) { return null; } result.push(value); } return result; }
javascript
function tryParseHexToBytes(hexStr) { if ((hexStr.length % 2) !== 0) { return null; } const result = []; for (let i = 0; i < hexStr.length; i += 2) { const value = parseInt(hexStr.substr(i, 2), 16); if (isNaN(value)) { return null; } result.push(value); } return result; }
[ "function", "tryParseHexToBytes", "(", "hexStr", ")", "{", "if", "(", "(", "hexStr", ".", "length", "%", "2", ")", "!==", "0", ")", "{", "return", "null", ";", "}", "const", "result", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "hexStr", ".", "length", ";", "i", "+=", "2", ")", "{", "const", "value", "=", "parseInt", "(", "hexStr", ".", "substr", "(", "i", ",", "2", ")", ",", "16", ")", ";", "if", "(", "isNaN", "(", "value", ")", ")", "{", "return", "null", ";", "}", "result", ".", "push", "(", "value", ")", ";", "}", "return", "result", ";", "}" ]
Parses |hexStr| to an array of bytes, or returns null if the input is not a valid hex string.
[ "Parses", "|hexStr|", "to", "an", "array", "of", "bytes", "or", "returns", "null", "if", "the", "input", "is", "not", "a", "valid", "hex", "string", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L330-L345
5,213
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
tryParseBase64ToBytes
function tryParseBase64ToBytes(b64Str) { let decodedStr; try { decodedStr = atob(b64Str); } catch (e) { return null; } return Uint8Array.from(decodedStr, c => c.charCodeAt(0)); }
javascript
function tryParseBase64ToBytes(b64Str) { let decodedStr; try { decodedStr = atob(b64Str); } catch (e) { return null; } return Uint8Array.from(decodedStr, c => c.charCodeAt(0)); }
[ "function", "tryParseBase64ToBytes", "(", "b64Str", ")", "{", "let", "decodedStr", ";", "try", "{", "decodedStr", "=", "atob", "(", "b64Str", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "null", ";", "}", "return", "Uint8Array", ".", "from", "(", "decodedStr", ",", "c", "=>", "c", ".", "charCodeAt", "(", "0", ")", ")", ";", "}" ]
Parses a base64 encoded string to a Uint8Array of bytes.
[ "Parses", "a", "base64", "encoded", "string", "to", "a", "Uint8Array", "of", "bytes", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L350-L360
5,214
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
defaultWriteParameter
function defaultWriteParameter(key, value, out) { if (key === 'headers' && value instanceof Array) { out.writeArrowIndentedLines(value); return; } // For transferred bytes, display the bytes in hex and ASCII. // TODO(eroman): 'hex_encoded_bytes' was removed in M73, and // support for it can be removed in the future. if (key === 'hex_encoded_bytes' && typeof value === 'string') { const bytes = tryParseHexToBytes(value); if (bytes) { out.writeArrowKey(key); writeHexString(bytes, out); return; } } if (key === 'bytes' && typeof value === 'string') { const bytes = tryParseBase64ToBytes(value); if (bytes) { out.writeArrowKey(key); writeHexString(bytes, out); return; } } // Handle source_dependency entries - add link and map source type to // string. if (key === 'source_dependency' && typeof value === 'object') { const link = '#events&s=' + value.id; const valueStr = value.id + ' (' + EventSourceTypeNames[value.type] + ')'; out.writeArrowKeyValue(key, valueStr, link); return; } if (key === 'net_error' && typeof value === 'number') { const valueStr = value + ' (' + netErrorToString(value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } if (key === 'quic_error' && typeof value === 'number') { const valueStr = value + ' (' + quicErrorToString(value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } if (key === 'quic_crypto_handshake_message' && typeof value === 'string') { const lines = value.split('\n'); out.writeArrowIndentedLines(lines); return; } if (key === 'quic_rst_stream_error' && typeof value === 'number') { const valueStr = value + ' (' + quicRstStreamErrorToString(value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } if (key === 'load_flags' && typeof value === 'number') { const valueStr = value + ' (' + getLoadFlagSymbolicString(value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } if (key === 'load_state' && typeof value === 'number') { const valueStr = value + ' (' + getKeyWithValue(LoadState, value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } // Otherwise just default to JSON formatting of the value. out.writeArrowKeyValue(key, JSON.stringify(value)); }
javascript
function defaultWriteParameter(key, value, out) { if (key === 'headers' && value instanceof Array) { out.writeArrowIndentedLines(value); return; } // For transferred bytes, display the bytes in hex and ASCII. // TODO(eroman): 'hex_encoded_bytes' was removed in M73, and // support for it can be removed in the future. if (key === 'hex_encoded_bytes' && typeof value === 'string') { const bytes = tryParseHexToBytes(value); if (bytes) { out.writeArrowKey(key); writeHexString(bytes, out); return; } } if (key === 'bytes' && typeof value === 'string') { const bytes = tryParseBase64ToBytes(value); if (bytes) { out.writeArrowKey(key); writeHexString(bytes, out); return; } } // Handle source_dependency entries - add link and map source type to // string. if (key === 'source_dependency' && typeof value === 'object') { const link = '#events&s=' + value.id; const valueStr = value.id + ' (' + EventSourceTypeNames[value.type] + ')'; out.writeArrowKeyValue(key, valueStr, link); return; } if (key === 'net_error' && typeof value === 'number') { const valueStr = value + ' (' + netErrorToString(value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } if (key === 'quic_error' && typeof value === 'number') { const valueStr = value + ' (' + quicErrorToString(value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } if (key === 'quic_crypto_handshake_message' && typeof value === 'string') { const lines = value.split('\n'); out.writeArrowIndentedLines(lines); return; } if (key === 'quic_rst_stream_error' && typeof value === 'number') { const valueStr = value + ' (' + quicRstStreamErrorToString(value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } if (key === 'load_flags' && typeof value === 'number') { const valueStr = value + ' (' + getLoadFlagSymbolicString(value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } if (key === 'load_state' && typeof value === 'number') { const valueStr = value + ' (' + getKeyWithValue(LoadState, value) + ')'; out.writeArrowKeyValue(key, valueStr); return; } // Otherwise just default to JSON formatting of the value. out.writeArrowKeyValue(key, JSON.stringify(value)); }
[ "function", "defaultWriteParameter", "(", "key", ",", "value", ",", "out", ")", "{", "if", "(", "key", "===", "'headers'", "&&", "value", "instanceof", "Array", ")", "{", "out", ".", "writeArrowIndentedLines", "(", "value", ")", ";", "return", ";", "}", "// For transferred bytes, display the bytes in hex and ASCII.", "// TODO(eroman): 'hex_encoded_bytes' was removed in M73, and", "// support for it can be removed in the future.", "if", "(", "key", "===", "'hex_encoded_bytes'", "&&", "typeof", "value", "===", "'string'", ")", "{", "const", "bytes", "=", "tryParseHexToBytes", "(", "value", ")", ";", "if", "(", "bytes", ")", "{", "out", ".", "writeArrowKey", "(", "key", ")", ";", "writeHexString", "(", "bytes", ",", "out", ")", ";", "return", ";", "}", "}", "if", "(", "key", "===", "'bytes'", "&&", "typeof", "value", "===", "'string'", ")", "{", "const", "bytes", "=", "tryParseBase64ToBytes", "(", "value", ")", ";", "if", "(", "bytes", ")", "{", "out", ".", "writeArrowKey", "(", "key", ")", ";", "writeHexString", "(", "bytes", ",", "out", ")", ";", "return", ";", "}", "}", "// Handle source_dependency entries - add link and map source type to", "// string.", "if", "(", "key", "===", "'source_dependency'", "&&", "typeof", "value", "===", "'object'", ")", "{", "const", "link", "=", "'#events&s='", "+", "value", ".", "id", ";", "const", "valueStr", "=", "value", ".", "id", "+", "' ('", "+", "EventSourceTypeNames", "[", "value", ".", "type", "]", "+", "')'", ";", "out", ".", "writeArrowKeyValue", "(", "key", ",", "valueStr", ",", "link", ")", ";", "return", ";", "}", "if", "(", "key", "===", "'net_error'", "&&", "typeof", "value", "===", "'number'", ")", "{", "const", "valueStr", "=", "value", "+", "' ('", "+", "netErrorToString", "(", "value", ")", "+", "')'", ";", "out", ".", "writeArrowKeyValue", "(", "key", ",", "valueStr", ")", ";", "return", ";", "}", "if", "(", "key", "===", "'quic_error'", "&&", "typeof", "value", "===", "'number'", ")", "{", "const", "valueStr", "=", "value", "+", "' ('", "+", "quicErrorToString", "(", "value", ")", "+", "')'", ";", "out", ".", "writeArrowKeyValue", "(", "key", ",", "valueStr", ")", ";", "return", ";", "}", "if", "(", "key", "===", "'quic_crypto_handshake_message'", "&&", "typeof", "value", "===", "'string'", ")", "{", "const", "lines", "=", "value", ".", "split", "(", "'\\n'", ")", ";", "out", ".", "writeArrowIndentedLines", "(", "lines", ")", ";", "return", ";", "}", "if", "(", "key", "===", "'quic_rst_stream_error'", "&&", "typeof", "value", "===", "'number'", ")", "{", "const", "valueStr", "=", "value", "+", "' ('", "+", "quicRstStreamErrorToString", "(", "value", ")", "+", "')'", ";", "out", ".", "writeArrowKeyValue", "(", "key", ",", "valueStr", ")", ";", "return", ";", "}", "if", "(", "key", "===", "'load_flags'", "&&", "typeof", "value", "===", "'number'", ")", "{", "const", "valueStr", "=", "value", "+", "' ('", "+", "getLoadFlagSymbolicString", "(", "value", ")", "+", "')'", ";", "out", ".", "writeArrowKeyValue", "(", "key", ",", "valueStr", ")", ";", "return", ";", "}", "if", "(", "key", "===", "'load_state'", "&&", "typeof", "value", "===", "'number'", ")", "{", "const", "valueStr", "=", "value", "+", "' ('", "+", "getKeyWithValue", "(", "LoadState", ",", "value", ")", "+", "')'", ";", "out", ".", "writeArrowKeyValue", "(", "key", ",", "valueStr", ")", ";", "return", ";", "}", "// Otherwise just default to JSON formatting of the value.", "out", ".", "writeArrowKeyValue", "(", "key", ",", "JSON", ".", "stringify", "(", "value", ")", ")", ";", "}" ]
Default parameter writer that outputs a visualization of field named |key| with value |value| to |out|.
[ "Default", "parameter", "writer", "that", "outputs", "a", "visualization", "of", "field", "named", "|key|", "with", "value", "|value|", "to", "|out|", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L366-L440
5,215
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
getSymbolicString
function getSymbolicString(bitmask, valueToName, zeroName) { const matchingFlagNames = []; for (const k in valueToName) { if (bitmask & valueToName[k]) { matchingFlagNames.push(k); } } // If no flags were matched, returns a special value. if (matchingFlagNames.length === 0) { return zeroName; } return matchingFlagNames.join(' | '); }
javascript
function getSymbolicString(bitmask, valueToName, zeroName) { const matchingFlagNames = []; for (const k in valueToName) { if (bitmask & valueToName[k]) { matchingFlagNames.push(k); } } // If no flags were matched, returns a special value. if (matchingFlagNames.length === 0) { return zeroName; } return matchingFlagNames.join(' | '); }
[ "function", "getSymbolicString", "(", "bitmask", ",", "valueToName", ",", "zeroName", ")", "{", "const", "matchingFlagNames", "=", "[", "]", ";", "for", "(", "const", "k", "in", "valueToName", ")", "{", "if", "(", "bitmask", "&", "valueToName", "[", "k", "]", ")", "{", "matchingFlagNames", ".", "push", "(", "k", ")", ";", "}", "}", "// If no flags were matched, returns a special value.", "if", "(", "matchingFlagNames", ".", "length", "===", "0", ")", "{", "return", "zeroName", ";", "}", "return", "matchingFlagNames", ".", "join", "(", "' | '", ")", ";", "}" ]
Returns a string representing the flags composing the given bitmask.
[ "Returns", "a", "string", "representing", "the", "flags", "composing", "the", "given", "bitmask", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L462-L477
5,216
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
reformatHeaders
function reformatHeaders(entry) { // If there are no headers, or it is not an object other than an array, // return |entry| without modification. if (!entry.params || entry.params.headers === undefined || typeof entry.params.headers !== 'object' || entry.params.headers instanceof Array) { return entry; } // Duplicate the top level object, and |entry.params|, so the original // object // will not be modified. entry = shallowCloneObject(entry); entry.params = shallowCloneObject(entry.params); // Convert headers to an array. const headers = []; for (const key in entry.params.headers) { headers.push(key + ': ' + entry.params.headers[key]); } entry.params.headers = headers; return entry; }
javascript
function reformatHeaders(entry) { // If there are no headers, or it is not an object other than an array, // return |entry| without modification. if (!entry.params || entry.params.headers === undefined || typeof entry.params.headers !== 'object' || entry.params.headers instanceof Array) { return entry; } // Duplicate the top level object, and |entry.params|, so the original // object // will not be modified. entry = shallowCloneObject(entry); entry.params = shallowCloneObject(entry.params); // Convert headers to an array. const headers = []; for (const key in entry.params.headers) { headers.push(key + ': ' + entry.params.headers[key]); } entry.params.headers = headers; return entry; }
[ "function", "reformatHeaders", "(", "entry", ")", "{", "// If there are no headers, or it is not an object other than an array,", "// return |entry| without modification.", "if", "(", "!", "entry", ".", "params", "||", "entry", ".", "params", ".", "headers", "===", "undefined", "||", "typeof", "entry", ".", "params", ".", "headers", "!==", "'object'", "||", "entry", ".", "params", ".", "headers", "instanceof", "Array", ")", "{", "return", "entry", ";", "}", "// Duplicate the top level object, and |entry.params|, so the original", "// object", "// will not be modified.", "entry", "=", "shallowCloneObject", "(", "entry", ")", ";", "entry", ".", "params", "=", "shallowCloneObject", "(", "entry", ".", "params", ")", ";", "// Convert headers to an array.", "const", "headers", "=", "[", "]", ";", "for", "(", "const", "key", "in", "entry", ".", "params", ".", "headers", ")", "{", "headers", ".", "push", "(", "key", "+", "': '", "+", "entry", ".", "params", ".", "headers", "[", "key", "]", ")", ";", "}", "entry", ".", "params", ".", "headers", "=", "headers", ";", "return", "entry", ";", "}" ]
If entry.param.headers exists and is an object other than an array, converts it into an array and returns a new entry. Otherwise, just returns the original entry.
[ "If", "entry", ".", "param", ".", "headers", "exists", "and", "is", "an", "object", "other", "than", "an", "array", "converts", "it", "into", "an", "array", "and", "returns", "a", "new", "entry", ".", "Otherwise", "just", "returns", "the", "original", "entry", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L501-L524
5,217
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
writeParamsForRequestHeaders
function writeParamsForRequestHeaders(entry, out, consumedParams) { const params = entry.params; if (!(typeof params.line === 'string') || !(params.headers instanceof Array)) { // Unrecognized params. return; } // Strip the trailing CRLF that params.line contains. const lineWithoutCRLF = params.line.replace(/\r\n$/g, ''); out.writeArrowIndentedLines([lineWithoutCRLF].concat(params.headers)); consumedParams.line = true; consumedParams.headers = true; }
javascript
function writeParamsForRequestHeaders(entry, out, consumedParams) { const params = entry.params; if (!(typeof params.line === 'string') || !(params.headers instanceof Array)) { // Unrecognized params. return; } // Strip the trailing CRLF that params.line contains. const lineWithoutCRLF = params.line.replace(/\r\n$/g, ''); out.writeArrowIndentedLines([lineWithoutCRLF].concat(params.headers)); consumedParams.line = true; consumedParams.headers = true; }
[ "function", "writeParamsForRequestHeaders", "(", "entry", ",", "out", ",", "consumedParams", ")", "{", "const", "params", "=", "entry", ".", "params", ";", "if", "(", "!", "(", "typeof", "params", ".", "line", "===", "'string'", ")", "||", "!", "(", "params", ".", "headers", "instanceof", "Array", ")", ")", "{", "// Unrecognized params.", "return", ";", "}", "// Strip the trailing CRLF that params.line contains.", "const", "lineWithoutCRLF", "=", "params", ".", "line", ".", "replace", "(", "/", "\\r\\n$", "/", "g", ",", "''", ")", ";", "out", ".", "writeArrowIndentedLines", "(", "[", "lineWithoutCRLF", "]", ".", "concat", "(", "params", ".", "headers", ")", ")", ";", "consumedParams", ".", "line", "=", "true", ";", "consumedParams", ".", "headers", "=", "true", ";", "}" ]
Outputs the request header parameters of |entry| to |out|.
[ "Outputs", "the", "request", "header", "parameters", "of", "|entry|", "to", "|out|", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L529-L544
5,218
catapult-project/catapult
netlog_viewer/netlog_viewer/log_view_painter.js
writeParamsForCertificates
function writeParamsForCertificates(entry, out, consumedParams) { writeCertificateParam(entry.params, out, consumedParams, 'certificates'); if (typeof(entry.params.verified_cert) === 'object') { writeCertificateParam( entry.params.verified_cert, out, consumedParams, 'verified_cert'); } if (typeof(entry.params.cert_status) === 'number') { const valueStr = entry.params.cert_status + ' (' + getCertStatusFlagSymbolicString(entry.params.cert_status) + ')'; out.writeArrowKeyValue('cert_status', valueStr); consumedParams.cert_status = true; } }
javascript
function writeParamsForCertificates(entry, out, consumedParams) { writeCertificateParam(entry.params, out, consumedParams, 'certificates'); if (typeof(entry.params.verified_cert) === 'object') { writeCertificateParam( entry.params.verified_cert, out, consumedParams, 'verified_cert'); } if (typeof(entry.params.cert_status) === 'number') { const valueStr = entry.params.cert_status + ' (' + getCertStatusFlagSymbolicString(entry.params.cert_status) + ')'; out.writeArrowKeyValue('cert_status', valueStr); consumedParams.cert_status = true; } }
[ "function", "writeParamsForCertificates", "(", "entry", ",", "out", ",", "consumedParams", ")", "{", "writeCertificateParam", "(", "entry", ".", "params", ",", "out", ",", "consumedParams", ",", "'certificates'", ")", ";", "if", "(", "typeof", "(", "entry", ".", "params", ".", "verified_cert", ")", "===", "'object'", ")", "{", "writeCertificateParam", "(", "entry", ".", "params", ".", "verified_cert", ",", "out", ",", "consumedParams", ",", "'verified_cert'", ")", ";", "}", "if", "(", "typeof", "(", "entry", ".", "params", ".", "cert_status", ")", "===", "'number'", ")", "{", "const", "valueStr", "=", "entry", ".", "params", ".", "cert_status", "+", "' ('", "+", "getCertStatusFlagSymbolicString", "(", "entry", ".", "params", ".", "cert_status", ")", "+", "')'", ";", "out", ".", "writeArrowKeyValue", "(", "'cert_status'", ",", "valueStr", ")", ";", "consumedParams", ".", "cert_status", "=", "true", ";", "}", "}" ]
Outputs the certificate parameters of |entry| to |out|.
[ "Outputs", "the", "certificate", "parameters", "of", "|entry|", "to", "|out|", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_view_painter.js#L562-L576
5,219
catapult-project/catapult
common/py_vulcanize/third_party/rcssmin/docs/apidoc/epydoc.js
collapse_all
function collapse_all(min_lines) { var elts = document.getElementsByTagName("div"); for (var i=0; i<elts.length; i++) { var elt = elts[i]; var split = elt.id.indexOf("-"); if (split > 0) if (elt.id.substring(split, elt.id.length) == "-expanded") if (num_lines(elt.innerHTML) > min_lines) collapse(elt.id.substring(0, split)); } }
javascript
function collapse_all(min_lines) { var elts = document.getElementsByTagName("div"); for (var i=0; i<elts.length; i++) { var elt = elts[i]; var split = elt.id.indexOf("-"); if (split > 0) if (elt.id.substring(split, elt.id.length) == "-expanded") if (num_lines(elt.innerHTML) > min_lines) collapse(elt.id.substring(0, split)); } }
[ "function", "collapse_all", "(", "min_lines", ")", "{", "var", "elts", "=", "document", ".", "getElementsByTagName", "(", "\"div\"", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elts", ".", "length", ";", "i", "++", ")", "{", "var", "elt", "=", "elts", "[", "i", "]", ";", "var", "split", "=", "elt", ".", "id", ".", "indexOf", "(", "\"-\"", ")", ";", "if", "(", "split", ">", "0", ")", "if", "(", "elt", ".", "id", ".", "substring", "(", "split", ",", "elt", ".", "id", ".", "length", ")", "==", "\"-expanded\"", ")", "if", "(", "num_lines", "(", "elt", ".", "innerHTML", ")", ">", "min_lines", ")", "collapse", "(", "elt", ".", "id", ".", "substring", "(", "0", ",", "split", ")", ")", ";", "}", "}" ]
Collapse all blocks that mave more than `min_lines` lines.
[ "Collapse", "all", "blocks", "that", "mave", "more", "than", "min_lines", "lines", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/common/py_vulcanize/third_party/rcssmin/docs/apidoc/epydoc.js#L160-L170
5,220
catapult-project/catapult
third_party/gsutil/third_party/httplib2/doc/html/_static/doctools.js
function() { var params = $.getQueryParameters(); var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; if (terms.length) { var body = $('div.body'); window.setTimeout(function() { $.each(terms, function() { body.highlightText(this.toLowerCase(), 'highlight'); }); }, 10); $('<li class="highlight-link"><a href="javascript:Documentation.' + 'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>') .appendTo($('.sidebar .this-page-menu')); } }
javascript
function() { var params = $.getQueryParameters(); var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; if (terms.length) { var body = $('div.body'); window.setTimeout(function() { $.each(terms, function() { body.highlightText(this.toLowerCase(), 'highlight'); }); }, 10); $('<li class="highlight-link"><a href="javascript:Documentation.' + 'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>') .appendTo($('.sidebar .this-page-menu')); } }
[ "function", "(", ")", "{", "var", "params", "=", "$", ".", "getQueryParameters", "(", ")", ";", "var", "terms", "=", "(", "params", ".", "highlight", ")", "?", "params", ".", "highlight", "[", "0", "]", ".", "split", "(", "/", "\\s+", "/", ")", ":", "[", "]", ";", "if", "(", "terms", ".", "length", ")", "{", "var", "body", "=", "$", "(", "'div.body'", ")", ";", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "$", ".", "each", "(", "terms", ",", "function", "(", ")", "{", "body", ".", "highlightText", "(", "this", ".", "toLowerCase", "(", ")", ",", "'highlight'", ")", ";", "}", ")", ";", "}", ",", "10", ")", ";", "$", "(", "'<li class=\"highlight-link\"><a href=\"javascript:Documentation.'", "+", "'hideSearchWords()\">'", "+", "_", "(", "'Hide Search Matches'", ")", "+", "'</a></li>'", ")", ".", "appendTo", "(", "$", "(", "'.sidebar .this-page-menu'", ")", ")", ";", "}", "}" ]
highlight the search words provided in the url in the text
[ "highlight", "the", "search", "words", "provided", "in", "the", "url", "in", "the", "text" ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/gsutil/third_party/httplib2/doc/html/_static/doctools.js#L163-L177
5,221
catapult-project/catapult
third_party/gsutil/third_party/httplib2/doc/html/_static/doctools.js
function() { var togglers = $('img.toggler').click(function() { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); console.log($('tr.cg-' + idnum).toggle()); if (src.substr(-9) == 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); }).css('display', ''); if (DOCUMENTATION_OPTIONS.COLLAPSE_MODINDEX) { togglers.click(); } }
javascript
function() { var togglers = $('img.toggler').click(function() { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); console.log($('tr.cg-' + idnum).toggle()); if (src.substr(-9) == 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); }).css('display', ''); if (DOCUMENTATION_OPTIONS.COLLAPSE_MODINDEX) { togglers.click(); } }
[ "function", "(", ")", "{", "var", "togglers", "=", "$", "(", "'img.toggler'", ")", ".", "click", "(", "function", "(", ")", "{", "var", "src", "=", "$", "(", "this", ")", ".", "attr", "(", "'src'", ")", ";", "var", "idnum", "=", "$", "(", "this", ")", ".", "attr", "(", "'id'", ")", ".", "substr", "(", "7", ")", ";", "console", ".", "log", "(", "$", "(", "'tr.cg-'", "+", "idnum", ")", ".", "toggle", "(", ")", ")", ";", "if", "(", "src", ".", "substr", "(", "-", "9", ")", "==", "'minus.png'", ")", "$", "(", "this", ")", ".", "attr", "(", "'src'", ",", "src", ".", "substr", "(", "0", ",", "src", ".", "length", "-", "9", ")", "+", "'plus.png'", ")", ";", "else", "$", "(", "this", ")", ".", "attr", "(", "'src'", ",", "src", ".", "substr", "(", "0", ",", "src", ".", "length", "-", "8", ")", "+", "'minus.png'", ")", ";", "}", ")", ".", "css", "(", "'display'", ",", "''", ")", ";", "if", "(", "DOCUMENTATION_OPTIONS", ".", "COLLAPSE_MODINDEX", ")", "{", "togglers", ".", "click", "(", ")", ";", "}", "}" ]
init the modindex toggle buttons
[ "init", "the", "modindex", "toggle", "buttons" ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/gsutil/third_party/httplib2/doc/html/_static/doctools.js#L182-L195
5,222
catapult-project/catapult
third_party/pipeline/pipeline/ui/status.js
scrollTreeToPipeline
function scrollTreeToPipeline(pipelineIdOrElement) { var element = pipelineIdOrElement; if (!(pipelineIdOrElement instanceof jQuery)) { element = $(getTreePipelineElementId(pipelineIdOrElement)); } $('#sidebar').scrollTop(element.attr('offsetTop')); $('#sidebar').scrollLeft(element.attr('offsetLeft')); }
javascript
function scrollTreeToPipeline(pipelineIdOrElement) { var element = pipelineIdOrElement; if (!(pipelineIdOrElement instanceof jQuery)) { element = $(getTreePipelineElementId(pipelineIdOrElement)); } $('#sidebar').scrollTop(element.attr('offsetTop')); $('#sidebar').scrollLeft(element.attr('offsetLeft')); }
[ "function", "scrollTreeToPipeline", "(", "pipelineIdOrElement", ")", "{", "var", "element", "=", "pipelineIdOrElement", ";", "if", "(", "!", "(", "pipelineIdOrElement", "instanceof", "jQuery", ")", ")", "{", "element", "=", "$", "(", "getTreePipelineElementId", "(", "pipelineIdOrElement", ")", ")", ";", "}", "$", "(", "'#sidebar'", ")", ".", "scrollTop", "(", "element", ".", "attr", "(", "'offsetTop'", ")", ")", ";", "$", "(", "'#sidebar'", ")", ".", "scrollLeft", "(", "element", ".", "attr", "(", "'offsetLeft'", ")", ")", ";", "}" ]
Scrolls to element of the pipeline in the tree.
[ "Scrolls", "to", "element", "of", "the", "pipeline", "in", "the", "tree", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/status.js#L63-L70
5,223
catapult-project/catapult
third_party/pipeline/pipeline/ui/status.js
expandTreeToPipeline
function expandTreeToPipeline(pipelineId) { if (pipelineId == null) { return; } var elementId = getTreePipelineElementId(pipelineId); var parents = $(elementId).parents('.expandable'); if (parents.size() > 0) { // The toggle function will scroll to highlight the pipeline. parents.children('.hitarea').click(); } else { // No children, so just scroll. scrollTreeToPipeline(pipelineId); } }
javascript
function expandTreeToPipeline(pipelineId) { if (pipelineId == null) { return; } var elementId = getTreePipelineElementId(pipelineId); var parents = $(elementId).parents('.expandable'); if (parents.size() > 0) { // The toggle function will scroll to highlight the pipeline. parents.children('.hitarea').click(); } else { // No children, so just scroll. scrollTreeToPipeline(pipelineId); } }
[ "function", "expandTreeToPipeline", "(", "pipelineId", ")", "{", "if", "(", "pipelineId", "==", "null", ")", "{", "return", ";", "}", "var", "elementId", "=", "getTreePipelineElementId", "(", "pipelineId", ")", ";", "var", "parents", "=", "$", "(", "elementId", ")", ".", "parents", "(", "'.expandable'", ")", ";", "if", "(", "parents", ".", "size", "(", ")", ">", "0", ")", "{", "// The toggle function will scroll to highlight the pipeline.", "parents", ".", "children", "(", "'.hitarea'", ")", ".", "click", "(", ")", ";", "}", "else", "{", "// No children, so just scroll.", "scrollTreeToPipeline", "(", "pipelineId", ")", ";", "}", "}" ]
Opens all pipelines down to the target one if not already expanded and scroll that pipeline into view.
[ "Opens", "all", "pipelines", "down", "to", "the", "target", "one", "if", "not", "already", "expanded", "and", "scroll", "that", "pipeline", "into", "view", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/status.js#L75-L88
5,224
catapult-project/catapult
third_party/pipeline/pipeline/ui/status.js
handleTreeToggle
function handleTreeToggle(index, element) { var parentItem = $(element).parent(); var collapsing = parentItem.hasClass('expandable'); if (collapsing) { } else { // When expanded be sure the pipeline and its children are showing. scrollTreeToPipeline(parentItem); } }
javascript
function handleTreeToggle(index, element) { var parentItem = $(element).parent(); var collapsing = parentItem.hasClass('expandable'); if (collapsing) { } else { // When expanded be sure the pipeline and its children are showing. scrollTreeToPipeline(parentItem); } }
[ "function", "handleTreeToggle", "(", "index", ",", "element", ")", "{", "var", "parentItem", "=", "$", "(", "element", ")", ".", "parent", "(", ")", ";", "var", "collapsing", "=", "parentItem", ".", "hasClass", "(", "'expandable'", ")", ";", "if", "(", "collapsing", ")", "{", "}", "else", "{", "// When expanded be sure the pipeline and its children are showing.", "scrollTreeToPipeline", "(", "parentItem", ")", ";", "}", "}" ]
Handles when the user toggles a leaf of the tree.
[ "Handles", "when", "the", "user", "toggles", "a", "leaf", "of", "the", "tree", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/status.js#L92-L100
5,225
catapult-project/catapult
third_party/pipeline/pipeline/ui/status.js
countChildren
function countChildren(pipelineId) { var current = STATUS_MAP.pipelines[pipelineId]; if (!current) { return [0, 0]; } var total = 1; var done = 0; if (current.status == 'done') { done += 1; } for (var i = 0, n = current.children.length; i < n; i++) { var parts = countChildren(current.children[i]); total += parts[0]; done += parts[1]; } return [total, done]; }
javascript
function countChildren(pipelineId) { var current = STATUS_MAP.pipelines[pipelineId]; if (!current) { return [0, 0]; } var total = 1; var done = 0; if (current.status == 'done') { done += 1; } for (var i = 0, n = current.children.length; i < n; i++) { var parts = countChildren(current.children[i]); total += parts[0]; done += parts[1]; } return [total, done]; }
[ "function", "countChildren", "(", "pipelineId", ")", "{", "var", "current", "=", "STATUS_MAP", ".", "pipelines", "[", "pipelineId", "]", ";", "if", "(", "!", "current", ")", "{", "return", "[", "0", ",", "0", "]", ";", "}", "var", "total", "=", "1", ";", "var", "done", "=", "0", ";", "if", "(", "current", ".", "status", "==", "'done'", ")", "{", "done", "+=", "1", ";", "}", "for", "(", "var", "i", "=", "0", ",", "n", "=", "current", ".", "children", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "parts", "=", "countChildren", "(", "current", ".", "children", "[", "i", "]", ")", ";", "total", "+=", "parts", "[", "0", "]", ";", "done", "+=", "parts", "[", "1", "]", ";", "}", "return", "[", "total", ",", "done", "]", ";", "}" ]
Counts the number of total and active children for the given pipeline. Will include the supplied pipeline in the totals.
[ "Counts", "the", "number", "of", "total", "and", "active", "children", "for", "the", "given", "pipeline", ".", "Will", "include", "the", "supplied", "pipeline", "in", "the", "totals", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/status.js#L105-L121
5,226
catapult-project/catapult
third_party/pipeline/pipeline/ui/status.js
prettyName
function prettyName(name, sidebar) { var adjustedName = name; if (sidebar) { var adjustedName = name; var parts = name.split('.'); if (parts.length > 0) { adjustedName = parts[parts.length - 1]; } } return adjustedName.replace(/\./, '.<wbr>'); }
javascript
function prettyName(name, sidebar) { var adjustedName = name; if (sidebar) { var adjustedName = name; var parts = name.split('.'); if (parts.length > 0) { adjustedName = parts[parts.length - 1]; } } return adjustedName.replace(/\./, '.<wbr>'); }
[ "function", "prettyName", "(", "name", ",", "sidebar", ")", "{", "var", "adjustedName", "=", "name", ";", "if", "(", "sidebar", ")", "{", "var", "adjustedName", "=", "name", ";", "var", "parts", "=", "name", ".", "split", "(", "'.'", ")", ";", "if", "(", "parts", ".", "length", ">", "0", ")", "{", "adjustedName", "=", "parts", "[", "parts", ".", "length", "-", "1", "]", ";", "}", "}", "return", "adjustedName", ".", "replace", "(", "/", "\\.", "/", ",", "'.<wbr>'", ")", ";", "}" ]
Create the readable name for the pipeline name.
[ "Create", "the", "readable", "name", "for", "the", "pipeline", "name", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/status.js#L125-L135
5,227
catapult-project/catapult
third_party/pipeline/pipeline/ui/status.js
generateSidebar
function generateSidebar(statusMap, nextPipelineId, rootElement) { var currentElement = null; if (nextPipelineId) { currentElement = $('<li>'); // Value should match return of getTreePipelineElementId currentElement.attr('id', 'item-pipeline-' + nextPipelineId); } else { currentElement = rootElement; nextPipelineId = statusMap.rootPipelineId; } var parentInfoMap = statusMap.pipelines[nextPipelineId]; currentElement.append( constructStageNode(nextPipelineId, parentInfoMap, true)); if (statusMap.pipelines[nextPipelineId]) { var children = statusMap.pipelines[nextPipelineId].children; if (children.length > 0) { var treeElement = null; if (rootElement) { treeElement = $('<ul id="pipeline-tree" class="treeview-black treeview">'); } else { treeElement = $('<ul>'); } $.each(children, function(index, childPipelineId) { var childElement = generateSidebar(statusMap, childPipelineId); treeElement.append(childElement); }); currentElement.append(treeElement); } } return currentElement; }
javascript
function generateSidebar(statusMap, nextPipelineId, rootElement) { var currentElement = null; if (nextPipelineId) { currentElement = $('<li>'); // Value should match return of getTreePipelineElementId currentElement.attr('id', 'item-pipeline-' + nextPipelineId); } else { currentElement = rootElement; nextPipelineId = statusMap.rootPipelineId; } var parentInfoMap = statusMap.pipelines[nextPipelineId]; currentElement.append( constructStageNode(nextPipelineId, parentInfoMap, true)); if (statusMap.pipelines[nextPipelineId]) { var children = statusMap.pipelines[nextPipelineId].children; if (children.length > 0) { var treeElement = null; if (rootElement) { treeElement = $('<ul id="pipeline-tree" class="treeview-black treeview">'); } else { treeElement = $('<ul>'); } $.each(children, function(index, childPipelineId) { var childElement = generateSidebar(statusMap, childPipelineId); treeElement.append(childElement); }); currentElement.append(treeElement); } } return currentElement; }
[ "function", "generateSidebar", "(", "statusMap", ",", "nextPipelineId", ",", "rootElement", ")", "{", "var", "currentElement", "=", "null", ";", "if", "(", "nextPipelineId", ")", "{", "currentElement", "=", "$", "(", "'<li>'", ")", ";", "// Value should match return of getTreePipelineElementId", "currentElement", ".", "attr", "(", "'id'", ",", "'item-pipeline-'", "+", "nextPipelineId", ")", ";", "}", "else", "{", "currentElement", "=", "rootElement", ";", "nextPipelineId", "=", "statusMap", ".", "rootPipelineId", ";", "}", "var", "parentInfoMap", "=", "statusMap", ".", "pipelines", "[", "nextPipelineId", "]", ";", "currentElement", ".", "append", "(", "constructStageNode", "(", "nextPipelineId", ",", "parentInfoMap", ",", "true", ")", ")", ";", "if", "(", "statusMap", ".", "pipelines", "[", "nextPipelineId", "]", ")", "{", "var", "children", "=", "statusMap", ".", "pipelines", "[", "nextPipelineId", "]", ".", "children", ";", "if", "(", "children", ".", "length", ">", "0", ")", "{", "var", "treeElement", "=", "null", ";", "if", "(", "rootElement", ")", "{", "treeElement", "=", "$", "(", "'<ul id=\"pipeline-tree\" class=\"treeview-black treeview\">'", ")", ";", "}", "else", "{", "treeElement", "=", "$", "(", "'<ul>'", ")", ";", "}", "$", ".", "each", "(", "children", ",", "function", "(", "index", ",", "childPipelineId", ")", "{", "var", "childElement", "=", "generateSidebar", "(", "statusMap", ",", "childPipelineId", ")", ";", "treeElement", ".", "append", "(", "childElement", ")", ";", "}", ")", ";", "currentElement", ".", "append", "(", "treeElement", ")", ";", "}", "}", "return", "currentElement", ";", "}" ]
Recursively creates the sidebar. Use null nextPipelineId to create from root.
[ "Recursively", "creates", "the", "sidebar", ".", "Use", "null", "nextPipelineId", "to", "create", "from", "root", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/status.js#L582-L617
5,228
catapult-project/catapult
third_party/pipeline/pipeline/ui/status.js
findActivePipeline
function findActivePipeline(pipelineId, isRoot) { var infoMap = STATUS_MAP.pipelines[pipelineId]; if (!infoMap) { return null; } // This is an active leaf node. if (infoMap.children.length == 0 && infoMap.status != 'done') { return pipelineId; } // Sort children by start time only. var children = infoMap.children.slice(0); children.sort(function(a, b) { var infoMapA = STATUS_MAP.pipelines[a]; var infoMapB = STATUS_MAP.pipelines[b]; if (!infoMapA || !infoMapB) { return 0; } if (infoMapA.startTimeMs && infoMapB.startTimeMs) { return infoMapA.startTimeMs - infoMapB.startTimeMs; } else { return 0; } }); for (var i = 0; i < children.length; ++i) { var foundPipelineId = findActivePipeline(children[i], false); if (foundPipelineId != null) { return foundPipelineId; } } return null; }
javascript
function findActivePipeline(pipelineId, isRoot) { var infoMap = STATUS_MAP.pipelines[pipelineId]; if (!infoMap) { return null; } // This is an active leaf node. if (infoMap.children.length == 0 && infoMap.status != 'done') { return pipelineId; } // Sort children by start time only. var children = infoMap.children.slice(0); children.sort(function(a, b) { var infoMapA = STATUS_MAP.pipelines[a]; var infoMapB = STATUS_MAP.pipelines[b]; if (!infoMapA || !infoMapB) { return 0; } if (infoMapA.startTimeMs && infoMapB.startTimeMs) { return infoMapA.startTimeMs - infoMapB.startTimeMs; } else { return 0; } }); for (var i = 0; i < children.length; ++i) { var foundPipelineId = findActivePipeline(children[i], false); if (foundPipelineId != null) { return foundPipelineId; } } return null; }
[ "function", "findActivePipeline", "(", "pipelineId", ",", "isRoot", ")", "{", "var", "infoMap", "=", "STATUS_MAP", ".", "pipelines", "[", "pipelineId", "]", ";", "if", "(", "!", "infoMap", ")", "{", "return", "null", ";", "}", "// This is an active leaf node.", "if", "(", "infoMap", ".", "children", ".", "length", "==", "0", "&&", "infoMap", ".", "status", "!=", "'done'", ")", "{", "return", "pipelineId", ";", "}", "// Sort children by start time only.", "var", "children", "=", "infoMap", ".", "children", ".", "slice", "(", "0", ")", ";", "children", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "var", "infoMapA", "=", "STATUS_MAP", ".", "pipelines", "[", "a", "]", ";", "var", "infoMapB", "=", "STATUS_MAP", ".", "pipelines", "[", "b", "]", ";", "if", "(", "!", "infoMapA", "||", "!", "infoMapB", ")", "{", "return", "0", ";", "}", "if", "(", "infoMapA", ".", "startTimeMs", "&&", "infoMapB", ".", "startTimeMs", ")", "{", "return", "infoMapA", ".", "startTimeMs", "-", "infoMapB", ".", "startTimeMs", ";", "}", "else", "{", "return", "0", ";", "}", "}", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "children", ".", "length", ";", "++", "i", ")", "{", "var", "foundPipelineId", "=", "findActivePipeline", "(", "children", "[", "i", "]", ",", "false", ")", ";", "if", "(", "foundPipelineId", "!=", "null", ")", "{", "return", "foundPipelineId", ";", "}", "}", "return", "null", ";", "}" ]
Depth-first search for active pipeline.
[ "Depth", "-", "first", "search", "for", "active", "pipeline", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/status.js#L630-L664
5,229
catapult-project/catapult
dashboard/dashboard/spa/chart-timeseries.js
filterTimeseriesesByLine
function filterTimeseriesesByLine(timeseriesesByLine) { const result = []; for (const {lineDescriptor, timeserieses} of timeseriesesByLine) { const filteredTimeserieses = timeserieses.filter(ts => ts); if (filteredTimeserieses.length === 0) continue; result.push({lineDescriptor, timeserieses: filteredTimeserieses}); } return result; }
javascript
function filterTimeseriesesByLine(timeseriesesByLine) { const result = []; for (const {lineDescriptor, timeserieses} of timeseriesesByLine) { const filteredTimeserieses = timeserieses.filter(ts => ts); if (filteredTimeserieses.length === 0) continue; result.push({lineDescriptor, timeserieses: filteredTimeserieses}); } return result; }
[ "function", "filterTimeseriesesByLine", "(", "timeseriesesByLine", ")", "{", "const", "result", "=", "[", "]", ";", "for", "(", "const", "{", "lineDescriptor", ",", "timeserieses", "}", "of", "timeseriesesByLine", ")", "{", "const", "filteredTimeserieses", "=", "timeserieses", ".", "filter", "(", "ts", "=>", "ts", ")", ";", "if", "(", "filteredTimeserieses", ".", "length", "===", "0", ")", "continue", ";", "result", ".", "push", "(", "{", "lineDescriptor", ",", "timeserieses", ":", "filteredTimeserieses", "}", ")", ";", "}", "return", "result", ";", "}" ]
Remove empty elements.
[ "Remove", "empty", "elements", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/dashboard/dashboard/spa/chart-timeseries.js#L524-L532
5,230
catapult-project/catapult
dashboard/dashboard/spa/chart-timeseries.js
getIcon
function getIcon(datum) { if (!datum.alert) return {}; if (datum.alert.improvement) { return { icon: 'cp:thumb-up', iconColor: 'var(--improvement-color, green)', }; } return { icon: 'cp:error', iconColor: datum.alert.bugId ? 'var(--neutral-color-dark, grey)' : 'var(--error-color, red)', }; }
javascript
function getIcon(datum) { if (!datum.alert) return {}; if (datum.alert.improvement) { return { icon: 'cp:thumb-up', iconColor: 'var(--improvement-color, green)', }; } return { icon: 'cp:error', iconColor: datum.alert.bugId ? 'var(--neutral-color-dark, grey)' : 'var(--error-color, red)', }; }
[ "function", "getIcon", "(", "datum", ")", "{", "if", "(", "!", "datum", ".", "alert", ")", "return", "{", "}", ";", "if", "(", "datum", ".", "alert", ".", "improvement", ")", "{", "return", "{", "icon", ":", "'cp:thumb-up'", ",", "iconColor", ":", "'var(--improvement-color, green)'", ",", "}", ";", "}", "return", "{", "icon", ":", "'cp:error'", ",", "iconColor", ":", "datum", ".", "alert", ".", "bugId", "?", "'var(--neutral-color-dark, grey)'", ":", "'var(--error-color, red)'", ",", "}", ";", "}" ]
Improvement alerts display thumbs-up icons. Regression alerts display error icons.
[ "Improvement", "alerts", "display", "thumbs", "-", "up", "icons", ".", "Regression", "alerts", "display", "error", "icons", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/dashboard/dashboard/spa/chart-timeseries.js#L632-L645
5,231
catapult-project/catapult
third_party/mapreduce/mapreduce/static/status.js
listConfigs
function listConfigs(resultFunc) { $.ajax({ type: 'GET', url: 'command/list_configs', dataType: 'text', error: function(request, textStatus) { getResponseDataJson(textStatus); }, success: function(data, textStatus, request) { var response = getResponseDataJson(null, data); if (response) { resultFunc(response.configs); } } }); }
javascript
function listConfigs(resultFunc) { $.ajax({ type: 'GET', url: 'command/list_configs', dataType: 'text', error: function(request, textStatus) { getResponseDataJson(textStatus); }, success: function(data, textStatus, request) { var response = getResponseDataJson(null, data); if (response) { resultFunc(response.configs); } } }); }
[ "function", "listConfigs", "(", "resultFunc", ")", "{", "$", ".", "ajax", "(", "{", "type", ":", "'GET'", ",", "url", ":", "'command/list_configs'", ",", "dataType", ":", "'text'", ",", "error", ":", "function", "(", "request", ",", "textStatus", ")", "{", "getResponseDataJson", "(", "textStatus", ")", ";", "}", ",", "success", ":", "function", "(", "data", ",", "textStatus", ",", "request", ")", "{", "var", "response", "=", "getResponseDataJson", "(", "null", ",", "data", ")", ";", "if", "(", "response", ")", "{", "resultFunc", "(", "response", ".", "configs", ")", ";", "}", "}", "}", ")", ";", "}" ]
Retrieve the list of configs.
[ "Retrieve", "the", "list", "of", "configs", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/mapreduce/mapreduce/static/status.js#L111-L126
5,232
catapult-project/catapult
third_party/mapreduce/mapreduce/static/status.js
listJobs
function listJobs(cursor, resultFunc) { // If the user is paging then they scrolled down so let's // help them by scrolling the window back to the top. var jumpToTop = !!cursor; cursor = cursor ? cursor : ''; setButter('Loading'); $.ajax({ type: 'GET', url: 'command/list_jobs?cursor=' + cursor, dataType: 'text', error: function(request, textStatus) { getResponseDataJson(textStatus); }, success: function(data, textStatus, request) { var response = getResponseDataJson(null, data); if (response) { resultFunc(response.jobs, response.cursor); if (jumpToTop) { window.scrollTo(0, 0); } hideButter(); // Hide the loading message. } } }); }
javascript
function listJobs(cursor, resultFunc) { // If the user is paging then they scrolled down so let's // help them by scrolling the window back to the top. var jumpToTop = !!cursor; cursor = cursor ? cursor : ''; setButter('Loading'); $.ajax({ type: 'GET', url: 'command/list_jobs?cursor=' + cursor, dataType: 'text', error: function(request, textStatus) { getResponseDataJson(textStatus); }, success: function(data, textStatus, request) { var response = getResponseDataJson(null, data); if (response) { resultFunc(response.jobs, response.cursor); if (jumpToTop) { window.scrollTo(0, 0); } hideButter(); // Hide the loading message. } } }); }
[ "function", "listJobs", "(", "cursor", ",", "resultFunc", ")", "{", "// If the user is paging then they scrolled down so let's", "// help them by scrolling the window back to the top.", "var", "jumpToTop", "=", "!", "!", "cursor", ";", "cursor", "=", "cursor", "?", "cursor", ":", "''", ";", "setButter", "(", "'Loading'", ")", ";", "$", ".", "ajax", "(", "{", "type", ":", "'GET'", ",", "url", ":", "'command/list_jobs?cursor='", "+", "cursor", ",", "dataType", ":", "'text'", ",", "error", ":", "function", "(", "request", ",", "textStatus", ")", "{", "getResponseDataJson", "(", "textStatus", ")", ";", "}", ",", "success", ":", "function", "(", "data", ",", "textStatus", ",", "request", ")", "{", "var", "response", "=", "getResponseDataJson", "(", "null", ",", "data", ")", ";", "if", "(", "response", ")", "{", "resultFunc", "(", "response", ".", "jobs", ",", "response", ".", "cursor", ")", ";", "if", "(", "jumpToTop", ")", "{", "window", ".", "scrollTo", "(", "0", ",", "0", ")", ";", "}", "hideButter", "(", ")", ";", "// Hide the loading message.", "}", "}", "}", ")", ";", "}" ]
Return the list of job records and notifies the user the content is being fetched.
[ "Return", "the", "list", "of", "job", "records", "and", "notifies", "the", "user", "the", "content", "is", "being", "fetched", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/mapreduce/mapreduce/static/status.js#L130-L154
5,233
catapult-project/catapult
third_party/mapreduce/mapreduce/static/status.js
cleanUpJob
function cleanUpJob(name, mapreduce_id) { if (!confirm('Clean up job "' + name + '" with ID "' + mapreduce_id + '"?')) { return; } $.ajax({ async: false, type: 'POST', url: 'command/cleanup_job', data: {'mapreduce_id': mapreduce_id}, dataType: 'text', error: function(request, textStatus) { getResponseDataJson(textStatus); }, success: function(data, textStatus, request) { var response = getResponseDataJson(null, data); if (response) { setButter(response.status); if (!response.status.error) { $('#row-' + mapreduce_id).remove(); } } } }); }
javascript
function cleanUpJob(name, mapreduce_id) { if (!confirm('Clean up job "' + name + '" with ID "' + mapreduce_id + '"?')) { return; } $.ajax({ async: false, type: 'POST', url: 'command/cleanup_job', data: {'mapreduce_id': mapreduce_id}, dataType: 'text', error: function(request, textStatus) { getResponseDataJson(textStatus); }, success: function(data, textStatus, request) { var response = getResponseDataJson(null, data); if (response) { setButter(response.status); if (!response.status.error) { $('#row-' + mapreduce_id).remove(); } } } }); }
[ "function", "cleanUpJob", "(", "name", ",", "mapreduce_id", ")", "{", "if", "(", "!", "confirm", "(", "'Clean up job \"'", "+", "name", "+", "'\" with ID \"'", "+", "mapreduce_id", "+", "'\"?'", ")", ")", "{", "return", ";", "}", "$", ".", "ajax", "(", "{", "async", ":", "false", ",", "type", ":", "'POST'", ",", "url", ":", "'command/cleanup_job'", ",", "data", ":", "{", "'mapreduce_id'", ":", "mapreduce_id", "}", ",", "dataType", ":", "'text'", ",", "error", ":", "function", "(", "request", ",", "textStatus", ")", "{", "getResponseDataJson", "(", "textStatus", ")", ";", "}", ",", "success", ":", "function", "(", "data", ",", "textStatus", ",", "request", ")", "{", "var", "response", "=", "getResponseDataJson", "(", "null", ",", "data", ")", ";", "if", "(", "response", ")", "{", "setButter", "(", "response", ".", "status", ")", ";", "if", "(", "!", "response", ".", "status", ".", "error", ")", "{", "$", "(", "'#row-'", "+", "mapreduce_id", ")", ".", "remove", "(", ")", ";", "}", "}", "}", "}", ")", ";", "}" ]
Cleans up a job with the given name and ID, updates butter with status.
[ "Cleans", "up", "a", "job", "with", "the", "given", "name", "and", "ID", "updates", "butter", "with", "status", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/mapreduce/mapreduce/static/status.js#L157-L182
5,234
catapult-project/catapult
third_party/mapreduce/mapreduce/static/status.js
getJobDetail
function getJobDetail(jobId, resultFunc) { $.ajax({ type: 'GET', url: 'command/get_job_detail', dataType: 'text', data: {'mapreduce_id': jobId}, statusCode: { 404: function() { setButter('job ' + jobId + ' was not found.', true); } }, error: function(request, textStatus) { getResponseDataJson(textStatus); }, success: function(data, textStatus, request) { var response = getResponseDataJson(null, data); if (response) { resultFunc(jobId, response); } } }); }
javascript
function getJobDetail(jobId, resultFunc) { $.ajax({ type: 'GET', url: 'command/get_job_detail', dataType: 'text', data: {'mapreduce_id': jobId}, statusCode: { 404: function() { setButter('job ' + jobId + ' was not found.', true); } }, error: function(request, textStatus) { getResponseDataJson(textStatus); }, success: function(data, textStatus, request) { var response = getResponseDataJson(null, data); if (response) { resultFunc(jobId, response); } } }); }
[ "function", "getJobDetail", "(", "jobId", ",", "resultFunc", ")", "{", "$", ".", "ajax", "(", "{", "type", ":", "'GET'", ",", "url", ":", "'command/get_job_detail'", ",", "dataType", ":", "'text'", ",", "data", ":", "{", "'mapreduce_id'", ":", "jobId", "}", ",", "statusCode", ":", "{", "404", ":", "function", "(", ")", "{", "setButter", "(", "'job '", "+", "jobId", "+", "' was not found.'", ",", "true", ")", ";", "}", "}", ",", "error", ":", "function", "(", "request", ",", "textStatus", ")", "{", "getResponseDataJson", "(", "textStatus", ")", ";", "}", ",", "success", ":", "function", "(", "data", ",", "textStatus", ",", "request", ")", "{", "var", "response", "=", "getResponseDataJson", "(", "null", ",", "data", ")", ";", "if", "(", "response", ")", "{", "resultFunc", "(", "jobId", ",", "response", ")", ";", "}", "}", "}", ")", ";", "}" ]
Retrieve the detail for a job.
[ "Retrieve", "the", "detail", "for", "a", "job", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/mapreduce/mapreduce/static/status.js#L209-L230
5,235
catapult-project/catapult
third_party/mapreduce/mapreduce/static/status.js
getSortedKeys
function getSortedKeys(obj) { var keys = []; $.each(obj, function(key, value) { keys.push(key); }); keys.sort(); return keys; }
javascript
function getSortedKeys(obj) { var keys = []; $.each(obj, function(key, value) { keys.push(key); }); keys.sort(); return keys; }
[ "function", "getSortedKeys", "(", "obj", ")", "{", "var", "keys", "=", "[", "]", ";", "$", ".", "each", "(", "obj", ",", "function", "(", "key", ",", "value", ")", "{", "keys", ".", "push", "(", "key", ")", ";", "}", ")", ";", "keys", ".", "sort", "(", ")", ";", "return", "keys", ";", "}" ]
Returns an array of the keys of an object in sorted order.
[ "Returns", "an", "array", "of", "the", "keys", "of", "an", "object", "in", "sorted", "order", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/mapreduce/mapreduce/static/status.js#L239-L246
5,236
catapult-project/catapult
third_party/mapreduce/mapreduce/static/status.js
getElapsedTimeString
function getElapsedTimeString(start_timestamp_ms, updated_timestamp_ms) { var updatedDiff = updated_timestamp_ms - start_timestamp_ms; var updatedDays = Math.floor(updatedDiff / 86400000.0); updatedDiff -= (updatedDays * 86400000.0); var updatedHours = Math.floor(updatedDiff / 3600000.0); updatedDiff -= (updatedHours * 3600000.0); var updatedMinutes = Math.floor(updatedDiff / 60000.0); updatedDiff -= (updatedMinutes * 60000.0); var updatedSeconds = Math.floor(updatedDiff / 1000.0); var updatedString = ''; if (updatedDays == 1) { updatedString = '1 day, '; } else if (updatedDays > 1) { updatedString = '' + updatedDays + ' days, '; } updatedString += leftPadNumber(updatedHours, 2, '0') + ':' + leftPadNumber(updatedMinutes, 2, '0') + ':' + leftPadNumber(updatedSeconds, 2, '0'); return updatedString; }
javascript
function getElapsedTimeString(start_timestamp_ms, updated_timestamp_ms) { var updatedDiff = updated_timestamp_ms - start_timestamp_ms; var updatedDays = Math.floor(updatedDiff / 86400000.0); updatedDiff -= (updatedDays * 86400000.0); var updatedHours = Math.floor(updatedDiff / 3600000.0); updatedDiff -= (updatedHours * 3600000.0); var updatedMinutes = Math.floor(updatedDiff / 60000.0); updatedDiff -= (updatedMinutes * 60000.0); var updatedSeconds = Math.floor(updatedDiff / 1000.0); var updatedString = ''; if (updatedDays == 1) { updatedString = '1 day, '; } else if (updatedDays > 1) { updatedString = '' + updatedDays + ' days, '; } updatedString += leftPadNumber(updatedHours, 2, '0') + ':' + leftPadNumber(updatedMinutes, 2, '0') + ':' + leftPadNumber(updatedSeconds, 2, '0'); return updatedString; }
[ "function", "getElapsedTimeString", "(", "start_timestamp_ms", ",", "updated_timestamp_ms", ")", "{", "var", "updatedDiff", "=", "updated_timestamp_ms", "-", "start_timestamp_ms", ";", "var", "updatedDays", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "86400000.0", ")", ";", "updatedDiff", "-=", "(", "updatedDays", "*", "86400000.0", ")", ";", "var", "updatedHours", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "3600000.0", ")", ";", "updatedDiff", "-=", "(", "updatedHours", "*", "3600000.0", ")", ";", "var", "updatedMinutes", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "60000.0", ")", ";", "updatedDiff", "-=", "(", "updatedMinutes", "*", "60000.0", ")", ";", "var", "updatedSeconds", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "1000.0", ")", ";", "var", "updatedString", "=", "''", ";", "if", "(", "updatedDays", "==", "1", ")", "{", "updatedString", "=", "'1 day, '", ";", "}", "else", "if", "(", "updatedDays", ">", "1", ")", "{", "updatedString", "=", "''", "+", "updatedDays", "+", "' days, '", ";", "}", "updatedString", "+=", "leftPadNumber", "(", "updatedHours", ",", "2", ",", "'0'", ")", "+", "':'", "+", "leftPadNumber", "(", "updatedMinutes", ",", "2", ",", "'0'", ")", "+", "':'", "+", "leftPadNumber", "(", "updatedSeconds", ",", "2", ",", "'0'", ")", ";", "return", "updatedString", ";", "}" ]
Get locale time string for time portion of job runtime. Specially handle number of days running as a prefix.
[ "Get", "locale", "time", "string", "for", "time", "portion", "of", "job", "runtime", ".", "Specially", "handle", "number", "of", "days", "running", "as", "a", "prefix", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/mapreduce/mapreduce/static/status.js#L274-L296
5,237
catapult-project/catapult
third_party/mapreduce/mapreduce/static/status.js
addParameters
function addParameters(params, prefix) { if (!params) { return; } var sortedParams = getSortedKeys(params); $.each(sortedParams, function(index, key) { var value = params[key]; var paramId = 'job-' + prefix + key + '-param'; var paramP = $('<p class="editable-input">'); // Deal with the case in which the value is an object rather than // just the default value string. var prettyKey = key; if (value && value['human_name']) { prettyKey = value['human_name']; } if (value && value['default_value']) { value = value['default_value']; } $('<label>') .attr('for', paramId) .text(prettyKey) .appendTo(paramP); $('<span>').text(': ').appendTo(paramP); $('<input type="text">') .attr('id', paramId) .attr('name', prefix + key) .attr('value', value) .appendTo(paramP); paramP.appendTo(jobForm); }); }
javascript
function addParameters(params, prefix) { if (!params) { return; } var sortedParams = getSortedKeys(params); $.each(sortedParams, function(index, key) { var value = params[key]; var paramId = 'job-' + prefix + key + '-param'; var paramP = $('<p class="editable-input">'); // Deal with the case in which the value is an object rather than // just the default value string. var prettyKey = key; if (value && value['human_name']) { prettyKey = value['human_name']; } if (value && value['default_value']) { value = value['default_value']; } $('<label>') .attr('for', paramId) .text(prettyKey) .appendTo(paramP); $('<span>').text(': ').appendTo(paramP); $('<input type="text">') .attr('id', paramId) .attr('name', prefix + key) .attr('value', value) .appendTo(paramP); paramP.appendTo(jobForm); }); }
[ "function", "addParameters", "(", "params", ",", "prefix", ")", "{", "if", "(", "!", "params", ")", "{", "return", ";", "}", "var", "sortedParams", "=", "getSortedKeys", "(", "params", ")", ";", "$", ".", "each", "(", "sortedParams", ",", "function", "(", "index", ",", "key", ")", "{", "var", "value", "=", "params", "[", "key", "]", ";", "var", "paramId", "=", "'job-'", "+", "prefix", "+", "key", "+", "'-param'", ";", "var", "paramP", "=", "$", "(", "'<p class=\"editable-input\">'", ")", ";", "// Deal with the case in which the value is an object rather than", "// just the default value string.", "var", "prettyKey", "=", "key", ";", "if", "(", "value", "&&", "value", "[", "'human_name'", "]", ")", "{", "prettyKey", "=", "value", "[", "'human_name'", "]", ";", "}", "if", "(", "value", "&&", "value", "[", "'default_value'", "]", ")", "{", "value", "=", "value", "[", "'default_value'", "]", ";", "}", "$", "(", "'<label>'", ")", ".", "attr", "(", "'for'", ",", "paramId", ")", ".", "text", "(", "prettyKey", ")", ".", "appendTo", "(", "paramP", ")", ";", "$", "(", "'<span>'", ")", ".", "text", "(", "': '", ")", ".", "appendTo", "(", "paramP", ")", ";", "$", "(", "'<input type=\"text\">'", ")", ".", "attr", "(", "'id'", ",", "paramId", ")", ".", "attr", "(", "'name'", ",", "prefix", "+", "key", ")", ".", "attr", "(", "'value'", ",", "value", ")", ".", "appendTo", "(", "paramP", ")", ";", "paramP", ".", "appendTo", "(", "jobForm", ")", ";", "}", ")", ";", "}" ]
Add parameter values to the job form.
[ "Add", "parameter", "values", "to", "the", "job", "form", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/mapreduce/mapreduce/static/status.js#L475-L509
5,238
catapult-project/catapult
dashboard/dashboard/spa/details-table.js
setCell
function setCell(map, key, columnCount, columnIndex, value) { if (!map.has(key)) map.set(key, new Array(columnCount)); map.get(key)[columnIndex] = value; }
javascript
function setCell(map, key, columnCount, columnIndex, value) { if (!map.has(key)) map.set(key, new Array(columnCount)); map.get(key)[columnIndex] = value; }
[ "function", "setCell", "(", "map", ",", "key", ",", "columnCount", ",", "columnIndex", ",", "value", ")", "{", "if", "(", "!", "map", ".", "has", "(", "key", ")", ")", "map", ".", "set", "(", "key", ",", "new", "Array", "(", "columnCount", ")", ")", ";", "map", ".", "get", "(", "key", ")", "[", "columnIndex", "]", "=", "value", ";", "}" ]
Build a table map.
[ "Build", "a", "table", "map", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/dashboard/dashboard/spa/details-table.js#L231-L234
5,239
catapult-project/catapult
dashboard/dashboard/spa/details-table.js
getDescriptorParts
function getDescriptorParts(lineDescriptor, descriptorFlags) { const descriptorParts = []; if (descriptorFlags.suite) { descriptorParts.push(lineDescriptor.suites.map(breakWords).join('\n')); } if (descriptorFlags.measurement) { descriptorParts.push(breakWords(lineDescriptor.measurement)); } if (descriptorFlags.bot) { descriptorParts.push(lineDescriptor.bots.map(breakWords).join('\n')); } if (descriptorFlags.cases) { descriptorParts.push(lineDescriptor.cases.map(breakWords).join('\n')); } if (descriptorFlags.buildType) { descriptorParts.push(lineDescriptor.buildType); } return descriptorParts; }
javascript
function getDescriptorParts(lineDescriptor, descriptorFlags) { const descriptorParts = []; if (descriptorFlags.suite) { descriptorParts.push(lineDescriptor.suites.map(breakWords).join('\n')); } if (descriptorFlags.measurement) { descriptorParts.push(breakWords(lineDescriptor.measurement)); } if (descriptorFlags.bot) { descriptorParts.push(lineDescriptor.bots.map(breakWords).join('\n')); } if (descriptorFlags.cases) { descriptorParts.push(lineDescriptor.cases.map(breakWords).join('\n')); } if (descriptorFlags.buildType) { descriptorParts.push(lineDescriptor.buildType); } return descriptorParts; }
[ "function", "getDescriptorParts", "(", "lineDescriptor", ",", "descriptorFlags", ")", "{", "const", "descriptorParts", "=", "[", "]", ";", "if", "(", "descriptorFlags", ".", "suite", ")", "{", "descriptorParts", ".", "push", "(", "lineDescriptor", ".", "suites", ".", "map", "(", "breakWords", ")", ".", "join", "(", "'\\n'", ")", ")", ";", "}", "if", "(", "descriptorFlags", ".", "measurement", ")", "{", "descriptorParts", ".", "push", "(", "breakWords", "(", "lineDescriptor", ".", "measurement", ")", ")", ";", "}", "if", "(", "descriptorFlags", ".", "bot", ")", "{", "descriptorParts", ".", "push", "(", "lineDescriptor", ".", "bots", ".", "map", "(", "breakWords", ")", ".", "join", "(", "'\\n'", ")", ")", ";", "}", "if", "(", "descriptorFlags", ".", "cases", ")", "{", "descriptorParts", ".", "push", "(", "lineDescriptor", ".", "cases", ".", "map", "(", "breakWords", ")", ".", "join", "(", "'\\n'", ")", ")", ";", "}", "if", "(", "descriptorFlags", ".", "buildType", ")", "{", "descriptorParts", ".", "push", "(", "lineDescriptor", ".", "buildType", ")", ";", "}", "return", "descriptorParts", ";", "}" ]
Build an array of strings to display the parts of lineDescriptor that are not common to all of this details-table's lineDescriptors.
[ "Build", "an", "array", "of", "strings", "to", "display", "the", "parts", "of", "lineDescriptor", "that", "are", "not", "common", "to", "all", "of", "this", "details", "-", "table", "s", "lineDescriptors", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/dashboard/dashboard/spa/details-table.js#L367-L385
5,240
catapult-project/catapult
dashboard/dashboard/spa/timeseries-cache-request.js
findLowIndexInSortedArray
function findLowIndexInSortedArray(ary, getKey, loVal) { if (ary.length === 0) return 1; let low = 0; let high = ary.length - 1; let i; let comparison; let hitPos = -1; while (low <= high) { i = Math.floor((low + high) / 2); comparison = getKey(ary[i]) - loVal; if (comparison < 0) { low = i + 1; continue; } else if (comparison > 0) { high = i - 1; continue; } else { hitPos = i; high = i - 1; } } // return where we hit, or failing that the low pos return hitPos !== -1 ? hitPos : low; }
javascript
function findLowIndexInSortedArray(ary, getKey, loVal) { if (ary.length === 0) return 1; let low = 0; let high = ary.length - 1; let i; let comparison; let hitPos = -1; while (low <= high) { i = Math.floor((low + high) / 2); comparison = getKey(ary[i]) - loVal; if (comparison < 0) { low = i + 1; continue; } else if (comparison > 0) { high = i - 1; continue; } else { hitPos = i; high = i - 1; } } // return where we hit, or failing that the low pos return hitPos !== -1 ? hitPos : low; }
[ "function", "findLowIndexInSortedArray", "(", "ary", ",", "getKey", ",", "loVal", ")", "{", "if", "(", "ary", ".", "length", "===", "0", ")", "return", "1", ";", "let", "low", "=", "0", ";", "let", "high", "=", "ary", ".", "length", "-", "1", ";", "let", "i", ";", "let", "comparison", ";", "let", "hitPos", "=", "-", "1", ";", "while", "(", "low", "<=", "high", ")", "{", "i", "=", "Math", ".", "floor", "(", "(", "low", "+", "high", ")", "/", "2", ")", ";", "comparison", "=", "getKey", "(", "ary", "[", "i", "]", ")", "-", "loVal", ";", "if", "(", "comparison", "<", "0", ")", "{", "low", "=", "i", "+", "1", ";", "continue", ";", "}", "else", "if", "(", "comparison", ">", "0", ")", "{", "high", "=", "i", "-", "1", ";", "continue", ";", "}", "else", "{", "hitPos", "=", "i", ";", "high", "=", "i", "-", "1", ";", "}", "}", "// return where we hit, or failing that the low pos", "return", "hitPos", "!==", "-", "1", "?", "hitPos", ":", "low", ";", "}" ]
Finds the first index in the array whose value is >= loVal. The key for the search is defined by the getKey. This array must be prearranged such that ary.map(getKey) would also be sorted in ascending order. @param {Array} ary An array of arbitrary objects. @param {function():*} getKey Callback that produces a key value from an element in ary. @param {number} loVal Value for which to search. @return {Number} Offset o into ary where all ary[i] for i <= o are < loVal, or ary.length if loVal is greater than all elements in the array.
[ "Finds", "the", "first", "index", "in", "the", "array", "whose", "value", "is", ">", "=", "loVal", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/dashboard/dashboard/spa/timeseries-cache-request.js#L58-L80
5,241
catapult-project/catapult
netlog_viewer/netlog_viewer/log_util.js
createLogDump
function createLogDump( userComments, constants, events, polledData, tabData, numericDate) { var logDump = { 'userComments': userComments, 'constants': constants, 'events': events, 'polledData': polledData, 'tabData': tabData }; // Not technically client info, but it's used at the same point in the code. if (numericDate && constants.clientInfo) { constants.clientInfo.numericDate = numericDate; } return logDump; }
javascript
function createLogDump( userComments, constants, events, polledData, tabData, numericDate) { var logDump = { 'userComments': userComments, 'constants': constants, 'events': events, 'polledData': polledData, 'tabData': tabData }; // Not technically client info, but it's used at the same point in the code. if (numericDate && constants.clientInfo) { constants.clientInfo.numericDate = numericDate; } return logDump; }
[ "function", "createLogDump", "(", "userComments", ",", "constants", ",", "events", ",", "polledData", ",", "tabData", ",", "numericDate", ")", "{", "var", "logDump", "=", "{", "'userComments'", ":", "userComments", ",", "'constants'", ":", "constants", ",", "'events'", ":", "events", ",", "'polledData'", ":", "polledData", ",", "'tabData'", ":", "tabData", "}", ";", "// Not technically client info, but it's used at the same point in the code.", "if", "(", "numericDate", "&&", "constants", ".", "clientInfo", ")", "{", "constants", ".", "clientInfo", ".", "numericDate", "=", "numericDate", ";", "}", "return", "logDump", ";", "}" ]
Creates a new log dump. |events| is a list of all events, |polledData| is an object containing the results of each poll, |tabData| is an object containing data for individual tabs, |date| is the time the dump was created, as a formatted string. Returns the new log dump as an object. Resulting object may have a null |numericDate|. TODO(eroman): Use javadoc notation for these parameters. Log dumps are just JSON objects containing five values: |userComments| User-provided notes describing what this dump file is about. |constants| needed to interpret the data. This also includes some browser state information. |events| from the NetLog. |polledData| from each PollableDataHelper available on the source OS. |tabData| containing any tab-specific state that's not present in |polledData|. |polledData| and |tabData| may be empty objects, or may be missing data for tabs not present on the OS the log is from.
[ "Creates", "a", "new", "log", "dump", ".", "|events|", "is", "a", "list", "of", "all", "events", "|polledData|", "is", "an", "object", "containing", "the", "results", "of", "each", "poll", "|tabData|", "is", "an", "object", "containing", "data", "for", "individual", "tabs", "|date|", "is", "the", "time", "the", "dump", "was", "created", "as", "a", "formatted", "string", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_util.js#L33-L49
5,242
catapult-project/catapult
netlog_viewer/netlog_viewer/log_util.js
onUpdateAllCompleted
function onUpdateAllCompleted(userComments, callback, polledData) { var logDump = createLogDump( userComments, Constants, EventsTracker.getInstance().getAllCapturedEvents(), polledData, getTabData_(), timeutil.getCurrentTime()); callback(JSON.stringify(logDump)); }
javascript
function onUpdateAllCompleted(userComments, callback, polledData) { var logDump = createLogDump( userComments, Constants, EventsTracker.getInstance().getAllCapturedEvents(), polledData, getTabData_(), timeutil.getCurrentTime()); callback(JSON.stringify(logDump)); }
[ "function", "onUpdateAllCompleted", "(", "userComments", ",", "callback", ",", "polledData", ")", "{", "var", "logDump", "=", "createLogDump", "(", "userComments", ",", "Constants", ",", "EventsTracker", ".", "getInstance", "(", ")", ".", "getAllCapturedEvents", "(", ")", ",", "polledData", ",", "getTabData_", "(", ")", ",", "timeutil", ".", "getCurrentTime", "(", ")", ")", ";", "callback", "(", "JSON", ".", "stringify", "(", "logDump", ")", ")", ";", "}" ]
Creates a full log dump using |polledData| and the return value of each tab's saveState function and passes it to |callback|.
[ "Creates", "a", "full", "log", "dump", "using", "|polledData|", "and", "the", "return", "value", "of", "each", "tab", "s", "saveState", "function", "and", "passes", "it", "to", "|callback|", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_util.js#L55-L61
5,243
catapult-project/catapult
netlog_viewer/netlog_viewer/log_util.js
createLogDumpAsync
function createLogDumpAsync(userComments, callback) { g_browser.updateAllInfo( onUpdateAllCompleted.bind(null, userComments, callback)); }
javascript
function createLogDumpAsync(userComments, callback) { g_browser.updateAllInfo( onUpdateAllCompleted.bind(null, userComments, callback)); }
[ "function", "createLogDumpAsync", "(", "userComments", ",", "callback", ")", "{", "g_browser", ".", "updateAllInfo", "(", "onUpdateAllCompleted", ".", "bind", "(", "null", ",", "userComments", ",", "callback", ")", ")", ";", "}" ]
Called to create a new log dump. Must not be called once a dump has been loaded. Once a log dump has been created, |callback| is passed the dumped text as a string.
[ "Called", "to", "create", "a", "new", "log", "dump", ".", "Must", "not", "be", "called", "once", "a", "dump", "has", "been", "loaded", ".", "Once", "a", "log", "dump", "has", "been", "created", "|callback|", "is", "passed", "the", "dumped", "text", "as", "a", "string", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_util.js#L68-L71
5,244
catapult-project/catapult
netlog_viewer/netlog_viewer/log_util.js
getTabData_
function getTabData_() { var tabData = {}; var tabSwitcher = MainView.getInstance().tabSwitcher(); var tabIdToView = tabSwitcher.getAllTabViews(); for (var tabId in tabIdToView) { var view = tabIdToView[tabId]; if (view.saveState) tabData[tabId] = view.saveState(); } }
javascript
function getTabData_() { var tabData = {}; var tabSwitcher = MainView.getInstance().tabSwitcher(); var tabIdToView = tabSwitcher.getAllTabViews(); for (var tabId in tabIdToView) { var view = tabIdToView[tabId]; if (view.saveState) tabData[tabId] = view.saveState(); } }
[ "function", "getTabData_", "(", ")", "{", "var", "tabData", "=", "{", "}", ";", "var", "tabSwitcher", "=", "MainView", ".", "getInstance", "(", ")", ".", "tabSwitcher", "(", ")", ";", "var", "tabIdToView", "=", "tabSwitcher", ".", "getAllTabViews", "(", ")", ";", "for", "(", "var", "tabId", "in", "tabIdToView", ")", "{", "var", "view", "=", "tabIdToView", "[", "tabId", "]", ";", "if", "(", "view", ".", "saveState", ")", "tabData", "[", "tabId", "]", "=", "view", ".", "saveState", "(", ")", ";", "}", "}" ]
Gather any tab-specific state information prior to creating a log dump.
[ "Gather", "any", "tab", "-", "specific", "state", "information", "prior", "to", "creating", "a", "log", "dump", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_util.js#L76-L85
5,245
catapult-project/catapult
netlog_viewer/netlog_viewer/log_util.js
loadLogFile
function loadLogFile(logFileContents, fileName) { // Try and parse the log dump as a single JSON string. If this succeeds, // it's most likely a full log dump. Otherwise, it may be a dump created by // --log-net-log. var parsedDump = null; var errorString = ''; try { parsedDump = JSON.parse(logFileContents); } catch (error) { try { // We may have a --log-net-log=blah log dump. If so, remove the comma // after the final good entry, and add the necessary close brackets. var end = Math.max( logFileContents.lastIndexOf(',\n'), logFileContents.lastIndexOf(',\r')); if (end != -1) { parsedDump = JSON.parse(logFileContents.substring(0, end) + ']}'); errorString += 'Log file truncated. Events may be missing.\n'; } } catch (error2) { } } if (!parsedDump) return 'Unable to parse log dump as JSON file.'; return errorString + loadLogDump(parsedDump, fileName); }
javascript
function loadLogFile(logFileContents, fileName) { // Try and parse the log dump as a single JSON string. If this succeeds, // it's most likely a full log dump. Otherwise, it may be a dump created by // --log-net-log. var parsedDump = null; var errorString = ''; try { parsedDump = JSON.parse(logFileContents); } catch (error) { try { // We may have a --log-net-log=blah log dump. If so, remove the comma // after the final good entry, and add the necessary close brackets. var end = Math.max( logFileContents.lastIndexOf(',\n'), logFileContents.lastIndexOf(',\r')); if (end != -1) { parsedDump = JSON.parse(logFileContents.substring(0, end) + ']}'); errorString += 'Log file truncated. Events may be missing.\n'; } } catch (error2) { } } if (!parsedDump) return 'Unable to parse log dump as JSON file.'; return errorString + loadLogDump(parsedDump, fileName); }
[ "function", "loadLogFile", "(", "logFileContents", ",", "fileName", ")", "{", "// Try and parse the log dump as a single JSON string. If this succeeds,", "// it's most likely a full log dump. Otherwise, it may be a dump created by", "// --log-net-log.", "var", "parsedDump", "=", "null", ";", "var", "errorString", "=", "''", ";", "try", "{", "parsedDump", "=", "JSON", ".", "parse", "(", "logFileContents", ")", ";", "}", "catch", "(", "error", ")", "{", "try", "{", "// We may have a --log-net-log=blah log dump. If so, remove the comma", "// after the final good entry, and add the necessary close brackets.", "var", "end", "=", "Math", ".", "max", "(", "logFileContents", ".", "lastIndexOf", "(", "',\\n'", ")", ",", "logFileContents", ".", "lastIndexOf", "(", "',\\r'", ")", ")", ";", "if", "(", "end", "!=", "-", "1", ")", "{", "parsedDump", "=", "JSON", ".", "parse", "(", "logFileContents", ".", "substring", "(", "0", ",", "end", ")", "+", "']}'", ")", ";", "errorString", "+=", "'Log file truncated. Events may be missing.\\n'", ";", "}", "}", "catch", "(", "error2", ")", "{", "}", "}", "if", "(", "!", "parsedDump", ")", "return", "'Unable to parse log dump as JSON file.'", ";", "return", "errorString", "+", "loadLogDump", "(", "parsedDump", ",", "fileName", ")", ";", "}" ]
Loads a log dump from the string |logFileContents|, which can be either a full net-internals dump, or a NetLog dump only. Returns a string containing a log of the load.
[ "Loads", "a", "log", "dump", "from", "the", "string", "|logFileContents|", "which", "can", "be", "either", "a", "full", "net", "-", "internals", "dump", "or", "a", "NetLog", "dump", "only", ".", "Returns", "a", "string", "containing", "a", "log", "of", "the", "load", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/log_util.js#L250-L276
5,246
catapult-project/catapult
dashboard/dashboard/spa/group-alerts.js
isRelated
function isRelated(a, b) { if (a.measurementAvg === b.measurementAvg) return true; if (a.relatedNames && a.relatedNames.has(b.measurementAvg)) { return true; } if (b.relatedNames && b.relatedNames.has(a.measurementAvg)) { return true; } return false; }
javascript
function isRelated(a, b) { if (a.measurementAvg === b.measurementAvg) return true; if (a.relatedNames && a.relatedNames.has(b.measurementAvg)) { return true; } if (b.relatedNames && b.relatedNames.has(a.measurementAvg)) { return true; } return false; }
[ "function", "isRelated", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "measurementAvg", "===", "b", ".", "measurementAvg", ")", "return", "true", ";", "if", "(", "a", ".", "relatedNames", "&&", "a", ".", "relatedNames", ".", "has", "(", "b", ".", "measurementAvg", ")", ")", "{", "return", "true", ";", "}", "if", "(", "b", ".", "relatedNames", "&&", "b", ".", "relatedNames", ".", "has", "(", "a", ".", "measurementAvg", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Two Alerts are related if either A) their measurements are equal, or B) either's relatedNames contains the other's measurement. @param {!Alert} a @param {!Alert} b @return {boolean}
[ "Two", "Alerts", "are", "related", "if", "either", "A", ")", "their", "measurements", "are", "equal", "or", "B", ")", "either", "s", "relatedNames", "contains", "the", "other", "s", "measurement", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/dashboard/dashboard/spa/group-alerts.js#L36-L47
5,247
catapult-project/catapult
third_party/polymer3/bower_components/polymer/lib/mixins/properties-mixin.js
superPropertiesClass
function superPropertiesClass(constructor) { const superCtor = Object.getPrototypeOf(constructor); // Note, the `PropertiesMixin` class below only refers to the class // generated by this call to the mixin; the instanceof test only works // because the mixin is deduped and guaranteed only to apply once, hence // all constructors in a proto chain will see the same `PropertiesMixin` return (superCtor.prototype instanceof PropertiesMixin) ? /** @type {PropertiesMixinConstructor} */ (superCtor) : null; }
javascript
function superPropertiesClass(constructor) { const superCtor = Object.getPrototypeOf(constructor); // Note, the `PropertiesMixin` class below only refers to the class // generated by this call to the mixin; the instanceof test only works // because the mixin is deduped and guaranteed only to apply once, hence // all constructors in a proto chain will see the same `PropertiesMixin` return (superCtor.prototype instanceof PropertiesMixin) ? /** @type {PropertiesMixinConstructor} */ (superCtor) : null; }
[ "function", "superPropertiesClass", "(", "constructor", ")", "{", "const", "superCtor", "=", "Object", ".", "getPrototypeOf", "(", "constructor", ")", ";", "// Note, the `PropertiesMixin` class below only refers to the class", "// generated by this call to the mixin; the instanceof test only works", "// because the mixin is deduped and guaranteed only to apply once, hence", "// all constructors in a proto chain will see the same `PropertiesMixin`", "return", "(", "superCtor", ".", "prototype", "instanceof", "PropertiesMixin", ")", "?", "/** @type {PropertiesMixinConstructor} */", "(", "superCtor", ")", ":", "null", ";", "}" ]
Returns the super class constructor for the given class, if it is an instance of the PropertiesMixin. @param {!PropertiesMixinConstructor} constructor PropertiesMixin constructor @return {PropertiesMixinConstructor} Super class constructor
[ "Returns", "the", "super", "class", "constructor", "for", "the", "given", "class", "if", "it", "is", "an", "instance", "of", "the", "PropertiesMixin", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer3/bower_components/polymer/lib/mixins/properties-mixin.js#L66-L75
5,248
catapult-project/catapult
tracing/third_party/gl-matrix/jsdoc-template/publish.js
makeSrcFile
function makeSrcFile(path, srcDir, name) { if (JSDOC.opt.s) return; if (!name) { name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_"); name = name.replace(/\:/g, "_"); } var src = {path: path, name:name, charset: IO.encoding, hilited: ""}; if (defined(JSDOC.PluginManager)) { JSDOC.PluginManager.run("onPublishSrc", src); } if (src.hilited) { IO.saveFile(srcDir, name+publish.conf.ext, src.hilited); } }
javascript
function makeSrcFile(path, srcDir, name) { if (JSDOC.opt.s) return; if (!name) { name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_"); name = name.replace(/\:/g, "_"); } var src = {path: path, name:name, charset: IO.encoding, hilited: ""}; if (defined(JSDOC.PluginManager)) { JSDOC.PluginManager.run("onPublishSrc", src); } if (src.hilited) { IO.saveFile(srcDir, name+publish.conf.ext, src.hilited); } }
[ "function", "makeSrcFile", "(", "path", ",", "srcDir", ",", "name", ")", "{", "if", "(", "JSDOC", ".", "opt", ".", "s", ")", "return", ";", "if", "(", "!", "name", ")", "{", "name", "=", "path", ".", "replace", "(", "/", "\\.\\.?[\\\\\\/]", "/", "g", ",", "\"\"", ")", ".", "replace", "(", "/", "[\\\\\\/]", "/", "g", ",", "\"_\"", ")", ";", "name", "=", "name", ".", "replace", "(", "/", "\\:", "/", "g", ",", "\"_\"", ")", ";", "}", "var", "src", "=", "{", "path", ":", "path", ",", "name", ":", "name", ",", "charset", ":", "IO", ".", "encoding", ",", "hilited", ":", "\"\"", "}", ";", "if", "(", "defined", "(", "JSDOC", ".", "PluginManager", ")", ")", "{", "JSDOC", ".", "PluginManager", ".", "run", "(", "\"onPublishSrc\"", ",", "src", ")", ";", "}", "if", "(", "src", ".", "hilited", ")", "{", "IO", ".", "saveFile", "(", "srcDir", ",", "name", "+", "publish", ".", "conf", ".", "ext", ",", "src", ".", "hilited", ")", ";", "}", "}" ]
Turn a raw source file into a code-hilited page in the docs.
[ "Turn", "a", "raw", "source", "file", "into", "a", "code", "-", "hilited", "page", "in", "the", "docs", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/tracing/third_party/gl-matrix/jsdoc-template/publish.js#L154-L171
5,249
catapult-project/catapult
tracing/third_party/gl-matrix/jsdoc-template/publish.js
makeSignature
function makeSignature(params) { if (!params) return "()"; var signature = "(" + params.filter( function($) { return $.name.indexOf(".") == -1; // don't show config params in signature } ).map( function($) { return $.name; } ).join(", ") + ")"; return signature; }
javascript
function makeSignature(params) { if (!params) return "()"; var signature = "(" + params.filter( function($) { return $.name.indexOf(".") == -1; // don't show config params in signature } ).map( function($) { return $.name; } ).join(", ") + ")"; return signature; }
[ "function", "makeSignature", "(", "params", ")", "{", "if", "(", "!", "params", ")", "return", "\"()\"", ";", "var", "signature", "=", "\"(\"", "+", "params", ".", "filter", "(", "function", "(", "$", ")", "{", "return", "$", ".", "name", ".", "indexOf", "(", "\".\"", ")", "==", "-", "1", ";", "// don't show config params in signature", "}", ")", ".", "map", "(", "function", "(", "$", ")", "{", "return", "$", ".", "name", ";", "}", ")", ".", "join", "(", "\", \"", ")", "+", "\")\"", ";", "return", "signature", ";", "}" ]
Build output for displaying function parameters.
[ "Build", "output", "for", "displaying", "function", "parameters", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/tracing/third_party/gl-matrix/jsdoc-template/publish.js#L174-L190
5,250
catapult-project/catapult
third_party/pipeline/pipeline/ui/common.js
getIso8601String
function getIso8601String(timeMs) { var time = new Date(); time.setTime(timeMs); return '' + time.getUTCFullYear() + '-' + leftPadNumber(time.getUTCMonth() + 1, 2, '0') + '-' + leftPadNumber(time.getUTCDate(), 2, '0') + 'T' + leftPadNumber(time.getUTCHours(), 2, '0') + ':' + leftPadNumber(time.getUTCMinutes(), 2, '0') + ':' + leftPadNumber(time.getUTCSeconds(), 2, '0') + 'Z'; }
javascript
function getIso8601String(timeMs) { var time = new Date(); time.setTime(timeMs); return '' + time.getUTCFullYear() + '-' + leftPadNumber(time.getUTCMonth() + 1, 2, '0') + '-' + leftPadNumber(time.getUTCDate(), 2, '0') + 'T' + leftPadNumber(time.getUTCHours(), 2, '0') + ':' + leftPadNumber(time.getUTCMinutes(), 2, '0') + ':' + leftPadNumber(time.getUTCSeconds(), 2, '0') + 'Z'; }
[ "function", "getIso8601String", "(", "timeMs", ")", "{", "var", "time", "=", "new", "Date", "(", ")", ";", "time", ".", "setTime", "(", "timeMs", ")", ";", "return", "''", "+", "time", ".", "getUTCFullYear", "(", ")", "+", "'-'", "+", "leftPadNumber", "(", "time", ".", "getUTCMonth", "(", ")", "+", "1", ",", "2", ",", "'0'", ")", "+", "'-'", "+", "leftPadNumber", "(", "time", ".", "getUTCDate", "(", ")", ",", "2", ",", "'0'", ")", "+", "'T'", "+", "leftPadNumber", "(", "time", ".", "getUTCHours", "(", ")", ",", "2", ",", "'0'", ")", "+", "':'", "+", "leftPadNumber", "(", "time", ".", "getUTCMinutes", "(", ")", ",", "2", ",", "'0'", ")", "+", "':'", "+", "leftPadNumber", "(", "time", ".", "getUTCSeconds", "(", ")", ",", "2", ",", "'0'", ")", "+", "'Z'", ";", "}" ]
Convert milliseconds since the epoch to an ISO8601 datestring.
[ "Convert", "milliseconds", "since", "the", "epoch", "to", "an", "ISO8601", "datestring", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/common.js#L34-L44
5,251
catapult-project/catapult
third_party/pipeline/pipeline/ui/common.js
getElapsedTimeString
function getElapsedTimeString(startTimestampMs, updatedTimestampMs) { var updatedDiff = Math.max(0, updatedTimestampMs - startTimestampMs); var updatedDays = Math.floor(updatedDiff / 86400000.0); updatedDiff -= (updatedDays * 86400000.0); var updatedHours = Math.floor(updatedDiff / 3600000.0); updatedDiff -= (updatedHours * 3600000.0); var updatedMinutes = Math.floor(updatedDiff / 60000.0); updatedDiff -= (updatedMinutes * 60000.0); var updatedSeconds = Math.floor(updatedDiff / 1000.0); updatedDiff -= (updatedSeconds * 1000.0); var updatedMs = Math.floor(updatedDiff / 1.0); var updatedString = ''; if (updatedMinutes > 0) { if (updatedDays == 1) { updatedString = '1 day, '; } else if (updatedDays > 1) { updatedString = '' + updatedDays + ' days, '; } updatedString += leftPadNumber(updatedHours, 2, '0') + ':' + leftPadNumber(updatedMinutes, 2, '0') + ':' + leftPadNumber(updatedSeconds, 2, '0'); if (updatedMs > 0) { updatedString += '.' + leftPadNumber(updatedMs, 3, '0'); } } else { updatedString += updatedSeconds; updatedString += '.' + leftPadNumber(updatedMs, 3, '0'); updatedString += ' seconds'; } return updatedString; }
javascript
function getElapsedTimeString(startTimestampMs, updatedTimestampMs) { var updatedDiff = Math.max(0, updatedTimestampMs - startTimestampMs); var updatedDays = Math.floor(updatedDiff / 86400000.0); updatedDiff -= (updatedDays * 86400000.0); var updatedHours = Math.floor(updatedDiff / 3600000.0); updatedDiff -= (updatedHours * 3600000.0); var updatedMinutes = Math.floor(updatedDiff / 60000.0); updatedDiff -= (updatedMinutes * 60000.0); var updatedSeconds = Math.floor(updatedDiff / 1000.0); updatedDiff -= (updatedSeconds * 1000.0); var updatedMs = Math.floor(updatedDiff / 1.0); var updatedString = ''; if (updatedMinutes > 0) { if (updatedDays == 1) { updatedString = '1 day, '; } else if (updatedDays > 1) { updatedString = '' + updatedDays + ' days, '; } updatedString += leftPadNumber(updatedHours, 2, '0') + ':' + leftPadNumber(updatedMinutes, 2, '0') + ':' + leftPadNumber(updatedSeconds, 2, '0'); if (updatedMs > 0) { updatedString += '.' + leftPadNumber(updatedMs, 3, '0'); } } else { updatedString += updatedSeconds; updatedString += '.' + leftPadNumber(updatedMs, 3, '0'); updatedString += ' seconds'; } return updatedString; }
[ "function", "getElapsedTimeString", "(", "startTimestampMs", ",", "updatedTimestampMs", ")", "{", "var", "updatedDiff", "=", "Math", ".", "max", "(", "0", ",", "updatedTimestampMs", "-", "startTimestampMs", ")", ";", "var", "updatedDays", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "86400000.0", ")", ";", "updatedDiff", "-=", "(", "updatedDays", "*", "86400000.0", ")", ";", "var", "updatedHours", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "3600000.0", ")", ";", "updatedDiff", "-=", "(", "updatedHours", "*", "3600000.0", ")", ";", "var", "updatedMinutes", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "60000.0", ")", ";", "updatedDiff", "-=", "(", "updatedMinutes", "*", "60000.0", ")", ";", "var", "updatedSeconds", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "1000.0", ")", ";", "updatedDiff", "-=", "(", "updatedSeconds", "*", "1000.0", ")", ";", "var", "updatedMs", "=", "Math", ".", "floor", "(", "updatedDiff", "/", "1.0", ")", ";", "var", "updatedString", "=", "''", ";", "if", "(", "updatedMinutes", ">", "0", ")", "{", "if", "(", "updatedDays", "==", "1", ")", "{", "updatedString", "=", "'1 day, '", ";", "}", "else", "if", "(", "updatedDays", ">", "1", ")", "{", "updatedString", "=", "''", "+", "updatedDays", "+", "' days, '", ";", "}", "updatedString", "+=", "leftPadNumber", "(", "updatedHours", ",", "2", ",", "'0'", ")", "+", "':'", "+", "leftPadNumber", "(", "updatedMinutes", ",", "2", ",", "'0'", ")", "+", "':'", "+", "leftPadNumber", "(", "updatedSeconds", ",", "2", ",", "'0'", ")", ";", "if", "(", "updatedMs", ">", "0", ")", "{", "updatedString", "+=", "'.'", "+", "leftPadNumber", "(", "updatedMs", ",", "3", ",", "'0'", ")", ";", "}", "}", "else", "{", "updatedString", "+=", "updatedSeconds", ";", "updatedString", "+=", "'.'", "+", "leftPadNumber", "(", "updatedMs", ",", "3", ",", "'0'", ")", ";", "updatedString", "+=", "' seconds'", ";", "}", "return", "updatedString", ";", "}" ]
Get time string for job runtime. Specially handle number of days running as a prefix and milliseconds as a suffix. If the runtime is less than one minute, use the format "38.123 seconds" instead.
[ "Get", "time", "string", "for", "job", "runtime", ".", "Specially", "handle", "number", "of", "days", "running", "as", "a", "prefix", "and", "milliseconds", "as", "a", "suffix", ".", "If", "the", "runtime", "is", "less", "than", "one", "minute", "use", "the", "format", "38", ".", "123", "seconds", "instead", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/common.js#L50-L84
5,252
catapult-project/catapult
third_party/pipeline/pipeline/ui/common.js
setButter
function setButter(message, error, traceback, asHtml) { var butter = $('#butter'); // Prevent flicker on butter update by hiding it first. butter.css('display', 'none'); if (error) { butter.removeClass('info').addClass('error'); } else { butter.removeClass('error').addClass('info'); } butter.children().remove(); if (asHtml) { butter.append($('<div>').html(message)); } else { butter.append($('<div>').text(message)); } function centerButter() { butter.css('left', ($(window).width() - $(butter).outerWidth()) / 2); } if (traceback) { var showDetail = $('<a href="">').text('Detail'); showDetail.click(function(event) { $('#butter-detail').toggle(); centerButter(); event.preventDefault(); }); var butterDetail = $('<pre id="butter-detail">').text(traceback); butterDetail.css('display', 'none'); butter.append(showDetail); butter.append(butterDetail); } centerButter(); butter.css('display', null); }
javascript
function setButter(message, error, traceback, asHtml) { var butter = $('#butter'); // Prevent flicker on butter update by hiding it first. butter.css('display', 'none'); if (error) { butter.removeClass('info').addClass('error'); } else { butter.removeClass('error').addClass('info'); } butter.children().remove(); if (asHtml) { butter.append($('<div>').html(message)); } else { butter.append($('<div>').text(message)); } function centerButter() { butter.css('left', ($(window).width() - $(butter).outerWidth()) / 2); } if (traceback) { var showDetail = $('<a href="">').text('Detail'); showDetail.click(function(event) { $('#butter-detail').toggle(); centerButter(); event.preventDefault(); }); var butterDetail = $('<pre id="butter-detail">').text(traceback); butterDetail.css('display', 'none'); butter.append(showDetail); butter.append(butterDetail); } centerButter(); butter.css('display', null); }
[ "function", "setButter", "(", "message", ",", "error", ",", "traceback", ",", "asHtml", ")", "{", "var", "butter", "=", "$", "(", "'#butter'", ")", ";", "// Prevent flicker on butter update by hiding it first.", "butter", ".", "css", "(", "'display'", ",", "'none'", ")", ";", "if", "(", "error", ")", "{", "butter", ".", "removeClass", "(", "'info'", ")", ".", "addClass", "(", "'error'", ")", ";", "}", "else", "{", "butter", ".", "removeClass", "(", "'error'", ")", ".", "addClass", "(", "'info'", ")", ";", "}", "butter", ".", "children", "(", ")", ".", "remove", "(", ")", ";", "if", "(", "asHtml", ")", "{", "butter", ".", "append", "(", "$", "(", "'<div>'", ")", ".", "html", "(", "message", ")", ")", ";", "}", "else", "{", "butter", ".", "append", "(", "$", "(", "'<div>'", ")", ".", "text", "(", "message", ")", ")", ";", "}", "function", "centerButter", "(", ")", "{", "butter", ".", "css", "(", "'left'", ",", "(", "$", "(", "window", ")", ".", "width", "(", ")", "-", "$", "(", "butter", ")", ".", "outerWidth", "(", ")", ")", "/", "2", ")", ";", "}", "if", "(", "traceback", ")", "{", "var", "showDetail", "=", "$", "(", "'<a href=\"\">'", ")", ".", "text", "(", "'Detail'", ")", ";", "showDetail", ".", "click", "(", "function", "(", "event", ")", "{", "$", "(", "'#butter-detail'", ")", ".", "toggle", "(", ")", ";", "centerButter", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}", ")", ";", "var", "butterDetail", "=", "$", "(", "'<pre id=\"butter-detail\">'", ")", ".", "text", "(", "traceback", ")", ";", "butterDetail", ".", "css", "(", "'display'", ",", "'none'", ")", ";", "butter", ".", "append", "(", "showDetail", ")", ";", "butter", ".", "append", "(", "butterDetail", ")", ";", "}", "centerButter", "(", ")", ";", "butter", ".", "css", "(", "'display'", ",", "null", ")", ";", "}" ]
Sets the status butter, optionally indicating if it's an error message.
[ "Sets", "the", "status", "butter", "optionally", "indicating", "if", "it", "s", "an", "error", "message", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/pipeline/pipeline/ui/common.js#L94-L129
5,253
catapult-project/catapult
third_party/snap-it/popup.js
completeProcess
function completeProcess(messages) { var html = outputHTMLString(messages); var file = new Blob([html], {type: 'text/html'}); var url = URL.createObjectURL(file); var a = document.getElementById('button'); a.className = 'download'; a.innerHTML = 'Download'; a.href = url; a.download = "snap-it.html"; }
javascript
function completeProcess(messages) { var html = outputHTMLString(messages); var file = new Blob([html], {type: 'text/html'}); var url = URL.createObjectURL(file); var a = document.getElementById('button'); a.className = 'download'; a.innerHTML = 'Download'; a.href = url; a.download = "snap-it.html"; }
[ "function", "completeProcess", "(", "messages", ")", "{", "var", "html", "=", "outputHTMLString", "(", "messages", ")", ";", "var", "file", "=", "new", "Blob", "(", "[", "html", "]", ",", "{", "type", ":", "'text/html'", "}", ")", ";", "var", "url", "=", "URL", ".", "createObjectURL", "(", "file", ")", ";", "var", "a", "=", "document", ".", "getElementById", "(", "'button'", ")", ";", "a", ".", "className", "=", "'download'", ";", "a", ".", "innerHTML", "=", "'Download'", ";", "a", ".", "href", "=", "url", ";", "a", ".", "download", "=", "\"snap-it.html\"", ";", "}" ]
Takes all the responses from the injected content scripts and creates the HTML file for download. @param {Array<Object>} messages The response from all of the injected content scripts.
[ "Takes", "all", "the", "responses", "from", "the", "injected", "content", "scripts", "and", "creates", "the", "HTML", "file", "for", "download", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/snap-it/popup.js#L40-L50
5,254
catapult-project/catapult
third_party/snap-it/popup.js
outputHTMLString
function outputHTMLString(messages) { var rootIndex = 0; for (var i = 1; i < messages.length; i++) { rootIndex = messages[i].frameIndex === '0' ? i : rootIndex; } fillRemainingHolesAndMinimizeStyles(messages, rootIndex); return messages[rootIndex].html.join(''); }
javascript
function outputHTMLString(messages) { var rootIndex = 0; for (var i = 1; i < messages.length; i++) { rootIndex = messages[i].frameIndex === '0' ? i : rootIndex; } fillRemainingHolesAndMinimizeStyles(messages, rootIndex); return messages[rootIndex].html.join(''); }
[ "function", "outputHTMLString", "(", "messages", ")", "{", "var", "rootIndex", "=", "0", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "messages", ".", "length", ";", "i", "++", ")", "{", "rootIndex", "=", "messages", "[", "i", "]", ".", "frameIndex", "===", "'0'", "?", "i", ":", "rootIndex", ";", "}", "fillRemainingHolesAndMinimizeStyles", "(", "messages", ",", "rootIndex", ")", ";", "return", "messages", "[", "rootIndex", "]", ".", "html", ".", "join", "(", "''", ")", ";", "}" ]
Converts the responses from the injected content scripts into a string representing the HTML. @param {Array<Object>} messages The response from all of the injected content scripts. @return {string} The resulting HTML.
[ "Converts", "the", "responses", "from", "the", "injected", "content", "scripts", "into", "a", "string", "representing", "the", "HTML", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/snap-it/popup.js#L60-L67
5,255
catapult-project/catapult
third_party/snap-it/popup.js
minimizeStyles
function minimizeStyles(message) { var nestingDepth = message.frameIndex.split('.').length - 1; var iframe = document.createElement('iframe'); document.body.appendChild(iframe); iframe.setAttribute( 'style', `height: ${message.windowHeight}px;` + `width: ${message.windowWidth}px;`); var html = message.html.join(''); html = unescapeHTML(html, nestingDepth); iframe.contentDocument.documentElement.innerHTML = html; var doc = iframe.contentDocument; // Remove entry in |message.html| where extra style element was specified. message.html[message.pseudoElementTestingStyleIndex] = ''; var finalPseudoElements = []; for (var selector in message.pseudoElementSelectorToCSSMap) { minimizePseudoElementStyle(message, doc, selector, finalPseudoElements); } if (finalPseudoElements.length > 0) { message.html[message.pseudoElementPlaceHolderIndex] = `<style>${finalPseudoElements.join(' ')}</style>`; } if (message.rootStyleIndex) { minimizeStyle( message, doc, doc.documentElement, message.rootId, message.rootStyleIndex); } for (var id in message.idToStyleIndex) { var index = message.idToStyleIndex[id]; var element = doc.getElementById(id); if (element) { minimizeStyle(message, doc, element, id, index); } } iframe.remove(); }
javascript
function minimizeStyles(message) { var nestingDepth = message.frameIndex.split('.').length - 1; var iframe = document.createElement('iframe'); document.body.appendChild(iframe); iframe.setAttribute( 'style', `height: ${message.windowHeight}px;` + `width: ${message.windowWidth}px;`); var html = message.html.join(''); html = unescapeHTML(html, nestingDepth); iframe.contentDocument.documentElement.innerHTML = html; var doc = iframe.contentDocument; // Remove entry in |message.html| where extra style element was specified. message.html[message.pseudoElementTestingStyleIndex] = ''; var finalPseudoElements = []; for (var selector in message.pseudoElementSelectorToCSSMap) { minimizePseudoElementStyle(message, doc, selector, finalPseudoElements); } if (finalPseudoElements.length > 0) { message.html[message.pseudoElementPlaceHolderIndex] = `<style>${finalPseudoElements.join(' ')}</style>`; } if (message.rootStyleIndex) { minimizeStyle( message, doc, doc.documentElement, message.rootId, message.rootStyleIndex); } for (var id in message.idToStyleIndex) { var index = message.idToStyleIndex[id]; var element = doc.getElementById(id); if (element) { minimizeStyle(message, doc, element, id, index); } } iframe.remove(); }
[ "function", "minimizeStyles", "(", "message", ")", "{", "var", "nestingDepth", "=", "message", ".", "frameIndex", ".", "split", "(", "'.'", ")", ".", "length", "-", "1", ";", "var", "iframe", "=", "document", ".", "createElement", "(", "'iframe'", ")", ";", "document", ".", "body", ".", "appendChild", "(", "iframe", ")", ";", "iframe", ".", "setAttribute", "(", "'style'", ",", "`", "${", "message", ".", "windowHeight", "}", "`", "+", "`", "${", "message", ".", "windowWidth", "}", "`", ")", ";", "var", "html", "=", "message", ".", "html", ".", "join", "(", "''", ")", ";", "html", "=", "unescapeHTML", "(", "html", ",", "nestingDepth", ")", ";", "iframe", ".", "contentDocument", ".", "documentElement", ".", "innerHTML", "=", "html", ";", "var", "doc", "=", "iframe", ".", "contentDocument", ";", "// Remove entry in |message.html| where extra style element was specified.", "message", ".", "html", "[", "message", ".", "pseudoElementTestingStyleIndex", "]", "=", "''", ";", "var", "finalPseudoElements", "=", "[", "]", ";", "for", "(", "var", "selector", "in", "message", ".", "pseudoElementSelectorToCSSMap", ")", "{", "minimizePseudoElementStyle", "(", "message", ",", "doc", ",", "selector", ",", "finalPseudoElements", ")", ";", "}", "if", "(", "finalPseudoElements", ".", "length", ">", "0", ")", "{", "message", ".", "html", "[", "message", ".", "pseudoElementPlaceHolderIndex", "]", "=", "`", "${", "finalPseudoElements", ".", "join", "(", "' '", ")", "}", "`", ";", "}", "if", "(", "message", ".", "rootStyleIndex", ")", "{", "minimizeStyle", "(", "message", ",", "doc", ",", "doc", ".", "documentElement", ",", "message", ".", "rootId", ",", "message", ".", "rootStyleIndex", ")", ";", "}", "for", "(", "var", "id", "in", "message", ".", "idToStyleIndex", ")", "{", "var", "index", "=", "message", ".", "idToStyleIndex", "[", "id", "]", ";", "var", "element", "=", "doc", ".", "getElementById", "(", "id", ")", ";", "if", "(", "element", ")", "{", "minimizeStyle", "(", "message", ",", "doc", ",", "element", ",", "id", ",", "index", ")", ";", "}", "}", "iframe", ".", "remove", "(", ")", ";", "}" ]
Removes all style attribute properties that are unneeded. @param {Object} message The message Object whose style attributes should be minimized.
[ "Removes", "all", "style", "attribute", "properties", "that", "are", "unneeded", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/snap-it/popup.js#L99-L142
5,256
catapult-project/catapult
third_party/snap-it/popup.js
minimizePseudoElementStyle
function minimizePseudoElementStyle( message, doc, selector, finalPseudoElements) { var maxNumberOfIterations = 5; var match = selector.match(/^#(.*):(:.*)$/); var id = match[1]; var type = match[2]; var element = doc.getElementById(id); if (element) { var originalStyleMap = message.pseudoElementSelectorToCSSMap[selector]; var requiredStyleMap = {}; // We compare the computed style before and after removing the pseudo // element and accumulate the differences in |requiredStyleMap|. The pseudo // element is removed by changing the element id. Because some properties // affect other properties, such as border-style: solid causing a change in // border-width, we do this iteratively until a fixed-point is reached (or // |maxNumberOfIterations| is hit). // TODO(sfine): Unify this logic with minimizeStyles. for (var i = 0; i < maxNumberOfIterations; i++) { var currentPseudoElement = ['#' + message.unusedId + ':' + type + '{']; currentPseudoElement.push(buildStyleAttribute(requiredStyleMap)); currentPseudoElement.push('}'); element.setAttribute('id', message.unusedId); var style = doc.getElementById(message.pseudoElementTestingStyleId); style.innerHTML = currentPseudoElement.join(' '); var foundNewRequiredStyle = updateMinimizedStyleMap( doc, element, originalStyleMap, requiredStyleMap, type); if (!foundNewRequiredStyle) { break; } } element.setAttribute('id', id); finalPseudoElements.push('#' + id + ':' + type + '{'); var finalPseudoElement = buildStyleAttribute(requiredStyleMap); var nestingDepth = message.frameIndex.split('.').length - 1; finalPseudoElement = finalPseudoElement.replace( /"/g, escapedQuote(nestingDepth)); finalPseudoElements.push(finalPseudoElement); finalPseudoElements.push('}'); } }
javascript
function minimizePseudoElementStyle( message, doc, selector, finalPseudoElements) { var maxNumberOfIterations = 5; var match = selector.match(/^#(.*):(:.*)$/); var id = match[1]; var type = match[2]; var element = doc.getElementById(id); if (element) { var originalStyleMap = message.pseudoElementSelectorToCSSMap[selector]; var requiredStyleMap = {}; // We compare the computed style before and after removing the pseudo // element and accumulate the differences in |requiredStyleMap|. The pseudo // element is removed by changing the element id. Because some properties // affect other properties, such as border-style: solid causing a change in // border-width, we do this iteratively until a fixed-point is reached (or // |maxNumberOfIterations| is hit). // TODO(sfine): Unify this logic with minimizeStyles. for (var i = 0; i < maxNumberOfIterations; i++) { var currentPseudoElement = ['#' + message.unusedId + ':' + type + '{']; currentPseudoElement.push(buildStyleAttribute(requiredStyleMap)); currentPseudoElement.push('}'); element.setAttribute('id', message.unusedId); var style = doc.getElementById(message.pseudoElementTestingStyleId); style.innerHTML = currentPseudoElement.join(' '); var foundNewRequiredStyle = updateMinimizedStyleMap( doc, element, originalStyleMap, requiredStyleMap, type); if (!foundNewRequiredStyle) { break; } } element.setAttribute('id', id); finalPseudoElements.push('#' + id + ':' + type + '{'); var finalPseudoElement = buildStyleAttribute(requiredStyleMap); var nestingDepth = message.frameIndex.split('.').length - 1; finalPseudoElement = finalPseudoElement.replace( /"/g, escapedQuote(nestingDepth)); finalPseudoElements.push(finalPseudoElement); finalPseudoElements.push('}'); } }
[ "function", "minimizePseudoElementStyle", "(", "message", ",", "doc", ",", "selector", ",", "finalPseudoElements", ")", "{", "var", "maxNumberOfIterations", "=", "5", ";", "var", "match", "=", "selector", ".", "match", "(", "/", "^#(.*):(:.*)$", "/", ")", ";", "var", "id", "=", "match", "[", "1", "]", ";", "var", "type", "=", "match", "[", "2", "]", ";", "var", "element", "=", "doc", ".", "getElementById", "(", "id", ")", ";", "if", "(", "element", ")", "{", "var", "originalStyleMap", "=", "message", ".", "pseudoElementSelectorToCSSMap", "[", "selector", "]", ";", "var", "requiredStyleMap", "=", "{", "}", ";", "// We compare the computed style before and after removing the pseudo", "// element and accumulate the differences in |requiredStyleMap|. The pseudo", "// element is removed by changing the element id. Because some properties", "// affect other properties, such as border-style: solid causing a change in", "// border-width, we do this iteratively until a fixed-point is reached (or", "// |maxNumberOfIterations| is hit).", "// TODO(sfine): Unify this logic with minimizeStyles.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "maxNumberOfIterations", ";", "i", "++", ")", "{", "var", "currentPseudoElement", "=", "[", "'#'", "+", "message", ".", "unusedId", "+", "':'", "+", "type", "+", "'{'", "]", ";", "currentPseudoElement", ".", "push", "(", "buildStyleAttribute", "(", "requiredStyleMap", ")", ")", ";", "currentPseudoElement", ".", "push", "(", "'}'", ")", ";", "element", ".", "setAttribute", "(", "'id'", ",", "message", ".", "unusedId", ")", ";", "var", "style", "=", "doc", ".", "getElementById", "(", "message", ".", "pseudoElementTestingStyleId", ")", ";", "style", ".", "innerHTML", "=", "currentPseudoElement", ".", "join", "(", "' '", ")", ";", "var", "foundNewRequiredStyle", "=", "updateMinimizedStyleMap", "(", "doc", ",", "element", ",", "originalStyleMap", ",", "requiredStyleMap", ",", "type", ")", ";", "if", "(", "!", "foundNewRequiredStyle", ")", "{", "break", ";", "}", "}", "element", ".", "setAttribute", "(", "'id'", ",", "id", ")", ";", "finalPseudoElements", ".", "push", "(", "'#'", "+", "id", "+", "':'", "+", "type", "+", "'{'", ")", ";", "var", "finalPseudoElement", "=", "buildStyleAttribute", "(", "requiredStyleMap", ")", ";", "var", "nestingDepth", "=", "message", ".", "frameIndex", ".", "split", "(", "'.'", ")", ".", "length", "-", "1", ";", "finalPseudoElement", "=", "finalPseudoElement", ".", "replace", "(", "/", "\"", "/", "g", ",", "escapedQuote", "(", "nestingDepth", ")", ")", ";", "finalPseudoElements", ".", "push", "(", "finalPseudoElement", ")", ";", "finalPseudoElements", ".", "push", "(", "'}'", ")", ";", "}", "}" ]
Removes all style attribute properties that are unneeded for a single pseudo element. @param {Object} message The message Object that contains the pseudo element whose style attributes should be minimized. @param {Document} doc The Document that contains the rendered HTML. @param {string} selector The CSS selector for the pseudo element. @param {Array<string>} finalPseudoElements An array to contain the final declaration of pseudo elements. It will be updated to reflect the pseudo element that is being processed.
[ "Removes", "all", "style", "attribute", "properties", "that", "are", "unneeded", "for", "a", "single", "pseudo", "element", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/snap-it/popup.js#L156-L203
5,257
catapult-project/catapult
third_party/snap-it/popup.js
minimizeStyle
function minimizeStyle(message, doc, element, id, index) { var originalStyleAttribute = element.getAttribute('style'); var originalStyleMap = message.idToStyleMap[id]; var requiredStyleMap = {}; var maxNumberOfIterations = 5; // We compare the computed style before and after removing the style attribute // and accumulate the differences in |requiredStyleMap|. Because some // properties affect other properties, such as boder-style: solid causing a // change in border-width, we do this iteratively until a fixed-point is // reached (or |maxNumberOfIterations| is hit). for (var i = 0; i < maxNumberOfIterations; i++) { element.setAttribute('style', buildStyleAttribute(requiredStyleMap)); var foundNewRequiredStyle = updateMinimizedStyleMap( doc, element, originalStyleMap, requiredStyleMap, null); element.setAttribute('style', buildStyleAttribute(originalStyleMap)); if (!foundNewRequiredStyle) { break; } } var finalStyleAttribute = buildStyleAttribute(requiredStyleMap); if (finalStyleAttribute) { var nestingDepth = message.frameIndex.split('.').length - 1; finalStyleAttribute = finalStyleAttribute.replace( /"/g, escapedQuote(nestingDepth + 1)); var quote = escapedQuote(nestingDepth); message.html[index] = `style=${quote}${finalStyleAttribute}${quote} `; } else { message.html[index] = ''; } }
javascript
function minimizeStyle(message, doc, element, id, index) { var originalStyleAttribute = element.getAttribute('style'); var originalStyleMap = message.idToStyleMap[id]; var requiredStyleMap = {}; var maxNumberOfIterations = 5; // We compare the computed style before and after removing the style attribute // and accumulate the differences in |requiredStyleMap|. Because some // properties affect other properties, such as boder-style: solid causing a // change in border-width, we do this iteratively until a fixed-point is // reached (or |maxNumberOfIterations| is hit). for (var i = 0; i < maxNumberOfIterations; i++) { element.setAttribute('style', buildStyleAttribute(requiredStyleMap)); var foundNewRequiredStyle = updateMinimizedStyleMap( doc, element, originalStyleMap, requiredStyleMap, null); element.setAttribute('style', buildStyleAttribute(originalStyleMap)); if (!foundNewRequiredStyle) { break; } } var finalStyleAttribute = buildStyleAttribute(requiredStyleMap); if (finalStyleAttribute) { var nestingDepth = message.frameIndex.split('.').length - 1; finalStyleAttribute = finalStyleAttribute.replace( /"/g, escapedQuote(nestingDepth + 1)); var quote = escapedQuote(nestingDepth); message.html[index] = `style=${quote}${finalStyleAttribute}${quote} `; } else { message.html[index] = ''; } }
[ "function", "minimizeStyle", "(", "message", ",", "doc", ",", "element", ",", "id", ",", "index", ")", "{", "var", "originalStyleAttribute", "=", "element", ".", "getAttribute", "(", "'style'", ")", ";", "var", "originalStyleMap", "=", "message", ".", "idToStyleMap", "[", "id", "]", ";", "var", "requiredStyleMap", "=", "{", "}", ";", "var", "maxNumberOfIterations", "=", "5", ";", "// We compare the computed style before and after removing the style attribute", "// and accumulate the differences in |requiredStyleMap|. Because some", "// properties affect other properties, such as boder-style: solid causing a", "// change in border-width, we do this iteratively until a fixed-point is", "// reached (or |maxNumberOfIterations| is hit).", "for", "(", "var", "i", "=", "0", ";", "i", "<", "maxNumberOfIterations", ";", "i", "++", ")", "{", "element", ".", "setAttribute", "(", "'style'", ",", "buildStyleAttribute", "(", "requiredStyleMap", ")", ")", ";", "var", "foundNewRequiredStyle", "=", "updateMinimizedStyleMap", "(", "doc", ",", "element", ",", "originalStyleMap", ",", "requiredStyleMap", ",", "null", ")", ";", "element", ".", "setAttribute", "(", "'style'", ",", "buildStyleAttribute", "(", "originalStyleMap", ")", ")", ";", "if", "(", "!", "foundNewRequiredStyle", ")", "{", "break", ";", "}", "}", "var", "finalStyleAttribute", "=", "buildStyleAttribute", "(", "requiredStyleMap", ")", ";", "if", "(", "finalStyleAttribute", ")", "{", "var", "nestingDepth", "=", "message", ".", "frameIndex", ".", "split", "(", "'.'", ")", ".", "length", "-", "1", ";", "finalStyleAttribute", "=", "finalStyleAttribute", ".", "replace", "(", "/", "\"", "/", "g", ",", "escapedQuote", "(", "nestingDepth", "+", "1", ")", ")", ";", "var", "quote", "=", "escapedQuote", "(", "nestingDepth", ")", ";", "message", ".", "html", "[", "index", "]", "=", "`", "${", "quote", "}", "${", "finalStyleAttribute", "}", "${", "quote", "}", "`", ";", "}", "else", "{", "message", ".", "html", "[", "index", "]", "=", "''", ";", "}", "}" ]
Removes all style attribute properties that are unneeded for a single element. @param {Object} message The message Object that contains the element whose style attributes should be minimized. @param {Document} doc The Document that contains the rendered HTML. @param {Element} element The Element whose style attributes should be minimized. @param {string} id The id of the Element in the final page. @param {number} index The index in |message.html| where the Element's style attribute is specified.
[ "Removes", "all", "style", "attribute", "properties", "that", "are", "unneeded", "for", "a", "single", "element", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/snap-it/popup.js#L219-L255
5,258
catapult-project/catapult
third_party/snap-it/popup.js
updateMinimizedStyleMap
function updateMinimizedStyleMap( doc, element, originalStyleMap, minimizedStyleMap, pseudo) { var currentComputedStyle = doc.defaultView.getComputedStyle(element, pseudo); var foundNewRequiredStyle = false; for (var property in originalStyleMap) { var originalValue = originalStyleMap[property]; if (originalValue != currentComputedStyle.getPropertyValue(property)) { minimizedStyleMap[property] = originalValue; foundNewRequiredStyle = true; } } return foundNewRequiredStyle; }
javascript
function updateMinimizedStyleMap( doc, element, originalStyleMap, minimizedStyleMap, pseudo) { var currentComputedStyle = doc.defaultView.getComputedStyle(element, pseudo); var foundNewRequiredStyle = false; for (var property in originalStyleMap) { var originalValue = originalStyleMap[property]; if (originalValue != currentComputedStyle.getPropertyValue(property)) { minimizedStyleMap[property] = originalValue; foundNewRequiredStyle = true; } } return foundNewRequiredStyle; }
[ "function", "updateMinimizedStyleMap", "(", "doc", ",", "element", ",", "originalStyleMap", ",", "minimizedStyleMap", ",", "pseudo", ")", "{", "var", "currentComputedStyle", "=", "doc", ".", "defaultView", ".", "getComputedStyle", "(", "element", ",", "pseudo", ")", ";", "var", "foundNewRequiredStyle", "=", "false", ";", "for", "(", "var", "property", "in", "originalStyleMap", ")", "{", "var", "originalValue", "=", "originalStyleMap", "[", "property", "]", ";", "if", "(", "originalValue", "!=", "currentComputedStyle", ".", "getPropertyValue", "(", "property", ")", ")", "{", "minimizedStyleMap", "[", "property", "]", "=", "originalValue", ";", "foundNewRequiredStyle", "=", "true", ";", "}", "}", "return", "foundNewRequiredStyle", ";", "}" ]
We compare the original computed style with the minimized computed style and update |minimizedStyleMap| based on any differences. @param {Document} doc The Document that contains the rendered HTML. @param {Element} element The Element whose style attributes should be minimized. @param {Object<string, string>} originalStyleMap A map representing the original computed style values. The keys are style attribute property names. The values are the corresponding property values. @param {Object<string, string>} minimizedStyleMap A map representing the minimized style values. The keys are style attribute property names. The values are the corresponding property values. @param {string} pseudo If the style describes an ordinary Element, then |pseudo| will be set to null. If the style describes a pseudo element, then |pseudo| will be the string that represents that pseudo element. @return {boolean} Returns true if minimizedStyleMap was changed. Returns false otherwise.
[ "We", "compare", "the", "original", "computed", "style", "with", "the", "minimized", "computed", "style", "and", "update", "|minimizedStyleMap|", "based", "on", "any", "differences", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/snap-it/popup.js#L277-L293
5,259
catapult-project/catapult
third_party/snap-it/popup.js
buildStyleAttribute
function buildStyleAttribute(styleMap) { var styleAttribute = []; for (var property in styleMap) { styleAttribute.push(property + ': ' + styleMap[property] + ';'); } return styleAttribute.join(' '); }
javascript
function buildStyleAttribute(styleMap) { var styleAttribute = []; for (var property in styleMap) { styleAttribute.push(property + ': ' + styleMap[property] + ';'); } return styleAttribute.join(' '); }
[ "function", "buildStyleAttribute", "(", "styleMap", ")", "{", "var", "styleAttribute", "=", "[", "]", ";", "for", "(", "var", "property", "in", "styleMap", ")", "{", "styleAttribute", ".", "push", "(", "property", "+", "': '", "+", "styleMap", "[", "property", "]", "+", "';'", ")", ";", "}", "return", "styleAttribute", ".", "join", "(", "' '", ")", ";", "}" ]
Build a style attribute from a map of property names to property values. @param {Object<string, string} styleMap The keys are style attribute property names. The values are the corresponding property values. @return {string} The correct style attribute.
[ "Build", "a", "style", "attribute", "from", "a", "map", "of", "property", "names", "to", "property", "values", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/snap-it/popup.js#L302-L308
5,260
catapult-project/catapult
third_party/snap-it/popup.js
unescapeHTML
function unescapeHTML(html, nestingDepth) { var div = document.createElement('div'); for (var i = 0; i < nestingDepth; i++) { div.innerHTML = `<iframe srcdoc="${html}"></iframe>`; html = div.childNodes[0].attributes.srcdoc.value; } return html; }
javascript
function unescapeHTML(html, nestingDepth) { var div = document.createElement('div'); for (var i = 0; i < nestingDepth; i++) { div.innerHTML = `<iframe srcdoc="${html}"></iframe>`; html = div.childNodes[0].attributes.srcdoc.value; } return html; }
[ "function", "unescapeHTML", "(", "html", ",", "nestingDepth", ")", "{", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nestingDepth", ";", "i", "++", ")", "{", "div", ".", "innerHTML", "=", "`", "${", "html", "}", "`", ";", "html", "=", "div", ".", "childNodes", "[", "0", "]", ".", "attributes", ".", "srcdoc", ".", "value", ";", "}", "return", "html", ";", "}" ]
Take a string that represents valid HTML and unescape it so that it can be rendered. @param {string} html The HTML to unescape. @param {number} nestingDepth The number of times the HTML must be unescaped. @return {string} The unescaped HTML.
[ "Take", "a", "string", "that", "represents", "valid", "HTML", "and", "unescape", "it", "so", "that", "it", "can", "be", "rendered", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/snap-it/popup.js#L318-L325
5,261
catapult-project/catapult
netlog_viewer/netlog_viewer/main.js
MainView
function MainView() { assertFirstConstructorCall(MainView); if (hasTouchScreen()) { document.body.classList.add('touch'); } // This must be initialized before the tabs, so they can register as // observers. g_browser = BrowserBridge.getInstance(); // This must be the first constants observer, so other constants observers // can safely use the globals, rather than depending on walking through // the constants themselves. g_browser.addConstantsObserver(new ConstantsObserver()); // Create the tab switcher. this.initTabs_(); // Cut out a small vertical strip at the top of the window, to display // a high level status (i.e. if we are displaying a log file or not). // Below it we will position the main tabs and their content area. this.topBarView_ = TopBarView.getInstance(this); const verticalSplitView = new VerticalSplitView(this.topBarView_, this.tabSwitcher_); superClass.call(this, verticalSplitView); // Trigger initial layout. this.resetGeometry(); window.onhashchange = this.onUrlHashChange_.bind(this); // Select the initial view based on the current URL. window.onhashchange(); // No log file loaded yet so set the status bar to that state. this.topBarView_.switchToSubView('loaded').setFileName( 'No log to display.'); // TODO(rayraymond): Follow-up is to completely remove all code from // g_browser that interacts with sending/receiving messages from // browser. g_browser.disable(); }
javascript
function MainView() { assertFirstConstructorCall(MainView); if (hasTouchScreen()) { document.body.classList.add('touch'); } // This must be initialized before the tabs, so they can register as // observers. g_browser = BrowserBridge.getInstance(); // This must be the first constants observer, so other constants observers // can safely use the globals, rather than depending on walking through // the constants themselves. g_browser.addConstantsObserver(new ConstantsObserver()); // Create the tab switcher. this.initTabs_(); // Cut out a small vertical strip at the top of the window, to display // a high level status (i.e. if we are displaying a log file or not). // Below it we will position the main tabs and their content area. this.topBarView_ = TopBarView.getInstance(this); const verticalSplitView = new VerticalSplitView(this.topBarView_, this.tabSwitcher_); superClass.call(this, verticalSplitView); // Trigger initial layout. this.resetGeometry(); window.onhashchange = this.onUrlHashChange_.bind(this); // Select the initial view based on the current URL. window.onhashchange(); // No log file loaded yet so set the status bar to that state. this.topBarView_.switchToSubView('loaded').setFileName( 'No log to display.'); // TODO(rayraymond): Follow-up is to completely remove all code from // g_browser that interacts with sending/receiving messages from // browser. g_browser.disable(); }
[ "function", "MainView", "(", ")", "{", "assertFirstConstructorCall", "(", "MainView", ")", ";", "if", "(", "hasTouchScreen", "(", ")", ")", "{", "document", ".", "body", ".", "classList", ".", "add", "(", "'touch'", ")", ";", "}", "// This must be initialized before the tabs, so they can register as", "// observers.", "g_browser", "=", "BrowserBridge", ".", "getInstance", "(", ")", ";", "// This must be the first constants observer, so other constants observers", "// can safely use the globals, rather than depending on walking through", "// the constants themselves.", "g_browser", ".", "addConstantsObserver", "(", "new", "ConstantsObserver", "(", ")", ")", ";", "// Create the tab switcher.", "this", ".", "initTabs_", "(", ")", ";", "// Cut out a small vertical strip at the top of the window, to display", "// a high level status (i.e. if we are displaying a log file or not).", "// Below it we will position the main tabs and their content area.", "this", ".", "topBarView_", "=", "TopBarView", ".", "getInstance", "(", "this", ")", ";", "const", "verticalSplitView", "=", "new", "VerticalSplitView", "(", "this", ".", "topBarView_", ",", "this", ".", "tabSwitcher_", ")", ";", "superClass", ".", "call", "(", "this", ",", "verticalSplitView", ")", ";", "// Trigger initial layout.", "this", ".", "resetGeometry", "(", ")", ";", "window", ".", "onhashchange", "=", "this", ".", "onUrlHashChange_", ".", "bind", "(", "this", ")", ";", "// Select the initial view based on the current URL.", "window", ".", "onhashchange", "(", ")", ";", "// No log file loaded yet so set the status bar to that state.", "this", ".", "topBarView_", ".", "switchToSubView", "(", "'loaded'", ")", ".", "setFileName", "(", "'No log to display.'", ")", ";", "// TODO(rayraymond): Follow-up is to completely remove all code from", "// g_browser that interacts with sending/receiving messages from", "// browser.", "g_browser", ".", "disable", "(", ")", ";", "}" ]
Main entry point. Called once the page has loaded. @constructor
[ "Main", "entry", "point", ".", "Called", "once", "the", "page", "has", "loaded", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/main.js#L54-L98
5,262
catapult-project/catapult
netlog_viewer/netlog_viewer/main.js
areValidConstants
function areValidConstants(receivedConstants) { return typeof(receivedConstants) === 'object' && typeof(receivedConstants.logEventTypes) === 'object' && typeof(receivedConstants.clientInfo) === 'object' && typeof(receivedConstants.logEventPhase) === 'object' && typeof(receivedConstants.logSourceType) === 'object' && typeof(receivedConstants.loadFlag) === 'object' && typeof(receivedConstants.netError) === 'object' && typeof(receivedConstants.addressFamily) === 'object' && isNetLogNumber(receivedConstants.timeTickOffset) && typeof(receivedConstants.logFormatVersion) === 'number'; }
javascript
function areValidConstants(receivedConstants) { return typeof(receivedConstants) === 'object' && typeof(receivedConstants.logEventTypes) === 'object' && typeof(receivedConstants.clientInfo) === 'object' && typeof(receivedConstants.logEventPhase) === 'object' && typeof(receivedConstants.logSourceType) === 'object' && typeof(receivedConstants.loadFlag) === 'object' && typeof(receivedConstants.netError) === 'object' && typeof(receivedConstants.addressFamily) === 'object' && isNetLogNumber(receivedConstants.timeTickOffset) && typeof(receivedConstants.logFormatVersion) === 'number'; }
[ "function", "areValidConstants", "(", "receivedConstants", ")", "{", "return", "typeof", "(", "receivedConstants", ")", "===", "'object'", "&&", "typeof", "(", "receivedConstants", ".", "logEventTypes", ")", "===", "'object'", "&&", "typeof", "(", "receivedConstants", ".", "clientInfo", ")", "===", "'object'", "&&", "typeof", "(", "receivedConstants", ".", "logEventPhase", ")", "===", "'object'", "&&", "typeof", "(", "receivedConstants", ".", "logSourceType", ")", "===", "'object'", "&&", "typeof", "(", "receivedConstants", ".", "loadFlag", ")", "===", "'object'", "&&", "typeof", "(", "receivedConstants", ".", "netError", ")", "===", "'object'", "&&", "typeof", "(", "receivedConstants", ".", "addressFamily", ")", "===", "'object'", "&&", "isNetLogNumber", "(", "receivedConstants", ".", "timeTickOffset", ")", "&&", "typeof", "(", "receivedConstants", ".", "logFormatVersion", ")", "===", "'number'", ";", "}" ]
Returns true if it's given a valid-looking constants object. @param {Object} receivedConstants The received map of constants. @return {boolean} True if the |receivedConstants| object appears valid.
[ "Returns", "true", "if", "it", "s", "given", "a", "valid", "-", "looking", "constants", "object", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/netlog_viewer/netlog_viewer/main.js#L335-L346
5,263
catapult-project/catapult
third_party/polymer2/bower_components/web-animations-js/src/normalize-keyframes.js
expandShorthandAndAntiAlias
function expandShorthandAndAntiAlias(property, value, result) { if (isNotAnimatable(property)) { return; } var longProperties = shorthandToLonghand[property]; if (longProperties) { shorthandExpanderElem.style[property] = value; for (var i in longProperties) { var longProperty = longProperties[i]; var longhandValue = shorthandExpanderElem.style[longProperty]; result[longProperty] = antiAlias(longProperty, longhandValue); } } else { result[property] = antiAlias(property, value); } }
javascript
function expandShorthandAndAntiAlias(property, value, result) { if (isNotAnimatable(property)) { return; } var longProperties = shorthandToLonghand[property]; if (longProperties) { shorthandExpanderElem.style[property] = value; for (var i in longProperties) { var longProperty = longProperties[i]; var longhandValue = shorthandExpanderElem.style[longProperty]; result[longProperty] = antiAlias(longProperty, longhandValue); } } else { result[property] = antiAlias(property, value); } }
[ "function", "expandShorthandAndAntiAlias", "(", "property", ",", "value", ",", "result", ")", "{", "if", "(", "isNotAnimatable", "(", "property", ")", ")", "{", "return", ";", "}", "var", "longProperties", "=", "shorthandToLonghand", "[", "property", "]", ";", "if", "(", "longProperties", ")", "{", "shorthandExpanderElem", ".", "style", "[", "property", "]", "=", "value", ";", "for", "(", "var", "i", "in", "longProperties", ")", "{", "var", "longProperty", "=", "longProperties", "[", "i", "]", ";", "var", "longhandValue", "=", "shorthandExpanderElem", ".", "style", "[", "longProperty", "]", ";", "result", "[", "longProperty", "]", "=", "antiAlias", "(", "longProperty", ",", "longhandValue", ")", ";", "}", "}", "else", "{", "result", "[", "property", "]", "=", "antiAlias", "(", "property", ",", "value", ")", ";", "}", "}" ]
This delegates parsing shorthand value syntax to the browser.
[ "This", "delegates", "parsing", "shorthand", "value", "syntax", "to", "the", "browser", "." ]
992929ffccac68827869a497f01ee4d653ed4f25
https://github.com/catapult-project/catapult/blob/992929ffccac68827869a497f01ee4d653ed4f25/third_party/polymer2/bower_components/web-animations-js/src/normalize-keyframes.js#L159-L174
5,264
Shopify/slate
packages/slate-translations/index.js
createSchemaContentWithLocales
async function createSchemaContentWithLocales(localizedSchema, mainSchemaPath) { // eslint-disable-next-line func-style const traverse = async (obj) => { const objectKeys = Object.keys(obj); await Promise.all( objectKeys.map(async (key) => { if (typeof obj[key].t === 'string') { obj[key] = await _getLocalizedValues(obj[key].t, localizedSchema); } else if (typeof obj[key] === 'object') { await traverse(obj[key]); } }), ); return JSON.stringify(obj, null, 2); }; const mainSchema = await fs.readJSON(mainSchemaPath, 'utf-8'); return traverse(mainSchema); }
javascript
async function createSchemaContentWithLocales(localizedSchema, mainSchemaPath) { // eslint-disable-next-line func-style const traverse = async (obj) => { const objectKeys = Object.keys(obj); await Promise.all( objectKeys.map(async (key) => { if (typeof obj[key].t === 'string') { obj[key] = await _getLocalizedValues(obj[key].t, localizedSchema); } else if (typeof obj[key] === 'object') { await traverse(obj[key]); } }), ); return JSON.stringify(obj, null, 2); }; const mainSchema = await fs.readJSON(mainSchemaPath, 'utf-8'); return traverse(mainSchema); }
[ "async", "function", "createSchemaContentWithLocales", "(", "localizedSchema", ",", "mainSchemaPath", ")", "{", "// eslint-disable-next-line func-style", "const", "traverse", "=", "async", "(", "obj", ")", "=>", "{", "const", "objectKeys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "await", "Promise", ".", "all", "(", "objectKeys", ".", "map", "(", "async", "(", "key", ")", "=>", "{", "if", "(", "typeof", "obj", "[", "key", "]", ".", "t", "===", "'string'", ")", "{", "obj", "[", "key", "]", "=", "await", "_getLocalizedValues", "(", "obj", "[", "key", "]", ".", "t", ",", "localizedSchema", ")", ";", "}", "else", "if", "(", "typeof", "obj", "[", "key", "]", "===", "'object'", ")", "{", "await", "traverse", "(", "obj", "[", "key", "]", ")", ";", "}", "}", ")", ",", ")", ";", "return", "JSON", ".", "stringify", "(", "obj", ",", "null", ",", "2", ")", ";", "}", ";", "const", "mainSchema", "=", "await", "fs", ".", "readJSON", "(", "mainSchemaPath", ",", "'utf-8'", ")", ";", "return", "traverse", "(", "mainSchema", ")", ";", "}" ]
Goes through the main schema to get the translation keys and to fill the schema with translations @param {*} localizedSchema The schema with the combined locales @param {*} mainSchemaPath The path to the main schema (schema.json) @returns
[ "Goes", "through", "the", "main", "schema", "to", "get", "the", "translation", "keys", "and", "to", "fill", "the", "schema", "with", "translations" ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-translations/index.js#L12-L29
5,265
Shopify/slate
packages/slate-translations/index.js
combineLocales
async function combineLocales(localesPath) { const localesFiles = await fs.readdir(localesPath); const jsonFiles = localesFiles.filter((fileName) => fileName.endsWith('.json'), ); return jsonFiles.reduce(async (promise, file) => { const accumulator = await promise; const localeCode = path .basename(file) .split('.') .shift(); const fileContents = JSON.parse( await fs.readFile(path.resolve(localesPath, file), 'utf-8'), ); accumulator[localeCode] = fileContents; return accumulator; }, Promise.resolve({})); }
javascript
async function combineLocales(localesPath) { const localesFiles = await fs.readdir(localesPath); const jsonFiles = localesFiles.filter((fileName) => fileName.endsWith('.json'), ); return jsonFiles.reduce(async (promise, file) => { const accumulator = await promise; const localeCode = path .basename(file) .split('.') .shift(); const fileContents = JSON.parse( await fs.readFile(path.resolve(localesPath, file), 'utf-8'), ); accumulator[localeCode] = fileContents; return accumulator; }, Promise.resolve({})); }
[ "async", "function", "combineLocales", "(", "localesPath", ")", "{", "const", "localesFiles", "=", "await", "fs", ".", "readdir", "(", "localesPath", ")", ";", "const", "jsonFiles", "=", "localesFiles", ".", "filter", "(", "(", "fileName", ")", "=>", "fileName", ".", "endsWith", "(", "'.json'", ")", ",", ")", ";", "return", "jsonFiles", ".", "reduce", "(", "async", "(", "promise", ",", "file", ")", "=>", "{", "const", "accumulator", "=", "await", "promise", ";", "const", "localeCode", "=", "path", ".", "basename", "(", "file", ")", ".", "split", "(", "'.'", ")", ".", "shift", "(", ")", ";", "const", "fileContents", "=", "JSON", ".", "parse", "(", "await", "fs", ".", "readFile", "(", "path", ".", "resolve", "(", "localesPath", ",", "file", ")", ",", "'utf-8'", ")", ",", ")", ";", "accumulator", "[", "localeCode", "]", "=", "fileContents", ";", "return", "accumulator", ";", "}", ",", "Promise", ".", "resolve", "(", "{", "}", ")", ")", ";", "}" ]
Creates a single JSON object from all the languages in locales @param {*} localesPath Absolute path to the locales folder /sections/section-name/locales/ @returns
[ "Creates", "a", "single", "JSON", "object", "from", "all", "the", "languages", "in", "locales" ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-translations/index.js#L37-L55
5,266
Shopify/slate
packages/slate-translations/index.js
_getLocalizedValues
async function _getLocalizedValues(key, localizedSchema) { const combinedTranslationsObject = {}; await Promise.all( // eslint-disable-next-line array-callback-return Object.keys(localizedSchema).map((language) => { combinedTranslationsObject[language] = _.get( localizedSchema[language], key, ); }), ); return combinedTranslationsObject; }
javascript
async function _getLocalizedValues(key, localizedSchema) { const combinedTranslationsObject = {}; await Promise.all( // eslint-disable-next-line array-callback-return Object.keys(localizedSchema).map((language) => { combinedTranslationsObject[language] = _.get( localizedSchema[language], key, ); }), ); return combinedTranslationsObject; }
[ "async", "function", "_getLocalizedValues", "(", "key", ",", "localizedSchema", ")", "{", "const", "combinedTranslationsObject", "=", "{", "}", ";", "await", "Promise", ".", "all", "(", "// eslint-disable-next-line array-callback-return", "Object", ".", "keys", "(", "localizedSchema", ")", ".", "map", "(", "(", "language", ")", "=>", "{", "combinedTranslationsObject", "[", "language", "]", "=", "_", ".", "get", "(", "localizedSchema", "[", "language", "]", ",", "key", ",", ")", ";", "}", ")", ",", ")", ";", "return", "combinedTranslationsObject", ";", "}" ]
Gets all the translations for a translation key @param {*} key The key of the value to receive within the locales json object @param {*} localizedSchema Object containing all the translations in locales @returns Object with index for every language in the locales folder
[ "Gets", "all", "the", "translations", "for", "a", "translation", "key" ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-translations/index.js#L64-L78
5,267
Shopify/slate
packages/slate-tools/tools/utilities/index.js
getAvailablePortSeries
function getAvailablePortSeries(start, quantity, increment = 1) { const startPort = start; const endPort = start + (quantity - 1); return findAPortInUse(startPort, endPort, '127.0.0.1').then((port) => { if (typeof port === 'number') { return getAvailablePortSeries(port + increment, quantity); } const ports = []; for (let i = startPort; i <= endPort; i += increment) { ports.push(i); } return ports; }); }
javascript
function getAvailablePortSeries(start, quantity, increment = 1) { const startPort = start; const endPort = start + (quantity - 1); return findAPortInUse(startPort, endPort, '127.0.0.1').then((port) => { if (typeof port === 'number') { return getAvailablePortSeries(port + increment, quantity); } const ports = []; for (let i = startPort; i <= endPort; i += increment) { ports.push(i); } return ports; }); }
[ "function", "getAvailablePortSeries", "(", "start", ",", "quantity", ",", "increment", "=", "1", ")", "{", "const", "startPort", "=", "start", ";", "const", "endPort", "=", "start", "+", "(", "quantity", "-", "1", ")", ";", "return", "findAPortInUse", "(", "startPort", ",", "endPort", ",", "'127.0.0.1'", ")", ".", "then", "(", "(", "port", ")", "=>", "{", "if", "(", "typeof", "port", "===", "'number'", ")", "{", "return", "getAvailablePortSeries", "(", "port", "+", "increment", ",", "quantity", ")", ";", "}", "const", "ports", "=", "[", "]", ";", "for", "(", "let", "i", "=", "startPort", ";", "i", "<=", "endPort", ";", "i", "+=", "increment", ")", "{", "ports", ".", "push", "(", "i", ")", ";", "}", "return", "ports", ";", "}", ")", ";", "}" ]
Finds a series of available ports of length quantity, starting at a given port number and incrementing up. Returns an array of port numbers.
[ "Finds", "a", "series", "of", "available", "ports", "of", "length", "quantity", "starting", "at", "a", "given", "port", "number", "and", "incrementing", "up", ".", "Returns", "an", "array", "of", "port", "numbers", "." ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-tools/tools/utilities/index.js#L36-L53
5,268
Shopify/slate
packages/slate-env/index.js
create
function create({values, name, root} = {}) { const envName = _getFileName(name); const envPath = path.resolve( root || config.get('env.rootDirectory'), envName, ); const envContents = _getFileContents(values); fs.writeFileSync(envPath, envContents); }
javascript
function create({values, name, root} = {}) { const envName = _getFileName(name); const envPath = path.resolve( root || config.get('env.rootDirectory'), envName, ); const envContents = _getFileContents(values); fs.writeFileSync(envPath, envContents); }
[ "function", "create", "(", "{", "values", ",", "name", ",", "root", "}", "=", "{", "}", ")", "{", "const", "envName", "=", "_getFileName", "(", "name", ")", ";", "const", "envPath", "=", "path", ".", "resolve", "(", "root", "||", "config", ".", "get", "(", "'env.rootDirectory'", ")", ",", "envName", ",", ")", ";", "const", "envContents", "=", "_getFileContents", "(", "values", ")", ";", "fs", ".", "writeFileSync", "(", "envPath", ",", "envContents", ")", ";", "}" ]
Creates a new env file with optional name and values
[ "Creates", "a", "new", "env", "file", "with", "optional", "name", "and", "values" ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-env/index.js#L25-L34
5,269
Shopify/slate
packages/slate-env/index.js
_getFileName
function _getFileName(name) { if (typeof name === 'undefined' || name.trim() === '') { return config.get('env.basename'); } return `${config.get('env.basename')}.${name}`; }
javascript
function _getFileName(name) { if (typeof name === 'undefined' || name.trim() === '') { return config.get('env.basename'); } return `${config.get('env.basename')}.${name}`; }
[ "function", "_getFileName", "(", "name", ")", "{", "if", "(", "typeof", "name", "===", "'undefined'", "||", "name", ".", "trim", "(", ")", "===", "''", ")", "{", "return", "config", ".", "get", "(", "'env.basename'", ")", ";", "}", "return", "`", "${", "config", ".", "get", "(", "'env.basename'", ")", "}", "${", "name", "}", "`", ";", "}" ]
Return the default env file name, with optional name appended
[ "Return", "the", "default", "env", "file", "name", "with", "optional", "name", "appended" ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-env/index.js#L37-L43
5,270
Shopify/slate
packages/slate-env/index.js
_getFileContents
function _getFileContents(values) { const env = getDefaultSlateEnv(); for (const key in values) { if (values.hasOwnProperty(key) && env.hasOwnProperty(key)) { env[key] = values[key]; } } return Object.entries(env) .map((keyValues) => { return `${keyValues.join('=')}\r\n`; }) .join('\r\n\r\n'); }
javascript
function _getFileContents(values) { const env = getDefaultSlateEnv(); for (const key in values) { if (values.hasOwnProperty(key) && env.hasOwnProperty(key)) { env[key] = values[key]; } } return Object.entries(env) .map((keyValues) => { return `${keyValues.join('=')}\r\n`; }) .join('\r\n\r\n'); }
[ "function", "_getFileContents", "(", "values", ")", "{", "const", "env", "=", "getDefaultSlateEnv", "(", ")", ";", "for", "(", "const", "key", "in", "values", ")", "{", "if", "(", "values", ".", "hasOwnProperty", "(", "key", ")", "&&", "env", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "env", "[", "key", "]", "=", "values", "[", "key", "]", ";", "}", "}", "return", "Object", ".", "entries", "(", "env", ")", ".", "map", "(", "(", "keyValues", ")", "=>", "{", "return", "`", "${", "keyValues", ".", "join", "(", "'='", ")", "}", "\\r", "\\n", "`", ";", "}", ")", ".", "join", "(", "'\\r\\n\\r\\n'", ")", ";", "}" ]
Return default list of env variables with their assigned value, if any.
[ "Return", "default", "list", "of", "env", "variables", "with", "their", "assigned", "value", "if", "any", "." ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-env/index.js#L46-L60
5,271
Shopify/slate
packages/slate-env/index.js
assign
function assign(name) { const envFileName = _getFileName(name); const envPath = path.resolve(config.get('env.rootDirectory'), envFileName); const result = dotenv.config({path: envPath}); if (typeof name !== 'undefined' && result.error) { throw result.error; } _setEnvName(name); }
javascript
function assign(name) { const envFileName = _getFileName(name); const envPath = path.resolve(config.get('env.rootDirectory'), envFileName); const result = dotenv.config({path: envPath}); if (typeof name !== 'undefined' && result.error) { throw result.error; } _setEnvName(name); }
[ "function", "assign", "(", "name", ")", "{", "const", "envFileName", "=", "_getFileName", "(", "name", ")", ";", "const", "envPath", "=", "path", ".", "resolve", "(", "config", ".", "get", "(", "'env.rootDirectory'", ")", ",", "envFileName", ")", ";", "const", "result", "=", "dotenv", ".", "config", "(", "{", "path", ":", "envPath", "}", ")", ";", "if", "(", "typeof", "name", "!==", "'undefined'", "&&", "result", ".", "error", ")", "{", "throw", "result", ".", "error", ";", "}", "_setEnvName", "(", "name", ")", ";", "}" ]
Reads an .env file and assigns their values to environment variables
[ "Reads", "an", ".", "env", "file", "and", "assigns", "their", "values", "to", "environment", "variables" ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-env/index.js#L63-L73
5,272
Shopify/slate
packages/slate-env/index.js
validate
function validate() { const errors = [].concat( _validateStore(), _validatePassword(), _validateThemeId(), ); return { errors, isValid: errors.length === 0, }; }
javascript
function validate() { const errors = [].concat( _validateStore(), _validatePassword(), _validateThemeId(), ); return { errors, isValid: errors.length === 0, }; }
[ "function", "validate", "(", ")", "{", "const", "errors", "=", "[", "]", ".", "concat", "(", "_validateStore", "(", ")", ",", "_validatePassword", "(", ")", ",", "_validateThemeId", "(", ")", ",", ")", ";", "return", "{", "errors", ",", "isValid", ":", "errors", ".", "length", "===", "0", ",", "}", ";", "}" ]
Checks if Slate env variables are the required value types and format
[ "Checks", "if", "Slate", "env", "variables", "are", "the", "required", "value", "types", "and", "format" ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-env/index.js#L92-L103
5,273
Shopify/slate
packages/slate-env/index.js
getSlateEnv
function getSlateEnv() { const env = {}; SLATE_ENV_VARS.forEach((key) => { env[key] = process.env[key]; }); return env; }
javascript
function getSlateEnv() { const env = {}; SLATE_ENV_VARS.forEach((key) => { env[key] = process.env[key]; }); return env; }
[ "function", "getSlateEnv", "(", ")", "{", "const", "env", "=", "{", "}", ";", "SLATE_ENV_VARS", ".", "forEach", "(", "(", "key", ")", "=>", "{", "env", "[", "key", "]", "=", "process", ".", "env", "[", "key", "]", ";", "}", ")", ";", "return", "env", ";", "}" ]
Get the values of Slate's required environment variables
[ "Get", "the", "values", "of", "Slate", "s", "required", "environment", "variables" ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/slate-env/index.js#L179-L187
5,274
Shopify/slate
packages/create-slate-theme/create-slate-theme.js
installThemeDeps
function installThemeDeps(root, options) { if (options.skipInstall) { console.log('Skipping theme dependency installation...'); return Promise.resolve(); } const prevDir = process.cwd(); console.log('Installing theme dependencies...'); process.chdir(root); const cmd = utils.shouldUseYarn() ? utils.spawn('yarnpkg') : utils.spawn('npm install'); return cmd.then(() => process.chdir(prevDir)); }
javascript
function installThemeDeps(root, options) { if (options.skipInstall) { console.log('Skipping theme dependency installation...'); return Promise.resolve(); } const prevDir = process.cwd(); console.log('Installing theme dependencies...'); process.chdir(root); const cmd = utils.shouldUseYarn() ? utils.spawn('yarnpkg') : utils.spawn('npm install'); return cmd.then(() => process.chdir(prevDir)); }
[ "function", "installThemeDeps", "(", "root", ",", "options", ")", "{", "if", "(", "options", ".", "skipInstall", ")", "{", "console", ".", "log", "(", "'Skipping theme dependency installation...'", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "const", "prevDir", "=", "process", ".", "cwd", "(", ")", ";", "console", ".", "log", "(", "'Installing theme dependencies...'", ")", ";", "process", ".", "chdir", "(", "root", ")", ";", "const", "cmd", "=", "utils", ".", "shouldUseYarn", "(", ")", "?", "utils", ".", "spawn", "(", "'yarnpkg'", ")", ":", "utils", ".", "spawn", "(", "'npm install'", ")", ";", "return", "cmd", ".", "then", "(", "(", ")", "=>", "process", ".", "chdir", "(", "prevDir", ")", ")", ";", "}" ]
Executes `npm install` or `yarn install` in rootPath.
[ "Executes", "npm", "install", "or", "yarn", "install", "in", "rootPath", "." ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/create-slate-theme/create-slate-theme.js#L88-L104
5,275
Shopify/slate
packages/create-slate-theme/create-slate-theme.js
copyFromDir
function copyFromDir(starter, root) { if (!fs.existsSync(starter)) { throw new Error(`starter ${starter} doesn't exist`); } // Chmod with 755. // 493 = parseInt('755', 8) return fs.mkdirp(root, {mode: 493}).then(() => { console.log( `Creating new theme from local starter: ${chalk.green(starter)}`, ); return fs.copy(starter, root, { filter: (file) => !/^\.(git|hg)$/.test(path.basename(file)) && !/node_modules/.test(file), }); }); }
javascript
function copyFromDir(starter, root) { if (!fs.existsSync(starter)) { throw new Error(`starter ${starter} doesn't exist`); } // Chmod with 755. // 493 = parseInt('755', 8) return fs.mkdirp(root, {mode: 493}).then(() => { console.log( `Creating new theme from local starter: ${chalk.green(starter)}`, ); return fs.copy(starter, root, { filter: (file) => !/^\.(git|hg)$/.test(path.basename(file)) && !/node_modules/.test(file), }); }); }
[ "function", "copyFromDir", "(", "starter", ",", "root", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "starter", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "starter", "}", "`", ")", ";", "}", "// Chmod with 755.", "// 493 = parseInt('755', 8)", "return", "fs", ".", "mkdirp", "(", "root", ",", "{", "mode", ":", "493", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "console", ".", "log", "(", "`", "${", "chalk", ".", "green", "(", "starter", ")", "}", "`", ",", ")", ";", "return", "fs", ".", "copy", "(", "starter", ",", "root", ",", "{", "filter", ":", "(", "file", ")", "=>", "!", "/", "^\\.(git|hg)$", "/", ".", "test", "(", "path", ".", "basename", "(", "file", ")", ")", "&&", "!", "/", "node_modules", "/", ".", "test", "(", "file", ")", ",", "}", ")", ";", "}", ")", ";", "}" ]
Copy starter from file system.
[ "Copy", "starter", "from", "file", "system", "." ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/create-slate-theme/create-slate-theme.js#L107-L123
5,276
Shopify/slate
packages/create-slate-theme/create-slate-theme.js
cloneFromGit
function cloneFromGit(hostInfo, root, ssh) { const branch = hostInfo.committish ? `-b ${hostInfo.committish}` : ''; let url; if (ssh) { url = hostInfo.ssh({noCommittish: true}); } else { url = hostInfo.https({noCommittish: true, noGitPlus: true}); } console.log(`Cloning theme from a git repo: ${chalk.green(url)}`); return utils .spawn(`git clone ${branch} ${url} "${root}" --single-branch`, { stdio: 'pipe', }) .then(() => { return fs.remove(path.join(root, '.git')); }) .catch((error) => { console.log(); console.log(chalk.red('There was an error while cloning the git repo:')); console.log(''); console.log(chalk.red(error)); process.exit(1); }); }
javascript
function cloneFromGit(hostInfo, root, ssh) { const branch = hostInfo.committish ? `-b ${hostInfo.committish}` : ''; let url; if (ssh) { url = hostInfo.ssh({noCommittish: true}); } else { url = hostInfo.https({noCommittish: true, noGitPlus: true}); } console.log(`Cloning theme from a git repo: ${chalk.green(url)}`); return utils .spawn(`git clone ${branch} ${url} "${root}" --single-branch`, { stdio: 'pipe', }) .then(() => { return fs.remove(path.join(root, '.git')); }) .catch((error) => { console.log(); console.log(chalk.red('There was an error while cloning the git repo:')); console.log(''); console.log(chalk.red(error)); process.exit(1); }); }
[ "function", "cloneFromGit", "(", "hostInfo", ",", "root", ",", "ssh", ")", "{", "const", "branch", "=", "hostInfo", ".", "committish", "?", "`", "${", "hostInfo", ".", "committish", "}", "`", ":", "''", ";", "let", "url", ";", "if", "(", "ssh", ")", "{", "url", "=", "hostInfo", ".", "ssh", "(", "{", "noCommittish", ":", "true", "}", ")", ";", "}", "else", "{", "url", "=", "hostInfo", ".", "https", "(", "{", "noCommittish", ":", "true", ",", "noGitPlus", ":", "true", "}", ")", ";", "}", "console", ".", "log", "(", "`", "${", "chalk", ".", "green", "(", "url", ")", "}", "`", ")", ";", "return", "utils", ".", "spawn", "(", "`", "${", "branch", "}", "${", "url", "}", "${", "root", "}", "`", ",", "{", "stdio", ":", "'pipe'", ",", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "fs", ".", "remove", "(", "path", ".", "join", "(", "root", ",", "'.git'", ")", ")", ";", "}", ")", ".", "catch", "(", "(", "error", ")", "=>", "{", "console", ".", "log", "(", ")", ";", "console", ".", "log", "(", "chalk", ".", "red", "(", "'There was an error while cloning the git repo:'", ")", ")", ";", "console", ".", "log", "(", "''", ")", ";", "console", ".", "log", "(", "chalk", ".", "red", "(", "error", ")", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", ")", ";", "}" ]
Clones starter from URI.
[ "Clones", "starter", "from", "URI", "." ]
c698803aa1106d0b6d555d463ddf59bf97e41bd1
https://github.com/Shopify/slate/blob/c698803aa1106d0b6d555d463ddf59bf97e41bd1/packages/create-slate-theme/create-slate-theme.js#L126-L153
5,277
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
CustomError
function CustomError (message, cause) { Error.call(this) if (Error.captureStackTrace) Error.captureStackTrace(this, arguments.callee) init.call(this, 'CustomError', message, cause) }
javascript
function CustomError (message, cause) { Error.call(this) if (Error.captureStackTrace) Error.captureStackTrace(this, arguments.callee) init.call(this, 'CustomError', message, cause) }
[ "function", "CustomError", "(", "message", ",", "cause", ")", "{", "Error", ".", "call", "(", "this", ")", "if", "(", "Error", ".", "captureStackTrace", ")", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", "init", ".", "call", "(", "this", ",", "'CustomError'", ",", "message", ",", "cause", ")", "}" ]
generic prototype, not intended to be actually used - helpful for `instanceof`
[ "generic", "prototype", "not", "intended", "to", "be", "actually", "used", "-", "helpful", "for", "instanceof" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L1578-L1583
5,278
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
doVisitFull
function doVisitFull(visit, node) { if(node.left) { var v = doVisitFull(visit, node.left) if(v) { return v } } var v = visit(node.key, node.value) if(v) { return v } if(node.right) { return doVisitFull(visit, node.right) } }
javascript
function doVisitFull(visit, node) { if(node.left) { var v = doVisitFull(visit, node.left) if(v) { return v } } var v = visit(node.key, node.value) if(v) { return v } if(node.right) { return doVisitFull(visit, node.right) } }
[ "function", "doVisitFull", "(", "visit", ",", "node", ")", "{", "if", "(", "node", ".", "left", ")", "{", "var", "v", "=", "doVisitFull", "(", "visit", ",", "node", ".", "left", ")", "if", "(", "v", ")", "{", "return", "v", "}", "}", "var", "v", "=", "visit", "(", "node", ".", "key", ",", "node", ".", "value", ")", "if", "(", "v", ")", "{", "return", "v", "}", "if", "(", "node", ".", "right", ")", "{", "return", "doVisitFull", "(", "visit", ",", "node", ".", "right", ")", "}", "}" ]
Visit all nodes inorder
[ "Visit", "all", "nodes", "inorder" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L2168-L2178
5,279
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
doVisitHalf
function doVisitHalf(lo, compare, visit, node) { var l = compare(lo, node.key) if(l <= 0) { if(node.left) { var v = doVisitHalf(lo, compare, visit, node.left) if(v) { return v } } var v = visit(node.key, node.value) if(v) { return v } } if(node.right) { return doVisitHalf(lo, compare, visit, node.right) } }
javascript
function doVisitHalf(lo, compare, visit, node) { var l = compare(lo, node.key) if(l <= 0) { if(node.left) { var v = doVisitHalf(lo, compare, visit, node.left) if(v) { return v } } var v = visit(node.key, node.value) if(v) { return v } } if(node.right) { return doVisitHalf(lo, compare, visit, node.right) } }
[ "function", "doVisitHalf", "(", "lo", ",", "compare", ",", "visit", ",", "node", ")", "{", "var", "l", "=", "compare", "(", "lo", ",", "node", ".", "key", ")", "if", "(", "l", "<=", "0", ")", "{", "if", "(", "node", ".", "left", ")", "{", "var", "v", "=", "doVisitHalf", "(", "lo", ",", "compare", ",", "visit", ",", "node", ".", "left", ")", "if", "(", "v", ")", "{", "return", "v", "}", "}", "var", "v", "=", "visit", "(", "node", ".", "key", ",", "node", ".", "value", ")", "if", "(", "v", ")", "{", "return", "v", "}", "}", "if", "(", "node", ".", "right", ")", "{", "return", "doVisitHalf", "(", "lo", ",", "compare", ",", "visit", ",", "node", ".", "right", ")", "}", "}" ]
Visit half nodes in order
[ "Visit", "half", "nodes", "in", "order" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L2181-L2194
5,280
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
doVisit
function doVisit(lo, hi, compare, visit, node) { var l = compare(lo, node.key) var h = compare(hi, node.key) var v if(l <= 0) { if(node.left) { v = doVisit(lo, hi, compare, visit, node.left) if(v) { return v } } if(h > 0) { v = visit(node.key, node.value) if(v) { return v } } } if(h > 0 && node.right) { return doVisit(lo, hi, compare, visit, node.right) } }
javascript
function doVisit(lo, hi, compare, visit, node) { var l = compare(lo, node.key) var h = compare(hi, node.key) var v if(l <= 0) { if(node.left) { v = doVisit(lo, hi, compare, visit, node.left) if(v) { return v } } if(h > 0) { v = visit(node.key, node.value) if(v) { return v } } } if(h > 0 && node.right) { return doVisit(lo, hi, compare, visit, node.right) } }
[ "function", "doVisit", "(", "lo", ",", "hi", ",", "compare", ",", "visit", ",", "node", ")", "{", "var", "l", "=", "compare", "(", "lo", ",", "node", ".", "key", ")", "var", "h", "=", "compare", "(", "hi", ",", "node", ".", "key", ")", "var", "v", "if", "(", "l", "<=", "0", ")", "{", "if", "(", "node", ".", "left", ")", "{", "v", "=", "doVisit", "(", "lo", ",", "hi", ",", "compare", ",", "visit", ",", "node", ".", "left", ")", "if", "(", "v", ")", "{", "return", "v", "}", "}", "if", "(", "h", ">", "0", ")", "{", "v", "=", "visit", "(", "node", ".", "key", ",", "node", ".", "value", ")", "if", "(", "v", ")", "{", "return", "v", "}", "}", "}", "if", "(", "h", ">", "0", "&&", "node", ".", "right", ")", "{", "return", "doVisit", "(", "lo", ",", "hi", ",", "compare", ",", "visit", ",", "node", ".", "right", ")", "}", "}" ]
Visit all nodes within a range
[ "Visit", "all", "nodes", "within", "a", "range" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L2197-L2214
5,281
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
swapNode
function swapNode(n, v) { n.key = v.key n.value = v.value n.left = v.left n.right = v.right n._color = v._color n._count = v._count }
javascript
function swapNode(n, v) { n.key = v.key n.value = v.value n.left = v.left n.right = v.right n._color = v._color n._count = v._count }
[ "function", "swapNode", "(", "n", ",", "v", ")", "{", "n", ".", "key", "=", "v", ".", "key", "n", ".", "value", "=", "v", ".", "value", "n", ".", "left", "=", "v", ".", "left", "n", ".", "right", "=", "v", ".", "right", "n", ".", "_color", "=", "v", ".", "_color", "n", ".", "_count", "=", "v", ".", "_count", "}" ]
Swaps two nodes
[ "Swaps", "two", "nodes" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L2460-L2467
5,282
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
collate
function collate(a, b) { if (a === b) { return 0; } a = normalizeKey(a); b = normalizeKey(b); var ai = collationIndex(a); var bi = collationIndex(b); if ((ai - bi) !== 0) { return ai - bi; } switch (typeof a) { case 'number': return a - b; case 'boolean': return a < b ? -1 : 1; case 'string': return stringCollate(a, b); } return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b); }
javascript
function collate(a, b) { if (a === b) { return 0; } a = normalizeKey(a); b = normalizeKey(b); var ai = collationIndex(a); var bi = collationIndex(b); if ((ai - bi) !== 0) { return ai - bi; } switch (typeof a) { case 'number': return a - b; case 'boolean': return a < b ? -1 : 1; case 'string': return stringCollate(a, b); } return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b); }
[ "function", "collate", "(", "a", ",", "b", ")", "{", "if", "(", "a", "===", "b", ")", "{", "return", "0", ";", "}", "a", "=", "normalizeKey", "(", "a", ")", ";", "b", "=", "normalizeKey", "(", "b", ")", ";", "var", "ai", "=", "collationIndex", "(", "a", ")", ";", "var", "bi", "=", "collationIndex", "(", "b", ")", ";", "if", "(", "(", "ai", "-", "bi", ")", "!==", "0", ")", "{", "return", "ai", "-", "bi", ";", "}", "switch", "(", "typeof", "a", ")", "{", "case", "'number'", ":", "return", "a", "-", "b", ";", "case", "'boolean'", ":", "return", "a", "<", "b", "?", "-", "1", ":", "1", ";", "case", "'string'", ":", "return", "stringCollate", "(", "a", ",", "b", ")", ";", "}", "return", "Array", ".", "isArray", "(", "a", ")", "?", "arrayCollate", "(", "a", ",", "b", ")", ":", "objectCollate", "(", "a", ",", "b", ")", ";", "}" ]
set to '_' for easier debugging
[ "set", "to", "_", "for", "easier", "debugging" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L6732-L6755
5,283
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
pop
function pop(stack, metaStack) { var obj = stack.pop(); if (metaStack.length) { var lastMetaElement = metaStack[metaStack.length - 1]; if (obj === lastMetaElement.element) { // popping a meta-element, e.g. an object whose value is another object metaStack.pop(); lastMetaElement = metaStack[metaStack.length - 1]; } var element = lastMetaElement.element; var lastElementIndex = lastMetaElement.index; if (Array.isArray(element)) { element.push(obj); } else if (lastElementIndex === stack.length - 2) { // obj with key+value var key = stack.pop(); element[key] = obj; } else { stack.push(obj); // obj with key only } } }
javascript
function pop(stack, metaStack) { var obj = stack.pop(); if (metaStack.length) { var lastMetaElement = metaStack[metaStack.length - 1]; if (obj === lastMetaElement.element) { // popping a meta-element, e.g. an object whose value is another object metaStack.pop(); lastMetaElement = metaStack[metaStack.length - 1]; } var element = lastMetaElement.element; var lastElementIndex = lastMetaElement.index; if (Array.isArray(element)) { element.push(obj); } else if (lastElementIndex === stack.length - 2) { // obj with key+value var key = stack.pop(); element[key] = obj; } else { stack.push(obj); // obj with key only } } }
[ "function", "pop", "(", "stack", ",", "metaStack", ")", "{", "var", "obj", "=", "stack", ".", "pop", "(", ")", ";", "if", "(", "metaStack", ".", "length", ")", "{", "var", "lastMetaElement", "=", "metaStack", "[", "metaStack", ".", "length", "-", "1", "]", ";", "if", "(", "obj", "===", "lastMetaElement", ".", "element", ")", "{", "// popping a meta-element, e.g. an object whose value is another object", "metaStack", ".", "pop", "(", ")", ";", "lastMetaElement", "=", "metaStack", "[", "metaStack", ".", "length", "-", "1", "]", ";", "}", "var", "element", "=", "lastMetaElement", ".", "element", ";", "var", "lastElementIndex", "=", "lastMetaElement", ".", "index", ";", "if", "(", "Array", ".", "isArray", "(", "element", ")", ")", "{", "element", ".", "push", "(", "obj", ")", ";", "}", "else", "if", "(", "lastElementIndex", "===", "stack", ".", "length", "-", "2", ")", "{", "// obj with key+value", "var", "key", "=", "stack", ".", "pop", "(", ")", ";", "element", "[", "key", "]", "=", "obj", ";", "}", "else", "{", "stack", ".", "push", "(", "obj", ")", ";", "// obj with key only", "}", "}", "}" ]
move up the stack while parsing this function moved outside of parseIndexableString for performance
[ "move", "up", "the", "stack", "while", "parsing", "this", "function", "moved", "outside", "of", "parseIndexableString", "for", "performance" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L6894-L6915
5,284
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
getHost
function getHost(name, opts) { // encode db name if opts.prefix is a url (#5574) if (hasUrlPrefix(opts)) { var dbName = opts.name.substr(opts.prefix.length); name = opts.prefix + encodeURIComponent(dbName); } // Prase the URI into all its little bits var uri = pouchdbUtils.parseUri(name); // Store the user and password as a separate auth object if (uri.user || uri.password) { uri.auth = {username: uri.user, password: uri.password}; } // Split the path part of the URI into parts using '/' as the delimiter // after removing any leading '/' and any trailing '/' var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/'); // Store the first part as the database name and remove it from the parts // array uri.db = parts.pop(); // Prevent double encoding of URI component if (uri.db.indexOf('%') === -1) { uri.db = encodeURIComponent(uri.db); } // Restore the path by joining all the remaining parts (all the parts // except for the database name) with '/'s uri.path = parts.join('/'); return uri; }
javascript
function getHost(name, opts) { // encode db name if opts.prefix is a url (#5574) if (hasUrlPrefix(opts)) { var dbName = opts.name.substr(opts.prefix.length); name = opts.prefix + encodeURIComponent(dbName); } // Prase the URI into all its little bits var uri = pouchdbUtils.parseUri(name); // Store the user and password as a separate auth object if (uri.user || uri.password) { uri.auth = {username: uri.user, password: uri.password}; } // Split the path part of the URI into parts using '/' as the delimiter // after removing any leading '/' and any trailing '/' var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/'); // Store the first part as the database name and remove it from the parts // array uri.db = parts.pop(); // Prevent double encoding of URI component if (uri.db.indexOf('%') === -1) { uri.db = encodeURIComponent(uri.db); } // Restore the path by joining all the remaining parts (all the parts // except for the database name) with '/'s uri.path = parts.join('/'); return uri; }
[ "function", "getHost", "(", "name", ",", "opts", ")", "{", "// encode db name if opts.prefix is a url (#5574)", "if", "(", "hasUrlPrefix", "(", "opts", ")", ")", "{", "var", "dbName", "=", "opts", ".", "name", ".", "substr", "(", "opts", ".", "prefix", ".", "length", ")", ";", "name", "=", "opts", ".", "prefix", "+", "encodeURIComponent", "(", "dbName", ")", ";", "}", "// Prase the URI into all its little bits", "var", "uri", "=", "pouchdbUtils", ".", "parseUri", "(", "name", ")", ";", "// Store the user and password as a separate auth object", "if", "(", "uri", ".", "user", "||", "uri", ".", "password", ")", "{", "uri", ".", "auth", "=", "{", "username", ":", "uri", ".", "user", ",", "password", ":", "uri", ".", "password", "}", ";", "}", "// Split the path part of the URI into parts using '/' as the delimiter", "// after removing any leading '/' and any trailing '/'", "var", "parts", "=", "uri", ".", "path", ".", "replace", "(", "/", "(^\\/|\\/$)", "/", "g", ",", "''", ")", ".", "split", "(", "'/'", ")", ";", "// Store the first part as the database name and remove it from the parts", "// array", "uri", ".", "db", "=", "parts", ".", "pop", "(", ")", ";", "// Prevent double encoding of URI component", "if", "(", "uri", ".", "db", ".", "indexOf", "(", "'%'", ")", "===", "-", "1", ")", "{", "uri", ".", "db", "=", "encodeURIComponent", "(", "uri", ".", "db", ")", ";", "}", "// Restore the path by joining all the remaining parts (all the parts", "// except for the database name) with '/'s", "uri", ".", "path", "=", "parts", ".", "join", "(", "'/'", ")", ";", "return", "uri", ";", "}" ]
Get all the information you possibly can about the URI given by name and return it as a suitable object.
[ "Get", "all", "the", "information", "you", "possibly", "can", "about", "the", "URI", "given", "by", "name", "and", "return", "it", "as", "a", "suitable", "object", "." ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L7222-L7255
5,285
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
genUrl
function genUrl(opts, path) { // If the host already has a path, then we need to have a path delimiter // Otherwise, the path delimiter is the empty string var pathDel = !opts.path ? '' : '/'; // If the host already has a path, then we need to have a path delimiter // Otherwise, the path delimiter is the empty string return opts.protocol + '://' + opts.host + (opts.port ? (':' + opts.port) : '') + '/' + opts.path + pathDel + path; }
javascript
function genUrl(opts, path) { // If the host already has a path, then we need to have a path delimiter // Otherwise, the path delimiter is the empty string var pathDel = !opts.path ? '' : '/'; // If the host already has a path, then we need to have a path delimiter // Otherwise, the path delimiter is the empty string return opts.protocol + '://' + opts.host + (opts.port ? (':' + opts.port) : '') + '/' + opts.path + pathDel + path; }
[ "function", "genUrl", "(", "opts", ",", "path", ")", "{", "// If the host already has a path, then we need to have a path delimiter", "// Otherwise, the path delimiter is the empty string", "var", "pathDel", "=", "!", "opts", ".", "path", "?", "''", ":", "'/'", ";", "// If the host already has a path, then we need to have a path delimiter", "// Otherwise, the path delimiter is the empty string", "return", "opts", ".", "protocol", "+", "'://'", "+", "opts", ".", "host", "+", "(", "opts", ".", "port", "?", "(", "':'", "+", "opts", ".", "port", ")", ":", "''", ")", "+", "'/'", "+", "opts", ".", "path", "+", "pathDel", "+", "path", ";", "}" ]
Generate a URL with the host data given by opts and the given path
[ "Generate", "a", "URL", "with", "the", "host", "data", "given", "by", "opts", "and", "the", "given", "path" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L7263-L7273
5,286
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
function (since, callback) { if (opts.aborted) { return; } params.since = since; // "since" can be any kind of json object in Coudant/CouchDB 2.x /* istanbul ignore next */ if (typeof params.since === "object") { params.since = JSON.stringify(params.since); } if (opts.descending) { if (limit) { params.limit = leftToFetch; } } else { params.limit = (!limit || leftToFetch > batchSize) ? batchSize : leftToFetch; } // Set the options for the ajax call var xhrOpts = { method: method, url: genDBUrl(host, '_changes' + paramsToStr(params)), timeout: opts.timeout, body: body }; lastFetchedSeq = since; /* istanbul ignore if */ if (opts.aborted) { return; } // Get the changes setup().then(function () { xhr = ajax(opts, xhrOpts, callback); }).catch(callback); }
javascript
function (since, callback) { if (opts.aborted) { return; } params.since = since; // "since" can be any kind of json object in Coudant/CouchDB 2.x /* istanbul ignore next */ if (typeof params.since === "object") { params.since = JSON.stringify(params.since); } if (opts.descending) { if (limit) { params.limit = leftToFetch; } } else { params.limit = (!limit || leftToFetch > batchSize) ? batchSize : leftToFetch; } // Set the options for the ajax call var xhrOpts = { method: method, url: genDBUrl(host, '_changes' + paramsToStr(params)), timeout: opts.timeout, body: body }; lastFetchedSeq = since; /* istanbul ignore if */ if (opts.aborted) { return; } // Get the changes setup().then(function () { xhr = ajax(opts, xhrOpts, callback); }).catch(callback); }
[ "function", "(", "since", ",", "callback", ")", "{", "if", "(", "opts", ".", "aborted", ")", "{", "return", ";", "}", "params", ".", "since", "=", "since", ";", "// \"since\" can be any kind of json object in Coudant/CouchDB 2.x", "/* istanbul ignore next */", "if", "(", "typeof", "params", ".", "since", "===", "\"object\"", ")", "{", "params", ".", "since", "=", "JSON", ".", "stringify", "(", "params", ".", "since", ")", ";", "}", "if", "(", "opts", ".", "descending", ")", "{", "if", "(", "limit", ")", "{", "params", ".", "limit", "=", "leftToFetch", ";", "}", "}", "else", "{", "params", ".", "limit", "=", "(", "!", "limit", "||", "leftToFetch", ">", "batchSize", ")", "?", "batchSize", ":", "leftToFetch", ";", "}", "// Set the options for the ajax call", "var", "xhrOpts", "=", "{", "method", ":", "method", ",", "url", ":", "genDBUrl", "(", "host", ",", "'_changes'", "+", "paramsToStr", "(", "params", ")", ")", ",", "timeout", ":", "opts", ".", "timeout", ",", "body", ":", "body", "}", ";", "lastFetchedSeq", "=", "since", ";", "/* istanbul ignore if */", "if", "(", "opts", ".", "aborted", ")", "{", "return", ";", "}", "// Get the changes", "setup", "(", ")", ".", "then", "(", "function", "(", ")", "{", "xhr", "=", "ajax", "(", "opts", ",", "xhrOpts", ",", "callback", ")", ";", "}", ")", ".", "catch", "(", "callback", ")", ";", "}" ]
Get all the changes starting wtih the one immediately after the sequence number given by since.
[ "Get", "all", "the", "changes", "starting", "wtih", "the", "one", "immediately", "after", "the", "sequence", "number", "given", "by", "since", "." ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L7999-L8037
5,287
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
decodeDoc
function decodeDoc(doc) { if (!doc) { return doc; } var idx = doc._doc_id_rev.lastIndexOf(':'); doc._id = doc._doc_id_rev.substring(0, idx - 1); doc._rev = doc._doc_id_rev.substring(idx + 1); delete doc._doc_id_rev; return doc; }
javascript
function decodeDoc(doc) { if (!doc) { return doc; } var idx = doc._doc_id_rev.lastIndexOf(':'); doc._id = doc._doc_id_rev.substring(0, idx - 1); doc._rev = doc._doc_id_rev.substring(idx + 1); delete doc._doc_id_rev; return doc; }
[ "function", "decodeDoc", "(", "doc", ")", "{", "if", "(", "!", "doc", ")", "{", "return", "doc", ";", "}", "var", "idx", "=", "doc", ".", "_doc_id_rev", ".", "lastIndexOf", "(", "':'", ")", ";", "doc", ".", "_id", "=", "doc", ".", "_doc_id_rev", ".", "substring", "(", "0", ",", "idx", "-", "1", ")", ";", "doc", ".", "_rev", "=", "doc", ".", "_doc_id_rev", ".", "substring", "(", "idx", "+", "1", ")", ";", "delete", "doc", ".", "_doc_id_rev", ";", "return", "doc", ";", "}" ]
read the doc back out from the database. we don't store the _id or _rev because we already have _doc_id_rev.
[ "read", "the", "doc", "back", "out", "from", "the", "database", ".", "we", "don", "t", "store", "the", "_id", "or", "_rev", "because", "we", "already", "have", "_doc_id_rev", "." ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L8238-L8247
5,288
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
readBlobData
function readBlobData(body, type, asBlob, callback) { if (asBlob) { if (!body) { callback(pouchdbBinaryUtils.blob([''], {type: type})); } else if (typeof body !== 'string') { // we have blob support callback(body); } else { // no blob support callback(pouchdbBinaryUtils.base64StringToBlobOrBuffer(body, type)); } } else { // as base64 string if (!body) { callback(''); } else if (typeof body !== 'string') { // we have blob support pouchdbBinaryUtils.readAsBinaryString(body, function (binary) { callback(pouchdbBinaryUtils.btoa(binary)); }); } else { // no blob support callback(body); } } }
javascript
function readBlobData(body, type, asBlob, callback) { if (asBlob) { if (!body) { callback(pouchdbBinaryUtils.blob([''], {type: type})); } else if (typeof body !== 'string') { // we have blob support callback(body); } else { // no blob support callback(pouchdbBinaryUtils.base64StringToBlobOrBuffer(body, type)); } } else { // as base64 string if (!body) { callback(''); } else if (typeof body !== 'string') { // we have blob support pouchdbBinaryUtils.readAsBinaryString(body, function (binary) { callback(pouchdbBinaryUtils.btoa(binary)); }); } else { // no blob support callback(body); } } }
[ "function", "readBlobData", "(", "body", ",", "type", ",", "asBlob", ",", "callback", ")", "{", "if", "(", "asBlob", ")", "{", "if", "(", "!", "body", ")", "{", "callback", "(", "pouchdbBinaryUtils", ".", "blob", "(", "[", "''", "]", ",", "{", "type", ":", "type", "}", ")", ")", ";", "}", "else", "if", "(", "typeof", "body", "!==", "'string'", ")", "{", "// we have blob support", "callback", "(", "body", ")", ";", "}", "else", "{", "// no blob support", "callback", "(", "pouchdbBinaryUtils", ".", "base64StringToBlobOrBuffer", "(", "body", ",", "type", ")", ")", ";", "}", "}", "else", "{", "// as base64 string", "if", "(", "!", "body", ")", "{", "callback", "(", "''", ")", ";", "}", "else", "if", "(", "typeof", "body", "!==", "'string'", ")", "{", "// we have blob support", "pouchdbBinaryUtils", ".", "readAsBinaryString", "(", "body", ",", "function", "(", "binary", ")", "{", "callback", "(", "pouchdbBinaryUtils", ".", "btoa", "(", "binary", ")", ")", ";", "}", ")", ";", "}", "else", "{", "// no blob support", "callback", "(", "body", ")", ";", "}", "}", "}" ]
Read a blob from the database, encoding as necessary and translating from base64 if the IDB doesn't support native Blobs
[ "Read", "a", "blob", "from", "the", "database", "encoding", "as", "necessary", "and", "translating", "from", "base64", "if", "the", "IDB", "doesn", "t", "support", "native", "Blobs" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L8252-L8272
5,289
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
postProcessAttachments
function postProcessAttachments(results, asBlob) { return Promise.all(results.map(function (row) { if (row.doc && row.doc._attachments) { var attNames = Object.keys(row.doc._attachments); return Promise.all(attNames.map(function (att) { var attObj = row.doc._attachments[att]; if (!('body' in attObj)) { // already processed return; } var body = attObj.body; var type = attObj.content_type; return new Promise(function (resolve) { readBlobData(body, type, asBlob, function (data) { row.doc._attachments[att] = pouchdbUtils.assign( pouchdbUtils.pick(attObj, ['digest', 'content_type']), {data: data} ); resolve(); }); }); })); } })); }
javascript
function postProcessAttachments(results, asBlob) { return Promise.all(results.map(function (row) { if (row.doc && row.doc._attachments) { var attNames = Object.keys(row.doc._attachments); return Promise.all(attNames.map(function (att) { var attObj = row.doc._attachments[att]; if (!('body' in attObj)) { // already processed return; } var body = attObj.body; var type = attObj.content_type; return new Promise(function (resolve) { readBlobData(body, type, asBlob, function (data) { row.doc._attachments[att] = pouchdbUtils.assign( pouchdbUtils.pick(attObj, ['digest', 'content_type']), {data: data} ); resolve(); }); }); })); } })); }
[ "function", "postProcessAttachments", "(", "results", ",", "asBlob", ")", "{", "return", "Promise", ".", "all", "(", "results", ".", "map", "(", "function", "(", "row", ")", "{", "if", "(", "row", ".", "doc", "&&", "row", ".", "doc", ".", "_attachments", ")", "{", "var", "attNames", "=", "Object", ".", "keys", "(", "row", ".", "doc", ".", "_attachments", ")", ";", "return", "Promise", ".", "all", "(", "attNames", ".", "map", "(", "function", "(", "att", ")", "{", "var", "attObj", "=", "row", ".", "doc", ".", "_attachments", "[", "att", "]", ";", "if", "(", "!", "(", "'body'", "in", "attObj", ")", ")", "{", "// already processed", "return", ";", "}", "var", "body", "=", "attObj", ".", "body", ";", "var", "type", "=", "attObj", ".", "content_type", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "readBlobData", "(", "body", ",", "type", ",", "asBlob", ",", "function", "(", "data", ")", "{", "row", ".", "doc", ".", "_attachments", "[", "att", "]", "=", "pouchdbUtils", ".", "assign", "(", "pouchdbUtils", ".", "pick", "(", "attObj", ",", "[", "'digest'", ",", "'content_type'", "]", ")", ",", "{", "data", ":", "data", "}", ")", ";", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ")", ";", "}", "}", ")", ")", ";", "}" ]
IDB-specific postprocessing necessary because we don't know whether we stored a true Blob or a base64-encoded string, and if it's a Blob it needs to be read outside of the transaction context
[ "IDB", "-", "specific", "postprocessing", "necessary", "because", "we", "don", "t", "know", "whether", "we", "stored", "a", "true", "Blob", "or", "a", "base64", "-", "encoded", "string", "and", "if", "it", "s", "a", "Blob", "it", "needs", "to", "be", "read", "outside", "of", "the", "transaction", "context" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L8311-L8334
5,290
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
insertAttachmentMappings
function insertAttachmentMappings(docInfo, seq, callback) { var attsAdded = 0; var attsToAdd = Object.keys(docInfo.data._attachments || {}); if (!attsToAdd.length) { return callback(); } function checkDone() { if (++attsAdded === attsToAdd.length) { callback(); } } function add(att) { var digest = docInfo.data._attachments[att].digest; var req = attachAndSeqStore.put({ seq: seq, digestSeq: digest + '::' + seq }); req.onsuccess = checkDone; req.onerror = function (e) { // this callback is for a constaint error, which we ignore // because this docid/rev has already been associated with // the digest (e.g. when new_edits == false) e.preventDefault(); // avoid transaction abort e.stopPropagation(); // avoid transaction onerror checkDone(); }; } for (var i = 0; i < attsToAdd.length; i++) { add(attsToAdd[i]); // do in parallel } }
javascript
function insertAttachmentMappings(docInfo, seq, callback) { var attsAdded = 0; var attsToAdd = Object.keys(docInfo.data._attachments || {}); if (!attsToAdd.length) { return callback(); } function checkDone() { if (++attsAdded === attsToAdd.length) { callback(); } } function add(att) { var digest = docInfo.data._attachments[att].digest; var req = attachAndSeqStore.put({ seq: seq, digestSeq: digest + '::' + seq }); req.onsuccess = checkDone; req.onerror = function (e) { // this callback is for a constaint error, which we ignore // because this docid/rev has already been associated with // the digest (e.g. when new_edits == false) e.preventDefault(); // avoid transaction abort e.stopPropagation(); // avoid transaction onerror checkDone(); }; } for (var i = 0; i < attsToAdd.length; i++) { add(attsToAdd[i]); // do in parallel } }
[ "function", "insertAttachmentMappings", "(", "docInfo", ",", "seq", ",", "callback", ")", "{", "var", "attsAdded", "=", "0", ";", "var", "attsToAdd", "=", "Object", ".", "keys", "(", "docInfo", ".", "data", ".", "_attachments", "||", "{", "}", ")", ";", "if", "(", "!", "attsToAdd", ".", "length", ")", "{", "return", "callback", "(", ")", ";", "}", "function", "checkDone", "(", ")", "{", "if", "(", "++", "attsAdded", "===", "attsToAdd", ".", "length", ")", "{", "callback", "(", ")", ";", "}", "}", "function", "add", "(", "att", ")", "{", "var", "digest", "=", "docInfo", ".", "data", ".", "_attachments", "[", "att", "]", ".", "digest", ";", "var", "req", "=", "attachAndSeqStore", ".", "put", "(", "{", "seq", ":", "seq", ",", "digestSeq", ":", "digest", "+", "'::'", "+", "seq", "}", ")", ";", "req", ".", "onsuccess", "=", "checkDone", ";", "req", ".", "onerror", "=", "function", "(", "e", ")", "{", "// this callback is for a constaint error, which we ignore", "// because this docid/rev has already been associated with", "// the digest (e.g. when new_edits == false)", "e", ".", "preventDefault", "(", ")", ";", "// avoid transaction abort", "e", ".", "stopPropagation", "(", ")", ";", "// avoid transaction onerror", "checkDone", "(", ")", ";", "}", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "attsToAdd", ".", "length", ";", "i", "++", ")", "{", "add", "(", "attsToAdd", "[", "i", "]", ")", ";", "// do in parallel", "}", "}" ]
map seqs to attachment digests, which we will need later during compaction
[ "map", "seqs", "to", "attachment", "digests", "which", "we", "will", "need", "later", "during", "compaction" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L8725-L8760
5,291
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
fetchDocAsynchronously
function fetchDocAsynchronously(metadata, row, winningRev$$1) { var key = metadata.id + "::" + winningRev$$1; docIdRevIndex.get(key).onsuccess = function onGetDoc(e) { row.doc = decodeDoc(e.target.result); if (opts.conflicts) { var conflicts = pouchdbMerge.collectConflicts(metadata); if (conflicts.length) { row.doc._conflicts = conflicts; } } fetchAttachmentsIfNecessary(row.doc, opts, txn); }; }
javascript
function fetchDocAsynchronously(metadata, row, winningRev$$1) { var key = metadata.id + "::" + winningRev$$1; docIdRevIndex.get(key).onsuccess = function onGetDoc(e) { row.doc = decodeDoc(e.target.result); if (opts.conflicts) { var conflicts = pouchdbMerge.collectConflicts(metadata); if (conflicts.length) { row.doc._conflicts = conflicts; } } fetchAttachmentsIfNecessary(row.doc, opts, txn); }; }
[ "function", "fetchDocAsynchronously", "(", "metadata", ",", "row", ",", "winningRev$$1", ")", "{", "var", "key", "=", "metadata", ".", "id", "+", "\"::\"", "+", "winningRev$$1", ";", "docIdRevIndex", ".", "get", "(", "key", ")", ".", "onsuccess", "=", "function", "onGetDoc", "(", "e", ")", "{", "row", ".", "doc", "=", "decodeDoc", "(", "e", ".", "target", ".", "result", ")", ";", "if", "(", "opts", ".", "conflicts", ")", "{", "var", "conflicts", "=", "pouchdbMerge", ".", "collectConflicts", "(", "metadata", ")", ";", "if", "(", "conflicts", ".", "length", ")", "{", "row", ".", "doc", ".", "_conflicts", "=", "conflicts", ";", "}", "}", "fetchAttachmentsIfNecessary", "(", "row", ".", "doc", ",", "opts", ",", "txn", ")", ";", "}", ";", "}" ]
if the user specifies include_docs=true, then we don't want to block the main cursor while we're fetching the doc
[ "if", "the", "user", "specifies", "include_docs", "=", "true", "then", "we", "don", "t", "want", "to", "block", "the", "main", "cursor", "while", "we", "re", "fetching", "the", "doc" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L8961-L8973
5,292
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
createSchema
function createSchema(db) { var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'}); db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true}) .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true}); db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'}); db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false}); db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); // added in v2 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false}); // added in v3 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'}); // added in v4 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE, {autoIncrement: true}); attAndSeqStore.createIndex('seq', 'seq'); attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true}); }
javascript
function createSchema(db) { var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'}); db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true}) .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true}); db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'}); db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false}); db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); // added in v2 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false}); // added in v3 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'}); // added in v4 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE, {autoIncrement: true}); attAndSeqStore.createIndex('seq', 'seq'); attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true}); }
[ "function", "createSchema", "(", "db", ")", "{", "var", "docStore", "=", "db", ".", "createObjectStore", "(", "DOC_STORE", ",", "{", "keyPath", ":", "'id'", "}", ")", ";", "db", ".", "createObjectStore", "(", "BY_SEQ_STORE", ",", "{", "autoIncrement", ":", "true", "}", ")", ".", "createIndex", "(", "'_doc_id_rev'", ",", "'_doc_id_rev'", ",", "{", "unique", ":", "true", "}", ")", ";", "db", ".", "createObjectStore", "(", "ATTACH_STORE", ",", "{", "keyPath", ":", "'digest'", "}", ")", ";", "db", ".", "createObjectStore", "(", "META_STORE", ",", "{", "keyPath", ":", "'id'", ",", "autoIncrement", ":", "false", "}", ")", ";", "db", ".", "createObjectStore", "(", "DETECT_BLOB_SUPPORT_STORE", ")", ";", "// added in v2", "docStore", ".", "createIndex", "(", "'deletedOrLocal'", ",", "'deletedOrLocal'", ",", "{", "unique", ":", "false", "}", ")", ";", "// added in v3", "db", ".", "createObjectStore", "(", "LOCAL_STORE", ",", "{", "keyPath", ":", "'_id'", "}", ")", ";", "// added in v4", "var", "attAndSeqStore", "=", "db", ".", "createObjectStore", "(", "ATTACH_AND_SEQ_STORE", ",", "{", "autoIncrement", ":", "true", "}", ")", ";", "attAndSeqStore", ".", "createIndex", "(", "'seq'", ",", "'seq'", ")", ";", "attAndSeqStore", ".", "createIndex", "(", "'digestSeq'", ",", "'digestSeq'", ",", "{", "unique", ":", "true", "}", ")", ";", "}" ]
called when creating a fresh new database
[ "called", "when", "creating", "a", "fresh", "new", "database" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L9352-L9371
5,293
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
addDeletedOrLocalIndex
function addDeletedOrLocalIndex(txn, callback) { var docStore = txn.objectStore(DOC_STORE); docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false}); docStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { var metadata = cursor.value; var deleted = pouchdbMerge.isDeleted(metadata); metadata.deletedOrLocal = deleted ? "1" : "0"; docStore.put(metadata); cursor.continue(); } else { callback(); } }; }
javascript
function addDeletedOrLocalIndex(txn, callback) { var docStore = txn.objectStore(DOC_STORE); docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false}); docStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { var metadata = cursor.value; var deleted = pouchdbMerge.isDeleted(metadata); metadata.deletedOrLocal = deleted ? "1" : "0"; docStore.put(metadata); cursor.continue(); } else { callback(); } }; }
[ "function", "addDeletedOrLocalIndex", "(", "txn", ",", "callback", ")", "{", "var", "docStore", "=", "txn", ".", "objectStore", "(", "DOC_STORE", ")", ";", "docStore", ".", "createIndex", "(", "'deletedOrLocal'", ",", "'deletedOrLocal'", ",", "{", "unique", ":", "false", "}", ")", ";", "docStore", ".", "openCursor", "(", ")", ".", "onsuccess", "=", "function", "(", "event", ")", "{", "var", "cursor", "=", "event", ".", "target", ".", "result", ";", "if", "(", "cursor", ")", "{", "var", "metadata", "=", "cursor", ".", "value", ";", "var", "deleted", "=", "pouchdbMerge", ".", "isDeleted", "(", "metadata", ")", ";", "metadata", ".", "deletedOrLocal", "=", "deleted", "?", "\"1\"", ":", "\"0\"", ";", "docStore", ".", "put", "(", "metadata", ")", ";", "cursor", ".", "continue", "(", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}", ";", "}" ]
migration to version 2 unfortunately "deletedOrLocal" is a misnomer now that we no longer store local docs in the main doc-store, but whaddyagonnado
[ "migration", "to", "version", "2", "unfortunately", "deletedOrLocal", "is", "a", "misnomer", "now", "that", "we", "no", "longer", "store", "local", "docs", "in", "the", "main", "doc", "-", "store", "but", "whaddyagonnado" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L9376-L9392
5,294
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
verifyAttachment
function verifyAttachment(digest, callback) { txn.get(stores.attachmentStore, digest, function (levelErr) { if (levelErr) { var err = pouchdbErrors.createError(pouchdbErrors.MISSING_STUB, 'unknown stub attachment with digest ' + digest); callback(err); } else { callback(); } }); }
javascript
function verifyAttachment(digest, callback) { txn.get(stores.attachmentStore, digest, function (levelErr) { if (levelErr) { var err = pouchdbErrors.createError(pouchdbErrors.MISSING_STUB, 'unknown stub attachment with digest ' + digest); callback(err); } else { callback(); } }); }
[ "function", "verifyAttachment", "(", "digest", ",", "callback", ")", "{", "txn", ".", "get", "(", "stores", ".", "attachmentStore", ",", "digest", ",", "function", "(", "levelErr", ")", "{", "if", "(", "levelErr", ")", "{", "var", "err", "=", "pouchdbErrors", ".", "createError", "(", "pouchdbErrors", ".", "MISSING_STUB", ",", "'unknown stub attachment with digest '", "+", "digest", ")", ";", "callback", "(", "err", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}", ")", ";", "}" ]
verify any stub attachments as a precondition test
[ "verify", "any", "stub", "attachments", "as", "a", "precondition", "test" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L10649-L10660
5,295
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
fromList
function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; }
javascript
function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; }
[ "function", "fromList", "(", "n", ",", "state", ")", "{", "// nothing buffered", "if", "(", "state", ".", "length", "===", "0", ")", "return", "null", ";", "var", "ret", ";", "if", "(", "state", ".", "objectMode", ")", "ret", "=", "state", ".", "buffer", ".", "shift", "(", ")", ";", "else", "if", "(", "!", "n", "||", "n", ">=", "state", ".", "length", ")", "{", "// read it all, truncate the list", "if", "(", "state", ".", "decoder", ")", "ret", "=", "state", ".", "buffer", ".", "join", "(", "''", ")", ";", "else", "if", "(", "state", ".", "buffer", ".", "length", "===", "1", ")", "ret", "=", "state", ".", "buffer", ".", "head", ".", "data", ";", "else", "ret", "=", "state", ".", "buffer", ".", "concat", "(", "state", ".", "length", ")", ";", "state", ".", "buffer", ".", "clear", "(", ")", ";", "}", "else", "{", "// read part of list", "ret", "=", "fromListPartial", "(", "n", ",", "state", ".", "buffer", ",", "state", ".", "decoder", ")", ";", "}", "return", "ret", ";", "}" ]
Pluck off n bytes from an array of buffers. Length is the combined lengths of all the buffers in the list. This function is designed to be inlinable, so please take care when making changes to the function body.
[ "Pluck", "off", "n", "bytes", "from", "an", "array", "of", "buffers", ".", "Length", "is", "the", "combined", "lengths", "of", "all", "the", "buffers", "in", "the", "list", ".", "This", "function", "is", "designed", "to", "be", "inlinable", "so", "please", "take", "care", "when", "making", "changes", "to", "the", "function", "body", "." ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L12580-L12595
5,296
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
fromListPartial
function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; }
javascript
function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; }
[ "function", "fromListPartial", "(", "n", ",", "list", ",", "hasStrings", ")", "{", "var", "ret", ";", "if", "(", "n", "<", "list", ".", "head", ".", "data", ".", "length", ")", "{", "// slice is the same for buffers and strings", "ret", "=", "list", ".", "head", ".", "data", ".", "slice", "(", "0", ",", "n", ")", ";", "list", ".", "head", ".", "data", "=", "list", ".", "head", ".", "data", ".", "slice", "(", "n", ")", ";", "}", "else", "if", "(", "n", "===", "list", ".", "head", ".", "data", ".", "length", ")", "{", "// first chunk is a perfect match", "ret", "=", "list", ".", "shift", "(", ")", ";", "}", "else", "{", "// result spans more than one buffer", "ret", "=", "hasStrings", "?", "copyFromBufferString", "(", "n", ",", "list", ")", ":", "copyFromBuffer", "(", "n", ",", "list", ")", ";", "}", "return", "ret", ";", "}" ]
Extracts only enough buffered data to satisfy the amount requested. This function is designed to be inlinable, so please take care when making changes to the function body.
[ "Extracts", "only", "enough", "buffered", "data", "to", "satisfy", "the", "amount", "requested", ".", "This", "function", "is", "designed", "to", "be", "inlinable", "so", "please", "take", "care", "when", "making", "changes", "to", "the", "function", "body", "." ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L12600-L12614
5,297
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
writeOrBuffer
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { chunk = decodeChunk(state, chunk, encoding); if (Buffer.isBuffer(chunk)) encoding = 'buffer'; } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; }
javascript
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { chunk = decodeChunk(state, chunk, encoding); if (Buffer.isBuffer(chunk)) encoding = 'buffer'; } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; }
[ "function", "writeOrBuffer", "(", "stream", ",", "state", ",", "isBuf", ",", "chunk", ",", "encoding", ",", "cb", ")", "{", "if", "(", "!", "isBuf", ")", "{", "chunk", "=", "decodeChunk", "(", "state", ",", "chunk", ",", "encoding", ")", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "chunk", ")", ")", "encoding", "=", "'buffer'", ";", "}", "var", "len", "=", "state", ".", "objectMode", "?", "1", ":", "chunk", ".", "length", ";", "state", ".", "length", "+=", "len", ";", "var", "ret", "=", "state", ".", "length", "<", "state", ".", "highWaterMark", ";", "// we must ensure that previous needDrain will not be reset to false.", "if", "(", "!", "ret", ")", "state", ".", "needDrain", "=", "true", ";", "if", "(", "state", ".", "writing", "||", "state", ".", "corked", ")", "{", "var", "last", "=", "state", ".", "lastBufferedRequest", ";", "state", ".", "lastBufferedRequest", "=", "new", "WriteReq", "(", "chunk", ",", "encoding", ",", "cb", ")", ";", "if", "(", "last", ")", "{", "last", ".", "next", "=", "state", ".", "lastBufferedRequest", ";", "}", "else", "{", "state", ".", "bufferedRequest", "=", "state", ".", "lastBufferedRequest", ";", "}", "state", ".", "bufferedRequestCount", "+=", "1", ";", "}", "else", "{", "doWrite", "(", "stream", ",", "state", ",", "false", ",", "len", ",", "chunk", ",", "encoding", ",", "cb", ")", ";", "}", "return", "ret", ";", "}" ]
if we're already writing something, then just put this in the queue, and wait our turn. Otherwise, call _write If we return false, then we need a drain event, so set that flag.
[ "if", "we", "re", "already", "writing", "something", "then", "just", "put", "this", "in", "the", "queue", "and", "wait", "our", "turn", ".", "Otherwise", "call", "_write", "If", "we", "return", "false", "then", "we", "need", "a", "drain", "event", "so", "set", "that", "flag", "." ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L13199-L13226
5,298
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
normalizeEncoding
function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; }
javascript
function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; }
[ "function", "normalizeEncoding", "(", "enc", ")", "{", "var", "nenc", "=", "_normalizeEncoding", "(", "enc", ")", ";", "if", "(", "typeof", "nenc", "!==", "'string'", "&&", "(", "Buffer", ".", "isEncoding", "===", "isEncoding", "||", "!", "isEncoding", "(", "enc", ")", ")", ")", "throw", "new", "Error", "(", "'Unknown encoding: '", "+", "enc", ")", ";", "return", "nenc", "||", "enc", ";", "}" ]
Do not cache `Buffer.isEncoding` when checking encoding names as some modules monkey-patch it to support additional encodings
[ "Do", "not", "cache", "Buffer", ".", "isEncoding", "when", "checking", "encoding", "names", "as", "some", "modules", "monkey", "-", "patch", "it", "to", "support", "additional", "encodings" ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L13567-L13571
5,299
HospitalRun/hospitalrun-frontend
prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js
utf8FillLast
function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; }
javascript
function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; }
[ "function", "utf8FillLast", "(", "buf", ")", "{", "var", "p", "=", "this", ".", "lastTotal", "-", "this", ".", "lastNeed", ";", "var", "r", "=", "utf8CheckExtraBytes", "(", "this", ",", "buf", ",", "p", ")", ";", "if", "(", "r", "!==", "undefined", ")", "return", "r", ";", "if", "(", "this", ".", "lastNeed", "<=", "buf", ".", "length", ")", "{", "buf", ".", "copy", "(", "this", ".", "lastChar", ",", "p", ",", "0", ",", "this", ".", "lastNeed", ")", ";", "return", "this", ".", "lastChar", ".", "toString", "(", "this", ".", "encoding", ",", "0", ",", "this", ".", "lastTotal", ")", ";", "}", "buf", ".", "copy", "(", "this", ".", "lastChar", ",", "p", ",", "0", ",", "buf", ".", "length", ")", ";", "this", ".", "lastNeed", "-=", "buf", ".", "length", ";", "}" ]
Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
[ "Attempts", "to", "complete", "a", "multi", "-", "byte", "UTF", "-", "8", "character", "using", "bytes", "from", "a", "Buffer", "." ]
60b692a1b7aa6f2ef007c28717e76582014e07ad
https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L13699-L13709