public ArrayDeque shunting(ArrayDeque<Token> infix) throws IOException {
    operatorStack = new Stack<Character>();
    postfixDeque = new ArrayDeque<String>();

    while (!infix.isEmpty()) {
      Token token = infix.poll();
      if (token.type == "OPERATOR") {
        processOperator((token.data).charAt(0));
      } else if (token.type == "SIN") {
        // TODO: This is kind of a weird place to put this... should be delegated to a more generic
        // method.
        String d = "";
        Pattern pattern = Pattern.compile("([-]?[0-9.]+)");
        Matcher matcher = pattern.matcher(token.data);
        while (matcher.find()) {
          d = matcher.group(1);
        }
        processOperator('s'); // 's' will be sin function.
        postfixDeque.add(d);
      } else {
        postfixDeque.add(token.data);
      }
    }
    // Pop any remaining operators and
    // append them to postfix.
    while (!operatorStack.empty()) {
      char op = operatorStack.pop();
      postfixDeque.add(String.valueOf(op));
    }
    return postfixDeque;
  }
Ejemplo n.º 2
0
 public void forceQueRequest(Request request) {
   synchronized (lock) {
     if (blockingRequest == null) {
       requestQueue.add(request);
       channel.writeAndFlush(request.getRequest());
       if (request.isBlocking()) {
         blockingRequest = new BlockingRequestInProgress(request);
         request
             .getToComplete()
             .addListener(
                 new DbListener<Object>() {
                   @Override
                   public void onCompletion(DbFuture<Object> future) {
                     blockingRequest.continueWithRequests();
                   }
                 });
       }
     } else {
       if (blockingRequest.unblockBy(request)) {
         requestQueue.add(request);
         channel.writeAndFlush(request.getRequest());
       } else {
         blockingRequest.add(request);
       }
     }
   }
 }
  @Test
  public void testBlockUnblockWithPresence() throws Exception {
    JID connJid = JID.jidInstanceNS("[email protected]/test-111");
    JID userJid = JID.jidInstanceNS("[email protected]/res-1");
    XMPPResourceConnection sess = getSession(connJid, userJid);

    String blockJid = "*****@*****.**";
    RosterAbstract roster_util = RosterFactory.getRosterImplementation(true);
    roster_util.addBuddy(sess, JID.jidInstance(blockJid), "Block-1", null, null);
    roster_util.setBuddySubscription(
        sess, RosterAbstract.SubscriptionType.both, JID.jidInstance(blockJid));

    checkPrivacyJidBlocked(sess, blockJid, false);
    List<String> blocked = getBlocked(sess);
    assertTrue(blocked == null || blocked.isEmpty());

    block(sess, blockJid);
    assertEquals(3, results.size());
    privacy.filter(null, sess, null, results);

    assertEquals(3, results.size());
    Packet result = results.poll();
    assertNotNull(result);
    assertEquals(tigase.server.Presence.ELEM_NAME, result.getElemName());
    assertEquals(StanzaType.unavailable, result.getType());
    result = results.poll();
    assertNotNull(result);
    assertEquals(Iq.ELEM_NAME, result.getElemName());
    assertEquals(StanzaType.result, result.getType());
    result = results.poll();
    assertNotNull(result);
    assertEquals(Iq.ELEM_NAME, result.getElemName());
    assertEquals(StanzaType.set, result.getType());

    checkPrivacyJidBlocked(sess, blockJid, true);
    blocked = getBlocked(sess);
    assertTrue(blocked.contains(blockJid));

    unblock(sess, blockJid);
    assertEquals(3, results.size());
    privacy.filter(null, sess, null, results);

    assertEquals(3, results.size());
    result = results.poll();
    assertNotNull(result);
    assertEquals(tigase.server.Presence.ELEM_NAME, result.getElemName());
    assertEquals(StanzaType.probe, result.getType());
    result = results.poll();
    assertNotNull(result);
    assertEquals(Iq.ELEM_NAME, result.getElemName());
    assertEquals(StanzaType.result, result.getType());
    result = results.poll();
    assertNotNull(result);
    assertEquals(Iq.ELEM_NAME, result.getElemName());
    assertEquals(StanzaType.set, result.getType());

    checkPrivacyJidBlocked(sess, blockJid, false);
    blocked = getBlocked(sess);
    assertTrue(blocked == null || blocked.isEmpty());
  }
Ejemplo n.º 4
0
  public static void main(String[] args) {
    // AI a = new AI();
    String input = "exampleinput.txt";
    /*
     * try{ BufferedReader br = new BufferedReader(new
     * InputStreamReader(System.in));
     * System.out.println("Please enter an input filename location: ");
     * input = br.readLine(); }catch(IOException io){ io.printStackTrace();
     * }
     */

    GUI.Threes.readFile(input);
    GUI.Threes.set();
    Moves.storeNext();
    Moves.resetNext();
    ArrayDeque<String> Res = AStar(GUI.Threes.board, 400);
    System.out.println(Res.removeFirst());
    System.out.println(Res.removeFirst());

    Moves.doMove(GUI.Threes.board, Res, true);
    System.out.println("Final board is");
    // GUI.Threes.finalBoard();

    while (!Res.isEmpty()) {
      System.out.print(Res.removeLast());
    }
    System.out.println();
    GUI.Threes.readFile(input);
    GUI.Threes.set();
    Moves.resetNext();
    recur(GUI.Threes.board, 10);
  }
Ejemplo n.º 5
0
 synchronized void add(Chunk c) throws InterruptedException {
   int len = c.getData().length;
   if (BLOCK_WHEN_FULL) while (len + dataSizeBytes > maxDataSize) wait();
   else chunks.remove();
   dataSizeBytes += len;
   chunks.add(c);
 }
Ejemplo n.º 6
0
  private void checkEnum(EnumDataSchema older, EnumDataSchema newer) {
    checkName(older, newer);

    _path.addLast(DataSchemaConstants.SYMBOLS_KEY);

    // using list to preserve symbol order
    List<String> newerOnlySymbols = new CheckerArrayList<String>(newer.getSymbols());
    newerOnlySymbols.removeAll(older.getSymbols());

    List<String> olderOnlySymbols = new CheckerArrayList<String>(older.getSymbols());
    olderOnlySymbols.removeAll(newer.getSymbols());

    if (newerOnlySymbols.isEmpty() == false) {
      appendMessage(
          CompatibilityMessage.Impact.BREAKS_OLD_READER,
          "new enum added symbols %s",
          newerOnlySymbols);
    }

    if (olderOnlySymbols.isEmpty() == false) {
      appendMessage(
          CompatibilityMessage.Impact.BREAKS_NEW_READER,
          "new enum removed symbols %s",
          olderOnlySymbols);
    }

    _path.removeLast();
  }
 private void processOperator(char op) {
   if (operatorStack.empty()) {
     operatorStack.push(op);
   } else {
     char topOp = operatorStack.peek();
     if (op == '(') {
       operatorStack.push(op);
     } else if ((topOp == '(' || precedence(op) > precedence(topOp)) && op != ')') {
       operatorStack.push(op);
     } else if (op == ')') {
       while (topOp != '(') {
         operatorStack.pop();
         postfixDeque.add(String.valueOf(topOp));
         if (!operatorStack.empty()) {
           topOp = operatorStack.peek();
         }
       }
       operatorStack.pop(); // removes the right parenthesis
     } else {
       // Pop all stacked operators with equal
       // or higher precedence than op.
       while (!operatorStack.empty() && precedence(op) <= precedence(topOp) && topOp != '(') {
         operatorStack.pop();
         postfixDeque.add(String.valueOf(topOp));
         if (!operatorStack.empty()) {
           // Reset topOp.
           topOp = operatorStack.peek();
         }
       }
       operatorStack.push(op);
     }
   }
 }
Ejemplo n.º 8
0
 public boolean subsetFound(int t, ArrayDeque<BaseVertex> complement, ArrayDeque<BaseVertex> set) {
   nn++;
   if (max < set.size()) {
     max = set.size();
   }
   return false;
 }
Ejemplo n.º 9
0
 public boolean subsetFound(int t, ArrayDeque<BaseVertex> complement, ArrayDeque<BaseVertex> set) {
   if (max <= set.size()) {
     max = set.size();
     maxsets.add(new ArrayDeque<BaseVertex>(set));
   }
   return false;
 }
Ejemplo n.º 10
0
 private void _submitQuery(WorkerRunnable runnable) {
   attachRunnable(runnable);
   synchronized (runQueue) {
     runQueue.add(runnable);
     runQueue.notify();
   }
 }
  /** Build a new trace starting at {@code block}. */
  @SuppressWarnings("try")
  private Collection<T> startTrace(T block, int traceNumber) {
    ArrayDeque<T> trace = new ArrayDeque<>();
    try (Indent i = Debug.logAndIndent("StartTrace: " + block)) {
      try (Indent indentFront = Debug.logAndIndent("Head:")) {
        for (T currentBlock = block;
            currentBlock != null;
            currentBlock = selectPredecessor(currentBlock)) {
          addBlockToTrace(currentBlock, traceNumber);
          trace.addFirst(currentBlock);
        }
      }
      /* Number head blocks. Can not do this in the loop as we go backwards. */
      int blockNr = 0;
      for (T b : trace) {
        b.setLinearScanNumber(blockNr++);
      }

      try (Indent indentBack = Debug.logAndIndent("Tail:")) {
        for (T currentBlock = selectSuccessor(block);
            currentBlock != null;
            currentBlock = selectSuccessor(currentBlock)) {
          addBlockToTrace(currentBlock, traceNumber);
          trace.addLast(currentBlock);
          /* This time we can number the blocks immediately as we go forwards. */
          currentBlock.setLinearScanNumber(blockNr++);
        }
      }
    }
    Debug.log("Trace: %s", trace);
    return trace;
  }
Ejemplo n.º 12
0
  /** Get a list of all the people that ignorer is ignoring */
  public static ArrayDeque<UUIDName> get_ignoring(UUID ignorer) {
    ArrayDeque<UUIDName> ret = null;
    try {
      String query = "SELECT * FROM ignores WHERE " + "ignorer = ?;";
      PreparedStatement st = conn.prepareStatement(query);
      st.setString(1, ignorer.toString());

      ResultSet rs = st.executeQuery();
      ret = new ArrayDeque<UUIDName>();
      while (rs.next()) {
        UUID uuid = UUID.fromString(rs.getString("ignored"));
        String name = rs.getString("ignoredname");

        UUIDName tmp = new UUIDName(uuid, name);
        ret.add(tmp);
      }

      rs.close();
      st.close();

    } catch (Exception e) {
      Ignore.instance.getLogger().warning(e.getMessage());
    }

    return ret;
  }
Ejemplo n.º 13
0
  @Override
  public void onNotify(ActionValueNotifierClient source, ActionValueEvent notification) {
    L.d(notification.toString());
    queue.add(new ActionNotification(source, notification));

    if (queue.size() == 1 && !jobRunning) Synapse.handler.post(dequeJob);
  }
Ejemplo n.º 14
0
  private Expression createFunction(String name, int noOfMembers) throws SAXPathException {
    if (noOfMembers == 0) {
      if (name.equals("position")) {
        Step step = stepStack.peekLast();
        if (step != null) {
          int axis = step.axis;
          if (axis == Axis.SELF
              || ((axis == Axis.ATTRIBUTE || axis == Axis.NAMESPACE)
                  && step.constraint instanceof QName)
              || step.predicateSet.getPredicate() instanceof ExactPosition)
            return new Literal(DataType.ONE, DataType.NUMBER);
        }
        return new Position();
      } else if (name.equals("last")) {
        Step step = stepStack.peekLast();
        if (step != null) {
          int axis = step.axis;
          if (axis == Axis.SELF
              || ((axis == Axis.ATTRIBUTE || axis == Axis.NAMESPACE)
                  && step.constraint instanceof QName)
              || step.predicateSet.getPredicate() instanceof ExactPosition)
            return new Literal(DataType.ONE, DataType.NUMBER);
        }
        return new Last();
      } else if (name.equals("true")) return new Literal(Boolean.TRUE, DataType.BOOLEAN);
      else if (name.equals("false")) return new Literal(Boolean.FALSE, DataType.BOOLEAN);
    }

    Function function = Functions.library.get(name);
    if (function == null) throw new SAXPathException("Unknown function: " + name);
    return new FunctionCall(function, noOfMembers);
  }
Ejemplo n.º 15
0
  public int numIslands(char[][] grid) {
    int counter = 0;
    int n = grid.length;
    if (n == 0) return 0;
    int m = grid[0].length;
    if (m == 0) return 0;
    int[][] direct = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (grid[i][j] == '1') {
          counter++;
          ArrayDeque<Integer> q = new ArrayDeque<Integer>();
          grid[i][j] = 0;
          q.add(i);
          q.add(j);
          while (!q.isEmpty()) {
            int r = q.poll();
            int c = q.poll();
            for (int[] d : direct) {
              int rr = d[0] + r;
              int cc = d[1] + c;
              if (rr >= 0 && rr < n && cc >= 0 && cc < m && grid[rr][cc] == '1') {
                grid[rr][cc] = 0;
                q.add(rr);
                q.add(cc);
              }
            }
          }
        }
      }
    }
    return counter;
  }
Ejemplo n.º 16
0
 private Runnable popSimulationInvokes() {
   Runnable r;
   synchronized (pollRequests) {
     r = pollRequests.pop();
     hasPollRequests = !pollRequests.isEmpty();
   }
   return r;
 }
Ejemplo n.º 17
0
        @Override
        protected ArrayDeque<T> initialValue() {
          ArrayDeque<T> objects = new ArrayDeque<>(maxSize);

          for (int i = 0; i < maxSize; i++) objects.push(newInstance());

          return objects;
        }
Ejemplo n.º 18
0
 /**
  * Add a single dependency. Exists only for test cases.
  *
  * @param depId
  * @param vt
  */
 void addDependency(final int depId, final VoltTable vt) {
   ArrayDeque<VoltTable> deque = m_depsById.get(depId);
   if (deque == null) {
     deque = new ArrayDeque<VoltTable>();
     m_depsById.put(depId, deque);
   }
   deque.add(vt);
 }
Ejemplo n.º 19
0
  private void displayOutput(String site, String restoredAccount) {
    // Get a reference to the layout where the card will be displayed
    final LinearLayout layout = (LinearLayout) findViewById(R.id.now_layout);

    // Create the View for the card
    final CardView card = new CardView(this);

    // Specify layout parameters to be applied
    LinearLayout.LayoutParams lp =
        new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 20, 0, 0);

    // Set the internal state of the card
    card.setSite(site);

    // Show the prettier string if available
    if (siteNames.containsKey(site)) {
      card.setSiteHeaderText(siteNames.get(site));
    } else {
      card.setSiteHeaderText(site);
    }

    // Check if account is specified or pick the most recent from the search history if not
    if (restoredAccount == null) {
      if (!searchHistory.isEmpty()) {
        card.setSiteAccountText("Compromised: " + searchHistory.peekLast());
      }
    } else {
      card.setSiteAccountText(restoredAccount);
    }

    if (siteDescriptions.containsKey(site)) {
      card.setSiteDescriptionText(siteDescriptions.get(site));
    } else {
      card.setSiteDescriptionText(getString(R.string.card_description_unavailable));
    }
    card.setLayoutParams(lp);

    // Create the swipe-to-dismiss touch listener.
    card.setOnTouchListener(
        new SwipeDismissTouchListener(
            card,
            null,
            new SwipeDismissTouchListener.DismissCallbacks() {
              @Override
              public boolean canDismiss(Object token) {
                return true;
              }

              @Override
              public void onDismiss(View view, Object token) {
                layout.removeView(card);
              }
            }));

    layout.addView(card);
  }
  public void pushSRI(StreamSRI header) {

    if (logger != null) {
      logger.trace("bulkio.InPort pushSRI  ENTER (port=" + name + ")");
    }
    synchronized (sriUpdateLock) {
      if (!currentHs.containsKey(header.streamID)) {
        if (logger != null) {
          logger.debug("pushSRI PORT:" + name + " NEW SRI:" + header.streamID);
        }
        if (sriCallback != null) {
          sriCallback.newSRI(header);
        }
        currentHs.put(header.streamID, new sriState(header, true));
        if (header.blocking) {
          // If switching to blocking we have to set the semaphore
          synchronized (dataBufferLock) {
            if (!blocking) {
              try {
                queueSem.acquire(workQueue.size());
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
            }
            blocking = true;
          }
        }
      } else {
        StreamSRI oldSri = currentHs.get(header.streamID).getSRI();
        boolean cval = false;
        if (sri_cmp != null) {
          cval = sri_cmp.compare(header, oldSri);
        }
        if (cval == false) {
          if (sriCallback != null) {
            sriCallback.changedSRI(header);
          }
          this.currentHs.put(header.streamID, new sriState(header, true));
          if (header.blocking) {
            // If switching to blocking we have to set the semaphore
            synchronized (dataBufferLock) {
              if (!blocking) {
                try {
                  queueSem.acquire(workQueue.size());
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              }
              blocking = true;
            }
          }
        }
      }
    }
    if (logger != null) {
      logger.trace("bulkio.InPort pushSRI  EXIT (port=" + name + ")");
    }
  }
Ejemplo n.º 21
0
 @Override
 public Item removeItem() throws Exception {
   if (!itemList.isEmpty()) {
     maxItemCnt -= 1;
     return itemList.removeLast();
   } else {
     throw new ItemStoreException("Стопка пуста");
   }
 }
Ejemplo n.º 22
0
  // undo
  // 从undoQueue中删除并放到redoQueue中
  public String undo() {

    String last = undoQueue.pollLast();
    if (last != null) {
      redoQueue.addLast(last);
    }

    return undoQueue.peekLast();
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent
  * )
  */
 @Override
 protected void append(LoggingEvent loggingEvent) {
   synchronized (bufferLock) {
     if (buffer.size() == capacity) {
       buffer.poll();
     }
     buffer.offer(loggingEvent);
   }
 }
Ejemplo n.º 24
0
  public void run() {
    super.run();

    long currentTime = this.bh.getTime();
    if (!auctionSubmissionTimes.isEmpty() && currentTime >= auctionSubmissionTimes.peekLast()) {
      auctionSubmissionTimes.removeLast();
      submitAuction();
    }
  }
  @Override
  public boolean doWork(boolean rejoining) {
    if (rejoining && (m_rejoinState == RejoinState.NORMAL)) {
      m_rejoinState = RejoinState.REJOINING;
      if (!m_isReadOnly) {
        m_loggedFragments =
            new FragmentTaskLogMessage(
                m_notice.getInitiatorHSId(), m_notice.getCoordinatorHSId(), m_notice.getTxnId());
        assert (m_loggedFragments.getTxnId() == getNotice().getTxnId());
      }
    }

    if (!m_hasStartedWork) {
      m_site.beginNewTxn(this);
      m_hasStartedWork = true;
    }

    if (m_done) {
      return true;
    }

    while (!isBlocked()) {
      WorkUnit wu = m_readyWorkUnits.poll();
      if (wu.shouldResumeProcedure()) {
        assert (m_stackFrameDropWUs != null);
        m_stackFrameDropWUs.remove(wu);

        m_shouldResumeProcedure = true;
        m_previousStackFrameDropDependencies = wu.getDependencies();

        for (WorkUnit sfd : m_stackFrameDropWUs) {
          sfd.m_stackCount--;
          if (sfd.allDependenciesSatisfied()) {
            m_readyWorkUnits.add(sfd);
          }
        }

        return m_done;
      }

      VoltMessage payload = wu.getPayload();

      if (payload instanceof InitiateTaskMessage) {
        initiateProcedure((InitiateTaskMessage) payload);
      } else if (payload instanceof FragmentTaskMessage) {
        if ((m_rejoinState == RejoinState.REJOINING) && (wu.nonTransactional == false)) {
          processRejoiningFragmentWork((FragmentTaskMessage) payload, wu.getDependencies());
        } else {
          // when recovering, still do non-transactional work
          processFragmentWork((FragmentTaskMessage) payload, wu.getDependencies());
        }
      }
    }

    return m_done;
  }
Ejemplo n.º 26
0
  // redo
  // 从redo队头获取一个元素,移到undoQueue中
  public String redo() {
    if (redoQueue.isEmpty()) {
      return null;
    }

    String str = redoQueue.pollFirst();
    redoQueue.addLast(str);

    return str;
  }
Ejemplo n.º 27
0
  private void fineSubstract(Node n) {
    int xGrid, yGrid;

    xGrid = (int) ((n.subX + HALF_VIEW + .5) * VIEW_TO_GRID);
    yGrid = (int) ((n.subY + HALF_VIEW + .5) * VIEW_TO_GRID);
    ArrayDeque<Node> deque = bins[yGrid][xGrid];
    if (deque != null) {
      deque.pollFirst();
    }
  }
Ejemplo n.º 28
0
 @Override
 public void endUnionExpr(boolean create) {
   ArrayDeque stack = popFrame();
   if (create) {
     LocationPath result = new LocationPath(Scope.LOCAL, 0);
     result.addToContext((LocationPath) stack.pollFirst());
     result.addToContext((LocationPath) stack.pollFirst());
     push(result);
   } else push(stack.peek());
 }
 private long testingArrayDeque() {
   ArrayDeque<Object> array = new ArrayDeque<Object>();
   long start = System.currentTimeMillis();
   for (int i = 0; i < getMax(); i++) {
     array.add(i);
   }
   long end = System.currentTimeMillis();
   long time = (end - start);
   refreshTotalTime(time);
   return time;
 }
Ejemplo n.º 30
0
 public Clause createClause(DPLLEngine engine) {
   assert (mAnnotationStack.size() == 1);
   LAAnnotation baseAnnotation = mAnnotationStack.getLast();
   Literal[] lits = baseAnnotation.collectLiterals();
   Clause clause = new Clause(lits);
   if (engine.isProofGenerationEnabled()) {
     clause.setProof(new LeafNode(LeafNode.THEORY_LA, baseAnnotation));
   }
   assert validClause();
   return clause;
 }