@Test @SuppressWarnings("unchecked") public void testGetTimeSinceLastMeasurement() throws Exception { long sleepTime = 20L; // fill history with the same value. long now = System.nanoTime() - 2 * sleepTime * 1000000; for (int i = 0; i < TestUtils.getPropertyValue(history, "retention", Integer.class); i++) { history.success(now); } final Deque<Long> times = TestUtils.getPropertyValue(history, "times", Deque.class); assertEquals(Long.valueOf(now), times.peekFirst()); assertEquals(Long.valueOf(now), times.peekLast()); // increment just so we'll have a different value between first and last history.success(System.nanoTime() - sleepTime * 1000000); assertNotEquals(times.peekFirst(), times.peekLast()); /* * We've called Thread.sleep twice with the same value in quick * succession. If timeSinceLastSend is pulling off the correct end of * the queue, then we should be closer to the sleep time than we are to * 2 x sleepTime, but we should definitely be greater than the sleep * time. */ double timeSinceLastMeasurement = history.getTimeSinceLastMeasurement(); assertThat(timeSinceLastMeasurement, Matchers.greaterThan((double) (sleepTime / 100))); assertThat(timeSinceLastMeasurement, Matchers.lessThanOrEqualTo(1.5 * sleepTime / 100)); }
private void doesEatRegime() { if (isEnd) return; if (Math.abs(blocks.peekFirst().getX() - regimeRectangle.getX()) < 10 && Math.abs(blocks.peekFirst().getY() - regimeRectangle.getY()) < 10 && System.currentTimeMillis() - currentTime <= 10000) { regimeRectangle.setX(1200); isRegime = false; ++score; scoreLabel.setText(String.valueOf(score)); blocks.pollLast(); blocks.pollLast(); blocks.pollLast(); group.getChildren().remove(rectangles.peekLast()); rectangles.pollLast(); group.getChildren().remove(rectangles.peekLast()); rectangles.pollLast(); group.getChildren().remove(rectangles.peekLast()); rectangles.pollLast(); } if (System.currentTimeMillis() - currentTime > 10000) { regimeRectangle.setX(1200); isRegime = false; } }
public Future<SessionMessage> requestMessage( Map<String, InputOperation> operations, ExecutionThread ethread) { final SessionMessageFuture future = new SessionMessageNDFuture(operations.keySet().toArray(new String[0])); ethread.cancelIfKilled(future); synchronized (messageQueues) { Deque<SessionMessage> queue = null; SessionMessage message = null; InputOperation operation = null; Iterator<Deque<SessionMessage>> it = messageQueues.values().iterator(); while (operation == null && it.hasNext()) { queue = it.next(); message = queue.peekFirst(); if (message != null) { operation = operations.get(message.message().operationName()); } } if (message == null) { queue = uncorrelatedMessageQueue; message = queue.peekFirst(); if (message != null) { operation = operations.get(message.message().operationName()); } } if (message == null || operation == null) { for (Map.Entry<String, InputOperation> entry : operations.entrySet()) { addMessageWaiter(entry.getValue(), future); } } else { future.setResult(message); queue.removeFirst(); // Check if we unlocked other receives boolean keepRun = true; SessionMessageFuture f; while (keepRun && !queue.isEmpty()) { message = queue.peekFirst(); f = getMessageWaiter(message.message().operationName()); if (f != null) { // We found a waiter for the unlocked message f.setResult(message); queue.removeFirst(); } else { keepRun = false; } } } } return future; }
private void play() { if (isReload) reloadGame(); if (isEnd || isPause) return; addFeed(); doesEatFeed(); addRegime(); doesEatRegime(); crossBorder(); head = blocks.peekFirst(); Block newHead = new Block(head.getX() + dx[inputDirection], head.getY() + dy[inputDirection]); Rectangle headRect = new Rectangle(head.getX(), head.getY(), 10, 10); if (isEnd(newHead)) { isEnd = true; // Image image = new Image(this.getClass().getResourceAsStream("/gameOver.png")); // ImageView imageView = new ImageView(image); // group.getChildren().add(imageView); // scene.setOnKeyPressed(null); saveRecord(); showRecord(); return; } else { blocks.push(newHead); rectangles.push(headRect); blocks.pollLast(); updateGui(); } }
Variable addVariable(final ParserRuleContext source, final String name, final Type type) { if (getVariable(name) != null) { if (source == null) { throw new IllegalArgumentException( "Argument name [" + name + "] already defined within the scope."); } else { throw new IllegalArgumentException( error(source) + "Variable name [" + name + "] already defined within the scope."); } } final Variable previous = variables.peekFirst(); int slot = 0; if (previous != null) { slot += previous.slot + previous.type.type.getSize(); } final Variable variable = new Variable(name, type, slot); variables.push(variable); final int update = scopes.pop() + 1; scopes.push(update); return variable; }
@Override public String paramVal(String name) { if (null == queryParams) { queryParams = hse.getQueryParameters(); } Deque<String> dq = queryParams.get(name); return null == dq ? null : dq.peekFirst(); }
@Nullable @Override public DataNode<ProjectData> resolveProjectInfo( @NotNull final ExternalSystemTaskId id, @NotNull final String projectPath, final boolean isPreviewMode, @Nullable final GradleExecutionSettings settings, @NotNull final ExternalSystemTaskNotificationListener listener) throws ExternalSystemException, IllegalArgumentException, IllegalStateException { final GradleProjectResolverExtension projectResolverChain; if (settings != null) { myHelper.ensureInstalledWrapper(id, projectPath, settings, listener); List<ClassHolder<? extends GradleProjectResolverExtension>> extensionClasses = settings.getResolverExtensions(); Deque<GradleProjectResolverExtension> extensions = new ArrayDeque<GradleProjectResolverExtension>(); for (ClassHolder<? extends GradleProjectResolverExtension> holder : extensionClasses) { final GradleProjectResolverExtension extension; try { extension = holder.getTargetClass().newInstance(); } catch (Throwable e) { throw new IllegalArgumentException( String.format( "Can't instantiate project resolve extension for class '%s'", holder.getTargetClassName()), e); } final GradleProjectResolverExtension previous = extensions.peekLast(); if (previous != null) { previous.setNext(extension); } extensions.add(extension); } projectResolverChain = extensions.peekFirst(); } else { projectResolverChain = new BaseGradleProjectResolverExtension(); } return myHelper.execute( projectPath, settings, new Function<ProjectConnection, DataNode<ProjectData>>() { @Override public DataNode<ProjectData> fun(ProjectConnection connection) { try { return doResolveProjectInfo( new ProjectResolverContext( id, projectPath, settings, connection, listener, isPreviewMode), projectResolverChain); } catch (RuntimeException e) { LOG.info("Gradle project resolve error", e); throw projectResolverChain.getUserFriendlyError(e, projectPath, null); } } }); }
private void doesEatFeed() { if (isEnd) return; if (Math.abs(blocks.peekFirst().getX() - feedRectangle.getX()) < 10 && Math.abs(blocks.peekFirst().getY() - feedRectangle.getY()) < 10) { feedRectangle.setX(1200); isFeed = false; ++feedCounter2; ++score; scoreLabel.setText(String.valueOf(score)); head = blocks.peekFirst(); Block newHead = new Block(head.getX() + dx[inputDirection], head.getY() + dy[inputDirection]); Rectangle headRect = new Rectangle(head.getX(), head.getY(), 10, 10); blocks.push(newHead); rectangles.push(headRect); } }
public List<Integer> maxWindows(int[] array, int k) { List<Integer> result = new ArrayList<Integer>(); Deque<Integer> deque = new LinkedList<>(); for (int i = 0; i < array.length; i++) { while (!deque.isEmpty() && array[deque.peekLast()] <= array[i]) { deque.pollLast(); } deque.offerLast(i); if (i - k == deque.peekFirst()) { deque.pollFirst(); } if (i >= k - 1) { result.add(array[deque.peekFirst()]); } } return result; }
@Override public void writeStartElement(String localName) throws XMLStreamException { try { if (objectQueue.size() == 1 && objectQueue.peekFirst().name == null) { // This is the root object. Append its name objectQueue.peekFirst().name = localName; } else { JsonObject jsonObject = new JsonObject(localName); if (!objectQueue.isEmpty()) { objectQueue.peek().addChild(localName, jsonObject); } objectQueue.push(jsonObject); } } catch (Exception e) { throw new XMLStreamException(e); } }
@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; }
public String removeDuplicateLetters(String s) { Deque<Character> stack = new LinkedList<>(); Map<Character, Integer> count = new HashMap<>(); for (int i = 0; i < s.length(); i++) { count.compute( s.charAt(i), (key, val) -> { if (val == null) { return 1; } else { return val + 1; } }); } Set<Character> visited = new HashSet<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); count.put(ch, count.get(ch) - 1); if (visited.contains(ch)) { continue; } while (!stack.isEmpty() && stack.peekFirst() > ch && count.get(stack.peekFirst()) > 0) { visited.remove(stack.peekFirst()); stack.pollFirst(); } stack.offerFirst(ch); visited.add(ch); } StringBuffer buff = new StringBuffer(); while (!stack.isEmpty()) { buff.append(stack.pollLast()); } return buff.toString(); }
public Future<SessionMessage> requestMessage(InputOperation operation, ExecutionThread ethread) { SessionMessageFuture future = new SessionMessageFuture(); ethread.cancelIfKilled(future); CorrelationSet cset = interpreter().getCorrelationSetForOperation(operation.id()); synchronized (messageQueues) { Deque<SessionMessage> queue; if (cset == null) { queue = uncorrelatedMessageQueue; } else { queue = messageQueues.get(cset); } SessionMessage message = queue.peekFirst(); if (message == null || message.message().operationName().equals(operation.id()) == false) { addMessageWaiter(operation, future); } else { future.setResult(message); queue.removeFirst(); // Check if we unlocked other receives boolean keepRun = true; SessionMessageFuture currFuture; while (keepRun && !queue.isEmpty()) { message = queue.peekFirst(); currFuture = getMessageWaiter(message.message().operationName()); if (currFuture != null) { // We found a waiter for the unlocked message currFuture.setResult(message); queue.removeFirst(); } else { keepRun = false; } } } } return future; }
public boolean solve(int p1, int q1, int p2, int q2) { // given a start and end, is there a way to connect the two points in this maze? // stack of points visited so far in this thread. // each time you pop off the stack (backtrack), use the hashmap like so: // avoid is a cache of known bad cells. If you pop the cell b from the stack, then put b in the // avoid cache // before each move, check the cache to make sure you do not make a move you've already // disproved. Deque<Point> stack = new ArrayDeque<Point>(); HashSet<Point> avoid = new HashSet<Point>(); // avoid returns points you should NOT try. You've already gone there and exhausted all possible // moves. // stack.push(new Point(p1,q1)); stack = solver(new Point(p1, q1), new Point(p2, q2), stack, avoid); if (stack.peekFirst() != null) { return true; } return false; }
private HourlyAggregateData getBin(long timestamp) { shiftBufferIfLastBinIsStale(); long earliest = deque.peekFirst().timestamp.getTime(); long latest = deque.peekLast().timestamp.getTime() + TimeUnit.HOURS.toMillis(1); /* * If the (live) data is outside the current 24-hour window, we just * throw it away. This is rather unlikely to occur. */ if (timestamp < earliest || timestamp >= latest) { return null; } Iterator<HourlyAggregateData> i = deque.descendingIterator(); /* * There should always be 24 bins. If there aren't, the * iterator error would be a bug, so we let it propagate here. * * For the vast majority of time, live incoming values should be added * to the last bin (one possible exception would be if the timestamp of * the arriving data precedes the last hourly timestamp because we * have just shifted the buffer forward). * * On initialization, we need to search for the correct bin as * the view might have gaps. */ HourlyAggregateData next = i.next(); do { if (timestamp >= next.timestamp.getTime()) { break; } next = i.next(); } while (i.hasNext()); return next; }
public int[] larger(int input[]) { Deque<Integer> stack = new LinkedList<Integer>(); int result[] = new int[input.length]; for (int i = 0; i < result.length; i++) { result[i] = -1; } stack.offerFirst(0); for (int i = 1; i < input.length; i++) { while (stack.size() > 0) { int t = stack.peekFirst(); if (input[t] < input[i]) { result[t] = i; stack.pollFirst(); } else { break; } } stack.offerFirst(i); } return result; }
public String peekLastOutput() { return outputStack.peekFirst(); }
@Override public synchronized Object processRemoveEventAttribute(Object obj) { minDeque.removeFirstOccurrence(obj); minValue = minDeque.peekFirst(); return minValue; }
/** @since 1.5 */ public static MavenExecutionContext getThreadContext(boolean innermost) { final Deque<MavenExecutionContext> stack = threadLocal.get(); return stack != null ? (innermost ? stack.peekFirst() : stack.peekLast()) : null; }
public void eval2( LeftInputAdapterNode liaNode, PathMemory rmem, NetworkNode node, Memory nodeMem, SegmentMemory[] smems, int smemIndex, LeftTupleSets trgTuples, InternalWorkingMemory wm, LinkedList<StackEntry> stack, Set<String> visitedRules, boolean processRian, RuleExecutor executor) { LeftTupleSets srcTuples; SegmentMemory smem = smems[smemIndex]; while (true) { srcTuples = trgTuples; // previous target, is now the source if (log.isTraceEnabled()) { int offset = getOffset(node); log.trace( "{} {} {} {}", indent(offset), ++cycle, node.toString(), srcTuples.toStringSizes()); } if (NodeTypeEnums.isTerminalNode(node)) { TerminalNode rtn = (TerminalNode) node; if (node.getType() == NodeTypeEnums.QueryTerminalNode) { pQtNode.doNode((QueryTerminalNode) rtn, wm, srcTuples, stack); } else { pRtNode.doNode(rtn, wm, srcTuples, executor); } return; } else if (NodeTypeEnums.RightInputAdaterNode == node.getType()) { doRiaNode2(wm, srcTuples, (RightInputAdapterNode) node, stack); return; } LeftTupleSets stagedLeftTuples; if (node == smem.getTipNode() && smem.getFirst() != null) { // we are about to process the segment tip, allow it to merge insert/update/delete clashes // Can happen if the next segments have not yet been initialized stagedLeftTuples = smem.getFirst().getStagedLeftTuples(); } else { stagedLeftTuples = null; } LeftTupleSinkNode sink = ((LeftTupleSource) node).getSinkPropagator().getFirstLeftTupleSink(); trgTuples = new LeftTupleSets(); if (NodeTypeEnums.isBetaNode(node)) { BetaNode betaNode = (BetaNode) node; BetaMemory bm = null; AccumulateMemory am = null; if (NodeTypeEnums.AccumulateNode == node.getType()) { am = (AccumulateMemory) nodeMem; bm = am.getBetaMemory(); } else { bm = (BetaMemory) nodeMem; } if (processRian && betaNode.isRightInputIsRiaNode()) { // if the subnetwork is nested in this segment, it will create srcTuples containing // peer LeftTuples, suitable for the node in the main path. doRiaNode( wm, liaNode, rmem, srcTuples, betaNode, sink, smems, smemIndex, nodeMem, bm, stack, visitedRules, executor); return; // return here is doRiaNode queues the evaluation on the stack, which is necessary // to handled nested query nodes } if (!bm.getDequeu().isEmpty()) { // If there are no staged RightTuples, then process the Dequeue, popping entries, until // another insert/expiration clash RightTupleSets rightTuples = bm.getStagedRightTuples(); if (rightTuples.isEmpty()) { // nothing staged, so now process the Dequeu Deque<RightTuple> que = bm.getDequeu(); while (!que.isEmpty()) { RightTuple rightTuple = que.peekFirst(); if (rightTuple.getPropagationContext().getType() == PropagationContext.EXPIRATION && // Cannot pop an expired fact, if the insert/update has not yet been evaluated. rightTuple.getStagedType() != LeftTuple.NONE) { break; } switch (rightTuple.getPropagationContext().getType()) { case PropagationContext.INSERTION: case PropagationContext.RULE_ADDITION: rightTuples.addInsert(rightTuple); break; case PropagationContext.MODIFICATION: rightTuples.addUpdate(rightTuple); break; case PropagationContext.DELETION: case PropagationContext.EXPIRATION: case PropagationContext.RULE_REMOVAL: rightTuples.addDelete(rightTuple); break; } que.removeFirst(); } } if (!bm.getDequeu().isEmpty()) { // The DeQue is not empty, add StackEntry for reprocessing. StackEntry stackEntry = new StackEntry( liaNode, node, sink, rmem, nodeMem, smems, smemIndex, trgTuples, visitedRules, false); stack.add(stackEntry); } } switch (node.getType()) { case NodeTypeEnums.JoinNode: { pJoinNode.doNode( (JoinNode) node, sink, bm, wm, srcTuples, trgTuples, stagedLeftTuples); break; } case NodeTypeEnums.NotNode: { pNotNode.doNode((NotNode) node, sink, bm, wm, srcTuples, trgTuples, stagedLeftTuples); break; } case NodeTypeEnums.ExistsNode: { pExistsNode.doNode( (ExistsNode) node, sink, bm, wm, srcTuples, trgTuples, stagedLeftTuples); break; } case NodeTypeEnums.AccumulateNode: { pAccNode.doNode( (AccumulateNode) node, sink, am, wm, srcTuples, trgTuples, stagedLeftTuples); break; } } } else { switch (node.getType()) { case NodeTypeEnums.EvalConditionNode: { pEvalNode.doNode( (EvalConditionNode) node, (EvalMemory) nodeMem, sink, wm, srcTuples, trgTuples, stagedLeftTuples); break; } case NodeTypeEnums.FromNode: { pFromNode.doNode( (FromNode) node, (FromMemory) nodeMem, sink, wm, srcTuples, trgTuples, stagedLeftTuples); break; } case NodeTypeEnums.QueryElementNode: { QueryElementNodeMemory qmem = (QueryElementNodeMemory) nodeMem; if (srcTuples.isEmpty() && qmem.getResultLeftTuples().isEmpty()) { // no point in evaluating query element, and setting up stack, if there is nothing // to process break; } QueryElementNode qnode = (QueryElementNode) node; if (visitedRules == Collections.<String>emptySet()) { visitedRules = new HashSet<String>(); } visitedRules.add(qnode.getQueryElement().getQueryName()); // result tuples can happen when reactivity occurs inside of the query, prior to // evaluation // we will need special behaviour to add the results again, when this query result // resumes trgTuples.addAll(qmem.getResultLeftTuples()); if (!srcTuples.isEmpty()) { // only process the Query Node if there are src tuples StackEntry stackEntry = new StackEntry( liaNode, node, sink, rmem, nodeMem, smems, smemIndex, trgTuples, visitedRules, true); stack.add(stackEntry); pQueryNode.doNode( qnode, (QueryElementNodeMemory) nodeMem, stackEntry, sink, wm, srcTuples); SegmentMemory qsmem = ((QueryElementNodeMemory) nodeMem).getQuerySegmentMemory(); List<PathMemory> qrmems = qsmem.getPathMemories(); // Build the evaluation information for each 'or' branch // Exception fo the last, place each entry on the stack, the last one evaluate now. for (int i = qrmems.size() - 1; i >= 0; i--) { PathMemory qrmem = qrmems.get(i); rmem = qrmem; smems = qrmem.getSegmentMemories(); smemIndex = 0; smem = smems[smemIndex]; // 0 liaNode = (LeftInputAdapterNode) smem.getRootNode(); if (liaNode == smem.getTipNode()) { // segment only has liaNode in it // nothing is staged in the liaNode, so skip to next segment smem = smems[++smemIndex]; // 1 node = smem.getRootNode(); nodeMem = smem.getNodeMemories().getFirst(); } else { // lia is in shared segment, so point to next node node = liaNode.getSinkPropagator().getFirstLeftTupleSink(); nodeMem = smem.getNodeMemories().getFirst().getNext(); // skip the liaNode memory } trgTuples = smem.getStagedLeftTuples(); if (i != 0 && !trgTuples.isEmpty()) { // All entries except the last should be placed on the stack for evaluation // later. stackEntry = new StackEntry( liaNode, node, null, rmem, nodeMem, smems, smemIndex, trgTuples, visitedRules, false); if (log.isTraceEnabled()) { int offset = getOffset(stackEntry.getNode()); log.trace( "{} ORQueue branch={} {} {}", indent(offset), i, stackEntry.getNode().toString(), trgTuples.toStringSizes()); } stack.add(stackEntry); } } processRian = true; // make sure it's reset, so ria nodes are processed continue; } break; } case NodeTypeEnums.ConditionalBranchNode: { pBranchNode.doNode( (ConditionalBranchNode) node, (ConditionalBranchMemory) nodeMem, sink, wm, srcTuples, trgTuples, stagedLeftTuples, executor); break; } } } if (node != smem.getTipNode()) { // get next node and node memory in the segment node = sink; nodeMem = nodeMem.getNext(); } else { // Reached end of segment, start on new segment. SegmentPropagator.propagate(smem, trgTuples, wm); smem = smems[++smemIndex]; trgTuples = smem.getStagedLeftTuples(); if (log.isTraceEnabled()) { log.trace("Segment {}", smemIndex); } node = (LeftTupleSink) smem.getRootNode(); nodeMem = smem.getNodeMemories().getFirst(); } processRian = true; // make sure it's reset, so ria nodes are processed } }
public CommentsCollection parse(final InputStream in, final String charsetName) throws IOException, UnsupportedEncodingException { boolean lastWasASlashR = false; BufferedReader br = new BufferedReader(new InputStreamReader(in, charsetName)); CommentsCollection comments = new CommentsCollection(); int r; Deque prevTwoChars = new LinkedList<Character>(Arrays.asList('z', 'z')); State state = State.CODE; LineComment currentLineComment = null; BlockComment currentBlockComment = null; StringBuffer currentContent = null; int currLine = 1; int currCol = 1; while ((r = br.read()) != -1) { char c = (char) r; if (c == '\r') { lastWasASlashR = true; } else if (c == '\n' && lastWasASlashR) { lastWasASlashR = false; continue; } else { lastWasASlashR = false; } switch (state) { case CODE: if (prevTwoChars.peekLast().equals('/') && c == '/') { currentLineComment = new LineComment(); currentLineComment.setBeginLine(currLine); currentLineComment.setBeginColumn(currCol - 1); state = State.IN_LINE_COMMENT; currentContent = new StringBuffer(); } else if (prevTwoChars.peekLast().equals('/') && c == '*') { currentBlockComment = new BlockComment(); currentBlockComment.setBeginLine(currLine); currentBlockComment.setBeginColumn(currCol - 1); state = State.IN_BLOCK_COMMENT; currentContent = new StringBuffer(); } else if (c == '"') { state = State.IN_STRING; } else { // nothing to do } break; case IN_LINE_COMMENT: if (c == '\n' || c == '\r') { currentLineComment.setContent(currentContent.toString()); currentLineComment.setEndLine(currLine); currentLineComment.setEndColumn(currCol); comments.addComment(currentLineComment); state = State.CODE; } else { currentContent.append(c); } break; case IN_BLOCK_COMMENT: if (prevTwoChars.peekLast().equals('*') && c == '/' && !prevTwoChars.peekFirst().equals('/')) { // delete last character String content = currentContent.deleteCharAt(currentContent.toString().length() - 1).toString(); if (content.startsWith("*")) { JavadocComment javadocComment = new JavadocComment(); javadocComment.setContent(content.substring(1)); javadocComment.setBeginLine(currentBlockComment.getBeginLine()); javadocComment.setBeginColumn(currentBlockComment.getBeginColumn()); javadocComment.setEndLine(currLine); javadocComment.setEndColumn(currCol + 1); comments.addComment(javadocComment); } else { currentBlockComment.setContent(content); currentBlockComment.setEndLine(currLine); currentBlockComment.setEndColumn(currCol + 1); comments.addComment(currentBlockComment); } state = State.CODE; } else { currentContent.append(c == '\r' ? '\n' : c); } break; case IN_STRING: if (!prevTwoChars.peekLast().equals('\\') && c == '"') { state = State.CODE; } break; default: throw new RuntimeException("Unexpected"); } switch (c) { case '\n': case '\r': currLine += 1; currCol = 1; break; case '\t': currCol += COLUMNS_PER_TAB; break; default: currCol += 1; } prevTwoChars.remove(); prevTwoChars.add(c); } if (state == State.IN_LINE_COMMENT) { currentLineComment.setContent(currentContent.toString()); currentLineComment.setEndLine(currLine); currentLineComment.setEndColumn(currCol); comments.addComment(currentLineComment); } return comments; }
public Carta showCarta() { if (this.isEmpty()) throw new MazzoVuotoException("Il Mazzo è vuoto"); return carte.peekFirst(); }
private Deque<Point> solver(Point start, Point end, Deque<Point> stack, HashSet<Point> avoid) { // iterative solver // base case: if (start.equals(end)) { stack.push(end); return stack; } // return the solution if we've solved the problem. // iterative case Point prev = stack.peekFirst(); if (prev == null) { // System.out.println("no previous point."); prev = start; } // deals with finding a previous point, especially if there is none (because this is the first // instance of the iteration char[] toCheck = nesw(start.x, start.y); Point[] possibleMoves = new Point[4]; int numMoves = 0; // the way the solver works is to create a list of possible moves, then move to the first // possible move. // "possible" is found by applying several constraints to the base "north east south west" // directions // first filter uses "nesw" to filter out edges and corners. (if you're in the lower right // corner, you can't move more right or more down) /*System.out.println("\n"); System.out.println("prev = " + prev); System.out.println("we are at : " + start); System.out.println("stack so far:" + stack); System.out.println("avoid so far:" + avoid); */ // ^ Interesting debugging output Point n = new Point(start.x, start.y - 1); // constraints: if ((toCheck[0] == '1') && // is a legal position on the board, and is n, e, s, or w from this cell (isWall(start.x, start.y, n.x, n.y) == false) && // there are no walls between this cell and that cell !(prev.equals(n)) && // it's not a cell we've just been in !(avoid.contains( n))) // it's not on our blacklist of moves we've tried that haven't worked out. { // if we can totally go north no problem // System.out.println(avoid.contains(n)); possibleMoves[numMoves] = n; numMoves++; } Point e = new Point(start.x + 1, start.y); if ((toCheck[1] == '1') && (isWall(start.x, start.y, e.x, e.y) == false) && !(prev.equals(e)) && !(avoid.contains(e))) { // if we can totally go east no problem possibleMoves[numMoves] = e; numMoves++; } Point s = new Point(start.x, start.y + 1); if ((toCheck[2] == '1') && (isWall(start.x, start.y, s.x, s.y) == false) && !(prev.equals(s)) && !(avoid.contains(s))) { // if we can totally south possibleMoves[numMoves] = s; numMoves++; } Point w = new Point(start.x - 1, start.y); if ((toCheck[0] == '1') && (isWall(start.x, start.y, w.x, w.y) == false) && !(prev.equals(w)) && !(avoid.contains(w))) { // if we can totally go west no problem possibleMoves[numMoves] = w; numMoves++; } // now either numMoves > 0, in which case we can move forward, or it equals 0, which means we've // hit a dead end. if (numMoves == 0) { // if we have hit a dead end try { Point a = stack.removeFirst(); avoid.add(start); // System.out.println("hit a dead end. adding " + start + " to avoid queue"); return solver(a, end, stack, avoid); } catch (Exception NoSuchElementException) { // if the stack is empty, that means there's no solution System.out.println("Empty stack! No solution!"); return stack; } } else { // numMoves > 0. We can move forward Point m = possibleMoves[0]; // System.out.println("Moving to point: " + m.x + "," + m.y); stack.addFirst(start); // m.equals(obj) return solver(m, end, stack, avoid); } }
private void checkInMethod() { if (!METHOD_SCOPES.contains(scopes.peekFirst())) { throw new IllegalArgumentException(); } }
public JavaWriter beginConstructor( Set<Modifier> modifiers, List<String> parameters, List<String> throwsTypes) throws IOException { beginMethod(null, types.peekFirst(), modifiers, parameters, throwsTypes); return this; }
@Override public synchronized Object processRemove(Object data) { minDeque.removeFirstOccurrence(data); minValue = minDeque.peekFirst(); return minValue; }