@Test public void Deque_addFirst_AddsTwo() { deque.addFirst("firstString"); deque.addFirst("secondString"); assertFalse(deque.isEmpty()); assertEquals(deque.size(), 2); }
private void flatten() { // We use iterative traversal as recursion may exceed the stack size limit. final char[] chars = new char[length]; int pos = length; // Strings are most often composed by appending to the end, which causes ConsStrings // to be very unbalanced, with mostly single string elements on the right and a long // linear list on the left. Traversing from right to left helps to keep the stack small // in this scenario. final Deque<CharSequence> stack = new ArrayDeque<>(); stack.addFirst(left); CharSequence cs = right; do { if (cs instanceof ConsString) { final ConsString cons = (ConsString) cs; stack.addFirst(cons.left); cs = cons.right; } else { final String str = (String) cs; pos -= str.length(); str.getChars(0, str.length(), chars, pos); cs = stack.isEmpty() ? null : stack.pollFirst(); } } while (cs != null); left = new String(chars); right = ""; flat = true; }
@Test(expected = NoSuchElementException.class) public void Deque_addLast_removeFirst_throwsIfEmpty() { deque.addFirst("firstString"); deque.addFirst("secondString"); deque.removeLast(); deque.removeLast(); deque.removeFirst(); }
@Test public void Deque_iterator_hasNextIsFalse() { deque.addFirst("firstString"); deque.addFirst("secondString"); Iterator<String> dequeIterator = deque.iterator(); dequeIterator.next(); dequeIterator.next(); assertFalse(dequeIterator.hasNext()); }
public static <T extends FlowRenderable<T>> Iterable<LaidFlowLine<T>> getLines( Collection<T> flowRenderables, TextRenderStyle defaultRenderStyle, int yStart, ContainerRenderSpace containerRenderSpace) { // Take into account a minimum width int minWidth = determineMinWidth(flowRenderables, defaultRenderStyle); int x = 0; int y = yStart; int availableWidth = Math.max(minWidth, containerRenderSpace.getWidthForVerticalPosition(y)); List<LaidFlowLine<T>> result = new LinkedList<>(); int maxHeightInLine = 0; Deque<T> renderablesQueue = new LinkedList<>(flowRenderables); List<T> renderablesInLine = new LinkedList<>(); while (!renderablesQueue.isEmpty()) { FlowRenderable<T> flowRenderable = renderablesQueue.removeFirst(); FlowRenderable.SplitResult<T> splitResult = flowRenderable.splitAt(defaultRenderStyle, availableWidth - x); if (splitResult.before == null) { // This is the end of the line, this renderable doesn't fit result.add(new DefaultLaidFlowLine<>(x, maxHeightInLine, renderablesInLine)); renderablesInLine = new LinkedList<>(); x = 0; y += maxHeightInLine; availableWidth = Math.max(minWidth, containerRenderSpace.getWidthForVerticalPosition(y)); maxHeightInLine = 0; renderablesQueue.addFirst(splitResult.rest); } else { // Append the "before" part and push the "rest" onto the Deque if not null int renderableWidth = splitResult.before.getWidth(defaultRenderStyle); int renderableHeight = splitResult.before.getHeight(defaultRenderStyle); x += renderableWidth; maxHeightInLine = Math.max(maxHeightInLine, renderableHeight); renderablesInLine.add(splitResult.before); if (splitResult.rest != null) { result.add(new DefaultLaidFlowLine<>(x, maxHeightInLine, renderablesInLine)); renderablesInLine = new LinkedList<>(); x = 0; y += maxHeightInLine; availableWidth = Math.max(minWidth, containerRenderSpace.getWidthForVerticalPosition(y)); maxHeightInLine = 0; renderablesQueue.addFirst(splitResult.rest); } } } result.add(new DefaultLaidFlowLine<>(x, maxHeightInLine, renderablesInLine)); return result; }
@Test(expected = NoSuchElementException.class) public void Deque_iterator_throwsNoSuchElement() { deque.addFirst("firstString"); deque.addFirst("secondString"); Iterator<String> dequeIterator = deque.iterator(); dequeIterator.next(); dequeIterator.next(); dequeIterator.next(); }
@Test public void Deque_iterator_iterates() { deque.addFirst("firstString"); deque.addFirst("secondString"); deque.addLast("thirdString"); Iterator<String> dequeIterator = deque.iterator(); assertEquals(dequeIterator.next(), "secondString"); assertEquals(dequeIterator.next(), "firstString"); assertEquals(dequeIterator.next(), "thirdString"); }
/** * @param namedElement named element * @return ancestors of the named element, beginning with the root namespace and ending with the * named element itself, skipping local scopes */ public static Iterable<? extends INamedElement> ancestors(final INamedElement namedElement) { final Deque<INamedElement> ancestors = new LinkedList<>(); INamedElement ancestor = namedElement; while (membership(ancestor) != ScopeMembership.Root) { ancestors.addFirst(ancestor); ancestor = parentNamedElementOfScope(ancestor.parent()); } ancestors.addFirst(ancestor); return ancestors; }
@Override public void reset() { this.version = null; this.url = null; this.method = null; stateStack.addFirst(State.REQUEST_LINE_END); stateStack.addFirst(State.HTTP_VERSION); stateStack.addFirst(State.REQUEST_URI); stateStack.addFirst(State.METHOD); }
/** * Construct a new instance. * * @param componentDescription the associated component description * @param viewClassName the view class name * @param defaultConfiguratorRequired */ public ViewDescription( final ComponentDescription componentDescription, final String viewClassName, final boolean defaultConfiguratorRequired) { this.componentDescription = componentDescription; this.viewClassName = viewClassName; if (defaultConfiguratorRequired) { configurators.addFirst(DefaultConfigurator.INSTANCE); } configurators.addFirst(ViewBindingConfigurator.INSTANCE); }
public static boolean dfsIterative(TreeNode root, int val) { Deque<TreeNode> s = new LinkedList<>(); s.push(root); while (!s.isEmpty()) { TreeNode curr = s.removeFirst(); if (curr.value == val) return true; if (curr.left != null) s.addFirst(curr.left); if (curr.right != null) s.addFirst(curr.right); } return false; }
@Test public void Deque_addFirst_removeFirst_AddsRemovesTwo() { deque.addFirst("firstString"); deque.addFirst("secondString"); assertFalse(deque.isEmpty()); assertEquals(deque.size(), 2); String returnedString = deque.removeFirst(); assertEquals(returnedString, "secondString"); assertFalse(deque.isEmpty()); assertEquals(deque.size(), 1); returnedString = deque.removeFirst(); assertEquals(returnedString, "firstString"); assertTrue(deque.isEmpty()); assertEquals(deque.size(), 0); }
public T undo() { if (isUndoable()) { future.addFirst(present); present = past.removeFirst(); } return present; }
/* (non-Javadoc) * @see botFramework.IBot#sendCommands() */ public void sendCommands() { String command; boolean success; while (!queuedCommands.isEmpty()) { command = queuedCommands.removeFirst(); success = send(command); if (success == false) { queuedCommands.addFirst(command); log.error("error sending command. will reconnect and retry"); sendErrorEvent("Bot.sendCommands", "problem", "Could not send - reconnecting"); reconnect("Write error!"); return; } } try { sender.flush(); } catch (SocketTimeoutException e) { log.error("socket timeout while flushing", e); sendErrorEvent("Bot.sendCommands", "SocketTimeoutException", e.getMessage()); } catch (IOException e) { log.error("ioexception while flushing", e); sendErrorEvent("Bot.sendCommands", "IOException", e.getMessage()); reconnect("Write error!"); } }
/** This method builds an actual tree from multiple path. */ private ARGState buildTreeFromMultiplePaths(final Collection<ARGPath> targetPaths) { ARGState itpTreeRoot = null; Deque<ARGState> todo = new ArrayDeque<>(extractTargets(targetPaths)); // build the tree, bottom-up, starting from the target states while (!todo.isEmpty()) { final ARGState currentState = todo.removeFirst(); if (currentState.getParents().iterator().hasNext()) { if (!predecessorRelation.containsKey(currentState)) { ARGState parentState = currentState.getParents().iterator().next(); predecessorRelation.put(currentState, parentState); successorRelation.put(parentState, currentState); todo.addFirst(parentState); } } else if (itpTreeRoot == null) { itpTreeRoot = currentState; } } return itpTreeRoot; }
public T redo() { if (isRedoable()) { past.addFirst(present); present = future.removeFirst(); } return present; }
public void insert(T state) { past.addFirst(present); if (past.size() > limit) { past.removeLast(); } future.clear(); present = state; }
/** * Performs a depth-first, post-order traversal over a DAG. * * @param initialNodes The nodes from which to perform the traversal. Not allowed to contain * {@code null}. * @throws CycleException if a cycle is found while performing the traversal. */ @SuppressWarnings("PMD.PrematureDeclaration") public void traverse(Iterable<? extends T> initialNodes) throws CycleException, IOException, InterruptedException { // This corresponds to the current chain of nodes being explored. Enforcing this invariant makes // this data structure useful for debugging. Deque<Explorable> toExplore = Lists.newLinkedList(); for (T node : initialNodes) { toExplore.add(new Explorable(node)); } Set<T> inProgress = Sets.newHashSet(); LinkedHashSet<T> explored = Sets.newLinkedHashSet(); while (!toExplore.isEmpty()) { Explorable explorable = toExplore.peek(); T node = explorable.node; // This could happen if one of the initial nodes is a dependency of the other, for example. if (explored.contains(node)) { toExplore.removeFirst(); continue; } inProgress.add(node); // Find children that need to be explored to add to the stack. int stackSize = toExplore.size(); for (Iterator<T> iter = explorable.children; iter.hasNext(); ) { T child = iter.next(); if (inProgress.contains(child)) { throw createCycleException(child, toExplore); } else if (!explored.contains(child)) { toExplore.addFirst(new Explorable(child)); // Without this break statement: // (1) Children will be explored in reverse order instead of the specified order. // (2) CycleException may contain extra nodes. // Comment out the break statement and run the unit test to verify this for yourself. break; } } if (stackSize == toExplore.size()) { // Nothing was added to toExplore, so the current node can be popped off the stack and // marked as explored. toExplore.removeFirst(); inProgress.remove(node); explored.add(node); // Now that the internal state of this traversal has been updated, notify the observer. onNodeExplored(node); } } Preconditions.checkState(inProgress.isEmpty(), "No more nodes should be in progress."); onTraversalComplete(Iterables.unmodifiableIterable(explored)); }
private void fillNodes(Node node, Deque<Node> nodes) { if (node.entity == null) { return; } nodes.addFirst(node); if (node.parent != null) { this.fillNodes(node.parent, nodes); } }
public void fillBuild(Deque<Entity> build) { if (this.entity == null) { return; } build.addFirst(this.entity); if (this.parent != null) { this.parent.fillBuild(build); } }
@Override public void include(int line, int column, int currentFile, String incFile) { IncludeRef newRef = new IncludeRef(currRef, line, column); scopeStack.addFirst(new Scope(newRef)); currRef.macroEventList.add(newRef); currInclude = newRef; currRef = newRef; newRef.fileIndex = currentFile; newRef.setFileRefName(incFile); }
private void doAdd(@NotNull T element, boolean atHead) { synchronized (myQueue) { if (atHead) { myQueue.addFirst(element); } else { myQueue.add(element); } startProcessing(); } }
public boolean getNextBlock() throws IOException { if (curRangeIndex < 0 || curRangeIndex >= indexes.size()) return false; /* seek to the correct offset to the data, and calculate the data size */ IndexHelper.IndexInfo curColPosition = indexes.get(curRangeIndex); /* see if this read is really necessary. */ if (reversed) { if ((finishColumn.length > 0 && comparator.compare(finishColumn, curColPosition.lastName) > 0) || (startColumn.length > 0 && comparator.compare(startColumn, curColPosition.firstName) < 0)) return false; } else { if ((startColumn.length > 0 && comparator.compare(startColumn, curColPosition.lastName) > 0) || (finishColumn.length > 0 && comparator.compare(finishColumn, curColPosition.firstName) < 0)) return false; } boolean outOfBounds = false; // seek to current block // curIndexInfo.offset is the relative offset from the first block file.seek(firstBlockPos + curColPosition.offset); // read all columns of current block into memory! DataInputStream blockIn = ColumnFamily.serializer() .getBlockInputStream(file, curColPosition.sizeOnDisk, compressContext); try { int size = 0; while ((size < curColPosition.width) && !outOfBounds) { IColumn column = emptyColumnFamily.getColumnSerializer().deserialize(blockIn); size += column.serializedSize(); if (reversed) blockColumns.addFirst(column); else blockColumns.addLast(column); /* see if we can stop seeking. */ if (!reversed && finishColumn.length > 0) outOfBounds = comparator.compare(column.name(), finishColumn) >= 0; else if (reversed && startColumn.length > 0) outOfBounds = comparator.compare(column.name(), startColumn) >= 0; if (outOfBounds) break; } } catch (IOException e) { logger.error(e.toString()); throw e; } finally { ColumnFamily.serializer().releaseBlockInputStream(blockIn, compressContext); } if (reversed) curRangeIndex--; else curRangeIndex++; return true; }
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String elem = localName; if (elem.isEmpty()) { elem = qName; } elemStack.addFirst(elem); ElementHandler contextHandler = handlerStack.getFirst(); ElementHandler elemHandler = contextHandler.getHandler(elem); if (elemHandler == null) { throw new IllegalStateException( String.format( "Context handler %s have not returned handler for elem %s", contextHandler, elemStack)); } handlerStack.addFirst(elemHandler); elemHandler.startElement(attributes); }
@Override public void startDocument() throws SAXException { handlerStack.clear(); elemStack.clear(); lemmasParsed = 0; acceptedLemmaCounter = 0; rejectedLemmaCounter = 0; finished = false; rootHandler = new RootHandler(new DictionaryElemHandler()); handlerStack.addFirst(rootHandler); }
/** * Parses the next AST for declarations. * * @param frameStack stack containing the FrameTree being built. * @param ast AST to parse. */ private static void collectDeclarations(Deque<AbstractFrame> frameStack, DetailAST ast) { final AbstractFrame frame = frameStack.peek(); switch (ast.getType()) { case TokenTypes.VARIABLE_DEF: collectVariableDeclarations(ast, frame); break; case TokenTypes.PARAMETER_DEF: final DetailAST parameterIdent = ast.findFirstToken(TokenTypes.IDENT); frame.addIdent(parameterIdent); break; case TokenTypes.CLASS_DEF: case TokenTypes.INTERFACE_DEF: case TokenTypes.ENUM_DEF: case TokenTypes.ANNOTATION_DEF: final DetailAST classFrameNameIdent = ast.findFirstToken(TokenTypes.IDENT); frameStack.addFirst(new ClassFrame(frame, classFrameNameIdent)); break; case TokenTypes.SLIST: frameStack.addFirst(new BlockFrame(frame, ast)); break; case TokenTypes.METHOD_DEF: final DetailAST methodFrameNameIdent = ast.findFirstToken(TokenTypes.IDENT); if (frame.getType() == FrameType.CLASS_FRAME) { final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS); if (mods.branchContains(TokenTypes.LITERAL_STATIC)) { ((ClassFrame) frame).addStaticMethod(methodFrameNameIdent); } else { ((ClassFrame) frame).addInstanceMethod(methodFrameNameIdent); } } frameStack.addFirst(new MethodFrame(frame, methodFrameNameIdent)); break; case TokenTypes.CTOR_DEF: final DetailAST ctorFrameNameIdent = ast.findFirstToken(TokenTypes.IDENT); frameStack.addFirst(new ConstructorFrame(frame, ctorFrameNameIdent)); break; default: // do nothing } }
/** * Parse the next AST for declarations. * * @param frameStack Stack containing the FrameTree being built * @param ast AST to parse */ private static void collectDeclarations(Deque<LexicalFrame> frameStack, DetailAST ast) { final LexicalFrame frame = frameStack.peek(); switch (ast.getType()) { case TokenTypes.VARIABLE_DEF: collectVariableDeclarations(ast, frame); break; case TokenTypes.PARAMETER_DEF: final DetailAST parameterAST = ast.findFirstToken(TokenTypes.IDENT); frame.addName(parameterAST.getText()); break; case TokenTypes.CLASS_DEF: case TokenTypes.INTERFACE_DEF: case TokenTypes.ENUM_DEF: case TokenTypes.ANNOTATION_DEF: final DetailAST classAST = ast.findFirstToken(TokenTypes.IDENT); frame.addName(classAST.getText()); frameStack.addFirst(new ClassFrame(frame)); break; case TokenTypes.SLIST: frameStack.addFirst(new BlockFrame(frame)); break; case TokenTypes.METHOD_DEF: final String name = ast.findFirstToken(TokenTypes.IDENT).getText(); if (frame instanceof ClassFrame) { final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS); if (mods.branchContains(TokenTypes.LITERAL_STATIC)) { ((ClassFrame) frame).addStaticMethod(name); } else { ((ClassFrame) frame).addInstanceMethod(name); } } frameStack.addFirst(new MethodFrame(frame)); break; case TokenTypes.CTOR_DEF: frameStack.addFirst(new MethodFrame(frame)); break; default: // do nothing } }
@Override public void run() { for (int i = 0; i < 100; ++i) { Event event = new Event(Thread.currentThread().getName() + "_" + i, new Date()); deque.addFirst(event); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }
@VisibleForTesting IToken nextToken(final Supplier<Deque<IRobotLineElement>> elementsQueueSupplier) { if (tokensToAnalyze == null) { tokensToAnalyze = elementsQueueSupplier.get(); final IRobotLineElement firstToken = tokensToAnalyze.peekFirst(); if (firstToken != null) { currentOffsetInToken = rangeOffset - firstToken.getStartOffset(); } } if (tokensToAnalyze.isEmpty()) { lastTokenPosition = new Position(getTokenOffset() + getTokenLength(), 0); return Token.EOF; } final IRobotLineElement nextToken = tokensToAnalyze.poll(); for (final ISyntaxColouringRule rule : rules) { if (!rule.isApplicable(nextToken)) { continue; } final Optional<PositionedTextToken> tok = rule.evaluate(nextToken, currentOffsetInToken, analyzedTokens); if (tok.isPresent()) { final PositionedTextToken textToken = tok.get(); lastTokenPosition = textToken.getPosition(); if (lastTokenPosition.offset + lastTokenPosition.length >= nextToken.getStartOffset() + nextToken.getText().length()) { // rule have consumed whole Robot Token currentOffsetInToken = 0; analyzedTokens.add(nextToken); } else { // the token needs more coloring, so return it to queue and shift the // offset currentOffsetInToken = lastTokenPosition.getOffset() + lastTokenPosition.getLength() - nextToken.getStartOffset(); tokensToAnalyze.addFirst(nextToken); } return textToken.getToken(); } } lastTokenPosition = new Position( nextToken.getStartOffset() + currentOffsetInToken, nextToken.getText().length() - currentOffsetInToken); currentOffsetInToken = 0; analyzedTokens.add(nextToken); return ISyntaxColouringRule.DEFAULT_TOKEN; }
@Override public void onUpdate() { super.onUpdate(); int phase = (initialPhase + particleAge) % 64; motionY = 0.1f; motionX = cos[phase] * Config.soulFXPerturb; motionZ = sin[phase] * Config.soulFXPerturb; particleTrail.addFirst(new Double3(posX, posY, posZ)); while (particleTrail.size() > Config.soulFXTrailLength) particleTrail.removeLast(); if (!Config.globalEnabled) setDead(); }