Esempio n. 1
0
  public DomReader pop() throws NoSuchElementException {
    if (null == bookmarks) throw new NoSuchElementException("No bookmarks where ever created");

    current_element = bookmarks.pop();

    return this;
  }
Esempio n. 2
0
  public static void main(String[] args) {
    String[] elementArray = {"sway", "and", "twist", "stacks", "tall"}; // (1)
    System.out.println("Array of elements: " + Arrays.toString(elementArray));

    // Using ArrayDeque as a stack:                                             (2)
    ArrayDeque<String> stack = new ArrayDeque<String>();
    for (String string : elementArray) stack.push(string); // (3) Push elements.
    System.out.println("Stack before: TOP->" + stack + "<-BOTTOM");
    System.out.print("Popping stack: ");
    while (!stack.isEmpty()) { // (4)
      System.out.print(stack.pop() + " "); // (5) Pop elements.
    }
    System.out.println("\n");

    // Using ArrayDeque as a FIFO queue:                                        (6)
    elementArray = new String[] {"Waiting", "in", "queues", "is", "boring"}; // (7)
    System.out.println("Array of elements: " + Arrays.toString(elementArray));
    ArrayDeque<String> fifoQueue = new ArrayDeque<String>();
    for (String string : elementArray) fifoQueue.offerLast(string); // (8) Insert at tail.
    System.out.println("Queue before: HEAD->" + fifoQueue + "<-TAIL");
    System.out.print("Polling queue: ");
    while (!fifoQueue.isEmpty()) { // (9)
      String string = fifoQueue.pollFirst(); // (10) Remove from head.
      System.out.print(string.toUpperCase() + " ");
    }
    System.out.println();
  }
Esempio n. 3
0
  @Override
  public void render(float delta) {
    super.render(delta);

    int nextNodeIndex = -1;

    // prepare text

    kApplication.spriteBatch().begin();
    {
      this.background.draw(kApplication.spriteBatch());
    }
    kApplication.spriteBatch().end();

    this.chessboard_renderer_.begin();
    {
      nextNodeIndex = game_path_.peek().render(region_of_interest_);
    }
    this.chessboard_renderer_.end();

    kApplication.spriteBatch().begin();
    {
      hud.render(kApplication.spriteBatch(), delta);
    }
    kApplication.spriteBatch().end();

    if (nextNodeIndex > -1) {
      if (game_path_.size() > 1) {

        // Cull grandchildren to deallocate memory
        GraphSquare cur_top = game_path_.pop();
        game_path_.peek().CullGrandChildrenExcept(cur_top);
        game_path_.push(cur_top);
      }
      this.region_of_interest_.Reconstrain(
          game_path_.peek().getChildVirtualPosition(nextNodeIndex));
      game_path_.push(game_path_.peek().getChildNode(nextNodeIndex));

      this.hud.pushMove(this.game_path_.peek().toString());

    } else if (game_path_.size() > 1 && this.region_of_interest_.ZoomOutRequired()) {
      GraphSquare previous = game_path_.pop();
      region_of_interest_.Deconstrain(
          game_path_.peek().getChildVirtualPosition(game_path_.peek().getChildIndex(previous)));
      this.hud.popMove();
    }
  }
Esempio n. 4
0
 private Runnable popSimulationInvokes() {
   Runnable r;
   synchronized (pollRequests) {
     r = pollRequests.pop();
     hasPollRequests = !pollRequests.isEmpty();
   }
   return r;
 }
Esempio n. 5
0
 public static String create_string(DFA_Node head) {
   String transitions;
   ArrayDeque<DFA_Node> temp_stack = new ArrayDeque<DFA_Node>();
   Set<DFA_Node> temp_set2 = new HashSet<DFA_Node>();
   temp_stack.add(head);
   temp_set2.add(head);
   while (!temp_stack.isEmpty()) {
     DFA_Node current = temp_stack.pop();
     for (String character : Regex.character_set_test) {}
   }
   return null;
 }
Esempio n. 6
0
 public void distributeEvents() {
   // add collision callbacks
   int clistsize = collisionListeners.size();
   while (collisionEvents.isEmpty() == false) {
     PhysicsCollisionEvent physicsCollisionEvent = collisionEvents.pop();
     for (int i = 0; i < clistsize; i++) {
       collisionListeners.get(i).collision(physicsCollisionEvent);
     }
     // recycle events
     eventFactory.recycle(physicsCollisionEvent);
   }
 }
Esempio n. 7
0
  public void popFrame() {
    int temp = peek();
    int pop = framePointers.pop();

    while (size() - 1 >= pop) {
      if (!runStack.isEmpty()) {
        pop();
      }
    }

    push(temp);
  }
 private static Window pop(Window owner) {
   JRootPane root = getRootPane(owner);
   if (root != null) {
     synchronized (CACHE) {
       @SuppressWarnings("unchecked")
       ArrayDeque<Window> cache = (ArrayDeque<Window>) root.getClientProperty(CACHE);
       if (cache != null && !cache.isEmpty()) {
         return cache.pop();
       }
     }
   }
   return null;
 }
 /**
  * Return the root hash of a binary tree with leaves at the given depths and with the given hash
  * val in each leaf.
  */
 byte[] hashed(byte[] val, Integer... depths) {
   ArrayDeque<Integer> dstack = new ArrayDeque<Integer>();
   ArrayDeque<byte[]> hstack = new ArrayDeque<byte[]>();
   Iterator<Integer> depthiter = Arrays.asList(depths).iterator();
   if (depthiter.hasNext()) {
     dstack.push(depthiter.next());
     hstack.push(val);
   }
   while (depthiter.hasNext()) {
     Integer depth = depthiter.next();
     byte[] hash = val;
     while (depth.equals(dstack.peek())) {
       // consume the stack
       hash = Hashable.binaryHash(hstack.pop(), hash);
       depth = dstack.pop() - 1;
     }
     dstack.push(depth);
     hstack.push(hash);
   }
   assert hstack.size() == 1;
   return hstack.pop();
 }
Esempio n. 10
0
 /**
  * Thread synchronized method to prevent concurrent modification of buffer
  *
  * @param op
  * @param add
  * @return Frame being modified
  */
 private synchronized Frame bufferOp(BufferOp op, Frame add) {
   switch (op) {
     case ADD:
       buffer.addFirst(add);
       return add;
     case ADDLAST:
       buffer.addLast(add);
       return add;
     case REM:
       return buffer.pop();
     default:
       break;
   }
   return null;
 }
Esempio n. 11
0
 public VoltTable nextDependency(final int dependencyId) {
   // this formulation retains an arraydeque in the tracker that is
   // overwritten by the next transaction using this dependency id. If
   // the EE requests all dependencies (as is expected), the deque
   // will not retain any references to VoltTables (which is the goal).
   final ArrayDeque<VoltTable> vtstack = m_depsById.get(dependencyId);
   if (vtstack != null && vtstack.size() > 0) {
     // java doc. says this amortized constant time.
     return vtstack.pop();
   } else if (vtstack == null) {
     assert (false) : "receive without associated tracked dependency.";
     return null;
   } else {
     return null;
   }
 }
Esempio n. 12
0
 public boolean isValid(String s) {
   ArrayDeque<Character> stack = new ArrayDeque<Character>();
   for (int i = 0; i < s.length(); i++) {
     if (!stack.isEmpty()) {
       Character top = stack.peek();
       if (top == '(' && s.charAt(i) == ')'
           || top == '[' && s.charAt(i) == ']'
           || top == '{' && s.charAt(i) == '}') {
         stack.pop();
       } else {
         stack.push(s.charAt(i));
       }
     } else {
       stack.push(s.charAt(i));
     }
   }
   return stack.isEmpty();
 }
Esempio n. 13
0
 /** 深度优先遍历,相当于先根遍历 采用非递归实现 需要辅助数据结构:栈 */
 public void depthOrderTraversal() {
   if (root == null) {
     System.out.println("empty tree");
     return;
   }
   ArrayDeque<TreeNode> stack = new ArrayDeque<TreeNode>();
   stack.push(root);
   while (stack.isEmpty() == false) {
     TreeNode node = stack.pop();
     System.out.print(node.value + "    ");
     if (node.right != null) {
       stack.push(node.right);
     }
     if (node.left != null) {
       stack.push(node.left);
     }
   }
   System.out.print("\n");
 }
Esempio n. 14
0
  private static Map<Trace, Integer> buildTraceIdMap(final Trace root) {
    final Map<Trace, Integer> traceIds = new HashMap<Trace, Integer>();
    final ArrayDeque<Trace> stack = new ArrayDeque<Trace>();
    stack.push(root);

    int counter = 0;
    while (!stack.isEmpty()) {
      final Trace trace = stack.pop();
      traceIds.put(trace, counter++);
      for (Related<Trace> related : trace.getRelated()) {
        final Trace relatedTrace = related.getRelated();
        if (!traceIds.containsKey(relatedTrace)) {
          stack.push(related.getRelated());
        }
      }
    }

    return traceIds;
  }
Esempio n. 15
0
 private static Record readRecord(ArrayDeque<String> stack) {
   Record rec = new Record();
   for (; ; ) {
     if (stack.isEmpty()) {
       return rec;
     }
     String line = stack.pop();
     assert !line.isEmpty();
     if ("%%".equals(line)) {
       return rec;
     }
     if (line.charAt(0) == ' ') {
       // continuation
       continue;
     }
     int sep = line.indexOf(':');
     String name = line.substring(0, sep).trim();
     String value = line.substring(sep + 1).trim();
     Field field = Field.forName(name);
     assert field != null;
     switch (field) {
       case Deprecated:
       case PreferredValue:
       case Prefix:
       case Subtag:
       case Tag:
       case Type:
         rec.entries.put(field, value);
         break;
       case Added:
       case Comments:
       case Description:
       case Macrolanguage:
       case Scope:
       case SupressScript:
       default:
         // ignore these
         break;
     }
   }
 }
  @Override
  public JSType caseTemplateType(TemplateType type) {
    if (replacements.hasTemplateKey(type)) {
      if (hasVisitedType(type) || !replacements.hasTemplateType(type)) {
        // If we have already encountered this TemplateType during replacement
        // (i.e. there is a reference loop), or there is no JSType substitution
        // for the TemplateType, return the TemplateType type itself.
        return type;
      } else {
        JSType replacement = replacements.getTemplateType(type);

        visitedTypes.push(type);
        JSType visitedReplacement = replacement.visit(this);
        visitedTypes.pop();

        return visitedReplacement;
      }
    } else {
      return type;
    }
  }
Esempio n. 17
0
  private void run() {
    WorkerRunnable currentRunnable;

    while (!Thread.interrupted()) {
      synchronized (runQueue) {
        try {
          while (runQueue.isEmpty()) runQueue.wait();
        } catch (InterruptedException ex) {
          break;
        }
        currentRunnable = runQueue.pop();
      }

      try {
        callbackManager.callback(currentRunnable, currentRunnable.run());
      } catch (Throwable ex) {
        callbackManager.callback(currentRunnable, null, ex);
      }
      runnables.remove(currentRunnable.getClass());
    }
  }
Esempio n. 18
0
  @Override
  public void step() {
    if (this.isFinished()) {
      return;
    }

    if (openedList.isEmpty()) {
      this.isFinished = true;
      this.isRunning = false;
      return;
    }

    Node curr = openedList.pop();

    for (Map.Entry<Direction, Link> item : curr.links.entrySet()) {
      Direction dir = item.getKey();
      Link link = item.getValue();

      Node next = link.n1 == curr ? link.n2 : link.n1;

      if (next == goal) {
        parentMap.put(next, curr);
        createPath();
        return;
      }

      if (closedList.contains(next)) {
        // do nothing or reopen?
      } else if (openedList.contains(next)) {
        // do nothing?
      } else {
        openedList.addFirst(next);
        parentMap.put(next, curr);
      }
    }

    closedList.add(curr);
    steps++;
  }
Esempio n. 19
0
    /**
     * Find the next TreeRange.
     *
     * @return The next TreeRange.
     */
    @Override
    public TreeRange computeNext() {
      while (!tovisit.isEmpty()) {
        TreeRange active = tovisit.pop();

        if (active.hashable.hash() != null)
          // skip valid ranges
          continue;

        if (active.hashable instanceof Leaf)
          // found a leaf invalid range
          return active;

        Inner node = (Inner) active.hashable;
        // push intersecting children onto the stack
        TreeRange left =
            new TreeRange(tree, active.left, node.token, inc(active.depth), node.lchild);
        TreeRange right =
            new TreeRange(tree, node.token, active.right, inc(active.depth), node.rchild);
        if (right.intersects(range)) tovisit.push(right);
        if (left.intersects(range)) tovisit.push(left);
      }
      return endOfData();
    }
Esempio n. 20
0
 public final ClaimedMapping nextToCheck() {
   return toCheck.pop();
 }
 @SuppressWarnings("unchecked")
 public <T extends YAMLDescriptor> T pop() {
   return (T) stackedContext.pop();
 }
Esempio n. 22
0
 public String retrieveVersion() {
   return versions.pop();
 }
Esempio n. 23
0
 public T fetch() {
   ArrayDeque<T> objects = pool.get();
   return objects.pop();
 }
  /**
   * We only allow a single deployment at a time to be run through the class path processor.
   *
   * <p>This is because if multiple sibling deployments reference the same item we need to make sure
   * that they end up with the same external module, and do not both create an external module with
   * the same name.
   */
  public synchronized void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

    final DeploymentUnit parent = deploymentUnit.getParent();
    final DeploymentUnit topLevelDeployment = parent == null ? deploymentUnit : parent;
    final VirtualFile topLevelRoot =
        topLevelDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    final ExternalModuleService externalModuleService =
        topLevelDeployment.getAttachment(Attachments.EXTERNAL_MODULE_SERVICE);
    final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);

    // These are resource roots that are already accessible by default
    // such as ear/lib jars an web-inf/lib jars
    final Set<VirtualFile> existingAccessibleRoots = new HashSet<VirtualFile>();

    final Map<VirtualFile, ResourceRoot> subDeployments = new HashMap<VirtualFile, ResourceRoot>();
    for (ResourceRoot root : DeploymentUtils.allResourceRoots(topLevelDeployment)) {
      if (SubDeploymentMarker.isSubDeployment(root)) {
        subDeployments.put(root.getRoot(), root);
      } else if (ModuleRootMarker.isModuleRoot(root)) {
        // top level module roots are already accessible, as they are either
        // ear/lib jars, or jars that are already part of the deployment
        existingAccessibleRoots.add(root.getRoot());
      }
    }

    final ArrayDeque<RootEntry> resourceRoots = new ArrayDeque<RootEntry>();
    if (deploymentUnit.getParent() != null) {
      // top level deployments already had their exiting roots processed above
      for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) {

        if (ModuleRootMarker.isModuleRoot(root)) {
          // if this is a sub deployment of an ear we need to make sure we don't
          // re-add existing module roots as class path entries
          // this will mainly be WEB-INF/(lib|classes) entries
          existingAccessibleRoots.add(root.getRoot());
        }
      }
    }

    for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) {
      // add this to the list of roots to be processed
      resourceRoots.add(new RootEntry(deploymentUnit, root));
    }

    // build a map of the additional module locations
    // note that if a resource root has been added to two different additional modules
    // and is then referenced via a Class-Path entry the behaviour is undefined
    final Map<VirtualFile, AdditionalModuleSpecification> additionalModules =
        new HashMap<VirtualFile, AdditionalModuleSpecification>();
    for (AdditionalModuleSpecification module :
        topLevelDeployment.getAttachmentList(Attachments.ADDITIONAL_MODULES)) {
      for (ResourceRoot additionalModuleResourceRoot : module.getResourceRoots()) {
        additionalModules.put(additionalModuleResourceRoot.getRoot(), module);
      }
    }

    // additional resource roots may be added as
    while (!resourceRoots.isEmpty()) {
      final RootEntry entry = resourceRoots.pop();
      final ResourceRoot resourceRoot = entry.resourceRoot;
      final Attachable target = entry.target;

      // if this is a top level deployment we do not want to process sub deployments
      if (SubDeploymentMarker.isSubDeployment(resourceRoot) && resourceRoot != deploymentRoot) {
        continue;
      }

      final String[] items = getClassPathEntries(resourceRoot);
      for (final String item : items) {
        if (item.isEmpty()) {
          continue;
        }
        // first try and resolve relative to the manifest resource root
        final VirtualFile classPathFile = resourceRoot.getRoot().getParent().getChild(item);
        // then resolve relative to the deployment root
        final VirtualFile topLevelClassPathFile =
            deploymentRoot.getRoot().getParent().getChild(item);
        if (item.startsWith("/")) {
          if (externalModuleService.isValid(item)) {
            final ModuleIdentifier moduleIdentifier = externalModuleService.addExternalModule(item);
            target.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, moduleIdentifier);
            ServerLogger.DEPLOYMENT_LOGGER.debugf(
                "Resource %s added as external jar %s", classPathFile, resourceRoot.getRoot());
          } else {
            ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(
                item, resourceRoot.getRoot().getPathName());
          }
        } else {
          if (classPathFile.exists()) {
            // we need to check that this class path item actually lies within the deployment
            boolean found = false;
            VirtualFile file = classPathFile.getParent();
            while (file != null) {
              if (file.equals(topLevelRoot)) {
                found = true;
              }
              file = file.getParent();
            }
            if (!found) {
              ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(
                  item, resourceRoot.getRoot().getPathName());
            } else {
              handlingExistingClassPathEntry(
                  deploymentUnit,
                  resourceRoots,
                  topLevelDeployment,
                  topLevelRoot,
                  subDeployments,
                  additionalModules,
                  existingAccessibleRoots,
                  resourceRoot,
                  target,
                  classPathFile);
            }
          } else if (topLevelClassPathFile.exists()) {
            boolean found = false;
            VirtualFile file = topLevelClassPathFile.getParent();
            while (file != null) {
              if (file.equals(topLevelRoot)) {
                found = true;
              }
              file = file.getParent();
            }
            if (!found) {
              ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(
                  item, resourceRoot.getRoot().getPathName());
            } else {
              handlingExistingClassPathEntry(
                  deploymentUnit,
                  resourceRoots,
                  topLevelDeployment,
                  topLevelRoot,
                  subDeployments,
                  additionalModules,
                  existingAccessibleRoots,
                  resourceRoot,
                  target,
                  topLevelClassPathFile);
            }
          } else {
            ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(
                item, resourceRoot.getRoot().getPathName());
          }
        }
      }
    }
  }
Esempio n. 25
0
  /**
   * {@link LanguageSubtagRegistryData}
   *
   * @param langSubtagReg the language subtag registry file
   * @throws IOException if an I/O error occurs
   */
  static void languageSubtagRegistry(Path langSubtagReg) throws IOException {
    List<String> lines = Files.readAllLines(langSubtagReg, StandardCharsets.UTF_8);
    ArrayDeque<String> stack = new ArrayDeque<>(lines);

    ArrayList<Record> language = new ArrayList<>();
    ArrayList<Record> region = new ArrayList<>();
    ArrayList<Record> grandfathered = new ArrayList<>();
    ArrayList<Record> redundant = new ArrayList<>();

    ArrayList<Record> extlang = new ArrayList<>();
    ArrayList<Record> script = new ArrayList<>();
    ArrayList<Record> variant = new ArrayList<>();

    // skip first two lines (file date + %% separator)
    stack.pop();
    stack.pop();
    while (!stack.isEmpty()) {
      Record rec = readRecord(stack);
      String type = rec.get(Field.Type);
      assert type != null;
      if ("language".equals(type)) {
        if (rec.has(Field.PreferredValue)) {
          language.add(rec);
        }
      }
      if ("region".equals(type)) {
        if (rec.has(Field.PreferredValue)) {
          region.add(rec);
        }
      }
      if ("grandfathered".equals(type)) {
        grandfathered.add(rec);
      }
      if ("redundant".equals(type)) {
        if (rec.has(Field.PreferredValue)) {
          redundant.add(rec);
        }
      }
      if ("extlang".equals(type)) {
        if (rec.has(Field.PreferredValue)) {
          extlang.add(rec);
        }
      }
      if ("script".equals(type)) {
        if (rec.has(Field.PreferredValue)) {
          script.add(rec);
        }
      }
      if ("variant".equals(type)) {
        if (rec.has(Field.PreferredValue)) {
          variant.add(rec);
        }
      }
    }

    /* Generate LanguageSubtagRegistryData#scriptData entries */
    System.out.println("--- [LanguageSubtagRegistryData#scriptData] ---");
    for (Record record : script) {
      assert record.has(Field.Prefix);
      System.out.printf(
          "%s -> %s [%s]%n",
          record.get(Field.Subtag), record.get(Field.PreferredValue), record.get(Field.Prefix));
    }
    System.out.println();
    assert script.isEmpty() : "no preferred values for 'script' expected";

    /* Generate LanguageSubtagRegistryData#extlangData entries */
    System.out.println("--- [LanguageSubtagRegistryData#extlangData] ---");
    for (Record record : extlang) {
      assert record.has(Field.Prefix);
      assert record.get(Field.Subtag).equals(record.get(Field.PreferredValue))
          : record.get(Field.Subtag);
      System.out.printf(
          "map.put(\"%s\", \"%s\");%n", record.get(Field.Subtag), record.get(Field.Prefix));
    }
    System.out.println();

    /* Generate LanguageSubtagRegistryData#variantData entries */
    System.out.println("--- [LanguageSubtagRegistryData#variantData] ---");
    for (Record record : variant) {
      assert record.has(Field.Prefix);
      System.out.printf(
          "%s -> %s [%s]%n",
          record.get(Field.Subtag), record.get(Field.PreferredValue), record.get(Field.Prefix));
      System.out.printf(
          "map.put(\"%s\", \"%s\");%n", record.get(Field.Subtag), record.get(Field.PreferredValue));
    }
    System.out.println();
    assert variant.size() == 1 : "Only one variant entry expected";
    assert variant.get(0).get(Field.Subtag).equals("heploc");
    assert variant.get(0).get(Field.PreferredValue).equals("alalc97");

    /* Generate LanguageSubtagRegistryData#regionData entries */
    System.out.println("--- [LanguageSubtagRegistryData#regionData] ---");
    for (Record record : region) {
      assert !record.has(Field.Prefix);
      System.out.printf(
          "map.put(\"%s\", \"%s\");%n",
          record.get(Field.Subtag).toLowerCase(Locale.ROOT), record.get(Field.PreferredValue));
    }
    System.out.println();

    /* Generate LanguageSubtagRegistryData#languageData entries */
    System.out.println("--- [LanguageSubtagRegistryData#languageData] ---");
    for (Record record : language) {
      assert !record.has(Field.Prefix);
      System.out.printf(
          "map.put(\"%s\", \"%s\");%n", record.get(Field.Subtag), record.get(Field.PreferredValue));
    }
    System.out.println();

    /* Generate LanguageSubtagRegistryData#grandfatheredData entries */
    System.out.println("--- [LanguageSubtagRegistryData#grandfatheredData] ---");
    for (Record record : grandfathered) {
      assert !record.has(Field.Prefix);
      if (record.has(Field.PreferredValue)) {
        System.out.printf(
            "map.put(\"%s\", \"%s\");%n",
            record.get(Field.Tag).toLowerCase(Locale.ROOT), record.get(Field.PreferredValue));
      } else {
        System.out.printf(
            "map.put(\"%s\", \"%s\");%n",
            record.get(Field.Tag).toLowerCase(Locale.ROOT), record.get(Field.Tag));
      }
    }
    System.out.println();

    /* Generate LanguageSubtagRegistryData#redundantData entries */
    System.out.println("--- [LanguageSubtagRegistryData#redundantData] ---");
    for (Record record : redundant) {
      assert !record.has(Field.Prefix);
      System.out.printf(
          "map.put(\"%s\", \"%s\");%n",
          record.get(Field.Tag).toLowerCase(Locale.ROOT), record.get(Field.PreferredValue));
    }
    System.out.println();
  }