com.google.common.math.IntMath Java Examples

The following examples show how to use com.google.common.math.IntMath. 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: StreamMapping.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
public static PTOperator createSlidingUnifier(StreamMeta streamMeta, PhysicalPlan plan, int
    operatorApplicationWindowCount, int slidingWindowCount)
{
  int gcd = IntMath.gcd(operatorApplicationWindowCount, slidingWindowCount);
  OperatorMeta um = streamMeta.getSource()
      .getSlidingUnifier(operatorApplicationWindowCount / gcd, gcd, slidingWindowCount / gcd);
  PTOperator pu = plan.newOperator(um, um.getName());

  Operator unifier = um.getOperator();
  PortMappingDescriptor mergeDesc = new PortMappingDescriptor();
  Operators.describe(unifier, mergeDesc);
  if (mergeDesc.outputPorts.size() != 1) {
    throw new AssertionError("Unifier must have a single output port, instead found : " + mergeDesc.outputPorts);
  }
  pu.unifiedOperatorMeta = streamMeta.getSource().getOperatorMeta();
  pu.outputs.add(new PTOutput(mergeDesc.outputPorts.keySet().iterator().next(), streamMeta, pu));
  plan.newOpers.put(pu, unifier);
  return pu;
}
 
Example #2
Source File: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static String encodePathPattern(String pathPattern) {
    // We do not need full escaping because we validated the path pattern already and thus contains only
    // -, ' ', /, *, _, ., ',', a-z, A-Z, 0-9.
    // See Util.isValidPathPattern() for more information.
    int spacePos = pathPattern.indexOf(' ');
    if (spacePos < 0) {
        return pathPattern;
    }

    final StringBuilder buf = new StringBuilder(IntMath.saturatedMultiply(pathPattern.length(), 2));
    for (int pos = 0;;) {
        buf.append(pathPattern, pos, spacePos);
        buf.append("%20");
        pos = spacePos + 1;
        spacePos = pathPattern.indexOf(' ', pos);
        if (spacePos < 0) {
            buf.append(pathPattern, pos, pathPattern.length());
            break;
        }
    }

    return buf.toString();
}
 
Example #3
Source File: LayersCalculator.java    From compass with GNU Affero General Public License v3.0 6 votes vote down vote up
List<List<String>> calculateAllLayers(List<String> addresses) {
  int depth = IntMath.log2(addresses.size(), RoundingMode.FLOOR);
  List<List<String>> layers = new ArrayList<>(depth);
  List<String> last = addresses;
  layers.add(last);

  while (depth-- > 0) {
    log.info("Calculating nodes for depth " + depth);
    last = calculateNextLayer(last);

    layers.add(last);
  }

  Collections.reverse(layers);
  return layers;
}
 
Example #4
Source File: Aggregate.java    From Quicksql with MIT License 6 votes vote down vote up
public static Group induce(ImmutableBitSet groupSet,
    List<ImmutableBitSet> groupSets) {
  if (!ImmutableBitSet.ORDERING.isStrictlyOrdered(groupSets)) {
    throw new IllegalArgumentException("must be sorted: " + groupSets);
  }
  if (groupSets.size() == 1 && groupSets.get(0).equals(groupSet)) {
    return SIMPLE;
  }
  if (groupSets.size() == IntMath.pow(2, groupSet.cardinality())) {
    return CUBE;
  }
  if (isRollup(groupSet, groupSets)) {
    return ROLLUP;
  }
  return OTHER;
}
 
Example #5
Source File: HttpHeadersBase.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static String malformedHeaderValueMessage(String value) {
    final StringBuilder buf = new StringBuilder(IntMath.saturatedAdd(value.length(), 64));
    buf.append("malformed header value: ");

    final int valueLength = value.length();
    for (int i = 0; i < valueLength; i++) {
        final char ch = value.charAt(i);
        if (PROHIBITED_VALUE_CHARS.get(ch)) {
            buf.append(PROHIBITED_VALUE_CHAR_NAMES[ch]);
        } else {
            buf.append(ch);
        }
    }

    return buf.toString();
}
 
Example #6
Source File: DataHandler.java    From Nations with MIT License 5 votes vote down vote up
public static Nation getNation(Location<World> loc)
{
	if (!worldChunks.containsKey(loc.getExtent().getUniqueId()))
	{
		return null;
	}
	Vector2i area = new Vector2i(IntMath.divide(loc.getBlockX(), 16, RoundingMode.FLOOR), IntMath.divide(loc.getBlockZ(), 16, RoundingMode.FLOOR));
	if (!worldChunks.get(loc.getExtent().getUniqueId()).containsKey(area))
	{
		return null;
	}
	for (Nation nation : worldChunks.get(loc.getExtent().getUniqueId()).get(area))
	{
		if (nation.getRegion().isInside(loc))
		{
			return nation;
		}
	}
	//		for (Entry<Vector2i, ArrayList<Nation>> e : worldChunks.get(loc.getExtent().getUniqueId()).entrySet())
	//		{
	//			if (e.getKey().equals(new Vector2i(IntMath.divide(loc.getBlockX(), 16, RoundingMode.FLOOR), IntMath.divide(loc.getBlockZ(), 16, RoundingMode.FLOOR))))
	//			{
	//				for (Nation nation : e.getValue())
	//				{
	//					if (nation.getRegion().isInside(loc))
	//					{
	//						return nation;
	//					}
	//				}
	//				return null;
	//			}
	//		}
	return null;
}
 
Example #7
Source File: RatLitExpr.java    From theta with Apache License 2.0 5 votes vote down vote up
private RatLitExpr(final int num, final int denom) {
	checkArgument(denom != 0);

	final int gcd = IntMath.gcd(Math.abs(num), Math.abs(denom));
	if (denom >= 0) {
		this.num = num / gcd;
		this.denom = denom / gcd;
	} else {
		this.num = -num / gcd;
		this.denom = -denom / gcd;
	}
}
 
Example #8
Source File: KafkaConsumerManager.java    From vertx-kafka-service with Apache License 2.0 5 votes vote down vote up
private int computeNextDelay(int delaySeconds) {
    try {
        return Math.min(IntMath.checkedMultiply(delaySeconds, 2), configuration.getMaxRetryDelaySeconds());
    } catch (ArithmeticException e) {
        return configuration.getMaxRetryDelaySeconds();
    }
}
 
Example #9
Source File: SearchUtils.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Partition(Collection<T> allItems, Comparator<T> comparator, int itemsPerPartition, int currentPartition) {
    this.itemsPerPartition = itemsPerPartition;
    this.numPartitions = IntMath.divide(allItems.size(), itemsPerPartition, RoundingMode.CEILING);
    this.currentPartitionNumber = Math.min(this.numPartitions, Math.max(1, currentPartition));
    this.partitionItems = allItems.stream().sorted(comparator)
                    .skip((currentPartition - 1) * itemsPerPartition).limit(itemsPerPartition).collect(toList());
}
 
Example #10
Source File: CartesianList.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
CartesianList(ImmutableList<List<E>> axes) {
  this.axes = axes;

  int[] axesSizeProduct = new int[axes.size() + 1];
  axesSizeProduct[axes.size()] = 1;
  try {
    for (int i = axes.size() - 1; i >= 0; i--) {
      axesSizeProduct[i] = IntMath.checkedMultiply(axesSizeProduct[i + 1], axes.get(i).size());
    }
  } catch (ArithmeticException e) {
    throw new IllegalArgumentException("Cartesian product too large; must have size at most Integer.MAX_VALUE");
  }
  this.axesSizeProduct = axesSizeProduct;
}
 
Example #11
Source File: FilterTable.java    From CuckooFilter4J with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a FilterTable
 * 
 * @param bitsPerTag
 *            number of bits needed for each tag
 * @param numBuckets
 *            number of buckets in filter
 * @return
 */
static FilterTable create(int bitsPerTag, long numBuckets) {
	// why would this ever happen?
	checkArgument(bitsPerTag < 48, "tagBits (%s) should be less than 48 bits", bitsPerTag);
	// shorter fingerprints don't give us a good fill capacity
	checkArgument(bitsPerTag > 4, "tagBits (%s) must be > 4", bitsPerTag);
	checkArgument(numBuckets > 1, "numBuckets (%s) must be > 1", numBuckets);
	// checked so our implementors don't get too.... "enthusiastic" with
	// table size
	long bitsPerBucket = IntMath.checkedMultiply(CuckooFilter.BUCKET_SIZE, bitsPerTag);
	long bitSetSize = LongMath.checkedMultiply(bitsPerBucket, numBuckets);
	LongBitSet memBlock = new LongBitSet(bitSetSize);
	return new FilterTable(memBlock, bitsPerTag, numBuckets);
}
 
Example #12
Source File: AlternativeProvider.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
AlternativeProvider(List<MediaType> mediaTypes, List<CharacterEncoding> characterEncodings, List<Language> languages) {
	this.mediaTypes=EntityProvider.of(mediaTypes);
	this.characterEncodings=EntityProvider.of(characterEncodings);
	this.languages=EntityProvider.of(languages);
	this.size=
		this.mediaTypes.consumableEntities()*
		this.characterEncodings.consumableEntities()*
		this.languages.consumableEntities();
	this.position=0;
	this.buckets=IntMath.divide(this.size,MAX_BUCKETS,RoundingMode.CEILING);
}
 
Example #13
Source File: CountMin4.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/**
 * Increases the capacity of this <tt>FrequencySketch</tt> instance, if necessary, to ensure that
 * it can accurately estimate the popularity of elements given the maximum size of the cache. This
 * operation forgets all previous counts when resizing.
 *
 * @param maximumSize the maximum size of the cache
 */
protected void ensureCapacity(long maximumSize) {
  checkArgument(maximumSize >= 0);
  int maximum = (int) Math.min(maximumSize, Integer.MAX_VALUE >>> 1);
  if ((table != null) && (table.length >= maximum)) {
    return;
  }

  table = new long[(maximum == 0) ? 1 : IntMath.ceilingPowerOfTwo(maximum)];
  tableMask = Math.max(0, table.length - 1);
}
 
Example #14
Source File: GuavaMathUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void should_round_log2_result() {
    int result1 = IntMath.log2(5, RoundingMode.FLOOR);
    assertThat(result1, equalTo(2));

    int result2 = IntMath.log2(5, RoundingMode.CEILING);
    assertThat(result2, equalTo(3));
}
 
Example #15
Source File: MinMaxPriorityQueue.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns ~2x the old capacity if small; ~1.5x otherwise. */

  private int calculateNewCapacity() {
    int oldCapacity = queue.length;
    int newCapacity = (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3);
    return capAtMaximumSize(newCapacity, maximumSize);
          }
 
Example #16
Source File: MinMaxPriorityQueue.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns ~2x the old capacity if small; ~1.5x otherwise. */

  private int calculateNewCapacity() {
    int oldCapacity = queue.length;
    int newCapacity = (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3);
    return capAtMaximumSize(newCapacity, maximumSize);
          }
 
Example #17
Source File: AlternativeProvider.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private double currentQuality() {
	return
		DoubleUtils.
			limitPrecision(
				1.0D-IntMath.divide(this.position,this.buckets,RoundingMode.HALF_UP)*BUCKET_QUALITY,
				3);
}
 
Example #18
Source File: CartesianList.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
CartesianList(ImmutableList<List<E>> axes) {
  this.axes = axes;
  int[] axesSizeProduct = new int[axes.size() + 1];
  axesSizeProduct[axes.size()] = 1;
  try {
    for (int i = axes.size() - 1; i >= 0; i--) {
      axesSizeProduct[i] = IntMath.checkedMultiply(axesSizeProduct[i + 1], axes.get(i).size());
    }
  } catch (ArithmeticException e) {
    throw new IllegalArgumentException(
        "Cartesian product too large; must have size at most Integer.MAX_VALUE");
  }
  this.axesSizeProduct = axesSizeProduct;
}
 
Example #19
Source File: CountingSampler.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public boolean isSampled(long traceId) {
  // It's highly unlikely the total number of sampling decisions would reach the limit of a Long,
  // but if it did it would wrap to a negative number but the mod will remain positive and
  // will continue to cycle through decisions.
  return sampleDecisions.get(IntMath.mod(counter.getAndIncrement(), numBuckets));
}
 
Example #20
Source File: MathUtils.java    From turbo-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 最大公约数
 * 
 * @param a
 * @param b
 * @return
 */
public static int gcd(int a, int b) {
	if (a == b) {
		return a;
	}

	return IntMath.gcd(a, b);
}
 
Example #21
Source File: GuavaMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test(expected = ArithmeticException.class)
public void whenSumUnderflow_thenThrowException() {
    IntMath.checkedAdd(Integer.MIN_VALUE, -1);
}
 
Example #22
Source File: Collections2.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public int size() {
  return IntMath.factorial(inputList.size());
}
 
Example #23
Source File: GuavaIntMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() {
    int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 1000);
    assertEquals(Integer.MAX_VALUE, result);
}
 
Example #24
Source File: GuavaIntMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenPowTwoIntegerValues_shouldPowThemAndReturnTheResult() {
    int result = IntMath.pow(6, 4);
    assertEquals(1296, result);
}
 
Example #25
Source File: GuavaIntMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() {
    int result = IntMath.sqrt(30, RoundingMode.FLOOR);
    assertEquals(5, result);
}
 
Example #26
Source File: GuavaMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test(expected = ArithmeticException.class)
public void whenPowerUnderflow_thenThrowException() {
    IntMath.checkedPow(Integer.MIN_VALUE, 3);
}
 
Example #27
Source File: GuavaIntMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenLog10IntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() {
    int result = IntMath.log10(30, RoundingMode.CEILING);
    assertEquals(2, result);
}
 
Example #28
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public int size() {
  return IntMath.saturatedAdd(rest.length, 1);
}
 
Example #29
Source File: GuavaIntMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnTheResult() {
    int result = IntMath.saturatedPow(6, 2);
    assertEquals(36, result);
}
 
Example #30
Source File: GuavaMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void should_calculate_product() {
    int result = IntMath.checkedMultiply(21, 3);
    assertThat(result, equalTo(63));
}