id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
16,800
FVANCOP/ChartNew.js
mathFunctions.js
drawMathLine
function drawMathLine(i,lineFct) { var line = 0; // check if the math function exists if (typeof eval(lineFct) == "function") { var parameter = {data:data,datasetNr: i}; line = window[lineFct](parameter); } if (!(typeof(line)=='undefined')) { ctx.strokeStyle= data.datasets[i].mathLineStrokeColor ? data.datasets[i].mathLineStrokeColor : config.defaultStrokeColor; ctx.lineWidth = config.datasetStrokeWidth; ctx.beginPath(); ctx.moveTo(yAxisPosX,yPos(i,0,line,false)); ctx.lineTo(yAxisPosX + msr.availableWidth,yPos(i,data.datasets[i].data.length-1,line,false)); ctx.stroke(); ctx.closePath(); } }
javascript
function drawMathLine(i,lineFct) { var line = 0; // check if the math function exists if (typeof eval(lineFct) == "function") { var parameter = {data:data,datasetNr: i}; line = window[lineFct](parameter); } if (!(typeof(line)=='undefined')) { ctx.strokeStyle= data.datasets[i].mathLineStrokeColor ? data.datasets[i].mathLineStrokeColor : config.defaultStrokeColor; ctx.lineWidth = config.datasetStrokeWidth; ctx.beginPath(); ctx.moveTo(yAxisPosX,yPos(i,0,line,false)); ctx.lineTo(yAxisPosX + msr.availableWidth,yPos(i,data.datasets[i].data.length-1,line,false)); ctx.stroke(); ctx.closePath(); } }
[ "function", "drawMathLine", "(", "i", ",", "lineFct", ")", "{", "var", "line", "=", "0", ";", "// check if the math function exists", "if", "(", "typeof", "eval", "(", "lineFct", ")", "==", "\"function\"", ")", "{", "var", "parameter", "=", "{", "data", ":", "data", ",", "datasetNr", ":", "i", "}", ";", "line", "=", "window", "[", "lineFct", "]", "(", "parameter", ")", ";", "}", "if", "(", "!", "(", "typeof", "(", "line", ")", "==", "'undefined'", ")", ")", "{", "ctx", ".", "strokeStyle", "=", "data", ".", "datasets", "[", "i", "]", ".", "mathLineStrokeColor", "?", "data", ".", "datasets", "[", "i", "]", ".", "mathLineStrokeColor", ":", "config", ".", "defaultStrokeColor", ";", "ctx", ".", "lineWidth", "=", "config", ".", "datasetStrokeWidth", ";", "ctx", ".", "beginPath", "(", ")", ";", "ctx", ".", "moveTo", "(", "yAxisPosX", ",", "yPos", "(", "i", ",", "0", ",", "line", ",", "false", ")", ")", ";", "ctx", ".", "lineTo", "(", "yAxisPosX", "+", "msr", ".", "availableWidth", ",", "yPos", "(", "i", ",", "data", ".", "datasets", "[", "i", "]", ".", "data", ".", "length", "-", "1", ",", "line", ",", "false", ")", ")", ";", "ctx", ".", "stroke", "(", ")", ";", "ctx", ".", "closePath", "(", ")", ";", "}", "}" ]
Draw a horizontal line @param i {integer} numer of dataset @param lineFct {string} name of the mathfunctions => compute height
[ "Draw", "a", "horizontal", "line" ]
08681cadc1c1b6ea334c11d48b2ae43d2267d611
https://github.com/FVANCOP/ChartNew.js/blob/08681cadc1c1b6ea334c11d48b2ae43d2267d611/mathFunctions.js#L135-L151
16,801
FVANCOP/ChartNew.js
mathFunctions.js
yPos
function yPos(dataSet, iteration, add,value) { value = value ? 1*data.datasets[dataSet].data[iteration] : 0; return xAxisPosY - calculateOffset(config.logarithmic, value+add, calculatedScale, scaleHop); }
javascript
function yPos(dataSet, iteration, add,value) { value = value ? 1*data.datasets[dataSet].data[iteration] : 0; return xAxisPosY - calculateOffset(config.logarithmic, value+add, calculatedScale, scaleHop); }
[ "function", "yPos", "(", "dataSet", ",", "iteration", ",", "add", ",", "value", ")", "{", "value", "=", "value", "?", "1", "*", "data", ".", "datasets", "[", "dataSet", "]", ".", "data", "[", "iteration", "]", ":", "0", ";", "return", "xAxisPosY", "-", "calculateOffset", "(", "config", ".", "logarithmic", ",", "value", "+", "add", ",", "calculatedScale", ",", "scaleHop", ")", ";", "}" ]
Get a y position depending on the current values @param dataset {integer} number of dataset @param iteration {integer} number of value inside dataset.data @param add {float} add a value to the current value if value is true @param value {bool} true => value+add, false=>add @returns {float} position (px)
[ "Get", "a", "y", "position", "depending", "on", "the", "current", "values" ]
08681cadc1c1b6ea334c11d48b2ae43d2267d611
https://github.com/FVANCOP/ChartNew.js/blob/08681cadc1c1b6ea334c11d48b2ae43d2267d611/mathFunctions.js#L161-L164
16,802
FVANCOP/ChartNew.js
previous_versions/ChartNew_V1.js
populateLabels
function populateLabels(axis, config, labelTemplateString, labels, numberOfSteps, graphMin, graphMax, stepValue) { var logarithmic; if (axis == 2) { logarithmic = config.logarithmic2; fmtYLabel = config.fmtYLabel2; } else { logarithmic = config.logarithmic; fmtYLabel = config.fmtYLabel; } if (labelTemplateString) { //Fix floating point errors by setting to fixed the on the same decimal as the stepValue. if (!logarithmic) { // no logarithmic scale for (var i = 0; i < numberOfSteps + 1; i++) { labels.push(tmpl(labelTemplateString, { value: fmtChartJS(config, 1 * ((graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))), fmtYLabel) })); } } else { // logarithmic scale 10,100,1000,... var value = graphMin; for (var i = 0; i < numberOfSteps + 1; i++) { labels.push(tmpl(labelTemplateString, { value: fmtChartJS(config, 1 * value.toFixed(getDecimalPlaces(value)), fmtYLabel) })); value *= 10; } } } }
javascript
function populateLabels(axis, config, labelTemplateString, labels, numberOfSteps, graphMin, graphMax, stepValue) { var logarithmic; if (axis == 2) { logarithmic = config.logarithmic2; fmtYLabel = config.fmtYLabel2; } else { logarithmic = config.logarithmic; fmtYLabel = config.fmtYLabel; } if (labelTemplateString) { //Fix floating point errors by setting to fixed the on the same decimal as the stepValue. if (!logarithmic) { // no logarithmic scale for (var i = 0; i < numberOfSteps + 1; i++) { labels.push(tmpl(labelTemplateString, { value: fmtChartJS(config, 1 * ((graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))), fmtYLabel) })); } } else { // logarithmic scale 10,100,1000,... var value = graphMin; for (var i = 0; i < numberOfSteps + 1; i++) { labels.push(tmpl(labelTemplateString, { value: fmtChartJS(config, 1 * value.toFixed(getDecimalPlaces(value)), fmtYLabel) })); value *= 10; } } } }
[ "function", "populateLabels", "(", "axis", ",", "config", ",", "labelTemplateString", ",", "labels", ",", "numberOfSteps", ",", "graphMin", ",", "graphMax", ",", "stepValue", ")", "{", "var", "logarithmic", ";", "if", "(", "axis", "==", "2", ")", "{", "logarithmic", "=", "config", ".", "logarithmic2", ";", "fmtYLabel", "=", "config", ".", "fmtYLabel2", ";", "}", "else", "{", "logarithmic", "=", "config", ".", "logarithmic", ";", "fmtYLabel", "=", "config", ".", "fmtYLabel", ";", "}", "if", "(", "labelTemplateString", ")", "{", "//Fix floating point errors by setting to fixed the on the same decimal as the stepValue.", "if", "(", "!", "logarithmic", ")", "{", "// no logarithmic scale", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numberOfSteps", "+", "1", ";", "i", "++", ")", "{", "labels", ".", "push", "(", "tmpl", "(", "labelTemplateString", ",", "{", "value", ":", "fmtChartJS", "(", "config", ",", "1", "*", "(", "(", "graphMin", "+", "(", "stepValue", "*", "i", ")", ")", ".", "toFixed", "(", "getDecimalPlaces", "(", "stepValue", ")", ")", ")", ",", "fmtYLabel", ")", "}", ")", ")", ";", "}", "}", "else", "{", "// logarithmic scale 10,100,1000,...", "var", "value", "=", "graphMin", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numberOfSteps", "+", "1", ";", "i", "++", ")", "{", "labels", ".", "push", "(", "tmpl", "(", "labelTemplateString", ",", "{", "value", ":", "fmtChartJS", "(", "config", ",", "1", "*", "value", ".", "toFixed", "(", "getDecimalPlaces", "(", "value", ")", ")", ",", "fmtYLabel", ")", "}", ")", ")", ";", "value", "*=", "10", ";", "}", "}", "}", "}" ]
Populate an array of all the labels by interpolating the string.
[ "Populate", "an", "array", "of", "all", "the", "labels", "by", "interpolating", "the", "string", "." ]
08681cadc1c1b6ea334c11d48b2ae43d2267d611
https://github.com/FVANCOP/ChartNew.js/blob/08681cadc1c1b6ea334c11d48b2ae43d2267d611/previous_versions/ChartNew_V1.js#L5159-L5186
16,803
broofa/node-int64
Int64.js
function(allowImprecise) { var b = this.buffer, o = this.offset; // Running sum of octets, doing a 2's complement var negate = b[o] & 0x80, x = 0, carry = 1; for (var i = 7, m = 1; i >= 0; i--, m *= 256) { var v = b[o+i]; // 2's complement for negative numbers if (negate) { v = (v ^ 0xff) + carry; carry = v >> 8; v = v & 0xff; } x += v * m; } // Return Infinity if we've lost integer precision if (!allowImprecise && x >= Int64.MAX_INT) { return negate ? -Infinity : Infinity; } return negate ? -x : x; }
javascript
function(allowImprecise) { var b = this.buffer, o = this.offset; // Running sum of octets, doing a 2's complement var negate = b[o] & 0x80, x = 0, carry = 1; for (var i = 7, m = 1; i >= 0; i--, m *= 256) { var v = b[o+i]; // 2's complement for negative numbers if (negate) { v = (v ^ 0xff) + carry; carry = v >> 8; v = v & 0xff; } x += v * m; } // Return Infinity if we've lost integer precision if (!allowImprecise && x >= Int64.MAX_INT) { return negate ? -Infinity : Infinity; } return negate ? -x : x; }
[ "function", "(", "allowImprecise", ")", "{", "var", "b", "=", "this", ".", "buffer", ",", "o", "=", "this", ".", "offset", ";", "// Running sum of octets, doing a 2's complement", "var", "negate", "=", "b", "[", "o", "]", "&", "0x80", ",", "x", "=", "0", ",", "carry", "=", "1", ";", "for", "(", "var", "i", "=", "7", ",", "m", "=", "1", ";", "i", ">=", "0", ";", "i", "--", ",", "m", "*=", "256", ")", "{", "var", "v", "=", "b", "[", "o", "+", "i", "]", ";", "// 2's complement for negative numbers", "if", "(", "negate", ")", "{", "v", "=", "(", "v", "^", "0xff", ")", "+", "carry", ";", "carry", "=", "v", ">>", "8", ";", "v", "=", "v", "&", "0xff", ";", "}", "x", "+=", "v", "*", "m", ";", "}", "// Return Infinity if we've lost integer precision", "if", "(", "!", "allowImprecise", "&&", "x", ">=", "Int64", ".", "MAX_INT", ")", "{", "return", "negate", "?", "-", "Infinity", ":", "Infinity", ";", "}", "return", "negate", "?", "-", "x", ":", "x", ";", "}" ]
Convert to a native JS number. WARNING: Do not expect this value to be accurate to integer precision for large (positive or negative) numbers! @param allowImprecise If true, no check is performed to verify the returned value is accurate to integer precision. If false, imprecise numbers (very large positive or negative numbers) will be forced to +/- Infinity.
[ "Convert", "to", "a", "native", "JS", "number", "." ]
ea76fbc55f6d0e11719c1cb38126fc93e8c9e257
https://github.com/broofa/node-int64/blob/ea76fbc55f6d0e11719c1cb38126fc93e8c9e257/Int64.js#L150-L174
16,804
broofa/node-int64
Int64.js
function(sep) { var out = new Array(8); var b = this.buffer, o = this.offset; for (var i = 0; i < 8; i++) { out[i] = _HEX[b[o+i]]; } return out.join(sep || ''); }
javascript
function(sep) { var out = new Array(8); var b = this.buffer, o = this.offset; for (var i = 0; i < 8; i++) { out[i] = _HEX[b[o+i]]; } return out.join(sep || ''); }
[ "function", "(", "sep", ")", "{", "var", "out", "=", "new", "Array", "(", "8", ")", ";", "var", "b", "=", "this", ".", "buffer", ",", "o", "=", "this", ".", "offset", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "8", ";", "i", "++", ")", "{", "out", "[", "i", "]", "=", "_HEX", "[", "b", "[", "o", "+", "i", "]", "]", ";", "}", "return", "out", ".", "join", "(", "sep", "||", "''", ")", ";", "}" ]
Return a string showing the buffer octets, with MSB on the left. @param sep separator string. default is '' (empty string)
[ "Return", "a", "string", "showing", "the", "buffer", "octets", "with", "MSB", "on", "the", "left", "." ]
ea76fbc55f6d0e11719c1cb38126fc93e8c9e257
https://github.com/broofa/node-int64/blob/ea76fbc55f6d0e11719c1cb38126fc93e8c9e257/Int64.js#L198-L205
16,805
broofa/node-int64
Int64.js
function(rawBuffer) { if (rawBuffer && this.offset === 0) return this.buffer; var out = new Buffer(8); this.buffer.copy(out, 0, this.offset, this.offset + 8); return out; }
javascript
function(rawBuffer) { if (rawBuffer && this.offset === 0) return this.buffer; var out = new Buffer(8); this.buffer.copy(out, 0, this.offset, this.offset + 8); return out; }
[ "function", "(", "rawBuffer", ")", "{", "if", "(", "rawBuffer", "&&", "this", ".", "offset", "===", "0", ")", "return", "this", ".", "buffer", ";", "var", "out", "=", "new", "Buffer", "(", "8", ")", ";", "this", ".", "buffer", ".", "copy", "(", "out", ",", "0", ",", "this", ".", "offset", ",", "this", ".", "offset", "+", "8", ")", ";", "return", "out", ";", "}" ]
Returns the int64's 8 bytes in a buffer. @param {bool} [rawBuffer=false] If no offset and this is true, return the internal buffer. Should only be used if you're discarding the Int64 afterwards, as it breaks encapsulation.
[ "Returns", "the", "int64", "s", "8", "bytes", "in", "a", "buffer", "." ]
ea76fbc55f6d0e11719c1cb38126fc93e8c9e257
https://github.com/broofa/node-int64/blob/ea76fbc55f6d0e11719c1cb38126fc93e8c9e257/Int64.js#L213-L219
16,806
broofa/node-int64
Int64.js
function(other) { // If sign bits differ ... if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) { return other.buffer[other.offset] - this.buffer[this.offset]; } // otherwise, compare bytes lexicographically for (var i = 0; i < 8; i++) { if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) { return this.buffer[this.offset+i] - other.buffer[other.offset+i]; } } return 0; }
javascript
function(other) { // If sign bits differ ... if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) { return other.buffer[other.offset] - this.buffer[this.offset]; } // otherwise, compare bytes lexicographically for (var i = 0; i < 8; i++) { if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) { return this.buffer[this.offset+i] - other.buffer[other.offset+i]; } } return 0; }
[ "function", "(", "other", ")", "{", "// If sign bits differ ...", "if", "(", "(", "this", ".", "buffer", "[", "this", ".", "offset", "]", "&", "0x80", ")", "!=", "(", "other", ".", "buffer", "[", "other", ".", "offset", "]", "&", "0x80", ")", ")", "{", "return", "other", ".", "buffer", "[", "other", ".", "offset", "]", "-", "this", ".", "buffer", "[", "this", ".", "offset", "]", ";", "}", "// otherwise, compare bytes lexicographically", "for", "(", "var", "i", "=", "0", ";", "i", "<", "8", ";", "i", "++", ")", "{", "if", "(", "this", ".", "buffer", "[", "this", ".", "offset", "+", "i", "]", "!==", "other", ".", "buffer", "[", "other", ".", "offset", "+", "i", "]", ")", "{", "return", "this", ".", "buffer", "[", "this", ".", "offset", "+", "i", "]", "-", "other", ".", "buffer", "[", "other", ".", "offset", "+", "i", "]", ";", "}", "}", "return", "0", ";", "}" ]
Returns a number indicating whether this comes before or after or is the same as the other in sort order. @param {Int64} other Other Int64 to compare.
[ "Returns", "a", "number", "indicating", "whether", "this", "comes", "before", "or", "after", "or", "is", "the", "same", "as", "the", "other", "in", "sort", "order", "." ]
ea76fbc55f6d0e11719c1cb38126fc93e8c9e257
https://github.com/broofa/node-int64/blob/ea76fbc55f6d0e11719c1cb38126fc93e8c9e257/Int64.js#L237-L251
16,807
chainpoint/chainpoint-client-js
index.js
_isValidCoreURI
function _isValidCoreURI(coreURI) { if (_isEmpty(coreURI) || !_isString(coreURI)) return false try { return isURL(coreURI, { protocols: ['https'], require_protocol: true, host_whitelist: [/^[a-z]\.chainpoint\.org$/] }) } catch (error) { return false } }
javascript
function _isValidCoreURI(coreURI) { if (_isEmpty(coreURI) || !_isString(coreURI)) return false try { return isURL(coreURI, { protocols: ['https'], require_protocol: true, host_whitelist: [/^[a-z]\.chainpoint\.org$/] }) } catch (error) { return false } }
[ "function", "_isValidCoreURI", "(", "coreURI", ")", "{", "if", "(", "_isEmpty", "(", "coreURI", ")", "||", "!", "_isString", "(", "coreURI", ")", ")", "return", "false", "try", "{", "return", "isURL", "(", "coreURI", ",", "{", "protocols", ":", "[", "'https'", "]", ",", "require_protocol", ":", "true", ",", "host_whitelist", ":", "[", "/", "^[a-z]\\.chainpoint\\.org$", "/", "]", "}", ")", "}", "catch", "(", "error", ")", "{", "return", "false", "}", "}" ]
Check if valid Core URI @param {string} coreURI - The Core URI to test for validity @returns {bool} true if coreURI is a valid Core URI, otherwise false
[ "Check", "if", "valid", "Core", "URI" ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L97-L109
16,808
chainpoint/chainpoint-client-js
index.js
_isValidNodeURI
function _isValidNodeURI(nodeURI) { if (!_isString(nodeURI)) return false try { let isValidURI = isURL(nodeURI, { protocols: ['http', 'https'], require_protocol: true, host_blacklist: ['0.0.0.0'] }) let parsedURI = url.parse(nodeURI).hostname // Valid URI w/ IPv4 address? return isValidURI && isIP(parsedURI, 4) } catch (error) { return false } }
javascript
function _isValidNodeURI(nodeURI) { if (!_isString(nodeURI)) return false try { let isValidURI = isURL(nodeURI, { protocols: ['http', 'https'], require_protocol: true, host_blacklist: ['0.0.0.0'] }) let parsedURI = url.parse(nodeURI).hostname // Valid URI w/ IPv4 address? return isValidURI && isIP(parsedURI, 4) } catch (error) { return false } }
[ "function", "_isValidNodeURI", "(", "nodeURI", ")", "{", "if", "(", "!", "_isString", "(", "nodeURI", ")", ")", "return", "false", "try", "{", "let", "isValidURI", "=", "isURL", "(", "nodeURI", ",", "{", "protocols", ":", "[", "'http'", ",", "'https'", "]", ",", "require_protocol", ":", "true", ",", "host_blacklist", ":", "[", "'0.0.0.0'", "]", "}", ")", "let", "parsedURI", "=", "url", ".", "parse", "(", "nodeURI", ")", ".", "hostname", "// Valid URI w/ IPv4 address?", "return", "isValidURI", "&&", "isIP", "(", "parsedURI", ",", "4", ")", "}", "catch", "(", "error", ")", "{", "return", "false", "}", "}" ]
Check if valid Node URI @param {string} nodeURI - The value to check @returns {bool} true if value is a valid Node URI, otherwise false
[ "Check", "if", "valid", "Node", "URI" ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L176-L193
16,809
chainpoint/chainpoint-client-js
index.js
_isHex
function _isHex(value) { var hexRegex = /^[0-9a-f]{2,}$/i var isHex = hexRegex.test(value) && !(value.length % 2) return isHex }
javascript
function _isHex(value) { var hexRegex = /^[0-9a-f]{2,}$/i var isHex = hexRegex.test(value) && !(value.length % 2) return isHex }
[ "function", "_isHex", "(", "value", ")", "{", "var", "hexRegex", "=", "/", "^[0-9a-f]{2,}$", "/", "i", "var", "isHex", "=", "hexRegex", ".", "test", "(", "value", ")", "&&", "!", "(", "value", ".", "length", "%", "2", ")", "return", "isHex", "}" ]
Checks if value is a hexadecimal string @param {string} value - The value to check @returns {bool} true if value is a hexadecimal string, otherwise false
[ "Checks", "if", "value", "is", "a", "hexadecimal", "string" ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L258-L262
16,810
chainpoint/chainpoint-client-js
index.js
_isValidProofHandle
function _isValidProofHandle(handle) { if ( !_isEmpty(handle) && _isObject(handle) && _has(handle, 'uri') && _has(handle, 'hashIdNode') ) { return true } }
javascript
function _isValidProofHandle(handle) { if ( !_isEmpty(handle) && _isObject(handle) && _has(handle, 'uri') && _has(handle, 'hashIdNode') ) { return true } }
[ "function", "_isValidProofHandle", "(", "handle", ")", "{", "if", "(", "!", "_isEmpty", "(", "handle", ")", "&&", "_isObject", "(", "handle", ")", "&&", "_has", "(", "handle", ",", "'uri'", ")", "&&", "_has", "(", "handle", ",", "'hashIdNode'", ")", ")", "{", "return", "true", "}", "}" ]
Checks if a proof handle Object has valid params. @param {Object} handle - The proof handle to check @returns {bool} true if handle is valid Object with expected params, otherwise false
[ "Checks", "if", "a", "proof", "handle", "Object", "has", "valid", "params", "." ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L270-L279
16,811
chainpoint/chainpoint-client-js
index.js
_mapSubmitHashesRespToProofHandles
function _mapSubmitHashesRespToProofHandles(respArray) { if (!_isArray(respArray) && !respArray.length) throw new Error('_mapSubmitHashesRespToProofHandles arg must be an Array') let proofHandles = [] let groupIdList = [] if (respArray[0] && respArray[0].hashes) { _forEach(respArray[0].hashes, () => { groupIdList.push(uuidv1()) }) } _forEach(respArray, resp => { _forEach(resp.hashes, (hash, idx) => { let handle = {} handle.uri = resp.meta.submitted_to handle.hash = hash.hash handle.hashIdNode = hash.hash_id_node handle.groupId = groupIdList[idx] proofHandles.push(handle) }) }) return proofHandles }
javascript
function _mapSubmitHashesRespToProofHandles(respArray) { if (!_isArray(respArray) && !respArray.length) throw new Error('_mapSubmitHashesRespToProofHandles arg must be an Array') let proofHandles = [] let groupIdList = [] if (respArray[0] && respArray[0].hashes) { _forEach(respArray[0].hashes, () => { groupIdList.push(uuidv1()) }) } _forEach(respArray, resp => { _forEach(resp.hashes, (hash, idx) => { let handle = {} handle.uri = resp.meta.submitted_to handle.hash = hash.hash handle.hashIdNode = hash.hash_id_node handle.groupId = groupIdList[idx] proofHandles.push(handle) }) }) return proofHandles }
[ "function", "_mapSubmitHashesRespToProofHandles", "(", "respArray", ")", "{", "if", "(", "!", "_isArray", "(", "respArray", ")", "&&", "!", "respArray", ".", "length", ")", "throw", "new", "Error", "(", "'_mapSubmitHashesRespToProofHandles arg must be an Array'", ")", "let", "proofHandles", "=", "[", "]", "let", "groupIdList", "=", "[", "]", "if", "(", "respArray", "[", "0", "]", "&&", "respArray", "[", "0", "]", ".", "hashes", ")", "{", "_forEach", "(", "respArray", "[", "0", "]", ".", "hashes", ",", "(", ")", "=>", "{", "groupIdList", ".", "push", "(", "uuidv1", "(", ")", ")", "}", ")", "}", "_forEach", "(", "respArray", ",", "resp", "=>", "{", "_forEach", "(", "resp", ".", "hashes", ",", "(", "hash", ",", "idx", ")", "=>", "{", "let", "handle", "=", "{", "}", "handle", ".", "uri", "=", "resp", ".", "meta", ".", "submitted_to", "handle", ".", "hash", "=", "hash", ".", "hash", "handle", ".", "hashIdNode", "=", "hash", ".", "hash_id_node", "handle", ".", "groupId", "=", "groupIdList", "[", "idx", "]", "proofHandles", ".", "push", "(", "handle", ")", "}", ")", "}", ")", "return", "proofHandles", "}" ]
Map the JSON API response from submitting a hash to a Node to a more accessible form that can also be used as the input arg to getProofs function. @param {Array} respArray - An Array of responses, one for each Node submitted to @returns {Array<{uri: String, hash: String, hashIdNode: String}>} An Array of proofHandles
[ "Map", "the", "JSON", "API", "response", "from", "submitting", "a", "hash", "to", "a", "Node", "to", "a", "more", "accessible", "form", "that", "can", "also", "be", "used", "as", "the", "input", "arg", "to", "getProofs", "function", "." ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L301-L326
16,812
chainpoint/chainpoint-client-js
index.js
_parseProofs
function _parseProofs(proofs) { if (!_isArray(proofs)) throw new Error('proofs arg must be an Array') if (_isEmpty(proofs)) throw new Error('proofs arg must be a non-empty Array') let parsedProofs = [] _forEach(proofs, proof => { if (_isObject(proof)) { // OBJECT parsedProofs.push(cpp.parse(proof)) } else if (isJSON(proof)) { // JSON-LD parsedProofs.push(cpp.parse(JSON.parse(proof))) } else if (isBase64(proof) || _isBuffer(proof) || _isHex(proof)) { // BINARY parsedProofs.push(cpp.parse(proof)) } else { throw new Error('unknown proof format') } }) return parsedProofs }
javascript
function _parseProofs(proofs) { if (!_isArray(proofs)) throw new Error('proofs arg must be an Array') if (_isEmpty(proofs)) throw new Error('proofs arg must be a non-empty Array') let parsedProofs = [] _forEach(proofs, proof => { if (_isObject(proof)) { // OBJECT parsedProofs.push(cpp.parse(proof)) } else if (isJSON(proof)) { // JSON-LD parsedProofs.push(cpp.parse(JSON.parse(proof))) } else if (isBase64(proof) || _isBuffer(proof) || _isHex(proof)) { // BINARY parsedProofs.push(cpp.parse(proof)) } else { throw new Error('unknown proof format') } }) return parsedProofs }
[ "function", "_parseProofs", "(", "proofs", ")", "{", "if", "(", "!", "_isArray", "(", "proofs", ")", ")", "throw", "new", "Error", "(", "'proofs arg must be an Array'", ")", "if", "(", "_isEmpty", "(", "proofs", ")", ")", "throw", "new", "Error", "(", "'proofs arg must be a non-empty Array'", ")", "let", "parsedProofs", "=", "[", "]", "_forEach", "(", "proofs", ",", "proof", "=>", "{", "if", "(", "_isObject", "(", "proof", ")", ")", "{", "// OBJECT", "parsedProofs", ".", "push", "(", "cpp", ".", "parse", "(", "proof", ")", ")", "}", "else", "if", "(", "isJSON", "(", "proof", ")", ")", "{", "// JSON-LD", "parsedProofs", ".", "push", "(", "cpp", ".", "parse", "(", "JSON", ".", "parse", "(", "proof", ")", ")", ")", "}", "else", "if", "(", "isBase64", "(", "proof", ")", "||", "_isBuffer", "(", "proof", ")", "||", "_isHex", "(", "proof", ")", ")", "{", "// BINARY", "parsedProofs", ".", "push", "(", "cpp", ".", "parse", "(", "proof", ")", ")", "}", "else", "{", "throw", "new", "Error", "(", "'unknown proof format'", ")", "}", "}", ")", "return", "parsedProofs", "}" ]
Parse an Array of proofs, each of which can be in any supported format. @param {Array} proofs - An Array of proofs in any supported form @returns {Array} An Array of parsed proofs
[ "Parse", "an", "Array", "of", "proofs", "each", "of", "which", "can", "be", "in", "any", "supported", "format", "." ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L334-L356
16,813
chainpoint/chainpoint-client-js
index.js
_flattenProofs
function _flattenProofs(parsedProofs) { if (!_isArray(parsedProofs)) throw new Error('parsedProofs arg must be an Array') if (_isEmpty(parsedProofs)) throw new Error('parsedProofs arg must be a non-empty Array') let flatProofAnchors = [] _forEach(parsedProofs, parsedProof => { let proofAnchors = _flattenProofBranches(parsedProof.branches) _forEach(proofAnchors, proofAnchor => { let flatProofAnchor = {} flatProofAnchor.hash = parsedProof.hash flatProofAnchor.hash_id_node = parsedProof.hash_id_node flatProofAnchor.hash_id_core = parsedProof.hash_id_core flatProofAnchor.hash_submitted_node_at = parsedProof.hash_submitted_node_at flatProofAnchor.hash_submitted_core_at = parsedProof.hash_submitted_core_at flatProofAnchor.branch = proofAnchor.branch flatProofAnchor.uri = proofAnchor.uri flatProofAnchor.type = proofAnchor.type flatProofAnchor.anchor_id = proofAnchor.anchor_id flatProofAnchor.expected_value = proofAnchor.expected_value flatProofAnchors.push(flatProofAnchor) }) }) return flatProofAnchors }
javascript
function _flattenProofs(parsedProofs) { if (!_isArray(parsedProofs)) throw new Error('parsedProofs arg must be an Array') if (_isEmpty(parsedProofs)) throw new Error('parsedProofs arg must be a non-empty Array') let flatProofAnchors = [] _forEach(parsedProofs, parsedProof => { let proofAnchors = _flattenProofBranches(parsedProof.branches) _forEach(proofAnchors, proofAnchor => { let flatProofAnchor = {} flatProofAnchor.hash = parsedProof.hash flatProofAnchor.hash_id_node = parsedProof.hash_id_node flatProofAnchor.hash_id_core = parsedProof.hash_id_core flatProofAnchor.hash_submitted_node_at = parsedProof.hash_submitted_node_at flatProofAnchor.hash_submitted_core_at = parsedProof.hash_submitted_core_at flatProofAnchor.branch = proofAnchor.branch flatProofAnchor.uri = proofAnchor.uri flatProofAnchor.type = proofAnchor.type flatProofAnchor.anchor_id = proofAnchor.anchor_id flatProofAnchor.expected_value = proofAnchor.expected_value flatProofAnchors.push(flatProofAnchor) }) }) return flatProofAnchors }
[ "function", "_flattenProofs", "(", "parsedProofs", ")", "{", "if", "(", "!", "_isArray", "(", "parsedProofs", ")", ")", "throw", "new", "Error", "(", "'parsedProofs arg must be an Array'", ")", "if", "(", "_isEmpty", "(", "parsedProofs", ")", ")", "throw", "new", "Error", "(", "'parsedProofs arg must be a non-empty Array'", ")", "let", "flatProofAnchors", "=", "[", "]", "_forEach", "(", "parsedProofs", ",", "parsedProof", "=>", "{", "let", "proofAnchors", "=", "_flattenProofBranches", "(", "parsedProof", ".", "branches", ")", "_forEach", "(", "proofAnchors", ",", "proofAnchor", "=>", "{", "let", "flatProofAnchor", "=", "{", "}", "flatProofAnchor", ".", "hash", "=", "parsedProof", ".", "hash", "flatProofAnchor", ".", "hash_id_node", "=", "parsedProof", ".", "hash_id_node", "flatProofAnchor", ".", "hash_id_core", "=", "parsedProof", ".", "hash_id_core", "flatProofAnchor", ".", "hash_submitted_node_at", "=", "parsedProof", ".", "hash_submitted_node_at", "flatProofAnchor", ".", "hash_submitted_core_at", "=", "parsedProof", ".", "hash_submitted_core_at", "flatProofAnchor", ".", "branch", "=", "proofAnchor", ".", "branch", "flatProofAnchor", ".", "uri", "=", "proofAnchor", ".", "uri", "flatProofAnchor", ".", "type", "=", "proofAnchor", ".", "type", "flatProofAnchor", ".", "anchor_id", "=", "proofAnchor", ".", "anchor_id", "flatProofAnchor", ".", "expected_value", "=", "proofAnchor", ".", "expected_value", "flatProofAnchors", ".", "push", "(", "flatProofAnchor", ")", "}", ")", "}", ")", "return", "flatProofAnchors", "}" ]
Flatten an Array of parsed proofs where each proof anchor is represented as an Object with all relevant proof data. @param {Array} parsedProofs - An Array of previously parsed proofs @returns {Array} An Array of flattened proof objects
[ "Flatten", "an", "Array", "of", "parsed", "proofs", "where", "each", "proof", "anchor", "is", "represented", "as", "an", "Object", "with", "all", "relevant", "proof", "data", "." ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L365-L394
16,814
chainpoint/chainpoint-client-js
index.js
_flattenProofBranches
function _flattenProofBranches(proofBranchArray) { let flatProofAnchors = [] _forEach(proofBranchArray, proofBranch => { let anchors = proofBranch.anchors _forEach(anchors, anchor => { let flatAnchor = {} flatAnchor.branch = proofBranch.label || undefined flatAnchor.uri = anchor.uris[0] flatAnchor.type = anchor.type flatAnchor.anchor_id = anchor.anchor_id flatAnchor.expected_value = anchor.expected_value flatProofAnchors.push(flatAnchor) }) if (proofBranch.branches) { flatProofAnchors = flatProofAnchors.concat( _flattenProofBranches(proofBranch.branches) ) } }) return flatProofAnchors }
javascript
function _flattenProofBranches(proofBranchArray) { let flatProofAnchors = [] _forEach(proofBranchArray, proofBranch => { let anchors = proofBranch.anchors _forEach(anchors, anchor => { let flatAnchor = {} flatAnchor.branch = proofBranch.label || undefined flatAnchor.uri = anchor.uris[0] flatAnchor.type = anchor.type flatAnchor.anchor_id = anchor.anchor_id flatAnchor.expected_value = anchor.expected_value flatProofAnchors.push(flatAnchor) }) if (proofBranch.branches) { flatProofAnchors = flatProofAnchors.concat( _flattenProofBranches(proofBranch.branches) ) } }) return flatProofAnchors }
[ "function", "_flattenProofBranches", "(", "proofBranchArray", ")", "{", "let", "flatProofAnchors", "=", "[", "]", "_forEach", "(", "proofBranchArray", ",", "proofBranch", "=>", "{", "let", "anchors", "=", "proofBranch", ".", "anchors", "_forEach", "(", "anchors", ",", "anchor", "=>", "{", "let", "flatAnchor", "=", "{", "}", "flatAnchor", ".", "branch", "=", "proofBranch", ".", "label", "||", "undefined", "flatAnchor", ".", "uri", "=", "anchor", ".", "uris", "[", "0", "]", "flatAnchor", ".", "type", "=", "anchor", ".", "type", "flatAnchor", ".", "anchor_id", "=", "anchor", ".", "anchor_id", "flatAnchor", ".", "expected_value", "=", "anchor", ".", "expected_value", "flatProofAnchors", ".", "push", "(", "flatAnchor", ")", "}", ")", "if", "(", "proofBranch", ".", "branches", ")", "{", "flatProofAnchors", "=", "flatProofAnchors", ".", "concat", "(", "_flattenProofBranches", "(", "proofBranch", ".", "branches", ")", ")", "}", "}", ")", "return", "flatProofAnchors", "}" ]
Flatten an Array of proof branches where each proof anchor in each branch is represented as an Object with all relevant data for that anchor. @param {Array} proofBranchArray - An Array of branches for a given level in a proof @returns {Array} An Array of flattened proof anchor objects for each branch
[ "Flatten", "an", "Array", "of", "proof", "branches", "where", "each", "proof", "anchor", "in", "each", "branch", "is", "represented", "as", "an", "Object", "with", "all", "relevant", "data", "for", "that", "anchor", "." ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L403-L424
16,815
chainpoint/chainpoint-client-js
index.js
_flattenBtcBranches
function _flattenBtcBranches(proofs) { let flattenedBranches = [] _forEach(proofs, proof => { let btcAnchor = {} btcAnchor.hash_id_node = proof.hash_id_node if (proof.branches) { _forEach(proof.branches, branch => { // sub branches indicate other anchors // we want to find the sub-branch that anchors to btc if (branch.branches) { // get the raw tx from the btc_anchor_branch let btcBranch = branch.branches.find( element => element.label === 'btc_anchor_branch' ) btcAnchor.raw_btc_tx = btcBranch.rawTx // get the btc anchor let anchor = btcBranch.anchors.find(anchor => anchor.type === 'btc') // add expected_value (i.e. the merkle root of anchored block) btcAnchor.expected_value = anchor.expected_value // add anchor_id (i.e. the anchored block height) btcAnchor.anchor_id = anchor.anchor_id } }) } flattenedBranches.push(btcAnchor) }) return flattenedBranches }
javascript
function _flattenBtcBranches(proofs) { let flattenedBranches = [] _forEach(proofs, proof => { let btcAnchor = {} btcAnchor.hash_id_node = proof.hash_id_node if (proof.branches) { _forEach(proof.branches, branch => { // sub branches indicate other anchors // we want to find the sub-branch that anchors to btc if (branch.branches) { // get the raw tx from the btc_anchor_branch let btcBranch = branch.branches.find( element => element.label === 'btc_anchor_branch' ) btcAnchor.raw_btc_tx = btcBranch.rawTx // get the btc anchor let anchor = btcBranch.anchors.find(anchor => anchor.type === 'btc') // add expected_value (i.e. the merkle root of anchored block) btcAnchor.expected_value = anchor.expected_value // add anchor_id (i.e. the anchored block height) btcAnchor.anchor_id = anchor.anchor_id } }) } flattenedBranches.push(btcAnchor) }) return flattenedBranches }
[ "function", "_flattenBtcBranches", "(", "proofs", ")", "{", "let", "flattenedBranches", "=", "[", "]", "_forEach", "(", "proofs", ",", "proof", "=>", "{", "let", "btcAnchor", "=", "{", "}", "btcAnchor", ".", "hash_id_node", "=", "proof", ".", "hash_id_node", "if", "(", "proof", ".", "branches", ")", "{", "_forEach", "(", "proof", ".", "branches", ",", "branch", "=>", "{", "// sub branches indicate other anchors", "// we want to find the sub-branch that anchors to btc", "if", "(", "branch", ".", "branches", ")", "{", "// get the raw tx from the btc_anchor_branch", "let", "btcBranch", "=", "branch", ".", "branches", ".", "find", "(", "element", "=>", "element", ".", "label", "===", "'btc_anchor_branch'", ")", "btcAnchor", ".", "raw_btc_tx", "=", "btcBranch", ".", "rawTx", "// get the btc anchor", "let", "anchor", "=", "btcBranch", ".", "anchors", ".", "find", "(", "anchor", "=>", "anchor", ".", "type", "===", "'btc'", ")", "// add expected_value (i.e. the merkle root of anchored block)", "btcAnchor", ".", "expected_value", "=", "anchor", ".", "expected_value", "// add anchor_id (i.e. the anchored block height)", "btcAnchor", ".", "anchor_id", "=", "anchor", ".", "anchor_id", "}", "}", ")", "}", "flattenedBranches", ".", "push", "(", "btcAnchor", ")", "}", ")", "return", "flattenedBranches", "}" ]
Get raw btc transactions for each hash_id_node @param {Array} proofs - array of previously parsed proofs @return {Obect[]} - an array of objects with hash_id_node and raw btc tx
[ "Get", "raw", "btc", "transactions", "for", "each", "hash_id_node" ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L431-L462
16,816
chainpoint/chainpoint-client-js
index.js
_normalizeProofs
function _normalizeProofs(proofs) { // Validate proofs arg if (!_isArray(proofs)) throw new Error('proofs arg must be an Array') if (_isEmpty(proofs)) throw new Error('proofs arg must be a non-empty Array') // If any entry in the proofs Array is an Object, process // it assuming the same form as the output of getProofs(). return _map(proofs, proof => { if (_isObject(proof) && _has(proof, 'proof') && _isString(proof.proof)) { // Probably result of `submitProofs()` call. Extract proof String return proof.proof } else if ( _isObject(proof) && _has(proof, 'type') && proof.type === 'Chainpoint' ) { // Probably a JS Object Proof return proof } else if (_isString(proof) && (isJSON(proof) || isBase64(proof))) { // Probably a JSON String or Base64 encoded binary proof return proof } else { throw new Error( 'proofs arg Array has elements that are not Objects or Strings' ) } }) }
javascript
function _normalizeProofs(proofs) { // Validate proofs arg if (!_isArray(proofs)) throw new Error('proofs arg must be an Array') if (_isEmpty(proofs)) throw new Error('proofs arg must be a non-empty Array') // If any entry in the proofs Array is an Object, process // it assuming the same form as the output of getProofs(). return _map(proofs, proof => { if (_isObject(proof) && _has(proof, 'proof') && _isString(proof.proof)) { // Probably result of `submitProofs()` call. Extract proof String return proof.proof } else if ( _isObject(proof) && _has(proof, 'type') && proof.type === 'Chainpoint' ) { // Probably a JS Object Proof return proof } else if (_isString(proof) && (isJSON(proof) || isBase64(proof))) { // Probably a JSON String or Base64 encoded binary proof return proof } else { throw new Error( 'proofs arg Array has elements that are not Objects or Strings' ) } }) }
[ "function", "_normalizeProofs", "(", "proofs", ")", "{", "// Validate proofs arg", "if", "(", "!", "_isArray", "(", "proofs", ")", ")", "throw", "new", "Error", "(", "'proofs arg must be an Array'", ")", "if", "(", "_isEmpty", "(", "proofs", ")", ")", "throw", "new", "Error", "(", "'proofs arg must be a non-empty Array'", ")", "// If any entry in the proofs Array is an Object, process", "// it assuming the same form as the output of getProofs().", "return", "_map", "(", "proofs", ",", "proof", "=>", "{", "if", "(", "_isObject", "(", "proof", ")", "&&", "_has", "(", "proof", ",", "'proof'", ")", "&&", "_isString", "(", "proof", ".", "proof", ")", ")", "{", "// Probably result of `submitProofs()` call. Extract proof String", "return", "proof", ".", "proof", "}", "else", "if", "(", "_isObject", "(", "proof", ")", "&&", "_has", "(", "proof", ",", "'type'", ")", "&&", "proof", ".", "type", "===", "'Chainpoint'", ")", "{", "// Probably a JS Object Proof", "return", "proof", "}", "else", "if", "(", "_isString", "(", "proof", ")", "&&", "(", "isJSON", "(", "proof", ")", "||", "isBase64", "(", "proof", ")", ")", ")", "{", "// Probably a JSON String or Base64 encoded binary proof", "return", "proof", "}", "else", "{", "throw", "new", "Error", "(", "'proofs arg Array has elements that are not Objects or Strings'", ")", "}", "}", ")", "}" ]
validate and normalize proofs for actions such as parsing @param {Array} proofs - An Array of String, or Object proofs from getProofs(), to be verified. Proofs can be in any of the supported JSON-LD or Binary formats. @return {Array<Object>} - An Array of Objects, one for each proof submitted.
[ "validate", "and", "normalize", "proofs", "for", "actions", "such", "as", "parsing" ]
1c7541db69b0c78ee4b7fb475e644d65601cb8a5
https://github.com/chainpoint/chainpoint-client-js/blob/1c7541db69b0c78ee4b7fb475e644d65601cb8a5/index.js#L469-L496
16,817
biasmv/pv
js/foundation-5.4.7.min.js
function () { var sheet = Foundation.stylesheet; if (typeof this.rule_idx !== 'undefined') { sheet.deleteRule(this.rule_idx); sheet.deleteRule(this.rule_idx); delete this.rule_idx; } }
javascript
function () { var sheet = Foundation.stylesheet; if (typeof this.rule_idx !== 'undefined') { sheet.deleteRule(this.rule_idx); sheet.deleteRule(this.rule_idx); delete this.rule_idx; } }
[ "function", "(", ")", "{", "var", "sheet", "=", "Foundation", ".", "stylesheet", ";", "if", "(", "typeof", "this", ".", "rule_idx", "!==", "'undefined'", ")", "{", "sheet", ".", "deleteRule", "(", "this", ".", "rule_idx", ")", ";", "sheet", ".", "deleteRule", "(", "this", ".", "rule_idx", ")", ";", "delete", "this", ".", "rule_idx", ";", "}", "}" ]
Remove old dropdown rule index
[ "Remove", "old", "dropdown", "rule", "index" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/js/foundation-5.4.7.min.js#L2157-L2165
16,818
biasmv/pv
src/io.js
guessAtomElementFromName
function guessAtomElementFromName(fourLetterName) { if (fourLetterName[0] !== ' ') { var trimmed = fourLetterName.trim(); if (trimmed.length === 4) { // look for first character in range A-Z or a-z and use that // for the element. var i = 0; var charCode = trimmed.charCodeAt(i); while (i < 4 && (charCode < 65 || charCode > 122 || (charCode > 90 && charCode < 97))) { ++i; charCode = trimmed.charCodeAt(i); } return trimmed[i]; } // when first character is not empty and length is smaller than 4, // assume that it's either a heavy atom (CA, etc), or a hydrogen // name with a numeric prefix. That's not always correct, though. var firstCharCode = trimmed.charCodeAt(0); if (firstCharCode >= 48 && firstCharCode <= 57) { // numeric prefix, so it's a hydrogen return trimmed[1]; } return trimmed.substr(0, 2); } return fourLetterName[1]; }
javascript
function guessAtomElementFromName(fourLetterName) { if (fourLetterName[0] !== ' ') { var trimmed = fourLetterName.trim(); if (trimmed.length === 4) { // look for first character in range A-Z or a-z and use that // for the element. var i = 0; var charCode = trimmed.charCodeAt(i); while (i < 4 && (charCode < 65 || charCode > 122 || (charCode > 90 && charCode < 97))) { ++i; charCode = trimmed.charCodeAt(i); } return trimmed[i]; } // when first character is not empty and length is smaller than 4, // assume that it's either a heavy atom (CA, etc), or a hydrogen // name with a numeric prefix. That's not always correct, though. var firstCharCode = trimmed.charCodeAt(0); if (firstCharCode >= 48 && firstCharCode <= 57) { // numeric prefix, so it's a hydrogen return trimmed[1]; } return trimmed.substr(0, 2); } return fourLetterName[1]; }
[ "function", "guessAtomElementFromName", "(", "fourLetterName", ")", "{", "if", "(", "fourLetterName", "[", "0", "]", "!==", "' '", ")", "{", "var", "trimmed", "=", "fourLetterName", ".", "trim", "(", ")", ";", "if", "(", "trimmed", ".", "length", "===", "4", ")", "{", "// look for first character in range A-Z or a-z and use that ", "// for the element. ", "var", "i", "=", "0", ";", "var", "charCode", "=", "trimmed", ".", "charCodeAt", "(", "i", ")", ";", "while", "(", "i", "<", "4", "&&", "(", "charCode", "<", "65", "||", "charCode", ">", "122", "||", "(", "charCode", ">", "90", "&&", "charCode", "<", "97", ")", ")", ")", "{", "++", "i", ";", "charCode", "=", "trimmed", ".", "charCodeAt", "(", "i", ")", ";", "}", "return", "trimmed", "[", "i", "]", ";", "}", "// when first character is not empty and length is smaller than 4,", "// assume that it's either a heavy atom (CA, etc), or a hydrogen ", "// name with a numeric prefix. That's not always correct, though.", "var", "firstCharCode", "=", "trimmed", ".", "charCodeAt", "(", "0", ")", ";", "if", "(", "firstCharCode", ">=", "48", "&&", "firstCharCode", "<=", "57", ")", "{", "// numeric prefix, so it's a hydrogen", "return", "trimmed", "[", "1", "]", ";", "}", "return", "trimmed", ".", "substr", "(", "0", ",", "2", ")", ";", "}", "return", "fourLetterName", "[", "1", "]", ";", "}" ]
Very simple heuristic to determine the element from the atom name. This at the very least assume that people have the decency to follow the standard naming conventions for atom names when they are too lazy to write down elements
[ "Very", "simple", "heuristic", "to", "determine", "the", "element", "from", "the", "atom", "name", ".", "This", "at", "the", "very", "least", "assume", "that", "people", "have", "the", "decency", "to", "follow", "the", "standard", "naming", "conventions", "for", "atom", "names", "when", "they", "are", "too", "lazy", "to", "write", "down", "elements" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/io.js#L116-L142
16,819
biasmv/pv
src/mol/chain.js
function(fromNumAndIns, toNumAndIns, ss) { // FIXME: when the chain numbers are completely ordered, perform binary // search to identify range of residues to assign secondary structure to. var from = rnumInsCodeHash(fromNumAndIns[0], fromNumAndIns[1]); var to = rnumInsCodeHash(toNumAndIns[0], toNumAndIns[1]); for (var i = 1; i < this._residues.length-1; ++i) { var res = this._residues[i]; // FIXME: we currently don't set the secondary structure of the last // residue of helices and sheets. that takes care of better transitions // between coils and helices. ideally, this should be done in the // cartoon renderer, NOT in this function. var combined = rnumInsCodeHash(res.num(), res.insCode()); if (combined < from || combined >= to) { continue; } res.setSS(ss); } }
javascript
function(fromNumAndIns, toNumAndIns, ss) { // FIXME: when the chain numbers are completely ordered, perform binary // search to identify range of residues to assign secondary structure to. var from = rnumInsCodeHash(fromNumAndIns[0], fromNumAndIns[1]); var to = rnumInsCodeHash(toNumAndIns[0], toNumAndIns[1]); for (var i = 1; i < this._residues.length-1; ++i) { var res = this._residues[i]; // FIXME: we currently don't set the secondary structure of the last // residue of helices and sheets. that takes care of better transitions // between coils and helices. ideally, this should be done in the // cartoon renderer, NOT in this function. var combined = rnumInsCodeHash(res.num(), res.insCode()); if (combined < from || combined >= to) { continue; } res.setSS(ss); } }
[ "function", "(", "fromNumAndIns", ",", "toNumAndIns", ",", "ss", ")", "{", "// FIXME: when the chain numbers are completely ordered, perform binary ", "// search to identify range of residues to assign secondary structure to.", "var", "from", "=", "rnumInsCodeHash", "(", "fromNumAndIns", "[", "0", "]", ",", "fromNumAndIns", "[", "1", "]", ")", ";", "var", "to", "=", "rnumInsCodeHash", "(", "toNumAndIns", "[", "0", "]", ",", "toNumAndIns", "[", "1", "]", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "this", ".", "_residues", ".", "length", "-", "1", ";", "++", "i", ")", "{", "var", "res", "=", "this", ".", "_residues", "[", "i", "]", ";", "// FIXME: we currently don't set the secondary structure of the last ", "// residue of helices and sheets. that takes care of better transitions ", "// between coils and helices. ideally, this should be done in the ", "// cartoon renderer, NOT in this function.", "var", "combined", "=", "rnumInsCodeHash", "(", "res", ".", "num", "(", ")", ",", "res", ".", "insCode", "(", ")", ")", ";", "if", "(", "combined", "<", "from", "||", "combined", ">=", "to", ")", "{", "continue", ";", "}", "res", ".", "setSS", "(", "ss", ")", ";", "}", "}" ]
assigns secondary structure to residues in range from_num to to_num.
[ "assigns", "secondary", "structure", "to", "residues", "in", "range", "from_num", "to", "to_num", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/chain.js#L231-L248
16,820
biasmv/pv
src/gfx/base-geom.js
function(chains) { var vertArrays = this.vertArrays(); var selectedArrays = []; var set = {}; for (var ci = 0; ci < chains.length; ++ci) { set[chains[ci]] = true; } for (var i = 0; i < vertArrays.length; ++i) { if (set[vertArrays[i].chain()] === true) { selectedArrays.push(vertArrays[i]); } } return selectedArrays; }
javascript
function(chains) { var vertArrays = this.vertArrays(); var selectedArrays = []; var set = {}; for (var ci = 0; ci < chains.length; ++ci) { set[chains[ci]] = true; } for (var i = 0; i < vertArrays.length; ++i) { if (set[vertArrays[i].chain()] === true) { selectedArrays.push(vertArrays[i]); } } return selectedArrays; }
[ "function", "(", "chains", ")", "{", "var", "vertArrays", "=", "this", ".", "vertArrays", "(", ")", ";", "var", "selectedArrays", "=", "[", "]", ";", "var", "set", "=", "{", "}", ";", "for", "(", "var", "ci", "=", "0", ";", "ci", "<", "chains", ".", "length", ";", "++", "ci", ")", "{", "set", "[", "chains", "[", "ci", "]", "]", "=", "true", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "vertArrays", ".", "length", ";", "++", "i", ")", "{", "if", "(", "set", "[", "vertArrays", "[", "i", "]", ".", "chain", "(", ")", "]", "===", "true", ")", "{", "selectedArrays", ".", "push", "(", "vertArrays", "[", "i", "]", ")", ";", "}", "}", "return", "selectedArrays", ";", "}" ]
returns all vertex arrays that contain geometry for one of the specified chain names. Typically, there will only be one array for a given chain, but for larger chains with mesh geometries a single chain may be split across multiple vertex arrays.
[ "returns", "all", "vertex", "arrays", "that", "contain", "geometry", "for", "one", "of", "the", "specified", "chain", "names", ".", "Typically", "there", "will", "only", "be", "one", "array", "for", "a", "given", "chain", "but", "for", "larger", "chains", "with", "mesh", "geometries", "a", "single", "chain", "may", "be", "split", "across", "multiple", "vertex", "arrays", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/base-geom.js#L158-L171
16,821
biasmv/pv
src/gfx/base-geom.js
function(cam, shader, assembly) { var gens = assembly.generators(); for (var i = 0; i < gens.length; ++i) { var gen = gens[i]; var affectedVAs = this._vertArraysInvolving(gen.chains()); this._drawVertArrays(cam, shader, affectedVAs, gen.matrices()); } }
javascript
function(cam, shader, assembly) { var gens = assembly.generators(); for (var i = 0; i < gens.length; ++i) { var gen = gens[i]; var affectedVAs = this._vertArraysInvolving(gen.chains()); this._drawVertArrays(cam, shader, affectedVAs, gen.matrices()); } }
[ "function", "(", "cam", ",", "shader", ",", "assembly", ")", "{", "var", "gens", "=", "assembly", ".", "generators", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "gens", ".", "length", ";", "++", "i", ")", "{", "var", "gen", "=", "gens", "[", "i", "]", ";", "var", "affectedVAs", "=", "this", ".", "_vertArraysInvolving", "(", "gen", ".", "chains", "(", ")", ")", ";", "this", ".", "_drawVertArrays", "(", "cam", ",", "shader", ",", "affectedVAs", ",", "gen", ".", "matrices", "(", ")", ")", ";", "}", "}" ]
draws vertex arrays by using the symmetry generators contained in assembly
[ "draws", "vertex", "arrays", "by", "using", "the", "symmetry", "generators", "contained", "in", "assembly" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/base-geom.js#L175-L182
16,822
biasmv/pv
src/mol/bond.js
function(out) { if (!out) { out = vec3.create(); } vec3.add(out, self.atom_one.pos(), self.atom_two.pos()); vec3.scale(out, out, 0.5); return out; }
javascript
function(out) { if (!out) { out = vec3.create(); } vec3.add(out, self.atom_one.pos(), self.atom_two.pos()); vec3.scale(out, out, 0.5); return out; }
[ "function", "(", "out", ")", "{", "if", "(", "!", "out", ")", "{", "out", "=", "vec3", ".", "create", "(", ")", ";", "}", "vec3", ".", "add", "(", "out", ",", "self", ".", "atom_one", ".", "pos", "(", ")", ",", "self", ".", "atom_two", ".", "pos", "(", ")", ")", ";", "vec3", ".", "scale", "(", "out", ",", "out", ",", "0.5", ")", ";", "return", "out", ";", "}" ]
calculates the mid-point between the two atom positions
[ "calculates", "the", "mid", "-", "point", "between", "the", "two", "atom", "positions" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/bond.js#L37-L44
16,823
biasmv/pv
src/gfx/cam.js
Cam
function Cam(gl) { this._projection = mat4.create(); this._camModelView = mat4.create(); this._modelView = mat4.create(); this._rotation = mat4.create(); this._translation = mat4.create(); this._near = 0.10; this._onCameraChangedListeners = []; this._far = 4000.0; this._fogNear = -5; this._fogFar = 50; this._fog = true; this._fovY = Math.PI * 45.0 / 180.0; this._fogColor = vec3.fromValues(1, 1, 1); this._outlineColor = vec3.fromValues(0.1, 0.1, 0.1); this._outlineWidth = 1.0; this._outlineEnabled = true; this._selectionColor = vec4.fromValues(0.1, 1.0, 0.1, 0.7); this._center = vec3.create(); this._zoom = 50; this._screenDoorTransparency = false; this._updateProjectionMat = true; this._updateModelViewMat = true; this._upsamplingFactor = 1; this._gl = gl; this._currentShader = null; this._stateId = 0; this.setViewportSize(gl.viewportWidth, gl.viewportHeight); }
javascript
function Cam(gl) { this._projection = mat4.create(); this._camModelView = mat4.create(); this._modelView = mat4.create(); this._rotation = mat4.create(); this._translation = mat4.create(); this._near = 0.10; this._onCameraChangedListeners = []; this._far = 4000.0; this._fogNear = -5; this._fogFar = 50; this._fog = true; this._fovY = Math.PI * 45.0 / 180.0; this._fogColor = vec3.fromValues(1, 1, 1); this._outlineColor = vec3.fromValues(0.1, 0.1, 0.1); this._outlineWidth = 1.0; this._outlineEnabled = true; this._selectionColor = vec4.fromValues(0.1, 1.0, 0.1, 0.7); this._center = vec3.create(); this._zoom = 50; this._screenDoorTransparency = false; this._updateProjectionMat = true; this._updateModelViewMat = true; this._upsamplingFactor = 1; this._gl = gl; this._currentShader = null; this._stateId = 0; this.setViewportSize(gl.viewportWidth, gl.viewportHeight); }
[ "function", "Cam", "(", "gl", ")", "{", "this", ".", "_projection", "=", "mat4", ".", "create", "(", ")", ";", "this", ".", "_camModelView", "=", "mat4", ".", "create", "(", ")", ";", "this", ".", "_modelView", "=", "mat4", ".", "create", "(", ")", ";", "this", ".", "_rotation", "=", "mat4", ".", "create", "(", ")", ";", "this", ".", "_translation", "=", "mat4", ".", "create", "(", ")", ";", "this", ".", "_near", "=", "0.10", ";", "this", ".", "_onCameraChangedListeners", "=", "[", "]", ";", "this", ".", "_far", "=", "4000.0", ";", "this", ".", "_fogNear", "=", "-", "5", ";", "this", ".", "_fogFar", "=", "50", ";", "this", ".", "_fog", "=", "true", ";", "this", ".", "_fovY", "=", "Math", ".", "PI", "*", "45.0", "/", "180.0", ";", "this", ".", "_fogColor", "=", "vec3", ".", "fromValues", "(", "1", ",", "1", ",", "1", ")", ";", "this", ".", "_outlineColor", "=", "vec3", ".", "fromValues", "(", "0.1", ",", "0.1", ",", "0.1", ")", ";", "this", ".", "_outlineWidth", "=", "1.0", ";", "this", ".", "_outlineEnabled", "=", "true", ";", "this", ".", "_selectionColor", "=", "vec4", ".", "fromValues", "(", "0.1", ",", "1.0", ",", "0.1", ",", "0.7", ")", ";", "this", ".", "_center", "=", "vec3", ".", "create", "(", ")", ";", "this", ".", "_zoom", "=", "50", ";", "this", ".", "_screenDoorTransparency", "=", "false", ";", "this", ".", "_updateProjectionMat", "=", "true", ";", "this", ".", "_updateModelViewMat", "=", "true", ";", "this", ".", "_upsamplingFactor", "=", "1", ";", "this", ".", "_gl", "=", "gl", ";", "this", ".", "_currentShader", "=", "null", ";", "this", ".", "_stateId", "=", "0", ";", "this", ".", "setViewportSize", "(", "gl", ".", "viewportWidth", ",", "gl", ".", "viewportHeight", ")", ";", "}" ]
A camera, providing us with a view into the 3D worlds. Handles projection, and modelview matrices and controls the global render parameters such as shader and fog.
[ "A", "camera", "providing", "us", "with", "a", "view", "into", "the", "3D", "worlds", ".", "Handles", "projection", "and", "modelview", "matrices", "and", "controls", "the", "global", "render", "parameters", "such", "as", "shader", "and", "fog", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/cam.js#L49-L77
16,824
biasmv/pv
src/gfx/cam.js
function() { return[ vec3.fromValues(this._rotation[0], this._rotation[4], this._rotation[8]), vec3.fromValues(this._rotation[1], this._rotation[5], this._rotation[9]), vec3.fromValues(this._rotation[2], this._rotation[6], this._rotation[10]) ]; }
javascript
function() { return[ vec3.fromValues(this._rotation[0], this._rotation[4], this._rotation[8]), vec3.fromValues(this._rotation[1], this._rotation[5], this._rotation[9]), vec3.fromValues(this._rotation[2], this._rotation[6], this._rotation[10]) ]; }
[ "function", "(", ")", "{", "return", "[", "vec3", ".", "fromValues", "(", "this", ".", "_rotation", "[", "0", "]", ",", "this", ".", "_rotation", "[", "4", "]", ",", "this", ".", "_rotation", "[", "8", "]", ")", ",", "vec3", ".", "fromValues", "(", "this", ".", "_rotation", "[", "1", "]", ",", "this", ".", "_rotation", "[", "5", "]", ",", "this", ".", "_rotation", "[", "9", "]", ")", ",", "vec3", ".", "fromValues", "(", "this", ".", "_rotation", "[", "2", "]", ",", "this", ".", "_rotation", "[", "6", "]", ",", "this", ".", "_rotation", "[", "10", "]", ")", "]", ";", "}" ]
returns the 3 main axes of the current camera rotation
[ "returns", "the", "3", "main", "axes", "of", "the", "current", "camera", "rotation" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/cam.js#L140-L146
16,825
biasmv/pv
src/gfx/render.js
function(traces, vertsPerSlice, splineDetail) { var numVerts = 0; for (var i = 0; i < traces.length; ++i) { var traceVerts = ((traces[i].length() - 1) * splineDetail + 1) * vertsPerSlice; // in case there are more than 2^16 vertices for a single trace, we // need to manually split the trace in two and duplicate one of the // trace slices. Let's make room for some additional space... var splits = Math.ceil((traceVerts + 2)/65536); numVerts += traceVerts + (splits - 1) * vertsPerSlice; // triangles for capping the tube numVerts += 2; } return numVerts; }
javascript
function(traces, vertsPerSlice, splineDetail) { var numVerts = 0; for (var i = 0; i < traces.length; ++i) { var traceVerts = ((traces[i].length() - 1) * splineDetail + 1) * vertsPerSlice; // in case there are more than 2^16 vertices for a single trace, we // need to manually split the trace in two and duplicate one of the // trace slices. Let's make room for some additional space... var splits = Math.ceil((traceVerts + 2)/65536); numVerts += traceVerts + (splits - 1) * vertsPerSlice; // triangles for capping the tube numVerts += 2; } return numVerts; }
[ "function", "(", "traces", ",", "vertsPerSlice", ",", "splineDetail", ")", "{", "var", "numVerts", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "traces", ".", "length", ";", "++", "i", ")", "{", "var", "traceVerts", "=", "(", "(", "traces", "[", "i", "]", ".", "length", "(", ")", "-", "1", ")", "*", "splineDetail", "+", "1", ")", "*", "vertsPerSlice", ";", "// in case there are more than 2^16 vertices for a single trace, we", "// need to manually split the trace in two and duplicate one of the", "// trace slices. Let's make room for some additional space...", "var", "splits", "=", "Math", ".", "ceil", "(", "(", "traceVerts", "+", "2", ")", "/", "65536", ")", ";", "numVerts", "+=", "traceVerts", "+", "(", "splits", "-", "1", ")", "*", "vertsPerSlice", ";", "// triangles for capping the tube", "numVerts", "+=", "2", ";", "}", "return", "numVerts", ";", "}" ]
calculates the number of vertices required for the cartoon and tube render styles
[ "calculates", "the", "number", "of", "vertices", "required", "for", "the", "cartoon", "and", "tube", "render", "styles" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/render.js#L668-L682
16,826
biasmv/pv
src/geom.js
function(out, axis, angle) { var sa = Math.sin(angle), ca = Math.cos(angle), x = axis[0], y = axis[1], z = axis[2], xx = x * x, xy = x * y, xz = x * z, yy = y * y, yz = y * z, zz = z * z; out[0] = xx + ca - xx * ca; out[1] = xy - ca * xy - sa * z; out[2] = xz - ca * xz + sa * y; out[3] = xy - ca * xy + sa * z; out[4] = yy + ca - ca * yy; out[5] = yz - ca * yz - sa * x; out[6] = xz - ca * xz - sa * y; out[7] = yz - ca * yz + sa * x; out[8] = zz + ca - ca * zz; return out; }
javascript
function(out, axis, angle) { var sa = Math.sin(angle), ca = Math.cos(angle), x = axis[0], y = axis[1], z = axis[2], xx = x * x, xy = x * y, xz = x * z, yy = y * y, yz = y * z, zz = z * z; out[0] = xx + ca - xx * ca; out[1] = xy - ca * xy - sa * z; out[2] = xz - ca * xz + sa * y; out[3] = xy - ca * xy + sa * z; out[4] = yy + ca - ca * yy; out[5] = yz - ca * yz - sa * x; out[6] = xz - ca * xz - sa * y; out[7] = yz - ca * yz + sa * x; out[8] = zz + ca - ca * zz; return out; }
[ "function", "(", "out", ",", "axis", ",", "angle", ")", "{", "var", "sa", "=", "Math", ".", "sin", "(", "angle", ")", ",", "ca", "=", "Math", ".", "cos", "(", "angle", ")", ",", "x", "=", "axis", "[", "0", "]", ",", "y", "=", "axis", "[", "1", "]", ",", "z", "=", "axis", "[", "2", "]", ",", "xx", "=", "x", "*", "x", ",", "xy", "=", "x", "*", "y", ",", "xz", "=", "x", "*", "z", ",", "yy", "=", "y", "*", "y", ",", "yz", "=", "y", "*", "z", ",", "zz", "=", "z", "*", "z", ";", "out", "[", "0", "]", "=", "xx", "+", "ca", "-", "xx", "*", "ca", ";", "out", "[", "1", "]", "=", "xy", "-", "ca", "*", "xy", "-", "sa", "*", "z", ";", "out", "[", "2", "]", "=", "xz", "-", "ca", "*", "xz", "+", "sa", "*", "y", ";", "out", "[", "3", "]", "=", "xy", "-", "ca", "*", "xy", "+", "sa", "*", "z", ";", "out", "[", "4", "]", "=", "yy", "+", "ca", "-", "ca", "*", "yy", ";", "out", "[", "5", "]", "=", "yz", "-", "ca", "*", "yz", "-", "sa", "*", "x", ";", "out", "[", "6", "]", "=", "xz", "-", "ca", "*", "xz", "-", "sa", "*", "y", ";", "out", "[", "7", "]", "=", "yz", "-", "ca", "*", "yz", "+", "sa", "*", "x", ";", "out", "[", "8", "]", "=", "zz", "+", "ca", "-", "ca", "*", "zz", ";", "return", "out", ";", "}" ]
assumes that axis is normalized. don't expect to get meaningful results when it's not
[ "assumes", "that", "axis", "is", "normalized", ".", "don", "t", "expect", "to", "get", "meaningful", "results", "when", "it", "s", "not" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/geom.js#L63-L78
16,827
biasmv/pv
src/geom.js
interpolateScalars
function interpolateScalars(values, num) { var out = new Float32Array(num*(values.length-1) + 1); var index = 0; var bf = 0.0, af = 0.0; var delta = 1/num; for (var i = 0; i < values.length-1; ++i) { bf = values[i]; af = values[i + 1]; for (var j = 0; j < num; ++j) { var t = delta * j; out[index+0] = bf*(1-t)+af*t; index+=1; } } out[index+0] = af; return out; }
javascript
function interpolateScalars(values, num) { var out = new Float32Array(num*(values.length-1) + 1); var index = 0; var bf = 0.0, af = 0.0; var delta = 1/num; for (var i = 0; i < values.length-1; ++i) { bf = values[i]; af = values[i + 1]; for (var j = 0; j < num; ++j) { var t = delta * j; out[index+0] = bf*(1-t)+af*t; index+=1; } } out[index+0] = af; return out; }
[ "function", "interpolateScalars", "(", "values", ",", "num", ")", "{", "var", "out", "=", "new", "Float32Array", "(", "num", "*", "(", "values", ".", "length", "-", "1", ")", "+", "1", ")", ";", "var", "index", "=", "0", ";", "var", "bf", "=", "0.0", ",", "af", "=", "0.0", ";", "var", "delta", "=", "1", "/", "num", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "values", ".", "length", "-", "1", ";", "++", "i", ")", "{", "bf", "=", "values", "[", "i", "]", ";", "af", "=", "values", "[", "i", "+", "1", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "num", ";", "++", "j", ")", "{", "var", "t", "=", "delta", "*", "j", ";", "out", "[", "index", "+", "0", "]", "=", "bf", "*", "(", "1", "-", "t", ")", "+", "af", "*", "t", ";", "index", "+=", "1", ";", "}", "}", "out", "[", "index", "+", "0", "]", "=", "af", ";", "return", "out", ";", "}" ]
linearly interpolates the array of values and returns it as an Float32Array
[ "linearly", "interpolates", "the", "array", "of", "values", "and", "returns", "it", "as", "an", "Float32Array" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/geom.js#L284-L300
16,828
biasmv/pv
src/unique-object-id-pool.js
ContinuousIdRange
function ContinuousIdRange(pool, start, end) { this._pool = pool; this._start = start; this._next = start; this._end = end; }
javascript
function ContinuousIdRange(pool, start, end) { this._pool = pool; this._start = start; this._next = start; this._end = end; }
[ "function", "ContinuousIdRange", "(", "pool", ",", "start", ",", "end", ")", "{", "this", ".", "_pool", "=", "pool", ";", "this", ".", "_start", "=", "start", ";", "this", ".", "_next", "=", "start", ";", "this", ".", "_end", "=", "end", ";", "}" ]
A continous range of object identifiers.
[ "A", "continous", "range", "of", "object", "identifiers", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/unique-object-id-pool.js#L26-L31
16,829
biasmv/pv
src/viewer.js
function() { if (!this._resize) { return; } this._resize = false; this._cam.setViewportSize(this._canvas.viewportWidth(), this._canvas.viewportHeight()); this._pickBuffer.resize(this._options.width, this._options.height); }
javascript
function() { if (!this._resize) { return; } this._resize = false; this._cam.setViewportSize(this._canvas.viewportWidth(), this._canvas.viewportHeight()); this._pickBuffer.resize(this._options.width, this._options.height); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "_resize", ")", "{", "return", ";", "}", "this", ".", "_resize", "=", "false", ";", "this", ".", "_cam", ".", "setViewportSize", "(", "this", ".", "_canvas", ".", "viewportWidth", "(", ")", ",", "this", ".", "_canvas", ".", "viewportHeight", "(", ")", ")", ";", "this", ".", "_pickBuffer", ".", "resize", "(", "this", ".", "_options", ".", "width", ",", "this", ".", "_options", ".", "height", ")", ";", "}" ]
with rendering to avoid flickering.
[ "with", "rendering", "to", "avoid", "flickering", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/viewer.js#L295-L303
16,830
biasmv/pv
src/viewer.js
function(name, structure, opts) { opts = opts || {}; opts.forceTube = true; return this.cartoon(name, structure, opts); }
javascript
function(name, structure, opts) { opts = opts || {}; opts.forceTube = true; return this.cartoon(name, structure, opts); }
[ "function", "(", "name", ",", "structure", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "opts", ".", "forceTube", "=", "true", ";", "return", "this", ".", "cartoon", "(", "name", ",", "structure", ",", "opts", ")", ";", "}" ]
renders the protein using a smoothly interpolated tube, essentially identical to the cartoon render mode, but without special treatment for helices and strands.
[ "renders", "the", "protein", "using", "a", "smoothly", "interpolated", "tube", "essentially", "identical", "to", "the", "cartoon", "render", "mode", "but", "without", "special", "treatment", "for", "helices", "and", "strands", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/viewer.js#L833-L837
16,831
biasmv/pv
src/viewer.js
function(ms) { var axes = this._cam.mainAxes(); var intervals = [ new utils.Range(), new utils.Range(), new utils.Range() ]; this.forEach(function(obj) { if (!obj.visible()) { return; } obj.updateProjectionIntervals(axes[0], axes[1], axes[2], intervals[0], intervals[1], intervals[2]); }); this._fitToIntervals(axes, intervals, ms); }
javascript
function(ms) { var axes = this._cam.mainAxes(); var intervals = [ new utils.Range(), new utils.Range(), new utils.Range() ]; this.forEach(function(obj) { if (!obj.visible()) { return; } obj.updateProjectionIntervals(axes[0], axes[1], axes[2], intervals[0], intervals[1], intervals[2]); }); this._fitToIntervals(axes, intervals, ms); }
[ "function", "(", "ms", ")", "{", "var", "axes", "=", "this", ".", "_cam", ".", "mainAxes", "(", ")", ";", "var", "intervals", "=", "[", "new", "utils", ".", "Range", "(", ")", ",", "new", "utils", ".", "Range", "(", ")", ",", "new", "utils", ".", "Range", "(", ")", "]", ";", "this", ".", "forEach", "(", "function", "(", "obj", ")", "{", "if", "(", "!", "obj", ".", "visible", "(", ")", ")", "{", "return", ";", "}", "obj", ".", "updateProjectionIntervals", "(", "axes", "[", "0", "]", ",", "axes", "[", "1", "]", ",", "axes", "[", "2", "]", ",", "intervals", "[", "0", "]", ",", "intervals", "[", "1", "]", ",", "intervals", "[", "2", "]", ")", ";", "}", ")", ";", "this", ".", "_fitToIntervals", "(", "axes", ",", "intervals", ",", "ms", ")", ";", "}" ]
adapt the zoom level to fit the viewport to all visible objects.
[ "adapt", "the", "zoom", "level", "to", "fit", "the", "viewport", "to", "all", "visible", "objects", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/viewer.js#L939-L950
16,832
biasmv/pv
src/viewer.js
function(enable) { if (enable === undefined) { return this._rockAndRoll !== null; } if (!!enable) { if (this._rockAndRoll === null) { this._rockAndRoll = anim.rockAndRoll(); this._animControl.add(this._rockAndRoll); this.requestRedraw(); } return true; } this._animControl.remove(this._rockAndRoll); this._rockAndRoll = null; this.requestRedraw(); return false; }
javascript
function(enable) { if (enable === undefined) { return this._rockAndRoll !== null; } if (!!enable) { if (this._rockAndRoll === null) { this._rockAndRoll = anim.rockAndRoll(); this._animControl.add(this._rockAndRoll); this.requestRedraw(); } return true; } this._animControl.remove(this._rockAndRoll); this._rockAndRoll = null; this.requestRedraw(); return false; }
[ "function", "(", "enable", ")", "{", "if", "(", "enable", "===", "undefined", ")", "{", "return", "this", ".", "_rockAndRoll", "!==", "null", ";", "}", "if", "(", "!", "!", "enable", ")", "{", "if", "(", "this", ".", "_rockAndRoll", "===", "null", ")", "{", "this", ".", "_rockAndRoll", "=", "anim", ".", "rockAndRoll", "(", ")", ";", "this", ".", "_animControl", ".", "add", "(", "this", ".", "_rockAndRoll", ")", ";", "this", ".", "requestRedraw", "(", ")", ";", "}", "return", "true", ";", "}", "this", ".", "_animControl", ".", "remove", "(", "this", ".", "_rockAndRoll", ")", ";", "this", ".", "_rockAndRoll", "=", "null", ";", "this", ".", "requestRedraw", "(", ")", ";", "return", "false", ";", "}" ]
enable disable rock and rolling of camera
[ "enable", "disable", "rock", "and", "rolling", "of", "camera" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/viewer.js#L964-L980
16,833
biasmv/pv
src/viewer.js
function(glob) { var newObjects = []; var regex = this._globToRegex(glob); for (var i = 0; i < this._objects.length; ++i) { var obj = this._objects[i]; if (!regex.test(obj.name())) { newObjects.push(obj); } else { obj.destroy(); } } this._objects = newObjects; }
javascript
function(glob) { var newObjects = []; var regex = this._globToRegex(glob); for (var i = 0; i < this._objects.length; ++i) { var obj = this._objects[i]; if (!regex.test(obj.name())) { newObjects.push(obj); } else { obj.destroy(); } } this._objects = newObjects; }
[ "function", "(", "glob", ")", "{", "var", "newObjects", "=", "[", "]", ";", "var", "regex", "=", "this", ".", "_globToRegex", "(", "glob", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "_objects", ".", "length", ";", "++", "i", ")", "{", "var", "obj", "=", "this", ".", "_objects", "[", "i", "]", ";", "if", "(", "!", "regex", ".", "test", "(", "obj", ".", "name", "(", ")", ")", ")", "{", "newObjects", ".", "push", "(", "obj", ")", ";", "}", "else", "{", "obj", ".", "destroy", "(", ")", ";", "}", "}", "this", ".", "_objects", "=", "newObjects", ";", "}" ]
remove all objects whose names match the provided glob pattern from the viewer.
[ "remove", "all", "objects", "whose", "names", "match", "the", "provided", "glob", "pattern", "from", "the", "viewer", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/viewer.js#L1154-L1166
16,834
biasmv/pv
src/gfx/chain-data.js
LineChainData
function LineChainData(chain, gl, numVerts, float32Allocator) { VertexArray.call(this, gl, numVerts, float32Allocator); this._chain = chain; }
javascript
function LineChainData(chain, gl, numVerts, float32Allocator) { VertexArray.call(this, gl, numVerts, float32Allocator); this._chain = chain; }
[ "function", "LineChainData", "(", "chain", ",", "gl", ",", "numVerts", ",", "float32Allocator", ")", "{", "VertexArray", ".", "call", "(", "this", ",", "gl", ",", "numVerts", ",", "float32Allocator", ")", ";", "this", ".", "_chain", "=", "chain", ";", "}" ]
LineChainData and MeshChainData are two internal classes that add molecule- specific attributes and functionality to the IndexedVertexArray and VertexArray classes.
[ "LineChainData", "and", "MeshChainData", "are", "two", "internal", "classes", "that", "add", "molecule", "-", "specific", "attributes", "and", "functionality", "to", "the", "IndexedVertexArray", "and", "VertexArray", "classes", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/chain-data.js#L37-L40
16,835
biasmv/pv
src/gfx/animation.js
function(camera) { var time = Date.now(); this._animations = this._animations.filter(function(anim) { return !anim.step(camera, time); }); return this._animations.length > 0; }
javascript
function(camera) { var time = Date.now(); this._animations = this._animations.filter(function(anim) { return !anim.step(camera, time); }); return this._animations.length > 0; }
[ "function", "(", "camera", ")", "{", "var", "time", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "_animations", "=", "this", ".", "_animations", ".", "filter", "(", "function", "(", "anim", ")", "{", "return", "!", "anim", ".", "step", "(", "camera", ",", "time", ")", ";", "}", ")", ";", "return", "this", ".", "_animations", ".", "length", ">", "0", ";", "}" ]
apply all currently active animations to the camera returns true if there are pending animations.
[ "apply", "all", "currently", "active", "animations", "to", "the", "camera", "returns", "true", "if", "there", "are", "pending", "animations", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/animation.js#L186-L192
16,836
biasmv/pv
src/gfx/canvas.js
function(width, height) { if (width === this._width && height === this._height) { return; } this._resize = true; this._width = width; this._height = height; }
javascript
function(width, height) { if (width === this._width && height === this._height) { return; } this._resize = true; this._width = width; this._height = height; }
[ "function", "(", "width", ",", "height", ")", "{", "if", "(", "width", "===", "this", ".", "_width", "&&", "height", "===", "this", ".", "_height", ")", "{", "return", ";", "}", "this", ".", "_resize", "=", "true", ";", "this", ".", "_width", "=", "width", ";", "this", ".", "_height", "=", "height", ";", "}" ]
tells the canvas to resize. The resize does not happen immediately but is delayed until the next redraw. This avoids flickering
[ "tells", "the", "canvas", "to", "resize", ".", "The", "resize", "does", "not", "happen", "immediately", "but", "is", "delayed", "until", "the", "next", "redraw", ".", "This", "avoids", "flickering" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/canvas.js#L84-L91
16,837
biasmv/pv
src/gfx/line-geom.js
LineGeom
function LineGeom(gl, float32Allocator) { BaseGeom.call(this, gl); this._vertArrays = []; this._float32Allocator = float32Allocator; this._lineWidth = 0.5; this._pointSize = 1.0; }
javascript
function LineGeom(gl, float32Allocator) { BaseGeom.call(this, gl); this._vertArrays = []; this._float32Allocator = float32Allocator; this._lineWidth = 0.5; this._pointSize = 1.0; }
[ "function", "LineGeom", "(", "gl", ",", "float32Allocator", ")", "{", "BaseGeom", ".", "call", "(", "this", ",", "gl", ")", ";", "this", ".", "_vertArrays", "=", "[", "]", ";", "this", ".", "_float32Allocator", "=", "float32Allocator", ";", "this", ".", "_lineWidth", "=", "0.5", ";", "this", ".", "_pointSize", "=", "1.0", ";", "}" ]
Holds geometrical data for objects rendered as lines. For each vertex, the color and position is stored in an interleaved format.
[ "Holds", "geometrical", "data", "for", "objects", "rendered", "as", "lines", ".", "For", "each", "vertex", "the", "color", "and", "position", "is", "stored", "in", "an", "interleaved", "format", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/line-geom.js#L38-L44
16,838
biasmv/pv
src/gfx/vert-assoc.js
TraceVertexAssoc
function TraceVertexAssoc(structure, interpolation, callColoringBeginEnd) { this._structure = structure; this._assocs = []; this._callBeginEnd = callColoringBeginEnd; this._interpolation = interpolation || 1; this._perResidueColors = {}; }
javascript
function TraceVertexAssoc(structure, interpolation, callColoringBeginEnd) { this._structure = structure; this._assocs = []; this._callBeginEnd = callColoringBeginEnd; this._interpolation = interpolation || 1; this._perResidueColors = {}; }
[ "function", "TraceVertexAssoc", "(", "structure", ",", "interpolation", ",", "callColoringBeginEnd", ")", "{", "this", ".", "_structure", "=", "structure", ";", "this", ".", "_assocs", "=", "[", "]", ";", "this", ".", "_callBeginEnd", "=", "callColoringBeginEnd", ";", "this", ".", "_interpolation", "=", "interpolation", "||", "1", ";", "this", ".", "_perResidueColors", "=", "{", "}", ";", "}" ]
handles the association between a trace element, and sets of vertices.
[ "handles", "the", "association", "between", "a", "trace", "element", "and", "sets", "of", "vertices", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/gfx/vert-assoc.js#L135-L141
16,839
biasmv/pv
src/mol/mol.js
function() { var center = this.center(); var radiusSquare = 0.0; this.eachAtom(function(atom) { radiusSquare = Math.max(radiusSquare, vec3.sqrDist(center, atom.pos())); }); return new geom.Sphere(center, Math.sqrt(radiusSquare)); }
javascript
function() { var center = this.center(); var radiusSquare = 0.0; this.eachAtom(function(atom) { radiusSquare = Math.max(radiusSquare, vec3.sqrDist(center, atom.pos())); }); return new geom.Sphere(center, Math.sqrt(radiusSquare)); }
[ "function", "(", ")", "{", "var", "center", "=", "this", ".", "center", "(", ")", ";", "var", "radiusSquare", "=", "0.0", ";", "this", ".", "eachAtom", "(", "function", "(", "atom", ")", "{", "radiusSquare", "=", "Math", ".", "max", "(", "radiusSquare", ",", "vec3", ".", "sqrDist", "(", "center", ",", "atom", ".", "pos", "(", ")", ")", ")", ";", "}", ")", ";", "return", "new", "geom", ".", "Sphere", "(", "center", ",", "Math", ".", "sqrt", "(", "radiusSquare", ")", ")", ";", "}" ]
returns a sphere containing all atoms part of this structure. This will not calculate the minimal bounding sphere, just a good-enough approximation.
[ "returns", "a", "sphere", "containing", "all", "atoms", "part", "of", "this", "structure", ".", "This", "will", "not", "calculate", "the", "minimal", "bounding", "sphere", "just", "a", "good", "-", "enough", "approximation", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/mol.js#L166-L173
16,840
biasmv/pv
src/mol/mol.js
function() { var chains = this.chains(); var traces = []; for (var i = 0; i < chains.length; ++i) { Array.prototype.push.apply(traces, chains[i].backboneTraces()); } return traces; }
javascript
function() { var chains = this.chains(); var traces = []; for (var i = 0; i < chains.length; ++i) { Array.prototype.push.apply(traces, chains[i].backboneTraces()); } return traces; }
[ "function", "(", ")", "{", "var", "chains", "=", "this", ".", "chains", "(", ")", ";", "var", "traces", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "chains", ".", "length", ";", "++", "i", ")", "{", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "traces", ",", "chains", "[", "i", "]", ".", "backboneTraces", "(", ")", ")", ";", "}", "return", "traces", ";", "}" ]
returns all backbone traces of all chains of this structure
[ "returns", "all", "backbone", "traces", "of", "all", "chains", "of", "this", "structure" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/mol.js#L176-L183
16,841
biasmv/pv
src/mol/mol.js
function() { console.time('Mol.deriveConnectivity'); var thisStructure = this; var prevResidue = null; this.eachResidue(function(res) { var sqrDist; var atoms = res.atoms(); var numAtoms = atoms.length; for (var i = 0; i < numAtoms; i+=1) { var atomI = atoms[i]; var posI = atomI.pos(); var covalentI = covalentRadius(atomI.element()); for (var j = 0; j < i; j+=1) { var atomJ = atoms[j]; var covalentJ = covalentRadius(atomJ.element()); sqrDist = vec3.sqrDist(posI, atomJ.pos()); var lower = covalentI+covalentJ-0.30; var upper = covalentI+covalentJ+0.30; if (sqrDist < upper*upper && sqrDist > lower*lower) { thisStructure.connect(atomI, atomJ); } } } res._deduceType(); if (prevResidue !== null) { if (res.isAminoacid() && prevResidue.isAminoacid()) { connectPeptides(thisStructure, prevResidue, res); } if (res.isNucleotide() && prevResidue.isNucleotide()) { connectNucleotides(thisStructure, prevResidue, res); } } prevResidue = res; }); console.timeEnd('Mol.deriveConnectivity'); }
javascript
function() { console.time('Mol.deriveConnectivity'); var thisStructure = this; var prevResidue = null; this.eachResidue(function(res) { var sqrDist; var atoms = res.atoms(); var numAtoms = atoms.length; for (var i = 0; i < numAtoms; i+=1) { var atomI = atoms[i]; var posI = atomI.pos(); var covalentI = covalentRadius(atomI.element()); for (var j = 0; j < i; j+=1) { var atomJ = atoms[j]; var covalentJ = covalentRadius(atomJ.element()); sqrDist = vec3.sqrDist(posI, atomJ.pos()); var lower = covalentI+covalentJ-0.30; var upper = covalentI+covalentJ+0.30; if (sqrDist < upper*upper && sqrDist > lower*lower) { thisStructure.connect(atomI, atomJ); } } } res._deduceType(); if (prevResidue !== null) { if (res.isAminoacid() && prevResidue.isAminoacid()) { connectPeptides(thisStructure, prevResidue, res); } if (res.isNucleotide() && prevResidue.isNucleotide()) { connectNucleotides(thisStructure, prevResidue, res); } } prevResidue = res; }); console.timeEnd('Mol.deriveConnectivity'); }
[ "function", "(", ")", "{", "console", ".", "time", "(", "'Mol.deriveConnectivity'", ")", ";", "var", "thisStructure", "=", "this", ";", "var", "prevResidue", "=", "null", ";", "this", ".", "eachResidue", "(", "function", "(", "res", ")", "{", "var", "sqrDist", ";", "var", "atoms", "=", "res", ".", "atoms", "(", ")", ";", "var", "numAtoms", "=", "atoms", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numAtoms", ";", "i", "+=", "1", ")", "{", "var", "atomI", "=", "atoms", "[", "i", "]", ";", "var", "posI", "=", "atomI", ".", "pos", "(", ")", ";", "var", "covalentI", "=", "covalentRadius", "(", "atomI", ".", "element", "(", ")", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "i", ";", "j", "+=", "1", ")", "{", "var", "atomJ", "=", "atoms", "[", "j", "]", ";", "var", "covalentJ", "=", "covalentRadius", "(", "atomJ", ".", "element", "(", ")", ")", ";", "sqrDist", "=", "vec3", ".", "sqrDist", "(", "posI", ",", "atomJ", ".", "pos", "(", ")", ")", ";", "var", "lower", "=", "covalentI", "+", "covalentJ", "-", "0.30", ";", "var", "upper", "=", "covalentI", "+", "covalentJ", "+", "0.30", ";", "if", "(", "sqrDist", "<", "upper", "*", "upper", "&&", "sqrDist", ">", "lower", "*", "lower", ")", "{", "thisStructure", ".", "connect", "(", "atomI", ",", "atomJ", ")", ";", "}", "}", "}", "res", ".", "_deduceType", "(", ")", ";", "if", "(", "prevResidue", "!==", "null", ")", "{", "if", "(", "res", ".", "isAminoacid", "(", ")", "&&", "prevResidue", ".", "isAminoacid", "(", ")", ")", "{", "connectPeptides", "(", "thisStructure", ",", "prevResidue", ",", "res", ")", ";", "}", "if", "(", "res", ".", "isNucleotide", "(", ")", "&&", "prevResidue", ".", "isNucleotide", "(", ")", ")", "{", "connectNucleotides", "(", "thisStructure", ",", "prevResidue", ",", "res", ")", ";", "}", "}", "prevResidue", "=", "res", ";", "}", ")", ";", "console", ".", "timeEnd", "(", "'Mol.deriveConnectivity'", ")", ";", "}" ]
determine connectivity structure. for simplicity only connects atoms of the same residue, peptide bonds and nucleotides
[ "determine", "connectivity", "structure", ".", "for", "simplicity", "only", "connects", "atoms", "of", "the", "same", "residue", "peptide", "bonds", "and", "nucleotides" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/mol.js#L408-L443
16,842
biasmv/pv
src/mol/mol.js
function(chain, recurse) { var chainView = new ChainView(this, chain.full()); this._chains.push(chainView); if (recurse) { var residues = chain.residues(); for (var i = 0; i< residues.length; ++i) { chainView.addResidue(residues[i], true); } } return chainView; }
javascript
function(chain, recurse) { var chainView = new ChainView(this, chain.full()); this._chains.push(chainView); if (recurse) { var residues = chain.residues(); for (var i = 0; i< residues.length; ++i) { chainView.addResidue(residues[i], true); } } return chainView; }
[ "function", "(", "chain", ",", "recurse", ")", "{", "var", "chainView", "=", "new", "ChainView", "(", "this", ",", "chain", ".", "full", "(", ")", ")", ";", "this", ".", "_chains", ".", "push", "(", "chainView", ")", ";", "if", "(", "recurse", ")", "{", "var", "residues", "=", "chain", ".", "residues", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "residues", ".", "length", ";", "++", "i", ")", "{", "chainView", ".", "addResidue", "(", "residues", "[", "i", "]", ",", "true", ")", ";", "}", "}", "return", "chainView", ";", "}" ]
add chain to view
[ "add", "chain", "to", "view" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/mol.js#L459-L469
16,843
biasmv/pv
src/mol/select.js
_residuePredicates
function _residuePredicates(dict) { var predicates = []; if (dict.rname !== undefined) { predicates.push(function(r) { return r.name() === dict.rname; }); } if (dict.rnames !== undefined) { predicates.push(function(r) { var n = r.name(); for (var k = 0; k < dict.rnames.length; ++k) { if (n === dict.rnames[k]) { return true; } } return false; }); } if (dict.rnums !== undefined) { var num_set = {}; for (var i = 0; i < dict.rnums.length; ++i) { num_set[dict.rnums[i]] = true; } predicates.push(function(r) { var n = r.num(); return num_set[n] === true; }); } if (dict.rnum !== undefined) { predicates.push(function(r) { return r.num() === dict.rnum; }); } if (dict.rtype !== undefined) { predicates.push(function(r) { return r.ss() === dict.rtype; }); } return predicates; }
javascript
function _residuePredicates(dict) { var predicates = []; if (dict.rname !== undefined) { predicates.push(function(r) { return r.name() === dict.rname; }); } if (dict.rnames !== undefined) { predicates.push(function(r) { var n = r.name(); for (var k = 0; k < dict.rnames.length; ++k) { if (n === dict.rnames[k]) { return true; } } return false; }); } if (dict.rnums !== undefined) { var num_set = {}; for (var i = 0; i < dict.rnums.length; ++i) { num_set[dict.rnums[i]] = true; } predicates.push(function(r) { var n = r.num(); return num_set[n] === true; }); } if (dict.rnum !== undefined) { predicates.push(function(r) { return r.num() === dict.rnum; }); } if (dict.rtype !== undefined) { predicates.push(function(r) { return r.ss() === dict.rtype; }); } return predicates; }
[ "function", "_residuePredicates", "(", "dict", ")", "{", "var", "predicates", "=", "[", "]", ";", "if", "(", "dict", ".", "rname", "!==", "undefined", ")", "{", "predicates", ".", "push", "(", "function", "(", "r", ")", "{", "return", "r", ".", "name", "(", ")", "===", "dict", ".", "rname", ";", "}", ")", ";", "}", "if", "(", "dict", ".", "rnames", "!==", "undefined", ")", "{", "predicates", ".", "push", "(", "function", "(", "r", ")", "{", "var", "n", "=", "r", ".", "name", "(", ")", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "dict", ".", "rnames", ".", "length", ";", "++", "k", ")", "{", "if", "(", "n", "===", "dict", ".", "rnames", "[", "k", "]", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", ")", ";", "}", "if", "(", "dict", ".", "rnums", "!==", "undefined", ")", "{", "var", "num_set", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "dict", ".", "rnums", ".", "length", ";", "++", "i", ")", "{", "num_set", "[", "dict", ".", "rnums", "[", "i", "]", "]", "=", "true", ";", "}", "predicates", ".", "push", "(", "function", "(", "r", ")", "{", "var", "n", "=", "r", ".", "num", "(", ")", ";", "return", "num_set", "[", "n", "]", "===", "true", ";", "}", ")", ";", "}", "if", "(", "dict", ".", "rnum", "!==", "undefined", ")", "{", "predicates", ".", "push", "(", "function", "(", "r", ")", "{", "return", "r", ".", "num", "(", ")", "===", "dict", ".", "rnum", ";", "}", ")", ";", "}", "if", "(", "dict", ".", "rtype", "!==", "undefined", ")", "{", "predicates", ".", "push", "(", "function", "(", "r", ")", "{", "return", "r", ".", "ss", "(", ")", "===", "dict", ".", "rtype", ";", "}", ")", ";", "}", "return", "predicates", ";", "}" ]
extracts the residue predicates from the dictionary. ignores rindices, rindexRange because they are handled separately.
[ "extracts", "the", "residue", "predicates", "from", "the", "dictionary", ".", "ignores", "rindices", "rindexRange", "because", "they", "are", "handled", "separately", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/select.js#L36-L73
16,844
biasmv/pv
src/mol/select.js
_filterResidues
function _filterResidues(chain, dict) { var residues = chain.residues(); if (dict.rnumRange) { residues = chain.residuesInRnumRange(dict.rnumRange[0], dict.rnumRange[1]); } var selResidues = [], i, e; if (dict.rindexRange !== undefined) { for (i = dict.rindexRange[0], e = Math.min(residues.length - 1, dict.rindexRange[1]); i <= e; ++i) { selResidues.push(residues[i]); } return selResidues; } if (dict.rindices) { if (dict.rindices.length !== undefined) { selResidues = []; for (i = 0; i < dict.rindices.length; ++i) { selResidues.push(residues[dict.rindices[i]]); } return selResidues; } } return residues; }
javascript
function _filterResidues(chain, dict) { var residues = chain.residues(); if (dict.rnumRange) { residues = chain.residuesInRnumRange(dict.rnumRange[0], dict.rnumRange[1]); } var selResidues = [], i, e; if (dict.rindexRange !== undefined) { for (i = dict.rindexRange[0], e = Math.min(residues.length - 1, dict.rindexRange[1]); i <= e; ++i) { selResidues.push(residues[i]); } return selResidues; } if (dict.rindices) { if (dict.rindices.length !== undefined) { selResidues = []; for (i = 0; i < dict.rindices.length; ++i) { selResidues.push(residues[dict.rindices[i]]); } return selResidues; } } return residues; }
[ "function", "_filterResidues", "(", "chain", ",", "dict", ")", "{", "var", "residues", "=", "chain", ".", "residues", "(", ")", ";", "if", "(", "dict", ".", "rnumRange", ")", "{", "residues", "=", "chain", ".", "residuesInRnumRange", "(", "dict", ".", "rnumRange", "[", "0", "]", ",", "dict", ".", "rnumRange", "[", "1", "]", ")", ";", "}", "var", "selResidues", "=", "[", "]", ",", "i", ",", "e", ";", "if", "(", "dict", ".", "rindexRange", "!==", "undefined", ")", "{", "for", "(", "i", "=", "dict", ".", "rindexRange", "[", "0", "]", ",", "e", "=", "Math", ".", "min", "(", "residues", ".", "length", "-", "1", ",", "dict", ".", "rindexRange", "[", "1", "]", ")", ";", "i", "<=", "e", ";", "++", "i", ")", "{", "selResidues", ".", "push", "(", "residues", "[", "i", "]", ")", ";", "}", "return", "selResidues", ";", "}", "if", "(", "dict", ".", "rindices", ")", "{", "if", "(", "dict", ".", "rindices", ".", "length", "!==", "undefined", ")", "{", "selResidues", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "dict", ".", "rindices", ".", "length", ";", "++", "i", ")", "{", "selResidues", ".", "push", "(", "residues", "[", "dict", ".", "rindices", "[", "i", "]", "]", ")", ";", "}", "return", "selResidues", ";", "}", "}", "return", "residues", ";", "}" ]
handles all residue predicates that can be done through either index- based lookups, or optimized searches of some sorts.
[ "handles", "all", "residue", "predicates", "that", "can", "be", "done", "through", "either", "index", "-", "based", "lookups", "or", "optimized", "searches", "of", "some", "sorts", "." ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/select.js#L103-L128
16,845
biasmv/pv
src/mol/select.js
dictSelect
function dictSelect(structure, view, dict) { var residuePredicates = _residuePredicates(dict); var atomPredicates = _atomPredicates(dict); var chainPredicates = _chainPredicates(dict); if (dict.rindex) { dict.rindices = [dict.rindex]; } for (var ci = 0; ci < structure._chains.length; ++ci) { var chain = structure._chains[ci]; if (!fulfillsPredicates(chain, chainPredicates)) { continue; } var residues = _filterResidues(chain, dict); var chainView = null; for (var ri = 0; ri < residues.length; ++ri) { if (!fulfillsPredicates(residues[ri], residuePredicates)) { continue; } if (!chainView) { chainView = view.addChain(chain, false); } var residueView = null; var atoms = residues[ri].atoms(); for (var ai = 0; ai < atoms.length; ++ai) { if (!fulfillsPredicates(atoms[ai], atomPredicates)) { continue; } if (!residueView) { residueView = chainView.addResidue(residues[ri], false); } residueView.addAtom(atoms[ai]); } } } return view; }
javascript
function dictSelect(structure, view, dict) { var residuePredicates = _residuePredicates(dict); var atomPredicates = _atomPredicates(dict); var chainPredicates = _chainPredicates(dict); if (dict.rindex) { dict.rindices = [dict.rindex]; } for (var ci = 0; ci < structure._chains.length; ++ci) { var chain = structure._chains[ci]; if (!fulfillsPredicates(chain, chainPredicates)) { continue; } var residues = _filterResidues(chain, dict); var chainView = null; for (var ri = 0; ri < residues.length; ++ri) { if (!fulfillsPredicates(residues[ri], residuePredicates)) { continue; } if (!chainView) { chainView = view.addChain(chain, false); } var residueView = null; var atoms = residues[ri].atoms(); for (var ai = 0; ai < atoms.length; ++ai) { if (!fulfillsPredicates(atoms[ai], atomPredicates)) { continue; } if (!residueView) { residueView = chainView.addResidue(residues[ri], false); } residueView.addAtom(atoms[ai]); } } } return view; }
[ "function", "dictSelect", "(", "structure", ",", "view", ",", "dict", ")", "{", "var", "residuePredicates", "=", "_residuePredicates", "(", "dict", ")", ";", "var", "atomPredicates", "=", "_atomPredicates", "(", "dict", ")", ";", "var", "chainPredicates", "=", "_chainPredicates", "(", "dict", ")", ";", "if", "(", "dict", ".", "rindex", ")", "{", "dict", ".", "rindices", "=", "[", "dict", ".", "rindex", "]", ";", "}", "for", "(", "var", "ci", "=", "0", ";", "ci", "<", "structure", ".", "_chains", ".", "length", ";", "++", "ci", ")", "{", "var", "chain", "=", "structure", ".", "_chains", "[", "ci", "]", ";", "if", "(", "!", "fulfillsPredicates", "(", "chain", ",", "chainPredicates", ")", ")", "{", "continue", ";", "}", "var", "residues", "=", "_filterResidues", "(", "chain", ",", "dict", ")", ";", "var", "chainView", "=", "null", ";", "for", "(", "var", "ri", "=", "0", ";", "ri", "<", "residues", ".", "length", ";", "++", "ri", ")", "{", "if", "(", "!", "fulfillsPredicates", "(", "residues", "[", "ri", "]", ",", "residuePredicates", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "chainView", ")", "{", "chainView", "=", "view", ".", "addChain", "(", "chain", ",", "false", ")", ";", "}", "var", "residueView", "=", "null", ";", "var", "atoms", "=", "residues", "[", "ri", "]", ".", "atoms", "(", ")", ";", "for", "(", "var", "ai", "=", "0", ";", "ai", "<", "atoms", ".", "length", ";", "++", "ai", ")", "{", "if", "(", "!", "fulfillsPredicates", "(", "atoms", "[", "ai", "]", ",", "atomPredicates", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "residueView", ")", "{", "residueView", "=", "chainView", ".", "addResidue", "(", "residues", "[", "ri", "]", ",", "false", ")", ";", "}", "residueView", ".", "addAtom", "(", "atoms", "[", "ai", "]", ")", ";", "}", "}", "}", "return", "view", ";", "}" ]
helper function to perform selection by predicates
[ "helper", "function", "to", "perform", "selection", "by", "predicates" ]
ed561cb63210e7662a568c55f9501961f011dfe8
https://github.com/biasmv/pv/blob/ed561cb63210e7662a568c55f9501961f011dfe8/src/mol/select.js#L131-L167
16,846
sapegin/grunt-webfont
tasks/webfont.js
completeTask
function completeTask() { if (o && _.isFunction(o.callback)) { o.callback(o.fontName, o.types, o.glyphs, o.hash); } allDone(); }
javascript
function completeTask() { if (o && _.isFunction(o.callback)) { o.callback(o.fontName, o.types, o.glyphs, o.hash); } allDone(); }
[ "function", "completeTask", "(", ")", "{", "if", "(", "o", "&&", "_", ".", "isFunction", "(", "o", ".", "callback", ")", ")", "{", "o", ".", "callback", "(", "o", ".", "fontName", ",", "o", ".", "types", ",", "o", ".", "glyphs", ",", "o", ".", "hash", ")", ";", "}", "allDone", "(", ")", ";", "}" ]
Call callback function if it was specified in the options.
[ "Call", "callback", "function", "if", "it", "was", "specified", "in", "the", "options", "." ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L211-L216
16,847
sapegin/grunt-webfont
tasks/webfont.js
getHash
function getHash() { // Source SVG files contents o.files.forEach(function(file) { md5.update(fs.readFileSync(file, 'utf8')); }); // Options md5.update(JSON.stringify(o)); // grunt-webfont version var packageJson = require('../package.json'); md5.update(packageJson.version); // Templates if (o.template) { md5.update(fs.readFileSync(o.template, 'utf8')); } if (o.htmlDemoTemplate) { md5.update(fs.readFileSync(o.htmlDemoTemplate, 'utf8')); } return md5.digest('hex'); }
javascript
function getHash() { // Source SVG files contents o.files.forEach(function(file) { md5.update(fs.readFileSync(file, 'utf8')); }); // Options md5.update(JSON.stringify(o)); // grunt-webfont version var packageJson = require('../package.json'); md5.update(packageJson.version); // Templates if (o.template) { md5.update(fs.readFileSync(o.template, 'utf8')); } if (o.htmlDemoTemplate) { md5.update(fs.readFileSync(o.htmlDemoTemplate, 'utf8')); } return md5.digest('hex'); }
[ "function", "getHash", "(", ")", "{", "// Source SVG files contents", "o", ".", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "md5", ".", "update", "(", "fs", ".", "readFileSync", "(", "file", ",", "'utf8'", ")", ")", ";", "}", ")", ";", "// Options", "md5", ".", "update", "(", "JSON", ".", "stringify", "(", "o", ")", ")", ";", "// grunt-webfont version", "var", "packageJson", "=", "require", "(", "'../package.json'", ")", ";", "md5", ".", "update", "(", "packageJson", ".", "version", ")", ";", "// Templates", "if", "(", "o", ".", "template", ")", "{", "md5", ".", "update", "(", "fs", ".", "readFileSync", "(", "o", ".", "template", ",", "'utf8'", ")", ")", ";", "}", "if", "(", "o", ".", "htmlDemoTemplate", ")", "{", "md5", ".", "update", "(", "fs", ".", "readFileSync", "(", "o", ".", "htmlDemoTemplate", ",", "'utf8'", ")", ")", ";", "}", "return", "md5", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Calculate hash to flush browser cache. Hash is based on source SVG files contents, task options and grunt-webfont version. @return {String}
[ "Calculate", "hash", "to", "flush", "browser", "cache", ".", "Hash", "is", "based", "on", "source", "SVG", "files", "contents", "task", "options", "and", "grunt", "-", "webfont", "version", "." ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L224-L246
16,848
sapegin/grunt-webfont
tasks/webfont.js
cleanOutputDir
function cleanOutputDir(done) { var htmlDemoFileMask = path.join(o.destCss, o.fontBaseName + '*.{css,html}'); var files = glob.sync(htmlDemoFileMask).concat(wf.generatedFontFiles(o)); async.forEach(files, function(file, next) { fs.unlink(file, next); }, done); }
javascript
function cleanOutputDir(done) { var htmlDemoFileMask = path.join(o.destCss, o.fontBaseName + '*.{css,html}'); var files = glob.sync(htmlDemoFileMask).concat(wf.generatedFontFiles(o)); async.forEach(files, function(file, next) { fs.unlink(file, next); }, done); }
[ "function", "cleanOutputDir", "(", "done", ")", "{", "var", "htmlDemoFileMask", "=", "path", ".", "join", "(", "o", ".", "destCss", ",", "o", ".", "fontBaseName", "+", "'*.{css,html}'", ")", ";", "var", "files", "=", "glob", ".", "sync", "(", "htmlDemoFileMask", ")", ".", "concat", "(", "wf", ".", "generatedFontFiles", "(", "o", ")", ")", ";", "async", ".", "forEach", "(", "files", ",", "function", "(", "file", ",", "next", ")", "{", "fs", ".", "unlink", "(", "file", ",", "next", ")", ";", "}", ",", "done", ")", ";", "}" ]
Clean output directory @param {Function} done
[ "Clean", "output", "directory" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L266-L272
16,849
sapegin/grunt-webfont
tasks/webfont.js
generateFont
function generateFont(done) { var engine = require('./engines/' + o.engine); engine(o, function(result) { if (result === false) { // Font was not created, exit completeTask(); return; } if (result) { o = _.extend(o, result); } done(); }); }
javascript
function generateFont(done) { var engine = require('./engines/' + o.engine); engine(o, function(result) { if (result === false) { // Font was not created, exit completeTask(); return; } if (result) { o = _.extend(o, result); } done(); }); }
[ "function", "generateFont", "(", "done", ")", "{", "var", "engine", "=", "require", "(", "'./engines/'", "+", "o", ".", "engine", ")", ";", "engine", "(", "o", ",", "function", "(", "result", ")", "{", "if", "(", "result", "===", "false", ")", "{", "// Font was not created, exit", "completeTask", "(", ")", ";", "return", ";", "}", "if", "(", "result", ")", "{", "o", "=", "_", ".", "extend", "(", "o", ",", "result", ")", ";", "}", "done", "(", ")", ";", "}", ")", ";", "}" ]
Generate font using selected engine @param {Function} done
[ "Generate", "font", "using", "selected", "engine" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L279-L294
16,850
sapegin/grunt-webfont
tasks/webfont.js
generateWoff2Font
function generateWoff2Font(done) { if (!has(o.types, 'woff2')) { done(); return; } // Read TTF font var ttfFontPath = wf.getFontPath(o, 'ttf'); var ttfFont = fs.readFileSync(ttfFontPath); // Remove TTF font if not needed if (!has(o.types, 'ttf')) { fs.unlinkSync(ttfFontPath); } // Convert to WOFF2 var woffFont = ttf2woff2(ttfFont); // Save var woff2FontPath = wf.getFontPath(o, 'woff2'); fs.writeFile(woff2FontPath, woffFont, function() {done();}); }
javascript
function generateWoff2Font(done) { if (!has(o.types, 'woff2')) { done(); return; } // Read TTF font var ttfFontPath = wf.getFontPath(o, 'ttf'); var ttfFont = fs.readFileSync(ttfFontPath); // Remove TTF font if not needed if (!has(o.types, 'ttf')) { fs.unlinkSync(ttfFontPath); } // Convert to WOFF2 var woffFont = ttf2woff2(ttfFont); // Save var woff2FontPath = wf.getFontPath(o, 'woff2'); fs.writeFile(woff2FontPath, woffFont, function() {done();}); }
[ "function", "generateWoff2Font", "(", "done", ")", "{", "if", "(", "!", "has", "(", "o", ".", "types", ",", "'woff2'", ")", ")", "{", "done", "(", ")", ";", "return", ";", "}", "// Read TTF font", "var", "ttfFontPath", "=", "wf", ".", "getFontPath", "(", "o", ",", "'ttf'", ")", ";", "var", "ttfFont", "=", "fs", ".", "readFileSync", "(", "ttfFontPath", ")", ";", "// Remove TTF font if not needed", "if", "(", "!", "has", "(", "o", ".", "types", ",", "'ttf'", ")", ")", "{", "fs", ".", "unlinkSync", "(", "ttfFontPath", ")", ";", "}", "// Convert to WOFF2", "var", "woffFont", "=", "ttf2woff2", "(", "ttfFont", ")", ";", "// Save", "var", "woff2FontPath", "=", "wf", ".", "getFontPath", "(", "o", ",", "'woff2'", ")", ";", "fs", ".", "writeFile", "(", "woff2FontPath", ",", "woffFont", ",", "function", "(", ")", "{", "done", "(", ")", ";", "}", ")", ";", "}" ]
Converts TTF font to WOFF2. @param {Function} done
[ "Converts", "TTF", "font", "to", "WOFF2", "." ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L301-L322
16,851
sapegin/grunt-webfont
tasks/webfont.js
readCodepointsFromFile
function readCodepointsFromFile(){ if (!o.codepointsFile) return {}; if (!fs.existsSync(o.codepointsFile)){ logger.verbose('Codepoints file not found'); return {}; } var buffer = fs.readFileSync(o.codepointsFile); return JSON.parse(buffer.toString()); }
javascript
function readCodepointsFromFile(){ if (!o.codepointsFile) return {}; if (!fs.existsSync(o.codepointsFile)){ logger.verbose('Codepoints file not found'); return {}; } var buffer = fs.readFileSync(o.codepointsFile); return JSON.parse(buffer.toString()); }
[ "function", "readCodepointsFromFile", "(", ")", "{", "if", "(", "!", "o", ".", "codepointsFile", ")", "return", "{", "}", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "o", ".", "codepointsFile", ")", ")", "{", "logger", ".", "verbose", "(", "'Codepoints file not found'", ")", ";", "return", "{", "}", ";", "}", "var", "buffer", "=", "fs", ".", "readFileSync", "(", "o", ".", "codepointsFile", ")", ";", "return", "JSON", ".", "parse", "(", "buffer", ".", "toString", "(", ")", ")", ";", "}" ]
Gets the codepoints from the set filepath in o.codepointsFile
[ "Gets", "the", "codepoints", "from", "the", "set", "filepath", "in", "o", ".", "codepointsFile" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L403-L412
16,852
sapegin/grunt-webfont
tasks/webfont.js
saveCodepointsToFile
function saveCodepointsToFile(){ if (!o.codepointsFile) return; var codepointsToString = JSON.stringify(o.codepoints, null, 4); try { fs.writeFileSync(o.codepointsFile, codepointsToString); logger.verbose('Codepoints saved to file "' + o.codepointsFile + '".'); } catch (err) { logger.error(err.message); } }
javascript
function saveCodepointsToFile(){ if (!o.codepointsFile) return; var codepointsToString = JSON.stringify(o.codepoints, null, 4); try { fs.writeFileSync(o.codepointsFile, codepointsToString); logger.verbose('Codepoints saved to file "' + o.codepointsFile + '".'); } catch (err) { logger.error(err.message); } }
[ "function", "saveCodepointsToFile", "(", ")", "{", "if", "(", "!", "o", ".", "codepointsFile", ")", "return", ";", "var", "codepointsToString", "=", "JSON", ".", "stringify", "(", "o", ".", "codepoints", ",", "null", ",", "4", ")", ";", "try", "{", "fs", ".", "writeFileSync", "(", "o", ".", "codepointsFile", ",", "codepointsToString", ")", ";", "logger", ".", "verbose", "(", "'Codepoints saved to file \"'", "+", "o", ".", "codepointsFile", "+", "'\".'", ")", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ".", "message", ")", ";", "}", "}" ]
Saves the codespoints to the set file
[ "Saves", "the", "codespoints", "to", "the", "set", "file" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L417-L426
16,853
sapegin/grunt-webfont
tasks/webfont.js
generateDemoHtml
function generateDemoHtml(done) { if (!o.htmlDemo) { done(); return; } var context = prepareHtmlTemplateContext(); // Generate HTML var demoTemplate = readTemplate(o.htmlDemoTemplate, 'demo', '.html'); var demo = renderTemplate(demoTemplate, context); mkdirp(getDemoPath(), function(err) { if (err) { logger.log(err); return; } // Save file fs.writeFileSync(getDemoFilePath(), demo); done(); }); }
javascript
function generateDemoHtml(done) { if (!o.htmlDemo) { done(); return; } var context = prepareHtmlTemplateContext(); // Generate HTML var demoTemplate = readTemplate(o.htmlDemoTemplate, 'demo', '.html'); var demo = renderTemplate(demoTemplate, context); mkdirp(getDemoPath(), function(err) { if (err) { logger.log(err); return; } // Save file fs.writeFileSync(getDemoFilePath(), demo); done(); }); }
[ "function", "generateDemoHtml", "(", "done", ")", "{", "if", "(", "!", "o", ".", "htmlDemo", ")", "{", "done", "(", ")", ";", "return", ";", "}", "var", "context", "=", "prepareHtmlTemplateContext", "(", ")", ";", "// Generate HTML", "var", "demoTemplate", "=", "readTemplate", "(", "o", ".", "htmlDemoTemplate", ",", "'demo'", ",", "'.html'", ")", ";", "var", "demo", "=", "renderTemplate", "(", "demoTemplate", ",", "context", ")", ";", "mkdirp", "(", "getDemoPath", "(", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "log", "(", "err", ")", ";", "return", ";", "}", "// Save file", "fs", ".", "writeFileSync", "(", "getDemoFilePath", "(", ")", ",", "demo", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Generate HTML demo page @param {Function} done
[ "Generate", "HTML", "demo", "page" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L535-L557
16,854
sapegin/grunt-webfont
tasks/webfont.js
optionToArray
function optionToArray(val, defVal) { if (val === undefined) { val = defVal; } if (!val) { return []; } if (typeof val !== 'string') { return val; } return val.split(',').map(_.trim); }
javascript
function optionToArray(val, defVal) { if (val === undefined) { val = defVal; } if (!val) { return []; } if (typeof val !== 'string') { return val; } return val.split(',').map(_.trim); }
[ "function", "optionToArray", "(", "val", ",", "defVal", ")", "{", "if", "(", "val", "===", "undefined", ")", "{", "val", "=", "defVal", ";", "}", "if", "(", "!", "val", ")", "{", "return", "[", "]", ";", "}", "if", "(", "typeof", "val", "!==", "'string'", ")", "{", "return", "val", ";", "}", "return", "val", ".", "split", "(", "','", ")", ".", "map", "(", "_", ".", "trim", ")", ";", "}" ]
Helpers Convert a string of comma separated words into an array @param {String} val Input string @param {String} defVal Default value @return {Array}
[ "Helpers", "Convert", "a", "string", "of", "comma", "separated", "words", "into", "an", "array" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L581-L592
16,855
sapegin/grunt-webfont
tasks/webfont.js
normalizePath
function normalizePath(filepath) { if (!filepath.length) return filepath; // Make all slashes forward filepath = filepath.replace(/\\/g, '/'); // Make sure path ends with a slash if (!_s.endsWith(filepath, '/')) { filepath += '/'; } return filepath; }
javascript
function normalizePath(filepath) { if (!filepath.length) return filepath; // Make all slashes forward filepath = filepath.replace(/\\/g, '/'); // Make sure path ends with a slash if (!_s.endsWith(filepath, '/')) { filepath += '/'; } return filepath; }
[ "function", "normalizePath", "(", "filepath", ")", "{", "if", "(", "!", "filepath", ".", "length", ")", "return", "filepath", ";", "// Make all slashes forward", "filepath", "=", "filepath", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ";", "// Make sure path ends with a slash", "if", "(", "!", "_s", ".", "endsWith", "(", "filepath", ",", "'/'", ")", ")", "{", "filepath", "+=", "'/'", ";", "}", "return", "filepath", ";", "}" ]
Append a slash to end of a filepath if it not exists and make all slashes forward @param {String} filepath File path @return {String}
[ "Append", "a", "slash", "to", "end", "of", "a", "filepath", "if", "it", "not", "exists", "and", "make", "all", "slashes", "forward" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L667-L679
16,856
sapegin/grunt-webfont
tasks/webfont.js
readTemplate
function readTemplate(template, syntax, ext, optional) { var filename = template ? path.resolve(template.replace(path.extname(template), ext)) : path.join(__dirname, 'templates/' + syntax + ext) ; if (fs.existsSync(filename)) { return { filename: filename, template: fs.readFileSync(filename, 'utf8') }; } else if (!optional) { return grunt.fail.fatal('Cannot find template at path: ' + filename); } }
javascript
function readTemplate(template, syntax, ext, optional) { var filename = template ? path.resolve(template.replace(path.extname(template), ext)) : path.join(__dirname, 'templates/' + syntax + ext) ; if (fs.existsSync(filename)) { return { filename: filename, template: fs.readFileSync(filename, 'utf8') }; } else if (!optional) { return grunt.fail.fatal('Cannot find template at path: ' + filename); } }
[ "function", "readTemplate", "(", "template", ",", "syntax", ",", "ext", ",", "optional", ")", "{", "var", "filename", "=", "template", "?", "path", ".", "resolve", "(", "template", ".", "replace", "(", "path", ".", "extname", "(", "template", ")", ",", "ext", ")", ")", ":", "path", ".", "join", "(", "__dirname", ",", "'templates/'", "+", "syntax", "+", "ext", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "filename", ")", ")", "{", "return", "{", "filename", ":", "filename", ",", "template", ":", "fs", ".", "readFileSync", "(", "filename", ",", "'utf8'", ")", "}", ";", "}", "else", "if", "(", "!", "optional", ")", "{", "return", "grunt", ".", "fail", ".", "fatal", "(", "'Cannot find template at path: '", "+", "filename", ")", ";", "}", "}" ]
Reat the template file @param {String} template Template file path @param {String} syntax Syntax (bem, bootstrap, etc.) @param {String} ext Extention of the template @return {Object} {filename: 'Template filename', template: 'Template code'}
[ "Reat", "the", "template", "file" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L746-L760
16,857
sapegin/grunt-webfont
tasks/webfont.js
renderTemplate
function renderTemplate(template, context) { try { var func = _.template(template.template); return func(context); } catch (e) { grunt.fail.fatal('Error while rendering template ' + template.filename + ': ' + e.message); } }
javascript
function renderTemplate(template, context) { try { var func = _.template(template.template); return func(context); } catch (e) { grunt.fail.fatal('Error while rendering template ' + template.filename + ': ' + e.message); } }
[ "function", "renderTemplate", "(", "template", ",", "context", ")", "{", "try", "{", "var", "func", "=", "_", ".", "template", "(", "template", ".", "template", ")", ";", "return", "func", "(", "context", ")", ";", "}", "catch", "(", "e", ")", "{", "grunt", ".", "fail", ".", "fatal", "(", "'Error while rendering template '", "+", "template", ".", "filename", "+", "': '", "+", "e", ".", "message", ")", ";", "}", "}" ]
Render template with error reporting @param {Object} template {filename: 'Template filename', template: 'Template code'} @param {Object} context Template context @return {String}
[ "Render", "template", "with", "error", "reporting" ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L769-L777
16,858
sapegin/grunt-webfont
tasks/webfont.js
getCssFilePath
function getCssFilePath(stylesheet) { var cssFilePrefix = option(wf.cssFilePrefixes, stylesheet); return path.join(option(o.destCssPaths, stylesheet), cssFilePrefix + o.fontBaseName + '.' + stylesheet); }
javascript
function getCssFilePath(stylesheet) { var cssFilePrefix = option(wf.cssFilePrefixes, stylesheet); return path.join(option(o.destCssPaths, stylesheet), cssFilePrefix + o.fontBaseName + '.' + stylesheet); }
[ "function", "getCssFilePath", "(", "stylesheet", ")", "{", "var", "cssFilePrefix", "=", "option", "(", "wf", ".", "cssFilePrefixes", ",", "stylesheet", ")", ";", "return", "path", ".", "join", "(", "option", "(", "o", ".", "destCssPaths", ",", "stylesheet", ")", ",", "cssFilePrefix", "+", "o", ".", "fontBaseName", "+", "'.'", "+", "stylesheet", ")", ";", "}" ]
Return path of CSS file. @param {String} stylesheet (css, scss, ...) @return {String}
[ "Return", "path", "of", "CSS", "file", "." ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L808-L811
16,859
sapegin/grunt-webfont
tasks/webfont.js
getDemoFilePath
function getDemoFilePath() { if (!o.htmlDemo) return null; var name = o.htmlDemoFilename || o.fontBaseName; return path.join(o.destHtml, name + '.html'); }
javascript
function getDemoFilePath() { if (!o.htmlDemo) return null; var name = o.htmlDemoFilename || o.fontBaseName; return path.join(o.destHtml, name + '.html'); }
[ "function", "getDemoFilePath", "(", ")", "{", "if", "(", "!", "o", ".", "htmlDemo", ")", "return", "null", ";", "var", "name", "=", "o", ".", "htmlDemoFilename", "||", "o", ".", "fontBaseName", ";", "return", "path", ".", "join", "(", "o", ".", "destHtml", ",", "name", "+", "'.html'", ")", ";", "}" ]
Return path of HTML demo file or `null` if its generation was disabled. @return {String}
[ "Return", "path", "of", "HTML", "demo", "file", "or", "null", "if", "its", "generation", "was", "disabled", "." ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L818-L822
16,860
sapegin/grunt-webfont
tasks/webfont.js
saveHash
function saveHash(name, target, hash) { var filepath = getHashPath(name, target); mkdirp.sync(path.dirname(filepath)); fs.writeFileSync(filepath, hash); }
javascript
function saveHash(name, target, hash) { var filepath = getHashPath(name, target); mkdirp.sync(path.dirname(filepath)); fs.writeFileSync(filepath, hash); }
[ "function", "saveHash", "(", "name", ",", "target", ",", "hash", ")", "{", "var", "filepath", "=", "getHashPath", "(", "name", ",", "target", ")", ";", "mkdirp", ".", "sync", "(", "path", ".", "dirname", "(", "filepath", ")", ")", ";", "fs", ".", "writeFileSync", "(", "filepath", ",", "hash", ")", ";", "}" ]
Save hash to cache file. @param {String} name Task name (webfont). @param {String} target Task target name. @param {String} hash Hash.
[ "Save", "hash", "to", "cache", "file", "." ]
55114cc5c3625ec34dc82d7a844abc94d79411b8
https://github.com/sapegin/grunt-webfont/blob/55114cc5c3625ec34dc82d7a844abc94d79411b8/tasks/webfont.js#L839-L843
16,861
kyma-project/luigi
client/src/luigi-client.js
_callAllFns
function _callAllFns(objWithFns, payload) { for (var id in objWithFns) { if (objWithFns.hasOwnProperty(id) && isFunction(objWithFns[id])) { objWithFns[id](payload); } } }
javascript
function _callAllFns(objWithFns, payload) { for (var id in objWithFns) { if (objWithFns.hasOwnProperty(id) && isFunction(objWithFns[id])) { objWithFns[id](payload); } } }
[ "function", "_callAllFns", "(", "objWithFns", ",", "payload", ")", "{", "for", "(", "var", "id", "in", "objWithFns", ")", "{", "if", "(", "objWithFns", ".", "hasOwnProperty", "(", "id", ")", "&&", "isFunction", "(", "objWithFns", "[", "id", "]", ")", ")", "{", "objWithFns", "[", "id", "]", "(", "payload", ")", ";", "}", "}", "}" ]
Iterates over an object and executes all top-level functions with a given payload. @private
[ "Iterates", "over", "an", "object", "and", "executes", "all", "top", "-", "level", "functions", "with", "a", "given", "payload", "." ]
901cfeef1b4c126f08d55257f559bbd1a6f6b0e4
https://github.com/kyma-project/luigi/blob/901cfeef1b4c126f08d55257f559bbd1a6f6b0e4/client/src/luigi-client.js#L40-L46
16,862
kyma-project/luigi
client/src/luigi-client.js
luigiClientInit
function luigiClientInit() { /** * Save context data every time navigation to a different node happens * @private */ function setContext(rawData) { for (var index = 0; index < defaultContextKeys.length; index++) { var key = defaultContextKeys[index]; try { if (typeof rawData[key] === 'string') { rawData[key] = JSON.parse(rawData[key]); } } catch (e) { console.info( 'unable to parse luigi context data for', key, rawData[key], e ); } } currentContext = rawData; } function setAuthData(eventPayload) { if (eventPayload) { authData = eventPayload; } } window.addEventListener('message', function messageListener(e) { if ('luigi.init' === e.data.msg) { setContext(e.data); setAuthData(e.data.authData); luigiInitialized = true; _callAllFns(_onInitFns, currentContext.context); } else if ('luigi.navigate' === e.data.msg) { setContext(e.data); if (!currentContext.internal.isNavigateBack) { window.location.replace(e.data.viewUrl); } // execute the context change listener if set by the microfrontend _callAllFns(_onContextUpdatedFns, currentContext.context); window.parent.postMessage( { msg: 'luigi.navigate.ok' }, '*' ); } else if ('luigi.auth.tokenIssued' === e.data.msg) { setAuthData(e.data.authData); } if ('luigi.navigation.pathExists.answer' === e.data.msg) { var data = e.data.data; pathExistsPromises[data.correlationId].resolveFn(data.pathExists); delete pathExistsPromises[data.correlationId]; } if ('luigi.ux.confirmationModal.hide' === e.data.msg) { const data = e.data.data; const promise = promises.confirmationModal; if (promise) { data.confirmed ? promise.resolveFn() : promise.rejectFn(); delete promises.confirmationModal; } } if ('luigi.ux.alert.hide' === e.data.msg) { const { id } = e.data; if (id && promises.alerts[id]) { promises.alerts[id].resolveFn(id); delete promises.alerts[id]; } } }); window.parent.postMessage( { msg: 'luigi.get-context' }, '*' ); }
javascript
function luigiClientInit() { /** * Save context data every time navigation to a different node happens * @private */ function setContext(rawData) { for (var index = 0; index < defaultContextKeys.length; index++) { var key = defaultContextKeys[index]; try { if (typeof rawData[key] === 'string') { rawData[key] = JSON.parse(rawData[key]); } } catch (e) { console.info( 'unable to parse luigi context data for', key, rawData[key], e ); } } currentContext = rawData; } function setAuthData(eventPayload) { if (eventPayload) { authData = eventPayload; } } window.addEventListener('message', function messageListener(e) { if ('luigi.init' === e.data.msg) { setContext(e.data); setAuthData(e.data.authData); luigiInitialized = true; _callAllFns(_onInitFns, currentContext.context); } else if ('luigi.navigate' === e.data.msg) { setContext(e.data); if (!currentContext.internal.isNavigateBack) { window.location.replace(e.data.viewUrl); } // execute the context change listener if set by the microfrontend _callAllFns(_onContextUpdatedFns, currentContext.context); window.parent.postMessage( { msg: 'luigi.navigate.ok' }, '*' ); } else if ('luigi.auth.tokenIssued' === e.data.msg) { setAuthData(e.data.authData); } if ('luigi.navigation.pathExists.answer' === e.data.msg) { var data = e.data.data; pathExistsPromises[data.correlationId].resolveFn(data.pathExists); delete pathExistsPromises[data.correlationId]; } if ('luigi.ux.confirmationModal.hide' === e.data.msg) { const data = e.data.data; const promise = promises.confirmationModal; if (promise) { data.confirmed ? promise.resolveFn() : promise.rejectFn(); delete promises.confirmationModal; } } if ('luigi.ux.alert.hide' === e.data.msg) { const { id } = e.data; if (id && promises.alerts[id]) { promises.alerts[id].resolveFn(id); delete promises.alerts[id]; } } }); window.parent.postMessage( { msg: 'luigi.get-context' }, '*' ); }
[ "function", "luigiClientInit", "(", ")", "{", "/**\n * Save context data every time navigation to a different node happens\n * @private\n */", "function", "setContext", "(", "rawData", ")", "{", "for", "(", "var", "index", "=", "0", ";", "index", "<", "defaultContextKeys", ".", "length", ";", "index", "++", ")", "{", "var", "key", "=", "defaultContextKeys", "[", "index", "]", ";", "try", "{", "if", "(", "typeof", "rawData", "[", "key", "]", "===", "'string'", ")", "{", "rawData", "[", "key", "]", "=", "JSON", ".", "parse", "(", "rawData", "[", "key", "]", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "info", "(", "'unable to parse luigi context data for'", ",", "key", ",", "rawData", "[", "key", "]", ",", "e", ")", ";", "}", "}", "currentContext", "=", "rawData", ";", "}", "function", "setAuthData", "(", "eventPayload", ")", "{", "if", "(", "eventPayload", ")", "{", "authData", "=", "eventPayload", ";", "}", "}", "window", ".", "addEventListener", "(", "'message'", ",", "function", "messageListener", "(", "e", ")", "{", "if", "(", "'luigi.init'", "===", "e", ".", "data", ".", "msg", ")", "{", "setContext", "(", "e", ".", "data", ")", ";", "setAuthData", "(", "e", ".", "data", ".", "authData", ")", ";", "luigiInitialized", "=", "true", ";", "_callAllFns", "(", "_onInitFns", ",", "currentContext", ".", "context", ")", ";", "}", "else", "if", "(", "'luigi.navigate'", "===", "e", ".", "data", ".", "msg", ")", "{", "setContext", "(", "e", ".", "data", ")", ";", "if", "(", "!", "currentContext", ".", "internal", ".", "isNavigateBack", ")", "{", "window", ".", "location", ".", "replace", "(", "e", ".", "data", ".", "viewUrl", ")", ";", "}", "// execute the context change listener if set by the microfrontend", "_callAllFns", "(", "_onContextUpdatedFns", ",", "currentContext", ".", "context", ")", ";", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.navigate.ok'", "}", ",", "'*'", ")", ";", "}", "else", "if", "(", "'luigi.auth.tokenIssued'", "===", "e", ".", "data", ".", "msg", ")", "{", "setAuthData", "(", "e", ".", "data", ".", "authData", ")", ";", "}", "if", "(", "'luigi.navigation.pathExists.answer'", "===", "e", ".", "data", ".", "msg", ")", "{", "var", "data", "=", "e", ".", "data", ".", "data", ";", "pathExistsPromises", "[", "data", ".", "correlationId", "]", ".", "resolveFn", "(", "data", ".", "pathExists", ")", ";", "delete", "pathExistsPromises", "[", "data", ".", "correlationId", "]", ";", "}", "if", "(", "'luigi.ux.confirmationModal.hide'", "===", "e", ".", "data", ".", "msg", ")", "{", "const", "data", "=", "e", ".", "data", ".", "data", ";", "const", "promise", "=", "promises", ".", "confirmationModal", ";", "if", "(", "promise", ")", "{", "data", ".", "confirmed", "?", "promise", ".", "resolveFn", "(", ")", ":", "promise", ".", "rejectFn", "(", ")", ";", "delete", "promises", ".", "confirmationModal", ";", "}", "}", "if", "(", "'luigi.ux.alert.hide'", "===", "e", ".", "data", ".", "msg", ")", "{", "const", "{", "id", "}", "=", "e", ".", "data", ";", "if", "(", "id", "&&", "promises", ".", "alerts", "[", "id", "]", ")", "{", "promises", ".", "alerts", "[", "id", "]", ".", "resolveFn", "(", "id", ")", ";", "delete", "promises", ".", "alerts", "[", "id", "]", ";", "}", "}", "}", ")", ";", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.get-context'", "}", ",", "'*'", ")", ";", "}" ]
Adds event listener for communication with Luigi Core and starts communication @private
[ "Adds", "event", "listener", "for", "communication", "with", "Luigi", "Core", "and", "starts", "communication" ]
901cfeef1b4c126f08d55257f559bbd1a6f6b0e4
https://github.com/kyma-project/luigi/blob/901cfeef1b4c126f08d55257f559bbd1a6f6b0e4/client/src/luigi-client.js#L52-L137
16,863
kyma-project/luigi
client/src/luigi-client.js
setContext
function setContext(rawData) { for (var index = 0; index < defaultContextKeys.length; index++) { var key = defaultContextKeys[index]; try { if (typeof rawData[key] === 'string') { rawData[key] = JSON.parse(rawData[key]); } } catch (e) { console.info( 'unable to parse luigi context data for', key, rawData[key], e ); } } currentContext = rawData; }
javascript
function setContext(rawData) { for (var index = 0; index < defaultContextKeys.length; index++) { var key = defaultContextKeys[index]; try { if (typeof rawData[key] === 'string') { rawData[key] = JSON.parse(rawData[key]); } } catch (e) { console.info( 'unable to parse luigi context data for', key, rawData[key], e ); } } currentContext = rawData; }
[ "function", "setContext", "(", "rawData", ")", "{", "for", "(", "var", "index", "=", "0", ";", "index", "<", "defaultContextKeys", ".", "length", ";", "index", "++", ")", "{", "var", "key", "=", "defaultContextKeys", "[", "index", "]", ";", "try", "{", "if", "(", "typeof", "rawData", "[", "key", "]", "===", "'string'", ")", "{", "rawData", "[", "key", "]", "=", "JSON", ".", "parse", "(", "rawData", "[", "key", "]", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "info", "(", "'unable to parse luigi context data for'", ",", "key", ",", "rawData", "[", "key", "]", ",", "e", ")", ";", "}", "}", "currentContext", "=", "rawData", ";", "}" ]
Save context data every time navigation to a different node happens @private
[ "Save", "context", "data", "every", "time", "navigation", "to", "a", "different", "node", "happens" ]
901cfeef1b4c126f08d55257f559bbd1a6f6b0e4
https://github.com/kyma-project/luigi/blob/901cfeef1b4c126f08d55257f559bbd1a6f6b0e4/client/src/luigi-client.js#L57-L74
16,864
kyma-project/luigi
client/src/luigi-client.js
addInitListener
function addInitListener(initFn) { var id = _getRandomId(); _onInitFns[id] = initFn; if (luigiInitialized && isFunction(initFn)) { initFn(currentContext.context); } return id; }
javascript
function addInitListener(initFn) { var id = _getRandomId(); _onInitFns[id] = initFn; if (luigiInitialized && isFunction(initFn)) { initFn(currentContext.context); } return id; }
[ "function", "addInitListener", "(", "initFn", ")", "{", "var", "id", "=", "_getRandomId", "(", ")", ";", "_onInitFns", "[", "id", "]", "=", "initFn", ";", "if", "(", "luigiInitialized", "&&", "isFunction", "(", "initFn", ")", ")", "{", "initFn", "(", "currentContext", ".", "context", ")", ";", "}", "return", "id", ";", "}" ]
Use the functions and parameters to define the lifecycle of listeners, navigation nodes, and Event data. @name lifecycle Registers a listener called with the context object as soon as Luigi is instantiated. Defer your application bootstrap if you depend on authentication data coming from Luigi. @param {function} initFn the function that is called once Luigi is initialized @memberof lifecycle
[ "Use", "the", "functions", "and", "parameters", "to", "define", "the", "lifecycle", "of", "listeners", "navigation", "nodes", "and", "Event", "data", "." ]
901cfeef1b4c126f08d55257f559bbd1a6f6b0e4
https://github.com/kyma-project/luigi/blob/901cfeef1b4c126f08d55257f559bbd1a6f6b0e4/client/src/luigi-client.js#L152-L159
16,865
kyma-project/luigi
client/src/luigi-client.js
addContextUpdateListener
function addContextUpdateListener( contextUpdatedFn ) { var id = _getRandomId(); _onContextUpdatedFns[id] = contextUpdatedFn; if (luigiInitialized && isFunction(contextUpdatedFn)) { contextUpdatedFn(currentContext.context); } return id; }
javascript
function addContextUpdateListener( contextUpdatedFn ) { var id = _getRandomId(); _onContextUpdatedFns[id] = contextUpdatedFn; if (luigiInitialized && isFunction(contextUpdatedFn)) { contextUpdatedFn(currentContext.context); } return id; }
[ "function", "addContextUpdateListener", "(", "contextUpdatedFn", ")", "{", "var", "id", "=", "_getRandomId", "(", ")", ";", "_onContextUpdatedFns", "[", "id", "]", "=", "contextUpdatedFn", ";", "if", "(", "luigiInitialized", "&&", "isFunction", "(", "contextUpdatedFn", ")", ")", "{", "contextUpdatedFn", "(", "currentContext", ".", "context", ")", ";", "}", "return", "id", ";", "}" ]
Registers a listener called with the context object upon any navigation change. @param {function} contextUpdatedFn the listener function called each time Luigi context changes @memberof lifecycle
[ "Registers", "a", "listener", "called", "with", "the", "context", "object", "upon", "any", "navigation", "change", "." ]
901cfeef1b4c126f08d55257f559bbd1a6f6b0e4
https://github.com/kyma-project/luigi/blob/901cfeef1b4c126f08d55257f559bbd1a6f6b0e4/client/src/luigi-client.js#L177-L186
16,866
kyma-project/luigi
client/src/luigi-client.js
fromClosestContext
function fromClosestContext() { var hasParentNavigationContext = currentContext.context.parentNavigationContexts.length > 0; if (hasParentNavigationContext) { options.fromContext = null; options.fromClosestContext = true; } else { console.error( 'Navigation not possible, no parent navigationContext found.' ); } return this; }
javascript
function fromClosestContext() { var hasParentNavigationContext = currentContext.context.parentNavigationContexts.length > 0; if (hasParentNavigationContext) { options.fromContext = null; options.fromClosestContext = true; } else { console.error( 'Navigation not possible, no parent navigationContext found.' ); } return this; }
[ "function", "fromClosestContext", "(", ")", "{", "var", "hasParentNavigationContext", "=", "currentContext", ".", "context", ".", "parentNavigationContexts", ".", "length", ">", "0", ";", "if", "(", "hasParentNavigationContext", ")", "{", "options", ".", "fromContext", "=", "null", ";", "options", ".", "fromClosestContext", "=", "true", ";", "}", "else", "{", "console", ".", "error", "(", "'Navigation not possible, no parent navigationContext found.'", ")", ";", "}", "return", "this", ";", "}" ]
Sets the current navigation context which is then used by the `navigate` function. This has to be a parent navigation context, it is not possible to use the child navigation contexts. @returns {linkManager} link manager instance @example LuigiClient.linkManager().fromClosestContext().navigate('/users/groups/stakeholders')
[ "Sets", "the", "current", "navigation", "context", "which", "is", "then", "used", "by", "the", "navigate", "function", ".", "This", "has", "to", "be", "a", "parent", "navigation", "context", "it", "is", "not", "possible", "to", "use", "the", "child", "navigation", "contexts", "." ]
901cfeef1b4c126f08d55257f559bbd1a6f6b0e4
https://github.com/kyma-project/luigi/blob/901cfeef1b4c126f08d55257f559bbd1a6f6b0e4/client/src/luigi-client.js#L330-L342
16,867
kyma-project/luigi
client/src/luigi-client.js
uxManager
function uxManager() { return { /** @lends uxManager */ /** * Adds a backdrop with a loading indicator for the micro front-end frame. This overrides the {@link navigation-configuration.md#nodes loadingIndicator.enabled} setting. */ showLoadingIndicator: function showLoadingIndicator() { window.parent.postMessage( { msg: 'luigi.show-loading-indicator' }, '*' ); }, /** * Removes the loading indicator. Use it after calling {@link #showLoadingIndicator showLoadingIndicator()} or to hide the indicator when you use the {@link navigation-configuration.md#nodes loadingIndicator.hideAutomatically: false} node configuration. */ hideLoadingIndicator: function hideLoadingIndicator() { window.parent.postMessage( { msg: 'luigi.hide-loading-indicator' }, '*' ); }, /** * Adds a backdrop to block the top and side navigation. It is based on the Fundamental UI Modal, which you can use in your micro front-end to achieve the same behavior. */ addBackdrop: function addBackdrop() { window.parent.postMessage( { msg: 'luigi.add-backdrop' }, '*' ); }, /** * Removes the backdrop. */ removeBackdrop: function removeBackdrop() { window.parent.postMessage( { msg: 'luigi.remove-backdrop' }, '*' ); }, /** * This method informs the main application that there are unsaved changes in the current view in the iframe. For example, that can be a view with form fields which were edited but not submitted. * @param {boolean} isDirty indicates if there are any unsaved changes on the current page or in the component */ setDirtyStatus: function setDirtyStatus(isDirty) { window.parent.postMessage( { msg: 'luigi.set-page-dirty', dirty: isDirty }, '*' ); }, /** * Shows a confirmation modal. * @param {Object} [settings] the settings the confirmation modal. If no value is provided for any of the fields, a default value is set for it * @param {string} [settings.header="Confirmation"] the content of the modal header * @param {string} [settings.body="Are you sure you want to do this?"] the content of the modal body * @param {string} [settings.buttonConfirm="Yes"] the label for the modal confirm button * @param {string} [settings.buttonDismiss="No"] the label for the modal dismiss button * @returns {promise} which is resolved when accepting the confirmation modal and rejected when dismissing it */ showConfirmationModal: function showConfirmationModal(settings) { window.parent.postMessage( { msg: 'luigi.ux.confirmationModal.show', data: { settings } }, '*' ); promises.confirmationModal = {}; promises.confirmationModal.promise = new Promise((resolve, reject) => { promises.confirmationModal.resolveFn = resolve; promises.confirmationModal.rejectFn = reject; }); return promises.confirmationModal.promise; }, /** * Shows an alert. * @param {Object} settings the settings for the alert * @param {string} settings.text the content of the alert. To add a link to the content, you have to set up the link in the `links` object. The key(s) in the `links` object must be used in the text to reference the links, wrapped in curly brackets with no spaces. If you don't specify any text, the alert is not displayed * @param {('info'|'success'|'warning'|'error')} [settings.type] sets the type of the alert * @param {Object} [settings.links] provides links data * @param {Object} settings.links.LINK_KEY object containing the data for a particular link. To properly render the link in the alert message refer to the description of the **settings.text** parameter * @param {string} settings.links.LINK_KEY.text text which replaces the link identifier in the alert content * @param {string} settings.links.LINK_KEY.url url to navigate when you click the link. Currently, only internal links are supported in the form of relative or absolute paths. * @param {number} settings.closeAfter (optional) time in milliseconds that tells Luigi when to close the Alert automatically. If not provided, the Alert will stay on until closed manually. It has to be greater than `100`. * @returns {promise} which is resolved when the alert is dismissed. * @example * import LuigiClient from '@kyma-project/luigi-client'; * const settings = { * text: Ut enim ad minim veniam, {goToHome} quis nostrud exercitation ullamco {relativePath} laboris nisi ut aliquip ex ea commodo consequat. * Duis aute irure dolor {goToOtherProject}, * type: 'info', * links: { * goToHome: { text: 'homepage', url: '/overview' }, * goToOtherProject: { text: 'other project', url: '/projects/pr2' }, * relativePath: { text: 'relative hide side nav', url: 'hideSideNav' } * }, * closeAfter: 3000 * } * LuigiClient * .uxManager() * .showAlert(settings) * .then(() => { * // Logic to execute when the alert is dismissed * }); */ showAlert: function showAlert(settings) { //generate random ID settings.id = crypto.randomBytes(4).toString('hex'); if (settings.closeAfter && settings.closeAfter < 100) { console.warn( `Message with id='${ settings.id }' has too small 'closeAfter' value. It needs to be at least 100ms.` ); settings.closeAfter = undefined; } window.parent.postMessage( { msg: 'luigi.ux.alert.show', data: { settings } }, '*' ); promises.alerts[settings.id] = {}; promises.alerts[settings.id].promise = new Promise(resolve => { promises.alerts[settings.id].resolveFn = resolve; }); return promises.alerts[settings.id].promise; } }; }
javascript
function uxManager() { return { /** @lends uxManager */ /** * Adds a backdrop with a loading indicator for the micro front-end frame. This overrides the {@link navigation-configuration.md#nodes loadingIndicator.enabled} setting. */ showLoadingIndicator: function showLoadingIndicator() { window.parent.postMessage( { msg: 'luigi.show-loading-indicator' }, '*' ); }, /** * Removes the loading indicator. Use it after calling {@link #showLoadingIndicator showLoadingIndicator()} or to hide the indicator when you use the {@link navigation-configuration.md#nodes loadingIndicator.hideAutomatically: false} node configuration. */ hideLoadingIndicator: function hideLoadingIndicator() { window.parent.postMessage( { msg: 'luigi.hide-loading-indicator' }, '*' ); }, /** * Adds a backdrop to block the top and side navigation. It is based on the Fundamental UI Modal, which you can use in your micro front-end to achieve the same behavior. */ addBackdrop: function addBackdrop() { window.parent.postMessage( { msg: 'luigi.add-backdrop' }, '*' ); }, /** * Removes the backdrop. */ removeBackdrop: function removeBackdrop() { window.parent.postMessage( { msg: 'luigi.remove-backdrop' }, '*' ); }, /** * This method informs the main application that there are unsaved changes in the current view in the iframe. For example, that can be a view with form fields which were edited but not submitted. * @param {boolean} isDirty indicates if there are any unsaved changes on the current page or in the component */ setDirtyStatus: function setDirtyStatus(isDirty) { window.parent.postMessage( { msg: 'luigi.set-page-dirty', dirty: isDirty }, '*' ); }, /** * Shows a confirmation modal. * @param {Object} [settings] the settings the confirmation modal. If no value is provided for any of the fields, a default value is set for it * @param {string} [settings.header="Confirmation"] the content of the modal header * @param {string} [settings.body="Are you sure you want to do this?"] the content of the modal body * @param {string} [settings.buttonConfirm="Yes"] the label for the modal confirm button * @param {string} [settings.buttonDismiss="No"] the label for the modal dismiss button * @returns {promise} which is resolved when accepting the confirmation modal and rejected when dismissing it */ showConfirmationModal: function showConfirmationModal(settings) { window.parent.postMessage( { msg: 'luigi.ux.confirmationModal.show', data: { settings } }, '*' ); promises.confirmationModal = {}; promises.confirmationModal.promise = new Promise((resolve, reject) => { promises.confirmationModal.resolveFn = resolve; promises.confirmationModal.rejectFn = reject; }); return promises.confirmationModal.promise; }, /** * Shows an alert. * @param {Object} settings the settings for the alert * @param {string} settings.text the content of the alert. To add a link to the content, you have to set up the link in the `links` object. The key(s) in the `links` object must be used in the text to reference the links, wrapped in curly brackets with no spaces. If you don't specify any text, the alert is not displayed * @param {('info'|'success'|'warning'|'error')} [settings.type] sets the type of the alert * @param {Object} [settings.links] provides links data * @param {Object} settings.links.LINK_KEY object containing the data for a particular link. To properly render the link in the alert message refer to the description of the **settings.text** parameter * @param {string} settings.links.LINK_KEY.text text which replaces the link identifier in the alert content * @param {string} settings.links.LINK_KEY.url url to navigate when you click the link. Currently, only internal links are supported in the form of relative or absolute paths. * @param {number} settings.closeAfter (optional) time in milliseconds that tells Luigi when to close the Alert automatically. If not provided, the Alert will stay on until closed manually. It has to be greater than `100`. * @returns {promise} which is resolved when the alert is dismissed. * @example * import LuigiClient from '@kyma-project/luigi-client'; * const settings = { * text: Ut enim ad minim veniam, {goToHome} quis nostrud exercitation ullamco {relativePath} laboris nisi ut aliquip ex ea commodo consequat. * Duis aute irure dolor {goToOtherProject}, * type: 'info', * links: { * goToHome: { text: 'homepage', url: '/overview' }, * goToOtherProject: { text: 'other project', url: '/projects/pr2' }, * relativePath: { text: 'relative hide side nav', url: 'hideSideNav' } * }, * closeAfter: 3000 * } * LuigiClient * .uxManager() * .showAlert(settings) * .then(() => { * // Logic to execute when the alert is dismissed * }); */ showAlert: function showAlert(settings) { //generate random ID settings.id = crypto.randomBytes(4).toString('hex'); if (settings.closeAfter && settings.closeAfter < 100) { console.warn( `Message with id='${ settings.id }' has too small 'closeAfter' value. It needs to be at least 100ms.` ); settings.closeAfter = undefined; } window.parent.postMessage( { msg: 'luigi.ux.alert.show', data: { settings } }, '*' ); promises.alerts[settings.id] = {}; promises.alerts[settings.id].promise = new Promise(resolve => { promises.alerts[settings.id].resolveFn = resolve; }); return promises.alerts[settings.id].promise; } }; }
[ "function", "uxManager", "(", ")", "{", "return", "{", "/** @lends uxManager */", "/**\n * Adds a backdrop with a loading indicator for the micro front-end frame. This overrides the {@link navigation-configuration.md#nodes loadingIndicator.enabled} setting.\n */", "showLoadingIndicator", ":", "function", "showLoadingIndicator", "(", ")", "{", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.show-loading-indicator'", "}", ",", "'*'", ")", ";", "}", ",", "/**\n * Removes the loading indicator. Use it after calling {@link #showLoadingIndicator showLoadingIndicator()} or to hide the indicator when you use the {@link navigation-configuration.md#nodes loadingIndicator.hideAutomatically: false} node configuration.\n */", "hideLoadingIndicator", ":", "function", "hideLoadingIndicator", "(", ")", "{", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.hide-loading-indicator'", "}", ",", "'*'", ")", ";", "}", ",", "/**\n * Adds a backdrop to block the top and side navigation. It is based on the Fundamental UI Modal, which you can use in your micro front-end to achieve the same behavior.\n */", "addBackdrop", ":", "function", "addBackdrop", "(", ")", "{", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.add-backdrop'", "}", ",", "'*'", ")", ";", "}", ",", "/**\n * Removes the backdrop.\n */", "removeBackdrop", ":", "function", "removeBackdrop", "(", ")", "{", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.remove-backdrop'", "}", ",", "'*'", ")", ";", "}", ",", "/**\n * This method informs the main application that there are unsaved changes in the current view in the iframe. For example, that can be a view with form fields which were edited but not submitted.\n * @param {boolean} isDirty indicates if there are any unsaved changes on the current page or in the component\n */", "setDirtyStatus", ":", "function", "setDirtyStatus", "(", "isDirty", ")", "{", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.set-page-dirty'", ",", "dirty", ":", "isDirty", "}", ",", "'*'", ")", ";", "}", ",", "/**\n * Shows a confirmation modal.\n * @param {Object} [settings] the settings the confirmation modal. If no value is provided for any of the fields, a default value is set for it\n * @param {string} [settings.header=\"Confirmation\"] the content of the modal header\n * @param {string} [settings.body=\"Are you sure you want to do this?\"] the content of the modal body\n * @param {string} [settings.buttonConfirm=\"Yes\"] the label for the modal confirm button\n * @param {string} [settings.buttonDismiss=\"No\"] the label for the modal dismiss button\n * @returns {promise} which is resolved when accepting the confirmation modal and rejected when dismissing it\n */", "showConfirmationModal", ":", "function", "showConfirmationModal", "(", "settings", ")", "{", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.ux.confirmationModal.show'", ",", "data", ":", "{", "settings", "}", "}", ",", "'*'", ")", ";", "promises", ".", "confirmationModal", "=", "{", "}", ";", "promises", ".", "confirmationModal", ".", "promise", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "promises", ".", "confirmationModal", ".", "resolveFn", "=", "resolve", ";", "promises", ".", "confirmationModal", ".", "rejectFn", "=", "reject", ";", "}", ")", ";", "return", "promises", ".", "confirmationModal", ".", "promise", ";", "}", ",", "/**\n * Shows an alert.\n * @param {Object} settings the settings for the alert\n * @param {string} settings.text the content of the alert. To add a link to the content, you have to set up the link in the `links` object. The key(s) in the `links` object must be used in the text to reference the links, wrapped in curly brackets with no spaces. If you don't specify any text, the alert is not displayed\n * @param {('info'|'success'|'warning'|'error')} [settings.type] sets the type of the alert\n * @param {Object} [settings.links] provides links data\n * @param {Object} settings.links.LINK_KEY object containing the data for a particular link. To properly render the link in the alert message refer to the description of the **settings.text** parameter\n * @param {string} settings.links.LINK_KEY.text text which replaces the link identifier in the alert content\n * @param {string} settings.links.LINK_KEY.url url to navigate when you click the link. Currently, only internal links are supported in the form of relative or absolute paths.\n * @param {number} settings.closeAfter (optional) time in milliseconds that tells Luigi when to close the Alert automatically. If not provided, the Alert will stay on until closed manually. It has to be greater than `100`.\n * @returns {promise} which is resolved when the alert is dismissed. \n * @example\n * import LuigiClient from '@kyma-project/luigi-client';\n * const settings = {\n * text: Ut enim ad minim veniam, {goToHome} quis nostrud exercitation ullamco {relativePath} laboris nisi ut aliquip ex ea commodo consequat.\n * Duis aute irure dolor {goToOtherProject},\n * type: 'info',\n * links: {\n * goToHome: { text: 'homepage', url: '/overview' },\n * goToOtherProject: { text: 'other project', url: '/projects/pr2' },\n * relativePath: { text: 'relative hide side nav', url: 'hideSideNav' }\n * },\n * closeAfter: 3000\n * }\n * LuigiClient\n * .uxManager()\n * .showAlert(settings)\n * .then(() => {\n * // Logic to execute when the alert is dismissed\n * });\n\n */", "showAlert", ":", "function", "showAlert", "(", "settings", ")", "{", "//generate random ID", "settings", ".", "id", "=", "crypto", ".", "randomBytes", "(", "4", ")", ".", "toString", "(", "'hex'", ")", ";", "if", "(", "settings", ".", "closeAfter", "&&", "settings", ".", "closeAfter", "<", "100", ")", "{", "console", ".", "warn", "(", "`", "${", "settings", ".", "id", "}", "`", ")", ";", "settings", ".", "closeAfter", "=", "undefined", ";", "}", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.ux.alert.show'", ",", "data", ":", "{", "settings", "}", "}", ",", "'*'", ")", ";", "promises", ".", "alerts", "[", "settings", ".", "id", "]", "=", "{", "}", ";", "promises", ".", "alerts", "[", "settings", ".", "id", "]", ".", "promise", "=", "new", "Promise", "(", "resolve", "=>", "{", "promises", ".", "alerts", "[", "settings", ".", "id", "]", ".", "resolveFn", "=", "resolve", ";", "}", ")", ";", "return", "promises", ".", "alerts", "[", "settings", ".", "id", "]", ".", "promise", ";", "}", "}", ";", "}" ]
Use the UX Manager to manage the appearance features in Luigi. @name uxManager
[ "Use", "the", "UX", "Manager", "to", "manage", "the", "appearance", "features", "in", "Luigi", "." ]
901cfeef1b4c126f08d55257f559bbd1a6f6b0e4
https://github.com/kyma-project/luigi/blob/901cfeef1b4c126f08d55257f559bbd1a6f6b0e4/client/src/luigi-client.js#L430-L578
16,868
kyma-project/luigi
client/src/luigi-client.js
showConfirmationModal
function showConfirmationModal(settings) { window.parent.postMessage( { msg: 'luigi.ux.confirmationModal.show', data: { settings } }, '*' ); promises.confirmationModal = {}; promises.confirmationModal.promise = new Promise((resolve, reject) => { promises.confirmationModal.resolveFn = resolve; promises.confirmationModal.rejectFn = reject; }); return promises.confirmationModal.promise; }
javascript
function showConfirmationModal(settings) { window.parent.postMessage( { msg: 'luigi.ux.confirmationModal.show', data: { settings } }, '*' ); promises.confirmationModal = {}; promises.confirmationModal.promise = new Promise((resolve, reject) => { promises.confirmationModal.resolveFn = resolve; promises.confirmationModal.rejectFn = reject; }); return promises.confirmationModal.promise; }
[ "function", "showConfirmationModal", "(", "settings", ")", "{", "window", ".", "parent", ".", "postMessage", "(", "{", "msg", ":", "'luigi.ux.confirmationModal.show'", ",", "data", ":", "{", "settings", "}", "}", ",", "'*'", ")", ";", "promises", ".", "confirmationModal", "=", "{", "}", ";", "promises", ".", "confirmationModal", ".", "promise", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "promises", ".", "confirmationModal", ".", "resolveFn", "=", "resolve", ";", "promises", ".", "confirmationModal", ".", "rejectFn", "=", "reject", ";", "}", ")", ";", "return", "promises", ".", "confirmationModal", ".", "promise", ";", "}" ]
Shows a confirmation modal. @param {Object} [settings] the settings the confirmation modal. If no value is provided for any of the fields, a default value is set for it @param {string} [settings.header="Confirmation"] the content of the modal header @param {string} [settings.body="Are you sure you want to do this?"] the content of the modal body @param {string} [settings.buttonConfirm="Yes"] the label for the modal confirm button @param {string} [settings.buttonDismiss="No"] the label for the modal dismiss button @returns {promise} which is resolved when accepting the confirmation modal and rejected when dismissing it
[ "Shows", "a", "confirmation", "modal", "." ]
901cfeef1b4c126f08d55257f559bbd1a6f6b0e4
https://github.com/kyma-project/luigi/blob/901cfeef1b4c126f08d55257f559bbd1a6f6b0e4/client/src/luigi-client.js#L499-L515
16,869
kategengler/ember-cli-code-coverage
index.js
function(startOptions) { if (!this._isCoverageEnabled()) { return; } attachMiddleware.serverMiddleware(startOptions.app, { configPath: this.project.configPath(), root: this.project.root, fileLookup: fileLookup }); }
javascript
function(startOptions) { if (!this._isCoverageEnabled()) { return; } attachMiddleware.serverMiddleware(startOptions.app, { configPath: this.project.configPath(), root: this.project.root, fileLookup: fileLookup }); }
[ "function", "(", "startOptions", ")", "{", "if", "(", "!", "this", ".", "_isCoverageEnabled", "(", ")", ")", "{", "return", ";", "}", "attachMiddleware", ".", "serverMiddleware", "(", "startOptions", ".", "app", ",", "{", "configPath", ":", "this", ".", "project", ".", "configPath", "(", ")", ",", "root", ":", "this", ".", "project", ".", "root", ",", "fileLookup", ":", "fileLookup", "}", ")", ";", "}" ]
If coverage is enabled attach coverage middleware to the express server run by ember-cli @param {Object} startOptions - Express server start options
[ "If", "coverage", "is", "enabled", "attach", "coverage", "middleware", "to", "the", "express", "server", "run", "by", "ember", "-", "cli" ]
2cefa0477d6e14be8b7c812367ceddcc51f45303
https://github.com/kategengler/ember-cli-code-coverage/blob/2cefa0477d6e14be8b7c812367ceddcc51f45303/index.js#L100-L109
16,870
kategengler/ember-cli-code-coverage
index.js
function() { const dir = path.join(this.project.root, 'app'); let prefix = this.parent.isEmberCLIAddon() ? 'dummy' : this.parent.name(); return this._getIncludesForDir(dir, prefix); }
javascript
function() { const dir = path.join(this.project.root, 'app'); let prefix = this.parent.isEmberCLIAddon() ? 'dummy' : this.parent.name(); return this._getIncludesForDir(dir, prefix); }
[ "function", "(", ")", "{", "const", "dir", "=", "path", ".", "join", "(", "this", ".", "project", ".", "root", ",", "'app'", ")", ";", "let", "prefix", "=", "this", ".", "parent", ".", "isEmberCLIAddon", "(", ")", "?", "'dummy'", ":", "this", ".", "parent", ".", "name", "(", ")", ";", "return", "this", ".", "_getIncludesForDir", "(", "dir", ",", "prefix", ")", ";", "}" ]
Get paths to include for covering the "app" directory. @returns {Array<String>} include paths
[ "Get", "paths", "to", "include", "for", "covering", "the", "app", "directory", "." ]
2cefa0477d6e14be8b7c812367ceddcc51f45303
https://github.com/kategengler/ember-cli-code-coverage/blob/2cefa0477d6e14be8b7c812367ceddcc51f45303/index.js#L151-L155
16,871
kategengler/ember-cli-code-coverage
index.js
function() { let addon = this._findCoveredAddon(); if (addon) { const addonDir = path.join(this.project.root, 'addon'); const addonTestSupportDir = path.join(this.project.root, 'addon-test-support'); return concat( this._getIncludesForDir(addonDir, addon.name), this._getIncludesForDir(addonTestSupportDir, `${addon.name}/test-support`) ); } }
javascript
function() { let addon = this._findCoveredAddon(); if (addon) { const addonDir = path.join(this.project.root, 'addon'); const addonTestSupportDir = path.join(this.project.root, 'addon-test-support'); return concat( this._getIncludesForDir(addonDir, addon.name), this._getIncludesForDir(addonTestSupportDir, `${addon.name}/test-support`) ); } }
[ "function", "(", ")", "{", "let", "addon", "=", "this", ".", "_findCoveredAddon", "(", ")", ";", "if", "(", "addon", ")", "{", "const", "addonDir", "=", "path", ".", "join", "(", "this", ".", "project", ".", "root", ",", "'addon'", ")", ";", "const", "addonTestSupportDir", "=", "path", ".", "join", "(", "this", ".", "project", ".", "root", ",", "'addon-test-support'", ")", ";", "return", "concat", "(", "this", ".", "_getIncludesForDir", "(", "addonDir", ",", "addon", ".", "name", ")", ",", "this", ".", "_getIncludesForDir", "(", "addonTestSupportDir", ",", "`", "${", "addon", ".", "name", "}", "`", ")", ")", ";", "}", "}" ]
Get paths to include for covering the "addon" directory. @returns {Array<String>} include paths
[ "Get", "paths", "to", "include", "for", "covering", "the", "addon", "directory", "." ]
2cefa0477d6e14be8b7c812367ceddcc51f45303
https://github.com/kategengler/ember-cli-code-coverage/blob/2cefa0477d6e14be8b7c812367ceddcc51f45303/index.js#L161-L171
16,872
kategengler/ember-cli-code-coverage
index.js
function(dir, prefix) { if (fs.existsSync(dir)) { let dirname = path.relative(this.project.root, dir); let globs = this.parentRegistry.extensionsForType('js').map((extension) => `**/*.${extension}`); return walkSync(dir, { directories: false, globs }).map(file => { let module = prefix + '/' + file.replace(EXT_RE, '.js'); this.fileLookup[module] = path.join(dirname, file); return module; }); } else { return []; } }
javascript
function(dir, prefix) { if (fs.existsSync(dir)) { let dirname = path.relative(this.project.root, dir); let globs = this.parentRegistry.extensionsForType('js').map((extension) => `**/*.${extension}`); return walkSync(dir, { directories: false, globs }).map(file => { let module = prefix + '/' + file.replace(EXT_RE, '.js'); this.fileLookup[module] = path.join(dirname, file); return module; }); } else { return []; } }
[ "function", "(", "dir", ",", "prefix", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "dir", ")", ")", "{", "let", "dirname", "=", "path", ".", "relative", "(", "this", ".", "project", ".", "root", ",", "dir", ")", ";", "let", "globs", "=", "this", ".", "parentRegistry", ".", "extensionsForType", "(", "'js'", ")", ".", "map", "(", "(", "extension", ")", "=>", "`", "${", "extension", "}", "`", ")", ";", "return", "walkSync", "(", "dir", ",", "{", "directories", ":", "false", ",", "globs", "}", ")", ".", "map", "(", "file", "=>", "{", "let", "module", "=", "prefix", "+", "'/'", "+", "file", ".", "replace", "(", "EXT_RE", ",", "'.js'", ")", ";", "this", ".", "fileLookup", "[", "module", "]", "=", "path", ".", "join", "(", "dirname", ",", "file", ")", ";", "return", "module", ";", "}", ")", ";", "}", "else", "{", "return", "[", "]", ";", "}", "}" ]
Get paths to include for coverage @param {String} dir Include all js files under this directory. @param {String} prefix The prefix to the ember module ('app', 'dummy' or the name of the addon). @returns {Array<String>} include paths
[ "Get", "paths", "to", "include", "for", "coverage" ]
2cefa0477d6e14be8b7c812367ceddcc51f45303
https://github.com/kategengler/ember-cli-code-coverage/blob/2cefa0477d6e14be8b7c812367ceddcc51f45303/index.js#L198-L211
16,873
kategengler/ember-cli-code-coverage
index.js
function() { var value = process.env[this._getConfig().coverageEnvVar] || false; if (value.toLowerCase) { value = value.toLowerCase(); } return ['true', true].indexOf(value) !== -1; }
javascript
function() { var value = process.env[this._getConfig().coverageEnvVar] || false; if (value.toLowerCase) { value = value.toLowerCase(); } return ['true', true].indexOf(value) !== -1; }
[ "function", "(", ")", "{", "var", "value", "=", "process", ".", "env", "[", "this", ".", "_getConfig", "(", ")", ".", "coverageEnvVar", "]", "||", "false", ";", "if", "(", "value", ".", "toLowerCase", ")", "{", "value", "=", "value", ".", "toLowerCase", "(", ")", ";", "}", "return", "[", "'true'", ",", "true", "]", ".", "indexOf", "(", "value", ")", "!==", "-", "1", ";", "}" ]
Determine whether or not coverage is enabled @returns {Boolean} whether or not coverage is enabled
[ "Determine", "whether", "or", "not", "coverage", "is", "enabled" ]
2cefa0477d6e14be8b7c812367ceddcc51f45303
https://github.com/kategengler/ember-cli-code-coverage/blob/2cefa0477d6e14be8b7c812367ceddcc51f45303/index.js#L225-L233
16,874
kategengler/ember-cli-code-coverage
lib/config.js
config
function config(configPath) { var configDirName = path.dirname(configPath); var configFile = path.resolve(path.join(configDirName, 'coverage.js')); var defaultConfig = getDefaultConfig(); if (fs.existsSync(configFile)) { var projectConfig = require(configFile); return extend({}, defaultConfig, projectConfig); } return defaultConfig; }
javascript
function config(configPath) { var configDirName = path.dirname(configPath); var configFile = path.resolve(path.join(configDirName, 'coverage.js')); var defaultConfig = getDefaultConfig(); if (fs.existsSync(configFile)) { var projectConfig = require(configFile); return extend({}, defaultConfig, projectConfig); } return defaultConfig; }
[ "function", "config", "(", "configPath", ")", "{", "var", "configDirName", "=", "path", ".", "dirname", "(", "configPath", ")", ";", "var", "configFile", "=", "path", ".", "resolve", "(", "path", ".", "join", "(", "configDirName", ",", "'coverage.js'", ")", ")", ";", "var", "defaultConfig", "=", "getDefaultConfig", "(", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "configFile", ")", ")", "{", "var", "projectConfig", "=", "require", "(", "configFile", ")", ";", "return", "extend", "(", "{", "}", ",", "defaultConfig", ",", "projectConfig", ")", ";", "}", "return", "defaultConfig", ";", "}" ]
Get configuration for a project, falling back to default configuration if project does not provide a configuration of its own @param {String} configPath - The path for the configuration of the project @returns {Configuration} configuration to use for project
[ "Get", "configuration", "for", "a", "project", "falling", "back", "to", "default", "configuration", "if", "project", "does", "not", "provide", "a", "configuration", "of", "its", "own" ]
2cefa0477d6e14be8b7c812367ceddcc51f45303
https://github.com/kategengler/ember-cli-code-coverage/blob/2cefa0477d6e14be8b7c812367ceddcc51f45303/lib/config.js#L21-L32
16,875
bpmn-io/moddle-xml
lib/read.js
resolveReferences
function resolveReferences() { var elementsById = context.elementsById; var references = context.references; var i, r; for (i = 0; (r = references[i]); i++) { var element = r.element; var reference = elementsById[r.id]; var property = getModdleDescriptor(element).propertiesByName[r.property]; if (!reference) { context.addWarning({ message: 'unresolved reference <' + r.id + '>', element: r.element, property: r.property, value: r.id }); } if (property.isMany) { var collection = element.get(property.name), idx = collection.indexOf(r); // we replace an existing place holder (idx != -1) or // append to the collection instead if (idx === -1) { idx = collection.length; } if (!reference) { // remove unresolvable reference collection.splice(idx, 1); } else { // add or update reference in collection collection[idx] = reference; } } else { element.set(property.name, reference); } } }
javascript
function resolveReferences() { var elementsById = context.elementsById; var references = context.references; var i, r; for (i = 0; (r = references[i]); i++) { var element = r.element; var reference = elementsById[r.id]; var property = getModdleDescriptor(element).propertiesByName[r.property]; if (!reference) { context.addWarning({ message: 'unresolved reference <' + r.id + '>', element: r.element, property: r.property, value: r.id }); } if (property.isMany) { var collection = element.get(property.name), idx = collection.indexOf(r); // we replace an existing place holder (idx != -1) or // append to the collection instead if (idx === -1) { idx = collection.length; } if (!reference) { // remove unresolvable reference collection.splice(idx, 1); } else { // add or update reference in collection collection[idx] = reference; } } else { element.set(property.name, reference); } } }
[ "function", "resolveReferences", "(", ")", "{", "var", "elementsById", "=", "context", ".", "elementsById", ";", "var", "references", "=", "context", ".", "references", ";", "var", "i", ",", "r", ";", "for", "(", "i", "=", "0", ";", "(", "r", "=", "references", "[", "i", "]", ")", ";", "i", "++", ")", "{", "var", "element", "=", "r", ".", "element", ";", "var", "reference", "=", "elementsById", "[", "r", ".", "id", "]", ";", "var", "property", "=", "getModdleDescriptor", "(", "element", ")", ".", "propertiesByName", "[", "r", ".", "property", "]", ";", "if", "(", "!", "reference", ")", "{", "context", ".", "addWarning", "(", "{", "message", ":", "'unresolved reference <'", "+", "r", ".", "id", "+", "'>'", ",", "element", ":", "r", ".", "element", ",", "property", ":", "r", ".", "property", ",", "value", ":", "r", ".", "id", "}", ")", ";", "}", "if", "(", "property", ".", "isMany", ")", "{", "var", "collection", "=", "element", ".", "get", "(", "property", ".", "name", ")", ",", "idx", "=", "collection", ".", "indexOf", "(", "r", ")", ";", "// we replace an existing place holder (idx != -1) or", "// append to the collection instead", "if", "(", "idx", "===", "-", "1", ")", "{", "idx", "=", "collection", ".", "length", ";", "}", "if", "(", "!", "reference", ")", "{", "// remove unresolvable reference", "collection", ".", "splice", "(", "idx", ",", "1", ")", ";", "}", "else", "{", "// add or update reference in collection", "collection", "[", "idx", "]", "=", "reference", ";", "}", "}", "else", "{", "element", ".", "set", "(", "property", ".", "name", ",", "reference", ")", ";", "}", "}", "}" ]
Resolve collected references on parse end.
[ "Resolve", "collected", "references", "on", "parse", "end", "." ]
5b66184b6128b399be20951130e0cdf2571f0939
https://github.com/bpmn-io/moddle-xml/blob/5b66184b6128b399be20951130e0cdf2571f0939/lib/read.js#L697-L739
16,876
lwille/node-gphoto2
examples/public/js/dat.gui.js
function() { if (common.isUndefined(SAVE_DIALOGUE)) { SAVE_DIALOGUE = new CenteredDiv(); SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents; } if (this.parent) { throw new Error("You can only call remember on a top level GUI."); } var _this = this; common.each(Array.prototype.slice.call(arguments), function(object) { if (_this.__rememberedObjects.length == 0) { addSaveMenu(_this); } if (_this.__rememberedObjects.indexOf(object) == -1) { _this.__rememberedObjects.push(object); } }); if (this.autoPlace) { // Set save row width setWidth(this, this.width); } }
javascript
function() { if (common.isUndefined(SAVE_DIALOGUE)) { SAVE_DIALOGUE = new CenteredDiv(); SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents; } if (this.parent) { throw new Error("You can only call remember on a top level GUI."); } var _this = this; common.each(Array.prototype.slice.call(arguments), function(object) { if (_this.__rememberedObjects.length == 0) { addSaveMenu(_this); } if (_this.__rememberedObjects.indexOf(object) == -1) { _this.__rememberedObjects.push(object); } }); if (this.autoPlace) { // Set save row width setWidth(this, this.width); } }
[ "function", "(", ")", "{", "if", "(", "common", ".", "isUndefined", "(", "SAVE_DIALOGUE", ")", ")", "{", "SAVE_DIALOGUE", "=", "new", "CenteredDiv", "(", ")", ";", "SAVE_DIALOGUE", ".", "domElement", ".", "innerHTML", "=", "saveDialogueContents", ";", "}", "if", "(", "this", ".", "parent", ")", "{", "throw", "new", "Error", "(", "\"You can only call remember on a top level GUI.\"", ")", ";", "}", "var", "_this", "=", "this", ";", "common", ".", "each", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ",", "function", "(", "object", ")", "{", "if", "(", "_this", ".", "__rememberedObjects", ".", "length", "==", "0", ")", "{", "addSaveMenu", "(", "_this", ")", ";", "}", "if", "(", "_this", ".", "__rememberedObjects", ".", "indexOf", "(", "object", ")", "==", "-", "1", ")", "{", "_this", ".", "__rememberedObjects", ".", "push", "(", "object", ")", ";", "}", "}", ")", ";", "if", "(", "this", ".", "autoPlace", ")", "{", "// Set save row width", "setWidth", "(", "this", ",", "this", ".", "width", ")", ";", "}", "}" ]
Mark objects for saving. The order of these objects cannot change as the GUI grows. When remembering new objects, append them to the end of the list. @param {Object...} objects @throws {Error} if not called on a top level GUI. @instance
[ "Mark", "objects", "for", "saving", ".", "The", "order", "of", "these", "objects", "cannot", "change", "as", "the", "GUI", "grows", ".", "When", "remembering", "new", "objects", "append", "them", "to", "the", "end", "of", "the", "list", "." ]
99bef4a5575437a4f6a987c7e34a99c6ac667236
https://github.com/lwille/node-gphoto2/blob/99bef4a5575437a4f6a987c7e34a99c6ac667236/examples/public/js/dat.gui.js#L2147-L2174
16,877
lwille/node-gphoto2
examples/public/js/dat.gui.js
addRow
function addRow(gui, dom, liBefore) { var li = document.createElement('li'); if (dom) li.appendChild(dom); if (liBefore) { gui.__ul.insertBefore(li, params.before); } else { gui.__ul.appendChild(li); } gui.onResize(); return li; }
javascript
function addRow(gui, dom, liBefore) { var li = document.createElement('li'); if (dom) li.appendChild(dom); if (liBefore) { gui.__ul.insertBefore(li, params.before); } else { gui.__ul.appendChild(li); } gui.onResize(); return li; }
[ "function", "addRow", "(", "gui", ",", "dom", ",", "liBefore", ")", "{", "var", "li", "=", "document", ".", "createElement", "(", "'li'", ")", ";", "if", "(", "dom", ")", "li", ".", "appendChild", "(", "dom", ")", ";", "if", "(", "liBefore", ")", "{", "gui", ".", "__ul", ".", "insertBefore", "(", "li", ",", "params", ".", "before", ")", ";", "}", "else", "{", "gui", ".", "__ul", ".", "appendChild", "(", "li", ")", ";", "}", "gui", ".", "onResize", "(", ")", ";", "return", "li", ";", "}" ]
Add a row to the end of the GUI or before another row. @param gui @param [dom] If specified, inserts the dom content in the new row @param [liBefore] If specified, places the new row before another row
[ "Add", "a", "row", "to", "the", "end", "of", "the", "GUI", "or", "before", "another", "row", "." ]
99bef4a5575437a4f6a987c7e34a99c6ac667236
https://github.com/lwille/node-gphoto2/blob/99bef4a5575437a4f6a987c7e34a99c6ac667236/examples/public/js/dat.gui.js#L2337-L2347
16,878
aeternity/aepp-sdk-js
es/channel/index.js
update
function update (from, to, amount, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.new', params: { from, to, amount } }) return { handler: handlers.awaitingOffChainTx, state: { resolve, reject, sign } } } ) }) }
javascript
function update (from, to, amount, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.new', params: { from, to, amount } }) return { handler: handlers.awaitingOffChainTx, state: { resolve, reject, sign } } } ) }) }
[ "function", "update", "(", "from", ",", "to", ",", "amount", ",", "sign", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "enqueueAction", "(", "this", ",", "(", "channel", ",", "state", ")", "=>", "state", ".", "handler", "===", "handlers", ".", "channelOpen", ",", "(", "channel", ",", "state", ")", "=>", "{", "send", "(", "channel", ",", "{", "jsonrpc", ":", "'2.0'", ",", "method", ":", "'channels.update.new'", ",", "params", ":", "{", "from", ",", "to", ",", "amount", "}", "}", ")", "return", "{", "handler", ":", "handlers", ".", "awaitingOffChainTx", ",", "state", ":", "{", "resolve", ",", "reject", ",", "sign", "}", "}", "}", ")", "}", ")", "}" ]
Trigger a transfer update The transfer update is moving tokens from one channel account to another. The update is a change to be applied on top of the latest state. Sender and receiver are the channel parties. Both the initiator and responder can take those roles. Any public key outside of the channel is considered invalid. @param {String} from - Sender's public address @param {String} to - Receiver's public address @param {Number} amount - Transaction amount @param {Function} sign - Function which verifies and signs offchain transaction @return {Promise<Object>} @example channel.update( 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH', 'ak_V6an1xhec1xVaAhLuak7QoEbi6t7w5hEtYWp9bMKaJ19i6A9E', 10, async (tx) => await account.signTransaction(tx) ).then(({ accepted, signedTx }) => if (accepted) { console.log('Update has been accepted') } )
[ "Trigger", "a", "transfer", "update" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L125-L147
16,879
aeternity/aepp-sdk-js
es/channel/index.js
shutdown
function shutdown (sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.shutdown', params: {} }) return { handler: handlers.awaitingShutdownTx, state: { sign, resolve, reject } } } ) }) }
javascript
function shutdown (sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.shutdown', params: {} }) return { handler: handlers.awaitingShutdownTx, state: { sign, resolve, reject } } } ) }) }
[ "function", "shutdown", "(", "sign", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "enqueueAction", "(", "this", ",", "(", "channel", ",", "state", ")", "=>", "state", ".", "handler", "===", "handlers", ".", "channelOpen", ",", "(", "channel", ",", "state", ")", "=>", "{", "send", "(", "channel", ",", "{", "jsonrpc", ":", "'2.0'", ",", "method", ":", "'channels.shutdown'", ",", "params", ":", "{", "}", "}", ")", "return", "{", "handler", ":", "handlers", ".", "awaitingShutdownTx", ",", "state", ":", "{", "sign", ",", "resolve", ",", "reject", "}", "}", "}", ")", "}", ")", "}" ]
Trigger mutual close At any moment after the channel is opened, a closing procedure can be triggered. This can be done by either of the parties. The process is similar to the off-chain updates. @param {Function} sign - Function which verifies and signs mutual close transaction @return {Promise<String>} @example channel.shutdown( async (tx) => await account.signTransaction(tx) ).then(tx => console.log('on_chain_tx', tx))
[ "Trigger", "mutual", "close" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L242-L260
16,880
aeternity/aepp-sdk-js
es/channel/index.js
withdraw
function withdraw (amount, sign, { onOnChainTx, onOwnWithdrawLocked, onWithdrawLocked } = {}) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.withdraw', params: { amount } }) return { handler: handlers.awaitingWithdrawTx, state: { sign, resolve, reject, onOnChainTx, onOwnWithdrawLocked, onWithdrawLocked } } } ) }) }
javascript
function withdraw (amount, sign, { onOnChainTx, onOwnWithdrawLocked, onWithdrawLocked } = {}) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.withdraw', params: { amount } }) return { handler: handlers.awaitingWithdrawTx, state: { sign, resolve, reject, onOnChainTx, onOwnWithdrawLocked, onWithdrawLocked } } } ) }) }
[ "function", "withdraw", "(", "amount", ",", "sign", ",", "{", "onOnChainTx", ",", "onOwnWithdrawLocked", ",", "onWithdrawLocked", "}", "=", "{", "}", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "enqueueAction", "(", "this", ",", "(", "channel", ",", "state", ")", "=>", "state", ".", "handler", "===", "handlers", ".", "channelOpen", ",", "(", "channel", ",", "state", ")", "=>", "{", "send", "(", "channel", ",", "{", "jsonrpc", ":", "'2.0'", ",", "method", ":", "'channels.withdraw'", ",", "params", ":", "{", "amount", "}", "}", ")", "return", "{", "handler", ":", "handlers", ".", "awaitingWithdrawTx", ",", "state", ":", "{", "sign", ",", "resolve", ",", "reject", ",", "onOnChainTx", ",", "onOwnWithdrawLocked", ",", "onWithdrawLocked", "}", "}", "}", ")", "}", ")", "}" ]
Withdraw tokens from the channel After the channel had been opened any of the participants can initiate a withdrawal. The process closely resembles the update. The most notable difference is that the transaction has been co-signed: it is channel_withdraw_tx and after the procedure is finished - it is being posted on-chain. Any of the participants can initiate a withdrawal. The only requirements are: - Channel is already opened - No off-chain update/deposit/withdrawal is currently being performed - Channel is not being closed or in a solo closing state - The withdrawal amount must be equal to or greater than zero, and cannot exceed the available balance on the channel (minus the channel_reserve) After the other party had signed the withdraw transaction, the transaction is posted on-chain and onOnChainTx callback is called with on-chain transaction as first argument. After computing transaction hash it can be tracked on the chain: entering the mempool, block inclusion and a number of confirmations. After the minimum_depth block confirmations onOwnWithdrawLocked callback is called (without any arguments). When the other party had confirmed that the block height needed is reached onWithdrawLocked callback is called (without any arguments). @param {Number} amount - Amount of tokens to withdraw @param {Function} sign - Function which verifies and signs withdraw transaction @param {Object} [callbacks] @param {Function} [callbacks.onOnChainTx] - Called when withdraw transaction has been posted on chain @param {Function} [callbacks.onOwnWithdrawLocked] @param {Function} [callbacks.onWithdrawLocked] @return {Promise<Object>} @example channel.withdraw( 100, async (tx) => await account.signTransaction(tx), { onOnChainTx: (tx) => console.log('on_chain_tx', tx) } ).then(({ accepted, signedTx }) => { if (accepted) { console.log('Withdrawal has been accepted') } else { console.log('Withdrawal has been rejected') } })
[ "Withdraw", "tokens", "from", "the", "channel" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L308-L329
16,881
aeternity/aepp-sdk-js
es/channel/index.js
deposit
function deposit (amount, sign, { onOnChainTx, onOwnDepositLocked, onDepositLocked } = {}) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.deposit', params: { amount } }) return { handler: handlers.awaitingDepositTx, state: { sign, resolve, reject, onOnChainTx, onOwnDepositLocked, onDepositLocked } } } ) }) }
javascript
function deposit (amount, sign, { onOnChainTx, onOwnDepositLocked, onDepositLocked } = {}) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.deposit', params: { amount } }) return { handler: handlers.awaitingDepositTx, state: { sign, resolve, reject, onOnChainTx, onOwnDepositLocked, onDepositLocked } } } ) }) }
[ "function", "deposit", "(", "amount", ",", "sign", ",", "{", "onOnChainTx", ",", "onOwnDepositLocked", ",", "onDepositLocked", "}", "=", "{", "}", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "enqueueAction", "(", "this", ",", "(", "channel", ",", "state", ")", "=>", "state", ".", "handler", "===", "handlers", ".", "channelOpen", ",", "(", "channel", ",", "state", ")", "=>", "{", "send", "(", "channel", ",", "{", "jsonrpc", ":", "'2.0'", ",", "method", ":", "'channels.deposit'", ",", "params", ":", "{", "amount", "}", "}", ")", "return", "{", "handler", ":", "handlers", ".", "awaitingDepositTx", ",", "state", ":", "{", "sign", ",", "resolve", ",", "reject", ",", "onOnChainTx", ",", "onOwnDepositLocked", ",", "onDepositLocked", "}", "}", "}", ")", "}", ")", "}" ]
Deposit tokens into the channel After the channel had been opened any of the participants can initiate a deposit. The process closely resembles the update. The most notable difference is that the transaction has been co-signed: it is channel_deposit_tx and after the procedure is finished - it is being posted on-chain. Any of the participants can initiate a deposit. The only requirements are: - Channel is already opened - No off-chain update/deposit/withdrawal is currently being performed - Channel is not being closed or in a solo closing state - The deposit amount must be equal to or greater than zero, and cannot exceed the available balance on the channel (minus the channel_reserve) After the other party had signed the deposit transaction, the transaction is posted on-chain and onOnChainTx callback is called with on-chain transaction as first argument. After computing transaction hash it can be tracked on the chain: entering the mempool, block inclusion and a number of confirmations. After the minimum_depth block confirmations onOwnDepositLocked callback is called (without any arguments). When the other party had confirmed that the block height needed is reached onDepositLocked callback is called (without any arguments). @param {Number} amount - Amount of tokens to deposit @param {Function} sign - Function which verifies and signs deposit transaction @param {Object} [callbacks] @param {Function} [callbacks.onOnChainTx] - Called when deposit transaction has been posted on chain @param {Function} [callbacks.onOwnDepositLocked] @param {Function} [callbacks.onDepositLocked] @return {Promise<Object>} @example channel.deposit( 100, async (tx) => await account.signTransaction(tx), { onOnChainTx: (tx) => console.log('on_chain_tx', tx) } ).then(({ accepted, state }) => { if (accepted) { console.log('Deposit has been accepted') console.log('The new state is:', state) } else { console.log('Deposit has been rejected') } })
[ "Deposit", "tokens", "into", "the", "channel" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L378-L399
16,882
aeternity/aepp-sdk-js
es/channel/index.js
createContract
function createContract ({ code, callData, deposit, vmVersion, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.new_contract', params: { code, call_data: callData, deposit, vm_version: vmVersion, abi_version: abiVersion } }) return { handler: handlers.awaitingNewContractTx, state: { sign, resolve, reject } } } ) }) }
javascript
function createContract ({ code, callData, deposit, vmVersion, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.new_contract', params: { code, call_data: callData, deposit, vm_version: vmVersion, abi_version: abiVersion } }) return { handler: handlers.awaitingNewContractTx, state: { sign, resolve, reject } } } ) }) }
[ "function", "createContract", "(", "{", "code", ",", "callData", ",", "deposit", ",", "vmVersion", ",", "abiVersion", "}", ",", "sign", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "enqueueAction", "(", "this", ",", "(", "channel", ",", "state", ")", "=>", "state", ".", "handler", "===", "handlers", ".", "channelOpen", ",", "(", "channel", ",", "state", ")", "=>", "{", "send", "(", "channel", ",", "{", "jsonrpc", ":", "'2.0'", ",", "method", ":", "'channels.update.new_contract'", ",", "params", ":", "{", "code", ",", "call_data", ":", "callData", ",", "deposit", ",", "vm_version", ":", "vmVersion", ",", "abi_version", ":", "abiVersion", "}", "}", ")", "return", "{", "handler", ":", "handlers", ".", "awaitingNewContractTx", ",", "state", ":", "{", "sign", ",", "resolve", ",", "reject", "}", "}", "}", ")", "}", ")", "}" ]
Trigger create contract update The create contract update is creating a contract inside the channel's internal state tree. The update is a change to be applied on top of the latest state. That would create a contract with the poster being the owner of it. Poster commits initially a deposit amount of tokens to the new contract. @param {Object} options @param {String} options.code - Api encoded compiled AEVM byte code @param {String} options.callData - Api encoded compiled AEVM call data for the code @param {Number} options.deposit - Initial amount the owner of the contract commits to it @param {Number} options.vmVersion - Version of the AEVM @param {Number} options.abiVersion - Version of the ABI @param {Function} sign - Function which verifies and signs create contract transaction @return {Promise<Object>} @example channel.createContract({ code: 'cb_HKtpipK4aCgYb17wZ...', callData: 'cb_1111111111111111...', deposit: 10, vmVersion: 3, abiVersion: 1 }).then(({ accepted, signedTx, address }) => { if (accepted) { console.log('New contract has been created') console.log('Contract address:', address) } else { console.log('New contract has been rejected') } })
[ "Trigger", "create", "contract", "update" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L433-L461
16,883
aeternity/aepp-sdk-js
es/channel/index.js
callContract
function callContract ({ amount, callData, contract, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.call_contract', params: { amount, call_data: callData, contract, abi_version: abiVersion } }) return { handler: handlers.awaitingCallContractUpdateTx, state: { resolve, reject, sign } } } ) }) }
javascript
function callContract ({ amount, callData, contract, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.call_contract', params: { amount, call_data: callData, contract, abi_version: abiVersion } }) return { handler: handlers.awaitingCallContractUpdateTx, state: { resolve, reject, sign } } } ) }) }
[ "function", "callContract", "(", "{", "amount", ",", "callData", ",", "contract", ",", "abiVersion", "}", ",", "sign", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "enqueueAction", "(", "this", ",", "(", "channel", ",", "state", ")", "=>", "state", ".", "handler", "===", "handlers", ".", "channelOpen", ",", "(", "channel", ",", "state", ")", "=>", "{", "send", "(", "channel", ",", "{", "jsonrpc", ":", "'2.0'", ",", "method", ":", "'channels.update.call_contract'", ",", "params", ":", "{", "amount", ",", "call_data", ":", "callData", ",", "contract", ",", "abi_version", ":", "abiVersion", "}", "}", ")", "return", "{", "handler", ":", "handlers", ".", "awaitingCallContractUpdateTx", ",", "state", ":", "{", "resolve", ",", "reject", ",", "sign", "}", "}", "}", ")", "}", ")", "}" ]
Trigger call a contract update The call contract update is calling a preexisting contract inside the channel's internal state tree. The update is a change to be applied on top of the latest state. That would call a contract with the poster being the caller of it. Poster commits an amount of tokens to the contract. The call would also create a call object inside the channel state tree. It contains the result of the contract call. It is worth mentioning that the gas is not consumed, because this is an off-chain contract call. It would be consumed if it were a on-chain one. This could happen if a call with a similar computation amount is to be forced on-chain. @param {Object} options @param {String} [options.amount] - Amount the caller of the contract commits to it @param {String} [options.callData] - ABI encoded compiled AEVM call data for the code @param {Number} [options.contract] - Address of the contract to call @param {Number} [options.abiVersion] - Version of the ABI @param {Function} sign - Function which verifies and signs contract call transaction @return {Promise<Object>} @example channel.callContract({ contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa', callData: 'cb_1111111111111111...', amount: 0, abiVersion: 1 }).then(({ accepted, signedTx }) => { if (accepted) { console.log('Contract called succesfully') } else { console.log('Contract call has been rejected') } })
[ "Trigger", "call", "a", "contract", "update" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L499-L522
16,884
aeternity/aepp-sdk-js
es/channel/index.js
callContractStatic
async function callContractStatic ({ amount, callData, contract, abiVersion }) { return snakeToPascalObjKeys(await call(this, 'channels.dry_run.call_contract', { amount, call_data: callData, contract, abi_version: abiVersion })) }
javascript
async function callContractStatic ({ amount, callData, contract, abiVersion }) { return snakeToPascalObjKeys(await call(this, 'channels.dry_run.call_contract', { amount, call_data: callData, contract, abi_version: abiVersion })) }
[ "async", "function", "callContractStatic", "(", "{", "amount", ",", "callData", ",", "contract", ",", "abiVersion", "}", ")", "{", "return", "snakeToPascalObjKeys", "(", "await", "call", "(", "this", ",", "'channels.dry_run.call_contract'", ",", "{", "amount", ",", "call_data", ":", "callData", ",", "contract", ",", "abi_version", ":", "abiVersion", "}", ")", ")", "}" ]
Call contract using dry-run In order to get the result of a potential contract call, one might need to dry-run a contract call. It takes the exact same arguments as a call would and returns the call object. The call is executed in the channel's state but it does not impact the state whatsoever. It uses as an environment the latest channel's state and the current top of the blockchain as seen by the node. @param {Object} options @param {String} [options.amount] - Amount the caller of the contract commits to it @param {String} [options.callData] - ABI encoded compiled AEVM call data for the code @param {Number} [options.contract] - Address of the contract to call @param {Number} [options.abiVersion] - Version of the ABI @return {Promise<Object>} @example channel.callContractStatic({ contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa', callData: 'cb_1111111111111111...', amount: 0, abiVersion: 1 }).then(({ returnValue, gasUsed }) => { console.log('Returned value:', returnValue) console.log('Gas used:', gasUsed) })
[ "Call", "contract", "using", "dry", "-", "run" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L551-L558
16,885
aeternity/aepp-sdk-js
es/channel/index.js
getContractCall
async function getContractCall ({ caller, contract, round }) { return snakeToPascalObjKeys(await call(this, 'channels.get.contract_call', { caller, contract, round })) }
javascript
async function getContractCall ({ caller, contract, round }) { return snakeToPascalObjKeys(await call(this, 'channels.get.contract_call', { caller, contract, round })) }
[ "async", "function", "getContractCall", "(", "{", "caller", ",", "contract", ",", "round", "}", ")", "{", "return", "snakeToPascalObjKeys", "(", "await", "call", "(", "this", ",", "'channels.get.contract_call'", ",", "{", "caller", ",", "contract", ",", "round", "}", ")", ")", "}" ]
Get contract call result The combination of a caller, contract and a round of execution determines the contract call. Providing an incorrect set of those results in an error response. @param {Object} options @param {String} [options.caller] - Address of contract caller @param {String} [options.contract] - Address of the contract @param {Number} [options.round] - Round when contract was called @return {Promise<Object>} @example channel.getContractCall({ caller: 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH', contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa', round: 3 }).then(({ returnType, returnValue }) => { if (returnType === 'ok') console.log(returnValue) })
[ "Get", "contract", "call", "result" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L579-L581
16,886
aeternity/aepp-sdk-js
es/channel/index.js
getContractState
async function getContractState (contract) { const result = await call(this, 'channels.get.contract', { pubkey: contract }) return snakeToPascalObjKeys({ ...result, contract: snakeToPascalObjKeys(result.contract) }) }
javascript
async function getContractState (contract) { const result = await call(this, 'channels.get.contract', { pubkey: contract }) return snakeToPascalObjKeys({ ...result, contract: snakeToPascalObjKeys(result.contract) }) }
[ "async", "function", "getContractState", "(", "contract", ")", "{", "const", "result", "=", "await", "call", "(", "this", ",", "'channels.get.contract'", ",", "{", "pubkey", ":", "contract", "}", ")", "return", "snakeToPascalObjKeys", "(", "{", "...", "result", ",", "contract", ":", "snakeToPascalObjKeys", "(", "result", ".", "contract", ")", "}", ")", "}" ]
Get contract latest state @param {String} contract - Address of the contract @return {Promise<Object>} @example channel.getContractState( 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa' ).then(({ contract }) => { console.log('deposit:', contract.deposit) })
[ "Get", "contract", "latest", "state" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L594-L600
16,887
aeternity/aepp-sdk-js
es/channel/index.js
cleanContractCalls
function cleanContractCalls () { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.clean_contract_calls', params: {} }) return { handler: handlers.awaitingCallsPruned, state: { resolve, reject } } } ) }) }
javascript
function cleanContractCalls () { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.clean_contract_calls', params: {} }) return { handler: handlers.awaitingCallsPruned, state: { resolve, reject } } } ) }) }
[ "function", "cleanContractCalls", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "enqueueAction", "(", "this", ",", "(", "channel", ",", "state", ")", "=>", "state", ".", "handler", "===", "handlers", ".", "channelOpen", ",", "(", "channel", ",", "state", ")", "=>", "{", "send", "(", "channel", ",", "{", "jsonrpc", ":", "'2.0'", ",", "method", ":", "'channels.clean_contract_calls'", ",", "params", ":", "{", "}", "}", ")", "return", "{", "handler", ":", "handlers", ".", "awaitingCallsPruned", ",", "state", ":", "{", "resolve", ",", "reject", "}", "}", "}", ")", "}", ")", "}" ]
Clean up all locally stored contract calls Contract calls are kept locally in order for the participant to be able to look them up. They consume memory and in order for the participant to free it - one can prune all messages. This cleans up all locally stored contract calls and those will no longer be available for fetching and inspection. @return {Promise}
[ "Clean", "up", "all", "locally", "stored", "contract", "calls" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L612-L630
16,888
aeternity/aepp-sdk-js
es/channel/index.js
sendMessage
function sendMessage (message, recipient) { let info = message if (typeof message === 'object') { info = JSON.stringify(message) } enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.message', params: { info, to: recipient } }) return state } ) }
javascript
function sendMessage (message, recipient) { let info = message if (typeof message === 'object') { info = JSON.stringify(message) } enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.message', params: { info, to: recipient } }) return state } ) }
[ "function", "sendMessage", "(", "message", ",", "recipient", ")", "{", "let", "info", "=", "message", "if", "(", "typeof", "message", "===", "'object'", ")", "{", "info", "=", "JSON", ".", "stringify", "(", "message", ")", "}", "enqueueAction", "(", "this", ",", "(", "channel", ",", "state", ")", "=>", "state", ".", "handler", "===", "handlers", ".", "channelOpen", ",", "(", "channel", ",", "state", ")", "=>", "{", "send", "(", "channel", ",", "{", "jsonrpc", ":", "'2.0'", ",", "method", ":", "'channels.message'", ",", "params", ":", "{", "info", ",", "to", ":", "recipient", "}", "}", ")", "return", "state", "}", ")", "}" ]
Send generic message If message is an object it will be serialized into JSON string before sending. If there is ongoing update that has not yet been finished the message will be sent after that update is finalized. @param {String|Object} message @param {String} recipient - Address of the recipient @example channel.sendMessage( 'hello world', 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH' )
[ "Send", "generic", "message" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/channel/index.js#L648-L661
16,889
aeternity/aepp-sdk-js
es/utils/swagger.js
expandPath
function expandPath (path, replacements) { return R.toPairs(replacements).reduce((path, [key, value]) => path.replace(`{${key}}`, value), path) }
javascript
function expandPath (path, replacements) { return R.toPairs(replacements).reduce((path, [key, value]) => path.replace(`{${key}}`, value), path) }
[ "function", "expandPath", "(", "path", ",", "replacements", ")", "{", "return", "R", ".", "toPairs", "(", "replacements", ")", ".", "reduce", "(", "(", "path", ",", "[", "key", ",", "value", "]", ")", "=>", "path", ".", "replace", "(", "`", "${", "key", "}", "`", ",", "value", ")", ",", "path", ")", "}" ]
Perform path string interpolation @static @rtype (path: String, replacements: Object) => String @param {String} s - String to convert @return {String} Converted string
[ "Perform", "path", "string", "interpolation" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/swagger.js#L39-L41
16,890
aeternity/aepp-sdk-js
es/utils/swagger.js
conform
function conform (value, spec, types) { return (conformTypes[conformDispatch(spec)] || (() => { throw Object.assign(Error('Unsupported type'), { spec }) }))(value, spec, types) }
javascript
function conform (value, spec, types) { return (conformTypes[conformDispatch(spec)] || (() => { throw Object.assign(Error('Unsupported type'), { spec }) }))(value, spec, types) }
[ "function", "conform", "(", "value", ",", "spec", ",", "types", ")", "{", "return", "(", "conformTypes", "[", "conformDispatch", "(", "spec", ")", "]", "||", "(", "(", ")", "=>", "{", "throw", "Object", ".", "assign", "(", "Error", "(", "'Unsupported type'", ")", ",", "{", "spec", "}", ")", "}", ")", ")", "(", "value", ",", "spec", ",", "types", ")", "}" ]
Conform `value` against its `spec` @static @rtype (value: Any, spec: Object, types: Object) => Any, throws: Error @param {Object} value - Value to conform (validate and transform) @param {Object} spec - Specification object @param {Object} types - Types specification @return {Object} Conformed value
[ "Conform", "value", "against", "its", "spec" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/swagger.js#L187-L191
16,891
aeternity/aepp-sdk-js
es/utils/swagger.js
classifyParameters
function classifyParameters (parameters) { const { req, opts } = R.groupBy(p => p.required ? 'req' : 'opts', parameters) const { path, query, body } = R.groupBy(p => p.in, parameters) return { pathArgs: R.pluck('name', path || []), queryArgs: R.pluck('name', query || []), bodyArgs: R.pluck('name', body || []), req: req || [], opts: opts || [] } }
javascript
function classifyParameters (parameters) { const { req, opts } = R.groupBy(p => p.required ? 'req' : 'opts', parameters) const { path, query, body } = R.groupBy(p => p.in, parameters) return { pathArgs: R.pluck('name', path || []), queryArgs: R.pluck('name', query || []), bodyArgs: R.pluck('name', body || []), req: req || [], opts: opts || [] } }
[ "function", "classifyParameters", "(", "parameters", ")", "{", "const", "{", "req", ",", "opts", "}", "=", "R", ".", "groupBy", "(", "p", "=>", "p", ".", "required", "?", "'req'", ":", "'opts'", ",", "parameters", ")", "const", "{", "path", ",", "query", ",", "body", "}", "=", "R", ".", "groupBy", "(", "p", "=>", "p", ".", "in", ",", "parameters", ")", "return", "{", "pathArgs", ":", "R", ".", "pluck", "(", "'name'", ",", "path", "||", "[", "]", ")", ",", "queryArgs", ":", "R", ".", "pluck", "(", "'name'", ",", "query", "||", "[", "]", ")", ",", "bodyArgs", ":", "R", ".", "pluck", "(", "'name'", ",", "body", "||", "[", "]", ")", ",", "req", ":", "req", "||", "[", "]", ",", "opts", ":", "opts", "||", "[", "]", "}", "}" ]
Classify given `parameters` @rtype (parameters: [{required: Boolean, in: String}...]) => {pathArgs: [...Object], queryArgs: [...Object], bodyArgs: [...Object], req: [...Object], opts: [...Object]} @param {Object[]} parameters - Parameters to classify @return {Object[]} Classified parameters
[ "Classify", "given", "parameters" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/swagger.js#L215-L226
16,892
aeternity/aepp-sdk-js
es/utils/swagger.js
pascalizeParameters
function pascalizeParameters (parameters) { return parameters.map(o => R.assoc('name', snakeToPascal(o.name), o)) }
javascript
function pascalizeParameters (parameters) { return parameters.map(o => R.assoc('name', snakeToPascal(o.name), o)) }
[ "function", "pascalizeParameters", "(", "parameters", ")", "{", "return", "parameters", ".", "map", "(", "o", "=>", "R", ".", "assoc", "(", "'name'", ",", "snakeToPascal", "(", "o", ".", "name", ")", ",", "o", ")", ")", "}" ]
Convert `name` attributes in `parameters` from snake_case to PascalCase @rtype (parameters: [{name: String}...]) => [{name: String}...] @param {Object[]} parameters - Parameters to pascalize @return {Object[]} Pascalized parameters
[ "Convert", "name", "attributes", "in", "parameters", "from", "snake_case", "to", "PascalCase" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/swagger.js#L234-L236
16,893
aeternity/aepp-sdk-js
es/utils/swagger.js
operationSignature
function operationSignature (name, req, opts) { const args = req.length ? `${R.join(', ', R.pluck('name', req))}` : null const opt = opts.length ? `{${R.join(', ', R.pluck('name', opts))}}` : null return `${name} (${R.join(', ', [args, opt].filter(R.identity))})` }
javascript
function operationSignature (name, req, opts) { const args = req.length ? `${R.join(', ', R.pluck('name', req))}` : null const opt = opts.length ? `{${R.join(', ', R.pluck('name', opts))}}` : null return `${name} (${R.join(', ', [args, opt].filter(R.identity))})` }
[ "function", "operationSignature", "(", "name", ",", "req", ",", "opts", ")", "{", "const", "args", "=", "req", ".", "length", "?", "`", "${", "R", ".", "join", "(", "', '", ",", "R", ".", "pluck", "(", "'name'", ",", "req", ")", ")", "}", "`", ":", "null", "const", "opt", "=", "opts", ".", "length", "?", "`", "${", "R", ".", "join", "(", "', '", ",", "R", ".", "pluck", "(", "'name'", ",", "opts", ")", ")", "}", "`", ":", "null", "return", "`", "${", "name", "}", "${", "R", ".", "join", "(", "', '", ",", "[", "args", ",", "opt", "]", ".", "filter", "(", "R", ".", "identity", ")", ")", "}", "`", "}" ]
Obtain readable signature for operation @rtype (name: String, req: [...Object], opts: [...Object]) => Object @param {String} name - Name of operation @param {Object[]} req - Required parameters to operation @param {Object[]} opts - Optional parameters to operation @return {String} Signature
[ "Obtain", "readable", "signature", "for", "operation" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/swagger.js#L292-L297
16,894
aeternity/aepp-sdk-js
es/utils/swagger.js
destructureClientError
function destructureClientError (error) { const { method, url } = error.config const { status, data } = error.response const reason = R.has('reason', data) ? data.reason : R.toString(data) return `${method.toUpperCase()} to ${url} failed with ${status}: ${reason}` }
javascript
function destructureClientError (error) { const { method, url } = error.config const { status, data } = error.response const reason = R.has('reason', data) ? data.reason : R.toString(data) return `${method.toUpperCase()} to ${url} failed with ${status}: ${reason}` }
[ "function", "destructureClientError", "(", "error", ")", "{", "const", "{", "method", ",", "url", "}", "=", "error", ".", "config", "const", "{", "status", ",", "data", "}", "=", "error", ".", "response", "const", "reason", "=", "R", ".", "has", "(", "'reason'", ",", "data", ")", "?", "data", ".", "reason", ":", "R", ".", "toString", "(", "data", ")", "return", "`", "${", "method", ".", "toUpperCase", "(", ")", "}", "${", "url", "}", "${", "status", "}", "${", "reason", "}", "`", "}" ]
Destructure HTTP client `error` @rtype (error: Error) => String @param {Error} error @return {String}
[ "Destructure", "HTTP", "client", "error" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/swagger.js#L320-L326
16,895
aeternity/aepp-sdk-js
es/ae/oracle.js
postQueryToOracle
async function postQueryToOracle (oracleId, query, options = {}) { const opt = R.merge(this.Ae.defaults, options) const senderId = await this.address() const { tx: oracleRegisterTx, queryId } = await this.oraclePostQueryTx(R.merge(opt, { oracleId, senderId, query })) return { ...(await this.send(oracleRegisterTx, opt)), ...(await (await getOracleObject.bind(this)(oracleId)).getQuery(queryId)) } }
javascript
async function postQueryToOracle (oracleId, query, options = {}) { const opt = R.merge(this.Ae.defaults, options) const senderId = await this.address() const { tx: oracleRegisterTx, queryId } = await this.oraclePostQueryTx(R.merge(opt, { oracleId, senderId, query })) return { ...(await this.send(oracleRegisterTx, opt)), ...(await (await getOracleObject.bind(this)(oracleId)).getQuery(queryId)) } }
[ "async", "function", "postQueryToOracle", "(", "oracleId", ",", "query", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "senderId", "=", "await", "this", ".", "address", "(", ")", "const", "{", "tx", ":", "oracleRegisterTx", ",", "queryId", "}", "=", "await", "this", ".", "oraclePostQueryTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "oracleId", ",", "senderId", ",", "query", "}", ")", ")", "return", "{", "...", "(", "await", "this", ".", "send", "(", "oracleRegisterTx", ",", "opt", ")", ")", ",", "...", "(", "await", "(", "await", "getOracleObject", ".", "bind", "(", "this", ")", "(", "oracleId", ")", ")", ".", "getQuery", "(", "queryId", ")", ")", "}", "}" ]
Post query to oracle @alias module:@aeternity/aepp-sdk/es/ae/oracle @instance @function @category async @param {String} oracleId Oracle public key @param {String} query Oracle query object @param {Object} [options={}] @param {String|Number} [options.queryTtl] queryTtl Oracle query time to leave @param {String|Number} [options.responseTtl] queryFee Oracle query response time to leave @param {String|Number} [options.queryFee] queryFee Oracle query fee @param {Number} [options.fee] fee Transaction fee @param {Number} [options.ttl] Transaction time to leave @return {Promise<Object>} Query object
[ "Post", "query", "to", "oracle" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/oracle.js#L155-L168
16,896
aeternity/aepp-sdk-js
es/ae/wallet.js
hello
async function hello () { const id = await Rpc.compose.deepProperties.rpcMethods.hello.call(this) this.rpcSessions[id].address = await this.address() return Promise.resolve(id) }
javascript
async function hello () { const id = await Rpc.compose.deepProperties.rpcMethods.hello.call(this) this.rpcSessions[id].address = await this.address() return Promise.resolve(id) }
[ "async", "function", "hello", "(", ")", "{", "const", "id", "=", "await", "Rpc", ".", "compose", ".", "deepProperties", ".", "rpcMethods", ".", "hello", ".", "call", "(", "this", ")", "this", ".", "rpcSessions", "[", "id", "]", ".", "address", "=", "await", "this", ".", "address", "(", ")", "return", "Promise", ".", "resolve", "(", "id", ")", "}" ]
Confirm client connection attempt and associate new session with currently selected account preset @instance @category async @return {Promise<String>} Session ID
[ "Confirm", "client", "connection", "attempt", "and", "associate", "new", "session", "with", "currently", "selected", "account", "preset" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/wallet.js#L55-L59
16,897
aeternity/aepp-sdk-js
es/account/index.js
signTransaction
async function signTransaction (tx) { const networkId = this.getNetworkId() const rlpBinaryTx = Crypto.decodeBase64Check(Crypto.assertedType(tx, 'tx')) // Prepend `NETWORK_ID` to begin of data binary const txWithNetworkId = Buffer.concat([Buffer.from(networkId), rlpBinaryTx]) const signatures = [await this.sign(txWithNetworkId)] return buildTx({ encodedTx: rlpBinaryTx, signatures }, TX_TYPE.signed).tx }
javascript
async function signTransaction (tx) { const networkId = this.getNetworkId() const rlpBinaryTx = Crypto.decodeBase64Check(Crypto.assertedType(tx, 'tx')) // Prepend `NETWORK_ID` to begin of data binary const txWithNetworkId = Buffer.concat([Buffer.from(networkId), rlpBinaryTx]) const signatures = [await this.sign(txWithNetworkId)] return buildTx({ encodedTx: rlpBinaryTx, signatures }, TX_TYPE.signed).tx }
[ "async", "function", "signTransaction", "(", "tx", ")", "{", "const", "networkId", "=", "this", ".", "getNetworkId", "(", ")", "const", "rlpBinaryTx", "=", "Crypto", ".", "decodeBase64Check", "(", "Crypto", ".", "assertedType", "(", "tx", ",", "'tx'", ")", ")", "// Prepend `NETWORK_ID` to begin of data binary", "const", "txWithNetworkId", "=", "Buffer", ".", "concat", "(", "[", "Buffer", ".", "from", "(", "networkId", ")", ",", "rlpBinaryTx", "]", ")", "const", "signatures", "=", "[", "await", "this", ".", "sign", "(", "txWithNetworkId", ")", "]", "return", "buildTx", "(", "{", "encodedTx", ":", "rlpBinaryTx", ",", "signatures", "}", ",", "TX_TYPE", ".", "signed", ")", ".", "tx", "}" ]
Sign encoded transaction @instance @category async @rtype (tx: String) => tx: Promise[String], throws: Error @param {String} tx - Transaction to sign @return {String} Signed transaction
[ "Sign", "encoded", "transaction" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/account/index.js#L41-L49
16,898
aeternity/aepp-sdk-js
es/ae/index.js
send
async function send (tx, options) { const opt = R.merge(this.Ae.defaults, options) const signed = await this.signTransaction(tx) return this.sendTransaction(signed, opt) }
javascript
async function send (tx, options) { const opt = R.merge(this.Ae.defaults, options) const signed = await this.signTransaction(tx) return this.sendTransaction(signed, opt) }
[ "async", "function", "send", "(", "tx", ",", "options", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "signed", "=", "await", "this", ".", "signTransaction", "(", "tx", ")", "return", "this", ".", "sendTransaction", "(", "signed", ",", "opt", ")", "}" ]
Sign and post a transaction to the chain @instance @category async @rtype (tx: String, options: Object) => Promise[String] @param {String} tx - Transaction @param {Object} [options={}] options - Options @param {Object} [options.verify] verify - Verify transaction before broadcast, throw error if not valid @return {String|String} Transaction or transaction hash
[ "Sign", "and", "post", "a", "transaction", "to", "the", "chain" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/index.js#L43-L47
16,899
aeternity/aepp-sdk-js
es/ae/index.js
spend
async function spend (amount, recipientId, options = {}) { const opt = R.merge(this.Ae.defaults, options) const spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount: amount })) return this.send(spendTx, opt) }
javascript
async function spend (amount, recipientId, options = {}) { const opt = R.merge(this.Ae.defaults, options) const spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount: amount })) return this.send(spendTx, opt) }
[ "async", "function", "spend", "(", "amount", ",", "recipientId", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "spendTx", "=", "await", "this", ".", "spendTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "senderId", ":", "await", "this", ".", "address", "(", ")", ",", "recipientId", ",", "amount", ":", "amount", "}", ")", ")", "return", "this", ".", "send", "(", "spendTx", ",", "opt", ")", "}" ]
Send tokens to another account @instance @category async @rtype (amount: Number|String, recipientId: String, options?: Object) => Promise[String] @param {Number|String} amount - Amount to spend @param {String} recipientId - Address of recipient account @param {Object} options - Options @return {String|String} Transaction or transaction hash
[ "Send", "tokens", "to", "another", "account" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/index.js#L59-L63