下面列出了怎么用com.google.common.collect.Range的API类实例代码及写法,或者点击链接到github查看源代码。
@SuppressWarnings("null")
@Override
public void setValue(Range<Double> value) {
if (value == null)
return;
String minValue;
String maxValue;
if (numberFormat != null) {
minValue = String.valueOf(numberFormat.format(value.lowerEndpoint()));
maxValue = String.valueOf(numberFormat.format(value.upperEndpoint()));
} else {
minValue = String.valueOf(value.lowerEndpoint());
maxValue = String.valueOf(value.upperEndpoint());
}
minTxtField.setText(minValue);
maxTxtField.setText(maxValue);
}
private void searchModifications(PeakListRow rows, double lipidIonMass, LipidIdentity lipid,
double[] lipidModificationMasses, Range<Double> mzTolModification) {
for (int j = 0; j < lipidModificationMasses.length; j++) {
if (mzTolModification.contains(lipidIonMass + (lipidModificationMasses[j]))) {
// Calc relativ mass deviation
double relMassDev = ((lipidIonMass + (lipidModificationMasses[j]) - rows.getAverageMZ())
/ (lipidIonMass + lipidModificationMasses[j])) * 1000000;
// Add row identity
rows.addPeakIdentity(new SimplePeakIdentity(lipid + " " + lipidModification[j]), false);
rows.setComment("Ionization: " + ionizationType.getAdduct() + " " + lipidModification[j]
+ ", Δ " + NumberFormat.getInstance().format(relMassDev) + " ppm");
logger.info("Found modified lipid: " + lipid.getName() + " " + lipidModification[j] + ", Δ "
+ NumberFormat.getInstance().format(relMassDev) + " ppm");
}
}
}
@DataProvider(name = "computeTimeRanges")
public Object[][] provideComputeTimeRanges() {
DateTime now = DateTime.now();
DateTime yesterday = now.minusDays(1);
List<Object[]> entries = new ArrayList<>();
entries.add(new Object[] {
null, yesterday, now, Collections.singletonList(Range.closedOpen(yesterday, now))
});
entries.add(new Object[] {
new TimeGranularity(1, TimeUnit.DAYS), yesterday, now,
Collections.singletonList(Range.closedOpen(yesterday, now))
});
entries.add(new Object[] {
new TimeGranularity(6, TimeUnit.HOURS), yesterday, now,
Arrays.asList(Range.closedOpen(yesterday, yesterday.plusHours(6)),
Range.closedOpen(yesterday.plusHours(6), yesterday.plusHours(12)),
Range.closedOpen(yesterday.plusHours(12), yesterday.plusHours(18)),
Range.closedOpen(yesterday.plusHours(18), yesterday.plusHours(24)))
});
return entries.toArray(new Object[entries.size()][]);
}
private Range<Calendar> extractRange(TimeUnitRange timeUnit, SqlKind comparison,
Calendar c) {
switch (comparison) {
case EQUALS:
return Range.closedOpen(round(c, timeUnit, true),
round(c, timeUnit, false));
case LESS_THAN:
return Range.lessThan(round(c, timeUnit, true));
case LESS_THAN_OR_EQUAL:
return Range.lessThan(round(c, timeUnit, false));
case GREATER_THAN:
return Range.atLeast(round(c, timeUnit, false));
case GREATER_THAN_OR_EQUAL:
return Range.atLeast(round(c, timeUnit, true));
default:
throw new AssertionError(comparison);
}
}
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);
}
}
@Test
public void consumeDataFromKinesis() throws ExecutionException, InterruptedException {
// given
final ChannelPosition startFrom = findCurrentPosition();
sendTestMessages(Range.closed(1, 10), "some payload");
// when
kinesisMessageLog.consumeUntil(
startFrom,
endOfChannel()
).get();
// then
assertThat(messages, not(empty()));
assertThat(messages, hasSize(10));
}
private String searchModifications(double searchedMass, double lipidIonMass, LipidIdentity lipid,
double[] lipidModificationMasses, Range<Double> mzTolModification) {
String lipidAnnoation = "";
for (int j = 0; j < lipidModificationMasses.length; j++) {
if (mzTolModification.contains(lipidIonMass + (lipidModificationMasses[j]))) {
// Calc relativ mass deviation
double relMassDev = ((lipidIonMass + (lipidModificationMasses[j]) - searchedMass)
/ (lipidIonMass + lipidModificationMasses[j])) * 1000000;
// Add row identity
lipidAnnoation = lipid + " " + ionizationType.getAdduct() + " " + lipidModification[j]
+ ", Δ " + NumberFormat.getInstance().format(relMassDev) + " ppm";
logger.info("Found modified lipid: " + lipid.getName() + " " + lipidModification[j] + ", Δ "
+ NumberFormat.getInstance().format(relMassDev) + " ppm");
}
}
return lipidAnnoation;
}
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
PGobject pgObject = (PGobject) rs.getObject(names[0]);
if (pgObject == null) {
return null;
}
String type = pgObject.getType();
String value = pgObject.getValue();
if("int4range".equals(type)) {
return integerRange(value);
} else if("int8range".equals(type)) {
return longRange(value);
} else if("numrange".equals(type)) {
return bigDecimalRange(value);
} else {
throw new IllegalStateException("The range type [" + type + "] is not supported!");
}
}
protected void updatePlayerLimits() {
int min = 0, max = 0;
for(Team team : getTeams()) {
min += team.getMinPlayers();
max += team.getMaxPlayers();
}
getMatch().setPlayerLimits(Range.closed(min, max));
}
protected Map<ParticipantId, Set<Range<Integer>>> getAndPrintAnnotations(PluggableMutableDocument document, SimpleAnnotationSet annotationSet) {
Map<ParticipantId, Set<Range<Integer>>> rangesPerParticipant = new HashMap<ParticipantId, Set<Range<Integer>>>();
Iterable<AnnotationInterval<Object>> intervals =
annotationSet.annotationIntervals(0, document.size(), CollectionUtils.newStringSet(WaveletContributions.ANNOTATION_KEY));
intervals.forEach(interval -> {
System.out.println("Interval ("+interval.start()+","+interval.end()+") ");
final Range<Integer> r = Range.closed(interval.start(), interval.end());
interval.annotations().each(new ProcV<Object>() {
@Override
public void apply(String key, Object value) {
if (value != null) {
ParticipantId p = (ParticipantId) value;
if (!rangesPerParticipant.containsKey(p)) {
rangesPerParticipant.put(p, new HashSet<Range<Integer>>());
}
Set<Range<Integer>> rangeSet = rangesPerParticipant.get(p);
rangeSet.add(r);
System.out.println("\t "+key+"="+value.toString());
}
}
});
});
return rangesPerParticipant;
}
public static <T extends Number & Comparable<T>> T parseNumber(Node node, String text, Class<T> type, Range<T> range) throws InvalidXMLException {
T value = parseNumber(node, text, type, true);
if(!range.contains(value)) {
throw new InvalidXMLException(value + " is not in the range " + range, node);
}
return value;
}
@Test
public void testAdd_oneFiniteInterval_secondEdgeValue_returnsOverflowInterval() throws Exception {
MutableDistribution distribution =
new MutableDistribution(CustomFitter.create(ImmutableSet.of(1.0, 5.0)));
distribution.add(5.0);
assertThat(distribution.intervalCounts())
.isEqualTo(
ImmutableRangeMap.<Double, Long>builder()
.put(Range.lessThan(1.0), 0L)
.put(Range.closedOpen(1.0, 5.0), 0L)
.put(Range.atLeast(5.0), 1L)
.build());
}
public RawDataFileImpl(String dataFileName) throws IOException {
this.dataFileName = dataFileName;
// Prepare the hashtables for scan numbers and data limits.
scanNumbersCache = new Hashtable<Integer, int[]>();
dataMZRange = new Hashtable<Integer, Range<Double>>();
dataRTRange = new Hashtable<Integer, Range<Double>>();
dataMaxBasePeakIntensity = new Hashtable<Integer, Double>();
dataMaxTIC = new Hashtable<Integer, Double>();
scans = new Hashtable<Integer, StorableScan>();
dataPointsOffsets = new TreeMap<Integer, Long>();
dataPointsLengths = new TreeMap<Integer, Integer>();
}
/** Tree unfolding algorithm wrapper */
public static ArrayList<Range<Integer>> unfoldTree(final FoldableTree tree, final GreedyUnfoldAlgorithm algorithm,
final boolean debug) {
int count = -1;
// Store unfolded node ranges
final ArrayList<Range<Integer>> folds = Lists.newArrayList();
// Initialize optionsOP (stores unfolded nodes/terms)
algorithm.init(tree);
HashSet<Range<Integer>> rangeSet = null;
do {
count++;
if (debug)
System.out.println("===== " + algorithm.getClass().getName() + " Step " + count + " starting...\n");
rangeSet = algorithm.unfold(tree, debug);
if (rangeSet != null)
folds.addAll(rangeSet);
if (debug)
System.out.println("===== " + algorithm.getClass().getName() + " Step " + count + " done, new budget: "
+ tree.getBudget());
} while (rangeSet != null);
// printRandomlyBrokenTies();
return folds;
}
ProductIonFilterDataSet(RawDataFile rawDataFile, Object xAxisType, Range<Double> rtRange,
Range<Double> mzRange, ProductIonFilterVisualizerWindow visualizer, MZTolerance mzDifference,
List<Double> targetedMZ_List, List<Double> targetedNF_List, Double basePeakPercent,
File fileName) {
this.rawDataFile = rawDataFile;
totalMZRange = mzRange;
this.xAxisType = xAxisType;
this.visualizer = visualizer;
// mzDifference is maximum difference allowed between selected product
// m/z values and scan m/z
// value
this.mzDifference = mzDifference;
this.targetedMZ_List = targetedMZ_List;
this.targetedNF_List = targetedNF_List;
// output filename
this.fileName = fileName;
// Percent of base peak of which product ions must be above in order to
// include in analysis
this.basePeakPercent = basePeakPercent / 100;
// get MS/MS scans
scanNumbers = rawDataFile.getScanNumbers(2, rtRange);
totalScans = scanNumbers.length;
dataSeries = new HashMap<Integer, Vector<ProductIonFilterDataPoint>>();
dataSeries.put(RAW_LEVEL, new Vector<ProductIonFilterDataPoint>(totalScans));
dataSeries.put(PRECURSOR_LEVEL, new Vector<ProductIonFilterDataPoint>(totalScans));
dataSeries.put(NEUTRALLOSS_LEVEL, new Vector<ProductIonFilterDataPoint>(totalScans));
}
private static TimeInterval encodeTimeInterval(Range<Instant> nativeInterval, Kind metricKind) {
TimeInterval encodedInterval =
new TimeInterval().setStartTime(nativeInterval.lowerEndpoint().toString());
Instant endTimestamp =
nativeInterval.isEmpty() && metricKind != Kind.GAUGE
? nativeInterval.upperEndpoint().plusMillis(1)
: nativeInterval.upperEndpoint();
return encodedInterval.setEndTime(endTimestamp.toString());
}
/**
* subrange - allocate new subcolors to this range of chars, fill in arcs.
* The range will overlap existing ranges; even in the simplest case,
* it will overlap the initial WHITE range. For each existing range that
* it overlaps, allocate a new color, mark the range as mapping to that color,
* and add an arc between the states for that color.
*/
void subrange(int from, int to, State lp, State rp) throws RegexException {
/* Avoid one call to map.get() for each character in the range.
* This map will usually contain one item, but in complex cases more.
* For example, if we had [a-f][g-h] and then someone asked for [f-g], there
* would be two. Each of these new ranges will get a new color via subcolor.
*/
Map<Range<Integer>, Short> curColors = map.subRangeMap(Range.closed(from, to)).asMapOfRanges();
/*
* To avoid concurrent mod problems, we need to copy the ranges we are working from.
*/
List<Range<Integer>> ranges = Lists.newArrayList(curColors.keySet());
for (Range<Integer> rangeToProcess : ranges) {
// bound management here irritating.
int start = rangeToProcess.lowerEndpoint();
if (rangeToProcess.lowerBoundType() == BoundType.OPEN) {
start++;
}
int end = rangeToProcess.upperEndpoint();
if (rangeToProcess.upperBoundType() == BoundType.CLOSED) {
end++;
}
// allocate a new subcolor and account it owning the entire range.
short color = subcolor(start, end - start);
compiler.getNfa().newarc(Compiler.PLAIN, color, lp, rp);
}
}
MsMsDataSet(RawDataFile rawDataFile, Range<Double> rtRange, Range<Double> mzRange,
IntensityType intensityType, NormalizationType normalizationType, Double minPeakInt,
MsMsVisualizerWindow visualizer) {
this.rawDataFile = rawDataFile;
totalRTRange = rtRange;
totalMZRange = mzRange;
this.intensityType = intensityType;
this.normalizationType = normalizationType;
this.minPeakInt = minPeakInt - EPSILON;
allScanNumbers = rawDataFile.getScanNumbers();
msmsScanNumbers = rawDataFile.getScanNumbers(2, rtRange);
totalScans = allScanNumbers.length;
totalmsmsScans = msmsScanNumbers.length;
totalEntries = totalmsmsScans;
scanNumbers = new int[totalScans];
rtValues = new double[totalmsmsScans];
mzValues = new double[totalmsmsScans];
intensityValues = new double[totalmsmsScans];
colorValues = new Color[totalmsmsScans];
MZmineCore.getTaskController().addTask(this, TaskPriority.HIGH);
}
@Override
public Collection<String> doBetweenSharding(final Collection<String> dataSourceNames, final ShardingValue<Integer> shardingValue) {
Collection<String> result = new LinkedHashSet<>(dataSourceNames.size());
Range<Integer> range = shardingValue.getValueRange();
for (Integer value = range.lowerEndpoint(); value <= range.upperEndpoint(); value++) {
for (String each : dataSourceNames) {
if (each.endsWith(value % 2 + "")) {
result.add(each);
}
}
}
return result;
}
@Override
public Collection<String> doBetweenSharding(final Collection<String> availableTargetNames, final ShardingValue<Long> shardingValue) {
Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
Range<Long> range = shardingValue.getValueRange();
for (Long value = range.lowerEndpoint(); value <= range.upperEndpoint(); value++) {
for (String each : availableTargetNames) {
if (each.endsWith(value % 2 + "")) {
result.add(each);
}
}
}
return result;
}
@Override
public ImmutableList<Long> getSortedIds(boolean unused) {
return ImmutableList.copyOf(
ContiguousSet.create(
Range.open(-1, remotelyBuildingTargets.size()), DiscreteDomain.integers())
.stream()
.map(i -> Long.valueOf(i))
.collect(Collectors.toList()));
}
@Test
public void testJobUptimeLiveNonTerminalIgnored() {
long now = System.currentTimeMillis();
Set<IScheduledTask> instances = makeUptimeTasks(100, now);
instances.add(makeTask(ImmutableMap.of(now - 5000, RUNNING, now - 3000, RESTARTING)));
Number actual = JOB_UPTIME_99.getAlgorithm().calculate(instances, Range.closed(0L, now));
assertEquals(1.99, actual);
}
@Override
public Range<Double> attenuationRange(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) {
checkNotNull(deviceId);
checkNotNull(portNumber);
checkNotNull(ochSignal);
PowerConfig<Object> powerConfig = getPowerConfig(deviceId);
if (powerConfig != null) {
Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, ochSignal);
if (range.isPresent()) {
return range.get();
}
}
return null;
}
public DoubleRangeParameter(@Nonnull String name, @Nonnull String description,
@Nonnull String category, @Nullable NumberFormat numberFormat,
@Nullable ParameterValidator<Range<Double>> validator, @Nullable Range<Double> defaultValue) {
super(name, description, category, DoubleRangeEditor.class, validator);
setValue(defaultValue);
this.numberFormat = numberFormat;
}
@Test
public void testAddScalarReadingLimits() {
SensorDatabaseImpl db =
new SensorDatabaseImpl(getContext(), getAppAccount(), TEST_DATABASE_NAME);
db.addScalarReading("id", "tag", 0, 1, 1.0);
db.addScalarReading("id", "tag", 0, 2, 2.0);
db.addScalarReading("id", "tag", 0, 3, 3.0);
int limit = 2;
List<ScalarReading> readings =
ScalarReading.slurp(
db.getScalarReadings("id", "tag", TimeRange.oldest(Range.closed(0L, 4L)), 0, limit));
assertEquals(Arrays.asList(new ScalarReading(1, 1.0), new ScalarReading(2, 2.0)), readings);
}
@Test
public void google_guava_range_map_example () {
RangeMap<Integer, String> gradeScale = TreeRangeMap.create();
gradeScale.put(Range.closed(0, 60), "F");
gradeScale.put(Range.closed(61, 70), "D");
gradeScale.put(Range.closed(71, 80), "C");
gradeScale.put(Range.closed(81, 90), "B");
gradeScale.put(Range.closed(91, 100), "A");
String grade = gradeScale.get(77);
assertEquals("C", grade);
}
/**
*
* @param row The row.
* @return The average retention time range of all features contained in this peak list row across
* all raw data files. Empty range (0,0) if the row is null or has no feature assigned to
* it.
*/
public @Nonnull static Range<Double> getPeakListRowAvgRtRange(PeakListRow row) {
if (row == null || row.getBestPeak() == null)
return Range.closed(0.d, 0.d);
int size = row.getPeaks().length;
double[] lower = new double[size];
double[] upper = new double[size];
Feature[] f = row.getPeaks();
for (int i = 0; i < size; i++) {
if (f[i] == null)
continue;
Range<Double> r = f[i].getRawDataPointsRTRange();
lower[i] = r.lowerEndpoint();
upper[i] = r.upperEndpoint();
}
double avgL = 0, avgU = 0;
for (int i = 0; i < size; i++) {
avgL += lower[i];
avgU += upper[i];
}
avgL /= size;
avgU /= size;
return Range.closed(avgL, avgU);
}
@Override
public Range<Double> targetPortPowerRange(DeviceId deviceId, PortNumber portNumber) {
checkNotNull(deviceId);
checkNotNull(portNumber);
PowerConfig<Object> powerConfig = getPowerConfig(deviceId);
if (powerConfig != null) {
Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL);
if (range.isPresent()) {
return range.get();
}
}
return null;
}
private static <C extends Number & Comparable<C>> List<ValueRange> ensureResolvedRanges(
final List<ValueRange> unresolved, final Range<C> baseRange) {
// First check if we need to resolve anything at all
for (ValueRange c : unresolved) {
if (c.lowerBound() instanceof UnresolvedNumber || c.upperBound() instanceof UnresolvedNumber) {
return resolveRanges(unresolved, baseRange);
}
}
// No need, just return the same list
return unresolved;
}
public ScanSelection(Range<Integer> scanNumberRange, Integer baseFilteringInteger,
Range<Double> scanRTRange, PolarityType polarity, MassSpectrumType spectrumType,
Integer msLevel, String scanDefinition) {
this.scanNumberRange = scanNumberRange;
this.baseFilteringInteger = baseFilteringInteger;
this.scanRTRange = scanRTRange;
this.polarity = polarity;
this.spectrumType = spectrumType;
this.msLevel = msLevel;
this.scanDefinition = scanDefinition;
}