_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q50100
prepareBuild
train
function prepareBuild(config) { function serve(exitCode) { // Save our exitCode for testing _exitCode = exitCode; // Reset skyuxconfig.json resetConfig(); return server.start('unused-root', tmp) .then(port => browser.get(`https://localhost:${port}/dist/`)); } writeConfig(config); ...
javascript
{ "resource": "" }
q50101
prepareServe
train
function prepareServe() { if (webpackServer) { return bindServe(); } else { return new Promise((resolve, reject) => { portfinder.getPortPromise() .then(writeConfigServe) .then(bindServe) .then(resolve) .catch(err => reject(err)); }); } }
javascript
{ "resource": "" }
q50102
rimrafPromise
train
function rimrafPromise(dir) { return new Promise((resolve, reject) => { rimraf(dir, err => { if (err) { reject(err); } else { resolve(); } }); }); }
javascript
{ "resource": "" }
q50103
writeConfig
train
function writeConfig(json) { if (!skyuxConfigOriginal) { skyuxConfigOriginal = JSON.parse(fs.readFileSync(skyuxConfigPath)); } fs.writeFileSync(skyuxConfigPath, JSON.stringify(json), 'utf8'); }
javascript
{ "resource": "" }
q50104
writeConfigServe
train
function writeConfigServe(port) { return new Promise(resolve => { _port = port; const skyuxConfigWithPort = merge(true, skyuxConfigOriginal, { app: { port: port } }); writeConfig(skyuxConfigWithPort); const args = [cliPath, `serve`, `-l`, `none`, `--logFormat`, `none`]; we...
javascript
{ "resource": "" }
q50105
start
train
function start(root, distPath) { return new Promise((resolve, reject) => { const dist = path.resolve(process.cwd(), distPath || 'dist'); logger.info('Creating web server'); app.use(cors()); logger.info(`Exposing static directory: ${dist}`); app.use(express.static(dist)); if (root) { l...
javascript
{ "resource": "" }
q50106
getWebpackConfig
train
function getWebpackConfig(skyPagesConfig, argv = {}) { const resolves = [ process.cwd(), spaPath('node_modules'), outPath('node_modules') ]; let alias = aliasBuilder.buildAliasList(skyPagesConfig); const outConfigMode = skyPagesConfig && skyPagesConfig.skyux && skyPagesConfig.skyux.mode; const l...
javascript
{ "resource": "" }
q50107
version
train
function version() { const packageJson = require(path.resolve(__dirname, '..', 'package.json')); logger.info('@blackbaud/skyux-builder: %s', packageJson.version); }
javascript
{ "resource": "" }
q50108
createBundle
train
function createBundle(skyPagesConfig, webpack) { const webpackConfig = require('../config/webpack/build-public-library.webpack.config'); const config = webpackConfig.getWebpackConfig(skyPagesConfig); return runCompiler(webpack, config); }
javascript
{ "resource": "" }
q50109
transpile
train
function transpile() { return new Promise((resolve, reject) => { const result = spawn.sync( skyPagesConfigUtil.spaPath('node_modules', '.bin', 'ngc'), [ '--project', skyPagesConfigUtil.spaPathTemp('tsconfig.json') ], { stdio: 'inherit' } ); // Catch ngc errors. ...
javascript
{ "resource": "" }
q50110
getAssetsUrl
train
function getAssetsUrl(skyPagesConfig, baseUrl, rel) { return baseUrl + skyPagesConfig.runtime.app.base + (rel || ''); }
javascript
{ "resource": "" }
q50111
processAssets
train
function processAssets(content, baseUrl, callback) { let match = ASSETS_REGEX.exec(content); while (match) { const matchString = match[0]; let filePath; let filePathWithHash; if (isLocaleFile(matchString)) { filePath = resolvePhysicalLocaleFilePath(matchString); filePathWithHash = res...
javascript
{ "resource": "" }
q50112
setSkyAssetsLoaderUrl
train
function setSkyAssetsLoaderUrl(webpackConfig, skyPagesConfig, baseUrl, rel) { const rules = webpackConfig && webpackConfig.module && webpackConfig.module.rules; if (rules) { const assetsRule = rules.find(rule => /sky-assets$/.test(rule.loader)); assetsRule.options = assetsRule.options || {}; as...
javascript
{ "resource": "" }
q50113
getFilePathWithHash
train
function getFilePathWithHash(filePath, rel) { const indexOfLastDot = filePath.lastIndexOf('.'); let filePathWithHash = filePath.substr(0, indexOfLastDot) + '.' + hashFile.sync(skyPagesConfigUtil.spaPath('src', filePath)) + '.' + filePath.substr(indexOfLastDot + 1); if (!rel) { const srcPath ...
javascript
{ "resource": "" }
q50114
getUrl
train
function getUrl(baseUrl, filePath) { const filePathWithHash = getFilePathWithHash(filePath); const url = `${baseUrl}${filePathWithHash.replace(/\\/gi, '/')}`; return url; }
javascript
{ "resource": "" }
q50115
getPort
train
function getPort(config, skyPagesConfig) { return new Promise((resolve, reject) => { const configPort = skyPagesConfig && skyPagesConfig.skyux && skyPagesConfig.skyux.app && skyPagesConfig.skyux.app.port; if (configPort) { resolve(configPort); } else if (config.devServer && config...
javascript
{ "resource": "" }
q50116
serve
train
function serve(argv, skyPagesConfig, webpack, WebpackDevServer) { const webpackConfig = require('../config/webpack/serve.webpack.config'); let config = webpackConfig.getWebpackConfig(argv, skyPagesConfig); getPort(config, skyPagesConfig).then(port => { const localUrl = `https://localhost:${port}`; asse...
javascript
{ "resource": "" }
q50117
train
function (item) { const resolvedPath = path.resolve(item); const ignore = (resolvedPath.indexOf(srcPath) === -1); return ignore; }
javascript
{ "resource": "" }
q50118
resolve
train
function resolve(root, args) { args = root.concat(Array.prototype.slice.call(args)); return path.resolve.apply(path, args); }
javascript
{ "resource": "" }
q50119
getInstallDir
train
function getInstallDir (cb) { var key = new Registry({ hive: Registry.HKLM, key: '\\Software\\VideoLAN\\VLC' }) key.get('InstallDir', cb) }
javascript
{ "resource": "" }
q50120
isAllowedTagName
train
function isAllowedTagName(name) { const config = context.options[0] || {}; const allowedTagNames = config.allowedTagNames || DEFAULTS; return allowedTagNames.indexOf(name) !== -1; }
javascript
{ "resource": "" }
q50121
JSCS
train
function JSCS( options ) { this.checker = new Checker(); this.options = options; this._reporter = null; this.checker.registerDefaultRules(); this.checker.configure( this.getConfig() ); this.registerReporter( options.reporter ); }
javascript
{ "resource": "" }
q50122
parseCue
train
function parseCue (cue, i) { let identifier = ''; let start = 0; let end = 0.01; let text = ''; let styles = ''; // split and remove empty lines const lines = cue.split('\n').filter(Boolean); if (lines.length > 0 && lines[0].trim().startsWith('NOTE')) { return null; } if (lines.length === 1 &...
javascript
{ "resource": "" }
q50123
compileCue
train
function compileCue (cue) { // TODO: check for malformed JSON if (typeof cue !== 'object') { throw new CompilerError('Cue malformed: not of type object'); } if (typeof cue.identifier !== 'string' && typeof cue.identifier !== 'number' && cue.identifier !== null) { throw new CompilerError(`Cu...
javascript
{ "resource": "" }
q50124
drawSelectionRange
train
function drawSelectionRange(cm,range$$1,output){var display=cm.display,doc=cm.doc;var fragment=document.createDocumentFragment();var padding=paddingH(cm.display),leftSide=padding.left;var rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right;var docLTR=doc.direction=="ltr";funct...
javascript
{ "resource": "" }
q50125
doHandleBinding
train
function doHandleBinding(cm,bound,dropShift){if(typeof bound=="string"){bound=commands[bound];if(!bound){return false;}}// Ensure previous input has been read, so that the handler sees a // consistent view of the document cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=false;try{if(cm.isReadOnly()){...
javascript
{ "resource": "" }
q50126
bidiSimplify
train
function bidiSimplify(cm,range$$1){var anchor=range$$1.anchor;var head=range$$1.head;var anchorLine=getLine(cm.doc,anchor.line);if(cmp(anchor,head)==0&&anchor.sticky==head.sticky){return range$$1;}var order=getOrder(anchorLine);if(!order){return range$$1;}var index=getBidiPartAt(order,anchor.ch,anchor.sticky),part=orde...
javascript
{ "resource": "" }
q50127
prepareSelectAllHack
train
function prepareSelectAllHack(){if(te.selectionStart!=null){var selected=cm.somethingSelected();var extval='\u200B'+(selected?te.value:"");te.value='\u21DA';// Used to catch context-menu undo te.value=extval;input.prevInput=selected?"":'\u200B';te.selectionStart=1;te.selectionEnd=extval.length;// Re-set this, in case s...
javascript
{ "resource": "" }
q50128
getClosestInstanceFromNode
train
function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { nod...
javascript
{ "resource": "" }
q50129
createRoutesFromReactChildren
train
function createRoutesFromReactChildren(children, parentRoute) { var routes = []; _react2.default.Children.forEach(children, function (element) { if (_react2.default.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { ...
javascript
{ "resource": "" }
q50130
createRoutes
train
function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (routes && !Array.isArray(routes)) { routes = [routes]; } return routes; }
javascript
{ "resource": "" }
q50131
oneArgumentPooler
train
function oneArgumentPooler(copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }
javascript
{ "resource": "" }
q50132
accumulateDispatches
train
function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._disp...
javascript
{ "resource": "" }
q50133
listenBefore
train
function listenBefore(hook) { return history.listenBefore(function (location, callback) { _runTransitionHook2['default'](hook, addQuery(location), callback); }); }
javascript
{ "resource": "" }
q50134
beautifyCode
train
function beautifyCode(str) { var beautifulStr = str; try { beautifulStr = (0, _jsBeautify.html)(str, beautifySettings); } catch (err) { console.error('Beautify error:', err.message); } return beautifulStr; }
javascript
{ "resource": "" }
q50135
propsToString
train
function propsToString() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaultProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var propStr = ''; Object.keys(props).map(function (prop) { var propVal = props[prop]; ...
javascript
{ "resource": "" }
q50136
invokeGuardedCallback
train
function invokeGuardedCallback(name, func, a) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } }
javascript
{ "resource": "" }
q50137
unescape
train
function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; ...
javascript
{ "resource": "" }
q50138
findOwnerStack
train
function findOwnerStack(instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }
javascript
{ "resource": "" }
q50139
warning
train
function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in yo...
javascript
{ "resource": "" }
q50140
replaceReducer
train
function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); }
javascript
{ "resource": "" }
q50141
subscribe
train
function subscribe(observer) { if ((typeof observer === 'undefined' ? 'undefined' : _typeof(observer)) !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); ...
javascript
{ "resource": "" }
q50142
_loop
train
function _loop(prop) { if (!Object.prototype.hasOwnProperty.call(location, prop)) { return 'continue'; } Object.defineProperty(stateWithLocation, prop, { get: function get() { process.env.NODE_ENV !== 'production' ? (0, _routerWarning2.default)(false, 'Accessing location pro...
javascript
{ "resource": "" }
q50143
listenBefore
train
function listenBefore(hook) { return history.listenBefore(function (location, callback) { _runTransitionHook2['default'](hook, addBasename(location), callback); }); }
javascript
{ "resource": "" }
q50144
routerReducer
train
function routerReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, type = _ref.type, payload = _ref.payload; if (type === LOCATION_CHANGE) { return _extends({}...
javascript
{ "resource": "" }
q50145
createMarkupForCustomAttribute
train
function createMarkupForCustomAttribute(name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }
javascript
{ "resource": "" }
q50146
applyMiddleware
train
function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, en...
javascript
{ "resource": "" }
q50147
runLeaveHooks
train
function runLeaveHooks(routes, prevState) { for (var i = 0, len = routes.length; i < len; ++i) { if (routes[i].onLeave) routes[i].onLeave.call(routes[i], prevState); } }
javascript
{ "resource": "" }
q50148
pathIsActive
train
function pathIsActive(pathname, currentPathname) { // Normalize leading slash for consistency. Leading slash on pathname has // already been normalized in isActive. See caveat there. if (currentPathname.charAt(0) !== '/') { currentPathname = '/' + currentPathname; } // Normalize the end of both path name...
javascript
{ "resource": "" }
q50149
onChildRoutes
train
function onChildRoutes(error, childRoutes) { if (error) { callback(error); } else if (childRoutes) { // Check the child routes to see if any of them match. matchRoutes(childRoutes, location, function (error, match) { if (error) { callback(error); } els...
javascript
{ "resource": "" }
q50150
syncHistoryWithStore
train
function syncHistoryWithStore(history, store) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$selectLocationSt = _ref.selectLocationState, selectLocationState = _ref$selectLocationSt === undefined ? defaultSelectLocationState : _ref$selectLocationSt, _ref$ad...
javascript
{ "resource": "" }
q50151
getLocationInStore
train
function getLocationInStore(useInitialIfEmpty) { var locationState = selectLocationState(store.getState()); return locationState.locationBeforeTransitions || (useInitialIfEmpty ? initialLocation : undefined); }
javascript
{ "resource": "" }
q50152
handleLocationChange
train
function handleLocationChange(location) { // ... unless we just caused that location change if (isTimeTraveling) { return; } // Remember where we are currentLocation = location; // Are we being called for the first time? if (!initialLocation) { // Remember as a fallback in case...
javascript
{ "resource": "" }
q50153
listen
train
function listen(listener) { // Copy of last location. var lastPublishedLocation = getLocationInStore(true); // Keep track of whether we unsubscribed, as Redux store // only applies changes in subscriptions on next dispatch var unsubscribed = false; var unsubscribeFromStore = store.s...
javascript
{ "resource": "" }
q50154
routerMiddleware
train
function routerMiddleware(history) { return function () { return function (next) { return function (action) { if (action.type !== _actions.CALL_HISTORY_METHOD) { return next(action); } var _action$payload = action.payload, method = _action$payload.method, ...
javascript
{ "resource": "" }
q50155
getDataFromCustomEvent
train
function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if ((typeof detail === 'undefined' ? 'undefined' : _typeof(detail)) === 'object' && 'data' in detail) { return detail.data; } return null; }
javascript
{ "resource": "" }
q50156
receiveComponent
train
function receiveComponent(nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }
javascript
{ "resource": "" }
q50157
makeInsertMarkup
train
function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; }
javascript
{ "resource": "" }
q50158
makeRemove
train
function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; }
javascript
{ "resource": "" }
q50159
makeSetMarkup
train
function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; }
javascript
{ "resource": "" }
q50160
makeTextContent
train
function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; }
javascript
{ "resource": "" }
q50161
enqueue
train
function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; }
javascript
{ "resource": "" }
q50162
updateMarkup
train
function updateMarkup(nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? false ? invariant(false,...
javascript
{ "resource": "" }
q50163
unmountChildren
train
function unmountChildren(safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }
javascript
{ "resource": "" }
q50164
_maskContext
train
function _maskContext(context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } ...
javascript
{ "resource": "" }
q50165
constructSelectEvent
train
function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if ...
javascript
{ "resource": "" }
q50166
connectToServer
train
async function connectToServer(client, config) { return new Promise((resolve, reject) => { client .on('ready', error => (error ? reject(error) : resolve(client))) .on('error', error => reject(error)) .connect(config); }); }
javascript
{ "resource": "" }
q50167
createSftpConnection
train
async function createSftpConnection(client) { return new Promise((resolve, reject) => { client.sftp((error, sftp) => (error ? reject(error) : resolve(sftp))); }); }
javascript
{ "resource": "" }
q50168
readDirectory
train
async function readDirectory(sftp, path) { return new Promise(resolve => { sftp.readdir(path, (error, list) => { resolve(list || null); }); }); }
javascript
{ "resource": "" }
q50169
createDirectory
train
async function createDirectory(sftp, path) { return new Promise((resolve, reject) => { sftp.mkdir(path, error => (error ? reject(error) : resolve())); }); }
javascript
{ "resource": "" }
q50170
uploadFile
train
async function uploadFile(sftp, source, target) { return new Promise((resolve, reject) => { sftp.fastPut(source, target, error => (error ? reject(error) : resolve())); }); }
javascript
{ "resource": "" }
q50171
getNames
train
function getNames (resourceType) { const aliases = [resourceType]; if (resourceAliases[resourceType]) { return aliases.concat(resourceAliases[resourceType]); } return alias(resourceType); }
javascript
{ "resource": "" }
q50172
addPeer
train
function addPeer( sPeer ) { if ( assocKnownPeers[ sPeer ] ) { return; } // // save to memory // assocKnownPeers[ sPeer ] = true; // // save to local storage // let sHost = getHostByPeer( sPeer ); addPeerHost ( sHost, () => { console.log( "will insert peer " + sPeer ); db.query( "INSERT " + ...
javascript
{ "resource": "" }
q50173
pushOutBoundPeersToExplorer
train
function pushOutBoundPeersToExplorer(){ if(!conf.IF_BYZANTINE) return; if (conf.bLight ) return; findOutboundPeerOrConnect ( explorerUrl, ( err, oWsByExplorerUrl ) => { if ( ! err ) { let arrOutboundPeerUrls = arrOutboundPeers.map(function (ws) { return ws.peer; }); sendJustsaying( ...
javascript
{ "resource": "" }
q50174
sumOnLinePeers
train
function sumOnLinePeers() { let nowTime = Date.now(); assocOnlinePeers = {}; Object.keys(assocAllOutBoundPeers).forEach(function(curUrl){ var curPeers = assocAllOutBoundPeers[curUrl]; if(nowTime - parseInt(curPeers.time) < 3 * 60 * 1000){ for (var j=0; j<curPeers.peers.length; j++){ if(...
javascript
{ "resource": "" }
q50175
getOnLinePeers
train
function getOnLinePeers() { var arrOnlinePeers = []; function compare(){ return function(a,b){ return b['count'] - a['count']; } } Object.keys(assocOnlinePeers).forEach(function(curUrl){ arrOnlinePeers.push({peer:curUrl, count:assocOnlinePeers[curUrl]}); }) if(arrOnlinePeers.length === 0) return [...
javascript
{ "resource": "" }
q50176
notifyLightClientsAboutStableJoints
train
function notifyLightClientsAboutStableJoints(from_mci, to_mci) { db.query( "SELECT peer FROM units JOIN unit_authors USING(unit) JOIN watched_light_addresses USING(address) \n\ WHERE main_chain_index>? AND main_chain_index<=? \n\ UNION \n\ SELECT peer FROM units JOIN outputs USING(unit) JOIN watched_light_addr...
javascript
{ "resource": "" }
q50177
requestCatchup_Dev
train
function requestCatchup_Dev(oWebSocket, oRequestData) { // // { last_stable_mci: last_stable_mci, last_known_mci: last_known_mci } // if (!_bUnitTestEnv) { return console.log(`this function only works in dev env.`); } return sendRequest ( oWebSocket, 'catchup', oRequestData, true, handleCatchupChain...
javascript
{ "resource": "" }
q50178
sendPrivatePayment
train
function sendPrivatePayment(peer, arrChains) { let ws = getPeerWebSocket(peer); if (ws) return sendPrivatePaymentToWs(ws, arrChains); findOutboundPeerOrConnect(peer, function (err, ws) { if (!err) sendPrivatePaymentToWs(ws, arrChains); }); }
javascript
{ "resource": "" }
q50179
readHashTree
train
function readHashTree( hashTreeRequest, callbacks ) { let from_ball = hashTreeRequest.from_ball; let to_ball = hashTreeRequest.to_ball; if ( 'string' !== typeof from_ball ) { return callbacks.ifError( "no from_ball" ); } if ( 'string' !== typeof to_ball ) { return callbacks.ifError( "no to_ball" ); } let...
javascript
{ "resource": "" }
q50180
updateLastRoundIndexFromPeers
train
function updateLastRoundIndexFromPeers( nLastRoundIndex, nLastMainChainIndex ) { if ( 'number' === typeof nLastRoundIndex && nLastRoundIndex > 0 && 'number' === typeof nLastMainChainIndex && nLastMainChainIndex > 0 ) { if ( null === _nLastRoundIndexFromPeers || nLastRoundIndex > _nLastRoundIndexFromPeers || ...
javascript
{ "resource": "" }
q50181
train
function(cb){ deposit.getDepositAddressBySupernodeAddress(conn, objUnit.authors[0].address, function (err,depositAddress){ if(err) return cb(err + " can not send pow unit"); if(payload.deposit != depositAddress) return cb("pow unit deposit address is invalid expeected :" + depositAddress +" A...
javascript
{ "resource": "" }
q50182
gossiperOnReceivedMessage
train
function gossiperOnReceivedMessage( oWs, oMessage ) { try { _oGossiper.onReceivedMessage( oWs, oMessage ); } catch( oException ) { console.error( `GOSSIPER ))) gossiperOnReceivedMessage occurred an exception: ${ JSON.stringify( oException ) }` ); } }
javascript
{ "resource": "" }
q50183
_gossiperStartWithOptions
train
function _gossiperStartWithOptions( oOptions ) { // // create Gossiper instance // _oGossiper = new Gossiper( oOptions ); // // listen ... // _oGossiper.on( 'peer_update', ( sPeerUrl, sKey, vValue ) => { // console.log( `GOSSIPER ))) EVENT [peer_update] (${ GossiperUtils.isReservedKey( sKey ) ? "Reserved" :...
javascript
{ "resource": "" }
q50184
initByzantine
train
function initByzantine(){ if(!conf.IF_BYZANTINE) return; if(bByzantineUnderWay) return; db.query( "SELECT main_chain_index FROM units \n\ WHERE is_on_main_chain=1 AND is_stable=1 AND +sequence='good' AND pow_type=? \n\ ORDER BY main_chain_index DESC LIMIT 1", ...
javascript
{ "resource": "" }
q50185
getCoordinators
train
function getCoordinators(conn, hp, phase, cb){ hp = parseInt(hp); phase = parseInt(phase); var pIndex = Math.abs(hp-phase+999)%constants.TOTAL_COORDINATORS; if (assocByzantinePhase[hp] && assocByzantinePhase[hp].roundIndex && assocByzantinePhase[hp].witnesses){ return cb(null, assocByzantinePhas...
javascript
{ "resource": "" }
q50186
gossipLastMessageAtFixedInterval
train
function gossipLastMessageAtFixedInterval(){ if(p_phase_timeout >0 && Date.now() - p_phase_timeout > constants.BYZANTINE_PHASE_TIMEOUT){ if(bByzantineUnderWay && last_prevote_gossip && typeof last_prevote_gossip !== 'undefined' && Object.keys(last_prevote_gossip).length > 0){ ...
javascript
{ "resource": "" }
q50187
shrinkByzantineCache
train
function shrinkByzantineCache(){ // shrink assocByzantinePhase var arrByzantinePhases = Object.keys(assocByzantinePhase); if (arrByzantinePhases.length < constants.MAX_BYZANTINE_IN_CACHE){ //console.log("ByzantinePhaseCacheLog:shrinkByzantineCache,will not delete, assocByzantinePhase.length:" + arrByza...
javascript
{ "resource": "" }
q50188
addSharedAddressesOfWallet
train
function addSharedAddressesOfWallet(arrAddressList, handleAddedSharedAddresses){ if (!arrAddressList || arrAddressList.length === 0 ) return handleAddedSharedAddresses([]); var strAddressList = arrAddressList.map(db.escape).join(', '); db.query("SELECT DISTINCT shared_address FROM shared_address_signing_paths WHER...
javascript
{ "resource": "" }
q50189
buildPath
train
function buildPath(objLaterJoint, objEarlierJoint, arrChain, onDone){ function addJoint(unit, onAdded){ storage.readJoint(db, unit, { ifNotFound: function(){ throw Error("unit not found?"); }, ifFound: function(objJoint){ arrChain.push(objJoint); onAdded(objJoint); } }); } function...
javascript
{ "resource": "" }
q50190
reliablySendPreparedMessageToHub
train
function reliablySendPreparedMessageToHub(ws, recipient_device_pubkey, json, callbacks, conn){ var recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey); console.log('will encrypt and send to '+recipient_device_address+': '+JSON.stringify(json)); // encrypt to recipient's permanent pubkey b...
javascript
{ "resource": "" }
q50191
sendPreparedMessageToHub
train
function sendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks){ if (!callbacks) callbacks = {ifOk: function(){}, ifError: function(){}}; if (typeof ws === "string"){ var hub_host = ws; network.findOutboundPeerOrConnect(conf.WS_PROTOCOL+hub_host, function onLocatedHubForSend(err, w...
javascript
{ "resource": "" }
q50192
getMinWlByRoundIndex
train
function getMinWlByRoundIndex(conn, roundIndex, callback){ conn.query( "SELECT min_wl FROM round where round_index=?", [roundIndex], function(rows){ if (rows.length !== 1) throw Error("Can not find the right round index"); callback(rows[0].min_wl); } ); }
javascript
{ "resource": "" }
q50193
getCoinbaseByRoundIndex
train
function getCoinbaseByRoundIndex(roundIndex){ if(roundIndex < 1 || roundIndex > constants.ROUND_TOTAL_ALL) return 0; return constants.ROUND_COINBASE[Math.ceil(roundIndex/constants.ROUND_TOTAL_YEAR)-1]; }
javascript
{ "resource": "" }
q50194
queryFirstTrustMEBallOnMainChainByRoundIndex
train
function queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundI...
javascript
{ "resource": "" }
q50195
getLastCoinbaseUnitRoundIndex
train
function getLastCoinbaseUnitRoundIndex(conn, address, cb){ if (!conn) return getLastCoinbaseUnitRoundIndex(db, address, cb); if(!validationUtils.isNonemptyString(address)) return cb("param address is null or empty string"); if(!validationUtils.isValidAddress(address)) return cb("para...
javascript
{ "resource": "" }
q50196
readKeys
train
function readKeys(onDone){ console.log('-----------------------'); fs.readFile(KEYS_FILENAME, 'utf8', function(err, data){ var rl = readline.createInterface({ input: process.stdin, output: process.stdout, //terminal: true }); if (err){ // first start console.log('failed to read keys, will gen'); ...
javascript
{ "resource": "" }
q50197
writeKeys
train
function writeKeys(mnemonic_phrase, deviceTempPrivKey, devicePrevTempPrivKey, onDone){ var keys = { mnemonic_phrase: mnemonic_phrase, temp_priv_key: deviceTempPrivKey.toString('base64'), prev_temp_priv_key: devicePrevTempPrivKey.toString('base64') }; fs.writeFile(KEYS_FILENAME, JSON.stringify(keys, null, '\t')...
javascript
{ "resource": "" }
q50198
createWallet
train
function createWallet(xPrivKey, onDone){ var devicePrivKey = xPrivKey.derive("m/1'").privateKey.bn.toBuffer({size:32}); var device = require('../wallet/device.js'); device.setDevicePrivateKey(devicePrivKey); // we need device address before creating a wallet var strXPubKey = Bitcore.HDPublicKey(xPrivKey.derive("m/4...
javascript
{ "resource": "" }
q50199
determineIfWalletExists
train
function determineIfWalletExists(handleResult){ db.query("SELECT wallet FROM wallets", function(rows){ if (rows.length > 1) throw Error("more than 1 wallet"); handleResult(rows.length > 0); }); }
javascript
{ "resource": "" }