Ejemplo n.º 1
0
 @Test
 public void Deque_addLast_AddsTwo() {
   deque.addLast("firstString");
   deque.addLast("secondString");
   assertFalse(deque.isEmpty());
   assertEquals(deque.size(), 2);
 }
  @Override
  public Path search(Integer source, Integer target) {
    check(source, target);

    Deque<Integer> queue = new ArrayDeque<>(graph.size());
    Map<Integer, Integer> parents = new HashMap<>(graph.size());

    queue.addLast(source);
    parents.put(source, null);

    while (!queue.isEmpty()) {
      Integer current = queue.removeFirst();

      if (current.equals(target)) {
        return tracebackPath(target, parents, graph);
      }

      for (Integer child : graph.getChildrenOf(current)) {
        if (!parents.containsKey(child)) {
          parents.put(child, current);
          queue.addLast(child);
        }
      }
    }

    return Path.emptyPath();
  }
Ejemplo n.º 3
0
  /**
   * @param instanceFrame instance frame
   * @return iterable over instance members of the frame, including those nested in namespaces
   */
  public static Iterable<? extends INamedElement> instanceMembers(
      final IInstanceFrame instanceFrame) {
    final List<INamedElement> members = new ArrayList<>();

    // Iterate over the member functions of the frame, including those nested in namespaces.
    final Deque<INamedElement> queue = new LinkedList<>();
    queue.addLast(instanceFrame);
    while (!queue.isEmpty()) {
      final INamedElement cur = queue.getFirst();
      queue.removeFirst();

      final INamedElementContainer contCur = (INamedElementContainer) cur;
      for (final INamedElement member : contCur.members())
        if (Ast.membership(member)
            == (contCur == instanceFrame
                ? ScopeMembership.InstanceMember
                : ScopeMembership.StaticMember)) {
          members.add(member);
          if (member instanceof INamedElementContainer) {
            // Tail-recursively treat this nested namespace.
            queue.addLast(member);
          }
        }
    }

    return members;
  }
 public int[] maxSlidingWindow(int[] nums, int k) {
   if (nums.length == 0 || k == 0) {
     return new int[] {};
   }
   int[] result = new int[nums.length - k + 1];
   PriorityQueue<Integer> priorityQueue =
       new PriorityQueue<Integer>(
           k,
           new Comparator<Integer>() {
             @Override
             public int compare(Integer o1, Integer o2) {
               if (o1 < o2) {
                 return 1;
               } else if (o1 > o2) {
                 return -1;
               } else {
                 return 0;
               }
             }
           });
   Deque<Integer> deque = new LinkedList<Integer>();
   for (int i = 0; i < k; i++) {
     deque.addLast(nums[i]);
     priorityQueue.add(nums[i]);
   }
   for (int i = k; i < nums.length; i++) {
     result[i - k] = priorityQueue.peek();
     int first = deque.removeFirst();
     priorityQueue.remove(first);
     deque.addLast(nums[i]);
     priorityQueue.add(nums[i]);
   }
   result[result.length - 1] = priorityQueue.peek();
   return result;
 }
Ejemplo n.º 5
0
 private void buildForStatement(ForStatementTree tree) {
   Block falseBranch = currentBlock;
   // process step
   currentBlock = createBlock();
   Block updateBlock = currentBlock;
   for (StatementTree updateTree : Lists.reverse(tree.update())) {
     build(updateTree);
   }
   continueTargets.addLast(currentBlock);
   // process body
   currentBlock = createBlock(currentBlock);
   breakTargets.addLast(falseBranch);
   build(tree.statement());
   breakTargets.removeLast();
   continueTargets.removeLast();
   Block body = currentBlock;
   // process condition
   ExpressionTree condition = tree.condition();
   if (condition != null) {
     currentBlock = createBranch(tree, body, falseBranch);
     buildCondition(condition, body, falseBranch);
   } else {
     currentBlock = createUnconditionalJump(tree, body);
   }
   updateBlock.successors.add(currentBlock);
   // process init
   currentBlock = createBlock(currentBlock);
   for (StatementTree init : Lists.reverse(tree.initializer())) {
     build(init);
   }
 }
 // Method 2: BFS Solution
 public boolean validTreeII(int n, int[][] edges) {
   int[] visited = new int[n];
   List<List<Integer>> adjList = new ArrayList<>();
   for (int i = 0; i < n; ++i) {
     adjList.add(new ArrayList<Integer>());
   }
   for (int[] edge : edges) {
     adjList.get(edge[0]).add(edge[1]);
     adjList.get(edge[1]).add(edge[0]);
   }
   Deque<Integer> q = new LinkedList<Integer>();
   q.addLast(0);
   visited[0] = 1; // vertex 0 is in the queue, being visited
   while (!q.isEmpty()) {
     Integer cur = q.removeFirst();
     for (Integer succ : adjList.get(cur)) {
       if (visited[succ] == 1) {
         return false;
       } // loop detected
       if (visited[succ] == 0) {
         q.addLast(succ);
         visited[succ] = 1;
       }
     }
     visited[cur] = 2; // visit completed
   }
   for (int v : visited) {
     if (v == 0) {
       return false;
     }
   } // # of connected components is not 1
   return true;
 }
Ejemplo n.º 7
0
 protected void visitBlobsField(T state, Field field) throws PropertyException {
   Type type = field.getType();
   if (type.isSimpleType()) {
     // scalar
   } else if (type.isComplexType()) {
     // complex property
     String name = field.getName().getPrefixedName();
     T childState = getChild(state, name, type);
     if (childState != null) {
       path.addLast(name);
       visitBlobsComplex(childState, (ComplexType) type);
       path.removeLast();
     }
   } else {
     // array or list
     Type fieldType = ((ListType) type).getFieldType();
     if (fieldType.isSimpleType()) {
       // array
     } else {
       // complex list
       String name = field.getName().getPrefixedName();
       path.addLast(name);
       int i = 0;
       for (T childState : getChildAsList(state, name)) {
         path.addLast(String.valueOf(i++));
         visitBlobsComplex(childState, (ComplexType) fieldType);
         path.removeLast();
       }
       path.removeLast();
     }
   }
 }
Ejemplo n.º 8
0
  public int BFS(int end) {
    Deque<Vertice> q = new ArrayDeque();
    Set closed = new HashSet();

    Vertice initialVertice = cache.get(1);

    q.addLast(initialVertice);
    closed.add(initialVertice);

    while (!q.isEmpty()) {

      Vertice tmp = q.pollFirst();

      if (inverseCache.get(tmp) == end) return inverseCache.get(tmp);

      for (int x = 0; x < tmp.neighbours.size(); x++) {
        Vertice o = tmp.neighbours.get(x);
        if (!closed.contains(o)) {
          closed.add(o);
          q.addLast(o);
        }
      }
    }

    return 0;
  }
Ejemplo n.º 9
0
 /**
  * Queue it up in the {@link ReplayEntry#m_blockedMessages} queue before the {@link
  * CompleteTransactionMessage} for this entry's transaction is received. Otherwise add it
  * straight to the {@link ReplayEntry#m_sequencedMessages} queue.
  *
  * @param m an SP invocation message
  */
 void addBlockedMessage(VoltMessage m) {
   if (m_lastFragment == null) {
     m_blockedMessages.addLast(m);
   } else {
     m_sequencedMessages.addLast(m);
   }
 }
Ejemplo n.º 10
0
 private void buildSwitchStatement(SwitchStatementTree tree) {
   // FIXME useless node created for default cases.
   SwitchStatementTree switchStatementTree = tree;
   Block switchSuccessor = currentBlock;
   // process condition
   currentBlock = createBlock();
   currentBlock.terminator = switchStatementTree;
   switches.addLast(currentBlock);
   build(switchStatementTree.expression());
   // process body
   currentBlock = createBlock(switchSuccessor);
   breakTargets.addLast(switchSuccessor);
   if (!switchStatementTree.cases().isEmpty()) {
     CaseGroupTree firstCase = switchStatementTree.cases().get(0);
     for (CaseGroupTree caseGroupTree : Lists.reverse(switchStatementTree.cases())) {
       build(caseGroupTree.body());
       switches.getLast().successors.add(currentBlock);
       if (!caseGroupTree.equals(firstCase)) {
         // No block predecessing the first case group.
         currentBlock = createBlock(currentBlock);
       }
     }
   }
   breakTargets.removeLast();
   // process condition
   currentBlock = switches.removeLast();
 }
Ejemplo n.º 11
0
 @Override
 public void startElement(String uri, String localName, String qName, Attributes attributes) {
   elementStack.addLast(localName);
   elementContentStack.addLast(new StringBuilder());
   if (path(rootPath)) {
     currentText = new Text();
   }
 }
 public static boolean bfsIterative(TreeNode root, int val) {
   Deque<TreeNode> s = new LinkedList<>();
   s.push(root);
   while (!s.isEmpty()) {
     TreeNode curr = s.removeFirst();
     if (curr.left != null) s.addLast(curr.left);
     if (curr.right != null) s.addLast(curr.right);
     if (curr.value == val) return true;
   }
   return false;
 }
Ejemplo n.º 13
0
  /**
   * Overloaded method to add a new operand to the Node Equation
   *
   * @param operand
   * @throws InvalidEquationException
   * @throws InvalidOperandException
   */
  public void add(String inputOperand) throws InvalidEquationException, InvalidOperandException {
    // Check if this operand can be added at this state of equation
    Object equationEndElement = equation.peekLast();

    if (equationEndElement instanceof Operand) {
      logs.trace("Attempting to insert an operand after another operand");
      throw new InvalidEquationException("Operand can not be inserted after " + "another operator");
    }

    equation.addLast(new Operand(inputOperand));
    equation.addLast("");
  }
 private static void add(float x, float y) {
   Deque<Vector2f> tmp = new ArrayDeque<Vector2f>();
   while (!graphRes.isEmpty() && graphRes.getFirst().x < x) {
     tmp.addLast(graphRes.pollFirst());
   }
   tmp.addLast(new Vector2f(x, y));
   while (!graphRes.isEmpty()) {
     tmp.addLast(graphRes.pollFirst());
   }
   graphRes = tmp;
   while (y / graph1dY > height) {
     frame.jSliderdY1.setValue(frame.jSliderdY1.getValue() + 1);
   }
 }
Ejemplo n.º 15
0
 @Test
 public void Deque_addLast_removeLast_AddsRemovesTwo() {
   deque.addLast("firstString");
   deque.addLast("secondString");
   assertFalse(deque.isEmpty());
   assertEquals(deque.size(), 2);
   String returnedString = deque.removeLast();
   assertEquals(returnedString, "secondString");
   assertFalse(deque.isEmpty());
   assertEquals(deque.size(), 1);
   returnedString = deque.removeLast();
   assertEquals(returnedString, "firstString");
   assertTrue(deque.isEmpty());
   assertEquals(deque.size(), 0);
 }
Ejemplo n.º 16
0
 private void cycleKeyList(Object key) {
   keyList.addLast(key);
   if (keyList.size() > size) {
     Object oldestKey = keyList.removeFirst();
     delegate.removeObject(oldestKey);
   }
 }
Ejemplo n.º 17
0
 public ExchangeMetrics addContext(MetricsContext ctx) {
   contexts.addLast(ctx);
   if (started) {
     ctx.start(exchange);
   }
   return this;
 }
Ejemplo n.º 18
0
 private void updateEstimates(int secondsRemaining) {
   //        Archivo.logger.debug("Adding {} to estimates", secondsRemaining);
   recentEndTimeEstimates.addLast(secondsRemaining);
   if (recentEndTimeEstimates.size() > MAX_END_TIME_ESTIMATES) {
     recentEndTimeEstimates.removeFirst();
   }
 }
Ejemplo n.º 19
0
 @Override
 public WebSocketSession getSession(Deque<SessionContext> sessionContexts) {
   // Remove the first item, and add at the end
   SessionContext s = sessionContexts.removeFirst();
   sessionContexts.addLast(s);
   return s.getSession();
 }
Ejemplo n.º 20
0
 private static void deepVisitInternal(
     Object o,
     Predicate<Field> fieldPredicate,
     List<Object> visited,
     Deque<Object> refChain,
     Visitor visitor)
     throws IllegalArgumentException, IllegalAccessException {
   Class<?> clazz = (o != null) ? o.getClass() : null;
   refChain.addLast(o);
   Iterable<Object> filteredRefChain =
       Iterables.filter(refChain, Predicates.not(Predicates.instanceOf(Dumpers.Entry.class)));
   try {
     if (o == null) {
       // no-op
     } else if (isClassUntraversable(clazz)) {
       visitor.visit(o, filteredRefChain);
     } else if (containsSame(visited, o)) {
       // no-op
     } else {
       visited.add(o);
       boolean subTreeComplete = visitor.visit(o, filteredRefChain);
       if (!subTreeComplete) {
         Map<String, Object> members = findMembers(o, fieldPredicate);
         for (Map.Entry<String, Object> entry : members.entrySet()) {
           deepVisitInternal(entry.getValue(), fieldPredicate, visited, refChain, visitor);
         }
       }
     }
   } finally {
     refChain.removeLast();
   }
 }
 public TreeNode sinkZerosInBT2(TreeNode root) {
   if (deque == null) deque = new LinkedList<TreeNode>();
   if (root == null) return null;
   if (root.val == 0) deque.addLast(root);
   else {
     if (!deque.isEmpty()) {
       swap(root, deque.pollFirst());
       deque.addLast(root); // need to push this new zero-node to end of deque
     }
   }
   sinkZerosInBT2(root.left);
   sinkZerosInBT2(root.right);
   if (deque.peekLast() == root) // there's no non-zero node for us to swap, poll the zero node
   deque.pollLast();
   return root;
 }
Ejemplo n.º 22
0
 /** Undo the last entry that was added to this history. */
 public void undo() {
   if (canUndo()) {
     final HistoryAction entry = undoList.removeLast();
     entry.undo();
     redoList.addLast(entry);
   }
 }
Ejemplo n.º 23
0
 /** Do the last entry that was undone again. */
 public void redo() {
   if (canRedo()) {
     final HistoryAction entry = redoList.removeLast();
     entry.redo();
     undoList.addLast(entry);
   }
 }
Ejemplo n.º 24
0
 private void buildDoWhileStatement(DoWhileStatementTree tree) {
   DoWhileStatementTree s = tree;
   Block falseBranch = currentBlock;
   Block loopback = createBlock();
   // process condition
   currentBlock = createBranch(s, loopback, falseBranch);
   buildCondition(s.condition(), loopback, falseBranch);
   // process body
   currentBlock = createBlock(currentBlock);
   continueTargets.addLast(loopback);
   breakTargets.addLast(falseBranch);
   build(s.statement());
   breakTargets.removeLast();
   continueTargets.removeLast();
   loopback.successors.add(currentBlock);
   currentBlock = createBlock(currentBlock);
 }
 @Override
 public void exitDoubleOperand(@NotNull DoubleOperandContext ctx) {
   double value = Double.parseDouble(ctx.FLOAT().getText());
   if (ctx.DASH() != null) {
     value = -1 * value;
   }
   operandQueue.addLast(new DoubleOperand(value));
 }
 @Override
 public void exitLongOperand(@NotNull LongOperandContext ctx) {
   long value = Long.parseLong(ctx.INT().getText());
   if (ctx.DASH() != null) {
     value = -1 * value;
   }
   operandQueue.addLast(new LongOperand(value));
 }
Ejemplo n.º 27
0
  /**
   * Creates connection objects and pushes it into queue.
   *
   * @param factory Used to create JDBConnection implementations.
   * @param poolSize Number of JDBConnection implementations to create.
   * @param leaseTimeInMillis How long the client can use the connection before it expires.
   */
  public ConnectionPool(JdbConnectionFactory factory, int poolSize, long leaseTimeInMillis) {
    for (int i = 0; i < poolSize; i++) {
      pooled.addLast(factory.create());
    }

    this.factory = factory;
    this.leaseTimeInMillis = leaseTimeInMillis;
  }
Ejemplo n.º 28
0
 /**
  * Add a entry to the history list. This causes that the redo list is cleared and in case the undo
  * list is getting too long the oldest entry is removed.
  *
  * @param entry the entry to add to this list
  */
 @SuppressWarnings("nls")
 public void addEntry(final HistoryAction entry) {
   undoList.addLast(entry);
   redoList.clear();
   while (undoList.size() > MAX_HISTORY_LENGHT) {
     undoList.removeFirst();
   }
 }
Ejemplo n.º 29
0
 /**
  * Return a JdbConnection object back to the pool.
  *
  * @param jdbConnection The object retrieved from the pool via borrow()
  * @throws ConnectionPoolException Throws if connection has already been returned or forced to
  *     expire
  */
 public synchronized void forfeit(JdbConnection jdbConnection) throws ConnectionPoolException {
   if (borrowed.containsKey(jdbConnection)) {
     borrowed.remove(jdbConnection);
     pooled.addLast(jdbConnection);
   } else {
     throw new ConnectionPoolException("Connection already returned or forced to expire");
   }
 }
Ejemplo n.º 30
0
 private void buildForEachStatement(ForEachStatement tree) {
   // TODO(npe) One solution is to create a forstatement node depending on type of expression
   // (iterable or array) and build CFG from it.
   Block afterLoop = currentBlock;
   currentBlock = createBlock();
   Block loopback = currentBlock;
   continueTargets.addLast(loopback);
   breakTargets.addLast(afterLoop);
   build(tree.statement());
   breakTargets.removeLast();
   continueTargets.removeLast();
   currentBlock = createBranch(tree, currentBlock, afterLoop);
   loopback.successors.add(currentBlock);
   build(tree.variable());
   build(tree.expression());
   currentBlock = createBlock(currentBlock);
 }