_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q4500
getSnippetsCompletions
train
function getSnippetsCompletions(editor, prefix) { const syntax = detectSyntax(editor); if (isStylesheet(syntax)) { return getStylesheetSnippetsCompletions(editor, prefix); } else if (syntax) { return getMarkupSnippetsCompletions(editor, prefix); } return []; }
javascript
{ "resource": "" }
q4501
train
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
{ "resource": "" }
q4502
train
function(items) { var hasRelativePositioning = hasNumberProperty(items, 'relativePosition'); if(hasRelativePositioning) { items.sort(function(a, b) { return a.relativePosition - b.relativePosition; }); } }
javascript
{ "resource": "" }
q4503
train
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
{ "resource": "" }
q4504
train
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
{ "resource": "" }
q4505
train
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
{ "resource": "" }
q4506
train
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
{ "resource": "" }
q4507
train
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
{ "resource": "" }
q4508
train
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
{ "resource": "" }
q4509
train
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
{ "resource": "" }
q4510
train
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
{ "resource": "" }
q4511
train
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
{ "resource": "" }
q4512
train
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
{ "resource": "" }
q4513
train
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
{ "resource": "" }
q4514
train
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
{ "resource": "" }
q4515
train
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
{ "resource": "" }
q4516
runBeforeHooks
train
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
{ "resource": "" }
q4517
runAfterHooks
train
function runAfterHooks(connection, err, res, cb){ async.eachSeries(connection.hooks.after, function (hook, nextHook) { hook(err, res, nextHook); }, cb); }
javascript
{ "resource": "" }
q4518
setRequestHeaders
train
function setRequestHeaders(connection, req) { if(_.isObject(connection.headers)){ req.set(connection.headers); } }
javascript
{ "resource": "" }
q4519
handleResponse
train
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
{ "resource": "" }
q4520
getResponseHandler
train
function getResponseHandler(connection, cb) { return function (err, res) { if (res && !err) { err = null; } handleResponse(connection, err, res, cb); } }
javascript
{ "resource": "" }
q4521
castRecordDateFields
train
function castRecordDateFields(record) { _.forEach(record, function (value, key) { if(_.isString(value) && iso.test(value)){ record[key] = new Date(value); } }); }
javascript
{ "resource": "" }
q4522
processResponse
train
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
{ "resource": "" }
q4523
train
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
{ "resource": "" }
q4524
train
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
{ "resource": "" }
q4525
Rejson
train
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
{ "resource": "" }
q4526
train
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
{ "resource": "" }
q4527
train
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
{ "resource": "" }
q4528
includes
train
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
{ "resource": "" }
q4529
getMyIPs
train
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
{ "resource": "" }
q4530
train
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
{ "resource": "" }
q4531
train
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
{ "resource": "" }
q4532
train
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
{ "resource": "" }
q4533
train
function (params) { const oThis = this ; params = params || {}; params.options = params.options || {}; if (params.options.returnType === 'txReceipt') { oThis.runInAsync = false; } else { oThis.runInAsync = true; } }
javascript
{ "resource": "" }
q4534
train
async function (toApproveAmount) { const oThis = this ; const approveRsp = await simpleToken.approve( stakerAddress, stakerPassphrase, openSTValueContractAddress, toApproveAmount, oThis.runInAsync ); return Promise.resolve(approveRsp); }
javascript
{ "resource": "" }
q4535
train
function () { return simpleToken.balanceOf(stakerAddress) .then(function (result) { const stBalance = result.data['balance']; return new BigNumber(stBalance); }) }
javascript
{ "resource": "" }
q4536
train
function (params) { this.contractAddress = params.contractAddress; this.currContract = new web3Provider.eth.Contract(simpleStakeContractAbi, this.contractAddress); //this.currContract.setProvider(web3Provider.currentProvider); }
javascript
{ "resource": "" }
q4537
train
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
{ "resource": "" }
q4538
train
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
{ "resource": "" }
q4539
train
function (contractAddress) { this.contractAddress = contractAddress; if (this.contractAddress) { stPrimeContractObj.options.address = this.contractAddress; } //stPrimeContractObj.setProvider(web3Provider.currentProvider); this.currContract = stPrimeContractObj; }
javascript
{ "resource": "" }
q4540
train
async function () { const oThis = this , callMethodResult = await oThis._callMethod('uuid') , response = callMethodResult.data.uuid; return response[0]; }
javascript
{ "resource": "" }
q4541
train
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
{ "resource": "" }
q4542
train
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
{ "resource": "" }
q4543
train
function (params) { const oThis = this ; params = params || {}; oThis.transactionHash = params.transaction_hash; oThis.chain = params.chain; oThis.addressToNameMap = params.address_to_name_map || {}; }
javascript
{ "resource": "" }
q4544
train
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
{ "resource": "" }
q4545
train
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
{ "resource": "" }
q4546
train
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
{ "resource": "" }
q4547
train
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
{ "resource": "" }
q4548
train
function (web3Provider, result) { return new Promise(function (onResolve, onReject) { onResolve(web3Provider.eth.abi.decodeParameter('address', result)); }); }
javascript
{ "resource": "" }
q4549
train
function (web3Provider, result) { return new Promise(function (onResolve, onReject) { onResolve(web3Provider.utils.hexToNumber(result)); }); }
javascript
{ "resource": "" }
q4550
train
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
{ "resource": "" }
q4551
train
function (params) { const oThis = this ; params = params || {}; oThis.passphrase = params.passphrase || ''; oThis.chain = params.chain; }
javascript
{ "resource": "" }
q4552
train
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
{ "resource": "" }
q4553
train
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
{ "resource": "" }
q4554
train
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
{ "resource": "" }
q4555
train
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
{ "resource": "" }
q4556
train
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
{ "resource": "" }
q4557
train
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
{ "resource": "" }
q4558
train
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
{ "resource": "" }
q4559
train
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
{ "resource": "" }
q4560
train
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
{ "resource": "" }
q4561
train
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
{ "resource": "" }
q4562
train
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
{ "resource": "" }
q4563
train
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
{ "resource": "" }
q4564
train
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
{ "resource": "" }
q4565
train
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
{ "resource": "" }
q4566
train
function(relativePath, fileContent) { const file = setupHelper.setupFolderAbsolutePath() + '/' + relativePath; fileContent = fileContent || ''; return setupHelper.handleShellResponse(shell.exec('echo "' + fileContent + '" > ' + file)); }
javascript
{ "resource": "" }
q4567
train
function(relativePath, line) { const file = setupHelper.setupFolderAbsolutePath() + '/' + relativePath; return setupHelper.handleShellResponse(shell.exec('echo "' + line + '" >> ' + file)); }
javascript
{ "resource": "" }
q4568
train
function(fromFolder, toFolder, fileName) { const src = setupHelper.setupFolderAbsolutePath() + '/' + fromFolder + '/' + fileName , dest = setupHelper.setupFolderAbsolutePath() + '/' + toFolder + '/'; return setupHelper.handleShellResponse(shell.exec('cp -r ' + src + ' ' + dest)); }
javascript
{ "resource": "" }
q4569
train
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
{ "resource": "" }
q4570
train
function (params) { const oThis = this; params = params || {}; oThis.erc20Address = params.erc20_address; oThis.address = params.address; }
javascript
{ "resource": "" }
q4571
train
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
{ "resource": "" }
q4572
train
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
{ "resource": "" }
q4573
train
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
{ "resource": "" }
q4574
addPath
train
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
{ "resource": "" }
q4575
train
function (params) { const oThis = this ; params = params || {}; oThis.beneficiary = params.beneficiary; oThis.toStakeAmount = params.to_stake_amount; oThis.uuid = params.uuid; }
javascript
{ "resource": "" }
q4576
train
function (params) { const oThis = this ; params = params || {}; oThis.transactionHash = params.transaction_hash; oThis.chain = 'value'; }
javascript
{ "resource": "" }
q4577
train
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
{ "resource": "" }
q4578
train
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
{ "resource": "" }
q4579
train
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
{ "resource": "" }
q4580
train
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
{ "resource": "" }
q4581
train
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
{ "resource": "" }
q4582
train
function (erc20Address, owner) { const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token') , brandedToken = new BrandedTokenKlass({ERC20: erc20Address}) ; return brandedToken.getBalanceOf(owner); }
javascript
{ "resource": "" }
q4583
train
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
{ "resource": "" }
q4584
train
function (contractAddress, web3Provider, currContract, defaultGasPrice) { this.contractAddress = contractAddress; this.web3Provider = web3Provider; this.currContract = currContract; this.defaultGasPrice = defaultGasPrice; this.currContract.options.address = contractAddress; //this.currContract.setProvider(web3Provider.currentProvider); OwnedKlass.call(this, contractAddress, web3Provider, currContract, defaultGasPrice); }
javascript
{ "resource": "" }
q4585
train
function () { const oThis = this ; oThis.contractAddress = simpleTokenContractAddr; simpleTokenContractObj.options.address = oThis.contractAddress; //simpleTokenContractObj.setProvider(web3Provider.currentProvider); OpsManagedKlass.call(oThis, oThis.contractAddress, web3Provider, simpleTokenContractObj, VC_GAS_PRICE); }
javascript
{ "resource": "" }
q4586
train
function () { const oThis = this ; return { uuid: oThis.uuid, erc20_address: oThis.erc20Address, is_proposal_done: oThis.isProposalDone, is_registered_on_uc: oThis.isRegisteredOnUc, is_registered_on_vc: oThis.isRegisteredOnVc } }
javascript
{ "resource": "" }
q4587
train
function (params) { const oThis = this; oThis.btName = params.bt_name; // branded token name oThis.btSymbol = params.bt_symbol; // branded token symbol oThis.btConversionFactor = params.bt_conversion_factor; // branded token to OST conversion factor, 1 OST = 10 ACME oThis.reserveAddress = ''; // Member company address (will be generated and populated) oThis.reservePassphrase = 'acmeOnopenST'; // Member company address passphrase oThis.uuid = ''; // Member company uuid (will be generated and populated) oThis.erc20 = ''; // Member company ERC20 contract address (will be generated and populated) }
javascript
{ "resource": "" }
q4588
train
async function () { const oThis = this; // Validate new branded token logger.step("** Validating branded token"); await oThis._validateBrandedTokenDetails(); // Generate reserve address logger.step("** Generating reserve address"); var addressRes = await oThis._generateAddress(); oThis.reserveAddress = addressRes.data.address; logger.info("* address:", oThis.reserveAddress); // Start the BT proposal var proposeRes = await oThis._propose(); // Monitor the BT proposal response var statusRes = await oThis._checkProposeStatus(proposeRes.data.transaction_hash); var registrationStatus = statusRes.data.registration_status; oThis.uuid = registrationStatus['uuid']; oThis.erc20 = registrationStatus['erc20_address']; // Add branded token to config file logger.step("** Updating branded token config file"); await oThis._updateBrandedTokenConfig(); // Allocating shard for storage of token balances logger.step("** Allocating shard for storage of token balances"); await oThis._allocateShard(); process.exit(0); }
javascript
{ "resource": "" }
q4589
train
async function() { const oThis = this ; const addressObj = new generateAddress({chain: 'utility', passphrase: oThis.reservePassphrase}) , addressResponse = await addressObj.perform(); if (addressResponse.isFailure()) { logger.error("* Reserve address generation failed with error:", addressResponse); process.exit(1); } return Promise.resolve(addressResponse); }
javascript
{ "resource": "" }
q4590
train
async function() { const oThis = this ; logger.step("** Starting BT proposal"); logger.info("* Name:", oThis.btName, "Symbol:", oThis.btSymbol, "Conversion Factor:", oThis.btConversionFactor); const proposeBTObj = new proposeBrandedToken( {name: oThis.btName, symbol: oThis.btSymbol, conversion_factor: oThis.btConversionFactor} ); const proposeBTResponse = await proposeBTObj.perform(); if (proposeBTResponse.isFailure()) { logger.error("* Proposal failed with error:", proposeBTResponse); process.exit(1); } return Promise.resolve(proposeBTResponse); }
javascript
{ "resource": "" }
q4591
train
function(transaction_hash) { const oThis = this , timeInterval = 5000 , proposeSteps = {is_proposal_done: 0, is_registered_on_uc: 0, is_registered_on_vc: 0} ; return new Promise(function(onResolve, onReject){ logger.step("** Monitoring BT proposal status"); const statusObj = new getRegistrationStatus({transaction_hash: transaction_hash}); var statusTimer = setInterval(async function () { var statusResponse = await statusObj.perform(); if (statusResponse.isFailure()) { logger.error(statusResponse); clearInterval(statusTimer); process.exit(1); } else { var registrationStatus = statusResponse.data.registration_status; if (proposeSteps['is_proposal_done'] != registrationStatus['is_proposal_done']) { logger.info('* BT proposal done on utility chain. Waiting for registration utility and value chain.'); proposeSteps['is_proposal_done'] = registrationStatus['is_proposal_done']; } if (proposeSteps['is_registered_on_uc'] != registrationStatus['is_registered_on_uc']) { logger.info('* BT registration done on utility chain. Waiting for registration on value chain.'); proposeSteps['is_registered_on_uc'] = registrationStatus['is_registered_on_uc']; } if (proposeSteps['is_registered_on_vc'] != registrationStatus['is_registered_on_vc']) { logger.info('* BT registration done on value chain.'); proposeSteps['is_registered_on_vc'] = registrationStatus['is_registered_on_vc']; clearInterval(statusTimer); return onResolve(statusResponse); } } }, timeInterval); }); }
javascript
{ "resource": "" }
q4592
train
async function() { const oThis = this , existingBrandedTokens = await oThis._loadBrandedTokenConfig() ; for (var uuid in existingBrandedTokens) { var brandedToken = existingBrandedTokens[uuid]; if (oThis.btName.equalsIgnoreCase(brandedToken.Name)) { logger.error("* Branded token name already registered and present in BT config file"); process.exit(1); } if (oThis.btSymbol.equalsIgnoreCase(brandedToken.Symbol)) { logger.error("* Branded token symbol already registered and present in BT config file"); process.exit(1); } } return true; }
javascript
{ "resource": "" }
q4593
train
async function() { const oThis = this , existingBrandedTokens = await oThis._loadBrandedTokenConfig() ; if (existingBrandedTokens[oThis.uuid]) { logger.error("* Branded token uuid already registered and present in BT config file"); process.exit(1); } existingBrandedTokens[oThis.uuid] = { Name: oThis.btName, Symbol: oThis.btSymbol, ConversionFactor: oThis.btConversionFactor, Reserve: oThis.reserveAddress, ReservePassphrase: oThis.reservePassphrase, UUID: oThis.uuid, ERC20: oThis.erc20 }; logger.info("* Branded token config:", existingBrandedTokens[oThis.uuid]); return tokenHelper.addBrandedToken(existingBrandedTokens); }
javascript
{ "resource": "" }
q4594
train
async function() { const oThis = this ; await new openSTStorage.TokenBalanceModel({ ddb_service: ddbServiceObj, auto_scaling: autoScalingServiceObj, erc20_contract_address: oThis.erc20 }).allocate(); }
javascript
{ "resource": "" }
q4595
train
function (address, addressToNameMap) { const lcAddress = String(address).toLowerCase(); if (!addressToNameMap || !( addressToNameMap[address] || addressToNameMap[lcAddress] )) { return coreAddresses.getContractNameFor(address); } return addressToNameMap[address] || addressToNameMap[lcAddress]; }
javascript
{ "resource": "" }
q4596
subscribe
train
function subscribe() { openSTNotification.subscribeEvent.rabbit( ['#'], {queue: 'openst_platform'}, function (msgContent) { logger.debug('[RECEIVED]', msgContent, '\n'); } ).catch(function (err) { logger.error(err); }); }
javascript
{ "resource": "" }
q4597
parse
train
function parse( lang, sample ) { // TODO: this should be refactored let ianaLang; const language = { desc: lang.trim(), tag: lang.trim(), src: lang }; const parts = lang.match( /^([^(]+)\((.*)\)\s*$/ ); if ( parts && parts.length > 2 ) { language.desc = parts[ 1 ].trim(); language.tag = parts[ 2 ].trim(); ianaLang = _getLangWithTag( language.tag ); } else { // First check whether lang is a known IANA subtag like 'en' or 'en-GB' ianaLang = _getLangWithTag( lang.split( '-' )[ 0 ] ); if ( ianaLang ) { language.desc = ianaLang.descriptions()[ 0 ]; } else { // Check whether IANA language can be found with description ianaLang = _getLangWithDesc( language.desc ); if ( ianaLang ) { language.tag = ianaLang.data.subtag; } } } language.dir = _getDirectionality( sample ); return language; }
javascript
{ "resource": "" }
q4598
_getLangWithDesc
train
function _getLangWithDesc( desc ) { const results = ( desc ) ? tags.search( desc ).filter( _languagesOnly ) : []; return results[ 0 ] || ''; }
javascript
{ "resource": "" }
q4599
transform
train
function transform( survey ) { let xformDoc; const xsltParams = survey.includeRelevantMsg ? { 'include-relevant-msg': 1 } : {}; return _parseXml( survey.xform ) .then( doc => { if ( typeof survey.preprocess === 'function' ) { doc = survey.preprocess.call( libxmljs, doc ); } return doc; } ) .then( doc => { xformDoc = doc; return _transform( sheets.xslForm, xformDoc, xsltParams ); } ) .then( htmlDoc => { htmlDoc = _replaceTheme( htmlDoc, survey.theme ); htmlDoc = _replaceMediaSources( htmlDoc, survey.media ); htmlDoc = _replaceLanguageTags( htmlDoc, survey ); if ( survey.markdown !== false ) { survey.form = _renderMarkdown( htmlDoc ); } else { survey.form = _docToString( htmlDoc ); } return _transform( sheets.xslModel, xformDoc ); } ) .then( xmlDoc => { xmlDoc = _replaceMediaSources( xmlDoc, survey.media ); xmlDoc = _addInstanceIdNodeIfMissing( xmlDoc ); survey.model = xmlDoc.root().get( '*' ).toString( false ); survey.transformerVersion = pkg.version; delete survey.xform; delete survey.media; delete survey.preprocess; delete survey.markdown; delete survey.includeRelevantMsg; return survey; } ); }
javascript
{ "resource": "" }