Java Code Examples for com.google.common.collect.Range#atMost()

The following examples show how to use com.google.common.collect.Range#atMost() . 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: RexSimplify.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static <C extends Comparable<C>> Range<C> range(SqlKind comparison, C c) {
    switch (comparison) {
    case EQUALS:
        return Range.singleton(c);
    case LESS_THAN:
        return Range.lessThan(c);
    case LESS_THAN_OR_EQUAL:
        return Range.atMost(c);
    case GREATER_THAN:
        return Range.greaterThan(c);
    case GREATER_THAN_OR_EQUAL:
        return Range.atLeast(c);
    default:
        throw new AssertionError();
    }
}
 
Example 2
Source File: DateRangeRules.java    From Quicksql with MIT License 6 votes vote down vote up
private Range<Calendar> ceilRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  final Calendar ceil = ceil(c, timeUnit);
  boolean boundary = ceil.equals(c);
  switch (comparison) {
  case EQUALS:
    return Range.openClosed(boundary ? decrement(ceil, timeUnit) : ceil, ceil);
  case LESS_THAN:
    return Range.atMost(decrement(ceil, timeUnit));
  case LESS_THAN_OR_EQUAL:
    return boundary ? Range.atMost(ceil) : Range.atMost(decrement(ceil, timeUnit));
  case GREATER_THAN:
    return boundary ? Range.greaterThan(ceil) : Range.greaterThan(decrement(ceil, timeUnit));
  case GREATER_THAN_OR_EQUAL:
    return Range.greaterThan(decrement(ceil, timeUnit));
  default:
    throw Util.unexpected(comparison);
  }
}
 
Example 3
Source File: RexSimplify.java    From Quicksql with MIT License 6 votes vote down vote up
private static <C extends Comparable<C>> Range<C> range(SqlKind comparison,
    C c) {
  switch (comparison) {
  case EQUALS:
    return Range.singleton(c);
  case LESS_THAN:
    return Range.lessThan(c);
  case LESS_THAN_OR_EQUAL:
    return Range.atMost(c);
  case GREATER_THAN:
    return Range.greaterThan(c);
  case GREATER_THAN_OR_EQUAL:
    return Range.atLeast(c);
  default:
    throw new AssertionError();
  }
}
 
Example 4
Source File: FilterParser.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@MethodParser("kill-streak")
public KillStreakFilter parseKillStreak(Element el) throws InvalidXMLException {
  boolean repeat = XMLUtils.parseBoolean(el.getAttribute("repeat"), false);
  Integer count = XMLUtils.parseNumber(el.getAttribute("count"), Integer.class, (Integer) null);
  Integer min = XMLUtils.parseNumber(el.getAttribute("min"), Integer.class, (Integer) null);
  Integer max = XMLUtils.parseNumber(el.getAttribute("max"), Integer.class, (Integer) null);
  Range<Integer> range;

  if (count != null) {
    range = Range.singleton(count);
  } else if (min == null) {
    if (max == null) {
      throw new InvalidXMLException("kill-streak filter must have a count, min, or max", el);
    } else {
      range = Range.atMost(max);
    }
  } else {
    if (max == null) {
      range = Range.atLeast(min);
    } else {
      range = Range.closed(min, max);
    }
  }

  return new KillStreakFilter(range, repeat);
}
 
Example 5
Source File: RexSimplify.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static <C extends Comparable<C>> Range<C> range(SqlKind comparison,
    C c) {
  switch (comparison) {
  case EQUALS:
    return Range.singleton(c);
  case LESS_THAN:
    return Range.lessThan(c);
  case LESS_THAN_OR_EQUAL:
    return Range.atMost(c);
  case GREATER_THAN:
    return Range.greaterThan(c);
  case GREATER_THAN_OR_EQUAL:
    return Range.atLeast(c);
  default:
    throw new AssertionError();
  }
}
 
Example 6
Source File: DateRangeRules.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Range<Calendar> ceilRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  final Calendar ceil = ceil(c, timeUnit);
  boolean boundary = ceil.equals(c);
  switch (comparison) {
  case EQUALS:
    return Range.openClosed(boundary ? decrement(ceil, timeUnit) : ceil, ceil);
  case LESS_THAN:
    return Range.atMost(decrement(ceil, timeUnit));
  case LESS_THAN_OR_EQUAL:
    return boundary ? Range.atMost(ceil) : Range.atMost(decrement(ceil, timeUnit));
  case GREATER_THAN:
    return boundary ? Range.greaterThan(ceil) : Range.greaterThan(decrement(ceil, timeUnit));
  case GREATER_THAN_OR_EQUAL:
    return Range.greaterThan(decrement(ceil, timeUnit));
  default:
    throw Util.unexpected(comparison);
  }
}
 
Example 7
Source File: ScreenDensitySelector.java    From bundletool with Apache License 2.0 6 votes vote down vote up
private Range<Integer> getDpiRange(int targetDpi, ImmutableSet<Integer> alternatives) {
  if (alternatives.isEmpty()) {
    return Range.all();
  }

  Optional<Integer> lowMidPoint =
      getNearestLowerDpi(targetDpi, alternatives)
          .map(lowerDpi -> getMidPoint(lowerDpi, targetDpi))
          .map(val -> (int) Math.ceil(val));
  Optional<Integer> highMidPoint =
      getNearestHigherDpi(targetDpi, alternatives)
          .map(higherDpi -> getMidPoint(targetDpi, higherDpi))
          .map(val -> (int) Math.floor(val));

  if (!lowMidPoint.isPresent()) {
    return Range.atMost(highMidPoint.get());
  }
  if (!highMidPoint.isPresent()) {
    return Range.atLeast(lowMidPoint.get());
  }
  return Range.closed(lowMidPoint.get(), highMidPoint.get());
}
 
Example 8
Source File: DateRangeRules.java    From Bats with Apache License 2.0 6 votes vote down vote up
private Range<Calendar> ceilRange(TimeUnitRange timeUnit, SqlKind comparison, Calendar c) {
    final Calendar ceil = ceil(c, timeUnit);
    boolean boundary = ceil.equals(c);
    switch (comparison) {
    case EQUALS:
        return Range.openClosed(boundary ? decrement(ceil, timeUnit) : ceil, ceil);
    case LESS_THAN:
        return Range.atMost(decrement(ceil, timeUnit));
    case LESS_THAN_OR_EQUAL:
        return boundary ? Range.atMost(ceil) : Range.atMost(decrement(ceil, timeUnit));
    case GREATER_THAN:
        return boundary ? Range.greaterThan(ceil) : Range.greaterThan(decrement(ceil, timeUnit));
    case GREATER_THAN_OR_EQUAL:
        return Range.greaterThan(decrement(ceil, timeUnit));
    default:
        throw Util.unexpected(comparison);
    }
}
 
Example 9
Source File: IntervalShardingAlgorithmTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertUpperHalfRangeDoSharding() {
    Range<String> rangeValue = Range.atMost("2019-09-01 00:00:00");
    List<RouteValue> shardingValues = Collections.singletonList(new RangeRouteValue<>("create_time", "t_order", rangeValue));
    Collection<String> actual = shardingStrategyByQuarter.doSharding(availableTablesForQuarterStrategy, shardingValues, new ConfigurationProperties(new Properties()));
    assertThat(actual.size(), is(15));
}
 
Example 10
Source File: Parameter.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
public <O extends Comparable<? super O>>Range<O> bounds() {
  O mini = minInclusive();
  O mine = minExclusive();
  O maxi = maxInclusive();
  O maxe = maxExclusive();
  Ordering<O> ordering = Ordering.<O>natural();
  O min = ordering.nullsLast().min(mini,mine);
  O max = ordering.nullsFirst().max(maxi,maxe);
  BoundType lower = 
    min == null ? null :
    min == mini ? BoundType.CLOSED :
      BoundType.OPEN;
  BoundType upper = 
    max == null ? null : 
    max == maxi ? BoundType.CLOSED :
      BoundType.OPEN;
  if (lower == null && upper == null)
    return Range.<O>all();
  else if (lower != null && upper == null) 
    return lower == BoundType.CLOSED ? 
      Range.atLeast(min) : 
      Range.greaterThan(min);
  else if (lower == null && upper != null)
    return upper == BoundType.CLOSED ?
      Range.atMost(max) :
      Range.lessThan(max);
  else {
    return Range.range(min, lower, max, upper);
  }
}
 
Example 11
Source File: RangeHeader.java    From notification with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param builder
 */
private RangeHeader(final Builder builder) {

  this.field = builder.field;

  if (builder.fromId != null && builder.toId != null) {
    if (builder.fromInclusive && builder.toInclusive) {
      range = Range.closed(builder.fromId, builder.toId);
    } else if (builder.fromInclusive && !builder.toInclusive) {
      range = Range.closedOpen(builder.fromId, builder.toId);
    } else if (!builder.fromInclusive && builder.toInclusive) {
      range = Range.openClosed(builder.fromId, builder.toId);
    } else {
      range = Range.open(builder.fromId, builder.toId);
    }
  } else if (builder.fromId != null && builder.toId == null) {
    if (builder.fromInclusive) {
      range = Range.atLeast(builder.fromId);
    } else {
      range = Range.greaterThan(builder.fromId);
    }
  } else if (builder.fromId == null && builder.toId != null) {
    if (builder.toInclusive) {
      range = Range.atMost(builder.toId);
    } else {
      range = Range.lessThan(builder.toId);
    }
  } else {
    range = Range.all();
  }

  this.max = builder.max;
}
 
Example 12
Source File: FilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@MethodParser("kill-streak")
public KillStreakFilter parseKillStreak(Element el) throws InvalidXMLException {
    boolean repeat = XMLUtils.parseBoolean(el.getAttribute("repeat"), false);
    boolean persistent = XMLUtils.parseBoolean(el.getAttribute("persistent"), false);
    Integer count = XMLUtils.parseNumber(el.getAttribute("count"), Integer.class, (Integer) null);
    Integer min = XMLUtils.parseNumber(el.getAttribute("min"), Integer.class, (Integer) null);
    Integer max = XMLUtils.parseNumber(el.getAttribute("max"), Integer.class, (Integer) null);
    Range<Integer> range;

    if(count != null) {
        range = Range.singleton(count);
    } else if(min == null) {
        if(max == null) {
            throw new InvalidXMLException("kill-streak filter must have a count, min, or max", el);
        } else {
            range = Range.atMost(max);
        }
    } else {
        if(max == null) {
            range = Range.atLeast(min);
        } else {
            range = Range.closed(min, max);
        }
    }

    if(repeat && !range.hasUpperBound()) {
        throw new InvalidXMLException("repeating kill-streak filter must have a count or max", el);
    }

    return new KillStreakFilter(range, repeat, persistent);
}
 
Example 13
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends Comparable> Range<T> ofString(String str, Function<String, T> converter, Class<T> cls) {
    BoundType lowerBound = str.charAt(0) == '[' ? BoundType.CLOSED : BoundType.OPEN;
    BoundType upperBound = str.charAt(str.length() - 1) == ']' ? BoundType.CLOSED : BoundType.OPEN;

    int delim = str.indexOf(',');

    if (delim == -1) {
        throw new IllegalArgumentException("Cannot find comma character");
    }

    String lowerStr = str.substring(1, delim);
    String upperStr = str.substring(delim + 1, str.length() - 1);

    T lower = null;
    T upper = null;

    if (lowerStr.length() > 0) {
        lower = converter.apply(lowerStr);
    }

    if (upperStr.length() > 0) {
        upper = converter.apply(upperStr);
    }

    if (lower == null && upper == null) {
        throw new IllegalArgumentException("Cannot find bound type");
    }

    if (lowerStr.length() == 0) {
        return upperBound == BoundType.CLOSED ?
                Range.atMost(upper) :
                Range.lessThan(upper);
    } else if (upperStr.length() == 0) {
        return lowerBound == BoundType.CLOSED ?
                Range.atLeast(lower) :
                Range.greaterThan(lower);
    } else {
        return Range.range(lower, lowerBound, upper, upperBound);
    }
}
 
Example 14
Source File: JoinMatcherMatchTest.java    From grappa with Apache License 2.0 4 votes vote down vote up
@DataProvider
public Iterator<Object[]> getInput1MatchData()
{
    final List<Object[]> list = Lists.newArrayList();

    Range<Integer> range;
    int index;
    boolean match;

    range = Range.singleton(3);
    index = 5;
    match = true;
    list.add(new Object[] { range, index, match });

    range = Range.singleton(6);
    index = 9;
    match = false;
    list.add(new Object[] { range, index, match });

    range = Range.atMost(4);
    index = 7;
    match = true;
    list.add(new Object[] { range, index, match });

    range = Range.atLeast(2);
    index = 9;
    match = true;
    list.add(new Object[] { range, index, match });

    range = Range.closed(2, 9);
    index = 9;
    match = true;
    list.add(new Object[] { range, index, match });

    range = Range.closed(2, 4);
    index = 7;
    match = true;
    list.add(new Object[] { range, index, match });

    return list.iterator();
}
 
Example 15
Source File: RepeatMatcherMatchTest.java    From grappa with Apache License 2.0 4 votes vote down vote up
@DataProvider
public Iterator<Object[]> getInput1MatchData()
{
    final List<Object[]> list = Lists.newArrayList();

    Range<Integer> range;
    int index;
    boolean match;

    range = Range.singleton(3);
    index = 6;
    match = true;
    list.add(new Object[] { range, index, match });

    range = Range.singleton(6);
    index = 10;
    match = false;
    list.add(new Object[] { range, index, match });

    range = Range.atMost(4);
    index = 8;
    match = true;
    list.add(new Object[] { range, index, match });

    range = Range.atLeast(2);
    index = 10;
    match = true;
    list.add(new Object[] { range, index, match });

    range = Range.closed(2, 9);
    index = 10;
    match = true;
    list.add(new Object[] { range, index, match });

    range = Range.closed(2, 4);
    index = 8;
    match = true;
    list.add(new Object[] { range, index, match });

    return list.iterator();
}
 
Example 16
Source File: ScreenDensitySelector.java    From bundletool with Apache License 2.0 4 votes vote down vote up
/**
 * For a given range of devices dpi served by a split, returns the range of resources that are
 * reachable from this split.
 *
 * <p>The reachable resources can cover a be different dpi range than that of the devices since a
 * resource with dpi smaller than the lowest dpi device can be still preferred by that device.
 *
 * @param deviceDpiRange range of device dpis to serve by a given split
 * @param values {@link ConfigValue} objects of a resource under consideration
 * @return range of resource config values that can be matched by any device served by the split
 */
@CheckReturnValue
private ImmutableList<ConfigValue> getReachableConfigValues(
    Range<Integer> deviceDpiRange, ImmutableList<ConfigValue> values, Version bundleVersion) {
  // We are calculating the lowest and highest dpi of the resource that could be matched by the
  // devices from the given deviceDpiRange.
  // We take the lowest eligible dpi device and find the best matching resource for it, similarly
  // at the other end of the servedDpiRange. Because the best matching is monotonic, all resource
  // configs between those extremes and no others could be matched by any device that falls into
  // that dpi range.

  Optional<Integer> lowestResourceDpi = Optional.empty();
  Optional<Integer> highestResourceDpi = Optional.empty();
  if (deviceDpiRange.hasLowerBound()) {
    lowestResourceDpi =
        Optional.of(
            selectBestConfigValue(values, deviceDpiRange.lowerEndpoint(), bundleVersion)
                .getConfig()
                .getDensity());
  }
  if (deviceDpiRange.hasUpperBound()) {
    highestResourceDpi =
        Optional.of(
            selectBestConfigValue(values, deviceDpiRange.upperEndpoint(), bundleVersion)
                .getConfig()
                .getDensity());
  }

  Range<Integer> effectiveDpiRange;

  if (deviceDpiRange.equals(Range.all())) {
    effectiveDpiRange = Range.all();
  } else if (!lowestResourceDpi.isPresent()) {
    effectiveDpiRange = Range.atMost(highestResourceDpi.get());
  } else if (!highestResourceDpi.isPresent()) {
    effectiveDpiRange = Range.atLeast(lowestResourceDpi.get());
  } else {
    effectiveDpiRange = Range.closed(lowestResourceDpi.get(), highestResourceDpi.get());
  }

  return values.stream()
      .filter(configValue -> effectiveDpiRange.contains(configValue.getConfig().getDensity()))
      .collect(toImmutableList());
}
 
Example 17
Source File: TsConditionExtractor.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
private static Range<Long> extractTsConditionInternal(TupleFilter filter, TblColRef colRef) {
    if (filter == null) {
        return Range.all();
    }

    if (filter instanceof LogicalTupleFilter) {
        if (filter.getOperator() == TupleFilter.FilterOperatorEnum.AND) {
            Range<Long> ret = Range.all();
            for (TupleFilter child : filter.getChildren()) {
                Range childRange = extractTsConditionInternal(child, colRef);
                if (childRange != null) {
                    if (ret.isConnected(childRange) && !ret.intersection(childRange).isEmpty()) {
                        ret = ret.intersection(childRange);
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            }
            return ret.isEmpty() ? null : ret;
        } else {
            //for conditions like date > DATE'2000-11-11' OR date < DATE '1999-01-01'
            //we will use Ranges.all() rather than two ranges to represent them
            return Range.all();
        }
    }

    if (filter instanceof CompareTupleFilter) {
        CompareTupleFilter compareTupleFilter = (CompareTupleFilter) filter;
        if (compareTupleFilter.getColumn() == null)// column will be null at filters like " 1<>1"
            return Range.all();

        if (compareTupleFilter.getColumn().equals(colRef)) {
            Object firstValue = compareTupleFilter.getFirstValue();
            long t;
            switch (compareTupleFilter.getOperator()) {
            case EQ:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.closed(t, t);
            case LT:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.lessThan(t);
            case LTE:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.atMost(t);
            case GT:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.greaterThan(t);
            case GTE:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.atLeast(t);
            case NEQ:
            case IN://not handled for now
                break;
            default:
            }
        }
    }
    return Range.all();
}
 
Example 18
Source File: Version.java    From ovsdb with Eclipse Public License 1.0 4 votes vote down vote up
public static Range<Version> createRangeOf(final Version from, final Version to) {
    if (from == null || Version.NULL.equals(from)) {
        return to == null || Version.NULL.equals(to) ? Range.all() : Range.atMost(to);
    }
    return to == null || Version.NULL.equals(to) ? Range.atLeast(from) : Range.closed(from, to);
}
 
Example 19
Source File: DataPointSearchCriteriaBuilder.java    From omh-dsu-ri with Apache License 2.0 4 votes vote down vote up
public DataPointSearchCriteriaBuilder setCreationTimestampUpperEndpoint(OffsetDateTime upperEndpoint) {
    this.creationTimestampUpperEndpoint = upperEndpoint != null ? Range.atMost(upperEndpoint) : Range.all();
    return this;
}
 
Example 20
Source File: DiscretizationUtil.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
public Range<Double> toRange(Interval interval){
	Double leftMargin = NumberUtil.asDouble(interval.getLeftMargin());
	Double rightMargin = NumberUtil.asDouble(interval.getRightMargin());

	// "The leftMargin and rightMargin attributes are optional, but at least one value must be defined"
	if(leftMargin == null && rightMargin == null){
		throw new MissingAttributeException(interval, PMMLAttributes.INTERVAL_LEFTMARGIN);
	} // End if

	if(leftMargin != null && rightMargin != null && NumberUtil.compare(leftMargin, rightMargin) > 0){
		throw new InvalidElementException(interval);
	}

	Interval.Closure closure = interval.getClosure();
	if(closure == null){
		throw new MissingAttributeException(interval, PMMLAttributes.INTERVAL_CLOSURE);
	}

	switch(closure){
		case OPEN_OPEN:
			{
				if(leftMargin == null){
					return Range.lessThan(rightMargin);
				} else

				if(rightMargin == null){
					return Range.greaterThan(leftMargin);
				}

				return Range.open(leftMargin, rightMargin);
			}
		case OPEN_CLOSED:
			{
				if(leftMargin == null){
					return Range.atMost(rightMargin);
				} else

				if(rightMargin == null){
					return Range.greaterThan(leftMargin);
				}

				return Range.openClosed(leftMargin, rightMargin);
			}
		case CLOSED_OPEN:
			{
				if(leftMargin == null){
					return Range.lessThan(rightMargin);
				} else

				if(rightMargin == null){
					return Range.atLeast(leftMargin);
				}

				return Range.closedOpen(leftMargin, rightMargin);
			}
		case CLOSED_CLOSED:
			{
				if(leftMargin == null){
					return Range.atMost(rightMargin);
				} else

				if(rightMargin == null){
					return Range.atLeast(leftMargin);
				}

				return Range.closed(leftMargin, rightMargin);
			}
		default:
			throw new UnsupportedAttributeException(interval, closure);
	}
}