_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); return new Promise((resolve, reject) => { rimrafPromise(path.join(tmp, 'dist')) .then(() => exec(`node`, [cliPath, `build`, `--logFormat`, `none`], cwdOpts)) .then(serve) .then(resolve) .catch(err => reject(err)); }); }
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`]; webpackServer = childProcessSpawn(`node`, args, cwdOpts); resetConfig(); resolve(); }); }
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) { logger.info(`Mapping server requests from ${root} to ${dist}`); app.use(root, express.static(dist)); } const options = { cert: fs.readFileSync(path.resolve(__dirname, '../../ssl/server.crt')), key: fs.readFileSync(path.resolve(__dirname, '../../ssl/server.key')) }; server = https.createServer(options, app); server.on('error', reject); logger.info('Requesting open port...'); portfinder .getPortPromise() .then(port => { logger.info(`Open port found: ${port}`); logger.info('Starting web server...'); server.listen(port, 'localhost', () => { logger.info('Web server running.'); resolve(port); }); }) .catch(reject); }); }
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 logFormat = getLogFormat(skyPagesConfig, argv); let appPath; switch (outConfigMode) { case 'advanced': appPath = spaPath('src', 'main.ts'); break; default: appPath = outPath('src', 'main-internal.ts'); break; } let plugins = [ // Some properties are required on the root object passed to HtmlWebpackPlugin new HtmlWebpackPlugin({ template: skyPagesConfig.runtime.app.template, inject: skyPagesConfig.runtime.app.inject, runtime: skyPagesConfig.runtime, skyux: skyPagesConfig.skyux }), new CommonsChunkPlugin({ name: ['skyux', 'vendor', 'polyfills'] }), new webpack.DefinePlugin({ 'skyPagesConfig': JSON.stringify(skyPagesConfig) }), new LoaderOptionsPlugin({ options: { context: __dirname, skyPagesConfig: skyPagesConfig } }), new ContextReplacementPlugin( // The (\\|\/) piece accounts for path separators in *nix and Windows /angular(\\|\/)core(\\|\/)@angular/, spaPath('src'), {} ), new OutputKeepAlivePlugin({ enabled: argv['output-keep-alive'] }) ]; // Supporting a custom logging type of none if (logFormat !== 'none') { plugins.push(new SimpleProgressWebpackPlugin({ format: logFormat, color: logger.logColor })); } return { entry: { polyfills: [outPath('src', 'polyfills.ts')], vendor: [outPath('src', 'vendor.ts')], skyux: [outPath('src', 'skyux.ts')], app: [appPath] }, output: { filename: '[name].js', chunkFilename: '[id].chunk.js', path: spaPath('dist'), }, resolveLoader: { modules: resolves }, resolve: { alias: alias, modules: resolves, extensions: [ '.js', '.ts' ] }, module: { rules: [ { enforce: 'pre', test: /config\.ts$/, loader: outPath('loader', 'sky-app-config'), include: outPath('runtime') }, { enforce: 'pre', test: [ /\.(html|s?css)$/, /sky-pages\.module\.ts/ ], loader: outPath('loader', 'sky-assets') }, { enforce: 'pre', test: /sky-pages\.module\.ts$/, loader: outPath('loader', 'sky-pages-module') }, { enforce: 'pre', loader: outPath('loader', 'sky-processor', 'preload'), include: spaPath('src'), exclude: /node_modules/ }, { test: /\.s?css$/, use: [ 'raw-loader', 'sass-loader' ] }, { test: /\.html$/, loader: 'raw-loader' }, { test: /\.json$/, loader: 'json-loader' } ] }, plugins }; }
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. if (result.err) { reject(result.err); return; } // Catch non-zero status codes. if (result.status !== 0) { reject(new Error(`Angular compiler (ngc) exited with status code ${result.status}.`)); return; } resolve(); }); }
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 = resolveRelativeLocaleFileDestination( assetsUtils.getFilePathWithHash(filePath, true) ); } else { filePath = matchString.substring(2, matchString.length); filePathWithHash = assetsUtils.getFilePathWithHash(filePath, true); } if (callback) { callback(filePathWithHash, skyPagesConfigUtil.spaPath('src', filePath)); } const url = `${baseUrl}${filePathWithHash.replace(/\\/gi, '/')}`; content = content.replace( new RegExp(matchString, 'gi'), url ); match = ASSETS_REGEX.exec(content); } return content; }
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 || {}; assetsRule.options.baseUrl = getAssetsUrl(skyPagesConfig, baseUrl, rel); } }
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 = skyPagesConfigUtil.spaPath('src'); filePathWithHash = filePathWithHash.substr(srcPath.length + 1); } return filePathWithHash; }
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.devServer.port) { resolve(config.devServer.port); } else { portfinder.getPortPromise() .then(port => resolve(port)) .catch(err => reject(err)); } }); }
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}`; assetsProcessor.setSkyAssetsLoaderUrl(config, skyPagesConfig, localUrl); localeAssetsProcessor.prepareLocaleFiles(); // Save our found or defined port config.devServer.port = port; /* istanbul ignore else */ if (config.devServer.inline) { const inline = `webpack-dev-server/client?${localUrl}`; Object.keys(config.entry).forEach((entry) => { config.entry[entry].unshift(inline); }); } if (config.devServer.hot) { const hot = `webpack/hot/only-dev-server`; Object.keys(config.entry).forEach((entry) => { config.entry[entry].unshift(hot); }); // This is required in order to not have HMR requests routed to host. config.output.publicPath = `${localUrl}${config.devServer.publicPath}`; logger.info('Using hot module replacement.'); } const compiler = webpack(config); const server = new WebpackDevServer(compiler, config.devServer); server.listen(config.devServer.port, 'localhost', (err) => { if (err) { logger.error(err); } }); }).catch(err => logger.error(err)); }
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 && !lines[0].includes('-->')) { throw new ParserError(`Cue identifier cannot be standalone (cue #${i})`); } if (lines.length > 1 && !(lines[0].includes('-->') || lines[1].includes('-->'))) { const msg = `Cue identifier needs to be followed by timestamp (cue #${i})`; throw new ParserError(msg); } if (lines.length > 1 && lines[1].includes('-->')) { identifier = lines.shift(); } const times = lines[0].split(' --> '); if (times.length !== 2 || !validTimestamp(times[0]) || !validTimestamp(times[1])) { throw new ParserError(`Invalid cue timestamp (cue #${i})`); } start = parseTimestamp(times[0]); end = parseTimestamp(times[1]); if (start > end) { throw new ParserError(`Start timestamp greater than end (cue #${i})`); } if (end <= start) { throw new ParserError(`End must be greater than start (cue #${i})`); } // TODO better style validation styles = times[1].replace(TIMESTAMP_REGEXP, '').trim(); lines.shift(); text = lines.join('\n'); if (!text) { return false; } return { identifier, start, end, text, styles }; }
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(`Cue malformed: identifier value is not a string. ${JSON.stringify(cue)}`); } if (isNaN(cue.start)) { throw new CompilerError(`Cue malformed: null start value. ${JSON.stringify(cue)}`); } if (isNaN(cue.end)) { throw new CompilerError(`Cue malformed: null end value. ${JSON.stringify(cue)}`); } if (cue.start >= cue.end) { throw new CompilerError(`Cue malformed: start timestamp greater than end ${JSON.stringify(cue)}`); } if (typeof cue.text !== 'string') { throw new CompilerError(`Cue malformed: null text value. ${JSON.stringify(cue)}`); } if (typeof cue.styles !== 'string') { throw new CompilerError(`Cue malformed: null styles value. ${JSON.stringify(cue)}`); } let output = ''; if (cue.identifier.length > 0) { output += `${cue.identifier}\n`; } const startTimestamp = convertTimestamp(cue.start); const endTimestamp = convertTimestamp(cue.end); output += `${startTimestamp} --> ${endTimestamp}`; output += cue.styles ? ` ${cue.styles}` : ''; output += `\n${cue.text}`; return output; }
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";function add(left,top,width,bottom){if(top<0){top=0;}top=Math.round(top);bottom=Math.round(bottom);fragment.appendChild(elt("div",null,"CodeMirror-selected","position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(width==null?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px"));}function drawForLine(line,fromArg,toArg){var lineObj=getLine(doc,line);var lineLen=lineObj.text.length;var start,end;function coords(ch,bias){return _charCoords(cm,Pos(line,ch),"div",lineObj,bias);}function wrapX(pos,dir,side){var extent=wrappedLineExtentChar(cm,lineObj,null,pos);var prop=dir=="ltr"==(side=="after")?"left":"right";var ch=side=="after"?extent.begin:extent.end-(/\s/.test(lineObj.text.charAt(extent.end-1))?2:1);return coords(ch,prop)[prop];}var order=getOrder(lineObj,doc.direction);iterateBidiSections(order,fromArg||0,toArg==null?lineLen:toArg,function(from,to,dir,i){var ltr=dir=="ltr";var fromPos=coords(from,ltr?"left":"right");var toPos=coords(to-1,ltr?"right":"left");var openStart=fromArg==null&&from==0,openEnd=toArg==null&&to==lineLen;var first=i==0,last=!order||i==order.length-1;if(toPos.top-fromPos.top<=3){// Single line var openLeft=(docLTR?openStart:openEnd)&&first;var openRight=(docLTR?openEnd:openStart)&&last;var left=openLeft?leftSide:(ltr?fromPos:toPos).left;var right=openRight?rightSide:(ltr?toPos:fromPos).right;add(left,fromPos.top,right-left,fromPos.bottom);}else{// Multiple lines var topLeft,topRight,botLeft,botRight;if(ltr){topLeft=docLTR&&openStart&&first?leftSide:fromPos.left;topRight=docLTR?rightSide:wrapX(from,dir,"before");botLeft=docLTR?leftSide:wrapX(to,dir,"after");botRight=docLTR&&openEnd&&last?rightSide:toPos.right;}else{topLeft=!docLTR?leftSide:wrapX(from,dir,"before");topRight=!docLTR&&openStart&&first?rightSide:fromPos.right;botLeft=!docLTR&&openEnd&&last?leftSide:toPos.left;botRight=!docLTR?rightSide:wrapX(to,dir,"after");}add(topLeft,fromPos.top,topRight-topLeft,fromPos.bottom);if(fromPos.bottom<toPos.top){add(leftSide,fromPos.bottom,null,toPos.top);}add(botLeft,toPos.top,botRight-botLeft,toPos.bottom);}if(!start||cmpCoords(fromPos,start)<0){start=fromPos;}if(cmpCoords(toPos,start)<0){start=toPos;}if(!end||cmpCoords(fromPos,end)<0){end=fromPos;}if(cmpCoords(toPos,end)<0){end=toPos;}});return{start:start,end:end};}var sFrom=range$$1.from(),sTo=range$$1.to();if(sFrom.line==sTo.line){drawForLine(sFrom.line,sFrom.ch,sTo.ch);}else{var fromLine=getLine(doc,sFrom.line),toLine=getLine(doc,sTo.line);var singleVLine=visualLine(fromLine)==visualLine(toLine);var leftEnd=drawForLine(sFrom.line,sFrom.ch,singleVLine?fromLine.text.length+1:null).end;var rightStart=drawForLine(sTo.line,singleVLine?0:null,sTo.ch).start;if(singleVLine){if(leftEnd.top<rightStart.top-2){add(leftEnd.right,leftEnd.top,null,leftEnd.bottom);add(leftSide,rightStart.top,rightStart.left,rightStart.bottom);}else{add(leftEnd.right,leftEnd.top,rightStart.left-leftEnd.right,leftEnd.bottom);}}if(leftEnd.bottom<rightStart.top){add(leftSide,leftEnd.bottom,null,rightStart.top);}}output.appendChild(fragment);}
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()){cm.state.suppressEdits=true;}if(dropShift){cm.display.shift=false;}done=bound(cm)!=Pass;}finally{cm.display.shift=prevShift;cm.state.suppressEdits=false;}return done;}
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=order[index];if(part.from!=anchor.ch&&part.to!=anchor.ch){return range$$1;}var boundary=index+(part.from==anchor.ch==(part.level!=1)?0:1);if(boundary==0||boundary==order.length){return range$$1;}// Compute the relative visual position of the head compared to the // anchor (<0 is to the left, >0 to the right) var leftSide;if(head.line!=anchor.line){leftSide=(head.line-anchor.line)*(cm.doc.direction=="ltr"?1:-1)>0;}else{var headIndex=getBidiPartAt(order,head.ch,head.sticky);var dir=headIndex-index||(head.ch-anchor.ch)*(part.level==1?-1:1);if(headIndex==boundary-1||headIndex==boundary){leftSide=dir<0;}else{leftSide=dir>0;}}var usePart=order[boundary+(leftSide?-1:0)];var from=leftSide==(usePart.level==1);var ch=from?usePart.from:usePart.to,sticky=from?"after":"before";return anchor.ch==ch&&anchor.sticky==sticky?range$$1:new Range(new Pos(anchor.line,ch,sticky),head);}
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 some other handler touched the // selection in the meantime. display.selForContextMenu=cm.doc.sel;}}
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) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; }
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) { var route = element.type.createRouteFromReactElement(element, parentRoute); if (route) routes.push(route); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; }
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._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } }
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]; if (prop !== 'children' && propVal !== defaultProps[prop]) { propStr += ' ' + prop + '='; if (typeof propVal === 'string') { propStr += '"' + propVal + '"'; } else { propStr += '{' + JSON.stringify(propVal) + '}'; } } }); return propStr; }
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 your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ }
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()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; }
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 properties directly from the first argument to `getComponent`, `getComponents`, `getChildRoutes`, and `getIndexRoute` is deprecated. That argument is now the router state (`nextState` or `partialNextState`) rather than the location. To access the location, use `nextState.location` or `partialNextState.location`.') : void 0; return location[prop]; } }); }
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({}, state, { locationBeforeTransitions: payload }); } return state; }
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, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2.default.apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; }
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 names too. Maybe `/foo/` shouldn't show // `/foo` as active, but in this case, we would already have failed the // match. if (pathname.charAt(pathname.length - 1) !== '/') { pathname += '/'; } if (currentPathname.charAt(currentPathname.length - 1) !== '/') { currentPathname += '/'; } return currentPathname === pathname; }
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); } else if (match) { // A child route matched! Augment the match and pass it up the stack. match.routes.unshift(route); callback(null, match); } else { callback(); } }, remainingPathname, paramNames, paramValues); } else { callback(); } }
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$adjustUrlOnRepla = _ref.adjustUrlOnReplay, adjustUrlOnReplay = _ref$adjustUrlOnRepla === undefined ? true : _ref$adjustUrlOnRepla; // Ensure that the reducer is mounted on the store and functioning properly. if (typeof selectLocationState(store.getState()) === 'undefined') { throw new Error('Expected the routing state to be available either as `state.routing` ' + 'or as the custom expression you can specify as `selectLocationState` ' + 'in the `syncHistoryWithStore()` options. ' + 'Ensure you have added the `routerReducer` to your store\'s ' + 'reducers via `combineReducers` or whatever method you use to isolate ' + 'your reducers.'); } var initialLocation = void 0; var isTimeTraveling = void 0; var unsubscribeFromStore = void 0; var unsubscribeFromHistory = void 0; var currentLocation = void 0; // What does the store say about current location? var getLocationInStore = function getLocationInStore(useInitialIfEmpty) { var locationState = selectLocationState(store.getState()); return locationState.locationBeforeTransitions || (useInitialIfEmpty ? initialLocation : undefined); }; // Init initialLocation with potential location in store initialLocation = getLocationInStore(); // If the store is replayed, update the URL in the browser to match. if (adjustUrlOnReplay) { var handleStoreChange = function handleStoreChange() { var locationInStore = getLocationInStore(true); if (currentLocation === locationInStore || initialLocation === locationInStore) { return; } // Update address bar to reflect store state isTimeTraveling = true; currentLocation = locationInStore; history.transitionTo(_extends({}, locationInStore, { action: 'PUSH' })); isTimeTraveling = false; }; unsubscribeFromStore = store.subscribe(handleStoreChange); handleStoreChange(); } // Whenever location changes, dispatch an action to get it in the store var handleLocationChange = 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 state is reset initialLocation = location; // Respect persisted location, if any if (getLocationInStore()) { return; } } // Tell the store to update by dispatching an action store.dispatch({ type: _reducer.LOCATION_CHANGE, payload: location }); }; unsubscribeFromHistory = history.listen(handleLocationChange); // History 3.x doesn't call listen synchronously, so fire the initial location change ourselves if (history.getCurrentLocation) { handleLocationChange(history.getCurrentLocation()); } // The enhanced history uses store as source of truth return _extends({}, history, { // The listeners are subscribed to the store instead of history listen: 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.subscribe(function () { var currentLocation = getLocationInStore(true); if (currentLocation === lastPublishedLocation) { return; } lastPublishedLocation = currentLocation; if (!unsubscribed) { listener(lastPublishedLocation); } }); // History 2.x listeners expect a synchronous call. Make the first call to the // listener after subscribing to the store, in case the listener causes a // location change (e.g. when it redirects) if (!history.getCurrentLocation) { listener(lastPublishedLocation); } // Let user unsubscribe later return function () { unsubscribed = true; unsubscribeFromStore(); }; }, // It also provides a way to destroy internal listeners unsubscribe: function unsubscribe() { if (adjustUrlOnReplay) { unsubscribeFromStore(); } unsubscribeFromHistory(); } }); }
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 state is reset initialLocation = location; // Respect persisted location, if any if (getLocationInStore()) { return; } } // Tell the store to update by dispatching an action store.dispatch({ type: _reducer.LOCATION_CHANGE, payload: location }); }
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.subscribe(function () { var currentLocation = getLocationInStore(true); if (currentLocation === lastPublishedLocation) { return; } lastPublishedLocation = currentLocation; if (!unsubscribed) { listener(lastPublishedLocation); } }); // History 2.x listeners expect a synchronous call. Make the first call to the // listener after subscribing to the store, in case the listener causes a // location change (e.g. when it redirects) if (!history.getCurrentLocation) { listener(lastPublishedLocation); } // Let user unsubscribe later return function () { unsubscribed = true; unsubscribeFromStore(); }; }
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, args = _action$payload.args; history[method].apply(history, _toConsumableArray(args)); }; }; }; }
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, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }
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]; } return maskedContext; }
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 (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; }
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 " + db.getIgnore() + " INTO peers (peer_host, peer) VALUES (?,?)", [ sHost, sPeer ] ); } ); }
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( oWsByExplorerUrl, 'push_outbound_peers', arrOutboundPeerUrls ); } } ); }
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(assocOnlinePeers[curPeers.peers[j]]) assocOnlinePeers[curPeers.peers[j]]++; else assocOnlinePeers[curPeers.peers[j]] = 1; } } }); }
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 []; else return arrOnlinePeers.sort(compare()); }
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_addresses USING(address) \n\ WHERE main_chain_index>? AND main_chain_index<=? \n\ UNION \n\ SELECT peer FROM units JOIN watched_light_units USING(unit) \n\ WHERE main_chain_index>? AND main_chain_index<=?", [from_mci, to_mci, from_mci, to_mci, from_mci, to_mci], function (rows) { rows.forEach(function (row) { let ws = getPeerWebSocket(row.peer); if (ws && ws.readyState === ws.OPEN) sendJustsaying(ws, 'light/have_updates'); }); db.query("DELETE FROM watched_light_units \n\ WHERE unit IN (SELECT unit FROM units WHERE main_chain_index>? AND main_chain_index<=?)", [from_mci, to_mci], function () { }); } ); }
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 from_mci; let to_mci; _db.query ( "SELECT is_stable, is_on_main_chain, main_chain_index, ball FROM balls JOIN units USING(unit) WHERE ball IN(?,?)", [ from_ball, to_ball ], function( rows ) { if ( rows.length !== 2 ) { return callbacks.ifError( "some balls not found" ); } for ( let i = 0; i < rows.length; i++ ) { let props = rows[ i ]; if ( props.is_stable !== 1 ) { return callbacks.ifError( "some balls not stable" ); } if ( props.is_on_main_chain !== 1 ) { return callbacks.ifError( "some balls not on mc" ); } if ( props.ball === from_ball ) { from_mci = props.main_chain_index; } else if ( props.ball === to_ball ) { to_mci = props.main_chain_index; } } if ( from_mci >= to_mci ) { return callbacks.ifError( "from is after to" ); } let arrBalls = []; let op = ( from_mci === 0 ) ? ">=" : ">"; // if starting from 0, add genesis itself _db.query ( "SELECT unit, ball, content_hash FROM units LEFT JOIN balls USING(unit) \n\ WHERE main_chain_index " + op + " ? AND main_chain_index<=? ORDER BY `level`", [ from_mci, to_mci ], function( ball_rows ) { _async.eachSeries ( ball_rows, function( objBall, cb ) { if ( ! objBall.ball ) { throw Error( "no ball for unit " + objBall.unit ); } if ( objBall.content_hash ) { objBall.is_nonserial = true; } // ... delete objBall.content_hash; _db.query ( "SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball", [ objBall.unit ], function( parent_rows ) { if ( parent_rows.some(function(parent_row){ return ! parent_row.ball; })) { throw Error( "some parents have no balls" ); } if ( parent_rows.length > 0 ) { objBall.parent_balls = parent_rows.map(function(parent_row){ return parent_row.ball; }); } // // just collect skiplist balls // _db.query ( "SELECT ball FROM skiplist_units LEFT JOIN balls ON skiplist_unit=balls.unit WHERE skiplist_units.unit=? ORDER BY ball", [ objBall.unit ], function( srows ) { if ( srows.some(function(srow){ return ! srow.ball; })) { throw Error("some skiplist units have no balls"); } if ( srows.length > 0) { objBall.skiplist_balls = srows.map(function(srow){ return srow.ball; }); } // ... arrBalls.push( objBall ); // ... cb(); } ); } ); }, function() { callbacks.ifOk( arrBalls ); } ); } ); } ); }
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 || null === _nLastMainChainIndexFromPeers || nLastMainChainIndex > _nLastMainChainIndexFromPeers ) { _nLastRoundIndexFromPeers = nLastRoundIndex; _nLastMainChainIndexFromPeers = nLastMainChainIndex; _event_bus.emit( 'updated_last_round_index_from_peers', _nLastRoundIndexFromPeers, _nLastMainChainIndexFromPeers ); } } }
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 +" Actual :" + payload.deposit); deposit.getBalanceOfDepositContract(conn, depositAddress,objUnit.round_index, function (err,balance){ if(err) return cb(err); depositBalance = balance; cb(); }); }); }
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" : "Customized" }):: `, sPeerUrl, sKey, vValue ); // // callback while we received a update from remote peers // if ( ! GossiperUtils.isReservedKey( sKey ) ) { _oGossiperOptions.pfnPeerUpdate( sPeerUrl, sKey, vValue ); } }); _oGossiper.on( 'peer_alive', ( sPeerUrl ) => { // console.log( `GOSSIPER ))) EVENT [peer_alive] :: `, sPeerUrl ); }); _oGossiper.on( 'peer_failed', ( sPeerUrl ) => { console.error( `GOSSIPER ))) EVENT [peer_failed] :: `, sPeerUrl ); }); _oGossiper.on( 'new_peer', ( sPeerUrl ) => { // console.log( `GOSSIPER ))) EVENT [new_peer] :: `, sPeerUrl ); if ( sPeerUrl !== _oGossiperOptions.url && ! _oGossiper.m_oRouter.getSocket( sPeerUrl ) ) { // // try to connect to the new peer // _oGossiperOptions.pfnConnectToPeer( sPeerUrl, ( err, oNewWs ) => { if ( err ) { return console.error( `GOSSIPER ))) failed to connectToPeer: ${ sPeerUrl }.` ); } if ( ! oNewWs ) { return console.error( `GOSSIPER ))) connectToPeer returns an invalid oNewWs: ${ JSON.stringify( oNewWs ) }.` ); } // // update the remote socket // if ( ! DeUtilsCore.isPlainObjectWithKeys( oNewWs, 'url' ) || ! GossiperUtils.isValidPeerUrl( oNewWs.url ) ) { oNewWs.url = sPeerUrl; } // // update router // _oGossiper.updatePeerList({ [ sPeerUrl ] : oNewWs }); }); } }); _oGossiper.on( 'log', ( sType, vData ) => { // console.log( `GOSSIPER ))) EVENT [log/${ sType }] :: `, vData ); }); // // start gossiper // _oGossiper.start( {} ); }
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", [constants.POW_TYPE_TRUSTME], function(rows){ var hp = 1; // just after genesis or catchup from fresh start if (rows.length === 0){ db.query( "SELECT main_chain_index FROM units \n\ WHERE unit=?", [constants.GENESIS_UNIT], function(rowGenesis){ if(rowGenesis.length === 0){ setTimeout(function(){ initByzantine(); }, 3000); } else{ startPhase(hp, 0); } } ); } else if (rows.length === 1){ hp = rows[0].main_chain_index + 1; if(maxGossipHp === hp) { startPhase(hp, maxGossipPp); } else { setTimeout(function(){ initByzantine(); }, 3000); } } } ); }
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, assocByzantinePhase[hp].witnesses[pIndex], assocByzantinePhase[hp].roundIndex, assocByzantinePhase[hp].witnesses); } if(!validationUtils.isPositiveInteger(hp)) return cb("param hp is not a positive integer:" + hp); if(!validationUtils.isNonnegativeInteger(phase)) return cb("param phase is not a positive integer:" + phase); var conn = conn || db; round.getRoundIndexByNewMci(conn, hp, function(roundIndex){ if(roundIndex === -1) return cb("have not get the last mci yet "); round.getWitnessesByRoundIndex(conn, roundIndex, function(witnesses){ if(!assocByzantinePhase[hp] || typeof assocByzantinePhase[hp] === 'undefined' || Object.keys(assocByzantinePhase[hp]).length === 0){ assocByzantinePhase[hp] = {}; assocByzantinePhase[hp].roundIndex = roundIndex; assocByzantinePhase[hp].witnesses = witnesses; assocByzantinePhase[hp].phase = {}; assocByzantinePhase[hp].decision = {}; } cb(null, witnesses[pIndex], roundIndex, witnesses); }); }); }
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){ if(last_prevote_gossip.type === constants.BYZANTINE_PREVOTE && h_p === last_prevote_gossip.h){ // console.log("byllllogg gossipLastMessageAtFixedInterval broadcastPrevote" + JSON.stringify(last_prevote_gossip)); broadcastPrevote(last_prevote_gossip.h, last_prevote_gossip.p, last_prevote_gossip.idv); } } if(bByzantineUnderWay && last_precommit_gossip && typeof last_precommit_gossip !== 'undefined' && Object.keys(last_precommit_gossip).length > 0){ if(last_precommit_gossip.type === constants.BYZANTINE_PRECOMMIT && h_p === last_precommit_gossip.h){ if(last_precommit_gossip.idv !== null && assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal && typeof assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal !== 'undefined'){ var lastProposal = assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal; broadcastProposal(last_precommit_gossip.h, last_precommit_gossip.p, lastProposal, lastProposal.vp); } // console.log("byllllogg gossipLastMessageAtFixedInterval broadcastPrecommit" + JSON.stringify(last_precommit_gossip)); broadcastPrecommit(last_precommit_gossip.h, last_precommit_gossip.p, last_precommit_gossip.sig, last_precommit_gossip.idv); } } } }
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:" + arrByzantinePhases.length); return console.log('byllllogg byzantine cache is small, will not shrink'); } var minIndexByzantinePhases = Math.min.apply(Math, arrByzantinePhases); for (var offset1 = minIndexByzantinePhases; offset1 < h_p - constants.MAX_BYZANTINE_IN_CACHE; offset1++){ //console.log("byllllogg ByzantinePhaseCacheLog:shrinkByzantineCache,delete hp:" + offset1); delete assocByzantinePhase[offset1]; } // minIndexByzantinePhases = Math.min.apply(Math, arrByzantinePhases); // for (var offset2 = minIndexByzantinePhases; offset2 <= h_p; offset2++){ // if(assocByzantinePhase[offset2] && // typeof assocByzantinePhase[offset2] !== 'undefined' && // Object.keys(assocByzantinePhase[offset2]).length > 0){ // var phaseCount = Object.keys(assocByzantinePhase[offset2].phase).length; // if(phaseCount > constants.MAX_BYZANTINE_PHASE_IN_CACHE){ // for (var offset3 = 0; offset3 < phaseCount - constants.MAX_BYZANTINE_PHASE_IN_CACHE; offset3++){ // console.log("byllllogg ByzantinePhaseCacheLog:shrinkByzantineCache,delete hp phase:" + offset3); // delete assocByzantinePhase[offset2].phase[offset3]; // } // } // } // } }
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 WHERE address IN("+strAddressList+")", function(rows){ if (rows.length === 0) return handleAddedSharedAddresses(arrAddressList); var arrSharedAddresses = rows.map(function(row){ return row.shared_address; }); var arrNewMemberAddresses = _.difference(arrSharedAddresses, arrAddressList); if (arrNewMemberAddresses.length === 0) return handleAddedSharedAddresses(arrAddressList); addSharedAddressesOfWallet(arrAddressList.concat(arrNewMemberAddresses), handleAddedSharedAddresses); }); }
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 goUp(objChildJoint){ db.query( "SELECT parent.unit, parent.main_chain_index FROM units AS child JOIN units AS parent ON child.best_parent_unit=parent.unit \n\ WHERE child.unit=?", [objChildJoint.unit.unit], function(rows){ if (rows.length !== 1) throw Error("goUp not 1 parent"); if (rows[0].main_chain_index < objEarlierJoint.unit.main_chain_index) // jumped over the target return buildPathToEarlierUnit(objChildJoint); addJoint(rows[0].unit, function(objJoint){ (objJoint.unit.main_chain_index === objEarlierJoint.unit.main_chain_index) ? buildPathToEarlierUnit(objJoint) : goUp(objJoint); }); } ); } function buildPathToEarlierUnit(objJoint){ db.query( "SELECT unit FROM parenthoods JOIN units ON parent_unit=unit \n\ WHERE child_unit=? AND main_chain_index=?", [objJoint.unit.unit, objJoint.unit.main_chain_index], function(rows){ if (rows.length === 0) throw Error("no parents with same mci?"); var arrParentUnits = rows.map(function(row){ return row.unit }); if (arrParentUnits.indexOf(objEarlierJoint.unit.unit) >= 0) return onDone(); if (arrParentUnits.length === 1) return addJoint(arrParentUnits[0], buildPathToEarlierUnit); // find any parent that includes earlier unit async.eachSeries( arrParentUnits, function(unit, cb){ graph.determineIfIncluded(db, objEarlierJoint.unit.unit, [unit], function(bIncluded){ if (!bIncluded) return cb(); // try next cb(unit); // abort the eachSeries }); }, function(unit){ if (!unit) throw Error("none of the parents includes earlier unit"); addJoint(unit, buildPathToEarlierUnit); } ); } ); } if (objLaterJoint.unit.unit === objEarlierJoint.unit.unit) return onDone(); (objLaterJoint.unit.main_chain_index === objEarlierJoint.unit.main_chain_index) ? buildPathToEarlierUnit(objLaterJoint) : goUp(objLaterJoint); }
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 before storing the message into outbox var objEncryptedPackage = createEncryptedPackage(json, recipient_device_pubkey); // if the first attempt fails, this will be the inner message var objDeviceMessage = { encrypted_package: objEncryptedPackage }; var message_hash = objectHash.getBase64Hash(objDeviceMessage); conn = conn || db; conn.query( "INSERT INTO outbox (message_hash, `to`, message) VALUES (?,?,?)", [message_hash, recipient_device_address, JSON.stringify(objDeviceMessage)], function(){ if (callbacks && callbacks.onSaved) callbacks.onSaved(); sendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks); } ); }
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, ws){ if (err) return callbacks.ifError(err); sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks); }); } else sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks); }
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 queryFirstTrustMEBallOnMainChainByRoundIndex with invalid nRoundIndex, must be a number` ); } if ( nRoundIndex <= 0 ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundIndex with invalid nRoundIndex, must be greater than zero.` ); } // ... oConn.query ( "SELECT ball \ FROM balls JOIN units USING(unit) \ WHERE units.round_index = ? AND units.is_stable=1 AND units.is_on_main_chain=1 AND units.sequence='good' AND units.pow_type=? \ ORDER BY units.main_chain_index ASC \ LIMIT 1", [ nRoundIndex, constants.POW_TYPE_TRUSTME ], function( arrRows ) { if ( 1 !== arrRows.length ) { return pfnCallback( `Can not find a suitable ball for calculation pow.` ); } // ... return pfnCallback( null, arrRows[ 0 ][ 'ball' ] ); } ); }
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("param address is not a valid address"); conn.query( "SELECT round_index FROM units JOIN unit_authors USING(unit) \n\ WHERE is_stable=1 AND sequence='good' AND pow_type=? \n\ AND address=? ORDER BY round_index DESC LIMIT 1", [constants.POW_TYPE_COIN_BASE, address], function(rows){ if(rows.length === 0) return cb(null, 0); cb(null, rows[0].round_index); } ); }
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'); var suggestedDeviceName = require('os').hostname() || 'Headless'; // rl.question("Please name this device ["+suggestedDeviceName+"]: ", function(deviceName){ var deviceName = suggestedDeviceName; var userConfFile = appDataDir + '/conf.json'; fs.writeFile(userConfFile, JSON.stringify({deviceName: deviceName, admin_email: "admin@example.com", from_email: "noreply@example.com"}, null, '\t'), 'utf8', function(err){ if (err) throw Error('failed to write conf.json: '+err); // rl.question( console.log('Device name saved to '+userConfFile+', you can edit it later if you like.\n\nPassphrase for your private keys: ') // function(passphrase){ // rl.close(); var passphrase = "" if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1); if (process.stdout.clearLine) process.stdout.clearLine(); var deviceTempPrivKey = crypto.randomBytes(32); var devicePrevTempPrivKey = crypto.randomBytes(32); var mnemonic = new Mnemonic(); // generates new mnemonic while (!Mnemonic.isValid(mnemonic.toString())) mnemonic = new Mnemonic(); writeKeys(mnemonic.phrase, deviceTempPrivKey, devicePrevTempPrivKey, function(){ console.log('keys created'); xPrivKey = mnemonic.toHDPrivateKey(passphrase); createWallet(xPrivKey, function(){ onDone(mnemonic.phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); }); }); // } // ); }); // }); } else{ // 2nd or later start // rl.question("Passphrase: ", function(passphrase){ var passphrase = ""; // rl.close(); if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1); if (process.stdout.clearLine) process.stdout.clearLine(); var keys = JSON.parse(data); var deviceTempPrivKey = Buffer(keys.temp_priv_key, 'base64'); var devicePrevTempPrivKey = Buffer(keys.prev_temp_priv_key, 'base64'); determineIfWalletExists(function(bWalletExists){ if(!Mnemonic.isValid(keys.mnemonic_phrase)) throw Error('Invalid mnemonic_phrase in ' + KEYS_FILENAME) var mnemonic = new Mnemonic(keys.mnemonic_phrase); xPrivKey = mnemonic.toHDPrivateKey(passphrase); if (bWalletExists) onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); else{ createWallet(xPrivKey, function(){ onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); }); } }); // }); } }); }
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'), 'utf8', function(err){ if (err) throw Error("failed to write keys file"); if (onDone) onDone(); }); }
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/44'/0'/0'")).toString(); var walletDefinedByKeys = require('../wallet/wallet_defined_by_keys.js'); walletDefinedByKeys.createWalletByDevices(strXPubKey, 0, 1, [], 'any walletName', function(wallet_id){ walletDefinedByKeys.issueNextAddress(wallet_id, 0, function(){ onDone(); }); }); }
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": "" }