public static List<List<Integer>> levelOrderBottom(TreeNode root) {
   if (root == null) {
     return new ArrayList<>();
   }
   List<List<Integer>> res = new ArrayList<>();
   List<Integer> level = new ArrayList<>();
   Queue<TreeNode> queue = new LinkedList<>(); // 新建一个queue,用来记录哪些nodes是目前的波前
   queue.add(root); // 向root注水作为波前
   queue.add(null); // 在波前队列queue加null作为Flag代表这层level已访问结束
   while (queue.size() != 0) {
     TreeNode u = queue.poll();
     if (u != null) {
       level.add(u.val);
       /*
        * 波前u向其所有有连同的node扩散
        * u是v的predecessor前驱 or parent
        * v是u的 descendent后记
        * */
       if (u.left != null) {
         queue.add(u.left);
       }
       if (u.right != null) {
         queue.add(u.right);
       }
     } else {
       res.add(level);
       level = new ArrayList<Integer>();
       if (!queue.isEmpty()) {
         queue.add(null);
       }
     }
   }
   Collections.reverse(res);
   return res;
 }
  public List<List<Integer>> levelOrderBottom(TreeNode root) {
    List<List<Integer>> ret = new ArrayList<>();
    if (root == null) {
      return ret;
    }
    Stack<List<Integer>> tmpStack = new Stack<>();

    Queue<TreeNode> tmpQueue = new LinkedList<>();
    tmpQueue.add(root);

    while (tmpQueue.size() != 0) {
      int length = tmpQueue.size();
      List<Integer> tmp = new ArrayList<>();
      while (length != 0) {
        TreeNode topNode = tmpQueue.poll();
        if (topNode.right != null) {
          tmpQueue.add(topNode.right);
        }
        if (topNode.left != null) {
          tmpQueue.add(topNode.left);
        }
        tmp.add(topNode.val);
        length--;
      }
      tmpStack.push(tmp);
    }

    while (!tmpStack.empty()) {
      ret.add(tmpStack.pop());
    }

    return ret;
  }
Example #3
0
  /**
   * Run Method which simulates the number of threads running on the bridge
   *
   * @param None
   * @return None
   */
  public void run() {
    while (true) {
      Truck theTruck; // Stores the Truck Object

      // synchronized on truck queue before removing the truck objects
      synchronized (theTruckQueue) {
        // If there are no Trucks then wait for trucks to arrive
        while (theTruckQueue.isEmpty()) {
          try {
            theTruckQueue.wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        theTruck = theTruckQueue.remove();
      }
      // Check for the maximum trucks allowed on the bridge and max weight
      // allowed on the bridge
      // Do not allow any more trucks if we exceed any of the limit
      while (theBridgeQueue.size() == MAX_SIZE
          || (theTruck.getWeight() + getTotalWeight()) >= MAX_WEIGHT) {
        System.out.println("Total number of trucks on Bridge: " + theBridgeQueue.size());
        System.out.println("Total Weight on Bridge is: " + getTotalWeight());
        Truck truckOnBridge = theBridgeQueue.remove();
        System.out.println("The truck Entered " + truckOnBridge.getSide() + " of the Bridge left");
      }

      // Allow the trucks on the bridge on first come first serve basis
      System.out.println("Truck " + theTruck.getSide() + " is Entering the Bridge");
      theBridgeQueue.add(theTruck);
      System.out.println("Truck " + theTruck.getSide() + " is running on the Bridge");
    }
  }
  protected static <T> void parseEDISegmentOrSegmentGroup(
      EDIMessage ediMessage,
      T object,
      Iterator<Field> fieldIterator,
      Queue<String> lookAhead,
      SegmentIterator segmentIterator)
      throws EDIMessageException, IllegalAccessException, InvocationTargetException,
          InstantiationException, ClassNotFoundException, ConversionException {
    if (!fieldIterator.hasNext()) {
      throw new EDIMessageException("No more fields to read.");
    }

    if (!segmentIterator.hasNext() && lookAhead.size() == 0) {
      return;
    }

    // get the queued object first...
    String line = lookAhead.size() > 0 ? lookAhead.remove() : segmentIterator.next();

    // match up the field with the line...
    FieldMatch fm = advanceToMatch(ediMessage, fieldIterator, line);

    //

    if (fm != null) {
      Class<?> fieldType = getEDISegmentOrGroupType(fm.getField());
      if (fieldType.isAnnotationPresent(EDISegment.class)) {
        processSegment(ediMessage, object, lookAhead, segmentIterator, fm);
      } else if (fieldType.isAnnotationPresent(EDISegmentGroup.class)) {
        processSegmentGroup(ediMessage, object, lookAhead, segmentIterator, fm);
      }
    } else {
      lookAhead.add(line);
    }
  }
 /**
  * "Push" new content to consumers: publish to this input stream readers new content to be read
  * from <code>inputStream</code> parameter. This
  *
  * @param inputStream New content for producers
  * @throws IOException If this input stream was closed.
  * @throws IllegalArgumentException If <code>inputStream</code> is <code>null</code>.
  * @see #close()
  */
 public void push(InputStream inputStream) throws IOException {
   if (inputStream == null) {
     throw new IllegalArgumentException("Input stream can not be null.");
   }
   if (isClosed) {
     throw new IOException("Stream is closed");
   }
   while (!inputStreamBuffer.offer(inputStream)) {
     debug("[P] Waiting for a read to complete (" + inputStreamBuffer.size() + ")");
     synchronized (consumerMonitor) {
       consumerMonitor.notifyAll();
     }
     if (!inputStreamBuffer.offer(inputStream)) {
       synchronized (producerMonitor) {
         try {
           producerMonitor.wait();
         } catch (InterruptedException e) {
           throw new RuntimeException(e);
         }
       }
     }
     debug("[P] End of wait");
   }
   debug("[P] Added a new input stream (buffer now has " + inputStreamBuffer.size() + " streams)");
 }
 public void run() {
   while (isConnected()) {
     /*try {
     	Thread.sleep(500);
     } catch (InterruptedException e1) {
     	// TODO Auto-generated catch block
     	e1.printStackTrace();
     }*/
     // take out a message from Queue and send it
     try {
       if (messageQueue.size() > 0) {
         Log.debug("Number of messages in Queue = " + messageQueue.size());
       }
       OpenIGTMessage msg = messageQueue.poll();
       if (msg != null) {
         sendMessage(msg);
       } else if (curPos != null) {
         sendMessage(curPos);
         curPos = null;
       }
     } catch (Exception e) {
       if (!messageQueue.isEmpty()) {
         messageQueue
             .clear(); // clear message queue if ws not able to send as that is a connection
                       // problem
         Log.debug(
             "Clearing Message Sender Queue ; Number of messages in Queue = "
                 + messageQueue.size());
       }
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
   Log.debug("Stopped IGTLink client Sender");
 }
  private void createTaxis(int starthr, int endhr) {
    System.out.println(this.taxisOverTime);
    vqueue = new LinkedList<VData>();
    vdata = new ArrayList<VData>();
    for (int i = starthr; i <= endhr; i++) {
      List<TaxiDemandPerLor> demandPerLor;
      DemandPerLorParser dpl = new DemandPerLorParser();
      Integer day = (i / 24) + 15;
      Integer hr = i % 24;
      String hrstring = String.format("%02d", hr);

      String filename =
          DATADIR + "OD/demandperLorHr/OD_201304" + day.toString() + hrstring + "_OD.csv";
      BerlinVehicleGenerator.read(filename, dpl);
      demandPerLor = dpl.getDemand();

      int currentVeh = this.taxisOverTime.get(i);
      if (i == starthr) addStartVehicles(currentVeh, demandPerLor, hr);
      else {
        int lastVeh = this.taxisOverTime.get(i - 1);
        if (currentVeh > lastVeh) {
          addTaxis(currentVeh - lastVeh, demandPerLor, hr);
          System.out.println(currentVeh + ":" + lastVeh + " a:  " + vqueue.size());

        } else if (currentVeh < lastVeh) {
          if (!(hr > 24)) removeTaxis(lastVeh - currentVeh, hr);
          System.out.println(currentVeh + ":" + lastVeh + " r:  " + vqueue.size());
        }
      }
    }

    removeTaxis(vqueue.size(), endhr % 24 + 1);
  }
  public int compute(int cycles) throws HandlerException {
    System.out.println(
        "dbpedia spreader: "
            + cycles
            + " cycles over "
            + seeds.length
            + " seeds: "
            + seeds[0]
            + "...");
    for (int i = 0; i < cycles; i++) {
      if (0 == curGen.size()) {
        if (0 == nextGen.size()) {
          return 0;
        } else {
          System.out.println("weight " + weight + " --> " + weight * DECAY);
          weight *= DECAY;
          Queue<Resource> tmp = curGen;
          curGen = nextGen;
          nextGen = tmp;
        }
      } else {
        Resource r = curGen.remove();

        stepRelated(sailConnection, r, weight, vector, nextGen);
      }
    }

    return cycles;
  }
 @Override
 public synchronized int read(byte[] b, int off, int len) throws IOException {
   if (len == 0) {
     return 0;
   }
   try {
     while (state_ == State.OPEN && queue_.isEmpty()) {
       wait();
     }
     if (state_ == State.KILLED) {
       throw new IOException("Stream has been closed");
     }
     if (state_ == State.CLOSED && queue_.isEmpty()) {
       return -1;
     }
     if (len > queue_.size()) {
       len = queue_.size();
     }
     for (int i = 0; i < len; ++i) {
       b[off++] = queue_.remove();
     }
     return len;
   } catch (InterruptedException e) {
     throw new IOException("Interrupted");
   }
 }
  // Returns a code tree that is optimal for these frequencies. Always contains at least 2 symbols,
  // to avoid degenerate trees.
  public CodeTree buildCodeTree() {
    // Note that if two nodes have the same frequency, then the tie is broken by which tree contains
    // the lowest symbol. Thus the algorithm is not dependent on how the queue breaks ties.
    Queue<NodeWithFrequency> pqueue = new PriorityQueue<NodeWithFrequency>();

    // Add leaves for symbols with non-zero frequency
    for (int i = 0; i < frequencies.length; i++) {
      if (frequencies[i] > 0) pqueue.add(new NodeWithFrequency(new Leaf(i), i, frequencies[i]));
    }

    // Pad with zero-frequency symbols until queue has at least 2 items
    for (int i = 0; i < frequencies.length && pqueue.size() < 2; i++) {
      if (i >= frequencies.length || frequencies[i] == 0)
        pqueue.add(new NodeWithFrequency(new Leaf(i), i, 0));
    }
    if (pqueue.size() < 2) throw new AssertionError();

    // Repeatedly tie together two nodes with the lowest frequency
    while (pqueue.size() > 1) {
      NodeWithFrequency nf1 = pqueue.remove();
      NodeWithFrequency nf2 = pqueue.remove();
      pqueue.add(
          new NodeWithFrequency(
              new InternalNode(nf1.node, nf2.node),
              Math.min(nf1.lowestSymbol, nf2.lowestSymbol),
              nf1.frequency + nf2.frequency));
    }

    // Return the remaining node
    return new CodeTree((InternalNode) pqueue.remove().node, frequencies.length);
  }
Example #11
0
 private void adjustClientCount() {
   if (m_syncRequestClientCount < m_syncRequestClients.size()) {
     reduceClients(m_syncRequestClientCount);
   } else if (m_syncRequestClientCount > m_syncRequestClients.size()) {
     increaseClients(m_syncRequestClientCount);
   }
 }
  private void rightSideViewHelper(List<Integer> result, Queue<TreeNode> currLevel) {
    if (null == currLevel || currLevel.size() == 0) {
      return;
    }

    Queue<TreeNode> nextLevel = new LinkedList<>();

    while (currLevel.size() != 1) {
      TreeNode node = currLevel.poll();
      if (node.left != null) {
        nextLevel.add(node.left);
      }
      if (node.right != null) {
        nextLevel.add(node.right);
      }
    }

    TreeNode last = currLevel.poll();
    result.add(last.val);
    if (last.left != null) {
      nextLevel.add(last.left);
    }
    if (last.right != null) {
      nextLevel.add(last.right);
    }

    rightSideViewHelper(result, nextLevel);
  }
  protected void sendStreamOfCommands(int[] sequenceNumbers, boolean expected, int expectedCount) {
    for (int i = 0; i < sequenceNumbers.length; i++) {
      int commandId = sequenceNumbers[i];

      ConsumerInfo info = new ConsumerInfo();
      info.setSelector("Cheese: " + commandId);
      info.setCommandId(commandId);

      transport.onCommand(info);
    }

    Queue<Object> exceptions = listener.getExceptions();
    Queue<Object> commands = listener.getCommands();
    if (expected) {
      if (!exceptions.isEmpty()) {
        Exception e = (Exception) exceptions.remove();
        e.printStackTrace();
        fail("Caught exception: " + e);
      }
      assertEquals("number of messages received", expectedCount, commands.size());

      assertEquals("Should have no buffered commands", 0, transport.getBufferedCommandCount());
    } else {
      assertTrue("Should have received an exception!", exceptions.size() > 0);
      Exception e = (Exception) exceptions.remove();
      LOG.info("Caught expected response: " + e);
    }
  }
 /**
  * Close this stream and perform some checks:
  *
  * <ul>
  *   <li>Mark this stream as closed (no more calls to {@link #push(java.io.InputStream)} are
  *       allowed)
  *   <li>Closes any remaining stream pushed to this stream
  * </ul>
  *
  * <p>Calling this method wakes up any thread blocked on {@link #read()}
  *
  * <p>Wait till all streams pushed to this stream (and stored in <code>inputStreamBuffer</code>)
  * are processed by a reader.
  *
  * <p>When this method exits, the buffer is empty and the last stream in buffer is fully read
  * (i.e. until read() returns -1).
  *
  * <p><b>Note:</b> if {@link #setConsumerThread(Thread)} was previously called, this method will
  * wait for the death of consumer before returning.
  *
  * @throws IOException In case at least one stream in buffer hasn't been read.
  * @see java.io.InputStream#close()
  */
 @Override
 public void close() throws IOException {
   super.close();
   isClosed = true;
   warmUpStrategy = NoWarmUpStrategy.INSTANCE; // In case close() is called before end of warm up.
   synchronized (consumerMonitor) {
     consumerMonitor.notifyAll();
   }
   debug("[P] Input stream buffer size: " + inputStreamBuffer.size());
   debug("[P] Has finished read: " + consumeStrategy.isConsumed());
   while (!inputStreamBuffer.isEmpty() || !consumeStrategy.isConsumed()) {
     try {
       debug(
           "[P] Waiting for exhaust... ("
               + inputStreamBuffer.size()
               + " buffer(s) remaining / consumer finished: "
               + consumeStrategy.isConsumed()
               + ")");
       synchronized (exhaustLock) {
         exhaustLock.wait(200);
       }
       // In case we got woken up due to a failure
       throwLastFailure();
       debug("[P] Waiting for exhaust done.");
     } catch (InterruptedException e) {
       throw new RuntimeException(e);
     }
   }
   // In case failure happened on very last read.
   throwLastFailure();
   debug("[P] Close completed.");
 }
Example #15
0
  /**
   * put the flip lake tile of the game
   *
   * @param players list of players
   */
  private void setUpLakeTile(Queue<Player> players) {
    Random r = new Random();
    int randomRedLantern = r.nextInt(players.size());
    Queue<Color> color = startLakeTile.getColorOfFourSides();
    // change the current player who get red lantern card
    color.add(color.remove());
    for (int i = 0; i < randomRedLantern; i++) {
      players.add(players.remove());
    }
    int current_number_player = 0;
    // add index to player
    for (int i = 0; i < players.size(); i++) {
      Player p = players.remove();
      p.setIndex(i);
      players.add(p);
    }

    for (Color lantern_color : color) {
      if (current_number_player == players.size()) {
        break;
      } else {
        current_number_player++;
      }
      Player p = players.remove();

      p.getLanternCards().add(supply.get(lantern_color).pop());
      players.add(p);
    }
  }
  public void addPlaneFromBoard(AirplaneSprite plane) {
    if (hangerPlanes.size() == 4) {
      throw new IllegalStateException("Hanger Render Manager to full to add a plane to the runway");
    }

    plane.moveToPoint(spawnPoints.get(hangerPlanes.size()));
    hangerPlanes.add(plane);
  }
  public void addPlane(AirplaneSprite plane) {
    if (hangerPlanes.size() == 4) {
      throw new IllegalStateException("Hanger Render Manager to full to add a plane to the runway");
    }

    ImmutablePoint2 position = spawnPoints.get(hangerPlanes.size());
    plane.moveToPoint(position);
    hangerPlanes.add(plane);
  }
Example #18
0
 /**
  * Constructor of play area get all stuff of starting play area depend on number of players
  *
  * @param players list of players
  */
 public PlayArea(Queue<Player> players) {
   numberOfFavorTokens = 20;
   supply = new Supply(players.size());
   lakeTilesOnBoard = new LakeTile[65][65];
   initializeLakeTiles(players.size());
   lakeTilesOnBoard[32][32] = startLakeTile;
   initializeDedicationTokens(players.size());
   setUpLakeTile(players);
 }
Example #19
0
 public void expectNoMoreEvents() {
   int before = events.size();
   try {
     Thread.sleep(1);
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
   }
   int after = events.size();
   assertThat("expected no more events, but still got some more: " + events, after, is(before));
 }
Example #20
0
  public double next(int val) {

    if (q.size() == this.max) {
      total -= q.poll();
    }

    q.offer(val);
    total += val;

    return (double) total / q.size();
  }
Example #21
0
  public boolean hasNext()
      throws NoRecordsMatchException, BadResumptionTokenException, CannotDisseminateFormatException,
          NoSetHierarchyException, InternalHarvestException {
    if (_queue == null
        || (_queue.size() == 0 && resumption != null && !resumption.trim().equals(""))) {
      if (_queue == null) _queue = new LinkedList<Identifier>();
      this.harvest();
    }

    return (_queue.size() > 0);
  }
Example #22
0
  @Override
  public void sample() throws RDFHandlerException {
    getStartNodes();

    Utility.logInfo(queue.size());

    int u, v, pick, index;
    int individualLimit = statementLimit / queue.size(), currentLimit = 0;
    RDFEdge edge;
    List<RDFEdge> edges;
    Stack<Integer> stack = new Stack<Integer>();
    while (true) {
      if (noOfStatements >= statementLimit) {
        System.out.println("The number of statements in the sampling: " + noOfStatements);
        return;
      }
      if (noOfStatements >= currentLimit) {
        stack.clear();
      }

      if (stack.isEmpty()) {
        if (queue.isEmpty()) v = rand.nextInt(m_graph.numberOfIndividuals);
        else {
          v = queue.poll();
          currentLimit += individualLimit;
        }
        stack.add(v);
        //				Utility.logInfo(noOfStart + " new start: " + m_graph.getRawString(v));
        visit(v);
      }
      u = stack.peek();
      if (rand.nextInt(100) < 15) {
        stack.pop();
        continue;
      }
      if ((edges = m_graph.edges.get(u)) == null || edges.size() == 0) {
        stack.clear();
        continue;
      }

      index = 0;
      pick = rand.nextInt(edges.size());
      for (Iterator<RDFEdge> iter = edges.iterator(); iter.hasNext(); ++index) {
        edge = iter.next();
        if (index == pick) {
          stack.add(v = edge.m_dst);
          visit(v);
          m_writer.handleStatement(m_graph.getStatement(u, edge.m_label, edge.m_dst));
          ++noOfStatements;
          iter.remove();
        }
      }
    }
  }
  public static void assertEqual(Queue<NdPoint> expected, Queue<NdPoint> actual) {
    String error = String.format("expected: %s but was: %s", expected, actual);
    assertEquals(error, expected.size(), actual.size());

    Iterator<NdPoint> iexpect = expected.iterator();
    Iterator<NdPoint> iactual = actual.iterator();
    while (iexpect.hasNext()) {
      NdPoint e = iexpect.next();
      NdPoint a = iactual.next();
      assertTrue(error, e.equals(a));
    }
  }
Example #24
0
 public String toString() {
   return String.format(
       "%s [%d/%d@%d,%d/%d@%d,%d/%d@-]",
       getClass().getSimpleName(),
       _headers.size(),
       _maxSize,
       _headerSize,
       _buffers.size(),
       _maxSize,
       _bufferSize,
       _others.size(),
       _maxSize);
 }
Example #25
0
  public void runEnqueuedTasks() {
    // run reasoner if it is not yet running
    if (isReasoningEnabled() && !running) {

      // ensure that only one reasoner is started at the same time
      reasonerLock.lock();

      try {
        running = true;

        // run reasoner as long as there are tasks in the queue; if new tasks are added
        // while the reasoner is still running, they are executed in subsequent iterations
        // of the loop
        while (!taskQueue.isEmpty() && isReasoningEnabled()) {
          SystemStatus status =
              new SystemStatus(
                  "Reasoner ("
                      + taskQueue.size()
                      + (taskQueue.size() > 1 ? " tasks remaining)" : " task remaining)"));
          status.setId("reasonerStatus");
          statusService.addSystemStatus(status);

          currentTask = taskQueue.poll();

          if (currentTask == null) {
            log.error("task is null!");
          }

          try {
            processTask(currentTask);
          } catch (SecurityException e) {
            log.error("error while committing transaction (security exception)", e);
          } catch (IllegalStateException e) {
            log.error("error while committing transaction (illegal state)", e);
          } finally {
            statusService.removeSystemStatus(status);
          }
        }
      } finally {

        // release lock
        running = false;
        reasonerLock.unlock();
      }
    } else if (!isReasoningEnabled()) {
      log.info(
          "online reasoning disabled; just enqueuing reasoning task without starting reasoner");
    } else if (running) {
      log.info("reasoner already running; just enqueuing reasoning task");
    }
  }
Example #26
0
 public void fillQueue() {
   while (images.size() < this.minSize && paths.size() > 0) {
     String path = paths.poll();
     if (path != null) {
       try {
         Image img = ImageIO.read(new File(path));
         images.add(img);
         System.out.println("Caching " + path);
       } catch (IOException ioe) {
         // TODO: handle exception
       }
     }
   }
 }
 // Removes the element on top of the stack.
 public void pop() {
   if (q1.isEmpty()) {
     while (q2.size() > 1) {
       q1.offer(q2.poll());
     }
     q2.poll();
     return;
   }
   if (q2.isEmpty()) {
     while (q1.size() > 1) {
       q2.offer(q1.poll());
     }
     q1.poll();
   }
 }
Example #28
0
  public void restore_from_save(Queue<cell_w_coor> Q_for_pack, Vector<Coor> Q_of_cell) {

    this.Q_of_cell = Q_of_cell;
    System.out.println(Q_for_pack.size());
    // Resotre all live cell into grid
    while (Q_for_pack.size() != 0) {

      cell_w_coor temp = Q_for_pack.poll();
      cells[temp.z][temp.x][temp.y] = temp.cell;
      //	  System.out.println(temp.z + " " + temp.x + " " + temp.y);

    }
    // Refresh screen
    this.repaint();
  }
 public Object evaluate(EditorAdaptor vim, Queue<String> command) {
   String next = command.poll();
   int index = next.indexOf('=');
   if (index < 0) {
     noSuchOptionMessage(vim, next);
     return null;
   }
   String optName = next.substring(0, index).trim();
   String value = next.substring(index + 1);
   if (command.size() > 0) {
     // restore preceding space and spaces between tokens
     value += " " + StringUtils.join(" ", command);
   }
   Option<String> strOpt;
   Option<Integer> intOpt;
   try {
     if ((strOpt = find(Options.STRING_OPTIONS, optName)) != null) set(vim, strOpt, value);
     else if ((intOpt = find(Options.INT_OPTIONS, optName)) != null)
       set(vim, intOpt, Integer.valueOf(value));
     else noSuchOptionMessage(vim, optName);
   } catch (ValueException e) {
     invalidValueMessage(vim, value);
   } catch (NumberFormatException e) {
     invalidValueMessage(vim, value);
   }
   return null;
 }
 /**
  * Adds a ServiceRequest to the collection, and calls notifies a single waiting thread.
  *
  * @param item
  * @return
  */
 public boolean enqueue(ServiceRequest item) {
   synchronized (this) {
     System.out.println(Thread.currentThread().getName() + " adding: " + item);
     while (queue.size() == upperBound) {
       try {
         System.out.println(
             Thread.currentThread().getName() + " found queue size: " + queue.size());
         wait();
       } catch (InterruptedException e) {
       }
     }
     queue.add(item);
     notifyAll();
     return true;
   }
 }