_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q58500
recursiveFn
validation
function recursiveFn(source, target, key) { if (isArray(source) || isObject(source)) { target = isPrimitive(target) ? isObject(source) ? {} : [] : target; for (var _key in source) { // $FlowFixMe: support computed key here setter(target, _key, recursiveFn(source[_key], target[_key], _key)); // target[key] = recursiveFn(source[key], target[key], key); } return target; } return fn(source, target, key); }
javascript
{ "resource": "" }
q58501
deepAssign
validation
function deepAssign() { for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) { args[_key2] = arguments[_key2]; } if (args.length < 2) { throw new Error('deepAssign accept two and more argument'); } for (var i = args.length - 1; i > -1; i--) { if (isPrimitive(args[i])) { throw new TypeError('deepAssign only accept non primitive type'); } } var target = args.shift(); args.forEach(function (source) { return _deepAssign(source, target); }); return target; }
javascript
{ "resource": "" }
q58502
getDeepProperty
validation
function getDeepProperty(obj, keys) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$throwError = _ref.throwError, throwError = _ref$throwError === undefined ? false : _ref$throwError, backup = _ref.backup; if (isString(keys)) { keys = keys.split('.'); } if (!isArray(keys)) { throw new TypeError('keys of getDeepProperty must be string or Array<string>'); } var read = []; var target = obj; for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; if (isVoid(target)) { if (throwError) { throw new Error('obj' + (read.length > 0 ? '.' + read.join('.') : ' itself') + ' is ' + target); } else { return backup; } } target = target[key]; read.push(key); } return target; }
javascript
{ "resource": "" }
q58503
transObjectAttrIntoArray
validation
function transObjectAttrIntoArray(obj) { var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (a, b) { return +a - +b; }; return _Object$keys(obj).sort(fn).reduce(function (order, key) { return order.concat(obj[key]); }, []); }
javascript
{ "resource": "" }
q58504
runRejectableQueue
validation
function runRejectableQueue(queue) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return new _Promise(function (resolve, reject) { var step = function step(index) { if (index >= queue.length) { resolve(); return; } var result = isFunction(queue[index]) ? queue[index].apply(queue, _toConsumableArray(args)) : queue[index]; if (result === false) return reject('stop'); return _Promise.resolve(result).then(function () { return step(index + 1); }).catch(function (err) { return reject(err || 'stop'); }); }; step(0); }); }
javascript
{ "resource": "" }
q58505
runStoppableQueue
validation
function runStoppableQueue(queue) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } var step = function step(index) { if (index >= queue.length) { return true; } var result = isFunction(queue[index]) ? queue[index].apply(queue, _toConsumableArray(args)) : queue[index]; if (result === false) return false; return step(++index); }; return step(0); }
javascript
{ "resource": "" }
q58506
getLegalBox
validation
function getLegalBox(_ref) { var src = _ref.src, box = _ref.box; if (isString(box) && box) return box; src = src.toLowerCase(); for (var key in boxSuffixMap) { var suffix = boxSuffixMap[key]; if (src.indexOf(suffix) > -1) return key; } return 'native'; }
javascript
{ "resource": "" }
q58507
bind$1
validation
function bind$1(fn, context) { if (fn.bind) { return fn.bind(context); } else if (fn.apply) { return function __autobind__() { for (var _len2 = arguments.length, args = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) { args[_key3] = arguments[_key3]; } return fn.apply(context, args); }; } else { return function __autobind__() { for (var _len3 = arguments.length, args = Array(_len3), _key4 = 0; _key4 < _len3; _key4++) { args[_key4] = arguments[_key4]; } return fn.call.apply(fn, [context].concat(_toConsumableArray(args))); }; } }
javascript
{ "resource": "" }
q58508
isAccessorDescriptor
validation
function isAccessorDescriptor(desc) { return !!desc && (isFunction(desc.get) || isFunction(desc.set)) && isBoolean(desc.configurable) && isBoolean(desc.enumerable) && desc.writable === undefined; }
javascript
{ "resource": "" }
q58509
isDataDescriptor
validation
function isDataDescriptor(desc) { return !!desc && desc.hasOwnProperty('value') && isBoolean(desc.configurable) && isBoolean(desc.enumerable) && isBoolean(desc.writable); }
javascript
{ "resource": "" }
q58510
isInitializerDescriptor
validation
function isInitializerDescriptor(desc) { return !!desc && isFunction(desc.initializer) && isBoolean(desc.configurable) && isBoolean(desc.enumerable) && isBoolean(desc.writable); }
javascript
{ "resource": "" }
q58511
createDefaultSetter
validation
function createDefaultSetter(key) { return function set(newValue) { _Object$defineProperty(this, key, { configurable: true, writable: true, // IS enumerable when reassigned by the outside word enumerable: true, value: newValue }); return newValue; }; }
javascript
{ "resource": "" }
q58512
compressOneArgFnArray
validation
function compressOneArgFnArray(fns) { var errmsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'You must pass me an array of function'; if (!isArray(fns) || fns.length < 1) { throw new TypeError(errmsg); } if (fns.length === 1) { if (!isFunction(fns[0])) { throw new TypeError(errmsg); } return fns[0]; } return fns.reduce(function (prev, curr) { if (!isFunction(curr) || !isFunction(prev)) throw new TypeError(errmsg); return function (value) { return bind$1(curr, this)(bind$1(prev, this)(value)); }; }); }
javascript
{ "resource": "" }
q58513
getBoundSuper
validation
function getBoundSuper(obj, fn) { if (typeof _WeakMap === 'undefined') { throw new Error('Using @autobind on ' + fn.name + '() requires WeakMap support due to its use of super.' + fn.name + '()'); } if (!mapStore) { mapStore = new _WeakMap(); } if (mapStore.has(obj) === false) { mapStore.set(obj, new _WeakMap()); } var superStore = mapStore.get(obj); // $FlowFixMe: already insure superStore is not undefined if (superStore.has(fn) === false) { // $FlowFixMe: already insure superStore is not undefined superStore.set(fn, bind$1(fn, obj)); } // $FlowFixMe: already insure superStore is not undefined return superStore.get(fn); }
javascript
{ "resource": "" }
q58514
autobind
validation
function autobind(obj, prop, descriptor) { if (arguments.length === 1) return autobindClass()(obj); var _ref = descriptor || {}, fn = _ref.value, configurable = _ref.configurable; if (!isFunction(fn)) { throw new TypeError('@autobind can only be used on functions, not "' + fn + '" in ' + (typeof fn === 'undefined' ? 'undefined' : _typeof(fn)) + ' on property "' + prop + '"'); } var constructor = obj.constructor; return { configurable: configurable, enumerable: false, get: function get() { var _this = this; var boundFn = function boundFn() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return fn.call.apply(fn, [_this].concat(_toConsumableArray(args))); }; // Someone accesses the property directly on the prototype on which it is // actually defined on, i.e. Class.prototype.hasOwnProperty(key) if (this === obj) { return fn; } // Someone accesses the property directly on a prototype, // but it was found up the chain, not defined directly on it // i.e. Class.prototype.hasOwnProperty(key) == false && key in Class.prototype if (this.constructor !== constructor && _Object$getPrototypeOf(this).constructor === constructor) { return fn; } // Autobound method calling super.sameMethod() which is also autobound and so on. if (this.constructor !== constructor && prop in this.constructor.prototype) { return getBoundSuper(this, fn); } _Object$defineProperty(this, prop, { configurable: true, writable: true, // NOT enumerable when it's a bound method enumerable: false, value: boundFn }); return boundFn; }, set: createDefaultSetter(prop) }; }
javascript
{ "resource": "" }
q58515
set
validation
function set(value) { if (value === true) { while (waitingQueue.length > 0) { waitingQueue[0](); waitingQueue.shift(); } } return value; }
javascript
{ "resource": "" }
q58516
attrAndStyleCheck
validation
function attrAndStyleCheck() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length > 2) { return ['set'].concat(args); } if (args.length === 2) { if (['video', 'container', 'wrapper', 'videoElement'].indexOf(args[0]) > -1) { return ['get'].concat(args); } return ['set', 'container'].concat(args); } return ['get', 'container'].concat(args); }
javascript
{ "resource": "" }
q58517
Vessel
validation
function Vessel(dispatcher, target, config) { var _this = this; _classCallCheck(this, Vessel); this.__dispatcher = dispatcher; this.__target = target; ['width', 'height', 'position', 'display'].forEach(function (key) { _Object$defineProperty(_this, key, { get: function get() { return this.__dispatcher.dom.getStyle(this.__target, key); }, set: function set(value) { if (isNumber(value)) { value = value + 'px'; } if (!isString(value)) { throw new Error('The value of ' + key + ' in ' + this.__target + 'Config must be string, but not ' + (typeof value === 'undefined' ? 'undefined' : _typeof(value)) + '.'); } this.__dispatcher.dom.setStyle(this.__target, key, value); // return value; }, configurable: true, enumerable: true }); }); deepAssign(this, config); }
javascript
{ "resource": "" }
q58518
destroy
validation
function destroy() { for (var _key in this.plugins) { this.unuse(_key); } this.binder.destroy(); delete this.binder; this.dom.destroy(); delete this.dom; this.kernel.destroy(); delete this.kernel; delete this.vm; delete this.plugins; delete this.order; }
javascript
{ "resource": "" }
q58519
eventBinderCheck
validation
function eventBinderCheck(key, fn) { if (!chimeeHelper.isString(key)) throw new TypeError('key parameter must be String'); if (!chimeeHelper.isFunction(fn)) throw new TypeError('fn parameter must be Function'); }
javascript
{ "resource": "" }
q58520
oldVideoTimeupdate
validation
function oldVideoTimeupdate() { var currentTime = _this2.kernel.currentTime; if (bias <= 0 && currentTime >= idealTime || bias > 0 && (Math.abs(idealTime - currentTime) <= bias && newVideoReady || currentTime - idealTime > bias)) { chimeeHelper.removeEvent(_this2.dom.videoElement, 'timeupdate', oldVideoTimeupdate); chimeeHelper.removeEvent(video, 'error', _videoError, true); if (!newVideoReady) { chimeeHelper.removeEvent(video, 'canplay', videoCanplay, true); chimeeHelper.removeEvent(video, 'loadedmetadata', videoLoadedmetadata, true); kernel.destroy(); return resolve(); } return reject({ error: false, video: video, kernel: kernel }); } }
javascript
{ "resource": "" }
q58521
registerEvents
validation
function registerEvents() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, name = _ref.name, target = _ref.target; if (!name || !chimeeHelper.isString(name)) throw new Error('The event name must be a string, but not ' + (typeof name === 'undefined' ? 'undefined' : _typeof(name))); if (!target || !chimeeHelper.isString(target)) throw new Error('The event target must be a string, but not ' + (typeof target === 'undefined' ? 'undefined' : _typeof(target))); if (target === 'kernel') { kernelEvents.push(name); } }
javascript
{ "resource": "" }
q58522
validation
function (runState) { const [a, b] = runState.stack.popN(2) const r = new BN(a.lt(b) ? 1 : 0) runState.stack.push(r) }
javascript
{ "resource": "" }
q58523
validation
function (runState) { const [offset, length] = runState.stack.popN(2) subMemUsage(runState, offset, length) let data = Buffer.alloc(0) if (!length.isZero()) { data = runState.memory.read(offset.toNumber(), length.toNumber()) } // copy fee subGas(runState, new BN(runState._common.param('gasPrices', 'sha3Word')).imul(length.divCeil(new BN(32)))) const r = new BN(utils.keccak256(data)) runState.stack.push(r) }
javascript
{ "resource": "" }
q58524
validation
function (runState, cb) { const number = runState.stack.pop() var blockchain = runState.blockchain var diff = new BN(runState.block.header.number).sub(number) // block lookups must be within the past 256 blocks if (diff.gtn(256) || diff.lten(0)) { runState.stack.push(new BN(0)) cb(null) return } blockchain.getBlock(number, function (err, block) { if (err) return cb(err) const blockHash = new BN(block.hash()) runState.stack.push(blockHash) cb(null) }) }
javascript
{ "resource": "" }
q58525
validation
function (runState, done) { if (runState.static) { trap(ERROR.STATIC_STATE_CHANGE) } const [value, offset, length] = runState.stack.popN(3) subMemUsage(runState, offset, length) let data = Buffer.alloc(0) if (!length.isZero()) { data = runState.memory.read(offset.toNumber(), length.toNumber()) } // set up config var options = { value: value, data: data } var localOpts = { inOffset: offset, inLength: length, outOffset: new BN(0), outLength: new BN(0) } checkCallMemCost(runState, options, localOpts) checkOutOfGas(runState, options) makeCall(runState, options, localOpts, done) }
javascript
{ "resource": "" }
q58526
validation
function (runState, cb) { let selfdestructToAddress = runState.stack.pop() if (runState.static) { trap(ERROR.STATIC_STATE_CHANGE) } var stateManager = runState.stateManager var contract = runState.contract var contractAddress = runState.address selfdestructToAddress = addressToBuffer(selfdestructToAddress) stateManager.getAccount(selfdestructToAddress, function (err, toAccount) { // update balances if (err) { cb(err) return } stateManager.accountIsEmpty(selfdestructToAddress, function (error, empty) { if (error) { cb(error) return } if ((new BN(contract.balance)).gtn(0)) { if (empty) { try { subGas(runState, new BN(runState._common.param('gasPrices', 'callNewAccount'))) } catch (e) { cb(e.error) return } } } // only add to refund if this is the first selfdestruct for the address if (!runState.selfdestruct[contractAddress.toString('hex')]) { runState.gasRefund = runState.gasRefund.addn(runState._common.param('gasPrices', 'selfdestructRefund')) } runState.selfdestruct[contractAddress.toString('hex')] = selfdestructToAddress runState.stopped = true var newBalance = new BN(contract.balance).add(new BN(toAccount.balance)) async.waterfall([ stateManager.getAccount.bind(stateManager, selfdestructToAddress), function (account, cb) { account.balance = newBalance stateManager.putAccount(selfdestructToAddress, account, cb) }, stateManager.getAccount.bind(stateManager, contractAddress), function (account, cb) { account.balance = new BN(0) stateManager.putAccount(contractAddress, account, cb) } ], function (err) { // The reason for this is to avoid sending an array of results cb(err) }) }) }) }
javascript
{ "resource": "" }
q58527
getDataSlice
validation
function getDataSlice (data, offset, length) { let len = new BN(data.length) if (offset.gt(len)) { offset = len } let end = offset.add(length) if (end.gt(len)) { end = len } data = data.slice(offset.toNumber(), end.toNumber()) // Right-pad with zeros to fill dataLength bytes data = utils.setLengthRight(data, length.toNumber()) return data }
javascript
{ "resource": "" }
q58528
checkCallMemCost
validation
function checkCallMemCost (runState, callOptions, localOpts) { // calculates the gas need for saving the output in memory subMemUsage(runState, localOpts.outOffset, localOpts.outLength) if (!callOptions.gasLimit) { callOptions.gasLimit = new BN(runState.gasLeft) } }
javascript
{ "resource": "" }
q58529
validation
function (next) { genesisBlock.header = new BlockHeader( testData.genesisBlockHeader ) blockchain.putGenesis(genesisBlock, next) }
javascript
{ "resource": "" }
q58530
validation
function (next) { async.eachSeries(testData.blocks, eachBlock, next) function eachBlock (raw, cb) { try { var block = new Block( Buffer.from(raw.rlp.slice(2), 'hex')) // forces the block into thinking they are homestead block.header.isHomestead = function () { return true } block.uncleHeaders.forEach(function (uncle) { uncle.isHomestead = function () { return true } }) blockchain.putBlock(block, function (err) { cb(err) }) } catch (err) { cb() } } }
javascript
{ "resource": "" }
q58531
getHead
validation
function getHead (next) { vm.blockchain.getHead(function (err, block) { // make sure the state is set before checking post conditions state.root = block.header.stateRoot next(err) }) }
javascript
{ "resource": "" }
q58532
runVm
validation
function runVm (err) { // Check that the programCounter is in range. Does not overwrite the previous err, if any. const pc = runState.programCounter if (!err && pc !== 0 && (pc < 0 || pc >= runState.code.length)) { err = new VmError(ERROR.INVALID_OPCODE) } if (err) { return parseVmResults(err) } async.whilst(vmIsActive, iterateVm, parseVmResults) }
javascript
{ "resource": "" }
q58533
loadContract
validation
function loadContract (cb) { stateManager.getAccount(runState.address, function (err, account) { if (err) return cb(err) runState.contract = account cb() }) }
javascript
{ "resource": "" }
q58534
preprocessValidJumps
validation
function preprocessValidJumps (runState) { for (var i = 0; i < runState.code.length; i++) { var curOpCode = lookupOpInfo(runState.code[i]).name // no destinations into the middle of PUSH if (curOpCode === 'PUSH') { i += runState.code[i] - 0x5f } if (curOpCode === 'JUMPDEST') { runState.validJumps.push(i) } } }
javascript
{ "resource": "" }
q58535
getStartingState
validation
function getStartingState (cb) { // if we are just starting or if a chain re-org has happened if (!headBlock || reorg) { blockchain.getBlock(block.header.parentHash, function (err, parentBlock) { parentState = parentBlock.header.stateRoot // generate genesis state if we are at the genesis block // we don't have the genesis state if (!headBlock) { return self.stateManager.generateCanonicalGenesis(cb) } else { cb(err) } }) } else { parentState = headBlock.header.stateRoot cb() } }
javascript
{ "resource": "" }
q58536
runBlock
validation
function runBlock (cb) { self.runBlock({ block: block, root: parentState }, function (err, results) { if (err) { // remove invalid block blockchain.delBlock(block.header.hash(), function () { cb(err) }) } else { // set as new head block headBlock = block cb() } }) }
javascript
{ "resource": "" }
q58537
payOmmersAndMiner
validation
function payOmmersAndMiner (cb) { var ommers = block.uncleHeaders // pay each ommer async.series([ rewardOmmers, rewardMiner ], cb) function rewardOmmers (done) { async.each(block.uncleHeaders, function (ommer, next) { // calculate reward var minerReward = new BN(self._common.param('pow', 'minerReward')) var heightDiff = new BN(block.header.number).sub(new BN(ommer.number)) var reward = ((new BN(8)).sub(heightDiff)).mul(minerReward.divn(8)) if (reward.ltn(0)) { reward = new BN(0) } rewardAccount(ommer.coinbase, reward, next) }, done) } function rewardMiner (done) { // calculate nibling reward var minerReward = new BN(self._common.param('pow', 'minerReward')) var niblingReward = minerReward.divn(32) var totalNiblingReward = niblingReward.muln(ommers.length) var reward = minerReward.add(totalNiblingReward) rewardAccount(block.header.coinbase, reward, done) } function rewardAccount (address, reward, done) { self.stateManager.getAccount(address, function (err, account) { if (err) return done(err) // give miner the block reward account.balance = new BN(account.balance).add(reward) self.stateManager.putAccount(address, account, done) }) } }
javascript
{ "resource": "" }
q58538
parseBlockResults
validation
function parseBlockResults (err) { if (err) { if (checkpointedState) { self.stateManager.revert(function () { cb(err) }) } else { cb(err) } return } self.stateManager.commit(function (err) { if (err) return cb(err) self.stateManager.getStateRoot(function (err, stateRoot) { if (err) return cb(err) // credit all block rewards if (generateStateRoot) { block.header.stateRoot = stateRoot } if (validateStateRoot) { if (receiptTrie.root && receiptTrie.root.toString('hex') !== block.header.receiptTrie.toString('hex')) { err = new Error((err || '') + 'invalid receiptTrie ') } if (bloom.bitvector.toString('hex') !== block.header.bloom.toString('hex')) { err = new Error((err || '') + 'invalid bloom ') } if (ethUtil.bufferToInt(block.header.gasUsed) !== Number(gasUsed)) { err = new Error((err || '') + 'invalid gasUsed ') } if (stateRoot.toString('hex') !== block.header.stateRoot.toString('hex')) { err = new Error((err || '') + 'invalid block stateRoot ') } } result = { receipts: receipts, results: txResults, error: err } afterBlock(cb.bind(this, err, result)) }) }) }
javascript
{ "resource": "" }
q58539
setup
validation
function setup (cb) { // the address we are sending from var publicKeyBuf = Buffer.from(keyPair.publicKey, 'hex') var address = utils.pubToAddress(publicKeyBuf, true) // create a new account var account = new Account() // give the account some wei. // Note: this needs to be a `Buffer` or a string. All // strings need to be in hex. account.balance = '0xf00000000000000001' // store in the trie stateTrie.put(address, account.serialize(), cb) }
javascript
{ "resource": "" }
q58540
runTx
validation
function runTx (raw, cb) { // create a new transaction out of the json var tx = new Transaction(raw) // tx.from tx.sign(Buffer.from(keyPair.secretKey, 'hex')) console.log('----running tx-------') // run the tx \o/ vm.runTx({ tx: tx }, function (err, results) { createdAddress = results.createdAddress // log some results console.log('gas used: ' + results.gasUsed.toString()) console.log('returned: ' + results.vm.return.toString('hex')) if (createdAddress) { console.log('address created: ' + createdAddress.toString('hex')) } cb(err) }) }
javascript
{ "resource": "" }
q58541
checkResults
validation
function checkResults (cb) { // fetch the new account from the trie. stateTrie.get(createdAddress, function (err, val) { var account = new Account(val) storageRoot = account.stateRoot // used later! :) console.log('------results------') console.log('nonce: ' + account.nonce.toString('hex')) console.log('balance in wei: ' + account.balance.toString('hex')) console.log('stateRoot: ' + storageRoot.toString('hex')) console.log('codeHash:' + account.codeHash.toString('hex')) console.log('-------------------') cb(err) }) }
javascript
{ "resource": "" }
q58542
readStorage
validation
function readStorage (cb) { // we need to create a copy of the state root var storageTrie = stateTrie.copy() // Since we are using a copy we won't change the // root of `stateTrie` storageTrie.root = storageRoot var stream = storageTrie.createReadStream() console.log('------Storage------') // prints all of the keys and values in the storage trie stream.on('data', function (data) { // remove the 'hex' if you want to see the ascii values console.log('key: ' + data.key.toString('hex')) console.log('Value: ' + rlp.decode(data.value).toString()) }) stream.on('end', cb) }
javascript
{ "resource": "" }
q58543
_handleKey
validation
function _handleKey(character, modifiers, e) { var self = this; if (!self.recording) { _origHandleKey.apply(self, arguments); return; } // remember this character if we're currently recording a sequence if (e.type == 'keydown') { if (character.length === 1 && _recordedCharacterKey) { _recordCurrentCombo(); } for (i = 0; i < modifiers.length; ++i) { _recordKey(modifiers[i]); } _recordKey(character); // once a key is released, all keys that were held down at the time // count as a keypress } else if (e.type == 'keyup' && _currentRecordedKeys.length > 0) { _recordCurrentCombo(); } }
javascript
{ "resource": "" }
q58544
_recordKey
validation
function _recordKey(key) { var i; // one-off implementation of Array.indexOf, since IE6-9 don't support it for (i = 0; i < _currentRecordedKeys.length; ++i) { if (_currentRecordedKeys[i] === key) { return; } } _currentRecordedKeys.push(key); if (key.length === 1) { _recordedCharacterKey = true; } }
javascript
{ "resource": "" }
q58545
_normalizeSequence
validation
function _normalizeSequence(sequence) { var i; for (i = 0; i < sequence.length; ++i) { sequence[i].sort(function(x, y) { // modifier keys always come first, in alphabetical order if (x.length > 1 && y.length === 1) { return -1; } else if (x.length === 1 && y.length > 1) { return 1; } // character keys come next (list should contain no duplicates, // so no need for equality check) return x > y ? 1 : -1; }); sequence[i] = sequence[i].join('+'); } }
javascript
{ "resource": "" }
q58546
_finishRecording
validation
function _finishRecording() { if (_recordedSequenceCallback) { _normalizeSequence(_recordedSequence); _recordedSequenceCallback(_recordedSequence); } // reset all recorded state _recordedSequence = []; _recordedSequenceCallback = null; _currentRecordedKeys = []; }
javascript
{ "resource": "" }
q58547
CreateSetPolyfill
validation
function CreateSetPolyfill() { return /** @class */ (function () { function Set() { this._map = new _Map(); } Object.defineProperty(Set.prototype, "size", { get: function () { return this._map.size; }, enumerable: true, configurable: true }); Set.prototype.has = function (value) { return this._map.has(value); }; Set.prototype.add = function (value) { return this._map.set(value, value), this; }; Set.prototype.delete = function (value) { return this._map.delete(value); }; Set.prototype.clear = function () { this._map.clear(); }; Set.prototype.keys = function () { return this._map.keys(); }; Set.prototype.values = function () { return this._map.values(); }; Set.prototype.entries = function () { return this._map.entries(); }; Set.prototype["@@iterator"] = function () { return this.keys(); }; Set.prototype[iteratorSymbol] = function () { return this.keys(); }; return Set; }()); }
javascript
{ "resource": "" }
q58548
fuzzysearch
validation
function fuzzysearch (searchString, haystack, caseInsensitive) { var tlen = haystack.length; var qlen = searchString.length; var chunks = 1; var finding = false; var prefix = true; if (qlen > tlen) { return false; } if (qlen === tlen) { if (searchString === haystack) { return { caseMatch: true, chunks: 1, prefix: true }; } else if (searchString.toLowerCase() === haystack.toLowerCase()) { return { caseMatch: false, chunks: 1, prefix: true }; } else { return false; } } outer: for (var i = 0, j = 0; i < qlen; i++) { var nch = searchString[i]; while (j < tlen) { var targetChar = haystack[j++]; if (targetChar === nch) { finding = true; continue outer; } if (finding) { chunks++; finding = false; } } if (caseInsensitive) { return false } return fuzzysearch(searchString.toLowerCase(), haystack.toLowerCase(), true); } return { caseMatch: !caseInsensitive, chunks: chunks, prefix: j <= qlen }; }
javascript
{ "resource": "" }
q58549
getExternals
validation
function getExternals (api, pluginOptions) { const nodeModulesPath = pluginOptions.nodeModulesPath || './node_modules' let nodeModulesPaths = [] if (Array.isArray(nodeModulesPath)) { // Set to user-defined array nodeModulesPaths = nodeModulesPath } else { // Add path to list nodeModulesPaths.push(nodeModulesPath) } const userExternals = pluginOptions.externals || [] const userExternalsWhitelist = [] userExternals.forEach((d, i) => { if (d.match(/^!/)) { userExternals.splice(i, 1) userExternalsWhitelist.push(d.replace(/^!/, '')) } }) const { dependencies } = require(api.resolve('./package.json')) const externalsList = Object.keys(dependencies || {}).reduce( (depList, dep) => { // Return true if we want to add a dependency to externals try { let pgkString for (const path of nodeModulesPaths) { // Check if package.json exists if (fs.existsSync(api.resolve(`${path}/${dep}/package.json`))) { // If it does, read it and break pgkString = fs .readFileSync(api.resolve(`${path}/${dep}/package.json`)) .toString() break } } if (!pgkString) { throw new Error(`Could not find a package.json for module ${dep}`) } const pkg = JSON.parse(pgkString) const name = userExternals.find(name => new RegExp(`^${pkg.name}`).test(name) ) const fields = ['main', 'module', 'jsnext:main', 'browser'] if ( // Not whitelisted userExternalsWhitelist.indexOf(dep) === -1 && // Doesn't have main property (!fields.some(field => field in pkg) || // Has binary property !!pkg.binary || // Has gypfile property !!pkg.gypfile || // Listed in user-defined externals list !!name) ) { // Use user-provided name if it exists, for subpaths depList.push(name || dep) } } catch (e) { console.log(e) depList.push(dep) } return depList }, [] ) let externals = {} externalsList.forEach(d => { // Set external to be required during runtime externals[d] = `require("${d}")` }) return externals }
javascript
{ "resource": "" }
q58550
validation
function(hashKey, dataObject, myContent, myClass, bootstrapSettings) { var exportButton = document.createElement("button"); exportButton.setAttribute("type", "button"); exportButton.setAttribute(this.storageKey, hashKey); exportButton.className = bootstrapSettings.bootstrapClass + bootstrapSettings.bootstrapTheme + myClass; exportButton.textContent = myContent; return exportButton; }
javascript
{ "resource": "" }
q58551
validation
function(string) { var self = this; return String(string).replace(/[&<>'\/]/g, function(s) { return self.entityMap[s]; }); }
javascript
{ "resource": "" }
q58552
validation
function(string) { var str = String(string); for (var key in this.entityMap) { str = str.replace(RegExp(this.entityMap[key], "g"), key); } return str; }
javascript
{ "resource": "" }
q58553
validation
function(string) { if (!string) return ""; var types = this.typeConfig; if (~string.indexOf(types.string.defaultClass)) { return _TYPE.STRING; } else if (~string.indexOf(types.number.defaultClass)) { return _TYPE.NUMBER; } else if (~string.indexOf(types.boolean.defaultClass)) { return _TYPE.BOOLEAN; } else if (~string.indexOf(types.date.defaultClass)) { return _TYPE.DATE; } else { return ""; } }
javascript
{ "resource": "" }
q58554
validation
function(v, date1904) { if (date1904) v += 1462; var epoch = Date.parse(v); var result = (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000); return Math.floor(result); }
javascript
{ "resource": "" }
q58555
validation
function(data, merges) { var ws = {}; var range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } }; var types = this.typeConfig; for (var R = 0; R !== data.length; ++R) { for (var C = 0; C !== data[R].length; ++C) { if (range.s.r > R) range.s.r = R; if (range.s.c > C) range.s.c = C; if (range.e.r < R) range.e.r = R; if (range.e.c < C) range.e.c = C; var cell = data[R][C]; if (!cell || !cell.v) continue; var cell_ref = XLSX.utils.encode_cell({ c: C, r: R }); if (!cell.t) { if (types.number.assert(cell.v)) cell.t = _TYPE.NUMBER; else if (types.boolean.assert(cell.v)) cell.t = _TYPE.BOOLEAN; else if (types.date.assert(cell.v)) cell.t = _TYPE.DATE; else cell.t = _TYPE.STRING; } if (cell.t === _TYPE.DATE) { cell.t = _TYPE.NUMBER; cell.z = XLSX.SSF._table[14]; cell.v = this.dateNum(cell.v); } ws[cell_ref] = cell; } } ws["!merges"] = merges; if (range.s.c < 10000000) ws["!ref"] = XLSX.utils.encode_range(range); return ws; }
javascript
{ "resource": "" }
q58556
validation
function(event) { var target = event.target; var object = JSON.parse(Storage.getInstance().getItem(target.getAttribute(this.storageKey))), data = object.data, filename = object.filename, mimeType = object.mimeType, fileExtension = object.fileExtension, merges = object.merges, RTL = object.RTL, sheetname = object.sheetname; this.export2file(data, mimeType, filename, fileExtension, merges, RTL, sheetname); }
javascript
{ "resource": "" }
q58557
validation
function(data, mime, name, extension, merges, RTL, sheetname) { var format = extension.slice(1); data = this.getRawData(data, extension, name, merges, RTL, sheetname); if (_isMobile && (format === _FORMAT.CSV || format === _FORMAT.TXT)) { var dataURI = "data:" + mime + ";" + this.charset + "," + data; this.downloadDataURI(dataURI, name, extension); } else { // TODO: error and fallback when `saveAs` not available saveAs(new Blob([data], { type: mime + ";" + this.charset }), name + extension, true); } }
javascript
{ "resource": "" }
q58558
validation
function() { this._instance = null; this.store = sessionStorage; this.namespace = TableExport.prototype.defaultNamespace; this.getKey = function(key) { return this.namespace + key; }; this.setItem = function(_key, value, overwrite) { var key = this.getKey(_key); if (this.exists(_key) && !overwrite) { return; } if (typeof value !== "string") return _handleError('"value" must be a string.'); this.store.setItem(key, value); return _key; }; this.getItem = function(_key) { var key = this.getKey(_key); return this.store.getItem(key); }; this.exists = function(_key) { var key = this.getKey(_key); return this.store.getItem(key) !== null; }; this.removeItem = function(_key) { var key = this.getKey(_key); return this.store.removeItem(key); }; }
javascript
{ "resource": "" }
q58559
getPlatformLibtensorflowUri
validation
function getPlatformLibtensorflowUri() { let targetUri = BASE_URI; if (platform === 'linux') { if (os.arch() === 'arm') { // TODO(kreeger): Update to TensorFlow 1.13: // https://github.com/tensorflow/tfjs/issues/1370 targetUri = 'https://storage.googleapis.com/tf-builds/libtensorflow_r1_12_linux_arm.tar.gz'; } else { if (libType === 'gpu') { targetUri += GPU_LINUX; } else { targetUri += CPU_LINUX; } } } else if (platform === 'darwin') { targetUri += CPU_DARWIN; } else if (platform === 'win32') { // Use windows path path = path.win32; if (libType === 'gpu') { targetUri += GPU_WINDOWS; } else { targetUri += CPU_WINDOWS; } } else { throw new Error(`Unsupported platform: ${platform}`); } return targetUri; }
javascript
{ "resource": "" }
q58560
cleanDeps
validation
async function cleanDeps() { if (await exists(depsPath)) { await rimrafPromise(depsPath); } await mkdir(depsPath); }
javascript
{ "resource": "" }
q58561
downloadLibtensorflow
validation
async function downloadLibtensorflow(callback) { // Ensure dependencies staged directory is available: await ensureDir(depsPath); console.warn('* Downloading libtensorflow'); resources.downloadAndUnpackResource( getPlatformLibtensorflowUri(), depsPath, async () => { if (platform === 'win32') { // Some windows libtensorflow zip files are missing structure and the // eager headers. Check, restructure, and download resources as // needed. const depsIncludePath = path.join(depsPath, 'include'); if (!await exists(depsLibTensorFlowPath)) { // Verify that tensorflow.dll exists const libtensorflowDll = path.join(depsPath, 'tensorflow.dll'); if (!await exists(libtensorflowDll)) { throw new Error('Could not find libtensorflow.dll'); } await ensureDir(depsLibPath); await rename(libtensorflowDll, depsLibTensorFlowPath); } // Next check the structure for the C-library headers. If they don't // exist, download and unzip them. if (!await exists(depsIncludePath)) { // Remove duplicated assets from the original libtensorflow package. // They will be replaced by the download below: await unlink(path.join(depsPath, 'c_api.h')); await unlink(path.join(depsPath, 'LICENSE')); // Download the C headers only and unpack: resources.downloadAndUnpackResource( TF_WIN_HEADERS_URI, depsPath, () => { if (callback !== undefined) { callback(); } }); } else { if (callback !== undefined) { callback(); } } } else { // No other work is required on other platforms. if (callback !== undefined) { callback(); } } }); }
javascript
{ "resource": "" }
q58562
build
validation
async function build() { console.error('* Building TensorFlow Node.js bindings'); cp.exec('node-gyp rebuild', (err) => { if (err) { throw new Error('node-gyp rebuild failed with: ' + err); } }); }
javascript
{ "resource": "" }
q58563
run
validation
async function run() { // First check if deps library exists: if (forceDownload !== 'download' && await exists(depsLibTensorFlowPath)) { // Library has already been downloaded, then compile and simlink: await build(); } else { // Library has not been downloaded, download, then compile and symlink: await cleanDeps(); await downloadLibtensorflow(build); } }
javascript
{ "resource": "" }
q58564
symlinkDepsLib
validation
async function symlinkDepsLib() { if (destLibPath === undefined) { throw new Error('Destination path not supplied!'); } try { await symlink(depsLibTensorFlowPath, destLibPath); if (os.platform() !== 'win32') { await symlink(depsLibTensorFlowFrameworkPath, destFrameworkLibPath); } } catch (e) { console.error( ` * Symlink of ${destLibPath} failed, creating a copy on disk.`); await copy(depsLibTensorFlowPath, destLibPath); if (os.platform() !== 'win32') { await copy(depsLibTensorFlowFrameworkPath, destFrameworkLibPath); } } }
javascript
{ "resource": "" }
q58565
moveDepsLib
validation
async function moveDepsLib() { await rename(depsLibTensorFlowPath, destLibPath); if (os.platform() !== 'win32') { await rename(depsLibTensorFlowFrameworkPath, destFrameworkLibPath); } }
javascript
{ "resource": "" }
q58566
run
validation
async function run(action) { if (action.endsWith('symlink')) { // Symlink will happen during `node-gyp rebuild` await symlinkDepsLib(); } else if (action.endsWith('move')) { // Move action is used when installing this module as a package. await moveDepsLib(); } else { throw new Error('Invalid action: ' + action); } }
javascript
{ "resource": "" }
q58567
downloadAndUnpackResource
validation
async function downloadAndUnpackResource(uri, destPath, callback) { // If HTTPS_PROXY, https_proxy, HTTP_PROXY, or http_proxy is set const proxy = process.env['HTTPS_PROXY'] || process.env['https_proxy'] || process.env['HTTP_PROXY'] || process.env['http_proxy'] || ''; // Using object destructuring to construct the options object for the // http request. the '...url.parse(targetUri)' part fills in the host, // path, protocol, etc from the targetUri and then we set the agent to the // default agent which is overridden a few lines down if there is a proxy const options = {...url.parse(uri), agent: https.globalAgent}; if (proxy !== '') { options.agent = new HttpsProxyAgent(proxy); } const request = https.get(uri, response => { const bar = new ProgressBar('[:bar] :rate/bps :percent :etas', { complete: '=', incomplete: ' ', width: 30, total: parseInt(response.headers['content-length'], 10) }); if (uri.endsWith('.zip')) { // Save zip file to disk, extract, and delete the downloaded zip file. const tempFileName = path.join(__dirname, '_tmp.zip'); const outputFile = fs.createWriteStream(tempFileName); response.on('data', chunk => bar.tick(chunk.length)) .pipe(outputFile) .on('close', async () => { const zipFile = new zip(tempFileName); zipFile.extractAllTo(destPath, true /* overwrite */); await unlink(tempFileName); if (callback !== undefined) { callback(); } }); } else if (uri.endsWith('.tar.gz')) { response.on('data', chunk => bar.tick(chunk.length)) .pipe(tar.x({C: destPath, strict: true})) .on('close', () => { if (callback !== undefined) { callback(); } }); } else { throw new Error(`Unsupported packed resource: ${uri}`); } }); request.end(); }
javascript
{ "resource": "" }
q58568
cssToAST
validation
function cssToAST(text, syntax, filename) { var string = JSON.stringify; var fileInfo = filename ? ' at ' + filename : ''; var tree; try { tree = gonzales.parse(text, {syntax: syntax}); } catch (e) { throw new Error('Parsing error' + fileInfo + ': ' + e.message); } // TODO: When can tree be undefined? <tg> if (typeof tree === 'undefined') { let message = `Undefined tree ${fileInfo}: ${string(text)} => ${string(tree)}`; throw new Error(format(message)); } return tree; }
javascript
{ "resource": "" }
q58569
detectInTree
validation
function detectInTree(tree, handlers) { var detectedOptions = {}; // We walk across complete tree for each handler, // because we need strictly maintain order in which handlers work, // despite fact that handlers work on different level of the tree. handlers.forEach(function(handler) { detectedOptions[handler.name] = handler.detect(tree); }); return detectedOptions; }
javascript
{ "resource": "" }
q58570
getDetectedOptions
validation
function getDetectedOptions(detected, handlers) { var options = {}; Object.keys(detected).forEach(function(option) { // List of all the detected variants from the stylesheet // for the given option: var values = detected[option]; var i; if (!values.length) { // If there are no values for the option, check if there is // a default one: for (i = handlers.length; i--;) { if (handlers[i].name === option && handlers[i].detectDefault !== undefined) { options[option] = handlers[i].detectDefault; break; } } } else if (values.length === 1) { options[option] = values[0]; } else { // If there are more than one value for the option, find // the most popular one; `variants` would be populated // with the popularity for different values. var variants = {}; var bestGuess = null; var maximum = 0; for (i = values.length; i--;) { var currentValue = values[i]; // Count the current value: if (variants[currentValue]) { variants[currentValue]++; } else { variants[currentValue] = 1; } // If the current variant is the most popular one, treat // it as the best guess: if (variants[currentValue] >= maximum) { maximum = variants[currentValue]; bestGuess = currentValue; } } if (bestGuess !== null) { options[option] = bestGuess; } } }); return options; }
javascript
{ "resource": "" }
q58571
getHandler
validation
function getHandler(optionName) { var option = require('./options/' + optionName); if (!option.detect) throw new Error('Option does not have `detect()` method.'); return { name: option.name, detect: option.detect, detectDefault: option.detectDefault }; }
javascript
{ "resource": "" }
q58572
isEmptyBlock
validation
function isEmptyBlock(node) { if (!node.length) return true; return !node.content.some(function(node) { return !node.is('space'); }); }
javascript
{ "resource": "" }
q58573
getPrefixInfo
validation
function getPrefixInfo(propertyName, namespace, extraSymbols) { var baseName = propertyName; var prefixLength = 0; namespace = namespace || ''; extraSymbols = extraSymbols || 0; if (!propertyName) return; PREFIXES.some(function(prefix) { prefix = '-' + prefix + '-'; if (propertyName.indexOf(prefix) !== 0) return; baseName = baseName.substr(prefix.length); prefixLength = prefix.length; return true; }); return { id: namespace + baseName, baseName: baseName, prefixLength: prefixLength, extra: extraSymbols }; }
javascript
{ "resource": "" }
q58574
extraIndent
validation
function extraIndent(nodes) { if (!nodes || !nodes.length) return; var node; var crPos; var tabPos; var result = 0; for (var i = nodes.length; i--;) { node = nodes[i]; if (!node.content) { crPos = -1; } else { crPos = node.content.lastIndexOf('\n'); tabPos = node.content.lastIndexOf('\t'); if (tabPos > crPos) crPos = tabPos; } if (crPos !== -1) oneline = false; if (node.is('space')) { result += node.content.length - crPos - 1; if (crPos !== -1) break; } if (node.is('multilineComment')) { if (crPos === -1) { // Comment symbols length let offset = 4; result += node.content.length + offset; } else { // Only last comment symbols length - 1 (not count \n) let offset = crPos - 1; result += node.content.length - offset; break; } } } return result; }
javascript
{ "resource": "" }
q58575
extraIndentProperty
validation
function extraIndentProperty(nodes, i) { var subset = []; while (i--) { if (!nodes.get(i) || nodes.get(i).is('declarationDelimiter')) break; subset.unshift(nodes.get(i)); } return extraIndent(subset); }
javascript
{ "resource": "" }
q58576
extraIndentVal
validation
function extraIndentVal(nodes, i) { var subset = []; var declaration = nodes.get(i); if (!declaration.is('declaration')) return; for (var x = declaration.length; x--;) { if (!declaration.get(x).is('value')) continue; x--; while (!declaration.get(x).is('propertyDelimiter')) { subset.push(declaration.get(x)); x--; } break; } return extraIndent(subset); }
javascript
{ "resource": "" }
q58577
walk
validation
function walk(args) { args.node.forEach(function(item, i) { var name = args.selector(item); var namespace = args.namespaceSelector && makeNamespace(args.namespaceSelector(item)); var extraSymbols = args.getExtraSymbols(args.node, i); var info = name && getPrefixInfo(name, namespace, extraSymbols); if (!info) return; args.payload(info, i); }); }
javascript
{ "resource": "" }
q58578
updateDict
validation
function updateDict(info, dict) { if (info.prefixLength === 0 && info.extra === 0) return; var indent = dict[info.id] || {prefixLength: 0, extra: 0}; let indentLength = indent.prefixLength + indent.extra; let infoLength = info.prefixLength + info.extra; if (indentLength > infoLength) { dict[info.id] = indent; } else { dict[info.id] = { prefixLength: info.prefixLength, extra: info.extra }; } }
javascript
{ "resource": "" }
q58579
updateIndent
validation
function updateIndent(info, dict, whitespaceNode) { var item = dict[info.id]; if (!item) return whitespaceNode; var crPos = whitespaceNode.lastIndexOf('\n'); var tabPos = whitespaceNode.lastIndexOf('\t'); if (tabPos > crPos) crPos = tabPos; var firstPart = whitespaceNode.substr(0, crPos + 1); var extraIndent = new Array( (item.prefixLength - info.prefixLength) + (item.extra - info.extra) + whitespaceNode.length - firstPart.length + 1).join(' '); return firstPart.concat(extraIndent); }
javascript
{ "resource": "" }
q58580
animate
validation
function animate() { controls.update(); renderer.render(scene, camera); controls1.update(); renderer1.render(scene1, camera1); // request new frame requestAnimationFrame(function() { animate(); }); }
javascript
{ "resource": "" }
q58581
validation
function(vertex, face) { vertex.face = face; if (face.outside === null) { this.assigned.append(vertex); } else { this.assigned.insertBefore(face.outside, vertex); } face.outside = vertex; return this; }
javascript
{ "resource": "" }
q58582
validation
function(vertex, face) { if (vertex === face.outside) { // fix face.outside link if (vertex.next !== null && vertex.next.face === face) { // face has at least 2 outside vertices, move the 'outside' reference face.outside = vertex.next; } else { // vertex was the only outside vertex that face had face.outside = null; } } this.assigned.remove(vertex); return this; }
javascript
{ "resource": "" }
q58583
validation
function(face) { if (face.outside !== null) { // reference to the first and last vertex of this face var start = face.outside; var end = face.outside; while (end.next !== null && end.next.face === face) { end = end.next; } this.assigned.removeSubList(start, end); // fix references start.prev = end.next = null; face.outside = null; return start; } }
javascript
{ "resource": "" }
q58584
validation
function(face, absorbingFace) { var faceVertices = this.removeAllVerticesFromFace(face); if (faceVertices !== undefined) { if (absorbingFace === undefined) { // mark the vertices to be reassigned to some other face this.unassigned.appendChain(faceVertices); } else { // if there's an absorbing face try to assign as many vertices as possible to it var vertex = faceVertices; do { // we need to buffer the subsequent vertex at this point because the 'vertex.next' reference // will be changed by upcoming method calls var nextVertex = vertex.next; var distance = absorbingFace.distanceToPoint(vertex.point); // check if 'vertex' is able to see 'absorbingFace' if (distance > this.tolerance) { this.addVertexToFace(vertex, absorbingFace); } else { this.unassigned.append(vertex); } // now assign next vertex vertex = nextVertex; } while (vertex !== null); } } return this; }
javascript
{ "resource": "" }
q58585
validation
function(newFaces) { if (this.unassigned.isEmpty() === false) { var vertex = this.unassigned.first(); do { // buffer 'next' reference, see .deleteFaceVertices() var nextVertex = vertex.next; var maxDistance = this.tolerance; var maxFace = null; for (var i = 0; i < newFaces.length; i++) { var face = newFaces[i]; if (face.mark === Visible) { var distance = face.distanceToPoint(vertex.point); if (distance > maxDistance) { maxDistance = distance; maxFace = face; } if (maxDistance > 1000 * this.tolerance) break; } } // 'maxFace' can be null e.g. if there are identical vertices if (maxFace !== null) { this.addVertexToFace(vertex, maxFace); } vertex = nextVertex; } while (vertex !== null); } return this; }
javascript
{ "resource": "" }
q58586
validation
function() { var min = new THREE.Vector3(); var max = new THREE.Vector3(); var minVertices = []; var maxVertices = []; var i, l, j; // initially assume that the first vertex is the min/max for (i = 0; i < 3; i++) { minVertices[i] = maxVertices[i] = this.vertices[0]; } min.copy(this.vertices[0].point); max.copy(this.vertices[0].point); // compute the min/max vertex on all six directions for (i = 0, l = this.vertices.length; i < l; i++) { var vertex = this.vertices[i]; var point = vertex.point; // update the min coordinates for (j = 0; j < 3; j++) { if (point.getComponent(j) < min.getComponent(j)) { min.setComponent(j, point.getComponent(j)); minVertices[j] = vertex; } } // update the max coordinates for (j = 0; j < 3; j++) { if (point.getComponent(j) > max.getComponent(j)) { max.setComponent(j, point.getComponent(j)); maxVertices[j] = vertex; } } } // use min/max vectors to compute an optimal epsilon this.tolerance = 3 * Number.EPSILON * (Math.max(Math.abs(min.x), Math.abs(max.x)) + Math.max(Math.abs(min.y), Math.abs(max.y)) + Math.max(Math.abs(min.z), Math.abs(max.z))); return { min: minVertices, max: maxVertices }; }
javascript
{ "resource": "" }
q58587
validation
function() { var activeFaces = []; for (var i = 0; i < this.faces.length; i++) { var face = this.faces[i]; if (face.mark === Visible) { activeFaces.push(face); } } this.faces = activeFaces; return this; }
javascript
{ "resource": "" }
q58588
validation
function() { // if the 'assigned' list of vertices is empty, no vertices are left. return with 'undefined' if (this.assigned.isEmpty() === false) { var eyeVertex, maxDistance = 0; // grap the first available face and start with the first visible vertex of that face var eyeFace = this.assigned.first().face; var vertex = eyeFace.outside; // now calculate the farthest vertex that face can see do { var distance = eyeFace.distanceToPoint(vertex.point); if (distance > maxDistance) { maxDistance = distance; eyeVertex = vertex; } vertex = vertex.next; } while (vertex !== null && vertex.face === eyeFace); return eyeVertex; } }
javascript
{ "resource": "" }
q58589
validation
function(eyePoint, crossEdge, face, horizon) { // moves face's vertices to the 'unassigned' vertex list this.deleteFaceVertices(face); face.mark = Deleted; var edge; if (crossEdge === null) { edge = crossEdge = face.getEdge(0); } else { // start from the next edge since 'crossEdge' was already analyzed // (actually 'crossEdge.twin' was the edge who called this method recursively) edge = crossEdge.next; } do { var twinEdge = edge.twin; var oppositeFace = twinEdge.face; if (oppositeFace.mark === Visible) { if (oppositeFace.distanceToPoint(eyePoint) > this.tolerance) { // the opposite face can see the vertex, so proceed with next edge this.computeHorizon(eyePoint, twinEdge, oppositeFace, horizon); } else { // the opposite face can't see the vertex, so this edge is part of the horizon horizon.push(edge); } } edge = edge.next; } while (edge !== crossEdge); return this; }
javascript
{ "resource": "" }
q58590
validation
function(eyeVertex, horizonEdge) { // all the half edges are created in ccw order thus the face is always pointing outside the hull var face = Face.create(eyeVertex, horizonEdge.tail(), horizonEdge.head()); this.faces.push(face); // join face.getEdge( - 1 ) with the horizon's opposite edge face.getEdge( - 1 ) = face.getEdge( 2 ) face.getEdge(-1).setTwin(horizonEdge.twin); return face.getEdge(0); // the half edge whose vertex is the eyeVertex }
javascript
{ "resource": "" }
q58591
validation
function(eyeVertex) { var horizon = []; this.unassigned.clear(); // remove 'eyeVertex' from 'eyeVertex.face' so that it can't be added to the 'unassigned' vertex list this.removeVertexFromFace(eyeVertex, eyeVertex.face); this.computeHorizon(eyeVertex.point, null, eyeVertex.face, horizon); this.addNewFaces(eyeVertex, horizon); // reassign 'unassigned' vertices to the new faces this.resolveUnassignedPoints(this.newFaces); return this; }
javascript
{ "resource": "" }
q58592
VertexNode
validation
function VertexNode(point) { this.point = point; this.prev = null; this.next = null; this.face = null; // the face that is able to see this vertex }
javascript
{ "resource": "" }
q58593
validation
function(target, vertex) { vertex.prev = target.prev; vertex.next = target; if (vertex.prev === null) { this.head = vertex; } else { vertex.prev.next = vertex; } target.prev = vertex; return this; }
javascript
{ "resource": "" }
q58594
validation
function(target, vertex) { vertex.prev = target; vertex.next = target.next; if (vertex.next === null) { this.tail = vertex; } else { vertex.next.prev = vertex; } target.next = vertex; return this; }
javascript
{ "resource": "" }
q58595
validation
function(vertex) { if (this.head === null) { this.head = vertex; } else { this.tail.next = vertex; } vertex.prev = this.tail; vertex.next = null; // the tail has no subsequent vertex this.tail = vertex; return this; }
javascript
{ "resource": "" }
q58596
validation
function(vertex) { if (vertex.prev === null) { this.head = vertex.next; } else { vertex.prev.next = vertex.next; } if (vertex.next === null) { this.tail = vertex.prev; } else { vertex.next.prev = vertex.prev; } return this; }
javascript
{ "resource": "" }
q58597
validation
function(a, b) { if (a.prev === null) { this.head = b.next; } else { a.prev.next = b.next; } if (b.next === null) { this.tail = a.prev; } else { b.next.prev = a.prev; } return this; }
javascript
{ "resource": "" }
q58598
onWindowResize
validation
function onWindowResize() { camera.aspect = container.offsetWidth / container.offsetHeight; camera.updateProjectionMatrix(); renderer.setSize(container.offsetWidth, container.offsetHeight); }
javascript
{ "resource": "" }
q58599
info
validation
function info(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } }
javascript
{ "resource": "" }