java.util.ArrayDeque Java Examples

The following examples show how to use java.util.ArrayDeque. 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: RecordWriterTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that broadcasted events' buffers are independent (in their (reader) indices) once they
 * are put into the queue for Netty when broadcasting events to multiple channels.
 */
@Test
public void testBroadcastEventBufferIndependence() throws Exception {
	@SuppressWarnings("unchecked")
	ArrayDeque<BufferConsumer>[] queues =
		new ArrayDeque[]{new ArrayDeque(), new ArrayDeque()};

	ResultPartitionWriter partition =
		new CollectingPartitionWriter(queues, new TestPooledBufferProvider(Integer.MAX_VALUE));
	RecordWriter<?> writer = new RecordWriter<>(partition);

	writer.broadcastEvent(EndOfPartitionEvent.INSTANCE);

	// Verify added to all queues
	assertEquals(1, queues[0].size());
	assertEquals(1, queues[1].size());

	// these two buffers may share the memory but not the indices!
	Buffer buffer1 = buildSingleBuffer(queues[0].remove());
	Buffer buffer2 = buildSingleBuffer(queues[1].remove());
	assertEquals(0, buffer1.getReaderIndex());
	assertEquals(0, buffer2.getReaderIndex());
	buffer1.setReaderIndex(1);
	assertEquals("Buffer 2 shares the same reader index as buffer 1", 0, buffer2.getReaderIndex());
}
 
Example #2
Source File: UpstreamJobBuffer.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public synchronized void clearTerminatedJobs() {
    Iterator<Map.Entry<Long, UpstreamJob>> itr = workingJobs.entrySet().iterator();
    while (itr.hasNext()) {
        UpstreamJob job = itr.next().getValue();
        if (job.isTerminated()) {
            job.terminate();
            itr.remove();
        }
    }
    Queue<UpstreamJob> oldQueue = queue;
    queue = new ArrayDeque<>();
    oldQueue.forEach(job -> {
        if (!job.isTerminated()) {
            queue.add(job);
        }
    });
}
 
Example #3
Source File: BiomeDictionary.java    From patchwork-api with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Collection<Type> listSupertypes(Type... types) {
	Set<Type> supertypes = new HashSet<>();
	Deque<Type> next = new ArrayDeque<>();
	Collections.addAll(next, types);

	while (!next.isEmpty()) {
		Type type = next.remove();

		for (Type sType : Type.BY_NAME.values()) {
			if (sType.subTypes.contains(type) && supertypes.add(sType)) {
				next.add(sType);
			}
		}
	}

	return supertypes;
}
 
Example #4
Source File: VplsOperationManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Optimize operations with first is REMOVE operation and last is ADD
 * operation.
 */
@Test
public void testOptimizeOperationsRToA() {
    Deque<VplsOperation> operations = new ArrayDeque<>();
    VplsData vplsData = VplsData.of(VPLS1);
    vplsData.addInterfaces(ImmutableSet.of(V100H1));
    VplsOperation vplsOperation = VplsOperation.of(vplsData,
                                                   VplsOperation.Operation.REMOVE);
    operations.add(vplsOperation);
    vplsData = VplsData.of(VPLS1, EncapsulationType.VLAN);
    vplsData.addInterfaces(ImmutableSet.of(V100H1, V100H2));
    vplsOperation = VplsOperation.of(vplsData,
                                     VplsOperation.Operation.ADD);
    operations.add(vplsOperation);
    vplsOperation = VplsOperationManager.getOptimizedVplsOperation(operations);
    assertEquals(VplsOperation.of(vplsData, VplsOperation.Operation.UPDATE), vplsOperation);
}
 
Example #5
Source File: ChuLiuEdmonds.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
public static PartialSolution initialize(WeightedGraph graph) {
    final Partition<Node> stronglyConnected = Partition.singletons(graph.getNodes());
    final HashMap<Node, Weighted<DirectedEdge>> incomingByScc = new HashMap<>();
    final Deque<ExclusiveEdge> exclusiveEdges = new ArrayDeque<>();
    // group edges by their destination component
    final EdgeQueueMap incomingEdges = new EdgeQueueMap(stronglyConnected);
    for (Node destinationNode : graph.getNodes()) {
        for (Weighted<DirectedEdge> inEdge : graph.getIncomingEdges(destinationNode)) {
            if (inEdge.weight != Double.NEGATIVE_INFINITY) {
                incomingEdges.addEdge(inEdge);
            }
        }
    }
    return new PartialSolution(
            stronglyConnected,
            Partition.singletons(graph.getNodes()),
            incomingByScc,
            exclusiveEdges,
            incomingEdges,
            0.0
    );
}
 
Example #6
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method for import declarations, names, and qualified names.
 */
private void visitName(Tree node) {
    Deque<Name> stack = new ArrayDeque<>();
    for (; node instanceof MemberSelectTree; node = ((MemberSelectTree) node).getExpression()) {
        stack.addFirst(((MemberSelectTree) node).getIdentifier());
    }
    stack.addFirst(((IdentifierTree) node).getName());
    boolean first = true;
    for (Name name : stack) {
        if (!first) {
            token(".");
        }
        token(name.toString());
        first = false;
    }
}
 
Example #7
Source File: Operations.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** Returns bitset marking states reachable from the initial state. */
private static BitSet getLiveStatesFromInitial(Automaton a) {
  int numStates = a.getNumStates();
  BitSet live = new BitSet(numStates);
  if (numStates == 0) {
    return live;
  }
  ArrayDeque<Integer> workList = new ArrayDeque<>();
  live.set(0);
  workList.add(0);

  Transition t = new Transition();
  while (workList.isEmpty() == false) {
    int s = workList.removeFirst();
    int count = a.initTransition(s, t);
    for(int i=0;i<count;i++) {
      a.getNextTransition(t);
      if (live.get(t.dest) == false) {
        live.set(t.dest);
        workList.add(t.dest);
      }
    }
  }

  return live;
}
 
Example #8
Source File: SchemaContextUtil.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final QNameModule localNamespace,
        final YangLocationPath path) {
    final Deque<QName> ret = new ArrayDeque<>();
    for (Step step : path.getSteps()) {
        if (step instanceof AxisStep) {
            // We only support parent axis steps
            final YangXPathAxis axis = ((AxisStep) step).getAxis();
            checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
            ret.removeLast();
            continue;
        }

        // This has to be a QNameStep
        checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
        ret.addLast(resolve(((QNameStep) step).getQName(), localNamespace));
    }

    return findTargetNode(context, ret);
}
 
Example #9
Source File: SunLight.java    From Cubes with MIT License 6 votes vote down vote up
private static void propagateRemove(ArrayDeque<LightNode> removeQueue, ArrayDeque<LightNode> addQueue, LightWorldSection w) {
  if (removeQueue.isEmpty()) return;

  while (!removeQueue.isEmpty()) {
    LightNode n = removeQueue.pop();
    int x = n.x;
    int y = n.y;
    int z = n.z;
    int l = n.l;

    if (l <= 1) continue;

    tryPropagateRemove(removeQueue, addQueue, w, x - 1, y, z, l);
    tryPropagateRemove(removeQueue, addQueue, w, x + 1, y, z, l);
    tryPropagateRemove(removeQueue, addQueue, w, x, y, z - 1, l);
    tryPropagateRemove(removeQueue, addQueue, w, x, y, z + 1, l);
    if (y > 0)
      tryPropagateRemove(removeQueue, addQueue, w, x, y - 1, z, 16); //16 is higher than maximum light, therefore the sunlight is always removed
    tryPropagateRemove(removeQueue, addQueue, w, x, y + 1, z, l);
  }
}
 
Example #10
Source File: LPRoutedItem.java    From Logistics-Pipes-2 with MIT License 6 votes vote down vote up
public static LPRoutedItem readFromNBT(NBTTagCompound compound, TileGenericPipe holder) {
	double x = compound.getDouble("posX");
	double y = compound.getDouble("posY");
	double z = compound.getDouble("posZ");
	UUID id = compound.getUniqueId("UID");
	ItemStack content = new ItemStack(compound.getCompoundTag("inventory"));
	int ticks = compound.getInteger("ticks");
	Deque<EnumFacing> routingInfo = new ArrayDeque<>();
	NBTTagList routeList = (NBTTagList) compound.getTag("route");
	for(Iterator<NBTBase> i = routeList.iterator(); i.hasNext();) {
		NBTTagCompound node = (NBTTagCompound) i.next();
		EnumFacing nodeTuple = EnumFacing.values()[node.getInteger("heading")];
		routingInfo.add(nodeTuple);
	}
	LPRoutedItem item = new LPRoutedItem(x, y, z, content, ticks, id);
	item.setHeading(EnumFacing.VALUES[compound.getInteger("heading")]);
	item.setHolding(holder);
	item.route = routingInfo;
	return item;
}
 
Example #11
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
/**
 * 双端队列
 *
 * @param nums
 * @param k
 * @return
 */
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    if (len == 0) {
        return new int[0];
    }
    int[] res = new int[len - k + 1];
    Deque<Integer> queue = new ArrayDeque<>();
    for (int i = 0; i < len; i++) {
        if (i >= k && queue.getFirst() == i - k) {
            queue.removeFirst();
        }
        while (!queue.isEmpty() && nums[queue.getLast()] <= nums[i]) {
            queue.removeLast();
        }
        queue.add(i);

        if (i >= k - 1) {
            res[i - k + 1] = nums[queue.getFirst()];
        }
    }
    return res;
}
 
Example #12
Source File: AstHtmlRenderer.java    From doov with Apache License 2.0 6 votes vote down vote up
private void binary_SPACE(Metadata metadata, ArrayDeque<Metadata> parents) {
    final Optional<Metadata> pmd = parents.stream().skip(1).findFirst();
    final Operator pmdOperator = pmd.map(Metadata::getOperator).orElse(null);
    final boolean leftChild = pmd.map(m -> m.childAt(0) == metadata).orElse(false);
    if ((!leftChild || pmdOperator != or || metadata.getOperator() != and)) {
        // @see io.doov.core.dsl.meta.ast.HtmlAndTest.and_or_and()
        writer.writeExclusionBar(metadata, parents);
    }
    toHtml(metadata.childAt(0), parents);
    writer.write(SPACE);
    writer.writeBeginSpan(CSS_OPERATOR);
    writer.writeFromBundle(metadata.getOperator());
    writer.writeEndSpan();
    writer.write(SPACE);
    toHtml(metadata.childAt(1), parents);
}
 
Example #13
Source File: BisectingKMeansModelMapper.java    From Alink with Apache License 2.0 6 votes vote down vote up
private void assignClusterId() {
    Queue<TreeNode> queue = new ArrayDeque<>();
    queue.add(root);
    long id = 0L;
    treeNodeIds = new ArrayList<>();

    while (!queue.isEmpty()) {
        TreeNode top = queue.poll();
        if (top.isLeaf()) {
            top.clusterId = id;
            treeNodeIds.add(top.treeNodeId);
            id++;
        } else {
            if (top.leftChild != null) {
                queue.add(top.leftChild);
            }
            if (top.rightChild != null) {
                queue.add(top.rightChild);
            }
        }
    }
}
 
Example #14
Source File: VerifyPreorderSerializationOfABinaryTree.java    From LeetCode-Sol-Res with MIT License 6 votes vote down vote up
/**
 * Stack.
 * Iterate through the string characters.
 * If it's a number, just push to stack.
 * If it's a '#', we need to figure out some sub situations:
 * 1) If the top of the stack is a number, then this '#' is the left child, just push it.
 * 2) If the top of the stack is a '#', then this '#' is the right child, we should pop the subtree.
 * 2.1) After the subtree is popped, if the stack top is still '#', it means the subtree should be popped again.
 * 2.2) If the stack top is a number, we need to add a '#' to mark that the next node knows it's a right child.
 * https://discuss.leetcode.com/topic/35973/java-intuitive-22ms-solution-with-stack
 */
public boolean isValidSerialization(String preorder) {
  Deque<String> stack = new ArrayDeque<>();
  String[] nodes = preorder.split(",");
  for (int i = 0; i < nodes.length; i++) {
    String curr = nodes[i];
    while ("#".equals(curr) && !stack.isEmpty() && "#".equals(stack.peek())) {
      stack.pop();
      if (stack.isEmpty()) {
        return false;
      }
      stack.pop();
    }
    stack.push(curr);
  }
  return stack.size() == 1 && "#".equals(stack.peek());
}
 
Example #15
Source File: NegativeAcknowledgerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Test NegativeAcknowledger bulk action with a large batch
 */
@Test
public void testNackBulkActionLargeBatch() throws JMSException {

    /*
     * Set up the message queue
     */
    ArrayDeque<SQSMessageConsumerPrefetch.MessageManager> messageQueue = addSQSMessageToQueue(13);

    /*
     * Nack the messages in bulk actions
     */
    negativeAcknowledger.bulkAction(messageQueue, QUEUE_URL);

    /*
     * Verify results
     */
    verify(negativeAcknowledger, times(2)).action(eq(QUEUE_URL), anyList());
}
 
Example #16
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public SyncEngine(
    LocalStore localStore,
    RemoteStore remoteStore,
    User initialUser,
    int maxConcurrentLimboResolutions) {
  this.localStore = localStore;
  this.remoteStore = remoteStore;
  this.maxConcurrentLimboResolutions = maxConcurrentLimboResolutions;

  queryViewsByQuery = new HashMap<>();
  queriesByTarget = new HashMap<>();

  enqueuedLimboResolutions = new ArrayDeque<>();
  activeLimboTargetsByKey = new HashMap<>();
  activeLimboResolutionsByTarget = new HashMap<>();
  limboDocumentRefs = new ReferenceSet();

  mutationUserCallbacks = new HashMap<>();
  targetIdGenerator = TargetIdGenerator.forSyncEngine();
  currentUser = initialUser;

  pendingWritesCallbacks = new HashMap<>();
}
 
Example #17
Source File: FormattingXmlStreamWriter.java    From galleon with Apache License 2.0 6 votes vote down vote up
public void writeStartElement(final String localName) throws XMLStreamException {
    ArrayDeque<String> namespaces = unspecifiedNamespaces;
    String namespace = namespaces.getFirst();
    if (namespace != NO_NAMESPACE) {
        writeStartElement(namespace, localName);
        return;
    }

    unspecifiedNamespaces.push(namespace);

    // If this is a nested element flush the outer
    nl();
    indent();
    delegate.writeStartElement(localName);

    level++;
    state = START_ELEMENT;
    indentEndElement = false;
}
 
Example #18
Source File: NbProjectManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private <E extends Exception> void saveProjects(@NonNull final Class<E> clz) throws E {
    final Queue<Exception> causes = new ArrayDeque<Exception>();
    for (Project prj : projects) {
        try {
            owner.saveProject(prj);
        } catch (IOException ioe) {
            causes.add(ioe);
        }
    }
    if (!causes.isEmpty()) {
        try {
            final E exc = clz.getDeclaredConstructor().newInstance();
            for (Exception cause : causes) {
                exc.addSuppressed(cause);
            }
            throw  exc;
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException(e);
        }
    }
}
 
Example #19
Source File: QueryObjectProvider.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
public QueryObjectProvider(DatabaseSession databaseSession, BimServer bimServer, Query query, Set<Long> roids, PackageMetaData packageMetaData) throws IOException, QueryException {
	this.databaseSession = databaseSession;
	this.bimServer = bimServer;
	this.query = query;
	this.roids = roids;
	this.packageMetaData = packageMetaData;
	
	stack = new ArrayDeque<StackFrame>();
	stack.push(new StartFrame(this, roids));
	
	for (QueryPart queryPart : query.getQueryParts()) {
		if (queryPart.hasOids()) {
			goingToRead.addAll(queryPart.getOids());
		}
	}
}
 
Example #20
Source File: BlockingClient.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public void send(String address, List<Message> messages, long timeout, TimeUnit timeUnit) throws InterruptedException {
    ProtonClient client = ProtonClient.create(vertx);
    CountDownLatch latch = new CountDownLatch(1);
    Queue<Message> messageQueue = new ArrayDeque<>(messages);
    client.connect(host, port, connectEvent -> {
        if (connectEvent.succeeded()) {
            ProtonConnection connection = connectEvent.result();
            connection.open();

            ProtonSender sender = connection.createSender(address);
            sender.openHandler(senderOpenEvent -> {
                if (senderOpenEvent.succeeded()) {
                    sendNext(connection, sender, messageQueue, latch);
                }
            });
            sender.open();
        }
    });
    boolean ok = latch.await(timeout, timeUnit);
    if (!ok) {
        throw new RuntimeException("Sending messages timed out, " + messageQueue.size() + " messages unsent");
    }
}
 
Example #21
Source File: SearchFeatureDao.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private Optional<double[][]> toMatrix(ArrayDeque<double[]> sampledFeatures) {
    Optional<double[][]> samples;
    if (sampledFeatures.isEmpty()) {
        samples = Optional.empty();
    } else {
        samples = Optional.of(sampledFeatures.toArray(new double[0][0]));
    }
    return samples;
}
 
Example #22
Source File: ServerScheduler.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public int getQueueSize() {
    int size = pending.size();
    for (ArrayDeque<TaskHandler> queue : queueMap.values()) {
        size += queue.size();
    }
    return size;
}
 
Example #23
Source File: ProcessDataContext.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected Deque<String> getDeque(String property) {
  Deque<String> deque = propertyValues.get(property);
  if (deque == null) {
    deque = new ArrayDeque<>();
    propertyValues.put(property, deque);
  }
  return deque;
}
 
Example #24
Source File: ViewInspectorManager.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Nullable
private WXComponent findBoundComponentBy(@NonNull View targetView,@NonNull WXComponent rootComponent) {
    Deque<WXComponent> deque = new ArrayDeque<>();
    deque.add(rootComponent);
    WXComponent targetComponent = null;

    while (!deque.isEmpty()) {
        WXComponent component = deque.removeFirst();

        View view = component.getHostView();
        if(view != null && view.equals(targetView)) {
            targetComponent = component;
        }

        //we should take embed into account
        if(component instanceof WXEmbed) {
            WXComponent nestedRootComponent = ViewUtils.getNestedRootComponent((WXEmbed) component);
            if(nestedRootComponent != null) {
                deque.add(nestedRootComponent);
            }
        } else if(component instanceof WXVContainer) {
            WXVContainer container = (WXVContainer) component;
            for(int i = 0,len = container.getChildCount(); i < len; i++) {
                WXComponent c = container.getChild(i);
                deque.add(c);
            }
        }
    }

    return targetComponent;
}
 
Example #25
Source File: TyperVisitor.java    From rembulan with Apache License 2.0 5 votes vote down vote up
public TyperVisitor() {
	this.valTypes = new HashMap<>();
	this.phiValTypes = new HashMap<>();
	this.multiValTypes = new HashMap<>();
	this.varStates = new HashMap<>();

	this.allVars = new HashSet<>();
	this.reifiedVars = new HashSet<>();

	this.seen = new HashSet<>();
	this.open = new ArrayDeque<>();

	this.returnTypes = new HashSet<>();
}
 
Example #26
Source File: StatefulSequenceSource.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void initializeState(FunctionInitializationContext context) throws Exception {

	Preconditions.checkState(this.checkpointedState == null,
		"The " + getClass().getSimpleName() + " has already been initialized.");

	this.checkpointedState = context.getOperatorStateStore().getListState(
		new ListStateDescriptor<>(
			"stateful-sequence-source-state",
			LongSerializer.INSTANCE
		)
	);

	this.valuesToEmit = new ArrayDeque<>();
	if (context.isRestored()) {
		// upon restoring

		for (Long v : this.checkpointedState.get()) {
			this.valuesToEmit.add(v);
		}
	} else {
		// the first time the job is executed

		final int stepSize = getRuntimeContext().getNumberOfParallelSubtasks();
		final int taskIdx = getRuntimeContext().getIndexOfThisSubtask();
		final long congruence = start + taskIdx;

		long totalNoOfElements = Math.abs(end - start + 1);
		final int baseSize = safeDivide(totalNoOfElements, stepSize);
		final int toCollect = (totalNoOfElements % stepSize > taskIdx) ? baseSize + 1 : baseSize;

		for (long collected = 0; collected < toCollect; collected++) {
			this.valuesToEmit.add(collected * stepSize + congruence);
		}
	}
}
 
Example #27
Source File: BQLCompiler.java    From linden with Apache License 2.0 5 votes vote down vote up
private static TerminalNode getStartNode(ParseTree tree) {
  if (tree instanceof TerminalNode) {
    return (TerminalNode) tree;
  }

  Deque<ParseTree> workList = new ArrayDeque<ParseTree>();
  IntegerStack workIndexStack = new IntegerStack();
  workList.push(tree);
  workIndexStack.push(0);
  while (!workList.isEmpty()) {
    ParseTree currentTree = workList.peek();
    int currentIndex = workIndexStack.peek();
    if (currentIndex == currentTree.getChildCount()) {
      workList.pop();
      workIndexStack.pop();
      continue;
    }

    // move work list to next child
    workIndexStack.push(workIndexStack.pop() + 1);

    // process the current child
    ParseTree child = currentTree.getChild(currentIndex);
    if (child instanceof TerminalNode) {
      return (TerminalNode) child;
    }

    workList.push(child);
    workIndexStack.push(0);
  }

  return null;
}
 
Example #28
Source File: AbstractContentHandler.java    From eveapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Map<String, Set<String>> enableStrictCheckMode(boolean fullPath) {
    if (fullPath) {
        path = new ArrayDeque<>();
    }
    strictCheckMode = true;
    fields = new ConcurrentHashMap<>();
    return fields;
}
 
Example #29
Source File: AbstractFetcherWatermarksTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private static <T, KPH> void emitRecord(
		AbstractFetcher<T, KPH> fetcher,
		T record,
		KafkaTopicPartitionState<T, KPH> partitionState,
		long offset) {
	ArrayDeque<T> recordQueue = new ArrayDeque<>();
	recordQueue.add(record);

	fetcher.emitRecordsWithTimestamps(
			recordQueue,
			partitionState,
			offset,
			Long.MIN_VALUE);
}
 
Example #30
Source File: StreamTaskMultipleInputSelectiveReadingTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadFinishedInput() throws Exception {
	try {
		testInputSelection(new TestReadFinishedInputStreamOperatorFactory(), true, new ArrayDeque<>(), true);
		fail("should throw an IOException");
	} catch (Exception t) {
		if (!ExceptionUtils.findThrowableWithMessage(t, "Can not make a progress: all selected inputs are already finished").isPresent()) {
			throw t;
		}
	}
}