类com.google.common.primitives.Shorts源码实例Demo

下面列出了怎么用com.google.common.primitives.Shorts的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: plugins   文件: BankTagsPlugin.java
@Subscribe
public void onGrandExchangeSearched(GrandExchangeSearched event)
{
	final String input = client.getVar(VarClientStr.INPUT_TEXT);
	if (!input.startsWith(TAG_SEARCH))
	{
		return;
	}

	event.consume();

	final String tag = input.substring(TAG_SEARCH.length()).trim();
	final Set<Integer> ids = tagManager.getItemsForTag(tag)
		.stream()
		.mapToInt(Math::abs)
		.mapToObj(ItemVariationMapping::getVariations)
		.flatMap(Collection::stream)
		.distinct()
		.filter(i -> itemManager.getItemDefinition(i).isTradeable())
		.limit(MAX_RESULT_COUNT)
		.collect(Collectors.toCollection(TreeSet::new));

	client.setGeSearchResultIndex(0);
	client.setGeSearchResultCount(ids.size());
	client.setGeSearchResultIds(Shorts.toArray(ids));
}
 
源代码2 项目: presto   文件: JsonUtil.java
public static Long currentTokenAsSmallint(JsonParser parser)
        throws IOException
{
    switch (parser.currentToken()) {
        case VALUE_NULL:
            return null;
        case VALUE_STRING:
        case FIELD_NAME:
            return VarcharOperators.castToSmallint(Slices.utf8Slice(parser.getText()));
        case VALUE_NUMBER_FLOAT:
            return DoubleOperators.castToSmallint(parser.getDoubleValue());
        case VALUE_NUMBER_INT:
            return (long) Shorts.checkedCast(parser.getLongValue());
        case VALUE_TRUE:
            return BooleanOperators.castToSmallint(true);
        case VALUE_FALSE:
            return BooleanOperators.castToSmallint(false);
        default:
            throw new JsonCastException(format("Unexpected token when cast to %s: %s", StandardTypes.SMALLINT, parser.getText()));
    }
}
 
源代码3 项目: presto   文件: DecimalCasts.java
@UsedByGeneratedCode
public static long shortDecimalToSmallint(long decimal, long precision, long scale, long tenToScale)
{
    // this rounds the decimal value to the nearest integral value
    long longResult = (decimal + tenToScale / 2) / tenToScale;
    if (decimal < 0) {
        longResult = -((-decimal + tenToScale / 2) / tenToScale);
    }

    try {
        return Shorts.checkedCast(longResult);
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to SMALLINT", longResult));
    }
}
 
源代码4 项目: presto   文件: MetastoreHiveStatisticsProvider.java
private static long normalizeIntegerValue(Type type, long value)
{
    if (type.equals(BIGINT)) {
        return value;
    }
    if (type.equals(INTEGER)) {
        return Ints.saturatedCast(value);
    }
    if (type.equals(SMALLINT)) {
        return Shorts.saturatedCast(value);
    }
    if (type.equals(TINYINT)) {
        return SignedBytes.saturatedCast(value);
    }
    throw new IllegalArgumentException("Unexpected type: " + type);
}
 
源代码5 项目: kylin-on-parquet-v2   文件: MemcachedCache.java
protected byte[] encodeValue(byte[] key, byte[] valueB) {
    byte[] compressed = null;
    if (config.isEnableCompression() && (valueB.length + Ints.BYTES + key.length > compressThreshold)) {
        try {
            compressed = CompressionUtils.compress(ByteBuffer.allocate(Ints.BYTES + key.length + valueB.length)
                    .putInt(key.length).put(key).put(valueB).array());
        } catch (IOException e) {
            compressed = null;
            logger.warn("Compressing value bytes error.", e);
        }
    }
    if (compressed != null) {
        return ByteBuffer.allocate(Shorts.BYTES + compressed.length).putShort((short) 1).put(compressed).array();
    } else {
        return ByteBuffer.allocate(Shorts.BYTES + Ints.BYTES + key.length + valueB.length).putShort((short) 0)
                .putInt(key.length).put(key).put(valueB).array();
    }
}
 
源代码6 项目: ArchUnit   文件: JavaClassProcessor.java
@SuppressWarnings({"unchecked", "rawtypes"}) // NOTE: We assume the component type matches the list
private Object toArray(Class<?> componentType, List<Object> values) {
    if (componentType == boolean.class) {
        return Booleans.toArray((Collection) values);
    } else if (componentType == byte.class) {
        return Bytes.toArray((Collection) values);
    } else if (componentType == short.class) {
        return Shorts.toArray((Collection) values);
    } else if (componentType == int.class) {
        return Ints.toArray((Collection) values);
    } else if (componentType == long.class) {
        return Longs.toArray((Collection) values);
    } else if (componentType == float.class) {
        return Floats.toArray((Collection) values);
    } else if (componentType == double.class) {
        return Doubles.toArray((Collection) values);
    } else if (componentType == char.class) {
        return Chars.toArray((Collection) values);
    }
    return values.toArray((Object[]) Array.newInstance(componentType, values.size()));
}
 
源代码7 项目: hadoop   文件: PBHelper.java
public static CacheDirectiveInfo convert
    (CacheDirectiveInfoProto proto) {
  CacheDirectiveInfo.Builder builder =
      new CacheDirectiveInfo.Builder();
  if (proto.hasId()) {
    builder.setId(proto.getId());
  }
  if (proto.hasPath()) {
    builder.setPath(new Path(proto.getPath()));
  }
  if (proto.hasReplication()) {
    builder.setReplication(Shorts.checkedCast(
        proto.getReplication()));
  }
  if (proto.hasPool()) {
    builder.setPool(proto.getPool());
  }
  if (proto.hasExpiration()) {
    builder.setExpiration(convert(proto.getExpiration()));
  }
  return builder.build();
}
 
源代码8 项目: science-journal   文件: ShadowAudioRecord.java
@Implementation
protected int read(short[] audioData, int offsetInShorts, int sizeInShorts) {
  synchronized (audioDataLock) {
    if (ShadowAudioRecord.audioData.size() > 0) {
      System.arraycopy(
          Shorts.toArray(
              ShadowAudioRecord.audioData.subList(
                  0,
                  sizeInShorts > ShadowAudioRecord.audioData.size()
                      ? ShadowAudioRecord.audioData.size()
                      : sizeInShorts)),
          0,
          audioData,
          offsetInShorts,
          sizeInShorts);
      if (ShadowAudioRecord.audioData.size() > 10) {
        ShadowAudioRecord.audioData =
            ShadowAudioRecord.audioData.subList(sizeInShorts, ShadowAudioRecord.audioData.size());
      } else {
        ShadowAudioRecord.audioData.clear();
      }
      return sizeInShorts;
    }
    return 0;
  }
}
 
源代码9 项目: big-c   文件: PBHelper.java
public static CacheDirectiveInfo convert
    (CacheDirectiveInfoProto proto) {
  CacheDirectiveInfo.Builder builder =
      new CacheDirectiveInfo.Builder();
  if (proto.hasId()) {
    builder.setId(proto.getId());
  }
  if (proto.hasPath()) {
    builder.setPath(new Path(proto.getPath()));
  }
  if (proto.hasReplication()) {
    builder.setReplication(Shorts.checkedCast(
        proto.getReplication()));
  }
  if (proto.hasPool()) {
    builder.setPool(proto.getPool());
  }
  if (proto.hasExpiration()) {
    builder.setExpiration(convert(proto.getExpiration()));
  }
  return builder.build();
}
 
源代码10 项目: runelite   文件: BankTagsPlugin.java
@Subscribe
public void onGrandExchangeSearched(GrandExchangeSearched event)
{
	final String input = client.getVar(VarClientStr.INPUT_TEXT);
	if (!input.startsWith(TAG_SEARCH))
	{
		return;
	}

	event.consume();

	final String tag = input.substring(TAG_SEARCH.length()).trim();
	final Set<Integer> ids = tagManager.getItemsForTag(tag)
		.stream()
		.mapToInt(Math::abs)
		.mapToObj(ItemVariationMapping::getVariations)
		.flatMap(Collection::stream)
		.distinct()
		.filter(i -> itemManager.getItemComposition(i).isTradeable())
		.limit(MAX_RESULT_COUNT)
		.collect(Collectors.toCollection(TreeSet::new));

	client.setGeSearchResultIndex(0);
	client.setGeSearchResultCount(ids.size());
	client.setGeSearchResultIds(Shorts.toArray(ids));
}
 
源代码11 项目: spotbugs   文件: Ideas_2011_08_01.java
@ExpectWarning(value="RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE", num = 9)
public static int testGuavaPrimitiveCompareCalls() {
    int count = 0;
    if (Booleans.compare(false, true) == -1)
        count++;
    if (Chars.compare('a', 'b') == -1)
        count++;
    if (Doubles.compare(1, 2) == -1)
        count++;
    if (Floats.compare(1, 2) == -1)
        count++;
    if (Ints.compare(1, 2) == -1)
        count++;
    if (Longs.compare(1, 2) == -1)
        count++;
    if (Shorts.compare((short) 1, (short) 2) == -1)
        count++;
    if (SignedBytes.compare((byte) 1, (byte) 2) == -1)
        count++;
    if (UnsignedBytes.compare((byte) 1, (byte) 2) == -1)
        count++;
    return count;

}
 
源代码12 项目: bither-android   文件: AmplitudeData.java
public AmplitudeData(byte[] rawData) {
    if (rawData == null) {
        amplitude = 0;
        return;
    }

    int step = rawData.length / Shorts.BYTES / sampleCount;

    int count = 0;
    double sum = 0;
    for (int i = 0;
         i < rawData.length - Shorts.BYTES;
         i += step) {
        byte[] bytes = new byte[Shorts.BYTES];
        for (int j = 0;
             j < Shorts.BYTES;
             j++) {
            bytes[j] = rawData[i + j];
        }
        short s = Shorts.fromByteArray(bytes);
        sum += s * s;
        count++;
    }
    amplitude = (int) Math.sqrt(sum / count);
}
 
源代码13 项目: presto   文件: DecimalCasts.java
@UsedByGeneratedCode
public static long longDecimalToSmallint(Slice decimal, long precision, long scale, BigInteger tenToScale)
{
    try {
        return Shorts.checkedCast(unscaledDecimalToUnscaledLong(rescale(decimal, DecimalConversions.intScale(-scale))));
    }
    catch (ArithmeticException | IllegalArgumentException e) {
        throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to SMALLINT", Decimals.toString(decimal, DecimalConversions.intScale(scale))));
    }
}
 
源代码14 项目: presto   文件: SetDigest.java
public void mergeWith(SetDigest other)
{
    hll.mergeWith(other.hll);
    LongBidirectionalIterator iterator = other.minhash.keySet().iterator();
    while (iterator.hasNext()) {
        long key = iterator.nextLong();
        int count = minhash.get(key) + other.minhash.get(key);
        minhash.put(key, Shorts.saturatedCast(count));
    }
    while (minhash.size() > maxHashes) {
        minhash.remove(minhash.lastLongKey());
    }
}
 
源代码15 项目: presto   文件: BigintOperators.java
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.BIGINT) long value)
{
    try {
        return Shorts.checkedCast(value);
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + value, e);
    }
}
 
源代码16 项目: dhcp4j   文件: Dhcp6MessageEncoder.java
public void encode(final @Nonnull ByteBuffer byteBuffer, @Nonnull final Dhcp6Option option) {
    short tag = option.getTag();
    byte[] data = option.getData();
    byteBuffer.putShort(tag);
    byteBuffer.putShort(Shorts.checkedCast(data.length));
    byteBuffer.put(data);
}
 
源代码17 项目: presto   文件: SmallintOperators.java
@ScalarOperator(MULTIPLY)
@SqlType(StandardTypes.SMALLINT)
public static long multiply(@SqlType(StandardTypes.SMALLINT) long left, @SqlType(StandardTypes.SMALLINT) long right)
{
    try {
        return Shorts.checkedCast(left * right);
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, format("smallint multiplication overflow: %s * %s", left, right), e);
    }
}
 
源代码18 项目: presto   文件: SmallintOperators.java
@ScalarOperator(NEGATION)
@SqlType(StandardTypes.SMALLINT)
public static long negate(@SqlType(StandardTypes.SMALLINT) long value)
{
    try {
        return Shorts.checkedCast(-value);
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "smallint negation overflow: " + value, e);
    }
}
 
源代码19 项目: presto   文件: RealOperators.java
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.REAL) long value)
{
    float floatValue = intBitsToFloat((int) value);
    if (Float.isNaN(floatValue)) {
        throw new PrestoException(INVALID_CAST_ARGUMENT, "Cannot cast real NaN to smallint");
    }
    try {
        return Shorts.checkedCast((long) MathFunctions.round((double) floatValue));
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + floatValue, e);
    }
}
 
源代码20 项目: presto   文件: IntegerOperators.java
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.INTEGER) long value)
{
    try {
        return Shorts.checkedCast(value);
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + value, e);
    }
}
 
源代码21 项目: presto   文件: DoubleOperators.java
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.DOUBLE) double value)
{
    if (Double.isNaN(value)) {
        throw new PrestoException(INVALID_CAST_ARGUMENT, "Cannot cast double NaN to smallint");
    }
    try {
        return Shorts.checkedCast((long) MathFunctions.round(value));
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + value, e);
    }
}
 
源代码22 项目: presto   文件: HdfsEnvironment.java
@Inject
public HdfsEnvironment(
        HdfsConfiguration hdfsConfiguration,
        HdfsConfig config,
        HdfsAuthentication hdfsAuthentication)
{
    this.hdfsConfiguration = requireNonNull(hdfsConfiguration, "hdfsConfiguration is null");
    requireNonNull(config, "config is null");
    this.newDirectoryPermissions = FsPermission.createImmutable(Shorts.checkedCast(parseUnsignedInt(config.getNewDirectoryPermissions(), 8)));
    this.verifyChecksum = config.isVerifyChecksum();
    this.hdfsAuthentication = requireNonNull(hdfsAuthentication, "hdfsAuthentication is null");
}
 
源代码23 项目: dhcp4j   文件: Dhcp6MessageEncoder.java
public void encode(final @Nonnull ByteBuffer byteBuffer, @Nonnull final Dhcp6Option option) {
    short tag = option.getTag();
    byte[] data = option.getData();
    byteBuffer.putShort(tag);
    byteBuffer.putShort(Shorts.checkedCast(data.length));
    byteBuffer.put(data);
}
 
源代码24 项目: presto   文件: AbstractTestParquetReader.java
private static Short intToShort(Integer input)
{
    if (input == null) {
        return null;
    }
    return Shorts.checkedCast(input);
}
 
protected static int getValueSplit(MemcachedCacheConfig config, String keyS, int valueBLen) {
    // the number 6 means the chunk number size never exceeds 6 bytes
    final int valueSize = config.getMaxObjectSize() - Shorts.BYTES - Ints.BYTES
            - keyS.getBytes(Charsets.UTF_8).length - 6;
    final int maxValueSize = config.getMaxChunkSize() * valueSize;
    Preconditions.checkArgument(valueBLen <= maxValueSize,
            "the value bytes length [%d] exceeds maximum value size [%d]", valueBLen, maxValueSize);
    return (valueBLen - 1) / valueSize + 1;
}
 
源代码26 项目: joyqueue   文件: CreatePartitionGroupHandler.java
private void commit(PartitionGroup group) throws Exception {
    if(logger.isDebugEnabled())logger.debug("topic[{}] add partitionGroup[{}]",group.getTopic(),group.getGroup());
    //if (!storeService.partitionGroupExists(group.getTopic(),group.getGroup())) {
        storeService.createPartitionGroup(group.getTopic().getFullName(), group.getGroup(), Shorts.toArray(group.getPartitions()));
        //}
        Set<Integer> replicas = group.getReplicas();
        List<Broker> list = new ArrayList<>(replicas.size());
        replicas.forEach(brokerId->{
            list.add(clusterManager.getBrokerById(brokerId));
        });
        electionService.onPartitionGroupCreate(group.getElectType(),group.getTopic(),group.getGroup(),list,group.getLearners(),clusterManager.getBrokerId(),group.getLeader());
}
 
源代码27 项目: joyqueue   文件: StoreInitializer.java
protected void onAddPartitionGroup(TopicName topicName, PartitionGroup partitionGroup) throws Exception {
    logger.info("onAddPartitionGroup, topic: {}, partitionGroup: {}", topicName, partitionGroup);

    Set<Integer> replicas = partitionGroup.getReplicas();
    List<Broker> brokers = new ArrayList<>(replicas.size());
    replicas.forEach(brokerId -> {
        brokers.add(clusterManager.getBrokerById(brokerId));
    });
    storeService.createPartitionGroup(topicName.getFullName(), partitionGroup.getGroup(), Shorts.toArray(partitionGroup.getPartitions()));
    electionService.onPartitionGroupCreate(partitionGroup.getElectType(), partitionGroup.getTopic(), partitionGroup.getGroup(),
            brokers, partitionGroup.getLearners(), clusterManager.getBrokerId(), partitionGroup.getLeader());
}
 
源代码28 项目: drift   文件: ArrayField.java
public Map<Short, List<Short>> getMapShortList()
{
    if (mapShortArray == null) {
        return null;
    }
    return Maps.transformValues(mapShortArray, Shorts::asList);
}
 
源代码29 项目: 07kit   文件: MiningOverlayPlugin.java
@Override
public void onOptionsChanged() {
    RockType.CLAY.setShow(showClay);
    RockType.COPPER.setShow(showCopper);
    RockType.TIN.setShow(showTin);
    RockType.IRON.setShow(showIron);
    RockType.SILVER.setShow(showSilver);
    RockType.COAL.setShow(showCoal);
    RockType.GOLD.setShow(showGold);
    RockType.MITHRIL.setShow(showMithril);
    RockType.ADAMANTITE.setShow(showAdamntite);
    RockType.RUNITE.setShow(showRunite);

    List<Short> colors = new ArrayList<>();

    for (RockType r : RockType.values()) {
        if (r.isShow()) {
            colors.addAll(Shorts.asList(r.getColors()));
        }
    }

    filter = acceptable -> acceptable.getComposite() != null &&
            Arrays.asList(acceptable.getComposite().getOriginalModelColors())
                    .stream().anyMatch(shorts -> {
                if (shorts == null) {
                    return false;
                }
                for (short color : shorts) {
                    if (colors.contains(color)) {
                        return true;
                    }
                }
                return false;
            });
}
 
源代码30 项目: qpid-broker-j   文件: MultiQpidByteBuffer.java
@Override
public final short getShort()
{
    byte[] value = new byte[2];
    get(value, 0, value.length);
    return Shorts.fromByteArray(value);
}