Example #1
0
 /** subSet returns set with keys in requested range */
 public void testDescendingSubSetContents() {
   NavigableSet set = dset5();
   SortedSet sm = set.subSet(m2, m4);
   assertEquals(m2, sm.first());
   assertEquals(m3, sm.last());
   assertEquals(2, sm.size());
   assertFalse(sm.contains(m1));
   assertTrue(sm.contains(m2));
   assertTrue(sm.contains(m3));
   assertFalse(sm.contains(m4));
   assertFalse(sm.contains(m5));
   Iterator i = sm.iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(m2, k);
   k = (Integer) (i.next());
   assertEquals(m3, k);
   assertFalse(i.hasNext());
   Iterator j = sm.iterator();
   j.next();
   j.remove();
   assertFalse(set.contains(m2));
   assertEquals(4, set.size());
   assertEquals(1, sm.size());
   assertEquals(m3, sm.first());
   assertEquals(m3, sm.last());
   assertTrue(sm.remove(m3));
   assertTrue(sm.isEmpty());
   assertEquals(3, set.size());
 }
  @Override
  public void calculateMetricValue(Entity entity) {

    SortedSet<Version> versions = entity.getVersions();

    Version previousVersion = null;
    Double firstVersionMetricValue = null;

    if (!versions.isEmpty()) {
      previousVersion = versions.first();
      firstVersionMetricValue = entity.getMetricValue(versions.first(), conventionalMetric);
    }

    onNewEntity(entity);

    for (Version version : versions) {
      Double previousMetricValue = entity.getMetricValue(previousVersion, conventionalMetric);
      Double currentMetricValue = entity.getMetricValue(version, conventionalMetric);

      Double value =
          calculateMetricValueForOneVersion(
              firstVersionMetricValue, previousMetricValue, currentMetricValue);

      entity.addMetricValue(version, this, value);

      previousVersion = version;
    }
  }
Example #3
0
 /** subSet returns set with keys in requested range */
 public void testSubSetContents() {
   NavigableSet set = set5();
   SortedSet sm = set.subSet(two, four);
   assertEquals(two, sm.first());
   assertEquals(three, sm.last());
   assertEquals(2, sm.size());
   assertFalse(sm.contains(one));
   assertTrue(sm.contains(two));
   assertTrue(sm.contains(three));
   assertFalse(sm.contains(four));
   assertFalse(sm.contains(five));
   Iterator i = sm.iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(two, k);
   k = (Integer) (i.next());
   assertEquals(three, k);
   assertFalse(i.hasNext());
   Iterator j = sm.iterator();
   j.next();
   j.remove();
   assertFalse(set.contains(two));
   assertEquals(4, set.size());
   assertEquals(1, sm.size());
   assertEquals(three, sm.first());
   assertEquals(three, sm.last());
   assertTrue(sm.remove(three));
   assertTrue(sm.isEmpty());
   assertEquals(3, set.size());
 }
  /**
   * Test if the notification was to early. Minimum delay is the sum of minimal timeouts (30000)
   * plus the delay for timeout notification (5000). The maximum delay is the sum of maximum
   * timeouts (45000) plus the delay for timeout notification (5000) plus a tolerance of 2000.
   */
  @Test
  public void testClientReceivesTimeoutNotification() {
    assertFalse(
        "Client did not receive a timeout notification at all.",
        responseProcessor.getTransmissionTimeouts().isEmpty());

    long minDelay = 247000;

    SortedSet<Long> transmissionTimes =
        (SortedSet<Long>) responseProcessor.getTransmissions().keySet();

    long firstTransmissionTime = transmissionTimes.first();

    SortedSet<Long> transmissionTimeoutTimes =
        (SortedSet<Long>) responseProcessor.getTransmissionTimeouts().keySet();

    long transmissionTimeoutTime = transmissionTimeoutTimes.first();

    long actualDelay = transmissionTimeoutTime - firstTransmissionTime;

    String format =
        "Internal transmission timeout notification (expected minimum delay: %d millis, actual: %d"
            + "millis)";

    log.info(String.format(format, minDelay, actualDelay));

    assertTrue(
        "Internal transmission timeout notification was too early!", minDelay <= actualDelay);
  }
Example #5
0
  public static void outputResult(Stock[] stocks, Exchange exchange) {

    for (Stock stock : stocks) {
      SortedSet<Bid> buyBidsList = exchange.getBuyBidsList(stock);
      System.out.println(
          " buy "
              + stock
              + "  "
              + buyBidsList.size()
              + "  at "
              + buyBidsList.last().getPrice()
              + " "
              + buyBidsList.first().getPrice());
      SortedSet<Bid> sellBidsList = exchange.getSellBidsList(stock);
      System.out.println(
          " sell "
              + stock
              + "  "
              + sellBidsList.size()
              + "  at "
              + sellBidsList.first().getPrice()
              + " "
              + sellBidsList.last().getPrice());
    }
  }
Example #6
0
 private void dispatchForExecution(Schedule schedule) {
   long now = System.currentTimeMillis();
   synchronized (timingQueue) {
     if (timingQueue.size() == 0) {
       long nextRun = schedule.nextRun(now);
       if (nextRun < 0) {
         return;
       }
       System.out.println("Next run at: " + new DateTime(nextRun));
       timingQueue.add(new ScheduleTime(schedule.identity().get(), nextRun));
       if (scheduleHandler == null) {
         dispatchHandler();
       }
     } else {
       ScheduleTime first = timingQueue.first();
       long nextRun = schedule.nextRun(now);
       if (nextRun < 0) {
         return;
       }
       System.out.println("Next run at: " + new DateTime(nextRun));
       timingQueue.add(new ScheduleTime(schedule.identity().get(), nextRun));
       ScheduleTime newFirst = timingQueue.first();
       if (!first.equals(newFirst)) {
         // We need to restart the managementThread, which is currently waiting for a 'later' event
         // to
         // occur than the one that was just scheduled.
         scheduleHandler.future.cancel(true);
         dispatchHandler();
       }
     }
   }
 }
  private static void applyTiePointGeoCoding(
      TiffFileInfo info, double[] tiePoints, Product product) {
    final SortedSet<Double> xSet = new TreeSet<>();
    final SortedSet<Double> ySet = new TreeSet<>();
    for (int i = 0; i < tiePoints.length; i += 6) {
      xSet.add(tiePoints[i]);
      ySet.add(tiePoints[i + 1]);
    }
    final double xMin = xSet.first();
    final double xMax = xSet.last();
    final double xDiff = (xMax - xMin) / (xSet.size() - 1);
    final double yMin = ySet.first();
    final double yMax = ySet.last();
    final double yDiff = (yMax - yMin) / (ySet.size() - 1);

    final int width = xSet.size();
    final int height = ySet.size();

    int idx = 0;
    final Map<Double, Integer> xIdx = new HashMap<>();
    for (Double val : xSet) {
      xIdx.put(val, idx);
      idx++;
    }
    idx = 0;
    final Map<Double, Integer> yIdx = new HashMap<>();
    for (Double val : ySet) {
      yIdx.put(val, idx);
      idx++;
    }

    final float[] lats = new float[width * height];
    final float[] lons = new float[width * height];

    for (int i = 0; i < tiePoints.length; i += 6) {
      final int idxX = xIdx.get(tiePoints[i + 0]);
      final int idxY = yIdx.get(tiePoints[i + 1]);
      final int arrayIdx = idxY * width + idxX;
      lons[arrayIdx] = (float) tiePoints[i + 3];
      lats[arrayIdx] = (float) tiePoints[i + 4];
    }

    String[] names = Utils.findSuitableLatLonNames(product);
    final TiePointGrid latGrid =
        new TiePointGrid(names[0], width, height, xMin, yMin, xDiff, yDiff, lats);
    final TiePointGrid lonGrid =
        new TiePointGrid(names[1], width, height, xMin, yMin, xDiff, yDiff, lons);

    product.addTiePointGrid(latGrid);
    product.addTiePointGrid(lonGrid);
    final SortedMap<Integer, GeoKeyEntry> geoKeyEntries = info.getGeoKeyEntries();
    final Datum datum = getDatum(geoKeyEntries);
    product.setGeoCoding(new TiePointGeoCoding(latGrid, lonGrid, datum));
  }
Example #8
0
  @Override
  public void update(Observable o, Object arg) {
    SortedSet<Feature> fs = model.selectionModel().getFeatureSelection();

    if (fs.size() == 1) {

      if (fs.first().type() == listModel.getType()) {
        int row = listModel.getRow(fs.first());
        // getSelectionModel().setSelectionInterval(row, row);
        if (!(getParent() instanceof JViewport)) {
          return;
        }
        JViewport viewport = (JViewport) getParent();

        // This rectangle is relative to the table where the
        // northwest corner of cell (0,0) is always (0,0).
        Rectangle rect = getCellRect(row, 0, true);

        // The location of the view relative to the table
        Rectangle viewRect = viewport.getViewRect();

        int topVisible = viewport.getViewRect().y;
        int bottomVisible = viewport.getViewRect().height + topVisible;

        /* When the cell is visible, don't do anything */
        if (rect.y > topVisible && rect.y + rect.height < bottomVisible) {
          return;
        }
        // Translate the cell location so that it is relative
        // to the view, assuming the northwest corner of the
        // view is (0,0).
        rect.setLocation(rect.x - viewRect.x, rect.y - viewRect.y);

        // Calculate location of rect if it were at the center of view
        int centerX = (viewRect.width - rect.width) / 2;
        int centerY = (viewRect.height - rect.height) / 2;

        // Fake the location of the cell so that scrollRectToVisible
        // will move the cell to the center
        if (rect.x < centerX) {
          centerX = -centerX;
        }
        if (rect.y < centerY) {
          centerY = -centerY;
        }
        rect.translate(centerX, centerY);

        // Scroll the area into view.
        viewport.scrollRectToVisible(rect);
      }
    }
  }
Example #9
0
  private void storeGraph(Graph graph) {
    if (numPatternsToStore < 1) return;

    if (topGraphs.isEmpty() || score > topGraphs.first().getScore()) {
      Graph graphCopy = new EdgeListGraphSingleConnections(graph);

      topGraphs.add(new ScoredGraph(graphCopy, score));

      if (topGraphs.size() > getNumPatternsToStore()) {
        topGraphs.remove(topGraphs.first());
      }
    }
  }
Example #10
0
 @Override
 public String toString() {
   return "Depth{"
       + "symbol="
       + symbol
       + ", bids="
       + bids.first().rate()
       + "..."
       + bids.last().rate()
       + ", asks="
       + asks.first().rate()
       + "..."
       + asks.last().rate()
       + '}';
 }
Example #11
0
 @Override
 protected SortedSet<Integer> create(Integer[] elements) {
   SortedSet<Integer> set = nullCheckedTreeSet(elements);
   int tooLow = (set.isEmpty()) ? 0 : set.first() - 1;
   set.add(tooLow);
   return checkedCreate(set).tailSet(tooLow + 1);
 }
  @Test(enabled = true, dependsOnMethods = "testCompareSizes")
  public void testCreateTwoNodesWithRunScript() throws Exception {
    try {
      client.destroyNodesMatching(withTag(tag));
    } catch (NoSuchElementException e) {

    }
    refreshTemplate();
    try {
      nodes = newTreeSet(client.runNodesWithTag(tag, 2, template));
    } catch (RunNodesException e) {
      nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));
      throw e;
    }
    assertEquals(nodes.size(), 2);
    checkNodes(nodes, tag);
    NodeMetadata node1 = nodes.first();
    NodeMetadata node2 = nodes.last();
    // credentials aren't always the same
    // assertEquals(node1.getCredentials(), node2.getCredentials());

    assertLocationSameOrChild(node1.getLocation(), template.getLocation());
    assertLocationSameOrChild(node2.getLocation(), template.getLocation());
    checkImageIdMatchesTemplate(node1);
    checkImageIdMatchesTemplate(node2);
    checkOsMatchesTemplate(node1);
    checkOsMatchesTemplate(node2);
  }
  public NodeToken backtrack() {
    backtrackLeafArcTokens();

    NodeToken resultToken = null;

    while (!queue.isEmpty()) {
      NodeToken token = queue.first();
      queue.remove(token);
      if (token.getExecutionType().isBacktracked()) {
        continue;
      }

      token.getNode().backtrack(engine, token);

      boolean isDestination = token.equals(destinationToken);

      if (isDestination) {
        resultToken = backtrackCompletedToken(token, ExecutionType.Forward);
      } else {
        NodeToken backtrackToken = backtrackToken(token);

        if (backtrackToken != token) {
          backtrackToken.markBacktracked();
          NodeTokenEvent.fireBacktrackedEvent(engine, backtrackToken);

          backtrackToken.markComplete();
          NodeTokenEvent.fireCompletedEvent(engine, backtrackToken, null);
        }
      }
    }

    reactivateTokenSets();

    return resultToken;
  }
Example #14
0
 @Test
 public void testParsePlayListNumber() throws Exception {
   SortedSet<MatchResult> results =
       parser.parse(LogFileHelper.getValidCsvLogFile("playlistAsNumber.csv"));
   assertEquals(results.size(), 1);
   assertEquals(results.first().getPlayList(), MatchResult.SOLO_RANKED_3V3);
 }
Example #15
0
  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    Date startTime = new Date();
    String fname = "p079_keylog.txt";
    FileReader fr = new FileReader(fname);
    BufferedReader br = new BufferedReader(fr);
    SortedSet<String> slines = new TreeSet<String>();
    String line = "";

    while ((line = br.readLine()) != null) {
      slines.add(line);
    }

    String start = slines.first().split("")[0];

    String ans = "";

    for (String l : slines) {
      // System.out.println(l);
      for (String l2 : slines) {
        if (l2.contains(start) && l2.indexOf(start) > 0) start = l2.split("")[0];
      }
    }
    ans += start;
    // System.out.println(ans);
    for (int i = 0; i < 10; i++) {
      start = (getNext(slines, start));
      if (start == null) break;
      ans += start;
      // System.out.println(ans);
    }
    Date endTime = new Date();
    System.out.println(ans + " in " + (endTime.getTime() - startTime.getTime()) + " ms.");
  }
  public static List<Integer> findMinimumVisits(Interval[] intervals) {
    SortedSet<Interval> left = new TreeSet<>(new LeftComp());
    SortedSet<Interval> right = new TreeSet<>(new RightComp());

    for (Interval interval : intervals) {
      left.add(interval);
      right.add(interval);
    }

    List<Integer> s = new ArrayList<>();
    while (!left.isEmpty() && !right.isEmpty()) {
      int b = right.first().right;
      s.add(b);

      // Removes the intervals which intersect with R.cbegin().
      Iterator<Interval> it = left.iterator();
      while (it.hasNext()) {
        Interval interval = it.next();
        if (interval.left > b) {
          break;
        }

        right.remove(interval);
        it.remove();
      }
    }

    return s;
  }
  /** Test a TreeMultiset with a comparator that can return 0 when comparing unequal values. */
  public void testDegenerateComparator() throws Exception {
    TreeMultiset<String> ms = TreeMultiset.create(DEGENERATE_COMPARATOR);

    ms.add("foo");
    ms.add("a");
    ms.add("bar");
    ms.add("b");
    ms.add("c");

    assertEquals(2, ms.count("bar"));
    assertEquals(3, ms.count("b"));

    Multiset<String> ms2 = TreeMultiset.create(DEGENERATE_COMPARATOR);

    ms2.add("cat", 2);
    ms2.add("x", 3);

    assertEquals(ms, ms2);
    assertEquals(ms2, ms);

    SortedSet<String> elementSet = ms.elementSet();
    assertEquals("a", elementSet.first());
    assertEquals("foo", elementSet.last());
    assertEquals(DEGENERATE_COMPARATOR, elementSet.comparator());
  }
  @Test(enabled = true, dependsOnMethods = "testConcurrentUseOfComputeServiceToCreateNodes")
  public void testCreateTwoNodesWithRunScript() throws Exception {
    try {
      client.destroyNodesMatching(inGroup(group));
    } catch (NoSuchElementException e) {

    }
    refreshTemplate();
    try {
      nodes = newTreeSet(client.createNodesInGroup(group, 2, template));
    } catch (RunNodesException e) {
      nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));
      throw e;
    }

    assertEquals(nodes.size(), 2, "expected two nodes but was " + nodes);
    checkNodes(nodes, group, "bootstrap");
    NodeMetadata node1 = nodes.first();
    NodeMetadata node2 = nodes.last();
    // credentials aren't always the same
    // assertEquals(node1.getCredentials(), node2.getCredentials());

    assertLocationSameOrChild(
        checkNotNull(node1.getLocation(), "location of %s", node1), template.getLocation());
    assertLocationSameOrChild(
        checkNotNull(node2.getLocation(), "location of %s", node2), template.getLocation());
    checkImageIdMatchesTemplate(node1);
    checkImageIdMatchesTemplate(node2);
    checkOsMatchesTemplate(node1);
    checkOsMatchesTemplate(node2);
  }
Example #19
0
 private void dispatchHandler() {
   scheduleHandler = new ScheduleHandler();
   managementExecutor.schedule(
       scheduleHandler,
       timingQueue.first().nextTime - System.currentTimeMillis(),
       TimeUnit.MILLISECONDS);
 }
 /* (non-Javadoc)
  * @see org.semanticweb.HermiT.model.dataranges.CanonicalDataRange#getSmallestAssignment()
  */
 public DataConstant getSmallestAssignment() {
   if (!oneOf.isEmpty()) {
     SortedSet<DataConstant> sortedOneOfs = new TreeSet<DataConstant>(oneOf);
     return sortedOneOfs.first();
   }
   return null;
 }
  @Test
  public void testParseResults() {
    // given
    SortedSet<Update> updates = new TreeSet<Update>();
    updates.add(getUpdate());

    String result =
        "[info] "
            + updates.first().getUniqueIdentifer()
            + ": "
            + EInstallerMessage.INSTALLATION_FINISHED;

    // when
    status = null;
    new InstallersOutputParser().parseInstallersOutput(updates, executionQueueReader(result));

    // then
    assertThat(update).as("parseResults() should change Update's status").isNotNull();
    assertThat(update.getStatus())
        .as("parseResults() should change installed Update's status to INSTALLED")
        .isEqualTo(EUpdateStatus.INSTALLED);
    assertThat(status)
        .as("parseResults() should set Update's status as message")
        .isNotNull()
        .isEqualTo(update.getStatus());
  }
  public ObjectPropertyHierarchy(
      Set<OWLObjectProperty> atomicRoles,
      TreeMap<OWLObjectProperty, SortedSet<OWLObjectProperty>> roleHierarchyUp,
      TreeMap<OWLObjectProperty, SortedSet<OWLObjectProperty>> roleHierarchyDown) {
    super(roleHierarchyUp, roleHierarchyDown);

    // find most general and most special roles
    for (OWLObjectProperty role : atomicRoles) {
      SortedSet<OWLObjectProperty> moreGen = getMoreGeneralRoles(role);
      SortedSet<OWLObjectProperty> moreSpec = getMoreSpecialRoles(role);
      if (moreGen.size() == 0 || (moreGen.size() == 1 && moreGen.first().isTopEntity()))
        mostGeneralRoles.add(role);
      if (moreSpec.size() == 0 || (moreSpec.size() == 1 && moreSpec.first().isBottomEntity()))
        mostSpecialRoles.add(role);
    }
  }
Example #23
0
 @Test
 public void testParse() throws Exception {
   SortedSet<MatchResult> results = parser.parse(LogFileHelper.getValidCsvLogFile("log.csv"));
   assertEquals(results.size(), 2);
   assertEquals(results.first().getSkillMean(), -1f);
   assertEquals(results.first().getSkillSigma(), -1f);
 }
  @Test(enabled = true, dependsOnMethods = "testTemplateMatch")
  public void testCreateTwoNodesWithRunScript() throws Exception {
    try {
      client.destroyNodesMatching(NodePredicates.withTag(tag));
    } catch (HttpResponseException e) {
      // TODO hosting.com throws 400 when we try to delete a vApp
    } catch (NoSuchElementException e) {

    }
    template = buildTemplate(client.templateBuilder());

    template
        .getOptions()
        .installPrivateKey(keyPair.get("private"))
        .authorizePublicKey(keyPair.get("public"))
        .runScript(buildScript(template.getImage().getOsFamily()).getBytes());
    try {
      nodes = Sets.newTreeSet(client.runNodesWithTag(tag, 2, template));
    } catch (RunNodesException e) {
      nodes = Sets.newTreeSet(Iterables.concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));
      throw e;
    }
    assertEquals(nodes.size(), 2);
    checkNodes(nodes, tag);
    NodeMetadata node1 = nodes.first();
    NodeMetadata node2 = nodes.last();
    // credentials aren't always the same
    // assertEquals(node1.getCredentials(), node2.getCredentials());

    assertLocationSameOrChild(node1.getLocation(), template.getLocation());
    assertLocationSameOrChild(node2.getLocation(), template.getLocation());

    assertEquals(node1.getImage(), template.getImage());
    assertEquals(node2.getImage(), template.getImage());
  }
  /**
   * Checks to see if there are any "unseen" messages or delivery reports. Shows the most recent
   * notification if there is one.
   *
   * @param context the context to use
   * @param isNew if notify a new message comes, it should be true, otherwise, false.
   */
  public static void blockingUpdateNewMessageIndicator(
      Context context, boolean isNew, boolean isStatusMessage) {
    SortedSet<MmsSmsNotificationInfo> accumulator =
        new TreeSet<MmsSmsNotificationInfo>(INFO_COMPARATOR);
    MmsSmsDeliveryInfo delivery = null;
    Set<Long> threads = new HashSet<Long>(4);

    int count = 0;
    count +=
        accumulateNotificationInfo(accumulator, getMmsNewMessageNotificationInfo(context, threads));
    count +=
        accumulateNotificationInfo(accumulator, getSmsNewMessageNotificationInfo(context, threads));

    cancelNotification(context, NOTIFICATION_ID);
    if (!accumulator.isEmpty()) {
      if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
        Log.d(TAG, "blockingUpdateNewMessageIndicator: count=" + count + ", isNew=" + isNew);
      }
      accumulator.first().deliver(context, isNew, count, threads.size());
    }

    // And deals with delivery reports (which use Toasts). It's safe to call in a worker
    // thread because the toast will eventually get posted to a handler.
    delivery = getSmsNewDeliveryInfo(context);
    if (delivery != null) {
      delivery.deliver(context, isStatusMessage);
    }
  }
Example #26
0
  /**
   * Given an inverted index finds the smallest window containing all the characters. Order of
   * appearance does not matter.
   *
   * @param invertedIndex - map where each character points to sorted list of its positions in the
   *     string; each character with in the index must appear in the source string at least once
   *     (i.e. must have non-empty list of positions).
   * @return positions of characters that belong to minimum window.
   */
  private static SortedSet<Integer> minWindow(Map<Character, List<Integer>> invertedIndex) {
    SortedMap<Integer, Iterator<Integer>> currentWindow = new TreeMap<Integer, Iterator<Integer>>();
    int entriesProcessed = 0;
    for (List<Integer> list : invertedIndex.values()) {
      Iterator<Integer> iterator = list.iterator();
      currentWindow.put(iterator.next(), iterator);
      entriesProcessed++;
    }
    SortedSet<Integer> minWindow = new TreeSet<Integer>(currentWindow.keySet());
    int minWindowLength = minWindow.last() - minWindow.first();

    Iterator<Integer> iterator = currentWindow.remove(currentWindow.firstKey());
    while (iterator.hasNext()) {
      currentWindow.put(iterator.next(), iterator);
      int currentWindowLength = currentWindow.lastKey() - currentWindow.firstKey();
      if (currentWindowLength < minWindowLength) {
        minWindow = new TreeSet<Integer>(currentWindow.keySet());
        minWindowLength = currentWindowLength;
      }
      iterator = currentWindow.remove(currentWindow.firstKey());
      entriesProcessed++;
    }
    System.out.println("Walked through " + entriesProcessed + " entries in inverted index.");
    return minWindow;
  }
Example #27
0
  private void bes(Graph graph) {
    TetradLogger.getInstance().log("info", "** BACKWARD EQUIVALENCE SEARCH");

    initializeArrowsBackward(graph);

    while (!sortedArrows.isEmpty()) {
      Arrow arrow = sortedArrows.first();
      sortedArrows.remove(arrow);

      Node x = arrow.getX();
      Node y = arrow.getY();

      clearArrow(x, y);

      if (!validDelete(arrow.getHOrT(), arrow.getNaYX(), graph)) {
        continue;
      }

      List<Node> h = arrow.getHOrT();
      double bump = arrow.getBump();

      delete(x, y, h, graph, bump);
      score += bump;
      rebuildPattern(graph);

      storeGraph(graph);

      initializeArrowsBackward(
          graph); // Rebuilds Arrows from scratch each time. Fast enough for backwards.
    }
  }
 /**
  * {@inheritDoc}
  *
  * @see java.util.SortedSet#first()
  */
 public E first() {
   lockRead();
   try {
     return m_set.first();
   } finally {
     unlockRead();
   }
 }
Example #29
0
 private void fillOptimalSolutions() {
   while (optimalSolutions.size() < this.numOptimalSolutions && !this.otherSolutions.isEmpty()) {
     this.solutionStatus = SolutionStatus.OPTIMAL;
     Solution bestFeas = otherSolutions.first();
     otherSolutions.remove(bestFeas);
     optimalSolutions.add(bestFeas);
   }
 }
Example #30
0
  public boolean addAck(int ack) {
    if (ack < 0) throw new IllegalArgumentException("Got negative ack: " + ack);
    if (acks.contains(ack)) return true;
    if (acks.size() >= 255) return false;

    if (acks.size() == 0) {
      length += 3;
    } else if (ack < acks.first()) {
      if ((acks.first() - ack) > 255) return false;
    } else if (ack > acks.last()) {
      if ((ack - acks.last()) > 255) return false;
    }
    acks.add(ack);
    length++;

    return true;
  }