Example usage for org.apache.commons.lang3 Range between

List of usage examples for org.apache.commons.lang3 Range between

Introduction

In this page you can find the example usage for org.apache.commons.lang3 Range between.

Prototype

public static <T extends Comparable<T>> Range<T> between(final T fromInclusive, final T toInclusive) 

Source Link

Document

Obtains a range with the specified minimum and maximum values (both inclusive).

The range uses the natural ordering of the elements to determine where values lie in the range.

The arguments may be passed in the order (min,max) or (max,min).

Usage

From source file:enumsupport.reverselookupmapfactory.DeduplicatdeNumberSetFactoryTest.java

/**
 * Test of makeSet method, of class DeduplicatdeNumberSetFactory.
 *///from  ww w . j a  va  2s .c  om
@Test
@ExpectedExceptionMessage("????????")
public void testMakeSet5() {
    LOG.info("makeSet");
    DeduplicatdeNumberSetFactory<Integer> instance = new DeduplicatdeNumberSetFactory<>();
    Set<Integer> result = instance.makeSet(Range.between(10, 20), 10, 11, 12, 21, 13);
}

From source file:de.julielab.jcore.utility.JCoReAnnotationTools.java

@SuppressWarnings("unchecked")
public static <T extends Annotation> T getAnnotationAtMatchingOffsets(JCas aJCas, Annotation focusAnnotation,
        Class<T> cls) {//from   www . j av  a 2 s .c  o m
    FSIterator<Annotation> cursor = aJCas.getAnnotationIndex().iterator();

    cursor.moveTo(focusAnnotation);

    if (!cursor.isValid())
        throw new IllegalArgumentException(
                "Given FocusAnnotation was not found in the JCas' annotation index: " + focusAnnotation);

    while (cursor.isValid() && cursor.get().getBegin() >= focusAnnotation.getBegin()) {
        cursor.moveToPrevious();
    }
    if (!cursor.isValid())
        cursor.moveToFirst();
    else
        cursor.moveToNext();

    // Now that we have our starting point, we go to the right until we find an annotation of the correct type and
    // the same offsets as focusAnnotation
    Annotation currentAnnotation = null;
    while (cursor.isValid() && (currentAnnotation = cursor.get()).getBegin() <= focusAnnotation.getEnd()) {
        if (!cls.isInstance(currentAnnotation)) {
            cursor.moveToNext();
            continue;
        }
        Range<Integer> currentRange = Range.between(currentAnnotation.getBegin(), currentAnnotation.getEnd());
        Range<Integer> focusRange = Range.between(focusAnnotation.getBegin(), focusAnnotation.getEnd());
        if (cursor.isValid() && cls.isInstance(currentAnnotation) && focusRange.equals(currentRange))
            return (T) currentAnnotation;
        cursor.moveToNext();
    }
    return null;
}

From source file:libepg.epg.util.datetime.DateTimeFieldConverter.java

private static Map<HMS_KEY, Integer> BcdTimeToMap(byte[] hms) throws ParseException {
    Map<HMS_KEY, Integer> ret = new HashMap<>();
    if (hms.length != 3) {
        throw new IndexOutOfBoundsException(
                "?????3????????"
                        + " ?=" + Hex.encodeHexString(hms));
    }//from   w  ww. jav a2 s.  c om

    //ARIB????????????????
    if (Arrays.equals(hms, UNDEFINED_BCD_TIME_BLOCK.getData())) {
        throw new ParseException("???????????" + " ?="
                + Hex.encodeHexString(hms), 0);
    }
    Object[] parameters = null;

    final int hour = new BCD(hms[0]).getDecimal();
    final int minute = new BCD(hms[1]).getDecimal();
    final int second = new BCD(hms[2]).getDecimal();
    CHECK: {
        final Range<Integer> HOUR_RANGE = Range.between(0, 23);

        if (!HOUR_RANGE.contains(hour)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", hour };
            break CHECK;
        }

        final Range<Integer> MINUTE_AND_SECOND_RANGE = Range.between(0, 59);

        if (!MINUTE_AND_SECOND_RANGE.contains(minute)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", minute };
            break CHECK;
        }

        if (!MINUTE_AND_SECOND_RANGE.contains(second)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", second };
            break CHECK;
        }
    }

    if (parameters != null) {
        MessageFormat msg = new MessageFormat(
                "????????????={0} ={1} ={2}");
        throw new ParseException(msg.format(parameters), 0);
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("hour=" + hour + " minute=" + minute + " second=" + second);
    }

    ret.put(HMS_KEY.HOUR, hour);
    ret.put(HMS_KEY.MINUTE, minute);
    ret.put(HMS_KEY.SECOND, second);

    return ret;
}

From source file:de.tor.tribes.util.algo.types.TimeFrame.java

/**
 * Check if a movement with the provided runtime is possible for this
 * AttackFitter//  ww  w  . j  a  v a2 s.c  om
 *
 * @param pRuntime Runtime to check
 * @param pVillage Village for which the runtime is valid
 * @return boolean TRUE=Runtime might be fitted if not all send times are
 * already used
 */
public boolean isMovementPossible(long pRuntime) {
    if (startRanges == null) {
        startRanges = startTimespansToRanges();
    }
    if (arriveRanges == null) {
        arriveRanges = arriveTimespansToRanges();
    }

    for (Range<Long> currentStartRange : startRanges) {
        Range<Long> arriveRangeForStartRange = Range.between(currentStartRange.getMinimum() + pRuntime,
                currentStartRange.getMaximum() + pRuntime);
        for (Range<Long> currentArriveRange : arriveRanges) {
            if (currentArriveRange.isOverlappedBy(arriveRangeForStartRange)) {
                //movement with 'pRuntime' starting in 'currentStartRange' will arrive withing 'currentArriveRange'
                return true;
            }
        }
    }
    //no overlapping range was found
    return false;
}

From source file:enumsupport.reverselookupmapfactory.DeduplicatdeNumberSetFactoryTest.java

/**
 * Test of makeSet method, of class DeduplicatdeNumberSetFactory.
 *//* www. ja  va 2s.c o  m*/
@Test
@ExpectedExceptionMessage("????????")
public void testMakeSet6() {
    LOG.info("makeSet");
    DeduplicatdeNumberSetFactory<Integer> instance = new DeduplicatdeNumberSetFactory<>();
    Set<Integer> result = instance.makeSet(Range.between(10, 20), 10, 9, 12, 20, 13);
}

From source file:libepg.ts.packet.PROGRAM_ID.java

private PROGRAM_ID(String pidName, Integer pid, Integer... pids) {

    this.pidName = pidName;
    if ((this.pidName == null) || ("".equals(this.pidName))) {
        throw new IllegalArgumentException("???????????");
    }//from  w ww . j  av a  2 s.  c  o m

    List<Integer> t = new ArrayList<>();
    if (pid != null) {
        t.add(pid);
    } else {
        throw new NullPointerException("PID??????");
    }
    if (pids != null) {
        t.addAll(Arrays.asList(pids));
    }
    Range<Integer> r = Range.between(0x0000, 0x1FFF);
    for (Integer i : t) {
        if (!r.contains(i)) {
            MessageFormat msg = new MessageFormat("PID????PID={0}");
            Object[] parameters = { Integer.toHexString(i) };
            throw new IllegalArgumentException(msg.format(parameters));
        }
    }
    Set<Integer> temp = Collections.synchronizedSet(new HashSet<Integer>());
    temp.addAll(t);
    this.pids = Collections.unmodifiableSet(temp);
}

From source file:libepg.ts.packet.RESERVED_PROGRAM_ID.java

private RESERVED_PROGRAM_ID(String pidName, Integer pid, Integer... pids) {

    this.pidName = pidName;
    if ((this.pidName == null) || ("".equals(this.pidName))) {
        throw new IllegalArgumentException("???????????");
    }/*from   w  w w.j  a v a 2  s .c om*/
    Range<Integer> r = Range.between(0x0000, 0x1FFF);

    DeduplicatdeNumberSetFactory<Integer> setf = new DeduplicatdeNumberSetFactory<>();

    this.pids = setf.makeSet(r, pid, pids);

}

From source file:de.tor.tribes.util.algo.types.TimeFrame.java

/**
 * Returns an arrive date that fits into this AttackFitter and is based on the
 * provided runtime/*from www  .  j a  v  a 2  s .  com*/
 *
 * @param pRuntime Runtime to fit into
 * @param pVillage Village for which the arrive date should be valid
 * @param pUsedSendTimes Already used send times (possible times are checked
 * in steps of 1ms). This argument may be 'null'. Then send times are
 * not checked.
 * @return Date Fitted arrive time
 */
public Date getFittedArriveTime(long pRuntime, List<Long> pUsedSendTimes) {
    List<Range<Long>> startRanges = startTimespansToRanges();
    List<Range<Long>> arriveRanges = arriveTimespansToRanges();
    List<Range<Long>> possible = new ArrayList();
    for (Range<Long> currentStartRange : startRanges) {
        Range<Long> arriveRangeForStartRange = Range.between(currentStartRange.getMinimum() + pRuntime,
                currentStartRange.getMaximum() + pRuntime);
        for (Range<Long> currentArriveRange : arriveRanges) {
            if (currentArriveRange.isOverlappedBy(arriveRangeForStartRange)) {
                //movement possible for these 'currentStartRange' and 'currentArriveRange' so fit runtime into
                //           |-----------|
                //   |--------------|
                long minArrive = currentArriveRange.getMinimum();
                long minArriveForStartRange = arriveRangeForStartRange.getMinimum();
                long checkStart = 0;
                if (minArrive < minArriveForStartRange) {
                    //|----------- (Arrive)
                    //   |-------------- (ArriveForStart)
                    //check everything beginning with 'minArriveForStartRange'
                    checkStart = minArriveForStartRange;
                } else if (minArriveForStartRange <= minArrive) {
                    //     |----------- (Arrive)
                    //|-------------- (ArriveForStart)
                    //check everything beginning with 'minArrive'
                    checkStart = minArrive;
                }
                long maxArrive = currentArriveRange.getMaximum();
                long maxArriveForStartRange = arriveRangeForStartRange.getMaximum();
                long checkEnd = 0;
                if (maxArrive < maxArriveForStartRange) {
                    //-----------| (Arrive)
                    //---------------| (ArriveForStart)
                    //check everything until 'maxArrive'
                    checkEnd = maxArrive;
                } else if (maxArriveForStartRange <= maxArrive) {
                    //-------------| (Arrive)
                    //---------| (ArriveForStart)
                    //check everything until 'maxArriveForStartRange'
                    checkEnd = maxArriveForStartRange;
                }

                if (checkStart != checkEnd) {
                    //We are handling real Ranges
                    int cnt = 0;
                    while (cnt < 20) {
                        long arriveTime = checkStart + Math.round(Math.random() * (checkEnd - checkStart));
                        if (pUsedSendTimes == null || !pUsedSendTimes.contains(arriveTime - pRuntime)) {
                            if (pUsedSendTimes != null) {
                                pUsedSendTimes.add(arriveTime - pRuntime);
                            }
                            return new Date(arriveTime);
                        }
                        cnt++;
                    }
                    //We found nothing with random, try systematic search
                    for (long i = checkStart; i <= checkEnd; i++) {
                        if (!pUsedSendTimes.contains(i - pRuntime)) {
                            pUsedSendTimes.add(i - pRuntime);
                            return new Date(i);
                        }
                    }
                } else {
                    //We are handling a fixed arrive Time
                    if (pUsedSendTimes == null || !pUsedSendTimes.contains(checkStart - pRuntime)) {
                        if (pUsedSendTimes != null) {
                            pUsedSendTimes.add(checkStart - pRuntime);
                        }
                        return new Date(checkStart);
                    }
                }
                possible.add(Range.between(checkStart, checkEnd));
            }
        }
    }

    if (!possible.isEmpty()) {
        long cnt = 0;
        for (Range<Long> r : possible) {
            cnt += r.getMaximum() - r.getMinimum() + 1;
        }
        cnt = (long) (Math.random() * cnt);
        for (Range<Long> r : possible) {
            Long span = r.getMaximum() - r.getMinimum() + 1;
            if (cnt < span) {
                return new Date(r.getMinimum() + cnt);
            }
            cnt -= span;
        }
    }

    return null;
}

From source file:de.tor.tribes.types.TimeSpan.java

public boolean intersectsWithNightBonus() {
    if (!ServerSettings.getSingleton().isNightBonusActive()) {
        return false;
    }//w  w  w . ja  v a  2  s .  c  o m
    TimeSpan nightBonusSpan = new TimeSpan(
            Range.between(ServerSettings.getSingleton().getNightBonusStartHour() * DateUtils.MILLIS_PER_HOUR,
                    ServerSettings.getSingleton().getNightBonusEndHour() * DateUtils.MILLIS_PER_HOUR),
            true);
    return nightBonusSpan.intersects(this);
}

From source file:com.datatorrent.demos.mobile.Application.java

@Override
public void populateDAG(DAG dag, Configuration conf) {
    String lPhoneRange = conf.get(PHONE_RANGE_PROP, null);
    if (lPhoneRange != null) {
        String[] tokens = lPhoneRange.split("-");
        if (tokens.length != 2) {
            throw new IllegalArgumentException("Invalid range: " + lPhoneRange);
        }//from   ww w . ja v a  2  s .c  o m
        this.phoneRange = Range.between(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]));
    }
    LOG.debug("Phone range {}", this.phoneRange);

    RandomEventGenerator phones = dag.addOperator("Receiver", RandomEventGenerator.class);
    phones.setMinvalue(this.phoneRange.getMinimum());
    phones.setMaxvalue(this.phoneRange.getMaximum());

    PhoneMovementGenerator movementGen = dag.addOperator("LocationFinder", PhoneMovementGenerator.class);
    dag.setAttribute(movementGen, OperatorContext.COUNTERS_AGGREGATOR,
            new BasicCounters.LongAggregator<MutableLong>());

    StatelessThroughputBasedPartitioner<PhoneMovementGenerator> partitioner = new StatelessThroughputBasedPartitioner<PhoneMovementGenerator>();
    partitioner.setCooldownMillis(conf.getLong(COOL_DOWN_MILLIS, 45000));
    partitioner.setMaximumEvents(conf.getLong(MAX_THROUGHPUT, 30000));
    partitioner.setMinimumEvents(conf.getLong(MIN_THROUGHPUT, 10000));
    dag.setAttribute(movementGen, OperatorContext.STATS_LISTENERS,
            Arrays.asList(new StatsListener[] { partitioner }));
    dag.setAttribute(movementGen, OperatorContext.PARTITIONER, partitioner);

    // generate seed numbers
    Random random = new Random();
    int maxPhone = phoneRange.getMaximum() - phoneRange.getMinimum();
    int phonesToDisplay = conf.getInt(TOTAL_SEED_NOS, 10);
    for (int i = phonesToDisplay; i-- > 0;) {
        int phoneNo = phoneRange.getMinimum() + random.nextInt(maxPhone + 1);
        LOG.info("seed no: " + phoneNo);
        movementGen.phoneRegister.add(phoneNo);
    }
    // done generating data
    LOG.info("Finished generating seed data.");

    String gatewayAddress = dag.getValue(DAG.GATEWAY_CONNECT_ADDRESS);
    URI uri = URI.create("ws://" + gatewayAddress + "/pubsub");
    PubSubWebSocketOutputOperator<Object> wsOut = dag.addOperator("LocationResults",
            new PubSubWebSocketOutputOperator<Object>());
    wsOut.setUri(uri);
    PubSubWebSocketInputOperator<Map<String, String>> wsIn = dag.addOperator("QueryLocation",
            new PubSubWebSocketInputOperator<Map<String, String>>());
    wsIn.setUri(uri);
    // default partitioning: first connected stream to movementGen will be partitioned
    dag.addStream("Phone-Data", phones.integer_data, movementGen.data);
    dag.addStream("Results", movementGen.locationQueryResult, wsOut.input);
    dag.addStream("Query", wsIn.outputPort, movementGen.phoneQuery);
}