当前位置: 首页>>代码示例>>Java>>正文


Java Preconditions类代码示例

本文整理汇总了Java中com.google.common.base.Preconditions的典型用法代码示例。如果您正苦于以下问题:Java Preconditions类的具体用法?Java Preconditions怎么用?Java Preconditions使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Preconditions类属于com.google.common.base包,在下文中一共展示了Preconditions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: initialize

import com.google.common.base.Preconditions; //导入依赖的package包/类
private void initialize() {
    Preconditions.checkState(points.size() > kVal,
            "k-value is greater than or equal to number of points (%d >= %d).", kVal, points.size());
    Stopwatch sw = Stopwatch.createStarted();
    List<KmeansPoint<T>> pool = new ArrayList<>(points);
    KmeansPoint<T> sample = VectorMathUtils.sampleUniform(pool, random);
    pool.remove(sample);

    KmeansCentroid point = KmeansCentroid.centroid(sample, 0);
    centroids = Lists.newArrayList(point);
    for (int i = 1; i < kVal; ++i) {
        if (kMeansPlusPlus) {
            KmeansCentroid current = point;
            pool.parallelStream().forEach(p -> distanceToCentroid(p, current));
            sample = samplePoint(i - 1);
        } else {
            sample = VectorMathUtils.sampleUniform(pool, random);
        }
        pool.remove(sample);

        point = KmeansCentroid.centroid(sample, i);
        centroids.add(point);
    }
    log.info("Initialized centroids in {}.", sw);
}
 
开发者ID:clearwsd,项目名称:clearwsd,代码行数:26,代码来源:KMeans.java

示例2: handleConfirmation

import com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public FinalizationCodePart handleConfirmation(Integer voterIndex, Confirmation confirmation)
        throws IncorrectConfirmationRuntimeException {
    Preconditions.checkState(publicCredentials != null,
            "The public credentials need to have been retrieved first");
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<BigInteger> publicConfirmationCredentials =
            publicCredentials.stream().map(p -> p.y).collect(Collectors.toList());

    if (!voteConfirmationAuthorityAlgorithms.checkConfirmation(voterIndex, confirmation,
            publicConfirmationCredentials, ballotEntries, confirmationEntries)) {
        throw new IncorrectConfirmationRuntimeException("Confirmation for voter " + voterIndex + " was deemed invalid");
    }
    stopwatch.stop();
    confirmationVerificationTimes.add(stopwatch.elapsed(TimeUnit.MILLISECONDS));

    confirmationEntries.add(new ConfirmationEntry(voterIndex, confirmation));

    stopwatch.reset().start();
    FinalizationCodePart finalization = voteConfirmationAuthorityAlgorithms.getFinalization(voterIndex, electorateData.getP(), ballotEntries);
    stopwatch.stop();
    finalizationComputationTimes.add(stopwatch.elapsed(TimeUnit.MILLISECONDS));

    return finalization;
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:26,代码来源:DefaultAuthority.java

示例3: toString

import com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Algorithm 4.6: ToString
 *
 * @param x       the integer to convert
 * @param k       the required String size
 * @param upper_a the alphabet to be used
 * @return a string of length k, using alphabet A, and representing x
 */
public String toString(BigInteger x, int k, List<Character> upper_a) {
    Preconditions.checkArgument(x.signum() >= 0, "x should be a non-negative integer");
    int alphabetSize = upper_a.size();
    BigInteger N = BigInteger.valueOf(alphabetSize);
    Preconditions.checkArgument(N.pow(k).compareTo(x) >= 0,
            "x is too large to be encoded with k characters of alphabet upper_a");

    StringBuilder sb = new StringBuilder(k);
    BigInteger current = x;
    for (int i = 1; i <= k; i++) {
        BigInteger[] divideAndRemainder = current.divideAndRemainder(N);
        current = divideAndRemainder[0];
        // always insert before the previous character
        sb.insert(0, upper_a.get(divideAndRemainder[1].intValue()));
    }

    return sb.toString();
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:27,代码来源:Conversion.java

示例4: getMiddleName

import com.google.common.base.Preconditions; //导入依赖的package包/类
public static String getMiddleName( Row row ) {
    String name = row.getAs( "Defendant Name" );
    if ( name == null ) { return null; }
    name = name.replace( " Jr", "" );
    name = name.replace( " JR", "" );
    name = name.replace( " Sr", "" );
    name = name.replace( " SR", "" );

    List<String> names = nameSplitter.splitToList( name );
    Preconditions.checkState( names.size() > 0, "Must have at least some parts of name" );
    StringBuilder sb = new StringBuilder();
    for ( int i = 2; i < names.size(); ++i ) {
        sb.append( names.get( i ) ).append( " " );
    }

    return sb.toString().trim();
}
 
开发者ID:dataloom,项目名称:integrations,代码行数:18,代码来源:CaseChargesWithDispo2010.java

示例5: getStrategyForPrefix

import com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public ShardStrategy getStrategyForPrefix(@Nonnull final DOMDataTreeIdentifier prefix) {
    Preconditions.checkNotNull(prefix, "Prefix cannot be null");
    // FIXME using prefix tables like in mdsal will be better
    Entry<DOMDataTreeIdentifier, PrefixShardConfiguration> bestMatchEntry =
            new SimpleEntry<>(
                    new DOMDataTreeIdentifier(prefix.getDatastoreType(), YangInstanceIdentifier.EMPTY), null);

    for (Entry<DOMDataTreeIdentifier, PrefixShardConfiguration> entry : prefixConfigMap.entrySet()) {
        if (entry.getKey().contains(prefix) && entry.getKey().getRootIdentifier().getPathArguments().size()
                > bestMatchEntry.getKey().getRootIdentifier().getPathArguments().size()) {
            bestMatchEntry = entry;
        }
    }

    if (bestMatchEntry.getValue() == null) {
        return null;
    }
    return new PrefixShardStrategy(ClusterUtils
            .getCleanShardName(bestMatchEntry.getKey().getRootIdentifier()),
            bestMatchEntry.getKey().getRootIdentifier());
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:23,代码来源:ConfigurationImpl.java

示例6: buildPath

import com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * 从后到前。根据权重获取最优路径
 *
 * @param wordnet
 * @return
 */
private Wordpath buildPath(Wordnet wordnet) {
    //从后到前,获得完整的路径
    Wordpath wordPath = new Wordpath(wordnet, this);

    Vertex last = null;

    Vertex point = wordnet.getEndRow().first();

    while (point != null) {
        last = point;
        wordPath.combine(point);
        point = point.from;
    }

    // 最后一个point必定指向start节点
    Preconditions.checkState(last == wordnet.getBeginRow().first(), "非完整路径");

    return wordPath;
}
 
开发者ID:mayabot,项目名称:mynlp,代码行数:26,代码来源:ViterbiBestPathComputer.java

示例7: getReceiverParallelizationInfo

import com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public ParallelizationInfo getReceiverParallelizationInfo(List<DrillbitEndpoint> senderFragmentEndpoints) {
  Preconditions.checkArgument(senderFragmentEndpoints != null && senderFragmentEndpoints.size() > 0,
      "Sender fragment endpoint list should not be empty");

  // We want to run one mux receiver per Drillbit endpoint.
  // Identify the number of unique Drillbit endpoints in sender fragment endpoints.
  List<DrillbitEndpoint> drillbitEndpoints = ImmutableSet.copyOf(senderFragmentEndpoints).asList();

  List<EndpointAffinity> affinities = Lists.newArrayList();
  for(DrillbitEndpoint ep : drillbitEndpoints) {
    affinities.add(new EndpointAffinity(ep, Double.POSITIVE_INFINITY));
  }

  return ParallelizationInfo.create(affinities.size(), affinities.size(), affinities);
}
 
开发者ID:skhalifa,项目名称:QDrill,代码行数:17,代码来源:AbstractMuxExchange.java

示例8: resizeCluster

import com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public ClusterEnriched resizeCluster(ClusterId clusterId, int newContainersCount) throws ProvisioningHandlingException {
  // get info about cluster
  // children should do the rest
  Preconditions.checkNotNull(clusterId, "id is required");
  final Cluster cluster = store.get(clusterId);
  if (cluster == null) {
    throw new ProvisioningHandlingException("Cluster " + clusterId + " is not found. Nothing to resize");
  }

  cluster.getClusterConfig().getClusterSpec().setContainerCount(newContainersCount);
  final ProvisioningServiceDelegate service = concreteServices.get(cluster.getClusterConfig().getClusterType());
  if (service == null) {
    throw new ProvisioningHandlingException("Can not find service implementation for: " + cluster.getClusterConfig().getClusterType());
  }

  if (newContainersCount <= 0) {
    logger.info("Since number of requested containers to resize == 0. Stopping cluster");
    service.stopCluster(cluster);
  } else {
    service.resizeCluster(cluster);
  }
  store.put(clusterId, cluster);
  return service.getClusterInfo(cluster);
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:26,代码来源:ProvisioningServiceImpl.java

示例9: release

import com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Recycle the given byte array.
 * 
 * The byte array may or may not be allocated
 * by the {@link Impl#newByteArray(int)} method.
 * 
 * This is a non-blocking call.
 */
@Override
public int release(final byte[] array) {
  Preconditions.checkNotNull(array);
  if (LOG.isDebugEnabled()) {
    debugMessage.get().append("recycle: array.length=").append(array.length);
  }
  
  final int freeQueueSize;
  if (array.length == 0) {
    freeQueueSize = -1;
  } else {
    final FixedLengthManager manager = managers.get(array.length, false);
    freeQueueSize = manager == null? -1: manager.recycle(array);
  }
  
  if (LOG.isDebugEnabled()) {
    debugMessage.get().append(", freeQueueSize=").append(freeQueueSize);
    logDebugMessage();
  }
  return freeQueueSize;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:30,代码来源:ByteArrayManager.java

示例10: decrypt

import com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Do the decryption using inBuffer as input and outBuffer as output.
 * Upon return, inBuffer is cleared; the decrypted data starts at 
 * outBuffer.position() and ends at outBuffer.limit();
 */
private void decrypt(Decryptor decryptor, ByteBuffer inBuffer, 
    ByteBuffer outBuffer, byte padding) throws IOException {
  Preconditions.checkState(inBuffer.position() >= padding);
  if(inBuffer.position() == padding) {
    // There is no real data in inBuffer.
    return;
  }
  inBuffer.flip();
  outBuffer.clear();
  decryptor.decrypt(inBuffer, outBuffer);
  inBuffer.clear();
  outBuffer.flip();
  if (padding > 0) {
    /*
     * The plain text and cipher text have a 1:1 mapping, they start at the 
     * same position.
     */
    outBuffer.position(padding);
  }
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:26,代码来源:CryptoInputStream.java

示例11: transferTo

import com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * This code is more complicated than you would think because we might require multiple
 * transferTo invocations in order to transfer a single MessageWithHeader to avoid busy waiting.
 *
 * The contract is that the caller will ensure position is properly set to the total number
 * of bytes transferred so far (i.e. value returned by transfered()).
 */
@Override
public long transferTo(final WritableByteChannel target, final long position) throws IOException {
  Preconditions.checkArgument(position == totalBytesTransferred, "Invalid position.");
  // Bytes written for header in this call.
  long writtenHeader = 0;
  if (header.readableBytes() > 0) {
    writtenHeader = copyByteBuf(header, target);
    totalBytesTransferred += writtenHeader;
    if (header.readableBytes() > 0) {
      return writtenHeader;
    }
  }

  // Bytes written for body in this call.
  long writtenBody = 0;
  if (body instanceof FileRegion) {
    writtenBody = ((FileRegion) body).transferTo(target, totalBytesTransferred - headerLength);
  } else if (body instanceof ByteBuf) {
    writtenBody = copyByteBuf((ByteBuf) body, target);
  }
  totalBytesTransferred += writtenBody;

  return writtenHeader + writtenBody;
}
 
开发者ID:spafka,项目名称:spark_deep,代码行数:32,代码来源:MessageWithHeader.java

示例12: assertSender

import com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public FunctionalCommandBuilder<T> assertSender(Predicate<T> test, String failureMessage) {
    Preconditions.checkNotNull(test, "test");
    Preconditions.checkNotNull(failureMessage, "failureMessage");
    predicates.add(context -> {
        //noinspection unchecked
        T sender = (T) context.sender();
        if (test.test(sender)) {
            return true;
        }

        context.reply(failureMessage);
        return false;
    });
    return this;
}
 
开发者ID:lucko,项目名称:helper,代码行数:17,代码来源:FunctionalCommandBuilderImpl.java

示例13: call

import com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public Void call() {
	Preconditions.checkNotNull(input);
	Preconditions.checkNotNull(output);
	
	Commandline cmd = cmd();
	cmd.addArgs("receive-pack", "--stateless-rpc", ".");
	
	cmd.execute(output, new LineConsumer() {

		@Override
		public void consume(String line) {
			logger.error(line);
		}
		
	}, input).checkReturnCode();
	
	return null;
}
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:20,代码来源:ReceiveCommand.java

示例14: registerDebuff

import com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public void registerDebuff(@Nonnull EnumDebuffSlot slot, @Nonnull IDebuffBuilder abstractBuilder) {
    DebuffBuilder builder;
    try {
        builder = (DebuffBuilder) abstractBuilder;
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("Builder must an instance of the default builder received via DebuffBuilderFactory!", e);
    }
    //Build the finished debuff
    FirstAid.logger.debug("Building debuff from mod {} for slot {} with potion effect {}, type = {}", CommonUtils.getActiveModidSafe(), slot, builder.potionName, builder.isOnHit ? "OnHit" : "Constant");
    BooleanSupplier isEnabled = builder.isEnabledSupplier;
    if (isEnabled == null)
        isEnabled = () -> true;

    Preconditions.checkArgument(!builder.map.isEmpty(), "Failed to register debuff with condition has set");
    IDebuff debuff;
    if (builder.isOnHit) {
        debuff = new OnHitDebuff(builder.potionName, builder.map, isEnabled, builder.sound);
    } else {
        Preconditions.checkArgument(builder.sound == null, "Tried to register constant debuff with sound effect.");
        debuff = new ConstantDebuff(builder.potionName, builder.map, isEnabled);
    }
    registerDebuff(slot, debuff);
}
 
开发者ID:ichttt,项目名称:FirstAid,代码行数:25,代码来源:FirstAidRegistryImpl.java

示例15: fill

import com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public void fill(long fromIndex, long toIndex, long value) {
    Preconditions.checkArgument(fromIndex <= toIndex);
    if (fromIndex == toIndex) {
        return; // empty range
    }
    final int fromPage = pageIndex(fromIndex);
    final int toPage = pageIndex(toIndex - 1);
    if (fromPage == toPage) {
        Arrays.fill(pages[fromPage], indexInPage(fromIndex), indexInPage(toIndex - 1) + 1, value);
    } else {
        Arrays.fill(pages[fromPage], indexInPage(fromIndex), pages[fromPage].length, value);
        for (int i = fromPage + 1; i < toPage; ++i) {
            Arrays.fill(pages[i], value);
        }
        Arrays.fill(pages[toPage], 0, indexInPage(toIndex - 1) + 1, value);
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:19,代码来源:BigLongArray.java


注:本文中的com.google.common.base.Preconditions类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。