Exemplo n.º 1
0
 final String zzB(String paramString) {
   String[] arrayOfString1 = paramString.split("\n");
   if (arrayOfString1.length == 0) {
     return "";
   }
   zza localzza = new zza();
   PriorityQueue localPriorityQueue = new PriorityQueue(this.zztK, new Comparator() {});
   for (int i = 0; i < arrayOfString1.length; i++) {
     String[] arrayOfString2 = zzbx.zzD(arrayOfString1[i]);
     if (arrayOfString2.length >= this.zztJ) {
       zzbz.zza(arrayOfString2, this.zztK, this.zztJ, localPriorityQueue);
     }
   }
   Iterator localIterator = localPriorityQueue.iterator();
   for (; ; ) {
     if (localIterator.hasNext()) {
       zzbz.zza localzza1 = (zzbz.zza) localIterator.next();
       try {
         localzza.write(this.zztM.zzz(localzza1.zztR));
       } catch (IOException localIOException) {
         zzb.e("Error while writing hash to byteStream", localIOException);
       }
     }
   }
   return localzza.toString();
 }
  public void PQOrdering() {
    PriorityQueue<String> pq = new PriorityQueue<String>();
    pq.add("5");
    pq.add("3");
    pq.add("1");
    pq.add("2");
    pq.add("4");
    pq.add("6");

    System.out.println("Unordered: " + pq); // Unordered: [1, 2, 3, 5, 4, 6]

    Iterator<String> itr = pq.iterator();
    System.out.print("Unordered Itr: ");
    while (itr.hasNext()) {
      System.out.print(itr.next() + ", "); // Unordered Itr: 1, 2, 3, 5, 4, 6,
    }

    System.out.println("");
    System.out.print("Unordered Arrays: ");
    Object[] obj = pq.toArray();
    for (Object o : obj) {
      System.out.print(o + ", "); // Unordered Arrays: 1, 2, 3, 5, 4, 6,
    }

    // To order a PQ
    System.out.print("\nOrdered:");
    while (!pq.isEmpty()) {
      System.out.print(pq.poll() + ", "); // Ordered: 1, 2, 3, 4, 5, 6,
    }
    System.out.println("********************************************");
  }
 /**
  * Transfer all the jobs in the queue of a SchedulingAlgorithm to another, such as when switching
  * to another algorithm in the GUI
  *
  * @param otherAlg The other algorithm to transfer to.
  */
 public void transferJobsTo(SchedulingAlgorithm otherAlg) {
   Iterator<Process> iter = pQ.iterator();
   while (iter.hasNext()) {
     otherAlg.addJob(iter.next());
     iter.remove();
   }
 }
  public String solve() {
    PriorityQueue<Neighbor> copy = new PriorityQueue<Neighbor>(neighbors);

    // Mencari jumlah masing-masing kelas pada priority queue Neighbor
    Iterator<Neighbor> itr = copy.iterator();
    while (itr.hasNext()) {
      Neighbor n = itr.next();

      boolean found = false;
      int j = 0;
      while ((j < classes.size()) && !found) {
        // Jika kelas yang sama sudah ada, maka counter hanya akan bertambah
        if (data.get(n.index).get(data.get(n.index).size() - 1).equals(classes.get(j).classData)) {
          classes.get(j).addCounter();
          found = true;
        } else {
          j++;
        }
      }
      // Jika kelas belum ada pada list, maka kelas akan ditambahkan
      if (!found) {
        DataClass newData = new DataClass(data.get(n.index).get(data.get(n.index).size() - 1));
        classes.add(newData);
      }
    }
    classes.sort(
        new Comparator<DataClass>() {
          @Override
          public int compare(DataClass d1, DataClass d2) {
            return (d1.count <= d2.count ? 1 : -1);
          }
        });

    return classes.get(0).classData;
  }
Exemplo n.º 5
0
  @Override
  public void draw() {
    // Lock the state
    try {
      lock.acquire();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // Only draw if we are playing the replay
    if (playing) {
      background(25);
      // Mark whether or not we draw a frame
      boolean drewframe = false;
      // Loop through all frame
      for (Iterator<UpdatePacket> it = frameQueue.iterator(); it.hasNext(); ) {
        UpdatePacket u = it.next();
        // Only draw if it matches the current time
        if (!(u.timestamp == timeline.getTime())) continue;
        // Draw stuff
        for (int i = 0; i < u.numRects; i++) {
          fill(color(u.rectColors[i][0], u.rectColors[i][1], u.rectColors[i][2]));
          rect(
              (float) u.rectVals[i][0],
              (float) u.rectVals[i][1],
              (float) u.rectVals[i][2],
              (float) u.rectVals[i][3]);
        }
        // Remember this frame
        lastFrame.add(u);
        // Signal a frame was drawn
        drewframe = true;
      }

      // Check of no frame was drawn
      if (!drewframe) {
        // Draw the previous frame
        for (UpdatePacket u : lastFrame) {
          for (int i = 0; i < u.numRects; i++) {
            fill(color(u.rectColors[i][0], u.rectColors[i][1], u.rectColors[i][2]));
            rect(
                (float) u.rectVals[i][0],
                (float) u.rectVals[i][1],
                (float) u.rectVals[i][2],
                (float) u.rectVals[i][3]);
          }
        }
        // Clear the previous frame
        lastFrame.clear();
      }
      // Step the time-line
      timeline.step();
    }
    // Unlock the state
    lock.release();
  }
Exemplo n.º 6
0
  @Override
  protected void map(LongWritable key, Text value, Context context)
      throws IOException, InterruptedException {
    Configuration conf = context.getConfiguration();
    Integer k = Integer.valueOf(conf.get("krecords"));
    // _log.info("Threshold =>" + threshold);
    PriorityQueue<UniformData> sortedQueue =
        new PriorityQueue<UniformData>(k, new UniformDataComparator());

    String[] tokens = value.toString().split(",");
    Long id = Long.valueOf(tokens[2].trim());
    Double score = Double.valueOf(tokens[1]);
    if (_isFirst) {
      UniformData record = new UniformData(id, score);
      sortedQueue.add(record);
      _max = score;
      _counter++;
      _isFirst = false;
    } else {
      if (_counter <= k) {
        score = Utils.calculateScore(tokens);
        if (score > _max) {
          UniformData record = new UniformData(id, score);
          sortedQueue.add(record);
          _max = record.getScore();
          _counter++;
          // _log.info("Worst Threshold =>" + threshold+" for top-k/counter =>"+counter);
        }
      } else {
        List<UniformData> records = new ArrayList<UniformData>(sortedQueue);
        if (records.size() > 0) {
          if (records.get(k - 1).getScore() > _max) {
            UniformData record = new UniformData(id, score);
            sortedQueue.add(record);
            _max = records.get(k - 1).getScore();
            _counter++;
            // _log.info("Worst Threshold =>" + threshold+" for after k+1 =>"+counter);
          }
        }
      }
    }
    Iterator<UniformData> recIter = sortedQueue.iterator();
    Integer kRecords = 0;
    while (recIter.hasNext()) {
      UniformData record = recIter.next();
      DoubleWritable scoreWR = new DoubleWritable(record.getScore());
      context.write(scoreWR, record);
      if (kRecords == k) {
        break;
      }
      kRecords++;
    }
  }
Exemplo n.º 7
0
 /**
  * Removes one instance of the given message from the queue.
  *
  * @return true if removed, false if not. If false is returned, the message may be currently being
  *     dispatched.
  */
 public boolean remove(T message) {
   lock.lock();
   try {
     Iterator<DelayedMessage> iterator = queue.iterator();
     while (iterator.hasNext()) {
       DelayedMessage next = iterator.next();
       if (next.message.equals(message)) {
         iterator.remove();
         return true;
       }
     }
     return false;
   } finally {
     lock.unlock();
   }
 }
Exemplo n.º 8
0
  @Override
  public int advance(int targetDocId) {
    if (currentDocId == Constants.EOF) {
      return Constants.EOF;
    }
    if (targetDocId < minDocId) {
      targetDocId = minDocId;
    } else if (targetDocId > maxDocId) {
      currentDocId = Constants.EOF;
      return currentDocId;
    }
    long start = System.nanoTime();

    // Remove iterators that are before the target document id from the queue
    Iterator<IntPair> iterator = queue.iterator();
    while (iterator.hasNext()) {
      IntPair pair = iterator.next();
      if (pair.getLeft() < targetDocId) {
        iterator.remove();
        iteratorIsInQueue[pair.getRight()] = false;
      }
    }

    // Advance all iterators that are not in the queue to the target document id
    for (int i = 0; i < docIdIterators.length; i++) {
      if (!iteratorIsInQueue[i]) {
        int nextDocId = docIdIterators[i].advance(targetDocId);
        if (nextDocId != Constants.EOF) {
          pointers[i].setLeft(nextDocId);
          queue.add(pointers[i]);
        }
        iteratorIsInQueue[i] = true;
      }
    }

    // Return the first element
    if (queue.size() > 0) {
      currentDocId = queue.peek().getLeft();
    } else {
      currentDocId = Constants.EOF;
    }

    long end = System.nanoTime();
    timeMeasure.addAndGet(end - start);
    return currentDocId;
  }
Exemplo n.º 9
0
  public void printElementsQueue(PriorityQueue<Patient> queueToPrint, String name) {

    Patient patientQueuing = null;
    Iterator<Patient> iter = queueToPrint.iterator();

    String a = "[";
    while (iter.hasNext()) {
      Patient elementInQueue = iter.next();

      if (elementInQueue instanceof Patient) {
        patientQueuing = elementInQueue;
        a = a + patientQueuing.getId() + ", ";
      }
    }
    if (a.length() > 2)
      System.out.println(
          "" + this.getId() + " " + name + ": " + a.substring(0, a.length() - 2) + "]");
  }
Exemplo n.º 10
0
  /** Method to clear the Collection. */
  public synchronized void clear() {
    if (ownerOP != null && !delegate.isEmpty()) {
      // Cascade delete
      if (SCOUtils.hasDependentElement(ownerMmd)) {
        Iterator iter = delegate.iterator();
        while (iter.hasNext()) {
          ownerOP.getExecutionContext().deleteObjectInternal(iter.next());
        }
      }
    }

    delegate.clear();

    makeDirty();
    if (ownerOP != null && !ownerOP.getExecutionContext().getTransaction().isActive()) {
      ownerOP.getExecutionContext().processNontransactionalUpdate();
    }
  }
Exemplo n.º 11
0
Arquivo: Align.java Projeto: nh13/SRMA
  public static void align(
      Graph graph,
      SAMRecord rec,
      Node recNode,
      ReferenceSequence sequence,
      SAMProgramRecord programRecord,
      int offset,
      AlleleCoverageCutoffs alleleCoverageCutoffs,
      boolean correctBases,
      boolean useSequenceQualities,
      int MAXIMUM_TOTAL_COVERAGE,
      int MAX_HEAP_SIZE)
      throws Exception {

    int i;
    AlignHeapNode curAlignHeapNode = null;
    AlignHeapNode nextAlignHeapNode = null;
    AlignHeapNode bestAlignHeapNode = null;
    AlignHeap heap = null;
    String read = null; // could be cs
    String readBases = null; // always nt
    String qualities = null; // could be cq
    SRMAUtil.Space space = SRMAUtil.Space.NTSPACE;
    ListIterator<NodeRecord> iter = null;
    AlignHeapNodeComparator comp = null;
    int alignmentStart = -1;
    int numStartNodesAdded = 0;
    boolean strand = rec.getReadNegativeStrandFlag(); // false -> forward, true -> reverse
    String softClipStartBases = null;
    String softClipStartQualities = null;
    String softClipEndBases = null;
    String softClipEndQualities = null;

    // Debugging stuff
    String readName = rec.getReadName();

    assert SRMAUtil.Space.COLORSPACE != space;

    // Get space
    read = (String) rec.getAttribute("CS");
    if (null == read) {
      // Use base space
      space = SRMAUtil.Space.NTSPACE;
    } else {
      // assumes CS and CQ are always in sequencing order
      space = SRMAUtil.Space.COLORSPACE;
    }

    // Get read and qualities
    if (space == SRMAUtil.Space.NTSPACE) {
      byte tmpRead[] = rec.getReadString().getBytes();
      byte tmpQualities[] = rec.getBaseQualityString().getBytes();
      // Reverse once
      if (strand) { // reverse
        SAMRecordUtil.reverseArray(tmpRead);
        SAMRecordUtil.reverseArray(tmpQualities);
      }
      read = new String(tmpRead);
      readBases = new String(tmpRead);
      qualities = new String(tmpQualities);
      // Reverse again
      if (strand) { // reverse
        SAMRecordUtil.reverseArray(tmpRead);
        SAMRecordUtil.reverseArray(tmpQualities);
      }
    } else {
      byte tmpRead[] = rec.getReadString().getBytes();
      // Reverse once
      if (strand) { // reverse
        SAMRecordUtil.reverseArray(tmpRead);
      }
      readBases = new String(tmpRead);
      // Reverse again
      if (strand) { // reverse
        SAMRecordUtil.reverseArray(tmpRead);
      }
      read = SRMAUtil.normalizeColorSpaceRead(read);
      qualities = (String) rec.getAttribute("CQ");
      // Some aligners include a quality value for the adapter.  A quality value
      // IMHO should not be given for an unobserved (assumed) peice of data.  Trim
      // the first quality in this case
      if (qualities.length() == 1 + read.length()) { // trim the first quality
        qualities = qualities.substring(1);
      }
    }
    // Reverse back
    if (readBases.length() <= 0) {
      throw new Exception("Error.  The current alignment has no bases.");
    }
    if (read.length() <= 0) {
      throw new Exception("Error.  The current alignment has no bases.");
    }
    if (qualities.length() <= 0) {
      throw new Exception("Error.  The current alignment has no qualities.");
    }
    if (readBases.length() != read.length()) {
      if (space == SRMAUtil.Space.COLORSPACE) {
        throw new Exception(
            "Error.  The current alignment's read bases length does not match the length of the colors in the CS tag ["
                + rec.getReadName()
                + "].");
      } else {
        throw new Exception("Error.  Internal error: readBases.length() != read.length()");
      }
    }

    // Deal with soft-clipping
    // - save the soft clipped sequence for latter
    {
      List<CigarElement> cigarElements = null;

      cigarElements = rec.getCigar().getCigarElements();
      CigarElement e1 = cigarElements.get(0); // first
      CigarElement e2 = cigarElements.get(cigarElements.size() - 1); // last

      // Soft-clipped
      if (CigarOperator.S == e1.getOperator()) {
        if (space == SRMAUtil.Space.COLORSPACE) {
          throw new Exception(
              "Error.  Soft clipping with color-space data not currently supported.");
        }
        int l = e1.getLength();
        if (strand) { // reverse
          softClipStartBases = readBases.substring(readBases.length() - l);
          softClipStartQualities = qualities.substring(qualities.length() - l);
          readBases = readBases.substring(0, readBases.length() - l);
          read = read.substring(0, read.length() - l);
          qualities = qualities.substring(0, qualities.length() - l);
        } else {
          softClipStartBases = readBases.substring(0, l - 1);
          softClipStartQualities = qualities.substring(0, l - 1);
          readBases = readBases.substring(l);
          read = read.substring(l);
          qualities = qualities.substring(l);
        }
      }
      if (CigarOperator.S == e2.getOperator()) {
        if (space == SRMAUtil.Space.COLORSPACE) {
          throw new Exception(
              "Error.  Soft clipping with color-space data not currently supported.");
        }
        int l = e2.getLength();
        if (strand) { // reverse
          softClipEndBases = readBases.substring(0, l - 1);
          softClipEndQualities = qualities.substring(0, l - 1);
          readBases = readBases.substring(l);
          read = read.substring(l);
          qualities = qualities.substring(l);
        } else {
          softClipEndBases = readBases.substring(readBases.length() - l);
          softClipEndQualities = qualities.substring(qualities.length() - l);
          readBases = readBases.substring(0, readBases.length() - l);
          read = read.substring(0, read.length() - l);
          qualities = qualities.substring(0, qualities.length() - l);
        }
      }
    }

    // Remove mate pair information
    Align.removeMateInfo(rec);

    comp =
        new AlignHeapNodeComparator(
            (strand) ? AlignHeap.HeapType.MAXHEAP : AlignHeap.HeapType.MINHEAP);

    // Bound by original alignment if possible
    bestAlignHeapNode =
        Align.boundWithOriginalAlignment(
            rec,
            graph,
            recNode,
            comp,
            strand,
            read,
            qualities,
            readBases,
            space,
            sequence,
            alleleCoverageCutoffs,
            useSequenceQualities,
            MAXIMUM_TOTAL_COVERAGE,
            MAX_HEAP_SIZE);

    /*
    System.err.println("readName="+rec.getReadName());
    if(null != bestAlignHeapNode) {
    System.err.println("\nFOUND BEST:" + rec.toString());
    }
    else {
    System.err.println("\nNOT FOUND (BEST): " + rec.toString());
    }
    Align.updateSAM(rec, programRecord, bestAlignHeapNode, space, read, qualities, softClipStartBases, softClipStartQualities, softClipEndBases, softClipEndQualities, strand, correctBases);
    return;
    */

    heap = new AlignHeap((strand) ? AlignHeap.HeapType.MAXHEAP : AlignHeap.HeapType.MINHEAP);

    // Add start nodes
    if (strand) { // reverse
      alignmentStart = rec.getAlignmentEnd();
      for (i = alignmentStart + offset; alignmentStart - offset <= i; i--) {
        int position = graph.getPriorityQueueIndexAtPositionOrBefore(i);
        PriorityQueue<Node> startNodeQueue = graph.getPriorityQueue(position);
        if (0 != position && null != startNodeQueue) {
          Iterator<Node> startNodeQueueIter = startNodeQueue.iterator();
          while (startNodeQueueIter.hasNext()) {
            Node startNode = startNodeQueueIter.next();
            int f = passFilters(graph, startNode, alleleCoverageCutoffs, MAXIMUM_TOTAL_COVERAGE);
            if (0 == f) {
              heap.add(
                  new AlignHeapNode(
                      null,
                      startNode,
                      startNode.coverage,
                      read.charAt(0),
                      qualities.charAt(0),
                      useSequenceQualities,
                      space));
            } else if (f < 0) {
              return;
            }
            if (startNode.position < i) {
              i = startNode.position;
            }
            numStartNodesAdded++;
          }
        }
      }
    } else {
      alignmentStart = rec.getAlignmentStart();
      for (i = alignmentStart - offset; i <= alignmentStart + offset; i++) {
        int position = graph.getPriorityQueueIndexAtPositionOrGreater(i);
        PriorityQueue<Node> startNodeQueue = graph.getPriorityQueue(position);
        if (0 != position && null != startNodeQueue) {
          Iterator<Node> startNodeQueueIter = startNodeQueue.iterator();
          while (startNodeQueueIter.hasNext()) {
            Node startNode = startNodeQueueIter.next();
            int f = passFilters(graph, startNode, alleleCoverageCutoffs, MAXIMUM_TOTAL_COVERAGE);
            if (0 == f) {
              heap.add(
                  new AlignHeapNode(
                      null,
                      startNode,
                      startNode.coverage,
                      read.charAt(0),
                      qualities.charAt(0),
                      useSequenceQualities,
                      space));
            } else if (f < 0) {
              return;
            }
            if (i < startNode.position) {
              i = startNode.position;
            }
            numStartNodesAdded++;
          }
        }
      }
    }
    if (numStartNodesAdded == 0) {
      throw new Exception("Did not add any start nodes!");
    }

    // Get first node off the heap
    curAlignHeapNode = heap.poll();

    while (null != curAlignHeapNode) {

      if (MAX_HEAP_SIZE <= heap.size()) {
        // too many to consider
        return;
      }

      // System.err.println("strand:" + strand + "\tsize:" + heap.size() + "\talignmentStart:" +
      // alignmentStart + "\toffset:" + offset + "\treadOffset:" + curAlignHeapNode.readOffset);
      // System.err.print("size:" + heap.size() + ":" + curAlignHeapNode.readOffset + ":" +
      // curAlignHeapNode.score + ":" + curAlignHeapNode.alleleCoverageSum + ":" +
      // curAlignHeapNode.startPosition + "\t");
      // curAlignHeapNode.node.print(System.err);
      // System.err.print("\rposition:" + curAlignHeapNode.node.position + "\treadOffset:" +
      // curAlignHeapNode.readOffset);

      // Remove all non-insertions with the same contig/pos/read-offset/type/base and lower score
      nextAlignHeapNode = heap.peek();
      while (Node.INSERTION != curAlignHeapNode.node.type
          && null != nextAlignHeapNode
          && 0 == comp.compare(curAlignHeapNode, nextAlignHeapNode)) {
        if (curAlignHeapNode.score < nextAlignHeapNode.score
            || (curAlignHeapNode.score == nextAlignHeapNode.score
                && curAlignHeapNode.alleleCoverageSum < nextAlignHeapNode.alleleCoverageSum)) {
          // Update current node
          curAlignHeapNode = heap.poll();
        } else {
          // Ignore next node
          heap.poll();
        }
        nextAlignHeapNode = heap.peek();
      }
      nextAlignHeapNode = null;

      // Check if the alignment is complete
      if (curAlignHeapNode.readOffset == read.length() - 1) {
        // All read bases examined, store if has the best alignment.

        // System.err.print(curAlignHeapNode.alleleCoverageSum + ":" + curAlignHeapNode.score +
        // ":");
        // System.err.print(curAlignHeapNode.startPosition + ":");
        // curAlignHeapNode.node.print(System.err);

        if (null == bestAlignHeapNode
            || bestAlignHeapNode.score < curAlignHeapNode.score
            || (bestAlignHeapNode.score == curAlignHeapNode.score
                && bestAlignHeapNode.alleleCoverageSum < curAlignHeapNode.alleleCoverageSum)) {
          bestAlignHeapNode = curAlignHeapNode;
        }
      } else if (null != bestAlignHeapNode && curAlignHeapNode.score < bestAlignHeapNode.score) {
        // ignore, under the assumption that scores can only become more negative.
      } else {
        if (strand) { // reverse
          // Go to all the "prev" nodes
          iter = curAlignHeapNode.node.prev.listIterator();
        } else { // forward
          // Go to all "next" nodes
          iter = curAlignHeapNode.node.next.listIterator();
        }
        while (iter.hasNext()) {
          NodeRecord next = iter.next();
          int f =
              passFilters(
                  graph, next.node, next.coverage, alleleCoverageCutoffs, MAXIMUM_TOTAL_COVERAGE);
          if (0 == f) {
            heap.add(
                new AlignHeapNode(
                    curAlignHeapNode,
                    next.node,
                    next.coverage,
                    read.charAt(curAlignHeapNode.readOffset + 1),
                    qualities.charAt(curAlignHeapNode.readOffset + 1),
                    useSequenceQualities,
                    space));
          } else if (f < 0) {
            return;
          }
        }
        iter = null;
      }
      // Get next node
      curAlignHeapNode = heap.poll();
    }

    // Recover alignment
    Align.updateSAM(
        rec,
        sequence,
        programRecord,
        bestAlignHeapNode,
        space,
        read,
        qualities,
        softClipStartBases,
        softClipStartQualities,
        softClipEndBases,
        softClipEndQualities,
        strand,
        correctBases);
  }