Example usage for com.google.common.collect Range lowerEndpoint

List of usage examples for com.google.common.collect Range lowerEndpoint

Introduction

In this page you can find the example usage for com.google.common.collect Range lowerEndpoint.

Prototype

public C lowerEndpoint() 

Source Link

Document

Returns the lower endpoint of this range.

Usage

From source file:org.apache.drill.exec.store.AffinityCalculator.java

/**
 * For a given RowGroup, calculate how many bytes are available on each on drillbit endpoint
 *
 * @param rowGroup the RowGroup to calculate endpoint bytes for
 *///from   w w  w .jav a2  s .  c  om
public void setEndpointBytes(ParquetGroupScan.RowGroupInfo rowGroup) {
    Stopwatch watch = new Stopwatch();
    watch.start();
    String fileName = rowGroup.getPath();
    if (!blockMapMap.containsKey(fileName)) {
        buildBlockMap(fileName);
    }

    ImmutableRangeMap<Long, BlockLocation> blockMap = blockMapMap.get(fileName);
    HashMap<String, Long> hostMap = new HashMap<>();
    HashMap<DrillbitEndpoint, Long> endpointByteMap = new HashMap();
    long start = rowGroup.getStart();
    long end = start + rowGroup.getLength();
    Range<Long> rowGroupRange = Range.closedOpen(start, end);

    // Find submap of ranges that intersect with the rowGroup
    ImmutableRangeMap<Long, BlockLocation> subRangeMap = blockMap.subRangeMap(rowGroupRange);

    // Iterate through each block in this submap and get the host for the block location
    for (Map.Entry<Range<Long>, BlockLocation> block : subRangeMap.asMapOfRanges().entrySet()) {
        String[] hosts;
        Range<Long> blockRange = block.getKey();
        try {
            hosts = block.getValue().getHosts();
        } catch (IOException ioe) {
            throw new RuntimeException("Failed to get hosts for block location", ioe);
        }
        Range<Long> intersection = rowGroupRange.intersection(blockRange);
        long bytes = intersection.upperEndpoint() - intersection.lowerEndpoint();

        // For each host in the current block location, add the intersecting bytes to the corresponding endpoint
        for (String host : hosts) {
            DrillbitEndpoint endpoint = getDrillBitEndpoint(host);
            if (endpointByteMap.containsKey(endpoint)) {
                endpointByteMap.put(endpoint, endpointByteMap.get(endpoint) + bytes);
            } else {
                if (endpoint != null)
                    endpointByteMap.put(endpoint, bytes);
            }
        }
    }

    rowGroup.setEndpointBytes(endpointByteMap);
    rowGroup.setMaxBytes(endpointByteMap.size() > 0 ? Collections.max(endpointByteMap.values()) : 0);
    logger.debug("Row group ({},{}) max bytes {}", rowGroup.getPath(), rowGroup.getStart(),
            rowGroup.getMaxBytes());
    watch.stop();
    logger.debug("Took {} ms to set endpoint bytes", watch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:org.apache.brooklyn.location.jclouds.networking.SharedLocationSecurityGroupCustomizer.java

private Function<Range<Integer>, IpPermission> portRangeToPermission(
        final JcloudsLocationSecurityGroupCustomizer instance, final IpProtocol protocol) {
    return new Function<Range<Integer>, IpPermission>() {
        @Nullable//  ww  w  . ja  va 2s .c  om
        @Override
        public IpPermission apply(@Nullable Range<Integer> integerRange) {
            IpPermission extraPermission = IpPermission.builder().fromPort(integerRange.lowerEndpoint())
                    .toPort(integerRange.upperEndpoint()).ipProtocol(protocol)
                    .cidrBlock(instance.getBrooklynCidrBlock()).build();
            return extraPermission;
        }
    };
}

From source file:com.github.fge.grappa.buffers.LineCounter.java

public Position toPosition(@Tainted int index) {
    if (index < 0)
        throw new IllegalStateException();

    Range<Integer> range;

    // Edge case: unfortunately, we can get an illegal index
    if (index >= len) {
        range = lines.get(nrLines - 1);/*from  ww  w  .  j a  v a  2s.co m*/
        return new Position(nrLines, len - range.lowerEndpoint() + 1);
    }

    int lineNr = binarySearch(index);

    range = lines.get(lineNr);
    return new Position(lineNr + 1, index - range.lowerEndpoint() + 1);
}

From source file:com.github.fge.grappa.buffers.CharSequenceInputBuffer.java

@SuppressWarnings("AutoUnboxing")
@Override/*w ww .  j a v a  2  s .c  o  m*/
public IndexRange getLineRange(int lineNumber) {
    Range<Integer> range =
            //= Futures.getUnchecked(lineCounter)
            lineCounter.getLineRange(lineNumber);
    return new IndexRange(range.lowerEndpoint(), range.upperEndpoint());
}

From source file:org.pascani.dsl.dbmapper.databases.ElasticSearch.java

private Map<String, String> handle(ChangeEvent e) {
    Map<String, String> data = null;
    TaggedValue<Serializable> taggedValue = TaggedValue.instanceFrom(e.value(), Serializable.class);
    if (taggedValue.value() instanceof Number || taggedValue.value() instanceof Boolean
            || taggedValue.value() instanceof String) {
        data = toData(e, taggedValue.value(), taggedValue.tags());
    } else if (taggedValue.value() instanceof Range<?>) {
        Range<?> range = (Range<?>) taggedValue.value();
        Class<?> clazz = range.hasLowerBound() ? range.lowerEndpoint().getClass()
                : range.upperEndpoint().getClass();
        if (Number.class.isAssignableFrom(clazz)) {
            data = toData(e, taggedValue.value(), taggedValue.tags());
        } else {/* ww  w  .  jav a2s .co  m*/
            System.out.println("Not supported type " + clazz.getCanonicalName());
        }
    } else {
        System.out.println("Not supported type " + taggedValue.value().getClass().getCanonicalName());
    }
    return data;
}

From source file:com.github.parboiled1.grappa.backport.buffers.LineCounter.java

public Position toPosition(@Tainted final int index) {
    if (index < 0)
        throw new IllegalStateException();

    final Range<Integer> range;

    // Edge case: unfortunately, we can get an illegal index
    if (index >= len) {
        range = lines.get(nrLines - 1);//  www  . j a  v a  2  s  . c o  m
        return new Position(nrLines, len - range.lowerEndpoint() + 1);
    }

    final int lineNr = binarySearch(index);

    range = lines.get(lineNr);
    return new Position(lineNr + 1, index - range.lowerEndpoint() + 1);
}

From source file:eu.itesla_project.modules.histo.tools.HistoDbPrintVoltageRangeTool.java

@Override
public void run(CommandLine line) throws Exception {
    Interval interval = Interval.parse(line.getOptionValue("interval"));
    Path caseFile = Paths.get(line.getOptionValue("case-file"));
    Map<String, VoltageStats> ranges = new HashMap<>();

    Network network = Importers.loadNetwork(caseFile);
    if (network == null) {
        throw new RuntimeException("Case '" + caseFile + "' not found");
    }/*w  w w  .j av a2s .  c  om*/
    network.getStateManager().allowStateMultiThreadAccess(true);

    OfflineConfig config = OfflineConfig.load();
    try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create()) {
        Set<HistoDbAttributeId> attrIds = new LinkedHashSet<>();
        for (VoltageLevel vl : network.getVoltageLevels()) {
            attrIds.add(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.V));
        }
        HistoDbStats stats = histoDbClient.queryStats(attrIds, interval, HistoDbHorizon.SN, false);
        for (VoltageLevel vl : network.getVoltageLevels()) {
            HistoDbNetworkAttributeId attrId = new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.V);
            float min = stats.getValue(HistoDbStatsType.MIN, attrId, Float.NaN) / vl.getNominalV();
            float max = stats.getValue(HistoDbStatsType.MAX, attrId, Float.NaN) / vl.getNominalV();
            int count = (int) stats.getValue(HistoDbStatsType.COUNT, attrId, 0);
            VoltageStats vstats = new VoltageStats(Range.closed(min, max), count, vl.getNominalV());
            for (Generator g : vl.getGenerators()) {
                vstats.pmax += g.getMaxP();
            }
            ranges.put(vl.getId(), vstats);
        }
    }
    Table table = new Table(7, BorderStyle.CLASSIC_WIDE);
    table.addCell("ID");
    table.addCell("vnom");
    table.addCell("range");
    table.addCell("min");
    table.addCell("max");
    table.addCell("count");
    table.addCell("pmax");
    ranges.entrySet().stream().sorted((e1, e2) -> {
        VoltageStats stats1 = e1.getValue();
        VoltageStats stats2 = e2.getValue();
        Range<Float> r1 = stats1.range;
        Range<Float> r2 = stats2.range;
        float s1 = r1.upperEndpoint() - r1.lowerEndpoint();
        float s2 = r2.upperEndpoint() - r2.lowerEndpoint();
        return Float.compare(s1, s2);
    }).forEach(e -> {
        String vlId = e.getKey();
        VoltageStats stats = e.getValue();
        Range<Float> r = stats.range;
        float s = r.upperEndpoint() - r.lowerEndpoint();
        table.addCell(vlId);
        table.addCell(Float.toString(stats.vnom));
        table.addCell(Float.toString(s));
        table.addCell(Float.toString(r.lowerEndpoint()));
        table.addCell(Float.toString(r.upperEndpoint()));
        table.addCell(Integer.toString(stats.count));
        table.addCell(Float.toString(stats.pmax));
    });
    System.out.println(table.render());
}

From source file:com.rockhoppertech.music.series.time.TimeEvent.java

public boolean overlaps(TimeEvent te) {
    // boolean b = this.getRange().overlaps(te.getRange());
    boolean b = false;
    Range<Double> range1 = this.getOpenRange();
    Range<Double> range2 = te.getOpenRange();
    if (range1.contains(range2.lowerEndpoint()) || range1.contains(range2.upperEndpoint())) {
        b = true;/*from   w w w  .  j  a v  a 2s  .  c  om*/
    }

    logger.debug(String.format("overlaps %b %s %s", b, this.getOpenRange(), te.getOpenRange()));

    return b;
}

From source file:io.horizondb.model.core.blocks.AbstractDataBlock.java

/**
 * {@inheritDoc}//from w  w w .ja  v  a  2s  .co m
 */
@Override
public final RangeMap<Field, DataBlock> split(TimeSeriesDefinition definition) throws IOException {

    Range<Field> range = BlockHeaderUtils.getRange(getHeader());

    Range<Field> partitionRange = definition.getPartitionTimeRange(range.lowerEndpoint());

    if (partitionRange.contains(range.upperEndpoint())) {
        return ImmutableRangeMap.<Field, DataBlock>of(partitionRange, this);
    }

    TimeSeriesRecord[] records = definition.newRecords();

    ImmutableRangeMap.Builder<Field, DataBlock> builder = ImmutableRangeMap.builder();

    RecordAppender appender = new RecordAppender(definition, Buffers.getDefaultAllocator(), records);

    Field[] timestamps = new Field[records.length];
    for (int i = 0; i < timestamps.length; i++) {
        timestamps[i] = definition.newField(Record.TIMESTAMP_FIELD_NAME);
    }

    try (BinaryTimeSeriesRecordIterator iterator = new BinaryTimeSeriesRecordIterator(definition,
            singleton(this))) {

        while (iterator.hasNext()) {

            Record record = iterator.next();
            Field timestamp = timestamps[record.getType()];
            if (record.isDelta()) {
                timestamp.add(record.getField(Record.TIMESTAMP_FIELD_INDEX));
            } else {
                record.getField(Record.TIMESTAMP_FIELD_INDEX).copyTo(timestamp);
            }

            if (!partitionRange.contains(timestamp)) {

                builder.put(partitionRange, appender.getDataBlock());
                partitionRange = definition.getPartitionTimeRange(timestamp);
                appender = new RecordAppender(definition, Buffers.getDefaultAllocator(), records);
            }
            appender.append(record);
        }
        builder.put(partitionRange, appender.getDataBlock());
    }

    return builder.build();
}

From source file:org.robotframework.red.nattable.painter.RedTableTextPainter.java

private Stream<Range<Integer>> splitRangesForWrappedLabel(final int[] map, final String text,
        final Range<Integer> range) {
    final int lower = range.lowerEndpoint();
    final int upper = range.upperEndpoint() - 1;

    final int lowerEndpoint = map[lower] == -1 ? map[lower + 1] : map[lower];
    final int upperEndpoint = map[upper] == -1 ? map[upper - 1] : map[upper];
    final List<Range<Integer>> transformedRanges = new ArrayList<>();
    if (lowerEndpoint <= upperEndpoint) {
        final Matcher matcher = NEW_LINE_PATTERN.matcher(text.substring(lowerEndpoint, upperEndpoint + 1));

        int lastLower = lowerEndpoint;
        while (matcher.find()) {
            transformedRanges.add(Range.closedOpen(lastLower, matcher.start() + lowerEndpoint));
            lastLower = matcher.end() + lowerEndpoint;
        }//from  w  w w  .  j  a  v a  2 s  . c o  m
        transformedRanges.add(Range.closedOpen(lastLower, upperEndpoint + 1));
    }
    return transformedRanges.stream();
}