Ejemplo n.º 1
1
  private boolean startProcessing() {
    LOG.assertTrue(Thread.holdsLock(myQueue));

    if (isProcessing || !myStarted) {
      return false;
    }
    isProcessing = true;
    final T item = myQueue.removeFirst();
    final Runnable runnable =
        () -> {
          if (myDeathCondition.value(null)) return;
          runSafely(() -> myProcessor.consume(item, myContinuationContext));
        };
    final Application application = ApplicationManager.getApplication();
    if (myThreadToUse == ThreadToUse.AWT) {
      final ModalityState state = myModalityState.remove(new MyOverrideEquals(item));
      if (state != null) {
        application.invokeLater(runnable, state);
      } else {
        application.invokeLater(runnable);
      }
    } else {
      application.executeOnPooledThread(runnable);
    }
    return true;
  }
 /**
  * Uses the extraction template generated by the {@link #templateGeneration} process and utilizes
  * some own characteristics of the target page pt to extract the content of it which first needs
  * to be parsed to a DOM tree <em>tp</em>.
  *
  * @param tt The previouslz generated extraction template
  * @param tp_i The root DOM element of the document to predict the main content for
  */
 public void newsContentExtraction(Deque<Token> tt, Token tp_i) {
   // templateNode <-- tt.firstElement
   Token templateNode = tt.getFirst();
   if (templateNode.getName().equals(tp_i.getName())
       && templateNode.getLevel() == tp_i.getLevel()
       && templateNode.getSibNo() == tp_i.getSibNo()) {
     tt.removeFirst();
     if (tt.size() > 0) {
       Token nextTemplateNode = tt.getFirst();
       if (tp_i.getChildren() == null || tp_i.getChildren().length == 0) {
         LOG.info(tp_i.getText());
         while (nextTemplateNode.getParentNo() == templateNode.getNo()) {
           tt.removeFirst();
           templateNode = nextTemplateNode;
           nextTemplateNode = tt.getFirst();
         }
       } else {
         if (nextTemplateNode.getParentNo() != templateNode.getNo()) {
           System.out.println(this.deleteEmbeddedNoise(tp_i.getSubtreeText()));
         }
         for (int j = 0; j < tp_i.getChildren().length; j++) {
           this.newsContentExtraction(tt, tp_i.getChildren()[j]);
         }
       }
     } else {
       LOG.info(this.deleteEmbeddedNoise(tp_i.getSubtreeText()));
     }
   }
 }
Ejemplo n.º 3
0
 public static void main(String[] args) {
   Random r = new Random();
   for (int times = 0; times < 1000; ++times) {
     int n;
     if (args.length == 1) {
       n = Integer.parseInt(args[0]);
     } else {
       n = r.nextInt(10000) + 1;
     }
     List<Integer> A = new ArrayList<>();
     for (int i = 0; i < n; ++i) {
       Integer height = r.nextInt(2 * n) + 1;
       A.add(height);
     }
     Deque<BuildingWithHeight> res = examineBuildingsWithSunset(A.iterator());
     BuildingWithHeight prev = res.removeFirst();
     System.out.println(prev);
     while (!res.isEmpty()) {
       BuildingWithHeight current = res.removeFirst();
       System.out.println(current);
       assert (prev.id < current.id);
       assert (prev.height > current.height);
       prev = current;
     }
   }
 }
  /**
   * Performs a depth-first, post-order traversal over a DAG.
   *
   * @param initialNodes The nodes from which to perform the traversal. Not allowed to contain
   *     {@code null}.
   * @throws CycleException if a cycle is found while performing the traversal.
   */
  @SuppressWarnings("PMD.PrematureDeclaration")
  public void traverse(Iterable<? extends T> initialNodes)
      throws CycleException, IOException, InterruptedException {
    // This corresponds to the current chain of nodes being explored. Enforcing this invariant makes
    // this data structure useful for debugging.
    Deque<Explorable> toExplore = Lists.newLinkedList();
    for (T node : initialNodes) {
      toExplore.add(new Explorable(node));
    }

    Set<T> inProgress = Sets.newHashSet();
    LinkedHashSet<T> explored = Sets.newLinkedHashSet();

    while (!toExplore.isEmpty()) {
      Explorable explorable = toExplore.peek();
      T node = explorable.node;

      // This could happen if one of the initial nodes is a dependency of the other, for example.
      if (explored.contains(node)) {
        toExplore.removeFirst();
        continue;
      }

      inProgress.add(node);

      // Find children that need to be explored to add to the stack.
      int stackSize = toExplore.size();
      for (Iterator<T> iter = explorable.children; iter.hasNext(); ) {
        T child = iter.next();
        if (inProgress.contains(child)) {
          throw createCycleException(child, toExplore);
        } else if (!explored.contains(child)) {
          toExplore.addFirst(new Explorable(child));

          // Without this break statement:
          // (1) Children will be explored in reverse order instead of the specified order.
          // (2) CycleException may contain extra nodes.
          // Comment out the break statement and run the unit test to verify this for yourself.
          break;
        }
      }

      if (stackSize == toExplore.size()) {
        // Nothing was added to toExplore, so the current node can be popped off the stack and
        // marked as explored.
        toExplore.removeFirst();
        inProgress.remove(node);
        explored.add(node);

        // Now that the internal state of this traversal has been updated, notify the observer.
        onNodeExplored(node);
      }
    }

    Preconditions.checkState(inProgress.isEmpty(), "No more nodes should be in progress.");

    onTraversalComplete(Iterables.unmodifiableIterable(explored));
  }
Ejemplo n.º 5
0
 void playPrevious() {
   if (playStack.size() < 2) return;
   System.out.println("------------");
   for (PlaylistAndTrack pnt : playStack) {
     System.out.println(pnt.track.getTitle());
   }
   playStack.removeFirst();
   PlaylistAndTrack prevPlaylistAndTrack = playStack.removeFirst();
   playlistsView.getSelectionModel().select(prevPlaylistAndTrack.playlist);
   tracksView.getSelectionModel().select(prevPlaylistAndTrack.track);
   tracksView.scrollTo(tracksView.getSelectionModel().getSelectedIndex());
   playTrack(prevPlaylistAndTrack.track);
 }
Ejemplo n.º 6
0
  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;
  }
Ejemplo n.º 7
0
 @Test
 public void Deque_addFirst_removeFirst_AddsRemovesTwo() {
   deque.addFirst("firstString");
   deque.addFirst("secondString");
   assertFalse(deque.isEmpty());
   assertEquals(deque.size(), 2);
   String returnedString = deque.removeFirst();
   assertEquals(returnedString, "secondString");
   assertFalse(deque.isEmpty());
   assertEquals(deque.size(), 1);
   returnedString = deque.removeFirst();
   assertEquals(returnedString, "firstString");
   assertTrue(deque.isEmpty());
   assertEquals(deque.size(), 0);
 }
Ejemplo n.º 8
0
 public T undo() {
   if (isUndoable()) {
     future.addFirst(present);
     present = past.removeFirst();
   }
   return present;
 }
  @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.º 10
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.º 11
0
 private void cycleKeyList(Object key) {
   keyList.addLast(key);
   if (keyList.size() > size) {
     Object oldestKey = keyList.removeFirst();
     delegate.removeObject(oldestKey);
   }
 }
Ejemplo n.º 12
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;
  }
Ejemplo n.º 13
0
 public T redo() {
   if (isRedoable()) {
     past.addFirst(present);
     present = future.removeFirst();
   }
   return present;
 }
Ejemplo n.º 14
0
Archivo: Bot.java Proyecto: cmsd2/elsie
 /* (non-Javadoc)
  * @see botFramework.IBot#sendCommands()
  */
 public void sendCommands() {
   String command;
   boolean success;
   while (!queuedCommands.isEmpty()) {
     command = queuedCommands.removeFirst();
     success = send(command);
     if (success == false) {
       queuedCommands.addFirst(command);
       log.error("error sending command. will reconnect and retry");
       sendErrorEvent("Bot.sendCommands", "problem", "Could not send - reconnecting");
       reconnect("Write error!");
       return;
     }
   }
   try {
     sender.flush();
   } catch (SocketTimeoutException e) {
     log.error("socket timeout while flushing", e);
     sendErrorEvent("Bot.sendCommands", "SocketTimeoutException", e.getMessage());
   } catch (IOException e) {
     log.error("ioexception while flushing", e);
     sendErrorEvent("Bot.sendCommands", "IOException", e.getMessage());
     reconnect("Write error!");
   }
 }
Ejemplo n.º 15
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();
   }
 }
 // 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;
 }
 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.º 18
0
  /** This method builds an actual tree from multiple path. */
  private ARGState buildTreeFromMultiplePaths(final Collection<ARGPath> targetPaths) {
    ARGState itpTreeRoot = null;
    Deque<ARGState> todo = new ArrayDeque<>(extractTargets(targetPaths));

    // build the tree, bottom-up, starting from the target states
    while (!todo.isEmpty()) {
      final ARGState currentState = todo.removeFirst();

      if (currentState.getParents().iterator().hasNext()) {

        if (!predecessorRelation.containsKey(currentState)) {
          ARGState parentState = currentState.getParents().iterator().next();

          predecessorRelation.put(currentState, parentState);
          successorRelation.put(parentState, currentState);

          todo.addFirst(parentState);
        }

      } else if (itpTreeRoot == null) {
        itpTreeRoot = currentState;
      }
    }

    return itpTreeRoot;
  }
Ejemplo n.º 19
0
Archivo: Bot.java Proyecto: cmsd2/elsie
 /* (non-Javadoc)
  * @see botFramework.IBot#sendMessages()
  */
 public void sendMessages() {
   BotMessage msg;
   boolean success;
   if (!queuedMessages.isEmpty()) {
     msg = queuedMessages.removeFirst();
     messageTimer.schedule(msg, msg.getDelay());
   }
 }
Ejemplo n.º 20
0
 @Test(expected = NoSuchElementException.class)
 public void Deque_addLast_removeFirst_throwsIfEmpty() {
   deque.addFirst("firstString");
   deque.addFirst("secondString");
   deque.removeLast();
   deque.removeLast();
   deque.removeFirst();
 }
Ejemplo n.º 21
0
 private void prune() {
   // Remove all values that are too old
   TimeInterval periodAllowed = cachedPeriod.before(buffer.getLast().getTimestamp());
   while (!buffer.isEmpty() && !periodAllowed.contains(buffer.getFirst().getTimestamp())) {
     // Discard value
     buffer.removeFirst();
   }
 }
Ejemplo n.º 22
0
  private String upload() throws UploadException, IOException {
    Uploader uploader = new Uploader();
    uploader.setMaxFileSize(MAX_FILE_SIZE);
    uploader.setName(captchan.tfName.getText());
    uploader.setEmail(captchan.tfEmail.getText());
    uploader.setSubject(captchan.tfSubject.getText());
    uploader.setComment(getComment());
    uploader.setChallenge(reChallenges.removeFirst());
    uploader.setResponse(reResponses.removeFirst());
    uploader.setFile(files[workingOn]);
    uploader.setPostURL(postURL);
    uploader.setTopicURL(topicURL);
    uploader.setThread(captchan.tfThread.getText());
    uploader.setUserAgent(userAgent);

    return uploader.upload();
  }
Ejemplo n.º 23
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.º 24
0
 /**
  * Get a JdbConnection object either by the ones available in the queue or replace the first
  * expired connection. When a connection is given to a client, it is tagged with the current time.
  * This enables us to check the duration it has been out and replace if required.
  *
  * @return JDBConnection This contains the actual jdbc connection object to db.
  * @throws ConnectionPoolException Throws if no available connections
  */
 public synchronized JdbConnection borrow() throws ConnectionPoolException {
   if (pooled.size() > 0) {
     borrowed.put(pooled.peek(), Instant.now());
     return pooled.removeFirst();
   } else {
     return createReplacementIfExpiredConnFound();
   }
 }
  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
      throws Exception {
    Subject subject = getSubject(request, response);
    if (!subject.isAuthenticated() && !subject.isRemembered()) {
      // 如果没有登录,直接进行之后的流程
      return true;
    }

    Session session = subject.getSession();
    // String username = (String) subject.getPrincipal();
    String account = ((ShiroUser) subject.getPrincipal()).getAccount();
    Serializable sessionId = session.getId();

    // TODO 同步控制
    Deque<Serializable> deque = cache.get(account);
    if (deque == null) {
      deque = new LinkedList<Serializable>();
      cache.put(account, deque);
    }

    // 如果队列里没有此sessionId,且用户没有被踢出;放入队列
    if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
      deque.push(sessionId);
    }

    // 如果队列里的sessionId数超出最大会话数,开始踢人
    while (deque.size() > maxSession) {
      Serializable kickoutSessionId = null;
      if (kickoutAfter) { // 如果踢出后者
        kickoutSessionId = deque.removeFirst();
      } else { // 否则踢出前者
        kickoutSessionId = deque.removeLast();
      }
      try {
        Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
        if (kickoutSession != null) {
          // 设置会话的kickout属性表示踢出了
          kickoutSession.setAttribute("kickout", true);
        }
      } catch (Exception e) { // ignore exception
      }
    }

    // 如果被踢出了,直接退出,重定向到踢出后的地址
    if (session.getAttribute("kickout") != null) {
      // 会话被踢出了
      try {
        subject.logout();
      } catch (Exception e) { // ignore
      }
      saveRequest(request);
      WebUtils.issueRedirect(request, response, kickoutUrl);
      return false;
    }

    return true;
  }
  private void shiftBufferIfLastBinIsStale() {
    long latest = deque.peekLast().timestamp.getTime();

    if (System.currentTimeMillis() - latest > HOUR_IN_MILLIS) {
      deque.removeFirst();
      latest += HOUR_IN_MILLIS;
      deque.addLast(new HourlyAggregateData(latest));
    }
  }
Ejemplo n.º 27
0
  public static <T extends FlowRenderable<T>> Iterable<LaidFlowLine<T>> getLines(
      Collection<T> flowRenderables,
      TextRenderStyle defaultRenderStyle,
      int yStart,
      ContainerRenderSpace containerRenderSpace) {
    // Take into account a minimum width
    int minWidth = determineMinWidth(flowRenderables, defaultRenderStyle);

    int x = 0;
    int y = yStart;

    int availableWidth = Math.max(minWidth, containerRenderSpace.getWidthForVerticalPosition(y));

    List<LaidFlowLine<T>> result = new LinkedList<>();

    int maxHeightInLine = 0;

    Deque<T> renderablesQueue = new LinkedList<>(flowRenderables);
    List<T> renderablesInLine = new LinkedList<>();
    while (!renderablesQueue.isEmpty()) {
      FlowRenderable<T> flowRenderable = renderablesQueue.removeFirst();
      FlowRenderable.SplitResult<T> splitResult =
          flowRenderable.splitAt(defaultRenderStyle, availableWidth - x);
      if (splitResult.before == null) {
        // This is the end of the line, this renderable doesn't fit
        result.add(new DefaultLaidFlowLine<>(x, maxHeightInLine, renderablesInLine));
        renderablesInLine = new LinkedList<>();
        x = 0;
        y += maxHeightInLine;
        availableWidth = Math.max(minWidth, containerRenderSpace.getWidthForVerticalPosition(y));
        maxHeightInLine = 0;
        renderablesQueue.addFirst(splitResult.rest);
      } else {
        // Append the "before" part and push the "rest" onto the Deque if not null
        int renderableWidth = splitResult.before.getWidth(defaultRenderStyle);
        int renderableHeight = splitResult.before.getHeight(defaultRenderStyle);

        x += renderableWidth;
        maxHeightInLine = Math.max(maxHeightInLine, renderableHeight);
        renderablesInLine.add(splitResult.before);

        if (splitResult.rest != null) {
          result.add(new DefaultLaidFlowLine<>(x, maxHeightInLine, renderablesInLine));
          renderablesInLine = new LinkedList<>();
          x = 0;
          y += maxHeightInLine;
          availableWidth = Math.max(minWidth, containerRenderSpace.getWidthForVerticalPosition(y));
          maxHeightInLine = 0;
          renderablesQueue.addFirst(splitResult.rest);
        }
      }
    }

    result.add(new DefaultLaidFlowLine<>(x, maxHeightInLine, renderablesInLine));

    return result;
  }
Ejemplo n.º 28
0
  private Schema loadFromDirectories(List<Path> directories) throws IOException {
    final Deque<String> protos = new ArrayDeque<>(this.protos);
    if (protos.isEmpty()) {
      for (final Path directory : directories) {
        Files.walkFileTree(
            directory,
            new SimpleFileVisitor<Path>() {
              @Override
              public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                  throws IOException {
                protos.add(directory.relativize(file).toString());
                return FileVisitResult.CONTINUE;
              }
            });
      }
    }

    Map<String, ProtoFile> loaded = new LinkedHashMap<>();
    while (!protos.isEmpty()) {
      String proto = protos.removeFirst();
      if (loaded.containsKey(proto)) {
        continue;
      }

      ProtoFileElement element = null;
      for (Path directory : directories) {
        Source source = source(proto, directory);
        if (source == null) {
          continue;
        }

        try {
          Location location = Location.get(directory.toString(), proto);
          String data = Okio.buffer(source).readUtf8();
          element = ProtoParser.parse(location, data);
        } catch (IOException e) {
          throw new IOException("Failed to load " + proto + " from " + directory, e);
        } finally {
          source.close();
        }
      }
      if (element == null) {
        throw new FileNotFoundException("Failed to locate " + proto + " in " + sources);
      }

      ProtoFile protoFile = ProtoFile.get(element);
      loaded.put(proto, protoFile);

      // Queue dependencies to be loaded.
      for (String importPath : element.imports()) {
        protos.addLast(importPath);
      }
    }

    return new Linker(loaded.values()).link();
  }
 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.º 30
0
 @Override
 public void run() {
   while (true) {
     if (!messages.isEmpty()) {
       // Retrieve the first message and treat it
       NetMessage mess = messages.removeFirst();
       treatMessage(mess);
     }
     ZUtils.sleep(500);
   }
 }