Java Code Examples for java.util.PriorityQueue

The following examples show how to use java.util.PriorityQueue. These examples are extracted from open source projects. 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
/**
 * Determine the k nearest neighbors for a test instance.
 *
 * @param testInstance
 *            The time series to determine the k nearest neighbors for.
 * @return Queue of the k nearest neighbors as pairs (class, distance).
 */
protected PriorityQueue<Pair<Integer, Double>> calculateNearestNeigbors(final double[] testInstance) {
	int numberOfTrainInstances = this.values.length;
	// Priority queue of (class, distance)-pairs for nearest neigbors, sorted by
	// distance ascending.
	PriorityQueue<Pair<Integer, Double>> nearestNeighbors = new PriorityQueue<>(nearestNeighborComparator);

	// Calculate the k nearest neighbors.
	for (int i = 0; i < numberOfTrainInstances; i++) {
		double d = this.distanceMeasure.distance(testInstance, this.values[i]);

		Pair<Integer, Double> neighbor = new Pair<>(this.targets[i], d);
		nearestNeighbors.add(neighbor);
		if (nearestNeighbors.size() > this.k) {
			nearestNeighbors.poll();
		}
	}
	return nearestNeighbors;
}
 
Example 2
Source Project: flink   Source File: RocksStatesPerKeyGroupMergeIterator.java    License: Apache License 2.0 6 votes vote down vote up
private PriorityQueue<RocksSingleStateIterator> buildIteratorHeap(
	List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators) {

	Comparator<RocksSingleStateIterator> iteratorComparator = COMPARATORS.get(keyGroupPrefixByteCount - 1);

	PriorityQueue<RocksSingleStateIterator> iteratorPriorityQueue =
		new PriorityQueue<>(kvStateIterators.size(), iteratorComparator);

	for (Tuple2<RocksIteratorWrapper, Integer> rocksIteratorWithKVStateId : kvStateIterators) {
		final RocksIteratorWrapper rocksIterator = rocksIteratorWithKVStateId.f0;
		rocksIterator.seekToFirst();
		if (rocksIterator.isValid()) {
			iteratorPriorityQueue.offer(
				new RocksSingleStateIterator(rocksIterator, rocksIteratorWithKVStateId.f1));
		} else {
			IOUtils.closeQuietly(rocksIterator);
		}
	}
	return iteratorPriorityQueue;
}
 
Example 3
Source Project: streamline   Source File: Topn.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PriorityQueue<T> add(PriorityQueue<T> aggregate, Integer n, T val) {
    if (n <= 0) {
        return aggregate;
    }
    if (aggregate.size() >= n) {
        if (val.compareTo(aggregate.peek()) > 0) {
            aggregate.remove();
            aggregate.add(val);
        }
    } else {
        aggregate.add(val);
    }
    return aggregate;

}
 
Example 4
Source Project: cineast   Source File: YOLO.java    License: MIT License 6 votes vote down vote up
/**
 * It classifies the object/objects on the image
 *
 * @param tensorFlowOutput output from the TensorFlow, it is a 13x13x((num_class +1) * 5) tensor
 * 125 = (numClass +  Tx, Ty, Tw, Th, To) * 5 - cause we have 5 boxes per each cell
 * @param labels a string vector with the labels
 * @return a list of recognition objects
 */
private List<Recognition> classifyImage(final float[] tensorFlowOutput, final String[] labels) {
  int numClass = (int) (tensorFlowOutput.length / (Math.pow(SIZE, 2) * NUMBER_OF_BOUNDING_BOX)
      - 5);
  BoundingBox[][][] boundingBoxPerCell = new BoundingBox[SIZE][SIZE][NUMBER_OF_BOUNDING_BOX];
  PriorityQueue<Recognition> priorityQueue = new PriorityQueue<>(
      MAX_RECOGNIZED_CLASSES,
      new RecognitionComparator());

  int offset = 0;
  for (int cy = 0; cy < SIZE; cy++) {        // SIZE * SIZE cells
    for (int cx = 0; cx < SIZE; cx++) {
      for (int b = 0; b < NUMBER_OF_BOUNDING_BOX; b++) {   // 5 bounding boxes per each cell
        boundingBoxPerCell[cx][cy][b] = getModel(tensorFlowOutput, cx, cy, b, numClass, offset);
        calculateTopPredictions(boundingBoxPerCell[cx][cy][b], priorityQueue, labels);
        offset = offset + numClass + 5;
      }
    }
  }

  return getRecognition(priorityQueue);
}
 
Example 5
Source Project: incubator-iotdb   Source File: LastPointReader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * find the last TimeseriesMetadata in unseq files and unpack all overlapped unseq files
 */
private void UnpackOverlappedUnseqFiles(long lBoundTime) throws IOException {
  PriorityQueue<TsFileResource> unseqFileResource =
      sortUnSeqFileResourcesInDecendingOrder(dataSource.getUnseqResources());

  while (!unseqFileResource.isEmpty()
      && (lBoundTime <= unseqFileResource.peek().getEndTime(seriesPath.getDevice()))) {
    TimeseriesMetadata timeseriesMetadata =
        FileLoaderUtils.loadTimeSeriesMetadata(
            unseqFileResource.poll(), seriesPath, context, timeFilter, deviceMeasurements);

    if (timeseriesMetadata == null || (!timeseriesMetadata.isModified()
        && timeseriesMetadata.getStatistics().getEndTime() < lBoundTime)) {
      continue;
    }
    unseqTimeseriesMetadataList.add(timeseriesMetadata);
    if (!timeseriesMetadata.isModified()) {
      if (endtimeContainedByTimeFilter(timeseriesMetadata.getStatistics())) {
        lBoundTime = Math.max(lBoundTime, timeseriesMetadata.getStatistics().getEndTime());
      } else {
        lBoundTime = Math.max(lBoundTime, timeseriesMetadata.getStatistics().getStartTime());
      }
    }
  }
}
 
Example 6
Source Project: Hackerrank-Solutions   Source File: FindTheRunningMedian.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	PriorityQueue<Integer> highers = new PriorityQueue<Integer>();
	PriorityQueue<Integer> lowers = new PriorityQueue<Integer>(new Comparator<Integer>() {
		public int compare(Integer i1, Integer i2) {
			return i2.compareTo(i1);
		}
	});
	int N = sc.nextInt();
	double meadian = 0;
	for (int i = 1; i <= N; i++) {
		int number = sc.nextInt();
		addNumber(number, lowers, highers);
		rebalance(lowers, highers);
		meadian = getMedian(lowers, highers);
		System.out.println(meadian);
	}
	sc.close();
}
 
Example 7
protected Collection<TempQueue> getMostUnderservedQueues(
    PriorityQueue<TempQueue> orderedByNeed, TQComparator tqComparator) {
  ArrayList<TempQueue> underserved = new ArrayList<TempQueue>();
  while (!orderedByNeed.isEmpty()) {
    TempQueue q1 = orderedByNeed.remove();
    underserved.add(q1);
    TempQueue q2 = orderedByNeed.peek();
    // q1's pct of guaranteed won't be larger than q2's. If it's less, then
    // return what has already been collected. Otherwise, q1's pct of
    // guaranteed == that of q2, so add q2 to underserved list during the
    // next pass.
    if (q2 == null || tqComparator.compare(q1,q2) < 0) {
      return underserved;
    }
  }
  return underserved;
}
 
Example 8
Source Project: Algorithms   Source File: PrimeFactorization.java    License: MIT License 6 votes vote down vote up
public static ArrayList<Long> primeFactorization(long n) {
  ArrayList<Long> factors = new ArrayList<>();
  if (n <= 0) throw new IllegalArgumentException();
  else if (n == 1) return factors;
  PriorityQueue<Long> divisorQueue = new PriorityQueue<>();
  divisorQueue.add(n);
  while (!divisorQueue.isEmpty()) {
    long divisor = divisorQueue.remove();
    if (isPrime(divisor)) {
      factors.add(divisor);
      continue;
    }
    long next_divisor = pollardRho(divisor);
    if (next_divisor == divisor) {
      divisorQueue.add(divisor);
    } else {
      divisorQueue.add(next_divisor);
      divisorQueue.add(divisor / next_divisor);
    }
  }
  return factors;
}
 
Example 9
public static List<Integer> mergekSortedArrays(List<List<Integer>> arrays) {
    ArrayList<Integer> list = new ArrayList<>();
    if (arrays == null || arrays.size() == 0 || arrays.get(0).size() == 0) {
        return list;
    }
    PriorityQueue<NewInteger> pq = new PriorityQueue<>(arrays.size(), (x, y) -> x.value > y.value ? -1 : 1);
    for (int i = 0; i < arrays.size(); i++) {
        pq.offer(new NewInteger(arrays.get(i).get(0), i, 0));
    }
    while (list.size() < 3000 && !pq.isEmpty()) {
        NewInteger min = pq.poll();
        if (min.col + 1 < arrays.get(min.row).size()) {
            pq.offer(new NewInteger(arrays.get(min.row).get(min.col + 1), min.row, min.col + 1));
        }
        list.add(min.value);
    }
    return list;
}
 
Example 10
Source Project: flink   Source File: PriorityQueueSerializer.java    License: Apache License 2.0 6 votes vote down vote up
public PriorityQueue<?> read(Kryo k, Input i, Class<PriorityQueue<?>> c) {
	Comparator<Object> comp = (Comparator<Object>) k.readClassAndObject(i);
	int sz = i.readInt(true);
	// can't create with size 0:
	PriorityQueue<Object> result;
	if (sz == 0) {
		result = new PriorityQueue<Object>(1, comp);
	}
	else {
		result = new PriorityQueue<Object>(sz, comp);
	}
	int idx = 0;
	while (idx < sz) {
		result.add(k.readClassAndObject(i));
		idx += 1;
	}
	return result;
}
 
Example 11
Source Project: kylin   Source File: GTAggregateScanner.java    License: Apache License 2.0 6 votes vote down vote up
public DumpMerger(List<Dump> dumps) {
    minHeap = new PriorityQueue<>(dumps.size(), new Comparator<Entry<byte[], Integer>>() {
        @Override
        public int compare(Entry<byte[], Integer> o1, Entry<byte[], Integer> o2) {
            return bytesComparator.compare(o1.getKey(), o2.getKey());
        }
    });
    dumpIterators = Lists.newArrayListWithCapacity(dumps.size());
    dumpCurrentValues = Lists.newArrayListWithCapacity(dumps.size());

    Iterator<Pair<byte[], byte[]>> it;
    for (int i = 0; i < dumps.size(); i++) {
        it = dumps.get(i).iterator();
        dumpCurrentValues.add(i, null);
        if (it.hasNext()) {
            dumpIterators.add(i, it);
            enqueueFromDump(i);
        } else {
            dumpIterators.add(i, null);
        }
    }
}
 
Example 12
Source Project: JImageHash   Source File: BinaryTreeTest.java    License: MIT License 6 votes vote down vote up
@Test
public void searchItemMultipleValues2() {
	Hash hash = TestResources.createHash("101010100011", 0);
	Hash hash1 = TestResources.createHash("101010100010", 0);

	binTree.addHash(hash, 1);
	binTree.addHash(hash, 2);
	binTree.addHash(hash, 3);
	binTree.addHash(hash1, 3);
	binTree.addHash(hash1, 3);
	binTree.addHash(hash1, 3);

	PriorityQueue<Result> results = binTree.getElementsWithinHammingDistance(hash, 2);

	assertEquals(6, results.size());
}
 
Example 13
Source Project: LeetCode-Solution-in-Good-Style   Source File: Solution.java    License: Apache License 2.0 6 votes vote down vote up
public boolean isPossibleDivide(int[] nums, int k) {
    int len = nums.length;
    if (len % k != 0) {
        return false;
    }

    PriorityQueue<Integer> minHeap = new PriorityQueue<>(len);
    for (int num : nums) {
        minHeap.offer(num);
    }

    while (!minHeap.isEmpty()) {
        Integer top = minHeap.poll();

        for (int i = 1; i < k; i++) {
            // 从 1 开始,正好需要移除 k - 1 个元素
            // i 正好就是相对于 top 的偏移
            if (!minHeap.remove(top + i)) {
                // 如果移除失败,说明划分不存在,直接返回 false 即可
                return false;
            }
        }
    }
    return true;
}
 
Example 14
Source Project: j2objc   Source File: PriorityQueueTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_spliterator() throws Exception {
    ArrayList<Integer> testElements = new ArrayList<>(
            Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));
    PriorityQueue<Integer> list = new PriorityQueue<>();
    list.addAll(testElements);

    SpliteratorTester.runBasicIterationTests(list.spliterator(), testElements);
    SpliteratorTester.runBasicSplitTests(list, testElements);
    SpliteratorTester.testSpliteratorNPE(list.spliterator());

    assertTrue(list.spliterator().hasCharacteristics(
            Spliterator.SIZED | Spliterator.SUBSIZED));

    SpliteratorTester.runSizedTests(list, 16 /* expected size */);
    SpliteratorTester.runSubSizedTests(list, 16 /* expected size */);
    SpliteratorTester.assertSupportsTrySplit(list);
}
 
Example 15
Source Project: cineast   Source File: YOLO.java    License: MIT License 6 votes vote down vote up
private List<Recognition> getRecognition(final PriorityQueue<Recognition> priorityQueue) {
  ArrayList<Recognition> recognitions = new ArrayList<>();

  if (priorityQueue.size() > 0) {
    // Best recognition
    Recognition bestRecognition = priorityQueue.poll();
    recognitions.add(bestRecognition);

    for (int i = 0; i < Math.min(priorityQueue.size(), MAX_RESULTS); ++i) {
      Recognition recognition = priorityQueue.poll();
      boolean overlaps = false;
      for (Recognition previousRecognition : recognitions) {
        overlaps = overlaps || (getIntersectionProportion(previousRecognition.getLocation(),
            recognition.getLocation()) > OVERLAP_THRESHOLD);
      }

      if (!overlaps) {
        recognitions.add(recognition);
      }
    }
  }

  return recognitions;
}
 
Example 16
public Object getObject(final String command) throws Exception {
	final TemplatesImpl templates = Gadgets.createTemplatesImpl(command);
	// mock method name until armed
	final BeanComparator comparator = new BeanComparator("lowestSetBit");

	// create queue with numbers and basic comparator
	final PriorityQueue<Object> queue = new PriorityQueue<Object>(2, comparator);
	// stub data for replacement later
	queue.add(new BigInteger("1"));
	queue.add(new BigInteger("1"));

	// switch method called by comparator
	Reflections.setFieldValue(comparator, "property", "outputProperties");

	// switch contents of queue
	final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
	queueArray[0] = templates;
	queueArray[1] = templates;

	return queue;
}
 
Example 17
Source Project: uReplicator   Source File: TestAdminHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetControllerAutobalancing() throws Exception {
    ControllerHelixManager mockHelixManager = EasyMock.createMock(ControllerHelixManager.class);
    AdminHelper helper = new AdminHelper(mockHelixManager);
    Map<String, PriorityQueue<InstanceTopicPartitionHolder>> instanceMap = new HashMap<>();
    PriorityQueue<InstanceTopicPartitionHolder> sjc1aTosjc1Agg1 = new PriorityQueue<>();
    String pipeline = ControllerUtils.getPipelineName("sjc1a", "sjc1-agg1");
    InstanceTopicPartitionHolder ith = new InstanceTopicPartitionHolder("compute9527-sjc1",
        new TopicPartition(pipeline, 0));
    sjc1aTosjc1Agg1.add(ith);
    instanceMap.put(pipeline, sjc1aTosjc1Agg1);
    EasyMock.expect(mockHelixManager.getPipelineToInstanceMap()).andReturn(instanceMap).atLeastOnce();
    EasyMock.expect(mockHelixManager.getControllerAutobalancingStatus("compute9527-sjc1"))
        .andReturn(false);
    EasyMock.replay(mockHelixManager);
    JSONObject status = helper.getControllerAutobalancingStatus();
    Assert.assertEquals(status.size(), 1);
    JSONObject detail = (JSONObject) status.get("compute9527-sjc1");
    Assert.assertEquals(detail.get("autoBalance"), false);
    EasyMock.verify(mockHelixManager);
}
 
Example 18
Source Project: kieker   Source File: SessionReconstructionFilter.java    License: Apache License 2.0 6 votes vote down vote up
private <T extends AbstractSession<?>> void processTimeouts(final long currentTime, final String outputPortName, final PriorityQueue<T> timeoutQueue,
		final Map<String, T> openSessions) {
	while (!timeoutQueue.isEmpty()) {
		final T session = timeoutQueue.peek();
		final long currentThinkTime = (currentTime - session.getEndTimestamp());

		// The current session timed out
		if (currentThinkTime > this.maxThinkTime) {
			timeoutQueue.remove();
			openSessions.remove(session.getSessionId());
			this.dispatchCompletedSession(session, outputPortName);
		} else { // If the current session has not timed out, we are done due to the ordering of the queue
			break;
		}
	}
}
 
Example 19
Source Project: JedAIToolkit   Source File: CardinalityNodePruning.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<AbstractBlock> pruneEdges() {
    nearestEntities = new HashSet[noOfEntities];
    topKEdges = new PriorityQueue<>((int) (2 * threshold), new IncComparisonWeightComparator());
    if (weightingScheme.equals(WeightingScheme.ARCS)) {
        for (int i = 0; i < noOfEntities; i++) {
            processArcsEntity(i);
            verifyValidEntities(i);
        }
    } else {
        for (int i = 0; i < noOfEntities; i++) {
            processEntity(i);
            verifyValidEntities(i);
        }
    }

    return retainValidComparisons();
}
 
Example 20
Source Project: JImageHash   Source File: DatabaseExample.java    License: MIT License 5 votes vote down vote up
private static void createDatabaseViaCredentials() throws Exception {
	String dbName = "imageHashDB";
	String userName = "root";
	String password = "";

	// Wrap in try with block or call close at the end!
	try (H2DatabaseImageMatcher db = new H2DatabaseImageMatcher(dbName, userName, password)) {
		// Proceed as normal
		db.addHashingAlgorithm(new DifferenceHash(32, Precision.Double), .4);
		db.addHashingAlgorithm(new PerceptiveHash(32), .2);

		// Image files
		File ballon = new File("src/test/resources/ballon.jpg");
		File copyright = new File("src/test/resources/copyright.jpg");
		File highQuality = new File("src/test/resources/highQuality.jpg");

		db.addImages(ballon, copyright, highQuality);

		PriorityQueue<Result<String>> results = db.getMatchingImages(copyright);
		results.forEach(System.out::println);

		// Find all images which are similar to any image in the database
		System.out.println(db.getAllMatchingImages());
	}

	/*
	 * finally { //Not necessary since we use a try with otherwise db.close(); }
	 */

}
 
Example 21
Source Project: Java8CN   Source File: PriorityBlockingQueue.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Saves this queue to a stream (that is, serializes it).
 *
 * For compatibility with previous version of this class, elements
 * are first copied to a java.util.PriorityQueue, which is then
 * serialized.
 *
 * @param s the stream
 * @throws java.io.IOException if an I/O error occurs
 */
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    lock.lock();
    try {
        // avoid zero capacity argument
        q = new PriorityQueue<E>(Math.max(size, 1), comparator);
        q.addAll(this);
        s.defaultWriteObject();
    } finally {
        q = null;
        lock.unlock();
    }
}
 
Example 22
/**
 * Saves this queue to a stream (that is, serializes it).
 *
 * For compatibility with previous version of this class, elements
 * are first copied to a java.util.PriorityQueue, which is then
 * serialized.
 *
 * @param s the stream
 * @throws java.io.IOException if an I/O error occurs
 */
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    lock.lock();
    try {
        // avoid zero capacity argument
        q = new PriorityQueue<E>(Math.max(size, 1), comparator);
        q.addAll(this);
        s.defaultWriteObject();
    } finally {
        q = null;
        lock.unlock();
    }
}
 
Example 23
Source Project: Project   Source File: LessMoney.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // solution
    int[] arr = {10, 20, 30};
    System.out.println("形成 10,20,30 最少需要成本为:" + lessMoney(arr));

    int[] arrForHeap = {1, 2, 6, 4, 3, 7, 1, 8};

    System.out.println("{1,2,6,4,3,7,1,8}形成的最小堆为:");
    // min heap
    PriorityQueue<Integer> minQ1 = new PriorityQueue<>();
    for (int i = 0; i < arrForHeap.length; i++) {
        minQ1.add(arrForHeap[i]);
    }
    while (!minQ1.isEmpty()) {
        System.out.print(minQ1.poll() + " ");
    }
    System.out.println();

    // min heap use Comparator
    PriorityQueue<Integer> minQ2 = new PriorityQueue<>(new MinheapComparator());
    for (int i = 0; i < arrForHeap.length; i++) {
        minQ2.add(arrForHeap[i]);
    }
    while (!minQ2.isEmpty()) {
        System.out.print(minQ2.poll() + " ");
    }
    System.out.println();

    System.out.println("{1,2,6,4,3,7,1,8}形成的最大堆为:");
    // max heap use Comparator
    PriorityQueue<Integer> maxQ = new PriorityQueue<>(new MaxheapComparator());
    for (int i = 0; i < arrForHeap.length; i++) {
        maxQ.add(arrForHeap[i]);
    }
    while (!maxQ.isEmpty()) {
        System.out.print(maxQ.poll() + " ");
    }
}
 
Example 24
Source Project: deeplearning4j   Source File: GraphVectorsImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int[] verticesNearest(int vertexIdx, int top) {

    INDArray vec = lookupTable.getVector(vertexIdx).dup();
    double norm2 = vec.norm2Number().doubleValue();


    PriorityQueue<Pair<Double, Integer>> pq =
                    new PriorityQueue<>(lookupTable.getNumVertices(), new PairComparator());

    Level1 l1 = Nd4j.getBlasWrapper().level1();
    for (int i = 0; i < numVertices(); i++) {
        if (i == vertexIdx)
            continue;

        INDArray other = lookupTable.getVector(i);
        double cosineSim = l1.dot(vec.length(), 1.0, vec, other) / (norm2 * other.norm2Number().doubleValue());

        pq.add(new Pair<>(cosineSim, i));
    }

    int[] out = new int[top];
    for (int i = 0; i < top; i++) {
        out[i] = pq.remove().getSecond();
    }

    return out;
}
 
Example 25
/**
 * Generate a list of recommendations based on given list of candidate nodes and the original request.
 * @param request         original request message, contains filtering criteria
 * @param candidateNodes  list of candidate nodes
 * @return                list of {@link MomentRecommendationInfo}
 */
public static List<RecommendationInfo> generateMomentRecs(
  TopSecondDegreeByCountRequestForMoment request,
  List<NodeInfo> candidateNodes) {

  int maxNumResults = Math.min(request.getMaxNumResults(), RecommendationRequest.MAX_RECOMMENDATION_RESULTS);

  PriorityQueue<NodeInfo> validNodes =
    GeneratorHelper.getValidNodes(candidateNodes, request.getMinUserPerSocialProof(), maxNumResults);

  return getRecommendationsFromNodes(request, validNodes);
}
 
Example 26
Source Project: common-utils   Source File: CollectionUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 创建<code>PriorityQueue</code>实例
 * 
 * @param <E>
 * @param collection 集合 @see Collection
 * @return <code>PriorityQueue</code>实例
 */
public static <E> PriorityQueue<E> createPriorityQueue(Collection<? extends E> collection) {
    if (collection == null) {
        return null;
    }

    return new PriorityQueue<E>(collection);
}
 
Example 27
/**
 * Gets the sorted timestamps of any buffered events.
 *
 * @return a sorted list of timestamps that have at least one buffered event.
 */
private PriorityQueue<Long> getSortedTimestamps() throws Exception {
    PriorityQueue<Long> sortedTimestamps = new PriorityQueue<>();
    for (Long timestamp : elementQueueState.keys()) {
        sortedTimestamps.offer(timestamp);
    }
    return sortedTimestamps;
}
 
Example 28
/**
 * From all possible limb candidates for a given Limb Type, select those that maximize the total PAF score.
 * The algorithm starts from the limb candidates with higher PAF score. Also the algorithm tracks the parts
 * already assigned t a final limbs and rejects limb candidates with already assigned parts.
 *
 * @param limbType Limb Type for which final limbs a selected.
 * @param limbCandidatesQueue possible Limb candidates, sorted by total PAF score in a descending order.
 * @return Returns the final list of Limbs for a given {@link org.springframework.cloud.stream.app.pose.estimation.model.Model.LimbType}
 */
private List<Limb> selectFinalLimbs(Model.LimbType limbType, PriorityQueue<Limb> limbCandidatesQueue) {

	List<Limb> finalLimbs = new ArrayList<>();

	// Parts assigned to final limbs.
	Set<Part> assignedParts = new HashSet<>();

	// Start from the candidates with higher PAF score and progress in descending order
	while (!limbCandidatesQueue.isEmpty()) {

		Limb limbCandidate = limbCandidatesQueue.poll();

		Assert.isTrue(limbType == limbCandidate.getLimbType(), "Incorrect Limb Type!");

		// Ignore candidate limbs with parts already assigned a final Limb from earlier iteration.
		if (!assignedParts.contains(limbCandidate.getFromPart())
				&& !assignedParts.contains(limbCandidate.getToPart())) {

			// Make the candidate final.
			finalLimbs.add(limbCandidate);

			// Mark limb's parts as assigned.
			assignedParts.add(limbCandidate.getFromPart());
			assignedParts.add(limbCandidate.getToPart());
		}
	}

	return finalLimbs;
}
 
Example 29
Source Project: doctorkafka   Source File: KafkaCluster.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the broker Id that has the resource. Here we need to apply the proper placement policy.
 *
 * @param brokerQueue  the list of brokers that are sorted in resource usage
 * @param oosReplica  out of sync replicas
 * @param inBoundReq  inbound traffic
 * @param outBoundReq outbound traffc
 * @param preferredBroker preferred broker id
 * @return a BrokerId to KafkaBroker mapping
 */
public Map<Integer, KafkaBroker> getAlternativeBrokers(
    PriorityQueue<KafkaBroker> brokerQueue,
    OutOfSyncReplica oosReplica,
    double inBoundReq,
    double outBoundReq,
    int preferredBroker
) {

  boolean success = true;
  Map<Integer, KafkaBroker> result = new HashMap<>();
  Set<KafkaBroker> unusableBrokers = new HashSet<>();

  for (int oosBrokerId : oosReplica.outOfSyncBrokers) {
    // we will get the broker with the least network usage
    success = findNextBrokerForOosReplica(
        brokerQueue,
        unusableBrokers,
        oosReplica.replicaBrokers,
        result,
        oosBrokerId,
        oosReplica.topicPartition,
        inBoundReq,
        outBoundReq,
        preferredBroker
    );

    // short circuit if failed to find available broker
    if (!success) {
      break;
    }
  }
  // push the brokers back to brokerQueue to keep invariant true
  brokerQueue.addAll(unusableBrokers);
  return success ? result : null;
}
 
Example 30
/**
 * toArray contains all elements
 */
public void testToArray() {
    PriorityQueue q = populatedQueue(SIZE);
    Object[] o = q.toArray();
    Arrays.sort(o);
    for (int i = 0; i < o.length; i++)
        assertSame(o[i], q.poll());
}