use of org.apache.commons.lang3.Range in project neo4j by neo4j.
the class GBPTreeIT method shouldStayCorrectAfterRandomModifications.
@Test
public void shouldStayCorrectAfterRandomModifications() throws Exception {
// GIVEN
GBPTree<MutableLong, MutableLong> index = createIndex(256);
Comparator<MutableLong> keyComparator = layout;
Map<MutableLong, MutableLong> data = new TreeMap<>(keyComparator);
int count = 100;
int totalNumberOfRounds = 10;
for (int i = 0; i < count; i++) {
data.put(randomKey(random.random()), randomKey(random.random()));
}
// WHEN
try (Writer<MutableLong, MutableLong> writer = index.writer()) {
for (Map.Entry<MutableLong, MutableLong> entry : data.entrySet()) {
writer.put(entry.getKey(), entry.getValue());
}
}
for (int round = 0; round < totalNumberOfRounds; round++) {
// THEN
for (int i = 0; i < count; i++) {
MutableLong first = randomKey(random.random());
MutableLong second = randomKey(random.random());
MutableLong from, to;
if (first.longValue() < second.longValue()) {
from = first;
to = second;
} else {
from = second;
to = first;
}
Map<MutableLong, MutableLong> expectedHits = expectedHits(data, from, to, keyComparator);
try (RawCursor<Hit<MutableLong, MutableLong>, IOException> result = index.seek(from, to)) {
while (result.next()) {
MutableLong key = result.get().key();
if (expectedHits.remove(key) == null) {
fail("Unexpected hit " + key + " when searching for " + from + " - " + to);
}
assertTrue(keyComparator.compare(key, from) >= 0);
assertTrue(keyComparator.compare(key, to) < 0);
}
if (!expectedHits.isEmpty()) {
fail("There were results which were expected to be returned, but weren't:" + expectedHits + " when searching range " + from + " - " + to);
}
}
}
index.checkpoint(IOLimiter.unlimited());
randomlyModifyIndex(index, data, random.random(), (double) round / totalNumberOfRounds);
}
}
use of org.apache.commons.lang3.Range in project neo4j by neo4j.
the class InternalTreeLogicTest method mustPropagateAllStructureChanges.
@Test
public void mustPropagateAllStructureChanges() throws Exception {
assumeTrue("No checkpointing, no successor", isCheckpointing);
//given
initialize();
long key = 10;
while (numberOfRootSplits == 0) {
insert(key, key);
key++;
}
// ... enough keys in left child to share with right child if rebalance is needed
for (long smallKey = 0; smallKey < 2; smallKey++) {
insert(smallKey, smallKey);
}
// ... and the prim key dividing key range for left and right child
goTo(readCursor, rootId);
long oldPrimKey = keyAt(0);
// ... and left and right child
long originalLeftChild = childAt(readCursor, 0, stableGeneration, unstableGeneration);
long originalRightChild = childAt(readCursor, 1, stableGeneration, unstableGeneration);
goTo(readCursor, originalRightChild);
List<Long> keysInRightChild = allKeys(readCursor);
// when
// ... after checkpoint
generationManager.checkpoint();
// ... removing keys from right child until rebalance is triggered
int index = 0;
long rightChild;
long leftmostInRightChild;
do {
remove(keysInRightChild.get(index), readValue);
index++;
goTo(readCursor, rootId);
rightChild = childAt(readCursor, 1, stableGeneration, unstableGeneration);
goTo(readCursor, rightChild);
leftmostInRightChild = keyAt(0);
} while (leftmostInRightChild >= keysInRightChild.get(0));
// then
// ... primKey in root is updated
goTo(readCursor, rootId);
Long primKey = keyAt(0);
assertThat(primKey, is(leftmostInRightChild));
assertThat(primKey, is(not(oldPrimKey)));
// ... new versions of left and right child
long newLeftChild = childAt(readCursor, 0, stableGeneration, unstableGeneration);
long newRightChild = childAt(readCursor, 1, stableGeneration, unstableGeneration);
assertThat(newLeftChild, is(not(originalLeftChild)));
assertThat(newRightChild, is(not(originalRightChild)));
}
use of org.apache.commons.lang3.Range in project intellij-plugins by JetBrains.
the class DartServerCompletionContributor method createLookupElement.
private static LookupElement createLookupElement(@NotNull final Project project, @NotNull final CompletionSuggestion suggestion) {
final Element element = suggestion.getElement();
final Location location = element == null ? null : element.getLocation();
final DartLookupObject lookupObject = new DartLookupObject(project, location);
final String lookupString = suggestion.getCompletion();
LookupElementBuilder lookup = LookupElementBuilder.create(lookupObject, lookupString);
// keywords are bold
if (suggestion.getKind().equals(CompletionSuggestionKind.KEYWORD)) {
lookup = lookup.bold();
}
final int dotIndex = lookupString.indexOf('.');
if (dotIndex > 0 && dotIndex < lookupString.length() - 1 && StringUtil.isJavaIdentifier(lookupString.substring(0, dotIndex)) && StringUtil.isJavaIdentifier(lookupString.substring(dotIndex + 1))) {
// 'path.Context' should match 'Conte' prefix
lookup = lookup.withLookupString(lookupString.substring(dotIndex + 1));
}
boolean shouldSetSelection = true;
if (element != null) {
// @deprecated
if (element.isDeprecated()) {
lookup = lookup.strikeout();
}
// append type parameters
final String typeParameters = element.getTypeParameters();
if (typeParameters != null) {
lookup = lookup.appendTailText(typeParameters, false);
}
// append parameters
final String parameters = element.getParameters();
if (parameters != null) {
lookup = lookup.appendTailText(parameters, false);
}
// append return type
final String returnType = element.getReturnType();
if (!StringUtils.isEmpty(returnType)) {
lookup = lookup.withTypeText(returnType, true);
}
// icon
Icon icon = getBaseImage(element);
if (icon != null) {
icon = applyVisibility(icon, element.isPrivate());
icon = applyOverlay(icon, element.isFinal(), AllIcons.Nodes.FinalMark);
icon = applyOverlay(icon, element.isConst(), AllIcons.Nodes.FinalMark);
lookup = lookup.withIcon(icon);
}
// Prepare for typing arguments, if any.
if (CompletionSuggestionKind.INVOCATION.equals(suggestion.getKind())) {
shouldSetSelection = false;
final List<String> parameterNames = suggestion.getParameterNames();
if (parameterNames != null) {
lookup = lookup.withInsertHandler((context, item) -> {
// like in JavaCompletionUtil.insertParentheses()
final boolean needRightParenth = CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET || parameterNames.isEmpty() && context.getCompletionChar() != '(';
if (parameterNames.isEmpty()) {
final ParenthesesInsertHandler<LookupElement> handler = ParenthesesInsertHandler.getInstance(false, false, false, needRightParenth, false);
handler.handleInsert(context, item);
} else {
final ParenthesesInsertHandler<LookupElement> handler = ParenthesesInsertHandler.getInstance(true, false, false, needRightParenth, false);
handler.handleInsert(context, item);
// Show parameters popup.
final Editor editor = context.getEditor();
final PsiElement psiElement = lookupObject.getElement();
if (DartCodeInsightSettings.getInstance().INSERT_DEFAULT_ARG_VALUES) {
// Insert argument defaults if provided.
final String argumentListString = suggestion.getDefaultArgumentListString();
if (argumentListString != null) {
final Document document = editor.getDocument();
int offset = editor.getCaretModel().getOffset();
// At this point caret is expected to be right after the opening paren.
// But if user was completing using Tab over the existing method call with arguments then old arguments are still there,
// if so, skip inserting argumentListString
final CharSequence text = document.getCharsSequence();
if (text.charAt(offset - 1) == '(' && text.charAt(offset) == ')') {
document.insertString(offset, argumentListString);
PsiDocumentManager.getInstance(project).commitDocument(document);
final TemplateBuilderImpl builder = (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(context.getFile());
final int[] ranges = suggestion.getDefaultArgumentListTextRanges();
// Only proceed if ranges are provided and well-formed.
if (ranges != null && (ranges.length & 1) == 0) {
int index = 0;
while (index < ranges.length) {
final int start = ranges[index];
final int length = ranges[index + 1];
final String arg = argumentListString.substring(start, start + length);
final TextExpression expression = new TextExpression(arg);
final TextRange range = new TextRange(offset + start, offset + start + length);
index += 2;
builder.replaceRange(range, "group_" + (index - 1), expression, true);
}
builder.run(editor, true);
}
}
}
}
AutoPopupController.getInstance(project).autoPopupParameterInfo(editor, psiElement);
}
});
}
}
}
// Use selection offset / length.
if (shouldSetSelection) {
lookup = lookup.withInsertHandler((context, item) -> {
final Editor editor = context.getEditor();
final int startOffset = context.getStartOffset() + suggestion.getSelectionOffset();
final int endOffset = startOffset + suggestion.getSelectionLength();
editor.getCaretModel().moveToOffset(startOffset);
if (endOffset > startOffset) {
editor.getSelectionModel().setSelection(startOffset, endOffset);
}
});
}
return PrioritizedLookupElement.withPriority(lookup, suggestion.getRelevance());
}
use of org.apache.commons.lang3.Range in project gatk by broadinstitute.
the class CoverageModelEMWorkspace method getViterbiAsNDArray.
/**
* Fetches the Viterbi copy ratio (or copy number) states as a target-sample matrix
*
* @return an {@link INDArray}
*/
protected INDArray getViterbiAsNDArray(final List<List<HiddenStateSegmentRecord<STATE, Target>>> segments) {
final INDArray res = Nd4j.create(numSamples, numTargets);
final TargetCollection<Target> targetCollection = new HashedListTargetCollection<>(processedTargetList);
for (int si = 0; si < numSamples; si++) {
final SexGenotypeData sampleSexGenotype = processedSampleSexGenotypeData.get(si);
/* start with all ref */
final double[] calls = IntStream.range(0, numTargets).mapToDouble(ti -> referenceStateFactory.apply(sampleSexGenotype, processedTargetList.get(ti)).getScalar()).toArray();
/* go through segments and mutate ref calls as necessary */
segments.get(si).forEach(seg -> {
final IndexRange range = targetCollection.indexRange(seg.getSegment());
final double copyRatio = seg.getSegment().getCall().getScalar();
for (int ti = range.from; ti < range.to; ti++) {
calls[ti] = copyRatio;
}
});
res.get(NDArrayIndex.point(si), NDArrayIndex.all()).assign(Nd4j.create(calls, new int[] { 1, numTargets }));
}
return res.transpose();
}
use of org.apache.commons.lang3.Range in project RecurrentComplex by Ivorforce.
the class FactorMatch method consider.
@Override
public List<Pair<LineSelection, Float>> consider(WorldCache cache, LineSelection considerable, @Nullable IvBlockCollection blockCollection, StructurePlaceContext context) {
if (blockCollection == null)
throw new IllegalArgumentException("Missing a block collection!");
List<Pair<LineSelection, Float>> consideration = new ArrayList<>();
int[] size = StructureBoundingBoxes.size(context.boundingBox);
BlockPos lowerCoord = StructureBoundingBoxes.min(context.boundingBox);
Set<BlockPos.MutableBlockPos> sources = BlockAreas.streamMutablePositions(blockCollection.area()).filter(p -> sourceMatcher.evaluate(() -> blockCollection.getBlockState(p))).map(p -> new BlockPos.MutableBlockPos(context.transform.apply(p, size).add(lowerCoord.getX(), 0, lowerCoord.getZ()))).collect(Collectors.toSet());
for (IntegerRange range : (Iterable<IntegerRange>) considerable.streamSections(null, true)::iterator) {
Float curConformity = null;
int lastY = range.getMax();
int end = range.getMin();
for (int y = lastY; y >= end; y--) {
int finalY = y;
sources.forEach(p -> p.move(EnumFacing.UP, finalY));
float conformity = weight(cache, sources, requiredConformity);
sources.forEach(p -> p.move(EnumFacing.DOWN, finalY));
if (curConformity == null) {
curConformity = conformity;
lastY = y;
} else if (!DoubleMath.fuzzyEquals(conformity, curConformity, 0.01)) {
consideration.add(Pair.of(LineSelection.fromRange(IntegerRanges.from(lastY, y + 1), true), weight(curConformity)));
curConformity = conformity;
lastY = y;
}
}
if (curConformity != null)
consideration.add(Pair.of(LineSelection.fromRange(IntegerRanges.from(lastY, end), true), weight(curConformity)));
}
return consideration;
}
Aggregations