Java Code Examples for org.apache.commons.lang3.mutable.MutableInt#increment()

The following examples show how to use org.apache.commons.lang3.mutable.MutableInt#increment() . 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: AbstractStreamPatternMatcher.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public void process(T t)
{
  if (pattern.checkState(t, 0)) {
    partialMatches.add(new MutableInt(-1));
  }
  if (partialMatches.size() > 0) {
    MutableInt tempInt;
    Iterator<MutableInt> itr = partialMatches.iterator();
    while (itr.hasNext()) {
      tempInt = itr.next();
      tempInt.increment();
      if (!pattern.checkState(t, tempInt.intValue())) {
        itr.remove();
      } else if (tempInt.equals(patternLength)) {
        itr.remove();
        processPatternFound();
      }
    }
  }
}
 
Example 2
Source File: TestDataInterface.java    From count-db with MIT License 6 votes vote down vote up
@Test
public void testValuesIteratorWithFilter() {
    DataInterface<Long> dataInterface = createCountDataInterface("testValuesIteratorWithFilter");
    int numOfItems = 100;
    for (int i = 0; i < 100; i++) {
        dataInterface.write(i, (long) i);
    }
    dataInterface.flush();
    //Try with stream
    MutableInt numOfValuesRead = new MutableInt();
    dataInterface.streamValues(new EvenKeysFilter()).forEach((v) -> numOfValuesRead.increment());
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
    //Try with iterator
    numOfValuesRead.setValue(0);
    CloseableIterator<Long> closeableIterator = dataInterface.valueIterator(new EvenKeysFilter());
    while (closeableIterator.hasNext()) {
        closeableIterator.next();
        numOfValuesRead.increment();
    }
    closeableIterator.close();
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
}
 
Example 3
Source File: BulkLoadHFilesTool.java    From hbase with Apache License 2.0 6 votes vote down vote up
private boolean checkHFilesCountPerRegionPerFamily(
    final Multimap<ByteBuffer, LoadQueueItem> regionGroups) {
  for (Map.Entry<ByteBuffer, Collection<LoadQueueItem>> e : regionGroups.asMap().entrySet()) {
    Map<byte[], MutableInt> filesMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
    for (LoadQueueItem lqi : e.getValue()) {
      MutableInt count = filesMap.computeIfAbsent(lqi.getFamily(), k -> new MutableInt());
      count.increment();
      if (count.intValue() > maxFilesPerRegionPerFamily) {
        LOG.error("Trying to load more than " + maxFilesPerRegionPerFamily +
          " hfiles to family " + Bytes.toStringBinary(lqi.getFamily()) +
          " of region with start key " + Bytes.toStringBinary(e.getKey()));
        return false;
      }
    }
  }
  return true;
}
 
Example 4
Source File: GraphStrategy.java    From sqlg with MIT License 6 votes vote down vote up
@Override
protected boolean doFirst(ListIterator<Step<?, ?>> stepIterator, Step<?, ?> step, MutableInt pathCount) {
    this.currentReplacedStep = ReplacedStep.from(
            this.sqlgGraph.getTopology(),
            (AbstractStep<?, ?>) step,
            pathCount.getValue()
    );
    handleHasSteps(stepIterator, pathCount.getValue());
    handleOrderGlobalSteps(stepIterator, pathCount);
    handleRangeGlobalSteps(stepIterator, pathCount);
    handleConnectiveSteps(stepIterator);
    this.sqlgStep = constructSqlgStep(step);
    this.currentTreeNodeNode = this.sqlgStep.addReplacedStep(this.currentReplacedStep);
    replaceStepInTraversal(step, this.sqlgStep);
    if (this.sqlgStep instanceof SqlgGraphStep && ((SqlgGraphStep) this.sqlgStep).getIds().length > 0) {
        addHasContainerForIds((SqlgGraphStep) this.sqlgStep);
    }
    if (!this.currentReplacedStep.hasLabels()) {
        boolean precedesPathStep = precedesPathOrTreeStep(this.traversal);
        if (precedesPathStep) {
            this.currentReplacedStep.addLabel(pathCount.getValue() + BaseStrategy.PATH_LABEL_SUFFIX + BaseStrategy.SQLG_PATH_FAKE_LABEL);
        }
    }
    pathCount.increment();
    return true;
}
 
Example 5
Source File: CharacterFootprintTermFilter.java    From termsuite-core with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param anno the word anno
 * @param badChars the bad char counter. Being incremented
 * @return true if the word has one bad char, false otherwise
 */
private boolean isBadWord(WordAnnotation anno, MutableInt badChars) {
	final String coveredText = anno.getCoveredText();
	boolean foundOneBadChar = false;
	for(int i=0; i< coveredText.length(); i++) {
		boolean found = false;
		char c = coveredText.charAt(i);
		for(char a:this.allowedChars) {
			if(a==c) 
				found = true;
		}
		if(!found) {
			badChars.increment();
			foundOneBadChar = true;
		}
	}
	return foundOneBadChar;
}
 
Example 6
Source File: TestDataInterface.java    From count-db with MIT License 6 votes vote down vote up
@Test
public void testIteratorWithFilter() {
    DataInterface<Long> dataInterface = createCountDataInterface("testIteratorWithFilter");
    int numOfItems = 100;
    for (int i = 0; i < 100; i++) {
        dataInterface.write(i, (long) i);
    }
    dataInterface.flush();
    //Try with stream
    MutableInt numOfValuesRead = new MutableInt();
    dataInterface.stream(new EvenKeysFilter()).forEach((v) -> numOfValuesRead.increment());
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
    //Try with iterator
    numOfValuesRead.setValue(0);
    CloseableIterator<KeyValue<Long>> closeableIterator = dataInterface.iterator(new EvenKeysFilter());
    while (closeableIterator.hasNext()) {
        closeableIterator.next();
        numOfValuesRead.increment();
    }
    closeableIterator.close();
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
}
 
Example 7
Source File: JavaScriptJobManagerMinimalTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void addJob_multipleExecution_removeAllJobs() throws Exception {
    final MutableInt count = new MutableInt(0);
    final JavaScriptJob job = new BasicJavaScriptJob(50, Integer.valueOf(50)) {
        @Override
        public void run() {
            count.increment();
            if (count.intValue() >= 5) {
                manager_.removeAllJobs();
            }
        }
    };
    manager_.addJob(job, page_);
    manager_.waitForJobs(1000);
    assertEquals(5, count.intValue());
}
 
Example 8
Source File: JavaScriptJobManagerMinimalTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Didn't pass reliably.
 * @throws Exception if an error occurs
 */
@Test
public void addJob_periodicJob() throws Exception {
    final MutableInt count = new MutableInt(0);
    final JavaScriptJob job = new BasicJavaScriptJob(5, Integer.valueOf(100)) {
        @Override
        public void run() {
            count.increment();
        }
    };
    manager_.addJob(job, page_);
    assertEquals(1, manager_.getJobCount());
    final int remainingJobs = manager_.waitForJobs(1090);
    assertTrue("At least one remaining job expected.", remainingJobs >= 1);
    assertTrue("Less than 10 jobs (" + count.intValue() + ") processed.", count.intValue() >= 10);
}
 
Example 9
Source File: VariantAnnotator.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private AlleleLikelihoods<GATKRead, Allele> makeLikelihoods(final VariantContext vc, final ReadsContext readsContext) {
    final List<GATKRead> reads = Utils.stream(readsContext).collect(Collectors.toList());
    final AlleleLikelihoods<GATKRead, Allele> result = new AlleleLikelihoods<>(variantSamples,
            new IndexedAlleleList<>(vc.getAlleles()), AssemblyBasedCallerUtils.splitReadsBySample(variantSamples, getHeaderForReads(), reads));

    final ReadPileup readPileup = new ReadPileup(vc, readsContext);
    final Map<String, ReadPileup> pileupsBySample = readPileup.splitBySample(getHeaderForReads(), "__UNKNOWN__");

    final Allele refAllele = vc.getReference();
    final List<Allele> altAlleles = vc.getAlternateAlleles();
    final int numAlleles = vc.getNAlleles();

    // manually fill each sample's likelihoods one read at a time, assigning probability 1 (0 in log space) to the matching allele, if present
    for (final Map.Entry<String, ReadPileup> samplePileups : pileupsBySample.entrySet()) {
        final LikelihoodMatrix<GATKRead, Allele> sampleMatrix = result.sampleMatrix(result.indexOfSample(samplePileups.getKey()));

        final MutableInt readIndex = new MutableInt(0);
        for (final PileupElement pe : samplePileups.getValue()) {
            // initialize all alleles as equally unlikely
            IntStream.range(0, numAlleles).forEach(a -> sampleMatrix.set(a, readIndex.intValue(), Double.NEGATIVE_INFINITY));

            // if present set the matching allele as likely
            final Allele pileupAllele = GATKVariantContextUtils.chooseAlleleForRead(pe, refAllele, altAlleles, minBaseQualityScore);
            if (pileupAllele != null) {
                sampleMatrix.set(sampleMatrix.indexOfAllele(pileupAllele), readIndex.intValue(), 0);
            }


            readIndex.increment();
        }
    }

    return result;
}
 
Example 10
Source File: AllelicPanelOfNormalsCreator.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates an {@link AllelicPanelOfNormals} given a site-frequency threshold;
 * sites appearing in strictly less than this fraction of samples will not be included in the panel of normals.
 * @param siteFrequencyThreshold    site-frequency threshold
 * @return                          an {@link AllelicPanelOfNormals} containing sites
 *                                  above the site-frequency threshold
 */
public AllelicPanelOfNormals create(final double siteFrequencyThreshold) {
    logger.info("Creating allelic panel of normals...");
    final Map<SimpleInterval, MutableInt> numberOfSamplesMap = new HashMap<>(); //used to filter on frequency
    final Map<SimpleInterval, AllelicCount> totalCountsMap = new HashMap<>();   //store only the total counts (smaller memory footprint)
    int pulldownFileCounter = 1;
    final int totalNumberOfSamples = pulldownFiles.size();
    for (final File pulldownFile : pulldownFiles) {
        logger.info("Processing pulldown file " + pulldownFileCounter++ + "/" + totalNumberOfSamples + " (" + pulldownFile + ")...");
        final AllelicCountCollection pulldownCounts = new AllelicCountCollection(pulldownFile);
        for (final AllelicCount count : pulldownCounts.getCounts()) {
            //update the sum of ref and alt counts at each site
            final SimpleInterval site = count.getInterval();
            final AllelicCount currentCountAtSite = totalCountsMap.getOrDefault(site, new AllelicCount(site, 0, 0));
            final AllelicCount updatedCountAtSite = new AllelicCount(
                    site,
                    currentCountAtSite.getRefReadCount() + count.getRefReadCount(),
                    currentCountAtSite.getAltReadCount() + count.getAltReadCount());
            totalCountsMap.put(site, updatedCountAtSite);
            //update the number of samples seen possessing each site
            final MutableInt numberOfSamplesAtSite = numberOfSamplesMap.get(site);
            if (numberOfSamplesAtSite == null) {
                numberOfSamplesMap.put(site, new MutableInt(1));
            } else {
                numberOfSamplesAtSite.increment();
            }
        }
    }
    logger.info("Total number of unique sites present in samples: " + totalCountsMap.size());
    //filter out sites that appear at a frequency strictly less than the provided threshold
    final AllelicCountCollection totalCounts = new AllelicCountCollection();
    numberOfSamplesMap.entrySet().stream()
            .filter(e -> e.getValue().doubleValue() / totalNumberOfSamples >= siteFrequencyThreshold)
            .map(e -> totalCountsMap.get(e.getKey()))
            .forEach(totalCounts::add);
    logger.info(String.format("Number of unique sites present in samples above site frequency = %4.3f: %d", siteFrequencyThreshold, totalCounts.getCounts().size()));
    return new AllelicPanelOfNormals(totalCounts);
}
 
Example 11
Source File: WeeklyScheduleEvent.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void updateTransitionCounts(Map<String,MutableInt> counts) {
   for(Transition transition : transitions()) {
      for(DayOfWeek day : days()) {
         MutableInt count = counts.get(day + "-" + transition.zone());
         if(count == null) {
            counts.put(day + "-" + transition.zone(), new MutableInt(1));
         } else {
            count.increment();
         }
      }
   }
}
 
Example 12
Source File: JavaScriptJobManagerMinimalTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void addJob_singleExecution() throws Exception {
    final MutableInt count = new MutableInt(0);
    final JavaScriptJob job = new BasicJavaScriptJob(5, null) {
        @Override
        public void run() {
            count.increment();
        }
    };
    manager_.addJob(job, page_);
    assertEquals(1, manager_.getJobCount());
    manager_.waitForJobs(1000);
    assertEquals(1, count.intValue());
}
 
Example 13
Source File: Explain.java    From systemds with Apache License 2.0 5 votes vote down vote up
private static String explainLineageItemNR(LineageItem item, int level) {
	//NOTE: in contrast to similar non-recursive functions like resetVisitStatusNR,
	// we maintain a more complex stack to ensure DFS ordering where current nodes
	// are added after the subtree underneath is processed (backwards compatibility)
	Stack<LineageItem> stackItem = new Stack<>();
	Stack<MutableInt> stackPos = new Stack<>();
	stackItem.push(item); stackPos.push(new MutableInt(0));
	StringBuilder sb = new StringBuilder();
	while( !stackItem.empty() ) {
		LineageItem tmpItem = stackItem.peek();
		MutableInt tmpPos = stackPos.peek();
		//check ascent condition - no item processing
		if( tmpItem.isVisited() ) {
			stackItem.pop(); stackPos.pop();
		}
		//check ascent condition - append item
		else if( tmpItem.getInputs() == null 
			|| tmpItem.getInputs().length <= tmpPos.intValue() ) {
			sb.append(createOffset(level));
			sb.append(tmpItem.toString());
			sb.append('\n');
			stackItem.pop(); stackPos.pop();
			tmpItem.setVisited();
		}
		//check descent condition
		else if( tmpItem.getInputs() != null ) {
			stackItem.push(tmpItem.getInputs()[tmpPos.intValue()]);
			tmpPos.increment();
			stackPos.push(new MutableInt(0));
		}
	}
	return sb.toString();
}
 
Example 14
Source File: BaseStrategy.java    From sqlg with MIT License 5 votes vote down vote up
private void handleVertexStep(ListIterator<Step<?, ?>> stepIterator, AbstractStep<?, ?> step, MutableInt pathCount) {
    this.currentReplacedStep = ReplacedStep.from(
            this.sqlgGraph.getTopology(),
            step,
            pathCount.getValue()
    );
    //Important to add the replacedStep before collecting the additional steps.
    //In particular the orderGlobalStep needs to the currentStepDepth setted.
    ReplacedStepTree.TreeNode treeNodeNode = this.sqlgStep.addReplacedStep(this.currentReplacedStep);
    handleHasSteps(stepIterator, pathCount.getValue());
    handleOrderGlobalSteps(stepIterator, pathCount);
    handleRangeGlobalSteps(stepIterator, pathCount);
    handleConnectiveSteps(stepIterator);
    //if called from ChooseStep then the VertexStep is nested inside the ChooseStep and not one of the traversal's direct steps.
    int index = TraversalHelper.stepIndex(step, this.traversal);
    if (index != -1) {
        this.traversal.removeStep(step);
    }
    if (!this.currentReplacedStep.hasLabels()) {
        boolean precedesPathStep = precedesPathOrTreeStep(this.traversal);
        if (precedesPathStep) {
            this.currentReplacedStep.addLabel(pathCount.getValue() + BaseStrategy.PATH_LABEL_SUFFIX + BaseStrategy.SQLG_PATH_FAKE_LABEL);
        }
    }
    pathCount.increment();
    this.currentTreeNodeNode = treeNodeNode;
}
 
Example 15
Source File: JavaScriptJobManagerMinimalTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test for changes of revision 5589.
 * Ensures that interval jobs are scheduled at fix rate, no matter how long each one takes.
 * This test failed as of revision 5588 as consequence of the single threaded JS execution changes.
 * @throws Exception if an error occurs
 */
@Test
public void addJob_periodicJob2() throws Exception {
    final MutableInt count = new MutableInt(0);
    final JavaScriptJob job = new BasicJavaScriptJob(5, Integer.valueOf(200)) {
        @Override
        public void run() {
            if (count.intValue() == 0) {
                try {
                    Thread.sleep(200);
                }
                catch (final InterruptedException e) {
                    // ignore
                }
            }
            count.increment();
        }
    };
    manager_.addJob(job, page_);
    final int remainingJobs = manager_.waitForJobs(300);
    assertTrue(remainingJobs >= 1);
    // first interval starts at 5 and ends at 205
    // with a fix delay (what would be wrong), we would have second interval start at 205+200 = 405
    // and therefore count == 1
    // with a fix rate (correct), second interval starts at 205 and therefore count == 2
    assertEquals(2, count.intValue());
}
 
Example 16
Source File: HumanTime.java    From para with Apache License 2.0 5 votes vote down vote up
private boolean append(long d, long mod, long unit, char u, Appendable a, MutableInt parts) throws IOException {
		if (d >= unit) {
			a.append(floor(d, unit));
//                a.append(' ');
			a.append(u);
			parts.increment();
			if (mod <= lowerCeiling(unit)) {
				return true;
			}
		}
		return false;
	}
 
Example 17
Source File: ObjectUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find the most frequently occurring item.
 * 
 * @param <T> type of values processed by this method
 * @param items to check
 * @return most populous T, {@code null} if non-unique or no items supplied
 * @since 3.0.1
 */
public static <T> T mode(final T... items) {
    if (ArrayUtils.isNotEmpty(items)) {
        final HashMap<T, MutableInt> occurrences = new HashMap<T, MutableInt>(items.length);
        for (final T t : items) {
            final MutableInt count = occurrences.get(t);
            if (count == null) {
                occurrences.put(t, new MutableInt(1));
            } else {
                count.increment();
            }
        }
        T result = null;
        int max = 0;
        for (final Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
            final int cmp = e.getValue().intValue();
            if (cmp == max) {
                result = null;
            } else if (cmp > max) {
                max = cmp;
                result = e.getKey();
            }
        }
        return result;
    }
    return null;
}
 
Example 18
Source File: TreeGridGanttLayout.java    From gantt with Apache License 2.0 5 votes vote down vote up
/**
 * Add all child steps directed by the TreeGrid's hierarchical data source.
 */
private void addChildStepRecursively(TreeGrid<Step> grid, Step itemId, MutableInt index) {
    if (!dataProvider.hasChildren(itemId) || !grid.isExpanded(itemId)) {
        return;
    }
    if (index.getValue() == 0) {
        index.setValue(gantt.getSteps().indexOf(itemId) + 1);
    }
    for (Step child : dataProvider.getTreeData().getChildren(itemId)) {
        gantt.addStep(index.getValue(), child);
        index.increment();
        addChildStepRecursively(grid, child, index);
    }
}
 
Example 19
Source File: SimpleScheduleEvent.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void updateTransitionCounts(Map<String,MutableInt> counts) {
   for(Transition transition : transitions()) {
      MutableInt count = counts.get(transition.zone());
      if(count == null) {
         counts.put(transition.zone(), new MutableInt(1));
      } else {
         count.increment();
      }
   }
}
 
Example 20
Source File: AttributeServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Checks that {@link AttributeService#getAttributes(AttributeQueryCallback, Serializable...) AttributeService.getAttributes}
 * works.  This includes coverage of <a href=https://issues.alfresco.com/jira/browse/MNT-9112>MNT-9112</a>.
 */
public void testGetAttributes() throws Exception
{
    attributeService.setAttribute(VALUE_AAA_STRING, KEY_AAA);
    attributeService.setAttribute(VALUE_AAB_STRING, KEY_AAB);
    attributeService.setAttribute(VALUE_AAC_STRING, KEY_AAC);

    final List<Serializable> results = new ArrayList<Serializable>();
    final MutableInt counter = new MutableInt();
    final MutableInt max = new MutableInt(3);
    AttributeQueryCallback callback = new AttributeQueryCallback()
    {
        @Override
        public boolean handleAttribute(Long id, Serializable value, Serializable[] keys)
        {
            counter.increment();
            results.add(value);
            if (counter.intValue() == max.intValue())
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    };
    
    counter.setValue(0);
    max.setValue(3);
    results.clear();
    attributeService.getAttributes(callback, KEY_A);
    assertEquals(3, results.size());
    assertEquals(3, (int)counter.getValue());
    
    counter.setValue(0);
    max.setValue(2);
    results.clear();
    attributeService.getAttributes(callback, KEY_A);
    assertEquals(2, results.size());
    assertEquals(2, (int)counter.getValue());
}