Java Code Examples for java.util.Queue#remove()

The following examples show how to use java.util.Queue#remove() . 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: ReversibilityVerificationCommand.java    From workcraft with MIT License 6 votes vote down vote up
private HashSet<State> getBackwardReachableStates(final Fsm fsm, State initialState) {
    HashMap<State, HashSet<Event>> statePrevEvents = FsmUtils.calcStateIncommingEventsMap(fsm);

    HashSet<State> visitedStates = new HashSet<>();
    Queue<State> queueStates = new LinkedList<>();

    if (initialState != null) {
        queueStates.add(initialState);
    }

    while (!queueStates.isEmpty()) {
        State curState = queueStates.remove();
        if (visitedStates.contains(curState)) continue;
        visitedStates.add(curState);
        for (Event curEvent: statePrevEvents.get(curState)) {
            State prevState = (State) curEvent.getFirst();
            if (prevState != null) {
                queueStates.add(prevState);
            }
        }
    }
    return visitedStates;
}
 
Example 2
Source File: DesktopEditorErrorPanelUI.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int drawStripesEndingBefore(int ys, @Nonnull Queue<PositionedStripe> ends, @Nonnull List<PositionedStripe> stripes, @Nonnull Graphics g, int yStart) {
  while (!ends.isEmpty()) {
    PositionedStripe endingStripe = ends.peek();
    if (endingStripe.yEnd > ys) break;
    ends.remove();

    // check whether endingStripe got obscured in the range yStart..endingStripe.yEnd
    int i = stripes.indexOf(endingStripe);
    stripes.remove(i);
    if (i == 0) {
      // visible
      drawSpot(g, endingStripe.thin, yStart, endingStripe.yEnd, endingStripe.color);
      yStart = endingStripe.yEnd;
    }
  }
  return yStart;
}
 
Example 3
Source File: RuleKeyDiagnostics.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Computes the diagnostic rulekey data for the given rule and all of its appendables recursively.
 * Previously processed rules and appendables are skipped and not fed to the consumer. Results for
 * the newly processed rule and appendables are fed to the consumer, but not stored otherwise.
 * Only information of whether something has been processed or not gets stored.
 */
public void processRule(BuildRule rule, Consumer<Result<RULE_KEY, DIAG_KEY>> resultConsumer) {
  if (!computed.add(rule)) {
    return;
  }
  Queue<AddsToRuleKey> appendableQueue = new LinkedList<>();
  Result<RULE_KEY, DIAG_KEY> result = ruleResultSupplier.apply(rule);
  Iterables.addAll(appendableQueue, result.appendables);
  resultConsumer.accept(result);
  while (!appendableQueue.isEmpty()) {
    AddsToRuleKey appendable = appendableQueue.remove();
    if (computed.add(appendable)) {
      result = appendableResultSupplier.apply(appendable);
      Iterables.addAll(appendableQueue, result.appendables);
      resultConsumer.accept(result);
    }
  }
}
 
Example 4
Source File: SharedBehaviorTesting.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Runs all children with compilations coalesced for performance.
 */
private void runChildren(RunNotifier notifier) throws Throwable {
  if (superDescription.get().getChildren().size() > 1) {
    Queue<SharedCompiler> sharedCompilers = getSharedCompilers(notifier);
    while (!sharedCompilers.isEmpty()) {
      // Removing each shared compiler from the queue as we start it ensures it can be
      // garbage-collected as soon as we're finished with it.
      SharedCompiler sharedCompiler = sharedCompilers.remove();
      for (FrameworkMethod child : sharedCompiler.children) {
        runChild(notifier, sharedCompiler, child);
      }
    }
  } else {
    // Rerun individual tests with the default BehaviorTester.
    tester = BehaviorTester.create(features);
    try {
      superChildrenInvoker.apply(notifier).evaluate();
    } finally {
      tester = null;
    }
  }
}
 
Example 5
Source File: LeetCode111.java    From Project with Apache License 2.0 6 votes vote down vote up
public int minDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    int level = 1;
    Queue<TreeNode> levelQueue = new LinkedList<>();
    levelQueue.add(root);
    while (!levelQueue.isEmpty()) {
        int length = levelQueue.size();
        for (int i = 0; i < length; i++) {
            TreeNode remove = levelQueue.remove();
            if (remove.left != null) {
                levelQueue.add(remove.left);
            }
            if (remove.right != null) {
                levelQueue.add(remove.right);
            }
            // 如果一个节点左右子节点都为空则此层结束
            if (remove.left == null && remove.right == null) {
                return level;
            }
        }
        level++;
    }
    return level;
}
 
Example 6
Source File: TreeNode.java    From daily-coding-problems with Apache License 2.0 6 votes vote down vote up
public void printTree() {
    Queue<TreeNode<T>> queue = new LinkedList<>();

    queue.add(this);
    queue.add(null);
    while (!queue.isEmpty()) {
        TreeNode<T> current = queue.remove();
        if (current == null) {
            if (!queue.isEmpty()) {
                queue.add(null);
                System.out.print("\n");
            }
        } else {
            System.out.print(current.data + "\t");
            if (current.getLeft() != null) {
                queue.add(current.getLeft());
            }
            if (current.getRight() != null) {
                queue.add(current.getRight());
            }
        }

    }
    System.out.print("\n");
    System.out.print("\n");
}
 
Example 7
Source File: LoopEx.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void nodesInLoopBranch(NodeBitMap branchNodes, AbstractBeginNode branch) {
    Collection<AbstractBeginNode> blocks = new LinkedList<>();
    Collection<LoopExitNode> exits = new LinkedList<>();
    Queue<Block> work = new LinkedList<>();
    ControlFlowGraph cfg = loopsData().getCFG();
    work.add(cfg.blockFor(branch));
    while (!work.isEmpty()) {
        Block b = work.remove();
        if (loop().getExits().contains(b)) {
            exits.add((LoopExitNode) b.getBeginNode());
        } else {
            blocks.add(b.getBeginNode());
            for (Block d : b.getDominated()) {
                if (loop.getBlocks().contains(d)) {
                    work.add(d);
                }
            }
        }
    }
    LoopFragment.computeNodes(branchNodes, branch.graph(), blocks, exits);
}
 
Example 8
Source File: BST.java    From java-data-structure with Apache License 2.0 6 votes vote down vote up
public void levelOrder() {

        if (root == null)
            return;

        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {

            Node cur = queue.remove();
            System.out.println(cur.e);

            if (root.left != null)
                queue.add(root.left);
            if (root.right != null)
                queue.add(root.right);
        }
    }
 
Example 9
Source File: Types.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Set of classes and interfaces inherited or implemented by clazz.
 *
 * <p>Result includes clazz itself. Result is ordered closest to furthest, i.e. first entry will
 * always be clazz and last entry will always be {@link java.lang.Object}.
 */
public static ImmutableSet<Class<?>> getSupertypes(Class<?> clazz) {
  LinkedHashSet<Class<?>> ret = new LinkedHashSet<>();

  Queue<Class<?>> toExpand = new LinkedList<>();
  toExpand.add(clazz);
  while (!toExpand.isEmpty()) {
    Class<?> current = toExpand.remove();
    if (!ret.add(current)) {
      continue;
    }
    toExpand.addAll(Arrays.asList(current.getInterfaces()));
    if (current.getSuperclass() != null) {
      toExpand.add(current.getSuperclass());
    }
  }
  return ImmutableSet.copyOf(ret);
}
 
Example 10
Source File: SetsTest.java    From beepbeep-3 with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testReset1()
{
  Sets.PutInto pi = new Sets.PutInto();
  QueueSink qs = new QueueSink();
  Connector.connect(pi, qs);
  Pushable p = pi.getPushableInput();
  Queue<Object> q = qs.getQueue();
  p.push("foo");
  Set<?> set1 = (Set<?>) q.remove();
  assertEquals(1, set1.size());
  assertTrue(set1.contains("foo"));
  pi.reset();
  p.push("bar");
  Set<?> set2 = (Set<?>) q.remove();
  assertTrue(set1 == set2); // Both refer to the same collection
  assertEquals(1, set2.size());
  assertTrue(set1.contains("bar"));
  assertFalse(set1.contains("foo"));
}
 
Example 11
Source File: ConfigFieldParser.java    From aircon with MIT License 5 votes vote down vote up
private TypeMirror getIdentifiableConfigSourceTypeMirror(Types types, TypeMirror typeMirror) {
	final Queue<TypeMirror> typeMirrors = new LinkedList<>(Collections.singleton(typeMirror));
	while (!typeMirrors.isEmpty()) {
		final TypeMirror item = typeMirrors.remove();
		if (isIdentifiableConfigSource(item)) {
			return item;
		}
		typeMirrors.addAll(types.directSupertypes(item));
	}

	return null;
}
 
Example 12
Source File: AccountingLineValueAllowedValidation.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Recursively refreshes a property given by the queue path
 * @param bo the business object to refresh
 * @param path the path, in Queue form, of properties to refresh
 */
protected void refreshByQueue(PersistableBusinessObject bo, Queue<String> path) {
    if (path.size() > 1) { // we know that the last thing on our list is a code. why refresh that?
        String currentProperty = path.remove();
        bo.refreshReferenceObject(currentProperty);
        PersistableBusinessObject childBO = (PersistableBusinessObject)ObjectUtils.getPropertyValue(bo, currentProperty);
        if (!ObjectUtils.isNull(childBO)) {       
            refreshByQueue(childBO, path);
        }
    }
}
 
Example 13
Source File: PointWithDistanceUtil.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Util method that adds data point into heap if it fits (if heap size is less than {@code k} or a distance from
 * taget point to data point is less than a distance from target point to the most distant data point in heap).
 *
 * @param heap Heap with closest points.
 * @param k Number of neighbours.
 * @param dataPnt Data point to be added.
 * @param distance Distance to target point.
 * @param <L> Label type.
 */
public static <L> void tryToAddIntoHeap(Queue<PointWithDistance<L>> heap, int k, LabeledVector<L> dataPnt,
    double distance) {
    if (dataPnt != null) {
        if (heap.size() == k && heap.peek().getDistance() > distance)
            heap.remove();

        if (heap.size() < k)
            heap.add(new PointWithDistance<>(dataPnt, distance));
    }
}
 
Example 14
Source File: DependencyGraphSummarizer.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
public GraphSummary fromGraph(final DependencyGraph graph) {
    final Queue<Dependency> unprocessed = new LinkedList<>(graph.getRootDependencies());
    final Set<Dependency> processed = new HashSet<>();

    final GraphSummary graphSummary = new GraphSummary();

    while (unprocessed.size() > 0) {
        final Dependency nextDependency = unprocessed.remove();
        processed.add(nextDependency);

        final BdioId nextId = nextDependency.getExternalId().createBdioId();
        if (!graphSummary.dependencySummaries.containsKey(nextId)) {
            final NameVersion nameVersion = new NameVersion();
            nameVersion.setName(nextDependency.getName());
            nameVersion.setVersion(nextDependency.getVersion());
            graphSummary.dependencySummaries.put(nextId, nameVersion);
        }

        for (final Dependency dep : graph.getChildrenForParent(nextDependency)) {
            if (!graphSummary.externalDataIdRelationships.containsKey(nextId)) {
                graphSummary.externalDataIdRelationships.put(nextId, new HashSet<>());
            }
            graphSummary.externalDataIdRelationships.get(nextId).add(dep.getExternalId().createBdioId());
            if (!processed.contains(dep)) {
                unprocessed.add(dep);
            }
        }
    }

    for (final ExternalId externalId : graph.getRootDependencyExternalIds()) {
        graphSummary.rootExternalDataIds.add(externalId.createBdioId());
    }

    return graphSummary;
}
 
Example 15
Source File: SearchingTechniques.java    From big-o with MIT License 5 votes vote down vote up
private static <T> boolean doBfs(
		Map<GraphNode<T>, List<GraphNode<T>>> graph,
		GraphNode<T> startNode, GraphNode<T> nodeToBeSearched) {
	if (startNode.equals(nodeToBeSearched)) {
		return true;
	}

	Set<GraphNode<T>> visited = new HashSet<GraphNode<T>>();
	Queue<GraphNode<T>> queue = new LinkedList<GraphNode<T>>();
	visited.add(startNode);

	while (!queue.isEmpty()) {
		GraphNode<T> node = queue.remove();

		for (GraphNode<T> adjacentNode : graph.get(node)) {
			if (!visited.contains(adjacentNode)) {
				if (adjacentNode.equals(nodeToBeSearched)) {
					return true;
				}
				visited.add(adjacentNode);
				queue.add(adjacentNode);
			}
		}
	}

	return false;
}
 
Example 16
Source File: TaskSchedulePlanBuilder.java    From twister2 with Apache License 2.0 5 votes vote down vote up
ChainedContainerComparator(Queue<Scorer<T>> scorers) {
  if (scorers.isEmpty()) {
    this.comparator = new EqualsComparator<>();
    this.tieBreaker = null;
  } else {
    this.comparator = new ContainerComparator<>(scorers.remove());
    this.tieBreaker = new ChainedContainerComparator<>(scorers);
  }
}
 
Example 17
Source File: PackerTest.java    From beepbeep-3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void listPackerTest1() throws ProcessorException, InterruptedException
{
	TimePack lpp = new TimePack(1000);
	QueueSink sink = new QueueSink();
	Connector.connect(lpp, sink);
	Queue<Object> q = sink.getQueue();
	Pushable p = lpp.getPushableInput();
	lpp.start();
	for (int i = 0; i < 5; i++)
	{
		p.push(i);
	}
	Thread.sleep(1200);
	assertFalse(q.isEmpty());
	List<Object> list = (List<Object>) q.remove();
	assertEquals(5, list.size());
	for (int i = 20; i < 26; i++)
	{
		p.push(i);
	}
	assertTrue(q.isEmpty()); // Too early
	Thread.sleep(1200);
	list = (List<Object>) q.remove();
	assertEquals(6, list.size());
	lpp.stop();
}
 
Example 18
Source File: Window.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private Tuple2<Long, Double> increase(Double value, ID id, long windowSize) {
    if (!windows.containsKey(id)) {
        windows.put(id, new LinkedList<>());
    }
    Queue<Tuple2<Long, Double>> window = windows.get(id);
    long now = System.currentTimeMillis();
    window.offer(Tuple.of(now, value));
    Tuple2<Long, Double> ps = window.element();
    if ((now - ps._1) >= windowSize) {
        window.remove();
    }
    return ps;
}
 
Example 19
Source File: DuplicationFilter.java    From BungeeChat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String applyFilter(BungeeChatAccount sender, String message) throws BlockMessageException {
  if (!noPermissions && PermissionManager.hasPermission(sender, Permission.BYPASS_ANTI_DUPLICATE))
    return message;

  final UUID uuid = sender.getUniqueId();

  if (!playerMessagesStorage.containsKey(uuid)) {
    playerMessagesStorage.put(uuid, new ArrayDeque<>(checkPastMessages));
  }

  final Queue<TimePointMessage> playerMessages = playerMessagesStorage.get(uuid);
  final long now = System.nanoTime();
  final long expiry = now - expiryTimer;

  while (!playerMessages.isEmpty() && (playerMessages.peek().getTimePoint() < expiry)) {
    playerMessages.poll();
  }

  if (playerMessages.stream().map(TimePointMessage::getMessage).anyMatch(message::equals))
    throw new ExtendedBlockMessageException(Messages.ANTI_DUPLICATION, sender, message);

  if (playerMessages.size() == checkPastMessages) {
    playerMessages.remove();
  }

  playerMessages.add(new TimePointMessage(now, message));

  return message;
}
 
Example 20
Source File: BrokerFailureDetectorTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testFailureDetection() throws Exception {
  Time mockTime = getMockTime();
  Queue<Anomaly> anomalies = new PriorityBlockingQueue<>(ANOMALY_DETECTOR_INITIAL_QUEUE_SIZE, anomalyComparator());
  BrokerFailureDetector detector = createBrokerFailureDetector(anomalies, mockTime);
  try {
    // Start detection.
    detector.startDetection();
    assertTrue(anomalies.isEmpty());
    int brokerId = 0;
    killBroker(brokerId);
    long start = System.currentTimeMillis();
    while (anomalies.isEmpty() && System.currentTimeMillis() < start + 30000) {
      // wait for the anomalies to be drained.
    }
    assertEquals("One broker failure should have been detected before timeout.", 1, anomalies.size());
    Anomaly anomaly = anomalies.remove();
    assertTrue("The anomaly should be BrokerFailure", anomaly instanceof BrokerFailures);
    BrokerFailures brokerFailures = (BrokerFailures) anomaly;
    assertEquals("The failed broker should be 0 and time should be 100L", Collections.singletonMap(brokerId, 100L),
                 brokerFailures.failedBrokers());
    assertFalse(brokerFailures.fixable());

    // Ensure that broker failure is detected as long as the broker is down.
    detector.detectBrokerFailures(false);
    assertEquals("One broker failure should have been detected before timeout.", 1, anomalies.size());
    // Bring the broker back
    restartDeadBroker(brokerId);
    detector.detectBrokerFailures(true);
    assertTrue(detector.failedBrokers().isEmpty());
  } finally {
    detector.shutdown();
  }
}