Java Code Examples for java.util.OptionalInt#isEmpty()

The following examples show how to use java.util.OptionalInt#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OrcPageSource.java    From presto with Apache License 2.0 5 votes vote down vote up
static ColumnAdaptation bucketNumberColumn(OptionalInt bucketNumber)
{
    if (bucketNumber.isEmpty()) {
        return nullColumn(INTEGER);
    }
    return new BucketNumberColumn(bucketNumber.getAsInt());
}
 
Example 2
Source File: HiveMetadata.java    From presto with Apache License 2.0 5 votes vote down vote up
private static OptionalInt min(OptionalInt left, OptionalInt right)
{
    if (left.isEmpty()) {
        return right;
    }
    if (right.isEmpty()) {
        return left;
    }
    return OptionalInt.of(Math.min(left.getAsInt(), right.getAsInt()));
}
 
Example 3
Source File: SearchCluster.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate whether a subset of nodes in a group has enough coverage
 */
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
    if (orderedGroups().size() == 1) {
        boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
        return sufficient;
    }

    if (knownGroupId.isEmpty()) {
        return false;
    }
    int groupId = knownGroupId.getAsInt();
    Group group = groups().get(groupId);
    if (group == null) {
        return false;
    }
    int nodesInGroup = group.nodes().size();
    long sumOfActiveDocuments = 0;
    int otherGroups = 0;
    for (Group g : orderedGroups()) {
        if (g.id() != groupId) {
            sumOfActiveDocuments += g.getActiveDocuments();
            otherGroups++;
        }
    }
    long activeDocuments = 0;
    for (Node n : nodes) {
        activeDocuments += n.getActiveDocuments();
    }
    long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
    return isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
}
 
Example 4
Source File: GameTabSet.java    From luna with MIT License 5 votes vote down vote up
/**
 * Sets the tab interface at {@code index}.
 *
 * @param index The tab to set the interface at.
 * @param id The identifier of the interface to set.
 * @return {@code true} if the interface was set.
 */
public boolean set(TabIndex index, int id) {
    OptionalInt currentId = get(index);
    if (currentId.isEmpty() || currentId.getAsInt() != id) {
        player.queue(new TabInterfaceMessageWriter(index, id));
        tabs.put(index, id);
        return true;
    }
    return false;
}
 
Example 5
Source File: RaptorMetadata.java    From presto with Apache License 2.0 4 votes vote down vote up
private Optional<DistributionInfo> getOrCreateDistribution(Map<String, RaptorColumnHandle> columnHandleMap, Map<String, Object> properties)
{
    OptionalInt bucketCount = getBucketCount(properties);
    List<RaptorColumnHandle> bucketColumnHandles = getBucketColumnHandles(getBucketColumns(properties), columnHandleMap);

    if (bucketCount.isPresent() && bucketColumnHandles.isEmpty()) {
        throw new PrestoException(INVALID_TABLE_PROPERTY, format("Must specify '%s' along with '%s'", BUCKETED_ON_PROPERTY, BUCKET_COUNT_PROPERTY));
    }
    if (bucketCount.isEmpty() && !bucketColumnHandles.isEmpty()) {
        throw new PrestoException(INVALID_TABLE_PROPERTY, format("Must specify '%s' along with '%s'", BUCKET_COUNT_PROPERTY, BUCKETED_ON_PROPERTY));
    }
    ImmutableList.Builder<Type> bucketColumnTypes = ImmutableList.builder();
    for (RaptorColumnHandle column : bucketColumnHandles) {
        validateBucketType(column.getColumnType());
        bucketColumnTypes.add(column.getColumnType());
    }

    long distributionId;
    String distributionName = getDistributionName(properties);
    if (distributionName != null) {
        if (bucketColumnHandles.isEmpty()) {
            throw new PrestoException(INVALID_TABLE_PROPERTY, format("Must specify '%s' along with '%s'", BUCKETED_ON_PROPERTY, DISTRIBUTION_NAME_PROPERTY));
        }

        Distribution distribution = dao.getDistribution(distributionName);
        if (distribution == null) {
            if (bucketCount.isEmpty()) {
                throw new PrestoException(INVALID_TABLE_PROPERTY, "Distribution does not exist and bucket count is not specified");
            }
            distribution = getOrCreateDistribution(distributionName, bucketColumnTypes.build(), bucketCount.getAsInt());
        }
        distributionId = distribution.getId();

        if (bucketCount.isPresent() && (distribution.getBucketCount() != bucketCount.getAsInt())) {
            throw new PrestoException(INVALID_TABLE_PROPERTY, "Bucket count must match distribution");
        }
        if (!distribution.getColumnTypes().equals(bucketColumnTypes.build())) {
            throw new PrestoException(INVALID_TABLE_PROPERTY, "Bucket column types must match distribution");
        }
    }
    else if (bucketCount.isPresent()) {
        String types = Distribution.serializeColumnTypes(bucketColumnTypes.build());
        distributionId = dao.insertDistribution(null, types, bucketCount.getAsInt());
    }
    else {
        return Optional.empty();
    }

    shardManager.createBuckets(distributionId, bucketCount.getAsInt());

    return Optional.of(new DistributionInfo(distributionId, bucketCount.getAsInt(), bucketColumnHandles));
}
 
Example 6
Source File: BeaconStateUtil.java    From teku with Apache License 2.0 4 votes vote down vote up
static void process_deposit_without_checking_merkle_proof(
    final MutableBeaconState state,
    final Deposit deposit,
    final Map<BLSPublicKey, Integer> pubKeyToIndexMap) {
  state.setEth1_deposit_index(state.getEth1_deposit_index().plus(UnsignedLong.ONE));

  final BLSPublicKey pubkey = deposit.getData().getPubkey();
  final UnsignedLong amount = deposit.getData().getAmount();

  OptionalInt existingIndex;
  if (pubKeyToIndexMap != null) {
    Integer cachedIndex = pubKeyToIndexMap.putIfAbsent(pubkey, state.getValidators().size());
    existingIndex = cachedIndex == null ? OptionalInt.empty() : OptionalInt.of(cachedIndex);
  } else {
    SSZList<Validator> validators = state.getValidators();

    Cache<UnsignedLong, BLSPublicKey> publicKeyCache =
        BeaconStateCache.getTransitionCaches(state).getValidatorsPubKeys();
    Function<Integer, BLSPublicKey> validatorPubkey =
        index ->
            publicKeyCache.get(
                UnsignedLong.valueOf(index), i -> validators.get(index).getPubkey());
    existingIndex =
        IntStream.range(0, validators.size())
            .filter(index -> pubkey.equals(validatorPubkey.apply(index)))
            .findFirst();
  }

  if (existingIndex.isEmpty()) {

    // Verify the deposit signature (proof of possession) which is not checked by the deposit
    // contract
    if (BLS_VERIFY_DEPOSIT) {
      final DepositMessage deposit_message =
          new DepositMessage(pubkey, deposit.getData().getWithdrawal_credentials(), amount);
      final Bytes domain = compute_domain(DOMAIN_DEPOSIT);
      final Bytes signing_root = compute_signing_root(deposit_message, domain);
      boolean proof_is_valid =
          !BLS_VERIFY_DEPOSIT
              || BLS.verify(pubkey, signing_root, deposit.getData().getSignature());
      if (!proof_is_valid) {
        if (deposit instanceof DepositWithIndex) {
          LOG.debug(
              "Skipping invalid deposit with index {} and pubkey {}",
              ((DepositWithIndex) deposit).getIndex(),
              pubkey);
        } else {
          LOG.debug("Skipping invalid deposit with pubkey {}", pubkey);
        }
        if (pubKeyToIndexMap != null) {
          // The validator won't be created so the calculated index won't be correct
          pubKeyToIndexMap.remove(pubkey);
        }
        return;
      }
    }

    if (pubKeyToIndexMap == null) {
      LOG.debug("Adding new validator to state: {}", state.getValidators().size());
    }
    state
        .getValidators()
        .add(
            Validator.create(
                pubkey,
                deposit.getData().getWithdrawal_credentials(),
                min(
                    amount.minus(amount.mod(Constants.EFFECTIVE_BALANCE_INCREMENT)),
                    UnsignedLong.valueOf(MAX_EFFECTIVE_BALANCE)),
                false,
                FAR_FUTURE_EPOCH,
                FAR_FUTURE_EPOCH,
                FAR_FUTURE_EPOCH,
                FAR_FUTURE_EPOCH));
    state.getBalances().add(amount);
  } else {
    increase_balance(state, existingIndex.getAsInt(), amount);
  }
}