@Override
  public void walkJAXBElements(Object o) {

    Node existingParentNode = parentNode;

    if (o instanceof org.docx4j.wml.Tr) {

      tr.push(document.createElementNS(Namespaces.NS_WORD12, "tr"));
      // parentNode is in this case the DocumentFragment, that get's passed
      // to the TableModel/TableModelWriter
      parentNode.appendChild(tr.peek());

    } else if (o instanceof org.docx4j.wml.Tc) {

      tc.push(document.createElementNS(Namespaces.NS_WORD12, "tc"));
      (tr.peek()).appendChild(tc.peek());
      // now the html p content will go temporarily go in w:tc,
      // which is what we need for our existing table model.

      parentNode = tc.peek();
    }

    super.walkJAXBElements(o);

    if (o instanceof org.docx4j.wml.Tr) {

      tr.pop();

    } else if (o instanceof org.docx4j.wml.Tc) {

      tc.pop();

      parentNode = existingParentNode; // restore
    }
  }
Пример #2
0
 public void push(int val) {
   Integer sPeek = S.peek();
   values.push(val);
   if (sPeek == null || val <= sPeek) {
     S.push(val);
   }
 }
Пример #3
0
  private static LinkedList<Coords> graham(LinkedList<Coords> list) {
    LinkedList<Coords> stack = new LinkedList<Coords>();
    Coords next;
    stack.push(list.get(0));
    stack.push(list.get(1));
    int i = 2;
    int n = list.size();
    double debug;
    while (i < n) {
      System.out.println("Stack: ");
      printCoords(stack);
      System.out.println("Now comparing: ");
      System.out.print("P0: ");
      printCoord(stack.get(1));
      System.out.print(" - ");
      System.out.print("P1: ");
      printCoord(stack.get(0));
      System.out.print(" - ");
      System.out.print("P2: ");
      printCoord(list.get(i));
      System.out.println();
      if ((debug = compVect(stack.get(1), stack.get(0), list.get(i))) >= 0.0) {
        System.out.println("P2 is left of P0->P1: putting P2 on stack...");
        stack.push(list.get(i));
        i++;
      } else {
        System.out.println("P2 is right of P0->P1: removing P1 from stack...");
        stack.pop();
      }
    }

    return stack;
  }
Пример #4
0
  /** Parse the command string and split it into computations of connected operators */
  public static ArrayList<String> parseExpr(String in) throws BcException {
    LinkedList<String> tempStack = new LinkedList<String>();
    ArrayList<String> result = new ArrayList<String>();
    char currentChar;
    StringBuilder currentToken;

    for (int i = 0; i < in.length(); i++) {
      currentChar = in.charAt(i);
      if (currentChar == ' ') {
        continue;
      } else if (isOperator(currentChar)) {
        // operator
        currentToken = new StringBuilder();
        currentToken.append(currentChar);
        while (i + 1 < in.length() && isOperator(in.charAt(i + 1))) {
          i++;
          currentToken.append(in.charAt(i));
        }
        // if is negate
        if (currentToken.toString().equals("-")
            && (result.size() == 0 || (!tempStack.isEmpty() && i > 0 && in.charAt(i - 1) == '('))) {
          currentToken = new StringBuilder("--");
        }
        while (tempStack.size() > 0
            && priority(currentToken.toString()) <= priority(tempStack.peek()))
          result.add(tempStack.pop());
        tempStack.push(currentToken.toString());
      } else if (currentChar == '(') {
        tempStack.push(currentChar + "");
      } else if (currentChar == ')') {
        while (!tempStack.peek().equals('(' + "")) {
          if (tempStack.isEmpty()) {
            throw new BcException("");
          }
          result.add(tempStack.pop());
        }
        tempStack.pop();
      } else if (isDigitOrDot(currentChar)) {
        // operand
        currentToken = new StringBuilder();
        currentToken.append(currentChar);
        while (i + 1 < in.length() && isDigitOrDot(in.charAt(i + 1))) {
          i++;
          currentToken.append(in.charAt(i));
        }
        result.add(currentToken.toString());
      } else {
        throw new BcException("illegal character: " + currentChar);
      }
    }

    while (!tempStack.isEmpty()) {
      if (tempStack.peek().equals("(")) {
        throw new BcException("Unmatched bracket.");
      }
      result.add(tempStack.pop());
    }

    return result;
  }
 @Override
 protected Queue<Request> initGatt(final BluetoothGatt gatt) {
   final LinkedList<Request> requests = new LinkedList<>();
   requests.push(Request.newEnableNotificationsRequest(mGlucoseMeasurementCharacteristic));
   if (mGlucoseMeasurementContextCharacteristic != null)
     requests.push(
         Request.newEnableNotificationsRequest(mGlucoseMeasurementContextCharacteristic));
   requests.push(
       Request.newEnableIndicationsRequest(mRecordAccessControlPointCharacteristic));
   return requests;
 }
Пример #6
0
 static {
   queue.push("9.txt");
   queue.push("8.txt");
   queue.push("7.txt");
   queue.push("6.txt");
   queue.push("5.txt");
   queue.push("4.txt");
   queue.push("3.txt");
   queue.push("2.txt");
   queue.push("1.txt");
 }
Пример #7
0
 public void push(int val) {
   // 第一个元素入栈设置初始最小值
   if (values.peek() == null) {
     values.push(new Integer[] {val, val});
   }
   int min = values.peek()[1];
   if (min < val) {
     values.push(new Integer[] {val, min});
   } else {
     values.push(new Integer[] {val, val});
   }
 }
  public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

    if (root == null) return result;

    LinkedList<TreeNodeWrapper> queue = new LinkedList<TreeNodeWrapper>();
    Stack<TreeNodeWrapper> stack = new Stack<TreeNodeWrapper>();
    int level = -1;

    queue.push(new TreeNodeWrapper(root, 0));

    while (!queue.isEmpty()) {
      TreeNodeWrapper wrapper = queue.pop();
      stack.push(wrapper);
      if (wrapper.node.left != null) {
        queue.push(new TreeNodeWrapper(wrapper.node.left, wrapper.level + 1));
      }
      if (wrapper.node.right != null) {
        queue.push(new TreeNodeWrapper(wrapper.node.right, wrapper.level + 1));
      }
    }

    ArrayList<Integer> list = null;
    Map<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();

    // System.out.println("stack size: " + stack.size());

    while (!stack.isEmpty()) {
      TreeNodeWrapper wrapper = stack.pop();
      // System.out.println("wrapper level: " + wrapper.level +
      // " node val: " + wrapper.node.val);

      level = Math.max(level, wrapper.level); // get the max level

      if (!map.containsKey(wrapper.level)) {
        list = new ArrayList<Integer>();
        map.put(wrapper.level, list);
      } else {
        list = map.get(wrapper.level);
      }

      list.add(wrapper.node.val);
    }

    while (level >= 0) {
      result.add(map.get(level));
      map.remove(level);
      level--;
    }

    return result;
  }
  public static void main(String[] args) {

    // collections
    // happy paths

    // pushes elements to the LinkedList
    LinkedList lnkLst = new LinkedList();
    lnkLst.push("Kayla");
    lnkLst.push("Brad");
    lnkLst.push("Henry");
    lnkLst.push("Liesel");
    System.out.println(lnkLst);

    // pops out the reverse order of the LinkedList
    System.out.println(lnkLst.pop());
    System.out.println(lnkLst.pop());

    // removes an element from the LinkedList
    lnkLst.remove(1);
    System.out.println(lnkLst);

    // pushes element into a LinkedList
    lnkLst.push(5);
    System.out.println(lnkLst);

    // puts an element last no matter what in a LinkedList
    lnkLst.addLast("Last?");
    System.out.println(lnkLst);

    // gets the element in the LinkedList at index 1
    System.out.println(lnkLst.get(1));

    // nasty paths

    // asking for an element that doesn't exist.
    try {
      lnkLst.get(3);
    } catch (Exception e) {
      e.printStackTrace();
    }

    // trying a negative index
    try {
      lnkLst.get(-1);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 private static void madness(String line) {
   LinkedList<String> phraseStack = new LinkedList<String>();
   StringBuffer currentBlock = new StringBuffer();
   StringBuffer phrase = new StringBuffer();
   for (int i = 0; i < line.length(); i++) {
     switch (line.charAt(i)) {
       case '{':
       case '[':
       case '(':
         phraseStack.push(currentBlock.toString());
         currentBlock = new StringBuffer();
         break;
       case '}':
       case ']':
       case ')':
         phrase.append(currentBlock);
         currentBlock = new StringBuffer();
         String previousBlock = phraseStack.pop();
         if (!previousBlock.isEmpty()) {
           previousBlock = previousBlock.trim();
           previousBlock = ' ' + previousBlock;
         }
         currentBlock.append(previousBlock);
         break;
       default:
         currentBlock.append(line.charAt(i));
         break;
     }
   }
   System.out.println(phrase.toString());
 }
Пример #11
0
 public static Path[] getInputPaths(String rootPath) {
   try {
     Configuration conf = HBaseConfiguration.create();
     Path root = new Path(rootPath);
     ArrayList<Path> paths = new ArrayList<Path>();
     FileSystem fs = root.getFileSystem(conf);
     LinkedList<Path> list = new LinkedList<Path>();
     list.push(root);
     if (!fs.exists(root)) {
       System.out.println("path not exists: " + root.toString());
       return new Path[0];
     }
     while (!list.isEmpty()) {
       Path path = list.pop();
       if (fs.isFile(path)) {
         if (path.getName().matches("^.*part-r-\\d{5}.*$")) {
           paths.add(path);
           System.out.println("something is wrong with path" + path.toString());
         }
       } else {
         FileStatus[] statuses = fs.listStatus(path);
         for (FileStatus status : statuses) {
           if (status.isDir()) {
             list.add(status.getPath());
           } else if (status.getPath().getName().matches("^.*part-r-\\d{5}.*$")) {
             paths.add(status.getPath());
           }
         }
       }
     }
     return paths.toArray(new Path[paths.size()]);
   } catch (IOException ignored) {
     return new Path[0];
   }
 }
Пример #12
0
 public static void main(String[] args) {
   LinkedList books = new LinkedList();
   // 将字符串元素加入队列的尾部
   books.offer("疯狂Java讲义");
   // 将一个字符串元素加入栈的顶部
   books.push("轻量级Java EE企业应用实战");
   // 将字符串元素添加到队列的头部(相当于栈的顶部)
   books.offerFirst("疯狂Android讲义");
   // 以List的方式(按索引访问的方式)来遍历集合元素
   for (int i = 0; i < books.size(); i++) {
     System.out.println("遍历中:" + books.get(i));
   }
   // 访问、并不删除栈顶的元素
   System.out.println(books.peekFirst());
   // 访问、并不删除队列的最后一个元素
   System.out.println(books.peekLast());
   // 将栈顶的元素弹出“栈”
   System.out.println(books.pop());
   // 下面输出将看到队列中第一个元素被删除
   System.out.println(books);
   // 访问、并删除队列的最后一个元素
   System.out.println(books.pollLast());
   // 下面输出:[轻量级Java EE企业应用实战]
   System.out.println(books);
 }
Пример #13
0
  public void bfs_traverse_double_queue(mapNode root) {
    LinkedList<mapNode> next = new LinkedList<>();
    LinkedList<mapNode> current = new LinkedList<>();
    HashSet<mapNode> visited = new HashSet<>();

    int level = 0;

    current.push(root);
    visited.add(root);
    while (!current.isEmpty()) {
      level++;
      while (!current.isEmpty()) {
        mapNode cur = current.poll();
        System.out.println(cur.getData());
        ArrayList<mapNode> chl = cur.getChildren();
        if (chl != null) {
          for (mapNode node : chl) {
            next.add(node);
          }
        }
      }
      LinkedList<mapNode> temp = new LinkedList<>();
      temp = current;
      current = next;
      next = temp;
    }
    System.out.println('\n' + "level: " + level);
  }
Пример #14
0
 private void recurseTargets(int target, LinkedList<Integer> path, int steps) {
   LinkedList<Integer> tempAdj = new LinkedList<Integer>();
   ListIterator<Integer> itr = this.getAdjList(target).listIterator();
   while (itr.hasNext()) {
     int next = itr.next();
     if (seen[next] == false) {
       tempAdj.add(next);
     } else {
       continue;
     }
   }
   ListIterator<Integer> itrAdj = tempAdj.listIterator();
   while (itrAdj.hasNext()) {
     int nextNode = itrAdj.next();
     seen[nextNode] = true;
     path.push(nextNode);
     if (cells.get(nextNode).isRoom() != true || cells.get(nextNode).isDoorway() == true) {
       if (path.size() == steps) {
         targets.add(cells.get(nextNode));
       } else if (cells.get(nextNode).isDoorway()) {
         targets.add(cells.get(nextNode));
       } else {
         recurseTargets(nextNode, path, steps);
       }
     }
     path.removeLast();
     seen[nextNode] = false;
   }
 }
Пример #15
0
 /**
  * Performs a query search, writes the results to a data channel, and stops processing if the
  * source sets queryPromise.queryCancelled to true.
  *
  * @param path An array of QueryElement that contains a parsed query path.
  * @param result A DataChannelOutput to which the result will be written. In practice, this will
  *     be the head of a QueryOpProcessor that represents the first operator in a query, which in
  *     turn sends its output to another QueryOpProcessor and the last will send its output to a
  *     DataChannelOutput sending bytes back to meshy, usually defined at the MQSource side of
  *     code.
  * @param queryPromise A wrapper for a boolean flag that gets set to true by MQSource in case the
  *     user cancels the query at the MQMaster side.
  * @throws QueryException
  * @see {@link Query#parseQueryPath(String)}
  */
 public void search(
     QueryElement[] path, DataChannelOutput result, ChannelProgressivePromise queryPromise)
     throws QueryException {
   init();
   Thread thread = Thread.currentThread();
   synchronized (active) {
     if (!active.add(thread)) {
       throw new QueryException("Active Thread " + thread + " reentering search");
     }
   }
   try {
     LinkedList<DataTreeNode> stack = new LinkedList<>();
     stack.push(tree);
     tableSearch(
         stack, new FieldValueList(new KVBundleFormat()), path, 0, result, 0, queryPromise);
   } catch (QueryException | CancellationException ex) {
     log.debug("", ex);
   } catch (RuntimeException ex) {
     log.warn("", ex);
     throw ex;
   } finally {
     synchronized (active) {
       if (!active.remove(thread)) {
         log.warn("Active Thread {} missing from set", thread);
       }
     }
   }
 }
Пример #16
0
 public static ListNode reverseKGroup(ListNode head, int k) {
   if (head == null || head.next == null || k < 2) {
     return head;
   }
   LinkedList<ListNode> l = new LinkedList<ListNode>();
   int count = 0;
   ListNode pre = new ListNode(0);
   ListNode temp = pre;
   while (head != null) {
     if (count++ < k) {
       ListNode t = new ListNode(head.val);
       l.push(t);
       head = head.next;
     }
     if (count >= k) {
       count = 0;
       while (!l.isEmpty()) {
         temp.next = l.pop();
         temp = temp.next;
       }
     }
   }
   while (!l.isEmpty()) {
     temp.next = l.pollLast();
     temp = temp.next;
   }
   return pre.next;
 }
  /**
   * Tries to create a Harbour on x, y position
   *
   * @param xStr x coord
   * @param yStr y coord
   */
  public void createHarbor(String xStr, String yStr) {
    Location loc = parseAndCheckLocation(xStr, yStr);
    if (loc != null) {
      Harbor a = new Harbor(loc);

      harbors.push(a);
      buildings.push(a);
      renderables.add(a);
      iVoyageTargets.add(a);

      // Check if this function was called right after deserialization
      recoverChangesListeners();

      listeners.forEach(IChangesListener::OnWorldChanged);
    }
  }
  /**
   * Tries to create MilitaryAirport on x, y position
   *
   * @param xStr x coord as string
   * @param yStr y coord as string
   * @param capStr capacity of that airport
   */
  public void createMilitaryAirport(String xStr, String yStr, String capStr) {
    Location loc = parseAndCheckLocation(xStr, yStr);
    if (loc != null) {
      MilitaryAirport a = new MilitaryAirport(loc, Integer.valueOf(capStr));

      airports.push(a);
      buildings.push(a);
      renderables.add(a);
      militaryAirports.add(a);

      // Check if this function was called right after deserialization
      recoverChangesListeners();

      listeners.forEach(IChangesListener::OnWorldChanged);
    }
  }
Пример #19
0
                  // purpose
  public static void main(String[] args) throws Exception {
    LinkedList list = new LinkedList();
    System.out.println("Enter index");
    // Scanner b = new Scanner(System.in);
    // String m1 = b.next();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = br.readLine();
    int ind = Integer.parseInt(line);
    System.out.println("Enter the list of numbers separated by space");
    // Scanner a = new Scanner(System.in);
    String str = br.readLine();

    String[] strarr = str.split(" ");

    for (int i = 0; i < strarr.length; i++) {
      list.push(Integer.parseInt(strarr[i]));
    }

    //	    System.out.println();
    int len = list.size() - 1;
    if (ind <= len) {
      System.out.println(list.get(ind - 1));
    } else {
      System.out.println("NIL");
    }
  }
Пример #20
0
  private void fill() {
    if (selectedVertex != -1) {
      LinkedList<Integer> selected = new LinkedList<Integer>();
      Stack<Integer> tmp = new Stack<Integer>();
      int vertex;
      boolean[] painted = new boolean[itm.getVertices().length];

      tmp.push(new Integer(selectedVertex));
      while (!tmp.isEmpty()) {
        vertex = tmp.pop();
        if (!painted[vertex] && intensities[vertex] >= lowerThreshold) {
          selected.push(vertex);
          painted[vertex] = true;
          for (int i = 0; i < neighbors[vertex].length; ++i) {
            tmp.push(new Integer(neighbors[vertex][i]));
          }
        }
      }
      currentSegmentation = new ArrayList<Integer>(selected);

      HashSet<Integer> curr = new HashSet<Integer>(selected);
      outline = new ArrayList<Integer>();
      for (int v : currentSegmentation) {
        for (int i = 0; i < neighbors[v].length; i++) {
          if (!curr.contains(neighbors[v][i])) {
            outline.add(v);
            break;
          }
        }
      }
    }
  }
Пример #21
0
 public static List<String> getUserConfigFiles(final String path) throws IOException {
   File configPath = new File(path);
   if (!configPath.exists()) {
     throw new IOException(path + " does not exist!");
   }
   // We are going to assume that this is a top level directory with configuration files in it, we
   // are not going to recur downwards
   LinkedList<String> paths = new LinkedList<String>();
   if (configPath.isDirectory()) {
     for (File file : configPath.listFiles(new XMLFileNameFilter())) {
       paths.push(file.getAbsolutePath());
     }
   } else {
     paths.push(configPath.getAbsolutePath());
   }
   return paths;
 }
Пример #22
0
 public void playCard(CardType card) {
   // if (cards.contains(card)) {
   cards.removeFirstOccurrence(card);
   used.push(card);
   // } else {
   // throw new RuntimeException();
   // }
 }
Пример #23
0
  /** 测试LinkedList以堆栈(后进先出、LIFO)形式使用的方法、 */
  private static void testLinkedListASStack() {
    System.out.println("Test methods: push(E e), poll(), peek()");
    LinkedList<String> stack = new LinkedList<String>();
    stack.push("a");
    stack.push("b");
    stack.push("c");
    stack.push("d");
    printList(stack);

    /*
     *	pop(), poll()都是取出stack栈顶元素 、区别就是当stack中没有元素时、stack.pop()抛异常、stack.poll()返回null
     */
    printStr("取出stack栈顶元素 str :" + stack.pop());
    printStr("取出stack栈顶元素 str :" + stack.poll());
    printStr("查看stack栈顶元素 str :" + stack.peek());
    printList(stack);
  }
 /** @return the next smallest number */
 public int next() {
   while (cur != null) {
     stack.push(cur);
     cur = cur.left;
   }
   TreeNode node = stack.pop();
   cur = node.right;
   return node.val;
 }
 public GroupMembers(Recipients recipients) {
   for (Recipient recipient : recipients.getRecipientsList()) {
     if (isLocalNumber(recipient)) {
       members.push(recipient);
     } else {
       members.add(recipient);
     }
   }
 }
Пример #26
0
 public <T> T doInstance() {
   stateStack.push(State.CLASS_NAME);
   state = State.CLASS_NAME;
   T t = newInstance(getValue());
   stateStack.pop();
   stateStack.pop();
   state = stateStack.getLast();
   return t;
 }
Пример #27
0
 private RenderableObject getNextObjectInPool() {
   if (objectCount == objectPoolLength) {
     RenderableObject object = new RenderableObject();
     objectPool.push(object);
     objectPoolLength++;
     objectCount++;
     return object;
   }
   return objectPool.get(objectCount++);
 }
Пример #28
0
 private RenderableVertex getNextVertexInPool() {
   if (vertexCount == vertexPoolLength) {
     RenderableVertex vertex = new RenderableVertex();
     vertexPool.push(vertex);
     vertexPoolLength++;
     vertexCount++;
     return vertex;
   }
   return vertexPool.get(vertexCount++);
 }
  private LinkedList<String> iteratorOperation(JSONObject object) {

    Iterator iterator = object.keys();

    LinkedList<String> list = new LinkedList<String>();
    while (iterator.hasNext()) {
      list.push(iterator.next().toString());
    }
    return list;
  }
Пример #30
0
 protected void addReferencedDataTypeDefinitions(EndpointInterface ei) {
   LinkedList<Element> contextStack = new LinkedList<Element>();
   contextStack.push(ei);
   try {
     for (WebMethod webMethod : ei.getWebMethods()) {
       addReferencedTypeDefinitions(webMethod, contextStack);
     }
   } finally {
     contextStack.pop();
   }
 }