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
33,000
emmetio/atom-plugin
lib/actions/update-image-size.js
updateHTMLTag
function updateHTMLTag(editor, node, width, height) { const srcAttr = getAttribute(node, 'src'); const widthAttr = getAttribute(node, 'width'); const heightAttr = getAttribute(node, 'height'); editor.transact(() => { // apply changes from right to left, first for height, then for width let point; const quote = getAttributeQuote(editor, widthAttr || heightAttr || srcAttr); if (!heightAttr) { // no `height` attribute, add it right after `width` or `src` point = widthAttr ? widthAttr.end : srcAttr.end; editor.setTextInBufferRange([point, point], ` height=${quote}${height}${quote}`); } else { editor.setTextInBufferRange(getRange(heightAttr.value), String(height)); } if (!widthAttr) { // no `width` attribute, add it right before `height` or after `src` point = heightAttr ? heightAttr.start : srcAttr.end; editor.setTextInBufferRange([point, point], `${!heightAttr ? ' ' : ''}width=${quote}${width}${quote}${heightAttr ? ' ' : ''}`); } else { editor.setTextInBufferRange(getRange(widthAttr.value), String(width)); } }); }
javascript
function updateHTMLTag(editor, node, width, height) { const srcAttr = getAttribute(node, 'src'); const widthAttr = getAttribute(node, 'width'); const heightAttr = getAttribute(node, 'height'); editor.transact(() => { // apply changes from right to left, first for height, then for width let point; const quote = getAttributeQuote(editor, widthAttr || heightAttr || srcAttr); if (!heightAttr) { // no `height` attribute, add it right after `width` or `src` point = widthAttr ? widthAttr.end : srcAttr.end; editor.setTextInBufferRange([point, point], ` height=${quote}${height}${quote}`); } else { editor.setTextInBufferRange(getRange(heightAttr.value), String(height)); } if (!widthAttr) { // no `width` attribute, add it right before `height` or after `src` point = heightAttr ? heightAttr.start : srcAttr.end; editor.setTextInBufferRange([point, point], `${!heightAttr ? ' ' : ''}width=${quote}${width}${quote}${heightAttr ? ' ' : ''}`); } else { editor.setTextInBufferRange(getRange(widthAttr.value), String(width)); } }); }
[ "function", "updateHTMLTag", "(", "editor", ",", "node", ",", "width", ",", "height", ")", "{", "const", "srcAttr", "=", "getAttribute", "(", "node", ",", "'src'", ")", ";", "const", "widthAttr", "=", "getAttribute", "(", "node", ",", "'width'", ")", ";"...
Updates size of given HTML node @param {TextEditor} editor @param {Node} node @param {Number} width @param {Number} height
[ "Updates", "size", "of", "given", "HTML", "node" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/update-image-size.js#L134-L160
33,001
emmetio/atom-plugin
lib/actions/update-image-size.js
updateCSSNode
function updateCSSNode(editor, srcProp, width, height) { const rule = srcProp.parent; const widthProp = getProperty(rule, 'width'); const heightProp = getProperty(rule, 'height'); // Detect formatting const separator = srcProp.separator || ': '; const before = getBefore(editor, srcProp); const insertOpt = { autoIndent: false }; editor.transact(() => { // Apply changes from right to left, first for height, then for width if (!heightProp) { // no `height` property, add it right after `width` or source property editor.setCursorBufferPosition(widthProp ? widthProp.end : srcProp.end); editor.insertText(`${before}height${separator}${height}px;`, insertOpt); } else { editor.setTextInBufferRange(getRange(heightProp.valueToken), `${height}px`); } if (!widthProp) { // no `width` attribute, add it right after `height` or source property if (heightProp) { editor.setCursorBufferPosition(heightProp.previousSibling ? heightProp.previousSibling.end : rule.contentStart.end); } else { editor.setCursorBufferPosition(srcProp.end); } editor.insertText(`${before}width${separator}${width}px;`, insertOpt); } else { editor.setTextInBufferRange(getRange(widthProp.valueToken), `${width}px`); } }); }
javascript
function updateCSSNode(editor, srcProp, width, height) { const rule = srcProp.parent; const widthProp = getProperty(rule, 'width'); const heightProp = getProperty(rule, 'height'); // Detect formatting const separator = srcProp.separator || ': '; const before = getBefore(editor, srcProp); const insertOpt = { autoIndent: false }; editor.transact(() => { // Apply changes from right to left, first for height, then for width if (!heightProp) { // no `height` property, add it right after `width` or source property editor.setCursorBufferPosition(widthProp ? widthProp.end : srcProp.end); editor.insertText(`${before}height${separator}${height}px;`, insertOpt); } else { editor.setTextInBufferRange(getRange(heightProp.valueToken), `${height}px`); } if (!widthProp) { // no `width` attribute, add it right after `height` or source property if (heightProp) { editor.setCursorBufferPosition(heightProp.previousSibling ? heightProp.previousSibling.end : rule.contentStart.end); } else { editor.setCursorBufferPosition(srcProp.end); } editor.insertText(`${before}width${separator}${width}px;`, insertOpt); } else { editor.setTextInBufferRange(getRange(widthProp.valueToken), `${width}px`); } }); }
[ "function", "updateCSSNode", "(", "editor", ",", "srcProp", ",", "width", ",", "height", ")", "{", "const", "rule", "=", "srcProp", ".", "parent", ";", "const", "widthProp", "=", "getProperty", "(", "rule", ",", "'width'", ")", ";", "const", "heightProp", ...
Updates size of given CSS rule @param {TextEditor} editor @param {Node} srcProp @param {Number} width @param {Number} height
[ "Updates", "size", "of", "given", "CSS", "rule" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/update-image-size.js#L169-L204
33,002
emmetio/atom-plugin
lib/actions/update-image-size.js
findUrlToken
function findUrlToken(node, pos) { for (let i = 0, il = node.parsedValue.length, url; i < il; i++) { iterateCSSToken(node.parsedValue[i], token => { if (token.type === 'url' && containsPoint(token, pos)) { url = token; return false; } }); if (url) { return url; } } }
javascript
function findUrlToken(node, pos) { for (let i = 0, il = node.parsedValue.length, url; i < il; i++) { iterateCSSToken(node.parsedValue[i], token => { if (token.type === 'url' && containsPoint(token, pos)) { url = token; return false; } }); if (url) { return url; } } }
[ "function", "findUrlToken", "(", "node", ",", "pos", ")", "{", "for", "(", "let", "i", "=", "0", ",", "il", "=", "node", ".", "parsedValue", ".", "length", ",", "url", ";", "i", "<", "il", ";", "i", "++", ")", "{", "iterateCSSToken", "(", "node",...
Finds 'url' token for given `pos` point in given CSS property `node` @param {Node} node @param {Point} pos @return {Token}
[ "Finds", "url", "token", "for", "given", "pos", "point", "in", "given", "CSS", "property", "node" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/update-image-size.js#L235-L248
33,003
emmetio/atom-plugin
lib/actions/update-image-size.js
getProperty
function getProperty(rule, name) { return rule.children.find(node => node.type === 'property' && node.name === name); }
javascript
function getProperty(rule, name) { return rule.children.find(node => node.type === 'property' && node.name === name); }
[ "function", "getProperty", "(", "rule", ",", "name", ")", "{", "return", "rule", ".", "children", ".", "find", "(", "node", "=>", "node", ".", "type", "===", "'property'", "&&", "node", ".", "name", "===", "name", ")", ";", "}" ]
Returns `name` CSS property from given `rule` @param {Node} rule @param {String} name @return {Node}
[ "Returns", "name", "CSS", "property", "from", "given", "rule" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/update-image-size.js#L256-L258
33,004
emmetio/atom-plugin
lib/actions/select-item.js
selectItem
function selectItem(editor, model, getItemRange) { editor.transact(() => { const selections = editor.getSelectedBufferRanges() .map(anchor => getItemRange(model, anchor) || anchor); editor.setSelectedBufferRanges(selections); }); }
javascript
function selectItem(editor, model, getItemRange) { editor.transact(() => { const selections = editor.getSelectedBufferRanges() .map(anchor => getItemRange(model, anchor) || anchor); editor.setSelectedBufferRanges(selections); }); }
[ "function", "selectItem", "(", "editor", ",", "model", ",", "getItemRange", ")", "{", "editor", ".", "transact", "(", "(", ")", "=>", "{", "const", "selections", "=", "editor", ".", "getSelectedBufferRanges", "(", ")", ".", "map", "(", "anchor", "=>", "g...
Selects each item, returned by `getItem` method, in given editor @param {TextEditor} editor @param {SyntaxModel} model @param {Function} getItemRange
[ "Selects", "each", "item", "returned", "by", "getItem", "method", "in", "given", "editor" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L45-L52
33,005
emmetio/atom-plugin
lib/actions/select-item.js
getNextItemRange
function getNextItemRange(model, anchor, getItemRanges) { // Find HTML node for next selection let node = nodeForPoint(model, anchor.start, 'next'); let range; // We might need to narrow down node context to find best token match while (node && !range) { range = getNextRange(getItemRanges(node), anchor); node = node.firstChild || nextSibling(node); } return range; }
javascript
function getNextItemRange(model, anchor, getItemRanges) { // Find HTML node for next selection let node = nodeForPoint(model, anchor.start, 'next'); let range; // We might need to narrow down node context to find best token match while (node && !range) { range = getNextRange(getItemRanges(node), anchor); node = node.firstChild || nextSibling(node); } return range; }
[ "function", "getNextItemRange", "(", "model", ",", "anchor", ",", "getItemRanges", ")", "{", "// Find HTML node for next selection", "let", "node", "=", "nodeForPoint", "(", "model", ",", "anchor", ".", "start", ",", "'next'", ")", ";", "let", "range", ";", "/...
Returns selection range of useful code part of given `model` next to given `anchor` range. @param {SyntaxModel} model @param {Range} anchor @param {Function} getItemRanges A function to retreive node ranges @return {Range}
[ "Returns", "selection", "range", "of", "useful", "code", "part", "of", "given", "model", "next", "to", "given", "anchor", "range", "." ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L102-L114
33,006
emmetio/atom-plugin
lib/actions/select-item.js
getPreviousItemRange
function getPreviousItemRange(model, anchor, getItemRanges) { // Find HTML node for next selection let node = nodeForPoint(model, anchor.start, 'previous'); let range; // We might need to narrow down node context to find best token match while (node) { range = getPreviousRange(getItemRanges(node), anchor); if (range) { break; } node = previousSibling(node) || node.parent; } return range; }
javascript
function getPreviousItemRange(model, anchor, getItemRanges) { // Find HTML node for next selection let node = nodeForPoint(model, anchor.start, 'previous'); let range; // We might need to narrow down node context to find best token match while (node) { range = getPreviousRange(getItemRanges(node), anchor); if (range) { break; } node = previousSibling(node) || node.parent; } return range; }
[ "function", "getPreviousItemRange", "(", "model", ",", "anchor", ",", "getItemRanges", ")", "{", "// Find HTML node for next selection", "let", "node", "=", "nodeForPoint", "(", "model", ",", "anchor", ".", "start", ",", "'previous'", ")", ";", "let", "range", "...
Returns selection range of useful code part of given `model` that precedes given `anchor` range. @param {SyntaxModel} model @param {Range} anchor @param {Function} getItemRanges A function to retreive node ranges @return {Range}
[ "Returns", "selection", "range", "of", "useful", "code", "part", "of", "given", "model", "that", "precedes", "given", "anchor", "range", "." ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L124-L139
33,007
emmetio/atom-plugin
lib/actions/select-item.js
getNextRange
function getNextRange(ranges, anchor) { for (let i = 0; i < ranges.length; i++) { if (anchor.isEqual(ranges[i])) { // NB may return `undefined`, which is totally fine and means that // we should move to next element return ranges[i + 1]; } } // Keep ranges which are not on the left of given selection ranges = ranges.filter(r => anchor.end.isLessThanOrEqual(r.start)); return ranges[0]; }
javascript
function getNextRange(ranges, anchor) { for (let i = 0; i < ranges.length; i++) { if (anchor.isEqual(ranges[i])) { // NB may return `undefined`, which is totally fine and means that // we should move to next element return ranges[i + 1]; } } // Keep ranges which are not on the left of given selection ranges = ranges.filter(r => anchor.end.isLessThanOrEqual(r.start)); return ranges[0]; }
[ "function", "getNextRange", "(", "ranges", ",", "anchor", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "ranges", ".", "length", ";", "i", "++", ")", "{", "if", "(", "anchor", ".", "isEqual", "(", "ranges", "[", "i", "]", ")", ")",...
Tries to find range that equals given `anchor` range in `ranges` and returns next one. Otherwise returns next to given `anchor` range @param {Range[]} ranges @param {Range} anchor @return {Range} May return `undefined` if there’s no valid next range
[ "Tries", "to", "find", "range", "that", "equals", "given", "anchor", "range", "in", "ranges", "and", "returns", "next", "one", ".", "Otherwise", "returns", "next", "to", "given", "anchor", "range" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L148-L161
33,008
emmetio/atom-plugin
lib/actions/select-item.js
getPreviousRange
function getPreviousRange(ranges, anchor) { for (let i = 0; i < ranges.length; i++) { if (anchor.isEqual(ranges[i])) { // NB may return `undefined`, which is totally fine and means that // we should move to next element return ranges[i - 1]; } } // Keep ranges which are not on the left of given selection ranges = ranges.filter(r => r.end.isLessThanOrEqual(anchor.start)); return last(ranges); }
javascript
function getPreviousRange(ranges, anchor) { for (let i = 0; i < ranges.length; i++) { if (anchor.isEqual(ranges[i])) { // NB may return `undefined`, which is totally fine and means that // we should move to next element return ranges[i - 1]; } } // Keep ranges which are not on the left of given selection ranges = ranges.filter(r => r.end.isLessThanOrEqual(anchor.start)); return last(ranges); }
[ "function", "getPreviousRange", "(", "ranges", ",", "anchor", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "ranges", ".", "length", ";", "i", "++", ")", "{", "if", "(", "anchor", ".", "isEqual", "(", "ranges", "[", "i", "]", ")", ...
Tries to find range that equals given `anchor` range in `ranges` and returns previous one. Otherwise returns previous to given `anchor` range @param {Range[]} ranges @param {Range} anchor @return {Range} May return `undefined` if there’s no valid next range
[ "Tries", "to", "find", "range", "that", "equals", "given", "anchor", "range", "in", "ranges", "and", "returns", "previous", "one", ".", "Otherwise", "returns", "previous", "to", "given", "anchor", "range" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L170-L183
33,009
emmetio/atom-plugin
lib/actions/select-item.js
getRangesFromHTMLNode
function getRangesFromHTMLNode(node) { if (node.type !== 'tag') { return []; } let ranges = [ getRange(node.open.name) ]; if (node.attributes) { node.attributes.forEach(attr => { ranges.push(getRange(attr)); if (!attr.boolean) { // add attribute value (unquoted) range for non-boolean attributes ranges.push(getRange(attr.value)); if (attr.name.value.toLowerCase() === 'class') { // In case of `class` attribute, add each class item // as selection range, but only if this value is not // an expression (for example, React expression like // `class={items.join(' ')}`) ranges = ranges.concat(attributeValueTokens(attr.value)); } } }); } return uniqueRanges(ranges.filter(Boolean)); }
javascript
function getRangesFromHTMLNode(node) { if (node.type !== 'tag') { return []; } let ranges = [ getRange(node.open.name) ]; if (node.attributes) { node.attributes.forEach(attr => { ranges.push(getRange(attr)); if (!attr.boolean) { // add attribute value (unquoted) range for non-boolean attributes ranges.push(getRange(attr.value)); if (attr.name.value.toLowerCase() === 'class') { // In case of `class` attribute, add each class item // as selection range, but only if this value is not // an expression (for example, React expression like // `class={items.join(' ')}`) ranges = ranges.concat(attributeValueTokens(attr.value)); } } }); } return uniqueRanges(ranges.filter(Boolean)); }
[ "function", "getRangesFromHTMLNode", "(", "node", ")", "{", "if", "(", "node", ".", "type", "!==", "'tag'", ")", "{", "return", "[", "]", ";", "}", "let", "ranges", "=", "[", "getRange", "(", "node", ".", "open", ".", "name", ")", "]", ";", "if", ...
Returns possible selection ranges for given HTML model node @param {Node} node @return {Range[]}
[ "Returns", "possible", "selection", "ranges", "for", "given", "HTML", "model", "node" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L190-L216
33,010
emmetio/atom-plugin
lib/actions/select-item.js
getRangesFromCSSNode
function getRangesFromCSSNode(node) { let ranges; if (node.type === 'rule') { ranges = [ getRange(node.selectorToken) ].concat(node.parsedSelector.map(getRange)); } else if (node.type === 'at-rule') { const nameEndToken = node.expressionToken || node.nameToken; ranges = [ new Range(node.nameToken.start, nameEndToken.end), getRange(node.nameToken), getRange(node.expressionToken) ]; node.parsedExpression.forEach(token => { ranges.push(getRange(token)); iterateCSSToken(token, t => { if (t.type === 'argument') { ranges.push(getRange(t)); } }); }); } else if (node.type === 'property') { ranges = [ getRange(node), getRange(node.nameToken), getRange(node.valueToken) ]; node.parsedValue.forEach(value => { // parsed value contains a comma-separated list of sub-values, // each of them, it turn, may contain space-separated parts ranges.push(getRange(value)); for (let i = 0, il = value.size, token; i < il; i++) { token = value.item(i); if (token.type === 'url') { ranges.push(getRange(token), getRange(token.item(0))); } else if (token.type !== 'whitespace' && token !== 'comment') { ranges.push(getRange(token)); iterateCSSToken(token, t => { if (t.type === 'argument') { ranges.push(getRange(t)); } }); } } }); } return ranges ? uniqueRanges(ranges.filter(Boolean)) : []; }
javascript
function getRangesFromCSSNode(node) { let ranges; if (node.type === 'rule') { ranges = [ getRange(node.selectorToken) ].concat(node.parsedSelector.map(getRange)); } else if (node.type === 'at-rule') { const nameEndToken = node.expressionToken || node.nameToken; ranges = [ new Range(node.nameToken.start, nameEndToken.end), getRange(node.nameToken), getRange(node.expressionToken) ]; node.parsedExpression.forEach(token => { ranges.push(getRange(token)); iterateCSSToken(token, t => { if (t.type === 'argument') { ranges.push(getRange(t)); } }); }); } else if (node.type === 'property') { ranges = [ getRange(node), getRange(node.nameToken), getRange(node.valueToken) ]; node.parsedValue.forEach(value => { // parsed value contains a comma-separated list of sub-values, // each of them, it turn, may contain space-separated parts ranges.push(getRange(value)); for (let i = 0, il = value.size, token; i < il; i++) { token = value.item(i); if (token.type === 'url') { ranges.push(getRange(token), getRange(token.item(0))); } else if (token.type !== 'whitespace' && token !== 'comment') { ranges.push(getRange(token)); iterateCSSToken(token, t => { if (t.type === 'argument') { ranges.push(getRange(t)); } }); } } }); } return ranges ? uniqueRanges(ranges.filter(Boolean)) : []; }
[ "function", "getRangesFromCSSNode", "(", "node", ")", "{", "let", "ranges", ";", "if", "(", "node", ".", "type", "===", "'rule'", ")", "{", "ranges", "=", "[", "getRange", "(", "node", ".", "selectorToken", ")", "]", ".", "concat", "(", "node", ".", ...
Returns possible selection ranges from given CSS model node @param {Node} node @return {Range[]}
[ "Returns", "possible", "selection", "ranges", "from", "given", "CSS", "model", "node" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L223-L272
33,011
emmetio/atom-plugin
lib/actions/select-item.js
nodeForPoint
function nodeForPoint(model, point, direction) { const node = model.nodeForPoint(point); if (node) { return node; } // Looks like caret is outside of any top-level node. const topLevelNodes = model.dom.children; if (direction === 'next') { // Find next node, which is closest top-level to given position return topLevelNodes.find(node => node.start.isGreaterThanOrEqual(point)); } // Find previous node, which is deepest child of closest previous node for (let i = topLevelNodes.length - 1; i >= 0; i--) { if (topLevelNodes[i].end.isLessThanOrEqual(point)) { return deepestChild(topLevelNodes[i]); } } }
javascript
function nodeForPoint(model, point, direction) { const node = model.nodeForPoint(point); if (node) { return node; } // Looks like caret is outside of any top-level node. const topLevelNodes = model.dom.children; if (direction === 'next') { // Find next node, which is closest top-level to given position return topLevelNodes.find(node => node.start.isGreaterThanOrEqual(point)); } // Find previous node, which is deepest child of closest previous node for (let i = topLevelNodes.length - 1; i >= 0; i--) { if (topLevelNodes[i].end.isLessThanOrEqual(point)) { return deepestChild(topLevelNodes[i]); } } }
[ "function", "nodeForPoint", "(", "model", ",", "point", ",", "direction", ")", "{", "const", "node", "=", "model", ".", "nodeForPoint", "(", "point", ")", ";", "if", "(", "node", ")", "{", "return", "node", ";", "}", "// Looks like caret is outside of any to...
Returns best matching node for given position. If on direct position match, tries to find closest one on givrn direction @param {SyntaxModel} model @param {Point} point @param {String} direction 'next' or 'previous' @return {Node}
[ "Returns", "best", "matching", "node", "for", "given", "position", ".", "If", "on", "direct", "position", "match", "tries", "to", "find", "closest", "one", "on", "givrn", "direction" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L307-L328
33,012
emmetio/atom-plugin
lib/actions/select-item.js
nextSibling
function nextSibling(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parent; } }
javascript
function nextSibling(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parent; } }
[ "function", "nextSibling", "(", "node", ")", "{", "while", "(", "node", ")", "{", "if", "(", "node", ".", "nextSibling", ")", "{", "return", "node", ".", "nextSibling", ";", "}", "node", "=", "node", ".", "parent", ";", "}", "}" ]
Returns next sibling element for given node. If no direct sibling found, tries to find it from its parent and so on @param {Node} node @return {Node}
[ "Returns", "next", "sibling", "element", "for", "given", "node", ".", "If", "no", "direct", "sibling", "found", "tries", "to", "find", "it", "from", "its", "parent", "and", "so", "on" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/select-item.js#L336-L343
33,013
emmetio/atom-plugin
lib/abbreviation-marker.js
toggleEditorClass
function toggleEditorClass(editor, enabled) { const view = atom.views.getView(editor); if (view) { view.classList.toggle('has-emmet-abbreviation', enabled); } }
javascript
function toggleEditorClass(editor, enabled) { const view = atom.views.getView(editor); if (view) { view.classList.toggle('has-emmet-abbreviation', enabled); } }
[ "function", "toggleEditorClass", "(", "editor", ",", "enabled", ")", "{", "const", "view", "=", "atom", ".", "views", ".", "getView", "(", "editor", ")", ";", "if", "(", "view", ")", "{", "view", ".", "classList", ".", "toggle", "(", "'has-emmet-abbrevia...
Toggles HTML class on given editor view indicating whether Emmet abbreviation is available in given editor @param {TextEditor} editor [description] @param {Boolean} enabled
[ "Toggles", "HTML", "class", "on", "given", "editor", "view", "indicating", "whether", "Emmet", "abbreviation", "is", "available", "in", "given", "editor" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/abbreviation-marker.js#L184-L189
33,014
emmetio/atom-plugin
lib/abbreviation-marker.js
allowedForAutoActivation
function allowedForAutoActivation(model) { const rootNode = model.ast.children[0]; // The very first node should start with alpha character // Skips falsy activations for something like `$foo` etc. return rootNode && /^[a-z]/i.test(rootNode.name); }
javascript
function allowedForAutoActivation(model) { const rootNode = model.ast.children[0]; // The very first node should start with alpha character // Skips falsy activations for something like `$foo` etc. return rootNode && /^[a-z]/i.test(rootNode.name); }
[ "function", "allowedForAutoActivation", "(", "model", ")", "{", "const", "rootNode", "=", "model", ".", "ast", ".", "children", "[", "0", "]", ";", "// The very first node should start with alpha character", "// Skips falsy activations for something like `$foo` etc.", "return...
Check if given abbreviation model is allowed for auto-activated abbreviation marker. Used to reduce falsy activations @param {Object} model Parsed abbreviation model (see `createAbbreviationModel()`) @return {Boolean}
[ "Check", "if", "given", "abbreviation", "model", "is", "allowed", "for", "auto", "-", "activated", "abbreviation", "marker", ".", "Used", "to", "reduce", "falsy", "activations" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/abbreviation-marker.js#L197-L202
33,015
emmetio/atom-plugin
lib/autocomplete/abbreviation.js
getExpandedAbbreviationCompletion
function getExpandedAbbreviationCompletion({editor, bufferPosition, prefix, activatedManually}) { // We should expand marked abbreviation only. // If there’s no marked abbreviation, try to mark it but only if // user invoked automomplete popup manually let marker = findMarker(editor, bufferPosition); if (!marker && activatedManually) { marker = markAbbreviation(editor, bufferPosition, activatedManually); } if (marker) { const snippet = marker.model.snippet; // For some syntaxes like Pug, it’s possible that extracted abbreviation // matches prefix itself (e.g. `li.class` expands to `li.class` in Pug) // In this case skip completion output. if (removeFields(snippet) === prefix) { return null; } return { snippet, marker, type: 'snippet', className: `${baseClass} ${getClassModifier(snippet)}`, replacementPrefix: editor.getTextInBufferRange(marker.getRange()) }; } }
javascript
function getExpandedAbbreviationCompletion({editor, bufferPosition, prefix, activatedManually}) { // We should expand marked abbreviation only. // If there’s no marked abbreviation, try to mark it but only if // user invoked automomplete popup manually let marker = findMarker(editor, bufferPosition); if (!marker && activatedManually) { marker = markAbbreviation(editor, bufferPosition, activatedManually); } if (marker) { const snippet = marker.model.snippet; // For some syntaxes like Pug, it’s possible that extracted abbreviation // matches prefix itself (e.g. `li.class` expands to `li.class` in Pug) // In this case skip completion output. if (removeFields(snippet) === prefix) { return null; } return { snippet, marker, type: 'snippet', className: `${baseClass} ${getClassModifier(snippet)}`, replacementPrefix: editor.getTextInBufferRange(marker.getRange()) }; } }
[ "function", "getExpandedAbbreviationCompletion", "(", "{", "editor", ",", "bufferPosition", ",", "prefix", ",", "activatedManually", "}", ")", "{", "// We should expand marked abbreviation only.", "// If there’s no marked abbreviation, try to mark it but only if", "// user invoked au...
Returns completion option for Emmet abbreviation found in given autocomplete invocation options @param {Object} event Autocomplete invocation event @return {Object} Completion with expanded Emmet abbreviation or `null` if no valid abbreviation found at given context
[ "Returns", "completion", "option", "for", "Emmet", "abbreviation", "found", "in", "given", "autocomplete", "invocation", "options" ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/autocomplete/abbreviation.js#L85-L112
33,016
emmetio/atom-plugin
lib/autocomplete/abbreviation.js
getSnippetsCompletions
function getSnippetsCompletions(editor, prefix) { const syntax = detectSyntax(editor); if (isStylesheet(syntax)) { return getStylesheetSnippetsCompletions(editor, prefix); } else if (syntax) { return getMarkupSnippetsCompletions(editor, prefix); } return []; }
javascript
function getSnippetsCompletions(editor, prefix) { const syntax = detectSyntax(editor); if (isStylesheet(syntax)) { return getStylesheetSnippetsCompletions(editor, prefix); } else if (syntax) { return getMarkupSnippetsCompletions(editor, prefix); } return []; }
[ "function", "getSnippetsCompletions", "(", "editor", ",", "prefix", ")", "{", "const", "syntax", "=", "detectSyntax", "(", "editor", ")", ";", "if", "(", "isStylesheet", "(", "syntax", ")", ")", "{", "return", "getStylesheetSnippetsCompletions", "(", "editor", ...
Returns snippets completions for given editor. @param {TextEditor} editor @param {String} prefix @return {String[]}
[ "Returns", "snippets", "completions", "for", "given", "editor", "." ]
a7b4a447647e493d1edf9df3fb901740c9fbc384
https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/autocomplete/abbreviation.js#L137-L146
33,017
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function() { this.$el.addClass('timeline-me-container'); if(this.settings.orientation == 'horizontal') { this.$el.addClass('timeline-me-horizontal'); if(this.settings.scrollBar == false) this.$el.addClass('no-x-scroll'); } else { this.$el.addClass('timeline-me-vertical'); if(this.settings.scrollBar == false) this.$el.addClass('no-y-scroll'); } var timelineWrapper = $('<div class="timeline-me-wrapper">'); this.$el.append(timelineWrapper); var track = $('<div class="timeline-me-track">'); timelineWrapper.append(track); if(this.settings.scrollZones == true) { var leftScroll = $('<div class="timeline-me-leftscroll">'); var rightScroll = $('<div class="timeline-me-rightscroll">'); timelineWrapper.before(leftScroll); timelineWrapper.after(rightScroll); bindScrollTo(leftScroll, rightScroll, timelineWrapper); } if(this.settings.scrollArrows == true) { var leftScroll; var rightScroll; if(this.settings.leftArrowElm == undefined) { leftScroll = $('<span class="timeline-me-leftarrow">'); } else { leftScroll = $('<span class="timeline-me-leftarrow-c">'); leftScroll.html(this.settings.leftArrowElm); } if(this.settings.rightArrowElm == undefined) { rightScroll = $('<span class="timeline-me-rightarrow">'); } else { rightScroll = $('<span class="timeline-me-rightarrow-c">'); rightScroll.html(this.settings.rightArrowElm); } timelineWrapper.before(leftScroll); timelineWrapper.after(rightScroll); bindScrollTo(leftScroll, rightScroll, timelineWrapper); } if(this.settings.items && this.settings.items.length > 0) { this.content = this.settings.items; if(hasNumberProperty(this.content, 'relativePosition')) { this._sortItemsPosition(this.content); this._mergeSamePositionItems(this.content); this._calcDiffWithNextItem(this.content); } this._sortItemsPosition(this.content); this._fillItemsPosition(this.content); for(var i = 0; i < this.content.length; i++) { track.append(this._createItemElement(this.content[i])); if(this.settings.orientation == 'horizontal') { resolveContainerWidth(track); } } // once items' DOM elements have been built, we can reposition them if(hasNumberProperty(this.content, 'relativePosition')) { this._calcRelativePosRatio(this.content); this.maxRelativeRatio = getMaxPropertyValue(this.content, 'relativePosRatio'); this._calcRelativeHeight(this.content, this.maxRelativeRatio); this._addMissingRelativeHeight(this.content); } } }
javascript
function() { this.$el.addClass('timeline-me-container'); if(this.settings.orientation == 'horizontal') { this.$el.addClass('timeline-me-horizontal'); if(this.settings.scrollBar == false) this.$el.addClass('no-x-scroll'); } else { this.$el.addClass('timeline-me-vertical'); if(this.settings.scrollBar == false) this.$el.addClass('no-y-scroll'); } var timelineWrapper = $('<div class="timeline-me-wrapper">'); this.$el.append(timelineWrapper); var track = $('<div class="timeline-me-track">'); timelineWrapper.append(track); if(this.settings.scrollZones == true) { var leftScroll = $('<div class="timeline-me-leftscroll">'); var rightScroll = $('<div class="timeline-me-rightscroll">'); timelineWrapper.before(leftScroll); timelineWrapper.after(rightScroll); bindScrollTo(leftScroll, rightScroll, timelineWrapper); } if(this.settings.scrollArrows == true) { var leftScroll; var rightScroll; if(this.settings.leftArrowElm == undefined) { leftScroll = $('<span class="timeline-me-leftarrow">'); } else { leftScroll = $('<span class="timeline-me-leftarrow-c">'); leftScroll.html(this.settings.leftArrowElm); } if(this.settings.rightArrowElm == undefined) { rightScroll = $('<span class="timeline-me-rightarrow">'); } else { rightScroll = $('<span class="timeline-me-rightarrow-c">'); rightScroll.html(this.settings.rightArrowElm); } timelineWrapper.before(leftScroll); timelineWrapper.after(rightScroll); bindScrollTo(leftScroll, rightScroll, timelineWrapper); } if(this.settings.items && this.settings.items.length > 0) { this.content = this.settings.items; if(hasNumberProperty(this.content, 'relativePosition')) { this._sortItemsPosition(this.content); this._mergeSamePositionItems(this.content); this._calcDiffWithNextItem(this.content); } this._sortItemsPosition(this.content); this._fillItemsPosition(this.content); for(var i = 0; i < this.content.length; i++) { track.append(this._createItemElement(this.content[i])); if(this.settings.orientation == 'horizontal') { resolveContainerWidth(track); } } // once items' DOM elements have been built, we can reposition them if(hasNumberProperty(this.content, 'relativePosition')) { this._calcRelativePosRatio(this.content); this.maxRelativeRatio = getMaxPropertyValue(this.content, 'relativePosRatio'); this._calcRelativeHeight(this.content, this.maxRelativeRatio); this._addMissingRelativeHeight(this.content); } } }
[ "function", "(", ")", "{", "this", ".", "$el", ".", "addClass", "(", "'timeline-me-container'", ")", ";", "if", "(", "this", ".", "settings", ".", "orientation", "==", "'horizontal'", ")", "{", "this", ".", "$el", ".", "addClass", "(", "'timeline-me-horizo...
Initialize the plugin instance. Set any other attribtes, store any other element reference, register listeners, etc When bind listerners remember to name tag it with your plugin's name. Elements can have more than one listener attached to the same event so you need to tag it to unbind the appropriate listener on destroy: @example this.$someSubElement.on('click.' + pluginName, function() { // Do something });
[ "Initialize", "the", "plugin", "instance", ".", "Set", "any", "other", "attribtes", "store", "any", "other", "element", "reference", "register", "listeners", "etc" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L57-L132
33,018
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(items) { var hasRelativePositioning = hasNumberProperty(items, 'relativePosition'); if(hasRelativePositioning) { items.sort(function(a, b) { return a.relativePosition - b.relativePosition; }); } }
javascript
function(items) { var hasRelativePositioning = hasNumberProperty(items, 'relativePosition'); if(hasRelativePositioning) { items.sort(function(a, b) { return a.relativePosition - b.relativePosition; }); } }
[ "function", "(", "items", ")", "{", "var", "hasRelativePositioning", "=", "hasNumberProperty", "(", "items", ",", "'relativePosition'", ")", ";", "if", "(", "hasRelativePositioning", ")", "{", "items", ".", "sort", "(", "function", "(", "a", ",", "b", ")", ...
Method that sort items, depending on their relativePosition
[ "Method", "that", "sort", "items", "depending", "on", "their", "relativePosition" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L261-L269
33,019
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(items) { var hasRelativePositioning = hasNumberProperty(items, 'relativePosition'); for(var i = 0; i < items.length; i++) { if(i == items.length - 1) items[i].diffWithNextRelativePos = undefined; else items[i].diffWithNextRelativePos = items[i + 1].relativePosition - items[i].relativePosition; } }
javascript
function(items) { var hasRelativePositioning = hasNumberProperty(items, 'relativePosition'); for(var i = 0; i < items.length; i++) { if(i == items.length - 1) items[i].diffWithNextRelativePos = undefined; else items[i].diffWithNextRelativePos = items[i + 1].relativePosition - items[i].relativePosition; } }
[ "function", "(", "items", ")", "{", "var", "hasRelativePositioning", "=", "hasNumberProperty", "(", "items", ",", "'relativePosition'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "if", ...
Method that calculates relativePosition difference with next item
[ "Method", "that", "calculates", "relativePosition", "difference", "with", "next", "item" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L287-L296
33,020
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(items) { if(!items) return; var positions; if(this.settings.orientation == 'horizontal') positions = ['top', 'bottom']; else positions = ['left', 'right']; for(var i = 0; i < this.content.length; i++) { if(this.content[i].forcePosition && positions.indexOf(this.content[i].forcePosition) >= 0) { this.content[i].position = this.content[i].forcePosition; } else if(!this.content[i].position) { switch(this.content[i].type) { case 'milestone': if(this.settings.orientation == 'horizontal') this.content[i].position = 'top'; else this.content[i].position = 'right'; break; case 'smallItem': if(i == 0) this.content[i].position = this.settings.orientation == 'horizontal' ? 'top' : 'left'; else if(this.settings.orientation == 'horizontal' && this.content[i - 1].position == 'top') this.content[i].position = 'bottom'; else if(this.settings.orientation == 'horizontal' && this.content[i - 1].position == 'bottom') this.content[i].position = 'top'; else if(this.settings.orientation != 'horizontal' && this.content[i - 1].position == 'left') this.content[i].position = 'right'; else if(this.settings.orientation != 'horizontal' && this.content[i - 1].position == 'right') this.content[i].position = 'left'; else this.content[i].position = this.settings.orientation == 'horizontal' ? 'top' : 'left'; break; case 'bigItem': break; } } } return items; }
javascript
function(items) { if(!items) return; var positions; if(this.settings.orientation == 'horizontal') positions = ['top', 'bottom']; else positions = ['left', 'right']; for(var i = 0; i < this.content.length; i++) { if(this.content[i].forcePosition && positions.indexOf(this.content[i].forcePosition) >= 0) { this.content[i].position = this.content[i].forcePosition; } else if(!this.content[i].position) { switch(this.content[i].type) { case 'milestone': if(this.settings.orientation == 'horizontal') this.content[i].position = 'top'; else this.content[i].position = 'right'; break; case 'smallItem': if(i == 0) this.content[i].position = this.settings.orientation == 'horizontal' ? 'top' : 'left'; else if(this.settings.orientation == 'horizontal' && this.content[i - 1].position == 'top') this.content[i].position = 'bottom'; else if(this.settings.orientation == 'horizontal' && this.content[i - 1].position == 'bottom') this.content[i].position = 'top'; else if(this.settings.orientation != 'horizontal' && this.content[i - 1].position == 'left') this.content[i].position = 'right'; else if(this.settings.orientation != 'horizontal' && this.content[i - 1].position == 'right') this.content[i].position = 'left'; else this.content[i].position = this.settings.orientation == 'horizontal' ? 'top' : 'left'; break; case 'bigItem': break; } } } return items; }
[ "function", "(", "items", ")", "{", "if", "(", "!", "items", ")", "return", ";", "var", "positions", ";", "if", "(", "this", ".", "settings", ".", "orientation", "==", "'horizontal'", ")", "positions", "=", "[", "'top'", ",", "'bottom'", "]", ";", "e...
Method that fill 'position' field, depending on item's forcePosition option, on item's type and on position of the previous item
[ "Method", "that", "fill", "position", "field", "depending", "on", "item", "s", "forcePosition", "option", "on", "item", "s", "type", "and", "on", "position", "of", "the", "previous", "item" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L334-L376
33,021
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(item) { if(!item || (item && !item.element) || (item && !item.position)) return; switch(item.position) { case 'left': item.element .removeClass('timeline-me-top') .removeClass('timeline-me-right') .removeClass('timeline-me-bottom') .addClass('timeline-me-left'); break; case 'top': item.element .removeClass('timeline-me-left') .removeClass('timeline-me-right') .removeClass('timeline-me-bottom') .addClass('timeline-me-top'); break; case 'right': item.element .removeClass('timeline-me-top') .removeClass('timeline-me-left') .removeClass('timeline-me-bottom') .addClass('timeline-me-right'); break; case 'bottom': item.element .removeClass('timeline-me-top') .removeClass('timeline-me-right') .removeClass('timeline-me-left') .addClass('timeline-me-bottom'); break; } return item; }
javascript
function(item) { if(!item || (item && !item.element) || (item && !item.position)) return; switch(item.position) { case 'left': item.element .removeClass('timeline-me-top') .removeClass('timeline-me-right') .removeClass('timeline-me-bottom') .addClass('timeline-me-left'); break; case 'top': item.element .removeClass('timeline-me-left') .removeClass('timeline-me-right') .removeClass('timeline-me-bottom') .addClass('timeline-me-top'); break; case 'right': item.element .removeClass('timeline-me-top') .removeClass('timeline-me-left') .removeClass('timeline-me-bottom') .addClass('timeline-me-right'); break; case 'bottom': item.element .removeClass('timeline-me-top') .removeClass('timeline-me-right') .removeClass('timeline-me-left') .addClass('timeline-me-bottom'); break; } return item; }
[ "function", "(", "item", ")", "{", "if", "(", "!", "item", "||", "(", "item", "&&", "!", "item", ".", "element", ")", "||", "(", "item", "&&", "!", "item", ".", "position", ")", ")", "return", ";", "switch", "(", "item", ".", "position", ")", "...
Method that refresh item's class depending on its 'position' property
[ "Method", "that", "refresh", "item", "s", "class", "depending", "on", "its", "position", "property" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L379-L415
33,022
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(item) { var itemElm; switch(item.type) { case 'milestone': itemElm = this._buildMilestoneElement(item); break; case 'smallItem': itemElm = this._buildSmallItemElement(item); break; case 'bigItem': itemElm = this._buildBigItemElement(item); break; } item.element = itemElm; this._refreshItemPosition(item); item.element.on('timelineMe.itemHeightChanged', function(event) { // Do some stuff }); item.element.on('timelineMe.smallItem.displayfull', function(event) { // Do some stuff }); item.element.on('timelineMe.bigItem.flipped', function(event) { var container = item.element.find('.timeline-me-content-container'); if(item.element.hasClass('timeline-me-flipped')) { container.height(item.fullContentElement.outerHeight()); } else { container.height(item.shortContentElement.outerHeight()); } }); this._buildItemContent(item); this._fillItem(item); return itemElm; }
javascript
function(item) { var itemElm; switch(item.type) { case 'milestone': itemElm = this._buildMilestoneElement(item); break; case 'smallItem': itemElm = this._buildSmallItemElement(item); break; case 'bigItem': itemElm = this._buildBigItemElement(item); break; } item.element = itemElm; this._refreshItemPosition(item); item.element.on('timelineMe.itemHeightChanged', function(event) { // Do some stuff }); item.element.on('timelineMe.smallItem.displayfull', function(event) { // Do some stuff }); item.element.on('timelineMe.bigItem.flipped', function(event) { var container = item.element.find('.timeline-me-content-container'); if(item.element.hasClass('timeline-me-flipped')) { container.height(item.fullContentElement.outerHeight()); } else { container.height(item.shortContentElement.outerHeight()); } }); this._buildItemContent(item); this._fillItem(item); return itemElm; }
[ "function", "(", "item", ")", "{", "var", "itemElm", ";", "switch", "(", "item", ".", "type", ")", "{", "case", "'milestone'", ":", "itemElm", "=", "this", ".", "_buildMilestoneElement", "(", "item", ")", ";", "break", ";", "case", "'smallItem'", ":", ...
Method that create the item's html structure and fill it
[ "Method", "that", "create", "the", "item", "s", "html", "structure", "and", "fill", "it" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L418-L453
33,023
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(item) { if(!item || !item.element) return; var pixelsRegex = /[0-9]+px$/; // Following wrapper are only used in horizontal mode, in order to correctly display bigItems (with table display) var itemWrapper = $('<div class="timeline-me-item-wrapper">'); var labelWrapper = $('<div class="timeline-me-label-wrapper">'); var contentWrapper = $('<div class="timeline-me-content-wrapper">'); var labelElm = $('<div class="timeline-me-label">'); item.labelElement = labelElm; if(this.settings.orientation == 'horizontal' && this.settings.labelDimensionValue && pixelsRegex.test(this.settings.labelDimensionValue)) { labelElm.css('width', this.settings.labelDimensionValue); } var pictoElm = $('<div class="timeline-me-picto">'); item.pictoElement = pictoElm; labelWrapper.append(labelElm); itemWrapper.append(labelWrapper); if(item.type == 'smallItem' || item.type == 'bigItem') { var contentContainer = $('<div class="timeline-me-content-container">'); var contentElm = $('<div class="timeline-me-content"></div>'); contentContainer.append(contentElm); if(this.settings.orientation == 'horizontal' && this.settings.contentDimensionValue && pixelsRegex.test(this.settings.contentDimensionValue)) { contentElm.css('width', this.settings.contentDimensionValue); } var shortContentElm = $('<div class="timeline-me-shortcontent">'); contentElm.append(shortContentElm); item.shortContentElement = shortContentElm; var fullContentElm = $('<div class="timeline-me-fullcontent">'); contentElm.append(fullContentElm); item.fullContentElement = fullContentElm; var showMoreElm = $('<div class="timeline-me-showmore">'); item.showMoreElement = showMoreElm; var showLessElm = $('<div class="timeline-me-showless">'); item.showLessElement = showLessElm; contentWrapper.append(contentContainer); itemWrapper.append(contentWrapper); } item.element.append(itemWrapper); item.itemWrapperElement = itemWrapper; item.labelWrapperElement = labelWrapper; item.contentWrapperElement = contentWrapper; }
javascript
function(item) { if(!item || !item.element) return; var pixelsRegex = /[0-9]+px$/; // Following wrapper are only used in horizontal mode, in order to correctly display bigItems (with table display) var itemWrapper = $('<div class="timeline-me-item-wrapper">'); var labelWrapper = $('<div class="timeline-me-label-wrapper">'); var contentWrapper = $('<div class="timeline-me-content-wrapper">'); var labelElm = $('<div class="timeline-me-label">'); item.labelElement = labelElm; if(this.settings.orientation == 'horizontal' && this.settings.labelDimensionValue && pixelsRegex.test(this.settings.labelDimensionValue)) { labelElm.css('width', this.settings.labelDimensionValue); } var pictoElm = $('<div class="timeline-me-picto">'); item.pictoElement = pictoElm; labelWrapper.append(labelElm); itemWrapper.append(labelWrapper); if(item.type == 'smallItem' || item.type == 'bigItem') { var contentContainer = $('<div class="timeline-me-content-container">'); var contentElm = $('<div class="timeline-me-content"></div>'); contentContainer.append(contentElm); if(this.settings.orientation == 'horizontal' && this.settings.contentDimensionValue && pixelsRegex.test(this.settings.contentDimensionValue)) { contentElm.css('width', this.settings.contentDimensionValue); } var shortContentElm = $('<div class="timeline-me-shortcontent">'); contentElm.append(shortContentElm); item.shortContentElement = shortContentElm; var fullContentElm = $('<div class="timeline-me-fullcontent">'); contentElm.append(fullContentElm); item.fullContentElement = fullContentElm; var showMoreElm = $('<div class="timeline-me-showmore">'); item.showMoreElement = showMoreElm; var showLessElm = $('<div class="timeline-me-showless">'); item.showLessElement = showLessElm; contentWrapper.append(contentContainer); itemWrapper.append(contentWrapper); } item.element.append(itemWrapper); item.itemWrapperElement = itemWrapper; item.labelWrapperElement = labelWrapper; item.contentWrapperElement = contentWrapper; }
[ "function", "(", "item", ")", "{", "if", "(", "!", "item", "||", "!", "item", ".", "element", ")", "return", ";", "var", "pixelsRegex", "=", "/", "[0-9]+px$", "/", ";", "// Following wrapper are only used in horizontal mode, in order to correctly display bigItems (wit...
Method that fills the item's element with some useful html structure
[ "Method", "that", "fills", "the", "item", "s", "element", "with", "some", "useful", "html", "structure" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L474-L526
33,024
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(item) { if(!item || !item.type || !item.element) return false; switch(item.type) { case 'milestone': return (item.element.hasClass('timeline-milestone')); break; case 'smallItem': return (item.element.hasClass('timeline-smallitem')); break; case 'bigItem': return (item.element.hasClass('timeline-bigitem')); break; default: return false; break; } }
javascript
function(item) { if(!item || !item.type || !item.element) return false; switch(item.type) { case 'milestone': return (item.element.hasClass('timeline-milestone')); break; case 'smallItem': return (item.element.hasClass('timeline-smallitem')); break; case 'bigItem': return (item.element.hasClass('timeline-bigitem')); break; default: return false; break; } }
[ "function", "(", "item", ")", "{", "if", "(", "!", "item", "||", "!", "item", ".", "type", "||", "!", "item", ".", "element", ")", "return", "false", ";", "switch", "(", "item", ".", "type", ")", "{", "case", "'milestone'", ":", "return", "(", "i...
Method that checks if an item's element has the class defined by his type
[ "Method", "that", "checks", "if", "an", "item", "s", "element", "has", "the", "class", "defined", "by", "his", "type" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L648-L666
33,025
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(leftScrollElm, rightScrollElm, elmToScroll, scrollSpeed) { var scrollSpeed = scrollSpeed ? scrollSpeed : 5; leftScrollElm.on('mouseenter', function() { var timer = setInterval(function() { elmToScroll.scrollLeft(elmToScroll.scrollLeft() - scrollSpeed); }, 20); leftScrollElm.on('mouseleave', function() { clearInterval(timer); }); }); rightScrollElm.on('mouseenter', function() { var timer = setInterval(function() { elmToScroll.scrollLeft(elmToScroll.scrollLeft() + scrollSpeed); }, 20); rightScrollElm.on('mouseleave', function() { clearInterval(timer); }); }); }
javascript
function(leftScrollElm, rightScrollElm, elmToScroll, scrollSpeed) { var scrollSpeed = scrollSpeed ? scrollSpeed : 5; leftScrollElm.on('mouseenter', function() { var timer = setInterval(function() { elmToScroll.scrollLeft(elmToScroll.scrollLeft() - scrollSpeed); }, 20); leftScrollElm.on('mouseleave', function() { clearInterval(timer); }); }); rightScrollElm.on('mouseenter', function() { var timer = setInterval(function() { elmToScroll.scrollLeft(elmToScroll.scrollLeft() + scrollSpeed); }, 20); rightScrollElm.on('mouseleave', function() { clearInterval(timer); }); }); }
[ "function", "(", "leftScrollElm", ",", "rightScrollElm", ",", "elmToScroll", ",", "scrollSpeed", ")", "{", "var", "scrollSpeed", "=", "scrollSpeed", "?", "scrollSpeed", ":", "5", ";", "leftScrollElm", ".", "on", "(", "'mouseenter'", ",", "function", "(", ")", ...
These are real private methods. A plugin instance has access to them @return {[type]} Method that bind left & right scroll to any scrollable element
[ "These", "are", "real", "private", "methods", ".", "A", "plugin", "instance", "has", "access", "to", "them" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L675-L696
33,026
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(element) { if(!element) return; var children = element.children(); if(children.length <= 0) return; var totalWidth = 0; for(var i = 0; i < children.length; i++) { totalWidth += $(children[i]).width(); } element.width(totalWidth); }
javascript
function(element) { if(!element) return; var children = element.children(); if(children.length <= 0) return; var totalWidth = 0; for(var i = 0; i < children.length; i++) { totalWidth += $(children[i]).width(); } element.width(totalWidth); }
[ "function", "(", "element", ")", "{", "if", "(", "!", "element", ")", "return", ";", "var", "children", "=", "element", ".", "children", "(", ")", ";", "if", "(", "children", ".", "length", "<=", "0", ")", "return", ";", "var", "totalWidth", "=", "...
Method that return container width depending on children's width
[ "Method", "that", "return", "container", "width", "depending", "on", "children", "s", "width" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L699-L711
33,027
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(element, args) { if(!args) args = {}; var refreshDelay = args.refreshDelay ? args.refreshDelay : 500; var previousHeight = args.previousHeight; var level = args.level ? args.level : 0; var ret = new $.Deferred(); var elmHeight; if(element) elmHeight = element[0].getBoundingClientRect().height; if(elmHeight && (!previousHeight || previousHeight != elmHeight)) { ret.resolve(elmHeight, previousHeight, level); } else { args.previousHeight = elmHeight; setTimeout(function () { resolveElementHeightChange(element, {previousHeight: elmHeight, refreshDelay: refreshDelay, level: (level + 1)}).then(function(newHeightVal, previousHeightVal, levelVal) { ret.resolve(newHeightVal, previousHeightVal, level); }); }, refreshDelay); } return ret; }
javascript
function(element, args) { if(!args) args = {}; var refreshDelay = args.refreshDelay ? args.refreshDelay : 500; var previousHeight = args.previousHeight; var level = args.level ? args.level : 0; var ret = new $.Deferred(); var elmHeight; if(element) elmHeight = element[0].getBoundingClientRect().height; if(elmHeight && (!previousHeight || previousHeight != elmHeight)) { ret.resolve(elmHeight, previousHeight, level); } else { args.previousHeight = elmHeight; setTimeout(function () { resolveElementHeightChange(element, {previousHeight: elmHeight, refreshDelay: refreshDelay, level: (level + 1)}).then(function(newHeightVal, previousHeightVal, levelVal) { ret.resolve(newHeightVal, previousHeightVal, level); }); }, refreshDelay); } return ret; }
[ "function", "(", "element", ",", "args", ")", "{", "if", "(", "!", "args", ")", "args", "=", "{", "}", ";", "var", "refreshDelay", "=", "args", ".", "refreshDelay", "?", "args", ".", "refreshDelay", ":", "500", ";", "var", "previousHeight", "=", "arg...
Method that can return an element's height when it's changing
[ "Method", "that", "can", "return", "an", "element", "s", "height", "when", "it", "s", "changing" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L757-L781
33,028
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(items, propertyName) { if(!items) return false; var hasProperty = true; for(var i = 0; i < items.length; i++) { if(isNaN(items[i][propertyName])) hasProperty = false; } return hasProperty; }
javascript
function(items, propertyName) { if(!items) return false; var hasProperty = true; for(var i = 0; i < items.length; i++) { if(isNaN(items[i][propertyName])) hasProperty = false; } return hasProperty; }
[ "function", "(", "items", ",", "propertyName", ")", "{", "if", "(", "!", "items", ")", "return", "false", ";", "var", "hasProperty", "=", "true", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", ...
Method checking if all items of an array have a specific number property
[ "Method", "checking", "if", "all", "items", "of", "an", "array", "have", "a", "specific", "number", "property" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L799-L808
33,029
mickaelr/jquery-timelineMe
src/jquery.timelineMe.js
function(items, propertyName) { if(!items) return false; var maxProperty; for(var i = 0; i < items.length; i++) { if(maxProperty == undefined) maxProperty = items[i][propertyName]; else if(items[i][propertyName] > maxProperty) maxProperty = items[i][propertyName]; } return maxProperty; }
javascript
function(items, propertyName) { if(!items) return false; var maxProperty; for(var i = 0; i < items.length; i++) { if(maxProperty == undefined) maxProperty = items[i][propertyName]; else if(items[i][propertyName] > maxProperty) maxProperty = items[i][propertyName]; } return maxProperty; }
[ "function", "(", "items", ",", "propertyName", ")", "{", "if", "(", "!", "items", ")", "return", "false", ";", "var", "maxProperty", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "if", "...
Method returning max value of specific array's property
[ "Method", "returning", "max", "value", "of", "specific", "array", "s", "property" ]
b768b43269b3e179037bd80052045b011aac7b38
https://github.com/mickaelr/jquery-timelineMe/blob/b768b43269b3e179037bd80052045b011aac7b38/src/jquery.timelineMe.js#L811-L822
33,030
jtrussell/angular-selection-model
examples/vendor/angular-selection-model/selection-model.js
function(event) { /** * Set by the `selectionModelIgnore` directive * * Use `selectionModelIgnore` to cause `selectionModel` to selectively * ignore clicks on elements. This is useful if you want to manually * change a selection when certain things are clicked. */ if(event.selectionModelIgnore || (event.originalEvent && event.originalEvent.selectionModelIgnore)) { return; } // Never handle a single click twice. if(event.selectionModelClickHandled || (event.originalEvent && event.originalEvent.selectionModelClickHandled)) { return; } event.selectionModelClickHandled = true; if(event.originalEvent) { event.originalEvent.selectionModelClickHandled = true; } var isCtrlKeyDown = event.ctrlKey || event.metaKey || isModeAdditive , isShiftKeyDown = event.shiftKey , target = event.target || event.srcElement , isCheckboxClick = 'checkbox' === smType && 'INPUT' === target.tagName && 'checkbox' === target.type; /** * Guard against label + checkbox clicks * * Clicking a label will cause a click event to also be fired on the * associated input element. If that input is nearby (i.e. under the * selection model element) we'll suppress the click on the label to * avoid duplicate click events. */ if('LABEL' === target.tagName) { var labelFor = angular.element(target).attr('for'); if(labelFor) { var childInputs = element[0].getElementsByTagName('INPUT'), ix; for(ix = childInputs.length; ix--;) { if(childInputs[ix].id === labelFor) { return; } } } else if(target.getElementsByTagName('INPUT').length) { // Label has a nested input element, we'll handle the click on // that element return; } } // Select multiple allows for ranges - use shift key if(isShiftKeyDown && isMultiMode && !isCheckboxClick) { // Use ctrl+shift for additive ranges if(!isCtrlKeyDown) { scope.$apply(function() { deselectAllItemsExcept([smItem, selectionStack.peek(clickStackId)]); }); } selectItemsBetween(selectionStack.peek(clickStackId)); scope.$apply(); return; } // Use ctrl/shift without multi select to true toggle a row if(isCtrlKeyDown || isShiftKeyDown || isCheckboxClick) { var isSelected = !smItem[selectedAttribute]; if(!isMultiMode) { deselectAllItemsExcept(smItem); } smItem[selectedAttribute] = isSelected; if(smItem[selectedAttribute]) { selectionStack.push(clickStackId, smItem); } scope.$apply(); return; } // Otherwise the clicked on row becomes the only selected item deselectAllItemsExcept(smItem); scope.$apply(); smItem[selectedAttribute] = true; selectionStack.push(clickStackId, smItem); scope.$apply(); }
javascript
function(event) { /** * Set by the `selectionModelIgnore` directive * * Use `selectionModelIgnore` to cause `selectionModel` to selectively * ignore clicks on elements. This is useful if you want to manually * change a selection when certain things are clicked. */ if(event.selectionModelIgnore || (event.originalEvent && event.originalEvent.selectionModelIgnore)) { return; } // Never handle a single click twice. if(event.selectionModelClickHandled || (event.originalEvent && event.originalEvent.selectionModelClickHandled)) { return; } event.selectionModelClickHandled = true; if(event.originalEvent) { event.originalEvent.selectionModelClickHandled = true; } var isCtrlKeyDown = event.ctrlKey || event.metaKey || isModeAdditive , isShiftKeyDown = event.shiftKey , target = event.target || event.srcElement , isCheckboxClick = 'checkbox' === smType && 'INPUT' === target.tagName && 'checkbox' === target.type; /** * Guard against label + checkbox clicks * * Clicking a label will cause a click event to also be fired on the * associated input element. If that input is nearby (i.e. under the * selection model element) we'll suppress the click on the label to * avoid duplicate click events. */ if('LABEL' === target.tagName) { var labelFor = angular.element(target).attr('for'); if(labelFor) { var childInputs = element[0].getElementsByTagName('INPUT'), ix; for(ix = childInputs.length; ix--;) { if(childInputs[ix].id === labelFor) { return; } } } else if(target.getElementsByTagName('INPUT').length) { // Label has a nested input element, we'll handle the click on // that element return; } } // Select multiple allows for ranges - use shift key if(isShiftKeyDown && isMultiMode && !isCheckboxClick) { // Use ctrl+shift for additive ranges if(!isCtrlKeyDown) { scope.$apply(function() { deselectAllItemsExcept([smItem, selectionStack.peek(clickStackId)]); }); } selectItemsBetween(selectionStack.peek(clickStackId)); scope.$apply(); return; } // Use ctrl/shift without multi select to true toggle a row if(isCtrlKeyDown || isShiftKeyDown || isCheckboxClick) { var isSelected = !smItem[selectedAttribute]; if(!isMultiMode) { deselectAllItemsExcept(smItem); } smItem[selectedAttribute] = isSelected; if(smItem[selectedAttribute]) { selectionStack.push(clickStackId, smItem); } scope.$apply(); return; } // Otherwise the clicked on row becomes the only selected item deselectAllItemsExcept(smItem); scope.$apply(); smItem[selectedAttribute] = true; selectionStack.push(clickStackId, smItem); scope.$apply(); }
[ "function", "(", "event", ")", "{", "/**\r\n * Set by the `selectionModelIgnore` directive\r\n *\r\n * Use `selectionModelIgnore` to cause `selectionModel` to selectively\r\n * ignore clicks on elements. This is useful if you want to manually\r\n * change ...
Item click handler Use the `ctrl` key to select/deselect while preserving the rest of your selection. Note your your selection mode must be set to `'multiple'` to allow for more than one selected item at a time. In single select mode you still must use the `ctrl` or `shitft` keys to deselect an item. The `shift` key allows you to select ranges of items at a time. Use `ctrl` + `shift` to select a range while preserving your existing selection. In single select mode `shift` behaves like `ctrl`. When an item is clicked with no modifier keys pressed it will be the only selected item. On Mac the `meta` key is treated as `ctrl`. Note that when using the `'checkbox'` selection model type clicking on a checkbox will have no effect on any row other than the one the checkbox is in.
[ "Item", "click", "handler" ]
ad82c063dadcf41a688be5731ec3044f622489f6
https://github.com/jtrussell/angular-selection-model/blob/ad82c063dadcf41a688be5731ec3044f622489f6/examples/vendor/angular-selection-model/selection-model.js#L327-L414
33,031
jtrussell/angular-selection-model
examples/vendor/angular-selection-model/selection-model.js
function() { if(angular.isArray(selectedItemsList)) { var ixSmItem = selectedItemsList.indexOf(smItem); if(smItem[selectedAttribute]) { if(-1 === ixSmItem) { selectedItemsList.push(smItem); } } else { if(-1 < ixSmItem) { selectedItemsList.splice(ixSmItem, 1); } } } }
javascript
function() { if(angular.isArray(selectedItemsList)) { var ixSmItem = selectedItemsList.indexOf(smItem); if(smItem[selectedAttribute]) { if(-1 === ixSmItem) { selectedItemsList.push(smItem); } } else { if(-1 < ixSmItem) { selectedItemsList.splice(ixSmItem, 1); } } } }
[ "function", "(", ")", "{", "if", "(", "angular", ".", "isArray", "(", "selectedItemsList", ")", ")", "{", "var", "ixSmItem", "=", "selectedItemsList", ".", "indexOf", "(", "smItem", ")", ";", "if", "(", "smItem", "[", "selectedAttribute", "]", ")", "{", ...
Routine to keep the list of selected items up to date Adds/removes this item from `selectionModelSelectedItems`.
[ "Routine", "to", "keep", "the", "list", "of", "selected", "items", "up", "to", "date" ]
ad82c063dadcf41a688be5731ec3044f622489f6
https://github.com/jtrussell/angular-selection-model/blob/ad82c063dadcf41a688be5731ec3044f622489f6/examples/vendor/angular-selection-model/selection-model.js#L421-L434
33,032
zohararad/sails-rest
lib/connection.js
runBeforeHooks
function runBeforeHooks(req, method, config, conn, cb){ var httpMethod = conn.connection.methods[method]; async.eachSeries(conn.connection.hooks.before, function (hook, nextHook) { hook(req, httpMethod, config, conn, function (err) { if(err) { return nextHook(err); } if(!_.isEmpty(config.endpoint) && typeof req === 'undefined'){ req = request[httpMethod](config.endpoint); setRequestHeaders(conn.connection, req); } nextHook(); }); }, function (err) { if(err) { return cb(err); } cb(null, req); }); }
javascript
function runBeforeHooks(req, method, config, conn, cb){ var httpMethod = conn.connection.methods[method]; async.eachSeries(conn.connection.hooks.before, function (hook, nextHook) { hook(req, httpMethod, config, conn, function (err) { if(err) { return nextHook(err); } if(!_.isEmpty(config.endpoint) && typeof req === 'undefined'){ req = request[httpMethod](config.endpoint); setRequestHeaders(conn.connection, req); } nextHook(); }); }, function (err) { if(err) { return cb(err); } cb(null, req); }); }
[ "function", "runBeforeHooks", "(", "req", ",", "method", ",", "config", ",", "conn", ",", "cb", ")", "{", "var", "httpMethod", "=", "conn", ".", "connection", ".", "methods", "[", "method", "]", ";", "async", ".", "eachSeries", "(", "conn", ".", "conne...
Run all hook functions defined on `connection.hooks.before`. Used to modify request properties before running the actual request. Creates a SuperAgent Request object as soon as `config.endpoint` is defined by one of the hooks. @note When using your own hooks, please ensure the first hook in the chain defines `config.endpoint` properly, so SuperAgent Request object can be initialized with the correct HTTP endpoint. @param {Request} req - SuperAgent HTTP Request object @param {String} method - The model method @param {Object} config - configuration object used to hold request-specific configuration. this is used to avoid polluting the connection's own configuration object. @param {Object} conn - connection configuration object: - {Object} connection - Waterline connection configuration object - {String} collection - collection name. appended to API pathname. For example, given the api `http://localhost:8080/api/v1`, a collection named `user` will resolve to `http://localhost:8080/api/v1/user`. - {Object} options - query options object. contains query conditions (`where`), sort, limit etc. as per Waterline's API. - {Array<Object>} values - values of records to create. @param {Function} cb - function with error (Error object, or a falsy value if finished succesfully) and req (SuperAgent Request object, or undefined if error is not falsy) that is called when runBeforeHooks finishes
[ "Run", "all", "hook", "functions", "defined", "on", "connection", ".", "hooks", ".", "before", ".", "Used", "to", "modify", "request", "properties", "before", "running", "the", "actual", "request", ".", "Creates", "a", "SuperAgent", "Request", "object", "as", ...
484898cec7af6c1d4eaff4cad100037d794edd37
https://github.com/zohararad/sails-rest/blob/484898cec7af6c1d4eaff4cad100037d794edd37/lib/connection.js#L27-L47
33,033
zohararad/sails-rest
lib/connection.js
runAfterHooks
function runAfterHooks(connection, err, res, cb){ async.eachSeries(connection.hooks.after, function (hook, nextHook) { hook(err, res, nextHook); }, cb); }
javascript
function runAfterHooks(connection, err, res, cb){ async.eachSeries(connection.hooks.after, function (hook, nextHook) { hook(err, res, nextHook); }, cb); }
[ "function", "runAfterHooks", "(", "connection", ",", "err", ",", "res", ",", "cb", ")", "{", "async", ".", "eachSeries", "(", "connection", ".", "hooks", ".", "after", ",", "function", "(", "hook", ",", "nextHook", ")", "{", "hook", "(", "err", ",", ...
Run all hook functions defined on `connection.hooks.after`. Used to modify the response object and optionally handle any relevant errors if any. @param {Object} connection - connection configuration object @param {Error} err - response error object @param {Response} res - SuperAgent HTTP Response object @param {Function} cb - function with error (Error object, or a falsy value if finished succesfully) that is called when runAfterHooks finishes
[ "Run", "all", "hook", "functions", "defined", "on", "connection", ".", "hooks", ".", "after", ".", "Used", "to", "modify", "the", "response", "object", "and", "optionally", "handle", "any", "relevant", "errors", "if", "any", "." ]
484898cec7af6c1d4eaff4cad100037d794edd37
https://github.com/zohararad/sails-rest/blob/484898cec7af6c1d4eaff4cad100037d794edd37/lib/connection.js#L57-L61
33,034
zohararad/sails-rest
lib/connection.js
setRequestHeaders
function setRequestHeaders(connection, req) { if(_.isObject(connection.headers)){ req.set(connection.headers); } }
javascript
function setRequestHeaders(connection, req) { if(_.isObject(connection.headers)){ req.set(connection.headers); } }
[ "function", "setRequestHeaders", "(", "connection", ",", "req", ")", "{", "if", "(", "_", ".", "isObject", "(", "connection", ".", "headers", ")", ")", "{", "req", ".", "set", "(", "connection", ".", "headers", ")", ";", "}", "}" ]
Sets headers on request object before issuing an HTTP request. @param {Object} connection - Waterline connection configuration object @param {Request} req - SuperAgent HTTP Request object
[ "Sets", "headers", "on", "request", "object", "before", "issuing", "an", "HTTP", "request", "." ]
484898cec7af6c1d4eaff4cad100037d794edd37
https://github.com/zohararad/sails-rest/blob/484898cec7af6c1d4eaff4cad100037d794edd37/lib/connection.js#L68-L72
33,035
zohararad/sails-rest
lib/connection.js
handleResponse
function handleResponse(connection, err, res, cb) { runAfterHooks(connection, err, res, function (errFromHooks) { if(errFromHooks) { return cb(errFromHooks, null); } else if (res === undefined) { cb(err, null); } else { cb(err, res.body); } }); }
javascript
function handleResponse(connection, err, res, cb) { runAfterHooks(connection, err, res, function (errFromHooks) { if(errFromHooks) { return cb(errFromHooks, null); } else if (res === undefined) { cb(err, null); } else { cb(err, res.body); } }); }
[ "function", "handleResponse", "(", "connection", ",", "err", ",", "res", ",", "cb", ")", "{", "runAfterHooks", "(", "connection", ",", "err", ",", "res", ",", "function", "(", "errFromHooks", ")", "{", "if", "(", "errFromHooks", ")", "{", "return", "cb",...
Handle SuperAgent HTTP Response. Calls hook functions followed by Waterline callback. @param {Object} connection - connection configuration object @param {Error} err - response error object @param {Response} res - SuperAgent HTTP Response object @param {Function} cb - function to call with query results.
[ "Handle", "SuperAgent", "HTTP", "Response", ".", "Calls", "hook", "functions", "followed", "by", "Waterline", "callback", "." ]
484898cec7af6c1d4eaff4cad100037d794edd37
https://github.com/zohararad/sails-rest/blob/484898cec7af6c1d4eaff4cad100037d794edd37/lib/connection.js#L81-L91
33,036
zohararad/sails-rest
lib/connection.js
getResponseHandler
function getResponseHandler(connection, cb) { return function (err, res) { if (res && !err) { err = null; } handleResponse(connection, err, res, cb); } }
javascript
function getResponseHandler(connection, cb) { return function (err, res) { if (res && !err) { err = null; } handleResponse(connection, err, res, cb); } }
[ "function", "getResponseHandler", "(", "connection", ",", "cb", ")", "{", "return", "function", "(", "err", ",", "res", ")", "{", "if", "(", "res", "&&", "!", "err", ")", "{", "err", "=", "null", ";", "}", "handleResponse", "(", "connection", ",", "e...
Creates a generic, anonymous HTTP response handler to handle SuperAgent responses. @param {Object} connection - Waterline connection configuration object @param {Function} cb - function to call with query results. @returns {Function} SuperAgent response handler
[ "Creates", "a", "generic", "anonymous", "HTTP", "response", "handler", "to", "handle", "SuperAgent", "responses", "." ]
484898cec7af6c1d4eaff4cad100037d794edd37
https://github.com/zohararad/sails-rest/blob/484898cec7af6c1d4eaff4cad100037d794edd37/lib/connection.js#L99-L106
33,037
zohararad/sails-rest
lib/hooks.js
castRecordDateFields
function castRecordDateFields(record) { _.forEach(record, function (value, key) { if(_.isString(value) && iso.test(value)){ record[key] = new Date(value); } }); }
javascript
function castRecordDateFields(record) { _.forEach(record, function (value, key) { if(_.isString(value) && iso.test(value)){ record[key] = new Date(value); } }); }
[ "function", "castRecordDateFields", "(", "record", ")", "{", "_", ".", "forEach", "(", "record", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "_", ".", "isString", "(", "value", ")", "&&", "iso", ".", "test", "(", "value", ")", "...
Convert ISO formatted strings on response object into Javascript Date objects. Used to cast date fields returned from HTTP response into their correct Date type. @param {Object} record - response record object to process.
[ "Convert", "ISO", "formatted", "strings", "on", "response", "object", "into", "Javascript", "Date", "objects", ".", "Used", "to", "cast", "date", "fields", "returned", "from", "HTTP", "response", "into", "their", "correct", "Date", "type", "." ]
484898cec7af6c1d4eaff4cad100037d794edd37
https://github.com/zohararad/sails-rest/blob/484898cec7af6c1d4eaff4cad100037d794edd37/lib/hooks.js#L64-L70
33,038
zohararad/sails-rest
lib/hooks.js
processResponse
function processResponse(err, res, cb){ if(!err) { if(Array.isArray(res.body)){ res.body.forEach(function (body) { castRecordDateFields(body); }); } else if (_.isObject(res.body)) { castRecordDateFields(res.body); } } cb(); }
javascript
function processResponse(err, res, cb){ if(!err) { if(Array.isArray(res.body)){ res.body.forEach(function (body) { castRecordDateFields(body); }); } else if (_.isObject(res.body)) { castRecordDateFields(res.body); } } cb(); }
[ "function", "processResponse", "(", "err", ",", "res", ",", "cb", ")", "{", "if", "(", "!", "err", ")", "{", "if", "(", "Array", ".", "isArray", "(", "res", ".", "body", ")", ")", "{", "res", ".", "body", ".", "forEach", "(", "function", "(", "...
Process HTTP response. Converts response objects date fields from Strings to Dates. @param {Error} err - HTTP response error @param {Response} res - SuperAgent HTTP Response object @param {Function} cb - function that is called when this hook finishes
[ "Process", "HTTP", "response", ".", "Converts", "response", "objects", "date", "fields", "from", "Strings", "to", "Dates", "." ]
484898cec7af6c1d4eaff4cad100037d794edd37
https://github.com/zohararad/sails-rest/blob/484898cec7af6c1d4eaff4cad100037d794edd37/lib/hooks.js#L78-L89
33,039
zohararad/sails-rest
examples/User.js
function (path, query, cb) { var httpMethod = 'get', config = User.datastore.config, endpoint = url.format({ host: config.host, pathname: path, protocol: config.protocol, query: query }), req = request[httpMethod](endpoint); req.end(cb); }
javascript
function (path, query, cb) { var httpMethod = 'get', config = User.datastore.config, endpoint = url.format({ host: config.host, pathname: path, protocol: config.protocol, query: query }), req = request[httpMethod](endpoint); req.end(cb); }
[ "function", "(", "path", ",", "query", ",", "cb", ")", "{", "var", "httpMethod", "=", "'get'", ",", "config", "=", "User", ".", "datastore", ".", "config", ",", "endpoint", "=", "url", ".", "format", "(", "{", "host", ":", "config", ".", "host", ",...
Send an arbitrary GET query to REST backend @param path request path @param query request query-string object `{paramA: "valueA"}` @param cb request end callback. See https://github.com/visionmedia/superagent
[ "Send", "an", "arbitrary", "GET", "query", "to", "REST", "backend" ]
484898cec7af6c1d4eaff4cad100037d794edd37
https://github.com/zohararad/sails-rest/blob/484898cec7af6c1d4eaff4cad100037d794edd37/examples/User.js#L22-L33
33,040
JustBlackBird/gulp-phpcs
reporters/file.js
function(callback) { var stream = this; // We don't need to write an empty file. if (collectedErrors.length === 0) { callback(); return; } var report = collectedErrors.join('\n\n').trim() + '\n'; // Write the error output to the defined file fs.writeFile(options.path, report, function(err) { if (err) { stream.emit('error', new gutil.PluginError('gulp-phpcs', err)); callback(); return; } // Build console info message var message = util.format( 'Your PHPCS report with %s got written to %s', chalk.red(pluralize('error', collectedErrors.length, true)), chalk.magenta(options.path) ); // And output it. gutil.log(message); callback(); }); }
javascript
function(callback) { var stream = this; // We don't need to write an empty file. if (collectedErrors.length === 0) { callback(); return; } var report = collectedErrors.join('\n\n').trim() + '\n'; // Write the error output to the defined file fs.writeFile(options.path, report, function(err) { if (err) { stream.emit('error', new gutil.PluginError('gulp-phpcs', err)); callback(); return; } // Build console info message var message = util.format( 'Your PHPCS report with %s got written to %s', chalk.red(pluralize('error', collectedErrors.length, true)), chalk.magenta(options.path) ); // And output it. gutil.log(message); callback(); }); }
[ "function", "(", "callback", ")", "{", "var", "stream", "=", "this", ";", "// We don't need to write an empty file.", "if", "(", "collectedErrors", ".", "length", "===", "0", ")", "{", "callback", "(", ")", ";", "return", ";", "}", "var", "report", "=", "c...
After we collected all errors, output them to the defined file.
[ "After", "we", "collected", "all", "errors", "output", "them", "to", "the", "defined", "file", "." ]
fd0424a59c1d825ef60eb9c8e9df158eba0c9913
https://github.com/JustBlackBird/gulp-phpcs/blob/fd0424a59c1d825ef60eb9c8e9df158eba0c9913/reporters/file.js#L38-L71
33,041
evanhuang8/iorejson
lib/rejson.js
Rejson
function Rejson(opts) { // Instantiation if (!(this instanceof Rejson)) { return new Rejson(opts); } EventEmitter.call(this); opts = opts || {}; _.defaults(opts, Rejson.defaultOptions); var redis = new Redis(opts); // Add new commands this.cmds = {}; for (var i in Rejson.commands) { var command = Rejson.commands[i]; var cmd = redis.createBuiltinCommand(command); this.cmds[command] = cmd.string; this.cmds[command + 'Buffer'] = cmd.buffer; } this.client = redis; var _this = this; this.client.on('ready', function() { _this.emit('ready'); }); }
javascript
function Rejson(opts) { // Instantiation if (!(this instanceof Rejson)) { return new Rejson(opts); } EventEmitter.call(this); opts = opts || {}; _.defaults(opts, Rejson.defaultOptions); var redis = new Redis(opts); // Add new commands this.cmds = {}; for (var i in Rejson.commands) { var command = Rejson.commands[i]; var cmd = redis.createBuiltinCommand(command); this.cmds[command] = cmd.string; this.cmds[command + 'Buffer'] = cmd.buffer; } this.client = redis; var _this = this; this.client.on('ready', function() { _this.emit('ready'); }); }
[ "function", "Rejson", "(", "opts", ")", "{", "// Instantiation", "if", "(", "!", "(", "this", "instanceof", "Rejson", ")", ")", "{", "return", "new", "Rejson", "(", "opts", ")", ";", "}", "EventEmitter", ".", "call", "(", "this", ")", ";", "opts", "=...
Creates a Rejson instance @constructor
[ "Creates", "a", "Rejson", "instance" ]
2a8d095b821888b24ceb9014322c91b0a255ec7e
https://github.com/evanhuang8/iorejson/blob/2a8d095b821888b24ceb9014322c91b0a255ec7e/lib/rejson.js#L12-L41
33,042
JustBlackBird/gulp-phpcs
reporters/fail.js
function(file, enc, callback) { var report = file.phpcsReport || {}; if (report.error) { phpcsError = true; if (options.failOnFirst) { var errorMessage = 'PHP Code Sniffer failed' + ' on ' + chalk.magenta(file.path); this.emit('error', new gutil.PluginError('gulp-phpcs', errorMessage)); callback(); return; } else { badFiles.push(chalk.magenta(file.path)); } } this.push(file); callback(); }
javascript
function(file, enc, callback) { var report = file.phpcsReport || {}; if (report.error) { phpcsError = true; if (options.failOnFirst) { var errorMessage = 'PHP Code Sniffer failed' + ' on ' + chalk.magenta(file.path); this.emit('error', new gutil.PluginError('gulp-phpcs', errorMessage)); callback(); return; } else { badFiles.push(chalk.magenta(file.path)); } } this.push(file); callback(); }
[ "function", "(", "file", ",", "enc", ",", "callback", ")", "{", "var", "report", "=", "file", ".", "phpcsReport", "||", "{", "}", ";", "if", "(", "report", ".", "error", ")", "{", "phpcsError", "=", "true", ";", "if", "(", "options", ".", "failOnFi...
Watch for errors
[ "Watch", "for", "errors" ]
fd0424a59c1d825ef60eb9c8e9df158eba0c9913
https://github.com/JustBlackBird/gulp-phpcs/blob/fd0424a59c1d825ef60eb9c8e9df158eba0c9913/reporters/fail.js#L25-L46
33,043
JustBlackBird/gulp-phpcs
reporters/fail.js
function(callback) { // We have to check "failOnFirst" flag to make sure we did not // throw the error before. if (phpcsError && !options.failOnFirst) { this.emit('error', new gutil.PluginError( 'gulp-phpcs', 'PHP Code Sniffer failed on \n ' + badFiles.join('\n ') )); } callback(); }
javascript
function(callback) { // We have to check "failOnFirst" flag to make sure we did not // throw the error before. if (phpcsError && !options.failOnFirst) { this.emit('error', new gutil.PluginError( 'gulp-phpcs', 'PHP Code Sniffer failed on \n ' + badFiles.join('\n ') )); } callback(); }
[ "function", "(", "callback", ")", "{", "// We have to check \"failOnFirst\" flag to make sure we did not", "// throw the error before.", "if", "(", "phpcsError", "&&", "!", "options", ".", "failOnFirst", ")", "{", "this", ".", "emit", "(", "'error'", ",", "new", "guti...
Abort if we had at least one error.
[ "Abort", "if", "we", "had", "at", "least", "one", "error", "." ]
fd0424a59c1d825ef60eb9c8e9df158eba0c9913
https://github.com/JustBlackBird/gulp-phpcs/blob/fd0424a59c1d825ef60eb9c8e9df158eba0c9913/reporters/fail.js#L49-L60
33,044
san650/ember-web-app
lib/utils/includes.js
includes
function includes(array, element) { if (!array) { return false; } const length = array.length; for (let i = 0; i < length; i++) { if (array[i] === element) { return true; } } return false; }
javascript
function includes(array, element) { if (!array) { return false; } const length = array.length; for (let i = 0; i < length; i++) { if (array[i] === element) { return true; } } return false; }
[ "function", "includes", "(", "array", ",", "element", ")", "{", "if", "(", "!", "array", ")", "{", "return", "false", ";", "}", "const", "length", "=", "array", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", ...
Polyfill for Array.prototype.includes for Node.js < 6
[ "Polyfill", "for", "Array", ".", "prototype", ".", "includes", "for", "Node", ".", "js", "<", "6" ]
df3120686064c3daf01fd9472a08d2c26afb979d
https://github.com/san650/ember-web-app/blob/df3120686064c3daf01fd9472a08d2c26afb979d/lib/utils/includes.js#L6-L20
33,045
magicmonkey/lifxjs
lifx.js
getMyIPs
function getMyIPs() { var ips = []; var ifs = os.networkInterfaces(); for (var i in ifs) { for (var j in ifs[i]) { ips.push(ifs[i][j].address); } } return ips; }
javascript
function getMyIPs() { var ips = []; var ifs = os.networkInterfaces(); for (var i in ifs) { for (var j in ifs[i]) { ips.push(ifs[i][j].address); } } return ips; }
[ "function", "getMyIPs", "(", ")", "{", "var", "ips", "=", "[", "]", ";", "var", "ifs", "=", "os", ".", "networkInterfaces", "(", ")", ";", "for", "(", "var", "i", "in", "ifs", ")", "{", "for", "(", "var", "j", "in", "ifs", "[", "i", "]", ")",...
Utility method to get a list of local IP addresses
[ "Utility", "method", "to", "get", "a", "list", "of", "local", "IP", "addresses" ]
cfb4814d447d119a4db410274499d8ee77f66d96
https://github.com/magicmonkey/lifxjs/blob/cfb4814d447d119a4db410274499d8ee77f66d96/lifx.js#L238-L247
33,046
OpenSTFoundation/openst-platform
lib/contract_interact/openst_utility.js
function (contractAddress) { // Helpful while deployement, since ENV variables are not set at that time contractAddress = contractAddress || openSTUtilityContractAddr; const oThis = this; oThis.contractAddress = contractAddress; openSTUtilityContractObj.options.address = contractAddress; //openSTUtilityContractObj.setProvider(web3Provider.currentProvider); OwnedKlass.call(oThis, contractAddress, web3Provider, openSTUtilityContractObj, UC_GAS_PRICE) }
javascript
function (contractAddress) { // Helpful while deployement, since ENV variables are not set at that time contractAddress = contractAddress || openSTUtilityContractAddr; const oThis = this; oThis.contractAddress = contractAddress; openSTUtilityContractObj.options.address = contractAddress; //openSTUtilityContractObj.setProvider(web3Provider.currentProvider); OwnedKlass.call(oThis, contractAddress, web3Provider, openSTUtilityContractObj, UC_GAS_PRICE) }
[ "function", "(", "contractAddress", ")", "{", "// Helpful while deployement, since ENV variables are not set at that time", "contractAddress", "=", "contractAddress", "||", "openSTUtilityContractAddr", ";", "const", "oThis", "=", "this", ";", "oThis", ".", "contractAddress", ...
OpenST Utility Contract constructor @constructor @augments OwnedKlass @param {string} contractAddress - address on Utility Chain where Contract has been deployed
[ "OpenST", "Utility", "Contract", "constructor" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/openst_utility.js#L41-L54
33,047
OpenSTFoundation/openst-platform
helpers/custom_console_logger.js
function (message) { var newMessage = ""; if (requestNamespace) { if (requestNamespace.get('reqId')) { newMessage += "[" + requestNamespace.get('reqId') + "]"; } if (requestNamespace.get('workerId')) { newMessage += "[Worker - " + requestNamespace.get('workerId') + "]"; } const hrTime = process.hrtime(); newMessage += "[" + timeInMilli(hrTime) + "]"; } newMessage += message; return newMessage; }
javascript
function (message) { var newMessage = ""; if (requestNamespace) { if (requestNamespace.get('reqId')) { newMessage += "[" + requestNamespace.get('reqId') + "]"; } if (requestNamespace.get('workerId')) { newMessage += "[Worker - " + requestNamespace.get('workerId') + "]"; } const hrTime = process.hrtime(); newMessage += "[" + timeInMilli(hrTime) + "]"; } newMessage += message; return newMessage; }
[ "function", "(", "message", ")", "{", "var", "newMessage", "=", "\"\"", ";", "if", "(", "requestNamespace", ")", "{", "if", "(", "requestNamespace", ".", "get", "(", "'reqId'", ")", ")", "{", "newMessage", "+=", "\"[\"", "+", "requestNamespace", ".", "ge...
Method to append Request in each log line. @param {string} message
[ "Method", "to", "append", "Request", "in", "each", "log", "line", "." ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/helpers/custom_console_logger.js#L43-L57
33,048
OpenSTFoundation/openst-platform
services/approve/branded_token.js
function (params) { const oThis = this; params = params || {}; oThis.erc20Address = params.erc20_address; oThis.approverAddress = params.approver_address; oThis.approverPassphrase = params.approver_passphrase; oThis.approveeAddress = params.approvee_address; oThis.toApproveAmount = new BigNumber(params.to_approve_amount); oThis.returnType = (params.options || {}).returnType || 'txHash'; }
javascript
function (params) { const oThis = this; params = params || {}; oThis.erc20Address = params.erc20_address; oThis.approverAddress = params.approver_address; oThis.approverPassphrase = params.approver_passphrase; oThis.approveeAddress = params.approvee_address; oThis.toApproveAmount = new BigNumber(params.to_approve_amount); oThis.returnType = (params.options || {}).returnType || 'txHash'; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "oThis", ".", "erc20Address", "=", "params", ".", "erc20_address", ";", "oThis", ".", "approverAddress", "=", "params", ".", "approver_...
Approve for spending Branded Token @param {object} params @param {string} params.erc20_address - Branded token EIP20 address @param {string} params.approver_address - Approver address @param {string} params.approver_passphrase - Approver passphrase @param {string} params.approvee_address - Approvee address @param {number} params.to_approve_amount - To Approve amount in weis @param {object} params.options - optional params @constructor
[ "Approve", "for", "spending", "Branded", "Token" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/approve/branded_token.js#L32-L42
33,049
OpenSTFoundation/openst-platform
services/stake_and_mint/approve_openst_value_contract.js
function (params) { const oThis = this ; params = params || {}; params.options = params.options || {}; if (params.options.returnType === 'txReceipt') { oThis.runInAsync = false; } else { oThis.runInAsync = true; } }
javascript
function (params) { const oThis = this ; params = params || {}; params.options = params.options || {}; if (params.options.returnType === 'txReceipt') { oThis.runInAsync = false; } else { oThis.runInAsync = true; } }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "params", ".", "options", "=", "params", ".", "options", "||", "{", "}", ";", "if", "(", "params", ".", "options", ".", "returnTy...
Approve OpenST Value Contract Service @param {object} params - @param {object} params.options - @param {string} params.options.returnType - Desired return type. possible values: uuid, txHash, txReceipt. Default: txHash @constructor
[ "Approve", "OpenST", "Value", "Contract", "Service" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/stake_and_mint/approve_openst_value_contract.js#L35-L49
33,050
OpenSTFoundation/openst-platform
services/stake_and_mint/approve_openst_value_contract.js
async function (toApproveAmount) { const oThis = this ; const approveRsp = await simpleToken.approve( stakerAddress, stakerPassphrase, openSTValueContractAddress, toApproveAmount, oThis.runInAsync ); return Promise.resolve(approveRsp); }
javascript
async function (toApproveAmount) { const oThis = this ; const approveRsp = await simpleToken.approve( stakerAddress, stakerPassphrase, openSTValueContractAddress, toApproveAmount, oThis.runInAsync ); return Promise.resolve(approveRsp); }
[ "async", "function", "(", "toApproveAmount", ")", "{", "const", "oThis", "=", "this", ";", "const", "approveRsp", "=", "await", "simpleToken", ".", "approve", "(", "stakerAddress", ",", "stakerPassphrase", ",", "openSTValueContractAddress", ",", "toApproveAmount", ...
Approve OpenSTValue contract for starting the stake and mint process. @param {BigNumber} toApproveAmount - this is the amount which is used for approval @return {promise<result>} @private @ignore
[ "Approve", "OpenSTValue", "contract", "for", "starting", "the", "stake", "and", "mint", "process", "." ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/stake_and_mint/approve_openst_value_contract.js#L91-L106
33,051
OpenSTFoundation/openst-platform
services/stake_and_mint/approve_openst_value_contract.js
function () { return simpleToken.balanceOf(stakerAddress) .then(function (result) { const stBalance = result.data['balance']; return new BigNumber(stBalance); }) }
javascript
function () { return simpleToken.balanceOf(stakerAddress) .then(function (result) { const stBalance = result.data['balance']; return new BigNumber(stBalance); }) }
[ "function", "(", ")", "{", "return", "simpleToken", ".", "balanceOf", "(", "stakerAddress", ")", ".", "then", "(", "function", "(", "result", ")", "{", "const", "stBalance", "=", "result", ".", "data", "[", "'balance'", "]", ";", "return", "new", "BigNum...
Get ST balance of staker @return {promise<result>} @private @ignore
[ "Get", "ST", "balance", "of", "staker" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/stake_and_mint/approve_openst_value_contract.js#L115-L122
33,052
OpenSTFoundation/openst-platform
lib/contract_interact/simple_stake.js
function (params) { this.contractAddress = params.contractAddress; this.currContract = new web3Provider.eth.Contract(simpleStakeContractAbi, this.contractAddress); //this.currContract.setProvider(web3Provider.currentProvider); }
javascript
function (params) { this.contractAddress = params.contractAddress; this.currContract = new web3Provider.eth.Contract(simpleStakeContractAbi, this.contractAddress); //this.currContract.setProvider(web3Provider.currentProvider); }
[ "function", "(", "params", ")", "{", "this", ".", "contractAddress", "=", "params", ".", "contractAddress", ";", "this", ".", "currContract", "=", "new", "web3Provider", ".", "eth", ".", "Contract", "(", "simpleStakeContractAbi", ",", "this", ".", "contractAdd...
Constructor to create object of SimpleStakeKlass @constructor @param {object} params - @param {string} params.contractAddress - simple Stake contract address
[ "Constructor", "to", "create", "object", "of", "SimpleStakeKlass" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/simple_stake.js#L31-L39
33,053
OpenSTFoundation/openst-platform
lib/contract_interact/simple_stake.js
function () { const oThis = this; const callback = async function (response) { if (response.isFailure()) { return response; } return responseHelper.successWithData({allTimeStakedAmount: response.data.getTotalStake}); }; return oThis._callMethod('getTotalStake').then(callback); }
javascript
function () { const oThis = this; const callback = async function (response) { if (response.isFailure()) { return response; } return responseHelper.successWithData({allTimeStakedAmount: response.data.getTotalStake}); }; return oThis._callMethod('getTotalStake').then(callback); }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ";", "const", "callback", "=", "async", "function", "(", "response", ")", "{", "if", "(", "response", ".", "isFailure", "(", ")", ")", "{", "return", "response", ";", "}", "return", "responseHel...
Fetch all time staked amount @return {promise<result>}
[ "Fetch", "all", "time", "staked", "amount" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/simple_stake.js#L49-L62
33,054
OpenSTFoundation/openst-platform
lib/contract_interact/simple_stake.js
function (methodName, args) { const oThis = this , btAddress = oThis.contractAddress , scope = oThis.currContract.methods , transactionObject = scope[methodName].apply(scope, (args || [])) , encodeABI = transactionObject.encodeABI() , transactionOutputs = contractInteractHelper.getTransactionOutputs(transactionObject) , resultData = {}; return contractInteractHelper.call(web3Provider, btAddress, encodeABI, {}, transactionOutputs) .then(function (decodedResponse) { return decodedResponse[0]; }) .then(function (response) { resultData[methodName] = response; return responseHelper.successWithData(resultData); }) .catch(function (err) { logger.error(err); return responseHelper.error({ internal_error_identifier: 'l_ci_bt_callMethod_' + methodName + '_1', api_error_identifier: 'something_went_wrong', error_config: basicHelper.fetchErrorConfig() }); }) ; }
javascript
function (methodName, args) { const oThis = this , btAddress = oThis.contractAddress , scope = oThis.currContract.methods , transactionObject = scope[methodName].apply(scope, (args || [])) , encodeABI = transactionObject.encodeABI() , transactionOutputs = contractInteractHelper.getTransactionOutputs(transactionObject) , resultData = {}; return contractInteractHelper.call(web3Provider, btAddress, encodeABI, {}, transactionOutputs) .then(function (decodedResponse) { return decodedResponse[0]; }) .then(function (response) { resultData[methodName] = response; return responseHelper.successWithData(resultData); }) .catch(function (err) { logger.error(err); return responseHelper.error({ internal_error_identifier: 'l_ci_bt_callMethod_' + methodName + '_1', api_error_identifier: 'something_went_wrong', error_config: basicHelper.fetchErrorConfig() }); }) ; }
[ "function", "(", "methodName", ",", "args", ")", "{", "const", "oThis", "=", "this", ",", "btAddress", "=", "oThis", ".", "contractAddress", ",", "scope", "=", "oThis", ".", "currContract", ".", "methods", ",", "transactionObject", "=", "scope", "[", "meth...
Wrapper method to fetch properties @param {string} methodName - Contract method name @param {array} args - method arguments @return {promise<result>} @ignore
[ "Wrapper", "method", "to", "fetch", "properties" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/simple_stake.js#L74-L101
33,055
OpenSTFoundation/openst-platform
lib/contract_interact/st_prime.js
function (contractAddress) { this.contractAddress = contractAddress; if (this.contractAddress) { stPrimeContractObj.options.address = this.contractAddress; } //stPrimeContractObj.setProvider(web3Provider.currentProvider); this.currContract = stPrimeContractObj; }
javascript
function (contractAddress) { this.contractAddress = contractAddress; if (this.contractAddress) { stPrimeContractObj.options.address = this.contractAddress; } //stPrimeContractObj.setProvider(web3Provider.currentProvider); this.currContract = stPrimeContractObj; }
[ "function", "(", "contractAddress", ")", "{", "this", ".", "contractAddress", "=", "contractAddress", ";", "if", "(", "this", ".", "contractAddress", ")", "{", "stPrimeContractObj", ".", "options", ".", "address", "=", "this", ".", "contractAddress", ";", "}",...
Constructor for ST Prime Contract Interact @constructor @param {string} contractAddress - address where Contract has been deployed
[ "Constructor", "for", "ST", "Prime", "Contract", "Interact" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/st_prime.js#L60-L70
33,056
OpenSTFoundation/openst-platform
lib/contract_interact/st_prime.js
async function () { const oThis = this , callMethodResult = await oThis._callMethod('uuid') , response = callMethodResult.data.uuid; return response[0]; }
javascript
async function () { const oThis = this , callMethodResult = await oThis._callMethod('uuid') , response = callMethodResult.data.uuid; return response[0]; }
[ "async", "function", "(", ")", "{", "const", "oThis", "=", "this", ",", "callMethodResult", "=", "await", "oThis", ".", "_callMethod", "(", "'uuid'", ")", ",", "response", "=", "callMethodResult", ".", "data", ".", "uuid", ";", "return", "response", "[", ...
Get branded token UUID @return {promise<result>}
[ "Get", "branded", "token", "UUID" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/st_prime.js#L79-L84
33,057
OpenSTFoundation/openst-platform
lib/contract_interact/st_prime.js
async function (senderName, customOptions) { const oThis = this , encodedABI = stPrimeContractObj.methods.initialize().encodeABI() , stPrimeTotalSupplyInWei = web3Provider.utils.toWei(coreConstants.OST_UTILITY_STPRIME_TOTAL_SUPPLY, "ether"); var options = {gasPrice: UC_GAS_PRICE, value: stPrimeTotalSupplyInWei, gas: UC_GAS_LIMIT}; Object.assign(options, customOptions); return contractInteractHelper.safeSend( web3Provider, oThis.contractAddress, encodedABI, senderName, options ); }
javascript
async function (senderName, customOptions) { const oThis = this , encodedABI = stPrimeContractObj.methods.initialize().encodeABI() , stPrimeTotalSupplyInWei = web3Provider.utils.toWei(coreConstants.OST_UTILITY_STPRIME_TOTAL_SUPPLY, "ether"); var options = {gasPrice: UC_GAS_PRICE, value: stPrimeTotalSupplyInWei, gas: UC_GAS_LIMIT}; Object.assign(options, customOptions); return contractInteractHelper.safeSend( web3Provider, oThis.contractAddress, encodedABI, senderName, options ); }
[ "async", "function", "(", "senderName", ",", "customOptions", ")", "{", "const", "oThis", "=", "this", ",", "encodedABI", "=", "stPrimeContractObj", ".", "methods", ".", "initialize", "(", ")", ".", "encodeABI", "(", ")", ",", "stPrimeTotalSupplyInWei", "=", ...
Initial Transfer of ST Prime while chain setup @param {string} senderName - address who is initializing this transfer - named managed key @param {object} customOptions - custom params for this transaction @return {promise<result>}
[ "Initial", "Transfer", "of", "ST", "Prime", "while", "chain", "setup" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/st_prime.js#L125-L141
33,058
OpenSTFoundation/openst-platform
lib/contract_interact/st_prime.js
async function (senderAddress, senderPassphrase, beneficiaryAddress) { const oThis = this , encodedABI = oThis.currContract.methods.claim(beneficiaryAddress).encodeABI() , currentGasPrice = new BigNumber(await web3Provider.eth.getGasPrice()) ; const estimateGasObj = new EstimateGasKlass({ contract_name: stPrimeContractName, contract_address: oThis.contractAddress, chain: 'utility', sender_address: senderAddress, method_name: 'claim', method_arguments: [beneficiaryAddress] }); const estimateGasResponse = await estimateGasObj.perform() , gasToUse = estimateGasResponse.data.gas_to_use ; return contractInteractHelper.safeSendFromAddr( web3Provider, oThis.contractAddress, encodedABI, senderAddress, senderPassphrase, { gasPrice: (currentGasPrice.equals(0) ? '0x0' : UC_GAS_PRICE), gas: gasToUse } ); }
javascript
async function (senderAddress, senderPassphrase, beneficiaryAddress) { const oThis = this , encodedABI = oThis.currContract.methods.claim(beneficiaryAddress).encodeABI() , currentGasPrice = new BigNumber(await web3Provider.eth.getGasPrice()) ; const estimateGasObj = new EstimateGasKlass({ contract_name: stPrimeContractName, contract_address: oThis.contractAddress, chain: 'utility', sender_address: senderAddress, method_name: 'claim', method_arguments: [beneficiaryAddress] }); const estimateGasResponse = await estimateGasObj.perform() , gasToUse = estimateGasResponse.data.gas_to_use ; return contractInteractHelper.safeSendFromAddr( web3Provider, oThis.contractAddress, encodedABI, senderAddress, senderPassphrase, { gasPrice: (currentGasPrice.equals(0) ? '0x0' : UC_GAS_PRICE), gas: gasToUse } ); }
[ "async", "function", "(", "senderAddress", ",", "senderPassphrase", ",", "beneficiaryAddress", ")", "{", "const", "oThis", "=", "this", ",", "encodedABI", "=", "oThis", ".", "currContract", ".", "methods", ".", "claim", "(", "beneficiaryAddress", ")", ".", "en...
Claim ST' for beneficiary after they are process-minted @param {string} senderAddress - address of sender @param {string} senderPassphrase - passphrase of senderAddress @param {string} beneficiaryAddress - address where funds would be credited @return {promise<result>}
[ "Claim", "ST", "for", "beneficiary", "after", "they", "are", "process", "-", "minted" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/st_prime.js#L152-L182
33,059
OpenSTFoundation/openst-platform
services/transaction/get_receipt.js
function (params) { const oThis = this ; params = params || {}; oThis.transactionHash = params.transaction_hash; oThis.chain = params.chain; oThis.addressToNameMap = params.address_to_name_map || {}; }
javascript
function (params) { const oThis = this ; params = params || {}; oThis.transactionHash = params.transaction_hash; oThis.chain = params.chain; oThis.addressToNameMap = params.address_to_name_map || {}; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "oThis", ".", "transactionHash", "=", "params", ".", "transaction_hash", ";", "oThis", ".", "chain", "=", "params", ".", "chain", ";"...
Get Transaction Receipt Service @param {object} params - @param {string} params.chain - Chain on which transaction was executed @param {string} params.transaction_hash - Transaction hash for lookup @param {object} params.address_to_name_map - hash of contract address to contract name @constructor
[ "Get", "Transaction", "Receipt", "Service" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/transaction/get_receipt.js#L26-L34
33,060
OpenSTFoundation/openst-platform
lib/contract_interact/openst_value.js
function (contractAddress) { // Helpful while deployement, since ENV variables are not set at that time contractAddress = contractAddress || openSTValueContractAddr; this.contractAddress = contractAddress; openSTValueContractObj.options.address = contractAddress; //openSTValueContractObj.setProvider(web3Provider.currentProvider); OpsManagedKlass.call(this, contractAddress, web3Provider, openSTValueContractObj, VC_GAS_PRICE); }
javascript
function (contractAddress) { // Helpful while deployement, since ENV variables are not set at that time contractAddress = contractAddress || openSTValueContractAddr; this.contractAddress = contractAddress; openSTValueContractObj.options.address = contractAddress; //openSTValueContractObj.setProvider(web3Provider.currentProvider); OpsManagedKlass.call(this, contractAddress, web3Provider, openSTValueContractObj, VC_GAS_PRICE); }
[ "function", "(", "contractAddress", ")", "{", "// Helpful while deployement, since ENV variables are not set at that time", "contractAddress", "=", "contractAddress", "||", "openSTValueContractAddr", ";", "this", ".", "contractAddress", "=", "contractAddress", ";", "openSTValueCo...
OpenST Value Contract constructor @constructor @augments OpsManagedKlass @param {String} contractAddress - address on Value Chain where Contract has been deployed
[ "OpenST", "Value", "Contract", "constructor" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/openst_value.js#L38-L48
33,061
OpenSTFoundation/openst-platform
lib/contract_interact/utility_registrar.js
function (contractAddress) { const oThis = this; oThis.contractAddress = contractAddress; utilityRegistrarContractObj.options.address = oThis.contractAddress; //utilityRegistrarContractObj.setProvider(web3Provider.currentProvider); OpsManagedKlass.call(oThis, oThis.contractAddress, web3Provider, utilityRegistrarContractObj, UC_GAS_PRICE); }
javascript
function (contractAddress) { const oThis = this; oThis.contractAddress = contractAddress; utilityRegistrarContractObj.options.address = oThis.contractAddress; //utilityRegistrarContractObj.setProvider(web3Provider.currentProvider); OpsManagedKlass.call(oThis, oThis.contractAddress, web3Provider, utilityRegistrarContractObj, UC_GAS_PRICE); }
[ "function", "(", "contractAddress", ")", "{", "const", "oThis", "=", "this", ";", "oThis", ".", "contractAddress", "=", "contractAddress", ";", "utilityRegistrarContractObj", ".", "options", ".", "address", "=", "oThis", ".", "contractAddress", ";", "//utilityRegi...
Constructor for Utility Registrar Contract Interact @constructor @augments OpsManagedKlass @param {string} contractAddress - address where Contract has been deployed
[ "Constructor", "for", "Utility", "Registrar", "Contract", "Interact" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/utility_registrar.js#L38-L47
33,062
OpenSTFoundation/openst-platform
tools/setup/simple_token_prime/mint.js
function() { return new Promise(function(onResolve, onReject) { const getBalance = async function(){ const getSTPBalanceResponse = await fundManager.getSTPrimeBalanceOf(utilityChainOwnerAddr); if(getSTPBalanceResponse.isSuccess() && (new BigNumber(getSTPBalanceResponse.data.balance)).greaterThan(0)){ logger.info('* ST\' credited to utility chain owner'); return onResolve(getSTPBalanceResponse); } else { logger.info('* Waiting for credit of ST\' to utility chain owner'); setTimeout(getBalance, 60000); } }; getBalance(); }); }
javascript
function() { return new Promise(function(onResolve, onReject) { const getBalance = async function(){ const getSTPBalanceResponse = await fundManager.getSTPrimeBalanceOf(utilityChainOwnerAddr); if(getSTPBalanceResponse.isSuccess() && (new BigNumber(getSTPBalanceResponse.data.balance)).greaterThan(0)){ logger.info('* ST\' credited to utility chain owner'); return onResolve(getSTPBalanceResponse); } else { logger.info('* Waiting for credit of ST\' to utility chain owner'); setTimeout(getBalance, 60000); } }; getBalance(); }); }
[ "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "onResolve", ",", "onReject", ")", "{", "const", "getBalance", "=", "async", "function", "(", ")", "{", "const", "getSTPBalanceResponse", "=", "await", "fundManager", ".", "getSTPri...
Wait for ST Prime mint @return {promise} @private
[ "Wait", "for", "ST", "Prime", "mint" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/simple_token_prime/mint.js#L89-L107
33,063
OpenSTFoundation/openst-platform
services/transaction/estimate_gas.js
function (params) { const oThis = this ; oThis.contractName = params.contract_name; oThis.contractAddress = params.contract_address; oThis.chain = params.chain; oThis.senderAddress = params.sender_address; oThis.methodName = params.method_name; oThis.methodArguments = params.method_arguments; }
javascript
function (params) { const oThis = this ; oThis.contractName = params.contract_name; oThis.contractAddress = params.contract_address; oThis.chain = params.chain; oThis.senderAddress = params.sender_address; oThis.methodName = params.method_name; oThis.methodArguments = params.method_arguments; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "oThis", ".", "contractName", "=", "params", ".", "contract_name", ";", "oThis", ".", "contractAddress", "=", "params", ".", "contract_address", ";", "oThis", ".", "chain", "=", "para...
Estimate gas for a transaction service constructor @param {object} params @param {string} params.contract_name - Name of the contract having the method which needs to be called @param {string} params.contract_address - Address of the contract @param {string} params.chain - Chain on which the contract was deployed @param {string} params.sender_address - sender address @param {string} params.method_name - name of the method which needs to be called @param {string} params.method_arguments - arguments to be passed to the method @constructor
[ "Estimate", "gas", "for", "a", "transaction", "service", "constructor" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/transaction/estimate_gas.js#L35-L45
33,064
OpenSTFoundation/openst-platform
lib/contract_interact/helper.js
function (web3Provider, result) { return new Promise(function (onResolve, onReject) { onResolve(web3Provider.eth.abi.decodeParameter('address', result)); }); }
javascript
function (web3Provider, result) { return new Promise(function (onResolve, onReject) { onResolve(web3Provider.eth.abi.decodeParameter('address', result)); }); }
[ "function", "(", "web3Provider", ",", "result", ")", "{", "return", "new", "Promise", "(", "function", "(", "onResolve", ",", "onReject", ")", "{", "onResolve", "(", "web3Provider", ".", "eth", ".", "abi", ".", "decodeParameter", "(", "'address'", ",", "re...
Decode result and typecast it to an Address @param {web3} web3Provider - It could be value chain or utility chain provider @param {string} result - current contract address @return {promise}
[ "Decode", "result", "and", "typecast", "it", "to", "an", "Address" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/helper.js#L165-L169
33,065
OpenSTFoundation/openst-platform
lib/contract_interact/helper.js
function (web3Provider, result) { return new Promise(function (onResolve, onReject) { onResolve(web3Provider.utils.hexToNumber(result)); }); }
javascript
function (web3Provider, result) { return new Promise(function (onResolve, onReject) { onResolve(web3Provider.utils.hexToNumber(result)); }); }
[ "function", "(", "web3Provider", ",", "result", ")", "{", "return", "new", "Promise", "(", "function", "(", "onResolve", ",", "onReject", ")", "{", "onResolve", "(", "web3Provider", ".", "utils", ".", "hexToNumber", "(", "result", ")", ")", ";", "}", ")"...
Decode result and typecast it to a Number @param {web3} web3Provider - It could be value chain or utility chain provider @param {string} result - current contract address @return {promise}
[ "Decode", "result", "and", "typecast", "it", "to", "a", "Number" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/helper.js#L195-L199
33,066
OpenSTFoundation/openst-platform
lib/contract_interact/helper.js
function (web3Provider, transactionHash) { return new Promise(function (onResolve, onReject) { // number of times it will attempt to fetch var maxAttempts = 50; // time interval const timeInterval = 15000; var getReceipt = async function () { if (maxAttempts > 0) { const receipt = await web3Provider.eth.getTransactionReceipt(transactionHash); if (receipt) { return onResolve(responseHelper.successWithData({receipt: receipt})); } else { maxAttempts--; setTimeout(getReceipt, timeInterval); } } else { let errObj = responseHelper.error({ internal_error_identifier: 'l_ci_h_getTransactionReceiptFromTrasactionHash', api_error_identifier: 'receipt_not_found', error_config: basicHelper.fetchErrorConfig() }); return onResolve(errObj); } }; getReceipt(); }); }
javascript
function (web3Provider, transactionHash) { return new Promise(function (onResolve, onReject) { // number of times it will attempt to fetch var maxAttempts = 50; // time interval const timeInterval = 15000; var getReceipt = async function () { if (maxAttempts > 0) { const receipt = await web3Provider.eth.getTransactionReceipt(transactionHash); if (receipt) { return onResolve(responseHelper.successWithData({receipt: receipt})); } else { maxAttempts--; setTimeout(getReceipt, timeInterval); } } else { let errObj = responseHelper.error({ internal_error_identifier: 'l_ci_h_getTransactionReceiptFromTrasactionHash', api_error_identifier: 'receipt_not_found', error_config: basicHelper.fetchErrorConfig() }); return onResolve(errObj); } }; getReceipt(); }); }
[ "function", "(", "web3Provider", ",", "transactionHash", ")", "{", "return", "new", "Promise", "(", "function", "(", "onResolve", ",", "onReject", ")", "{", "// number of times it will attempt to fetch", "var", "maxAttempts", "=", "50", ";", "// time interval", "con...
Get transaction receipt @param {object} web3Provider - It could be value chain or utility chain provider @param {string} transactionHash - transaction hash @return {promise<result>}
[ "Get", "transaction", "receipt" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/helper.js#L269-L300
33,067
OpenSTFoundation/openst-platform
services/utils/generate_address.js
function (params) { const oThis = this ; params = params || {}; oThis.passphrase = params.passphrase || ''; oThis.chain = params.chain; }
javascript
function (params) { const oThis = this ; params = params || {}; oThis.passphrase = params.passphrase || ''; oThis.chain = params.chain; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "oThis", ".", "passphrase", "=", "params", ".", "passphrase", "||", "''", ";", "oThis", ".", "chain", "=", "params", ".", "chain", ...
Constructor to generate a new address @param {object} params @param {string} params.chain - Chain on which this new address should be generated and stored @param {string} [params.passphrase] - Passphrase for the new address. Default: blank @constructor
[ "Constructor", "to", "generate", "a", "new", "address" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/utils/generate_address.js#L25-L32
33,068
OpenSTFoundation/openst-platform
tools/setup/geth_checker.js
function () { const oThis = this , promiseArray = []; return new Promise(async function (onResolve, onReject) { for (var chain in setupConfig.chains) { promiseArray.push(oThis._isRunning(chain)); } return Promise.all(promiseArray).then(onResolve); }); }
javascript
function () { const oThis = this , promiseArray = []; return new Promise(async function (onResolve, onReject) { for (var chain in setupConfig.chains) { promiseArray.push(oThis._isRunning(chain)); } return Promise.all(promiseArray).then(onResolve); }); }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ",", "promiseArray", "=", "[", "]", ";", "return", "new", "Promise", "(", "async", "function", "(", "onResolve", ",", "onReject", ")", "{", "for", "(", "var", "chain", "in", "setupConfig", ".", ...
Check if chains started mining and are ready @return {promise}
[ "Check", "if", "chains", "started", "mining", "and", "are", "ready" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/geth_checker.js#L28-L38
33,069
OpenSTFoundation/openst-platform
tools/setup/geth_checker.js
function(chain) { const retryAttempts = 100 , timerInterval = 5000 , chainTimer = {timer: undefined, blockNumber: 0, retryCounter: 0} , provider = (chain == 'utility' ? web3UtilityProvider : web3ValueProvider) ; return new Promise(function (onResolve, onReject) { chainTimer['timer'] = setInterval(function () { if (chainTimer['retryCounter'] <= retryAttempts) { provider.eth.getBlockNumber(function (err, blocknumber) { if (err) { } else { if (chainTimer['blockNumber']!=0 && chainTimer['blockNumber']!=blocknumber) { logger.info("* Geth Checker - " + chain + " chain has new blocks."); clearInterval(chainTimer['timer']); onResolve(); } chainTimer['blockNumber'] = blocknumber; } }); } else { logger.error("Geth Checker - " + chain + " chain has no new blocks."); onReject(); process.exit(1); } chainTimer['retryCounter']++; }, timerInterval); }); }
javascript
function(chain) { const retryAttempts = 100 , timerInterval = 5000 , chainTimer = {timer: undefined, blockNumber: 0, retryCounter: 0} , provider = (chain == 'utility' ? web3UtilityProvider : web3ValueProvider) ; return new Promise(function (onResolve, onReject) { chainTimer['timer'] = setInterval(function () { if (chainTimer['retryCounter'] <= retryAttempts) { provider.eth.getBlockNumber(function (err, blocknumber) { if (err) { } else { if (chainTimer['blockNumber']!=0 && chainTimer['blockNumber']!=blocknumber) { logger.info("* Geth Checker - " + chain + " chain has new blocks."); clearInterval(chainTimer['timer']); onResolve(); } chainTimer['blockNumber'] = blocknumber; } }); } else { logger.error("Geth Checker - " + chain + " chain has no new blocks."); onReject(); process.exit(1); } chainTimer['retryCounter']++; }, timerInterval); }); }
[ "function", "(", "chain", ")", "{", "const", "retryAttempts", "=", "100", ",", "timerInterval", "=", "5000", ",", "chainTimer", "=", "{", "timer", ":", "undefined", ",", "blockNumber", ":", "0", ",", "retryCounter", ":", "0", "}", ",", "provider", "=", ...
Check if mentioned chain started mining and are ready @param {string} chain - name of the chain @return {promise}
[ "Check", "if", "mentioned", "chain", "started", "mining", "and", "are", "ready" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/geth_checker.js#L47-L75
33,070
OpenSTFoundation/openst-platform
tools/setup/start_services.js
async function () { const oThis = this , servicesList = []; var cmd = "ps aux | grep dynamo | grep -v grep | tr -s ' ' | cut -d ' ' -f2"; let processId = shell.exec(cmd).stdout; if (processId == '') { // Start Dynamo DB in openST env let startDynamo = new StartDynamo(); await startDynamo.perform(); } // Start Value Chain logger.step("** Start value chain"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-value.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); // Start Utility Chain logger.step("** Start utility chain"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-utility.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); // Wait for 5 seconds for geth to come up const sleep = function(ms) { return new Promise(function(resolve) {setTimeout(resolve, ms)}); }; await sleep(5000); // Check geths are up and running logger.step("** Check chains are up and responding"); const statusObj = new platformStatus() , servicesResponse = await statusObj.perform(); if (servicesResponse.isFailure()) { logger.error("* Error ", servicesResponse); process.exit(1); } else { logger.info("* Value Chain:", servicesResponse.data.chain.value, "Utility Chain:", servicesResponse.data.chain.utility); } // Start intercom processes in openST env logger.step("** Start stake and mint inter-communication process"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-stake_and_mint.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); logger.step("** Start redeem and unstake inter-communication process"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-redeem_and_unstake.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); logger.step("** Start register branded token inter-communication process"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-register_branded_token.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); // Start intercom processes in OST env logger.step("** Start stake and mint processor"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-stake_and_mint_processor.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); logger.step("** Start redeem and unstake processor"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-redeem_and_unstake_processor.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); logger.win("\n** Congratulation! All services are up and running. \n" + "NOTE: We will keep monitoring the services, and notify you if any service stops."); // Check all services are running oThis._uptime(servicesList); }
javascript
async function () { const oThis = this , servicesList = []; var cmd = "ps aux | grep dynamo | grep -v grep | tr -s ' ' | cut -d ' ' -f2"; let processId = shell.exec(cmd).stdout; if (processId == '') { // Start Dynamo DB in openST env let startDynamo = new StartDynamo(); await startDynamo.perform(); } // Start Value Chain logger.step("** Start value chain"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-value.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); // Start Utility Chain logger.step("** Start utility chain"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-utility.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); // Wait for 5 seconds for geth to come up const sleep = function(ms) { return new Promise(function(resolve) {setTimeout(resolve, ms)}); }; await sleep(5000); // Check geths are up and running logger.step("** Check chains are up and responding"); const statusObj = new platformStatus() , servicesResponse = await statusObj.perform(); if (servicesResponse.isFailure()) { logger.error("* Error ", servicesResponse); process.exit(1); } else { logger.info("* Value Chain:", servicesResponse.data.chain.value, "Utility Chain:", servicesResponse.data.chain.utility); } // Start intercom processes in openST env logger.step("** Start stake and mint inter-communication process"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-stake_and_mint.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); logger.step("** Start redeem and unstake inter-communication process"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-redeem_and_unstake.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); logger.step("** Start register branded token inter-communication process"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-register_branded_token.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); // Start intercom processes in OST env logger.step("** Start stake and mint processor"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-stake_and_mint_processor.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); logger.step("** Start redeem and unstake processor"); var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-redeem_and_unstake_processor.sh"; servicesList.push(cmd); oThis._asyncCommand(cmd); logger.win("\n** Congratulation! All services are up and running. \n" + "NOTE: We will keep monitoring the services, and notify you if any service stops."); // Check all services are running oThis._uptime(servicesList); }
[ "async", "function", "(", ")", "{", "const", "oThis", "=", "this", ",", "servicesList", "=", "[", "]", ";", "var", "cmd", "=", "\"ps aux | grep dynamo | grep -v grep | tr -s ' ' | cut -d ' ' -f2\"", ";", "let", "processId", "=", "shell", ".", "exec", "(", "cmd",...
Start all platform services
[ "Start", "all", "platform", "services" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/start_services.js#L35-L109
33,071
OpenSTFoundation/openst-platform
tools/setup/env_manager.js
function(purpose) { const oThis = this; // Create empty ENV file fileManager.touch(setupConfig.env_vars_file, '#!/bin/sh'); fileManager.append(setupConfig.env_vars_file, '#################'); fileManager.append(setupConfig.env_vars_file, '# opentST Platform Environment file'); fileManager.append(setupConfig.env_vars_file, '#################'); logger.info('* writing env basic, geth, cache and addresses related env vars'); // Create geth ENV variables oThis._gethVars(purpose); // Create cache ENV variables oThis._cacheVars(); // Create notification ENV variables oThis._notificationVars(); // Create miscellaneous ENV variables oThis._miscellaneousVars(); // Create dynamodb ENV variables oThis._dynamodbVars(); // Create dynamodb auto scaling ENV variables oThis._dynamodbAutoScalingVars(); // Create contract address ENV variables oThis._contractAddressVars(); // Create address ENV variables oThis._addressVars(); }
javascript
function(purpose) { const oThis = this; // Create empty ENV file fileManager.touch(setupConfig.env_vars_file, '#!/bin/sh'); fileManager.append(setupConfig.env_vars_file, '#################'); fileManager.append(setupConfig.env_vars_file, '# opentST Platform Environment file'); fileManager.append(setupConfig.env_vars_file, '#################'); logger.info('* writing env basic, geth, cache and addresses related env vars'); // Create geth ENV variables oThis._gethVars(purpose); // Create cache ENV variables oThis._cacheVars(); // Create notification ENV variables oThis._notificationVars(); // Create miscellaneous ENV variables oThis._miscellaneousVars(); // Create dynamodb ENV variables oThis._dynamodbVars(); // Create dynamodb auto scaling ENV variables oThis._dynamodbAutoScalingVars(); // Create contract address ENV variables oThis._contractAddressVars(); // Create address ENV variables oThis._addressVars(); }
[ "function", "(", "purpose", ")", "{", "const", "oThis", "=", "this", ";", "// Create empty ENV file", "fileManager", ".", "touch", "(", "setupConfig", ".", "env_vars_file", ",", "'#!/bin/sh'", ")", ";", "fileManager", ".", "append", "(", "setupConfig", ".", "e...
Generate ENV file from config.js
[ "Generate", "ENV", "file", "from", "config", ".", "js" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/env_manager.js#L24-L58
33,072
OpenSTFoundation/openst-platform
tools/setup/env_manager.js
function (purpose) { const oThis = this; for (var chain in setupConfig.chains) { // Add comment to ENV fileManager.append(setupConfig.env_vars_file, "\n# "+chain+" chain"); // Add content oThis._scanAndPopulateEnvVars(setupConfig.chains[chain],purpose); } }
javascript
function (purpose) { const oThis = this; for (var chain in setupConfig.chains) { // Add comment to ENV fileManager.append(setupConfig.env_vars_file, "\n# "+chain+" chain"); // Add content oThis._scanAndPopulateEnvVars(setupConfig.chains[chain],purpose); } }
[ "function", "(", "purpose", ")", "{", "const", "oThis", "=", "this", ";", "for", "(", "var", "chain", "in", "setupConfig", ".", "chains", ")", "{", "// Add comment to ENV", "fileManager", ".", "append", "(", "setupConfig", ".", "env_vars_file", ",", "\"\\n# ...
Populate all chains related env variables
[ "Populate", "all", "chains", "related", "env", "variables" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/env_manager.js#L63-L72
33,073
OpenSTFoundation/openst-platform
tools/setup/env_manager.js
function () { const oThis = this; // Add comment to ENV fileManager.append(setupConfig.env_vars_file, "\n# Contracts"); for (var address in setupConfig.contracts) { oThis._scanAndPopulateEnvVars(setupConfig.contracts[address]); } }
javascript
function () { const oThis = this; // Add comment to ENV fileManager.append(setupConfig.env_vars_file, "\n# Contracts"); for (var address in setupConfig.contracts) { oThis._scanAndPopulateEnvVars(setupConfig.contracts[address]); } }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ";", "// Add comment to ENV", "fileManager", ".", "append", "(", "setupConfig", ".", "env_vars_file", ",", "\"\\n# Contracts\"", ")", ";", "for", "(", "var", "address", "in", "setupConfig", ".", "contra...
Populate all contract address related env variables
[ "Populate", "all", "contract", "address", "related", "env", "variables" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/env_manager.js#L137-L146
33,074
OpenSTFoundation/openst-platform
services/inter_comm/base.js
function () { const oThis = this , clearCacheOfExpr = /(openst-platform\/config\/)|(openst-platform\/lib\/)/ ; Object.keys(require.cache).forEach(function (key) { if (key.search(clearCacheOfExpr) !== -1) { delete require.cache[key]; } }); oThis.setContractObj(); // Read this from a file oThis.snmData = JSON.parse(fs.readFileSync(oThis.filePath).toString()); oThis.checkForFurtherEvents(); }
javascript
function () { const oThis = this , clearCacheOfExpr = /(openst-platform\/config\/)|(openst-platform\/lib\/)/ ; Object.keys(require.cache).forEach(function (key) { if (key.search(clearCacheOfExpr) !== -1) { delete require.cache[key]; } }); oThis.setContractObj(); // Read this from a file oThis.snmData = JSON.parse(fs.readFileSync(oThis.filePath).toString()); oThis.checkForFurtherEvents(); }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ",", "clearCacheOfExpr", "=", "/", "(openst-platform\\/config\\/)|(openst-platform\\/lib\\/)", "/", ";", "Object", ".", "keys", "(", "require", ".", "cache", ")", ".", "forEach", "(", "function", "(", "...
Starts the process of the script with initializing processor
[ "Starts", "the", "process", "of", "the", "script", "with", "initializing", "processor" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/inter_comm/base.js#L32-L48
33,075
OpenSTFoundation/openst-platform
services/inter_comm/base.js
async function () { const oThis = this ; try { const highestBlock = await this.getChainHighestBlock(); // return if nothing more to do. if (highestBlock - 6 <= oThis.lastProcessedBlock) return oThis.schedule(); // consider case in which last block was not processed completely oThis.fromBlock = oThis.snmData.lastProcessedBlock + 1; oThis.toBlock = highestBlock - 6; const events = await oThis.completeContract.getPastEvents( oThis.EVENT_NAME, {fromBlock: oThis.fromBlock, toBlock: oThis.toBlock}, function (error, logs) { if (error) logger.error('getPastEvents error:', error); logger.log('getPastEvents done from block:', oThis.fromBlock, 'to block:', oThis.toBlock); } ); await oThis.processEventsArray(events); oThis.schedule(); } catch (err) { logger.info('Exception got:', err); if (oThis.interruptSignalObtained) { logger.info('Exiting Process....'); process.exit(1); } else { oThis.reInit(); } } }
javascript
async function () { const oThis = this ; try { const highestBlock = await this.getChainHighestBlock(); // return if nothing more to do. if (highestBlock - 6 <= oThis.lastProcessedBlock) return oThis.schedule(); // consider case in which last block was not processed completely oThis.fromBlock = oThis.snmData.lastProcessedBlock + 1; oThis.toBlock = highestBlock - 6; const events = await oThis.completeContract.getPastEvents( oThis.EVENT_NAME, {fromBlock: oThis.fromBlock, toBlock: oThis.toBlock}, function (error, logs) { if (error) logger.error('getPastEvents error:', error); logger.log('getPastEvents done from block:', oThis.fromBlock, 'to block:', oThis.toBlock); } ); await oThis.processEventsArray(events); oThis.schedule(); } catch (err) { logger.info('Exception got:', err); if (oThis.interruptSignalObtained) { logger.info('Exiting Process....'); process.exit(1); } else { oThis.reInit(); } } }
[ "async", "function", "(", ")", "{", "const", "oThis", "=", "this", ";", "try", "{", "const", "highestBlock", "=", "await", "this", ".", "getChainHighestBlock", "(", ")", ";", "// return if nothing more to do.", "if", "(", "highestBlock", "-", "6", "<=", "oTh...
Check for further events
[ "Check", "for", "further", "events" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/inter_comm/base.js#L54-L91
33,076
OpenSTFoundation/openst-platform
services/inter_comm/base.js
function () { const oThis = this; process.on('SIGINT', function () { logger.info("Received SIGINT, cancelling block scaning"); oThis.interruptSignalObtained = true; }); process.on('SIGTERM', function () { logger.info("Received SIGTERM, cancelling block scaning"); oThis.interruptSignalObtained = true; }); }
javascript
function () { const oThis = this; process.on('SIGINT', function () { logger.info("Received SIGINT, cancelling block scaning"); oThis.interruptSignalObtained = true; }); process.on('SIGTERM', function () { logger.info("Received SIGTERM, cancelling block scaning"); oThis.interruptSignalObtained = true; }); }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ";", "process", ".", "on", "(", "'SIGINT'", ",", "function", "(", ")", "{", "logger", ".", "info", "(", "\"Received SIGINT, cancelling block scaning\"", ")", ";", "oThis", ".", "interruptSignalObtained"...
Register interrup signal handlers
[ "Register", "interrup", "signal", "handlers" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/inter_comm/base.js#L97-L108
33,077
OpenSTFoundation/openst-platform
services/inter_comm/base.js
async function (events) { const oThis = this , promiseArray = [] ; // nothing to do if (!events || events.length === 0) { oThis.updateIntercomDataFile(); return Promise.resolve(); } //TODO: last processed transaction index. for (var i = 0; i < events.length; i++) { const eventObj = events[i] , j = i ; // await oThis.processEventObj(eventObj); if (oThis.parallelProcessingAllowed()) { promiseArray.push(new Promise(function (onResolve, onReject) { setTimeout(function () { oThis.processEventObj(eventObj) .then(onResolve) .catch(function (error) { logger.error('##### inside catch block #####: ', error); return onResolve(); }); }, (j * 1000 + 100)); })); } else { await oThis.processEventObj(eventObj) .catch(function (error) { logger.error('inside catch block: ', error); return Promise.resolve(); }); } } if (oThis.parallelProcessingAllowed()) { await Promise.all(promiseArray); } oThis.updateIntercomDataFile(); return Promise.resolve(); }
javascript
async function (events) { const oThis = this , promiseArray = [] ; // nothing to do if (!events || events.length === 0) { oThis.updateIntercomDataFile(); return Promise.resolve(); } //TODO: last processed transaction index. for (var i = 0; i < events.length; i++) { const eventObj = events[i] , j = i ; // await oThis.processEventObj(eventObj); if (oThis.parallelProcessingAllowed()) { promiseArray.push(new Promise(function (onResolve, onReject) { setTimeout(function () { oThis.processEventObj(eventObj) .then(onResolve) .catch(function (error) { logger.error('##### inside catch block #####: ', error); return onResolve(); }); }, (j * 1000 + 100)); })); } else { await oThis.processEventObj(eventObj) .catch(function (error) { logger.error('inside catch block: ', error); return Promise.resolve(); }); } } if (oThis.parallelProcessingAllowed()) { await Promise.all(promiseArray); } oThis.updateIntercomDataFile(); return Promise.resolve(); }
[ "async", "function", "(", "events", ")", "{", "const", "oThis", "=", "this", ",", "promiseArray", "=", "[", "]", ";", "// nothing to do", "if", "(", "!", "events", "||", "events", ".", "length", "===", "0", ")", "{", "oThis", ".", "updateIntercomDataFile...
Process events array @param {array} events - events array
[ "Process", "events", "array" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/inter_comm/base.js#L116-L161
33,078
OpenSTFoundation/openst-platform
services/inter_comm/base.js
function () { const oThis = this ; oThis.snmData.lastProcessedBlock = oThis.toBlock; fs.writeFileSync( oThis.filePath, JSON.stringify(oThis.snmData), function (err) { if (err) logger.error(err); } ); if (oThis.interruptSignalObtained) { logger.info('Exiting Process....'); process.exit(1); } }
javascript
function () { const oThis = this ; oThis.snmData.lastProcessedBlock = oThis.toBlock; fs.writeFileSync( oThis.filePath, JSON.stringify(oThis.snmData), function (err) { if (err) logger.error(err); } ); if (oThis.interruptSignalObtained) { logger.info('Exiting Process....'); process.exit(1); } }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ";", "oThis", ".", "snmData", ".", "lastProcessedBlock", "=", "oThis", ".", "toBlock", ";", "fs", ".", "writeFileSync", "(", "oThis", ".", "filePath", ",", "JSON", ".", "stringify", "(", "oThis", ...
Update intercom data file
[ "Update", "intercom", "data", "file" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/inter_comm/base.js#L188-L207
33,079
OpenSTFoundation/openst-platform
services/utils/platform_status.js
async function () { const oThis = this , statusResponse = {chain: {value: false, utility: false}}; // check geth status for (var chainName in statusResponse.chain) { var response = await oThis._gethStatus(chainName); if (response.isSuccess()) { statusResponse.chain[chainName] = true; } else { return Promise.resolve(response); } } return Promise.resolve(responseHelper.successWithData(statusResponse)); }
javascript
async function () { const oThis = this , statusResponse = {chain: {value: false, utility: false}}; // check geth status for (var chainName in statusResponse.chain) { var response = await oThis._gethStatus(chainName); if (response.isSuccess()) { statusResponse.chain[chainName] = true; } else { return Promise.resolve(response); } } return Promise.resolve(responseHelper.successWithData(statusResponse)); }
[ "async", "function", "(", ")", "{", "const", "oThis", "=", "this", ",", "statusResponse", "=", "{", "chain", ":", "{", "value", ":", "false", ",", "utility", ":", "false", "}", "}", ";", "// check geth status", "for", "(", "var", "chainName", "in", "st...
Check status of all services @return {promise<result>}
[ "Check", "status", "of", "all", "services" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/utils/platform_status.js#L29-L46
33,080
OpenSTFoundation/openst-platform
services/utils/platform_status.js
function (chain) { const web3Provider = web3ProviderFactory.getProvider(chain, web3ProviderFactory.typeWS) , retryAttempts = 100 , timerInterval = 5000 , chainTimer = {timer: undefined, blockNumber: 0, retryCounter: 0} ; if (!web3Provider) { // this is a error scenario. let errObj = responseHelper.error({ internal_error_identifier: 's_u_ps_1', api_error_identifier: 'invalid_chain', error_config: basicHelper.fetchErrorConfig() }); return Promise.reject(errObj); } return new Promise(function (onResolve, onReject) { chainTimer['timer'] = setInterval(function () { if (chainTimer['retryCounter'] <= retryAttempts) { web3Provider.eth.getBlockNumber(function (err, blocknumber) { if (err) { logger.error("Geth Checker - " + chain + " fetch block number failed.", err); chainTimer['retryCounter']++; } else { if (chainTimer['blockNumber'] != 0 && chainTimer['blockNumber'] != blocknumber) { clearInterval(chainTimer['timer']); onResolve(responseHelper.successWithData({})); } chainTimer['blockNumber'] = blocknumber; } }); } else { logger.error("Geth Checker - " + chain + " chain has no new blocks."); let errObj = responseHelper.error({ internal_error_identifier: 's_u_ps_2_' + chain, api_error_identifier: 'no_new_blocks', error_config: basicHelper.fetchErrorConfig() }); onReject(errObj); } chainTimer['retryCounter']++; }, timerInterval); }); }
javascript
function (chain) { const web3Provider = web3ProviderFactory.getProvider(chain, web3ProviderFactory.typeWS) , retryAttempts = 100 , timerInterval = 5000 , chainTimer = {timer: undefined, blockNumber: 0, retryCounter: 0} ; if (!web3Provider) { // this is a error scenario. let errObj = responseHelper.error({ internal_error_identifier: 's_u_ps_1', api_error_identifier: 'invalid_chain', error_config: basicHelper.fetchErrorConfig() }); return Promise.reject(errObj); } return new Promise(function (onResolve, onReject) { chainTimer['timer'] = setInterval(function () { if (chainTimer['retryCounter'] <= retryAttempts) { web3Provider.eth.getBlockNumber(function (err, blocknumber) { if (err) { logger.error("Geth Checker - " + chain + " fetch block number failed.", err); chainTimer['retryCounter']++; } else { if (chainTimer['blockNumber'] != 0 && chainTimer['blockNumber'] != blocknumber) { clearInterval(chainTimer['timer']); onResolve(responseHelper.successWithData({})); } chainTimer['blockNumber'] = blocknumber; } }); } else { logger.error("Geth Checker - " + chain + " chain has no new blocks."); let errObj = responseHelper.error({ internal_error_identifier: 's_u_ps_2_' + chain, api_error_identifier: 'no_new_blocks', error_config: basicHelper.fetchErrorConfig() }); onReject(errObj); } chainTimer['retryCounter']++; }, timerInterval); }); }
[ "function", "(", "chain", ")", "{", "const", "web3Provider", "=", "web3ProviderFactory", ".", "getProvider", "(", "chain", ",", "web3ProviderFactory", ".", "typeWS", ")", ",", "retryAttempts", "=", "100", ",", "timerInterval", "=", "5000", ",", "chainTimer", "...
Check geth status @param {string} chain - chain name @return {promise<result>} @private @ignore
[ "Check", "geth", "status" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/utils/platform_status.js#L57-L102
33,081
OpenSTFoundation/openst-platform
tools/setup/file_manager.js
function() { const oThis = this; // Remove old setup folder logger.info("* Deleting old openST setup folder"); oThis.rm(''); // Create new setup folder logger.info("* Creating new openST setup folder"); oThis.mkdir(''); // Create logs setup folder logger.info("* Creating openST setup logs folder"); oThis.mkdir(setupHelper.logsFolder()); // Create intercom data files in logs folder logger.info("* Creating openST intercom data files"); const intercomProcessIdentifiers = setupHelper.intercomProcessIdentifiers(); for (var i=0; i < intercomProcessIdentifiers.length; i++) { oThis.touch('logs/' + intercomProcessIdentifiers[i] + '.data', "{\\\"lastProcessedBlock\\\":0,\\\"lastProcessedTransactionIndex\\\":0}"); } // Create bin setup folder logger.info("* Creating openST setup bin folder"); oThis.mkdir(setupHelper.binFolder()); // Create empty ENV file logger.info("* Create empty ENV file"); oThis.touch(setupConfig.env_vars_file, '#!/bin/sh'); }
javascript
function() { const oThis = this; // Remove old setup folder logger.info("* Deleting old openST setup folder"); oThis.rm(''); // Create new setup folder logger.info("* Creating new openST setup folder"); oThis.mkdir(''); // Create logs setup folder logger.info("* Creating openST setup logs folder"); oThis.mkdir(setupHelper.logsFolder()); // Create intercom data files in logs folder logger.info("* Creating openST intercom data files"); const intercomProcessIdentifiers = setupHelper.intercomProcessIdentifiers(); for (var i=0; i < intercomProcessIdentifiers.length; i++) { oThis.touch('logs/' + intercomProcessIdentifiers[i] + '.data', "{\\\"lastProcessedBlock\\\":0,\\\"lastProcessedTransactionIndex\\\":0}"); } // Create bin setup folder logger.info("* Creating openST setup bin folder"); oThis.mkdir(setupHelper.binFolder()); // Create empty ENV file logger.info("* Create empty ENV file"); oThis.touch(setupConfig.env_vars_file, '#!/bin/sh'); }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ";", "// Remove old setup folder", "logger", ".", "info", "(", "\"* Deleting old openST setup folder\"", ")", ";", "oThis", ".", "rm", "(", "''", ")", ";", "// Create new setup folder", "logger", ".", "in...
Do the old setup clean up
[ "Do", "the", "old", "setup", "clean", "up" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/file_manager.js#L28-L57
33,082
OpenSTFoundation/openst-platform
tools/setup/file_manager.js
function(relativePath, fileContent) { const file = setupHelper.setupFolderAbsolutePath() + '/' + relativePath; fileContent = fileContent || ''; return setupHelper.handleShellResponse(shell.exec('echo "' + fileContent + '" > ' + file)); }
javascript
function(relativePath, fileContent) { const file = setupHelper.setupFolderAbsolutePath() + '/' + relativePath; fileContent = fileContent || ''; return setupHelper.handleShellResponse(shell.exec('echo "' + fileContent + '" > ' + file)); }
[ "function", "(", "relativePath", ",", "fileContent", ")", "{", "const", "file", "=", "setupHelper", ".", "setupFolderAbsolutePath", "(", ")", "+", "'/'", "+", "relativePath", ";", "fileContent", "=", "fileContent", "||", "''", ";", "return", "setupHelper", "."...
Create file inside openST setup environment @param {string} relativePath - relative file path @param {string} fileContent - optional file content
[ "Create", "file", "inside", "openST", "setup", "environment" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/file_manager.js#L85-L89
33,083
OpenSTFoundation/openst-platform
tools/setup/file_manager.js
function(relativePath, line) { const file = setupHelper.setupFolderAbsolutePath() + '/' + relativePath; return setupHelper.handleShellResponse(shell.exec('echo "' + line + '" >> ' + file)); }
javascript
function(relativePath, line) { const file = setupHelper.setupFolderAbsolutePath() + '/' + relativePath; return setupHelper.handleShellResponse(shell.exec('echo "' + line + '" >> ' + file)); }
[ "function", "(", "relativePath", ",", "line", ")", "{", "const", "file", "=", "setupHelper", ".", "setupFolderAbsolutePath", "(", ")", "+", "'/'", "+", "relativePath", ";", "return", "setupHelper", ".", "handleShellResponse", "(", "shell", ".", "exec", "(", ...
Append line at the end of the file @param {string} relativePath - relative file path @param {string} line - line to be appended to file
[ "Append", "line", "at", "the", "end", "of", "the", "file" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/file_manager.js#L97-L100
33,084
OpenSTFoundation/openst-platform
tools/setup/file_manager.js
function(fromFolder, toFolder, fileName) { const src = setupHelper.setupFolderAbsolutePath() + '/' + fromFolder + '/' + fileName , dest = setupHelper.setupFolderAbsolutePath() + '/' + toFolder + '/'; return setupHelper.handleShellResponse(shell.exec('cp -r ' + src + ' ' + dest)); }
javascript
function(fromFolder, toFolder, fileName) { const src = setupHelper.setupFolderAbsolutePath() + '/' + fromFolder + '/' + fileName , dest = setupHelper.setupFolderAbsolutePath() + '/' + toFolder + '/'; return setupHelper.handleShellResponse(shell.exec('cp -r ' + src + ' ' + dest)); }
[ "function", "(", "fromFolder", ",", "toFolder", ",", "fileName", ")", "{", "const", "src", "=", "setupHelper", ".", "setupFolderAbsolutePath", "(", ")", "+", "'/'", "+", "fromFolder", "+", "'/'", "+", "fileName", ",", "dest", "=", "setupHelper", ".", "setu...
Copy file from one folder to another inside openST setup environment @param {string} fromFolder - relative from folder @param {string} toFolder - relative to folder @param {string} fileName - file name
[ "Copy", "file", "from", "one", "folder", "to", "another", "inside", "openST", "setup", "environment" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/file_manager.js#L109-L113
33,085
OpenSTFoundation/openst-platform
services/transaction/transfer/simple_token.js
function (params) { const oThis = this ; params = params || {}; oThis.senderAddress = params.sender_address; oThis.senderPassphrase = params.sender_passphrase; oThis.senderName = params.sender_name; oThis.recipientAddress = params.recipient_address; oThis.recipientName = params.recipient_name; oThis.amountInWei = params.amount_in_wei; oThis.tag = (params.options || {}).tag; oThis.returnType = (params.options || {}).returnType || 'txHash'; }
javascript
function (params) { const oThis = this ; params = params || {}; oThis.senderAddress = params.sender_address; oThis.senderPassphrase = params.sender_passphrase; oThis.senderName = params.sender_name; oThis.recipientAddress = params.recipient_address; oThis.recipientName = params.recipient_name; oThis.amountInWei = params.amount_in_wei; oThis.tag = (params.options || {}).tag; oThis.returnType = (params.options || {}).returnType || 'txHash'; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "oThis", ".", "senderAddress", "=", "params", ".", "sender_address", ";", "oThis", ".", "senderPassphrase", "=", "params", ".", "sender...
Transfer Simple Token Service @param {object} params - @param {string} params.sender_address - Sender address @param {string} params.sender_passphrase - Sender passphrase @param {string} [params.sender_name] - Sender name where only platform has address and passphrase @param {string} params.recipient_address - Recipient address @param {string} [params.recipient_name] - Recipient name name where only platform has address and passphrase @param {number} params.amount_in_wei - Amount (in wei) to transfer @param {object} params.options - @param {string} params.options.tag - extra param which gets logged for transaction as transaction type @param {boolean} [params.options.returnType] - Desired return type. possible values: uuid, txHash, txReceipt. Default: txHash @constructor
[ "Transfer", "Simple", "Token", "Service" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/transaction/transfer/simple_token.js#L32-L47
33,086
OpenSTFoundation/openst-platform
services/balance/branded_token.js
function (params) { const oThis = this; params = params || {}; oThis.erc20Address = params.erc20_address; oThis.address = params.address; }
javascript
function (params) { const oThis = this; params = params || {}; oThis.erc20Address = params.erc20_address; oThis.address = params.address; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "oThis", ".", "erc20Address", "=", "params", ".", "erc20_address", ";", "oThis", ".", "address", "=", "params", ".", "address", ";", ...
Branded Token balance @param {object} params - @param {string} params.erc20_address - Branded token EIP20 address @param {string} params.address - Account address @constructor
[ "Branded", "Token", "balance" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/balance/branded_token.js#L24-L30
33,087
OpenSTFoundation/openst-platform
tools/setup/branded_token/mint.js
function (params) { const oThis = this ; oThis.brandedTokenUuid = params.uuid; oThis.amountToStakeInWeis = params.amount_to_stake_in_weis; oThis.reserveAddr = params.reserve_address; oThis.reservePassphrase = params.reserve_passphrase; oThis.erc20Address = params.erc20_address; }
javascript
function (params) { const oThis = this ; oThis.brandedTokenUuid = params.uuid; oThis.amountToStakeInWeis = params.amount_to_stake_in_weis; oThis.reserveAddr = params.reserve_address; oThis.reservePassphrase = params.reserve_passphrase; oThis.erc20Address = params.erc20_address; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "oThis", ".", "brandedTokenUuid", "=", "params", ".", "uuid", ";", "oThis", ".", "amountToStakeInWeis", "=", "params", ".", "amount_to_stake_in_weis", ";", "oThis", ".", "reserveAddr", ...
Constructor for Mint Branded Token @constructor
[ "Constructor", "for", "Mint", "Branded", "Token" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/branded_token/mint.js#L37-L46
33,088
OpenSTFoundation/openst-platform
tools/setup/branded_token/mint.js
function() { const oThis = this ; return new Promise(async function(onResolve, onReject) { // NOTE: NOT Relying on CACHE - this is because for in process memory, this goes into infinite loop const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token') , brandedToken = new BrandedTokenKlass({ERC20: oThis.erc20Address}); const beforeBalanceResponse = await brandedToken._callMethod('balanceOf', [oThis.reserveAddr]); const beforeBalance = new BigNumber(beforeBalanceResponse.data.balanceOf); logger.info('Balance of Reserve for Branded Token before mint:', beforeBalance.toString(10)); const getBalance = async function(){ const afterBalanceResponse = await brandedToken._callMethod('balanceOf', [oThis.reserveAddr]) , afterBalance = afterBalanceResponse.data.balanceOf; if(afterBalanceResponse.isSuccess() && (new BigNumber(afterBalance)).greaterThan(beforeBalance)){ logger.info('Balance of Reserve for Branded Token after mint:', afterBalance.toString(10)); return onResolve(); } else { setTimeout(getBalance, 5000); } }; getBalance(); }); }
javascript
function() { const oThis = this ; return new Promise(async function(onResolve, onReject) { // NOTE: NOT Relying on CACHE - this is because for in process memory, this goes into infinite loop const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token') , brandedToken = new BrandedTokenKlass({ERC20: oThis.erc20Address}); const beforeBalanceResponse = await brandedToken._callMethod('balanceOf', [oThis.reserveAddr]); const beforeBalance = new BigNumber(beforeBalanceResponse.data.balanceOf); logger.info('Balance of Reserve for Branded Token before mint:', beforeBalance.toString(10)); const getBalance = async function(){ const afterBalanceResponse = await brandedToken._callMethod('balanceOf', [oThis.reserveAddr]) , afterBalance = afterBalanceResponse.data.balanceOf; if(afterBalanceResponse.isSuccess() && (new BigNumber(afterBalance)).greaterThan(beforeBalance)){ logger.info('Balance of Reserve for Branded Token after mint:', afterBalance.toString(10)); return onResolve(); } else { setTimeout(getBalance, 5000); } }; getBalance(); }); }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ";", "return", "new", "Promise", "(", "async", "function", "(", "onResolve", ",", "onReject", ")", "{", "// NOTE: NOT Relying on CACHE - this is because for in process memory, this goes into infinite loop", "const"...
Wait for Branded Token mint @return {promise} @private
[ "Wait", "for", "Branded", "Token", "mint" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/branded_token/mint.js#L136-L166
33,089
OpenSTFoundation/openst-platform
tools/setup/branded_token/mint.js
function() { const oThis = this , web3UcProvider = web3ProviderFactory.getProvider('utility', 'ws') ; return new Promise(async function(onResolve, onReject) { const beforeBalance = new BigNumber(await web3UcProvider.eth.getBalance(oThis.reserveAddr)); logger.info('Balance of Reserve for Simple Token Prime before mint:', beforeBalance.toString(10)); const getBalance = async function(){ const afterBalance = new BigNumber(await web3UcProvider.eth.getBalance(oThis.reserveAddr)); if((new BigNumber(afterBalance)).greaterThan(beforeBalance)){ logger.info('Balance of Reserve for Simple Token Prime after mint:', afterBalance.toString(10)); return onResolve(); } else { setTimeout(getBalance, 5000); } }; getBalance(); }); }
javascript
function() { const oThis = this , web3UcProvider = web3ProviderFactory.getProvider('utility', 'ws') ; return new Promise(async function(onResolve, onReject) { const beforeBalance = new BigNumber(await web3UcProvider.eth.getBalance(oThis.reserveAddr)); logger.info('Balance of Reserve for Simple Token Prime before mint:', beforeBalance.toString(10)); const getBalance = async function(){ const afterBalance = new BigNumber(await web3UcProvider.eth.getBalance(oThis.reserveAddr)); if((new BigNumber(afterBalance)).greaterThan(beforeBalance)){ logger.info('Balance of Reserve for Simple Token Prime after mint:', afterBalance.toString(10)); return onResolve(); } else { setTimeout(getBalance, 5000); } }; getBalance(); }); }
[ "function", "(", ")", "{", "const", "oThis", "=", "this", ",", "web3UcProvider", "=", "web3ProviderFactory", ".", "getProvider", "(", "'utility'", ",", "'ws'", ")", ";", "return", "new", "Promise", "(", "async", "function", "(", "onResolve", ",", "onReject",...
Wait for Simple Token Prime mint @return {promise} @private
[ "Wait", "for", "Simple", "Token", "Prime", "mint" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/branded_token/mint.js#L174-L199
33,090
nikospara/require-lazy
src/build-scripts/map-path-inverse.js
addPath
function addPath(path, name) { // This will add a path -> name mapping, so that paths may be later // resolved to module names, as well as a filesystem full path to // module mapping, in case the `paths` value contains relative paths // (e.g. `../`, see issue #2). var fullPath = (pathModule.normalize(pathModule.join(baseFullUrl,path)) + ".js").replace(/\\/g,"/"); inversePaths[path] = name; inversePaths[fullPath] = name; }
javascript
function addPath(path, name) { // This will add a path -> name mapping, so that paths may be later // resolved to module names, as well as a filesystem full path to // module mapping, in case the `paths` value contains relative paths // (e.g. `../`, see issue #2). var fullPath = (pathModule.normalize(pathModule.join(baseFullUrl,path)) + ".js").replace(/\\/g,"/"); inversePaths[path] = name; inversePaths[fullPath] = name; }
[ "function", "addPath", "(", "path", ",", "name", ")", "{", "// This will add a path -> name mapping, so that paths may be later", "// resolved to module names, as well as a filesystem full path to", "// module mapping, in case the `paths` value contains relative paths", "// (e.g. `../`, see is...
Add the module to the inverse path mappings.
[ "Add", "the", "module", "to", "the", "inverse", "path", "mappings", "." ]
ef067ebe460bb81dd856e784aaf141d73a17dda5
https://github.com/nikospara/require-lazy/blob/ef067ebe460bb81dd856e784aaf141d73a17dda5/src/build-scripts/map-path-inverse.js#L41-L49
33,091
OpenSTFoundation/openst-platform
services/stake_and_mint/start_stake.js
function (params) { const oThis = this ; params = params || {}; oThis.beneficiary = params.beneficiary; oThis.toStakeAmount = params.to_stake_amount; oThis.uuid = params.uuid; }
javascript
function (params) { const oThis = this ; params = params || {}; oThis.beneficiary = params.beneficiary; oThis.toStakeAmount = params.to_stake_amount; oThis.uuid = params.uuid; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "oThis", ".", "beneficiary", "=", "params", ".", "beneficiary", ";", "oThis", ".", "toStakeAmount", "=", "params", ".", "to_stake_amoun...
Start Stake Service constructor @param {object} params - @param {string} params.beneficiary - Staked amount beneficiary address @param {number} params.to_stake_amount - Amount (in wei) to stake @param {string} params.uuid - Branded Token UUID @constructor
[ "Start", "Stake", "Service", "constructor" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/stake_and_mint/start_stake.js#L31-L39
33,092
OpenSTFoundation/openst-platform
services/stake_and_mint/get_approval_status.js
function (params) { const oThis = this ; params = params || {}; oThis.transactionHash = params.transaction_hash; oThis.chain = 'value'; }
javascript
function (params) { const oThis = this ; params = params || {}; oThis.transactionHash = params.transaction_hash; oThis.chain = 'value'; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "oThis", ".", "transactionHash", "=", "params", ".", "transaction_hash", ";", "oThis", ".", "chain", "=", "'value'", ";", "}" ]
Get approval status @param {object} params - @param {string} params.transaction_hash - Transaction hash for lookup @constructor
[ "Get", "approval", "status" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/stake_and_mint/get_approval_status.js#L23-L30
33,093
OpenSTFoundation/openst-platform
tools/setup/performer.js
function (deployPath) { const envFilePath = setupHelper.setupFolderAbsolutePath() + '/' + setupConfig.env_vars_file , clearCacheOfExpr = /(openst-platform\/config\/)|(openst-platform\/lib\/)|(openst-platform\/services\/)/; return new Promise(function (onResolve, onReject) { // source env shellSource(envFilePath, async function (err) { if (err) { throw err; } Object.keys(require.cache).forEach(function (key) { if (key.search(clearCacheOfExpr) !== -1) { delete require.cache[key]; } }); const setupHelper = require(deployPath); return onResolve(await setupHelper.perform()); }); }); }
javascript
function (deployPath) { const envFilePath = setupHelper.setupFolderAbsolutePath() + '/' + setupConfig.env_vars_file , clearCacheOfExpr = /(openst-platform\/config\/)|(openst-platform\/lib\/)|(openst-platform\/services\/)/; return new Promise(function (onResolve, onReject) { // source env shellSource(envFilePath, async function (err) { if (err) { throw err; } Object.keys(require.cache).forEach(function (key) { if (key.search(clearCacheOfExpr) !== -1) { delete require.cache[key]; } }); const setupHelper = require(deployPath); return onResolve(await setupHelper.perform()); }); }); }
[ "function", "(", "deployPath", ")", "{", "const", "envFilePath", "=", "setupHelper", ".", "setupFolderAbsolutePath", "(", ")", "+", "'/'", "+", "setupConfig", ".", "env_vars_file", ",", "clearCacheOfExpr", "=", "/", "(openst-platform\\/config\\/)|(openst-platform\\/lib\...
Run the deployer helper service @param {string} deployPath - contract deployment script path @return {promise}
[ "Run", "the", "deployer", "helper", "service" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/performer.js#L210-L231
33,094
OpenSTFoundation/openst-platform
services/on_boarding/propose_branded_token.js
function (params) { const oThis = this ; params = params || {}; oThis.name = params.name; oThis.symbol = params.symbol; oThis.conversionFactor = params.conversion_factor; oThis.conversionRate = null; oThis.conversionRateDecimals = null; }
javascript
function (params) { const oThis = this ; params = params || {}; oThis.name = params.name; oThis.symbol = params.symbol; oThis.conversionFactor = params.conversion_factor; oThis.conversionRate = null; oThis.conversionRateDecimals = null; }
[ "function", "(", "params", ")", "{", "const", "oThis", "=", "this", ";", "params", "=", "params", "||", "{", "}", ";", "oThis", ".", "name", "=", "params", ".", "name", ";", "oThis", ".", "symbol", "=", "params", ".", "symbol", ";", "oThis", ".", ...
Propose Branded Token Service @param {object} params - @param {string} params.name - Branded token name @param {string} params.symbol - Branded token symbol @param {string} params.conversion_factor - Conversion factor (1 OST = ? Branded token) @constructor
[ "Propose", "Branded", "Token", "Service" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/services/on_boarding/propose_branded_token.js#L35-L45
33,095
OpenSTFoundation/openst-platform
tools/setup/fund_manager.js
async function(senderAddr, senderPassphrase, recipient, amountInWei) { // TODO: should we have isAsync with UUID (unlock account will take time) and also tag, publish events? const oThis = this , web3Provider = web3ProviderFactory.getProvider('value', 'ws') , gasPrice = coreConstants.OST_VALUE_GAS_PRICE , gas = coreConstants.OST_VALUE_GAS_LIMIT ; // Validations if (!basicHelper.isAddressValid(senderAddr)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_1', api_error_identifier: 'invalid_address', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } if (!basicHelper.isAddressValid(recipient)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_2', api_error_identifier: 'invalid_address', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } if (senderAddr.equalsIgnoreCase(recipient)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_3', api_error_identifier: 'sender_and_recipient_same', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } if (!basicHelper.isNonZeroWeiValid(amountInWei)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_4', api_error_identifier: 'invalid_amount', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } // Convert amount in BigNumber var bigNumAmount = basicHelper.convertToBigNumber(amountInWei); // Validate sender balance const senderBalanceValidationResponse = await oThis.validateEthBalance(senderAddr, bigNumAmount); if (senderBalanceValidationResponse.isFailure()) { return Promise.resolve(senderBalanceValidationResponse); } // Perform transfer async const asyncTransfer = async function() { return web3Provider.eth.personal.unlockAccount(senderAddr, senderPassphrase) .then(function() { return web3Provider.eth.sendTransaction( {from: senderAddr, to: recipient, value: bigNumAmount.toString(10), gasPrice: gasPrice, gas: gas}); }) .then(function(transactionHash) { return responseHelper.successWithData({transactionHash: transactionHash}); }) .catch(function(reason) { logger.error('reason', reason); return responseHelper.error({ internal_error_identifier: 't_s_fm_5', api_error_identifier: 'something_went_wrong', error_config: basicHelper.fetchErrorConfig() }); }); }; return asyncTransfer(); }
javascript
async function(senderAddr, senderPassphrase, recipient, amountInWei) { // TODO: should we have isAsync with UUID (unlock account will take time) and also tag, publish events? const oThis = this , web3Provider = web3ProviderFactory.getProvider('value', 'ws') , gasPrice = coreConstants.OST_VALUE_GAS_PRICE , gas = coreConstants.OST_VALUE_GAS_LIMIT ; // Validations if (!basicHelper.isAddressValid(senderAddr)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_1', api_error_identifier: 'invalid_address', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } if (!basicHelper.isAddressValid(recipient)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_2', api_error_identifier: 'invalid_address', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } if (senderAddr.equalsIgnoreCase(recipient)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_3', api_error_identifier: 'sender_and_recipient_same', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } if (!basicHelper.isNonZeroWeiValid(amountInWei)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_4', api_error_identifier: 'invalid_amount', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } // Convert amount in BigNumber var bigNumAmount = basicHelper.convertToBigNumber(amountInWei); // Validate sender balance const senderBalanceValidationResponse = await oThis.validateEthBalance(senderAddr, bigNumAmount); if (senderBalanceValidationResponse.isFailure()) { return Promise.resolve(senderBalanceValidationResponse); } // Perform transfer async const asyncTransfer = async function() { return web3Provider.eth.personal.unlockAccount(senderAddr, senderPassphrase) .then(function() { return web3Provider.eth.sendTransaction( {from: senderAddr, to: recipient, value: bigNumAmount.toString(10), gasPrice: gasPrice, gas: gas}); }) .then(function(transactionHash) { return responseHelper.successWithData({transactionHash: transactionHash}); }) .catch(function(reason) { logger.error('reason', reason); return responseHelper.error({ internal_error_identifier: 't_s_fm_5', api_error_identifier: 'something_went_wrong', error_config: basicHelper.fetchErrorConfig() }); }); }; return asyncTransfer(); }
[ "async", "function", "(", "senderAddr", ",", "senderPassphrase", ",", "recipient", ",", "amountInWei", ")", "{", "// TODO: should we have isAsync with UUID (unlock account will take time) and also tag, publish events?", "const", "oThis", "=", "this", ",", "web3Provider", "=", ...
Transfer ETH on a particular chain from sender to receiver @param {string} senderAddr - address of user who is sending amount @param {string} senderPassphrase - sender address passphrase @param {string} recipient - address of user who is receiving amount @param {BigNumber} amountInWei - amount which is being transferred @return {promise<result>}
[ "Transfer", "ETH", "on", "a", "particular", "chain", "from", "sender", "to", "receiver" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/fund_manager.js#L54-L134
33,096
OpenSTFoundation/openst-platform
tools/setup/fund_manager.js
function(erc20Address, senderAddr, senderPassphrase, recipient, amountInWei) { const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token') , brandedToken = new BrandedTokenKlass({ERC20: erc20Address}) ; return brandedToken.transfer(senderAddr, senderPassphrase, recipient, amountInWei) }
javascript
function(erc20Address, senderAddr, senderPassphrase, recipient, amountInWei) { const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token') , brandedToken = new BrandedTokenKlass({ERC20: erc20Address}) ; return brandedToken.transfer(senderAddr, senderPassphrase, recipient, amountInWei) }
[ "function", "(", "erc20Address", ",", "senderAddr", ",", "senderPassphrase", ",", "recipient", ",", "amountInWei", ")", "{", "const", "BrandedTokenKlass", "=", "require", "(", "rootPrefix", "+", "'/lib/contract_interact/branded_token'", ")", ",", "brandedToken", "=", ...
Transfer Branded Token @param {string} erc20Address - address of erc20 contract address @param {string} senderAddr - address of user who is sending amount @param {string} senderPassphrase - sender address passphrase @param {string} recipient - address of user who is receiving amount @param {BigNumber} amountInWei - amount which is being transferred in Weis @return {promise<result>}
[ "Transfer", "Branded", "Token" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/fund_manager.js#L147-L154
33,097
OpenSTFoundation/openst-platform
tools/setup/fund_manager.js
function (owner) { const web3Provider = web3ProviderFactory.getProvider('value', 'ws') ; // Validate addresses if (!basicHelper.isAddressValid(owner)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_8', api_error_identifier: 'invalid_address', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } return web3Provider.eth.getBalance(owner) .then(function(balance) { return responseHelper.successWithData({balance: balance}); }) .catch(function (err) { //Format the error logger.error(err); return responseHelper.error({ internal_error_identifier: 't_s_fm_9', api_error_identifier: 'something_went_wrong', error_config: basicHelper.fetchErrorConfig() }); }); }
javascript
function (owner) { const web3Provider = web3ProviderFactory.getProvider('value', 'ws') ; // Validate addresses if (!basicHelper.isAddressValid(owner)) { let errObj = responseHelper.error({ internal_error_identifier: 't_s_fm_8', api_error_identifier: 'invalid_address', error_config: basicHelper.fetchErrorConfig() }); return Promise.resolve(errObj); } return web3Provider.eth.getBalance(owner) .then(function(balance) { return responseHelper.successWithData({balance: balance}); }) .catch(function (err) { //Format the error logger.error(err); return responseHelper.error({ internal_error_identifier: 't_s_fm_9', api_error_identifier: 'something_went_wrong', error_config: basicHelper.fetchErrorConfig() }); }); }
[ "function", "(", "owner", ")", "{", "const", "web3Provider", "=", "web3ProviderFactory", ".", "getProvider", "(", "'value'", ",", "'ws'", ")", ";", "// Validate addresses", "if", "(", "!", "basicHelper", ".", "isAddressValid", "(", "owner", ")", ")", "{", "l...
Get ETH Balance of an address @param {string} owner - address @return {promise<result>}
[ "Get", "ETH", "Balance", "of", "an", "address" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/fund_manager.js#L207-L234
33,098
OpenSTFoundation/openst-platform
tools/setup/fund_manager.js
function (erc20Address, owner) { const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token') , brandedToken = new BrandedTokenKlass({ERC20: erc20Address}) ; return brandedToken.getBalanceOf(owner); }
javascript
function (erc20Address, owner) { const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token') , brandedToken = new BrandedTokenKlass({ERC20: erc20Address}) ; return brandedToken.getBalanceOf(owner); }
[ "function", "(", "erc20Address", ",", "owner", ")", "{", "const", "BrandedTokenKlass", "=", "require", "(", "rootPrefix", "+", "'/lib/contract_interact/branded_token'", ")", ",", "brandedToken", "=", "new", "BrandedTokenKlass", "(", "{", "ERC20", ":", "erc20Address"...
Get Branded Token Balance of an address @param {string} erc20Address - address of erc20 contract address @param {string} owner - address @return {promise<result>}
[ "Get", "Branded", "Token", "Balance", "of", "an", "address" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/tools/setup/fund_manager.js#L298-L304
33,099
OpenSTFoundation/openst-platform
lib/contract_interact/value_registrar.js
function (contractAddress) { this.contractAddress = contractAddress; valueRegistrarContractObj.options.address = this.contractAddress; //valueRegistrarContractObj.setProvider(web3Provider.currentProvider); OpsManagedKlass.call(this, this.contractAddress, web3Provider, valueRegistrarContractObj, VC_GAS_PRICE); }
javascript
function (contractAddress) { this.contractAddress = contractAddress; valueRegistrarContractObj.options.address = this.contractAddress; //valueRegistrarContractObj.setProvider(web3Provider.currentProvider); OpsManagedKlass.call(this, this.contractAddress, web3Provider, valueRegistrarContractObj, VC_GAS_PRICE); }
[ "function", "(", "contractAddress", ")", "{", "this", ".", "contractAddress", "=", "contractAddress", ";", "valueRegistrarContractObj", ".", "options", ".", "address", "=", "this", ".", "contractAddress", ";", "//valueRegistrarContractObj.setProvider(web3Provider.currentPro...
Constructor for Value Registrar Contract Interact @constructor @augments OpsManagedKlass @param {String} contractAddress - address where Contract has been deployed
[ "Constructor", "for", "Value", "Registrar", "Contract", "Interact" ]
2bcc62c7c7740b5f424fd9b467197aa14a94bb32
https://github.com/OpenSTFoundation/openst-platform/blob/2bcc62c7c7740b5f424fd9b467197aa14a94bb32/lib/contract_interact/value_registrar.js#L37-L45