Beispiel #1
0
  /**
   * Converts the form field values in the <tt>ffValuesIter</tt> into a caps string.
   *
   * @param ffValuesIter the {@link Iterator} containing the form field values.
   * @param capsBldr a <tt>StringBuilder</tt> to which the caps string representing the form field
   *     values is to be appended
   */
  private static void formFieldValuesToCaps(Iterator<String> ffValuesIter, StringBuilder capsBldr) {
    SortedSet<String> fvs = new TreeSet<String>();

    while (ffValuesIter.hasNext()) fvs.add(ffValuesIter.next());

    for (String fv : fvs) capsBldr.append(fv).append('<');
  }
Beispiel #2
0
 /**
  * Constructs a new instance of {@code TreeSet} containing the elements of the specified SortedSet
  * and using the same Comparator.
  *
  * @param set the SortedSet of elements to add.
  */
 public TreeSet(SortedSet<E> set) {
   this(set.comparator());
   Iterator<E> it = set.iterator();
   while (it.hasNext()) {
     add(it.next());
   }
 }
Beispiel #3
0
  public static void RetrieveTrainMatrix() {
    try {
      BufferedReader flrdr =
          new BufferedReader(
              new FileReader("D:\\IR\\Assignment7\\Pytest\\part2\\output\\train_matrix.txt"));
      String line = "";
      int doc_count = 0;

      while ((line = flrdr.readLine()) != null) {
        SortedSet<Integer> word_ids = new TreeSet<Integer>();
        int val_count = 0;

        String[] key_value = line.split(" :: ");
        key_value[1] = key_value[1].substring(1, key_value[1].length() - 2);
        String[] values = key_value[1].split(",");

        FeatureNode[] node = new FeatureNode[values.length];

        for (String val : values) word_ids.add(Integer.parseInt(val.trim()));

        for (int val : word_ids) node[val_count++] = new FeatureNode(val, 1);

        if (spam_docs.contains(key_value[0].trim())) ylable[doc_count] = 1;
        else ylable[doc_count] = 0;

        train_matrix[doc_count++] = node;
      }
      flrdr.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
  }
 /**
  * Since the segmentations are disjoint, the total set of differentially expressed segments is the
  * union of the sets of differentially expressed segments in each segmentation.
  *
  * @param c1
  * @param c2
  * @return
  */
 public SortedSet<DifferentialKey> differentialRegions(int c1, int c2) {
   SortedSet<DifferentialKey> keys = new TreeSet<DifferentialKey>();
   for (InputSegmentation iseg : segmentations) {
     keys.addAll(differentialRegions(iseg, c1, c2));
   }
   return keys;
 }
  /**
   * O(N) Determine if this set is equal to other. Two sets are equal if they have exactly the same
   * elements. The order of the elements does not matter. <br>
   * pre: none
   *
   * @param other the object to compare to this set
   * @return true if other is a Set and has the same elements as this set
   */
  public boolean equals(Object other) {
    // Calling object cannot be null so if other is null then the two objects
    // cannot be equal
    if (other == null) return false;
    if (!(other instanceof ISet<?>)) return false;
    // At this point we KNOW that other is a non-null ISet object
    ISet<?> otherSet = (ISet<?>) other;

    // we know E is a Comparable, but we don't know if
    // otherSet is a SortedSet.

    // local var of correct type so we only have to cast once
    SortedSet<?> otherSortedSet;

    // do we need to create a new SortedSet based on otherSet or is otherSet
    // really a SortedSet?
    if (!(otherSet instanceof SortedSet<?>)) return super.equals(otherSet);
    else otherSortedSet = (SortedSet<?>) otherSet;

    if (otherSortedSet.size() != this.size()) return false;
    else {
      for (int x = 0; x < this.size(); x++) {
        if (!(this.myCon.get(x).equals(otherSortedSet.myCon.get(x)))) return false;
      }
      return true;
    }
  }
  /** Set the contents of the field selector list. */
  private void setupFieldSelector() {
    fieldListModel.clear();
    SortedSet<String> contents = new TreeSet<String>();
    for (String s : metaData) {
      if (s.startsWith(Globals.SELECTOR_META_PREFIX)) {
        contents.add(s.substring(Globals.SELECTOR_META_PREFIX.length()));
      }
    }
    if (contents.size() == 0) {
      // if nothing was added, put the default fields (as described in the help)
      fieldListModel.addElement("author");
      fieldListModel.addElement("journal");
      fieldListModel.addElement("keywords");
      fieldListModel.addElement("publisher");
    } else {
      for (String s : contents) {
        fieldListModel.addElement(s);
      }
    }

    if (currentField == null) {
      // if dialog is created for the whole database,
      // select the first field to avoid confusions in GUI usage
      fieldList.setSelectedIndex(0);
    } else {
      // a specific field has been chosen at the constructur
      // select this field
      int i = fieldListModel.indexOf(currentField);
      if (i != -1) {
        // field has been found in list, select it
        fieldList.setSelectedIndex(i);
      }
    }
  }
 @SuppressWarnings("EmptyCatchBlock")
 static void ensureNotDirectlyModifiable(SortedSet<Integer> unmod) {
   try {
     unmod.add(4);
     fail("UnsupportedOperationException expected");
   } catch (UnsupportedOperationException expected) {
   }
   try {
     unmod.remove(4);
     fail("UnsupportedOperationException expected");
   } catch (UnsupportedOperationException expected) {
   }
   try {
     unmod.addAll(Collections.singleton(4));
     fail("UnsupportedOperationException expected");
   } catch (UnsupportedOperationException expected) {
   }
   try {
     Iterator<Integer> iterator = unmod.iterator();
     iterator.next();
     iterator.remove();
     fail("UnsupportedOperationException expected");
   } catch (UnsupportedOperationException expected) {
   }
 }
  public List<Locale> getAvailableLanguages() {
    Locale[] locales = Locale.getAvailableLocales();
    Map<String, Locale> localeMap = new HashMap<String, Locale>();

    // remove all variants
    for (Locale locale : locales) {
      if (isTranslationsOnly()
          && !ArrayUtils.contains(config.getAvailableTranslations(), locale.getLanguage())) {
        continue;
      }

      if (localeMap.containsKey(locale.getLanguage())
          && locale.getDisplayName().indexOf('(') != -1) {
        continue;
      }

      localeMap.put(locale.getLanguage(), locale);
    }

    SortedSet<Locale> localeSet =
        new TreeSet<Locale>(new LocaleComparator(LocaleComparator.CompareType.LANGUAGE));

    for (Locale locale : localeMap.values()) {
      localeSet.add(locale);
    }

    return new ArrayList<Locale>(localeSet);
  }
Beispiel #9
0
 /** @tests java.util.TreeSet#add(java.lang.Object) */
 public void test_addLjava_lang_Object() {
   // Test for method boolean java.util.TreeSet.add(java.lang.Object)
   ts.add(new Integer(-8));
   assertTrue("Failed to add Object", ts.contains(new Integer(-8)));
   ts.add(objArray[0]);
   assertTrue("Added existing element", ts.size() == objArray.length + 1);
 }
 /**
  * Gets the unique read groups in the table
  *
  * @param report the GATKReport containing the table with RecalUtils.READGROUP_REPORT_TABLE_TITLE
  * @return the unique read groups
  */
 private static SortedSet<String> getReadGroups(final GATKReport report) {
   final GATKReportTable reportTable = report.getTable(RecalUtils.READGROUP_REPORT_TABLE_TITLE);
   final SortedSet<String> readGroups = new TreeSet<String>();
   for (int i = 0; i < reportTable.getNumRows(); i++)
     readGroups.add(reportTable.get(i, RecalUtils.READGROUP_COLUMN_NAME).toString());
   return readGroups;
 }
Beispiel #11
0
  public String toString() {
    String s = new String();
    SortedSet antecedent = getAntecedent();
    Iterator it2 = antecedent.iterator();
    SortedSet consequence = getConsequence();
    Iterator it3 = consequence.iterator();
    while (it2.hasNext()) {
      String itemCourantant = it2.next().toString();
      s = s + (itemCourantant = itemCourantant + " ");
    }
    String itemCourantcons;
    for (s = s + " --> "; it3.hasNext(); s = s + itemCourantcons + " ")
      itemCourantcons = it3.next().toString();

    s = s + "\t\t";
    s = s + "(S = ";
    String sup = Double.toString((double) (int) (getSupport() * 100D) / 100D);
    s = s + sup;
    s = s + "% ; ";
    s = s + "C = ";
    String c = Double.toString((double) (int) (getConfiance() * 100D) / 100D);
    s = s + c;
    s = s + ")";
    return s;
  }
Beispiel #12
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.
    }
  }
  @Test
  public void testCompareByName() throws Exception {

    final Category cat1 = context.mock(Category.class, "cat1");
    final Category cat2 = context.mock(Category.class, "cat2");

    context.checking(
        new Expectations() {
          {
            allowing(cat1).getRank();
            will(returnValue(0));
            allowing(cat1).getName();
            will(returnValue("name 2"));
            allowing(cat1).getCategoryId();
            will(returnValue(1L));
            allowing(cat2).getRank();
            will(returnValue(0));
            allowing(cat2).getName();
            will(returnValue("name 1"));
          }
        });

    final SortedSet<Category> set = new TreeSet<Category>(new CategoryRankNameComparator());
    set.addAll(Arrays.asList(cat1, cat2));

    final List<Category> list = new ArrayList<Category>(set);
    assertTrue(cat2 == list.get(0));
    assertTrue(cat1 == list.get(1));
  }
Beispiel #14
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.");
  }
Beispiel #15
0
 static SortedSet<TypeColorEntry> fromPainter(myjava.gui.syntax.Painter painter) {
   Token.Type[] types = Token.Type.values();
   SortedSet<TypeColorEntry> entries = new TreeSet<>();
   for (Token.Type type : types) {
     entries.add(new TypeColorEntry(type, painter.fromType(type)));
   }
   return entries;
 }
 public List<File> getAffectedPaths() {
   final SortedSet<FilePath> set = myIdx.getAffectedPaths();
   final List<File> result = new ArrayList<File>(set.size());
   for (FilePath path : set) {
     result.add(path.getIOFile());
   }
   return result;
 }
 @Override
 protected Integer detectCurrentVersionNumber() throws IOException {
   SortedSet<CueballFilePath> localBases = Cueball.getBases(localPartitionRoot);
   if (localBases.size() > 0) {
     return localBases.last().getVersion();
   } else {
     return null;
   }
 }
 private Set<Sector> getNeighbors(Sector[] sectors) {
   SortedSet<Sector> neighbors = new TreeSet<Sector>(ELEMENT_ORDER);
   for (Sector s : sectors) {
     if (s != null) {
       neighbors.add(s);
     }
   }
   return neighbors;
 }
 /** @return the repeatable scripts that failed during the last database update */
 protected SortedSet<ExecutedScript> getRepeatableScriptsThatFailedDuringLastUpdate() {
   SortedSet<ExecutedScript> failedExecutedScripts = new TreeSet<ExecutedScript>();
   for (ExecutedScript script : executedScriptInfoSource.getExecutedScripts()) {
     if (!script.isSuccessful() && script.getScript().isRepeatable()) {
       failedExecutedScripts.add(script);
     }
   }
   return failedExecutedScripts;
 }
Beispiel #20
0
 /** @tests java.util.TreeSet#iterator() */
 public void test_iterator() {
   // Test for method java.util.Iterator java.util.TreeSet.iterator()
   SortedSet s = db.createTreeSet("test");
   s.addAll(ts);
   Iterator i = ts.iterator();
   Set as = new HashSet(Arrays.asList(objArray));
   while (i.hasNext()) as.remove(i.next());
   assertEquals("Returned incorrect iterator", 0, as.size());
 }
  @Test
  public void simpleQueryWithRangeTombstoneTest() throws Exception {
    Table table = Table.open(KSNAME);
    ColumnFamilyStore cfs = table.getColumnFamilyStore(CFNAME);

    // Inserting data
    String key = "k1";
    RowMutation rm;
    ColumnFamily cf;

    rm = new RowMutation(KSNAME, ByteBufferUtil.bytes(key));
    for (int i = 0; i < 40; i += 2) add(rm, i, 0);
    rm.apply();
    cfs.forceBlockingFlush();

    rm = new RowMutation(KSNAME, ByteBufferUtil.bytes(key));
    cf = rm.addOrGet(CFNAME);
    delete(cf, 10, 22, 1);
    rm.apply();
    cfs.forceBlockingFlush();

    rm = new RowMutation(KSNAME, ByteBufferUtil.bytes(key));
    for (int i = 1; i < 40; i += 2) add(rm, i, 2);
    rm.apply();
    cfs.forceBlockingFlush();

    rm = new RowMutation(KSNAME, ByteBufferUtil.bytes(key));
    cf = rm.addOrGet(CFNAME);
    delete(cf, 19, 27, 3);
    rm.apply();
    // We don't flush to test with both a range tomsbtone in memtable and in sstable

    QueryPath path = new QueryPath(CFNAME);

    // Queries by name
    int[] live = new int[] {4, 9, 11, 17, 28};
    int[] dead = new int[] {12, 19, 21, 24, 27};
    SortedSet<ByteBuffer> columns = new TreeSet<ByteBuffer>(cfs.getComparator());
    for (int i : live) columns.add(b(i));
    for (int i : dead) columns.add(b(i));
    cf = cfs.getColumnFamily(QueryFilter.getNamesFilter(dk(key), path, columns));

    for (int i : live) assert isLive(cf, cf.getColumn(b(i))) : "Column " + i + " should be live";
    for (int i : dead)
      assert !isLive(cf, cf.getColumn(b(i))) : "Column " + i + " shouldn't be live";

    // Queries by slices
    cf =
        cfs.getColumnFamily(
            QueryFilter.getSliceFilter(dk(key), path, b(7), b(30), false, Integer.MAX_VALUE));

    for (int i : new int[] {7, 8, 9, 11, 13, 15, 17, 28, 29, 30})
      assert isLive(cf, cf.getColumn(b(i))) : "Column " + i + " should be live";
    for (int i : new int[] {10, 12, 14, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27})
      assert !isLive(cf, cf.getColumn(b(i))) : "Column " + i + " shouldn't be live";
  }
Beispiel #22
0
 /**
  * The earliest start date of this research staff.
  *
  * @return the active date
  */
 @Transient
 public Date getActiveDate() {
   SortedSet<Date> dates = new TreeSet<Date>();
   for (SiteResearchStaff srs : this.getSiteResearchStaffs()) {
     Date activeDate = srs.getActiveDate();
     if (activeDate != null) dates.add(activeDate);
   }
   if (dates.size() > 0) return dates.first();
   else return null;
 }
Beispiel #23
0
  public static IFilter getFilter(SlicePredicate predicate, AbstractType<?> comparator) {
    if (predicate.column_names != null) {
      final SortedSet<ByteBuffer> columnNameSet = new TreeSet<ByteBuffer>(comparator);
      columnNameSet.addAll(predicate.column_names);
      return new NamesQueryFilter(columnNameSet);
    }

    SliceRange range = predicate.slice_range;
    return new SliceQueryFilter(range.start, range.finish, range.reversed, range.count);
  }
Beispiel #24
0
  // assumes o is in satisfiers \ exceptions
  private int getIndexInPOPApp(ObjectSet satisfiers, Set exceptions, Object o) {
    SortedSet exceptionIndices = new TreeSet();
    for (Iterator iter = exceptions.iterator(); iter.hasNext(); ) {
      Object exception = iter.next();
      exceptionIndices.add(new Integer(satisfiers.indexOf(exception)));
    }

    int origIndex = satisfiers.indexOf(o);
    int numExceptionsBefore = exceptionIndices.headSet(new Integer(origIndex)).size();
    return (origIndex - numExceptionsBefore);
  }
 @Override
 public Map<Class<?>, Set<EventHandler>> findAllSubscribers(Object listener) {
   Map<Class<?>, Set<EventHandler>> found = HandlerFinder.ANNOTATED.findAllSubscribers(listener);
   Map<Class<?>, Set<EventHandler>> sorted = new HashMap<Class<?>, Set<EventHandler>>();
   for (Map.Entry<Class<?>, Set<EventHandler>> entry : found.entrySet()) {
     SortedSet<EventHandler> handlers = new TreeSet<EventHandler>(handlerComparator);
     handlers.addAll(entry.getValue());
     sorted.put(entry.getKey(), handlers);
   }
   return sorted;
 }
 /**
  * Returns a new {@link GapAwareTrackingToken} instance based on the given {@code index} and
  * collection of {@code gaps}.
  *
  * @param index the highest global sequence number of events up until (and including) this
  *     tracking token
  * @param gaps global sequence numbers of events that have not been seen yet even though these
  *     sequence numbers are smaller than the current index. These missing sequence numbers may be
  *     filled in later when those events get committed to the store or may never be filled in if
  *     those events never get committed.
  * @return a new tracking token from given index and gaps
  */
 public static GapAwareTrackingToken newInstance(long index, Collection<Long> gaps) {
   if (gaps.isEmpty()) {
     return new GapAwareTrackingToken(index, Collections.emptySortedSet());
   }
   SortedSet<Long> gapSet = new TreeSet<>(gaps);
   Assert.isTrue(
       gapSet.last() < index,
       () ->
           String.format(
               "Gap indices [%s] should all be smaller than head index [%d]", gaps, index));
   return new GapAwareTrackingToken(index, gapSet);
 }
Beispiel #27
0
 private String privilegesAsString(Set<Privilege> privileges) {
   SortedSet<Privilege> sortedPrivileges =
       new TreeSet<Privilege>(
           new Comparator<Privilege>() {
             @Override
             public int compare(Privilege p1, Privilege p2) {
               return p1.ordinal() - p2.ordinal();
             }
           });
   sortedPrivileges.addAll(privileges);
   return sortedPrivileges.toString().replaceAll(" ", "");
 }
  private SSLContext createSSLContext(LDAPConnectionHandlerCfg config) throws DirectoryException {
    try {
      DN keyMgrDN = config.getKeyManagerProviderDN();
      KeyManagerProvider<?> keyManagerProvider = DirectoryServer.getKeyManagerProvider(keyMgrDN);
      if (keyManagerProvider == null) {
        logger.error(ERR_NULL_KEY_PROVIDER_MANAGER, keyMgrDN, friendlyName);
        disableAndWarnIfUseSSL(config);
        keyManagerProvider = new NullKeyManagerProvider();
        // The SSL connection is unusable without a key manager provider
      } else if (!keyManagerProvider.containsAtLeastOneKey()) {
        logger.error(ERR_INVALID_KEYSTORE, friendlyName);
        disableAndWarnIfUseSSL(config);
      }

      final SortedSet<String> aliases = new TreeSet<>(config.getSSLCertNickname());
      final KeyManager[] keyManagers;
      if (aliases.isEmpty()) {
        keyManagers = keyManagerProvider.getKeyManagers();
      } else {
        final Iterator<String> it = aliases.iterator();
        while (it.hasNext()) {
          if (!keyManagerProvider.containsKeyWithAlias(it.next())) {
            logger.error(ERR_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, aliases, friendlyName);
            it.remove();
          }
        }

        if (aliases.isEmpty()) {
          disableAndWarnIfUseSSL(config);
        }
        keyManagers =
            SelectableCertificateKeyManager.wrap(
                keyManagerProvider.getKeyManagers(), aliases, friendlyName);
      }

      DN trustMgrDN = config.getTrustManagerProviderDN();
      TrustManagerProvider<?> trustManagerProvider =
          DirectoryServer.getTrustManagerProvider(trustMgrDN);
      if (trustManagerProvider == null) {
        trustManagerProvider = new NullTrustManagerProvider();
      }

      SSLContext sslContext = SSLContext.getInstance(SSL_CONTEXT_INSTANCE_NAME);
      sslContext.init(keyManagers, trustManagerProvider.getTrustManagers(), null);
      return sslContext;
    } catch (Exception e) {
      logger.traceException(e);
      ResultCode resCode = DirectoryServer.getServerErrorResultCode();
      LocalizableMessage message =
          ERR_CONNHANDLER_SSL_CANNOT_INITIALIZE.get(getExceptionMessage(e));
      throw new DirectoryException(resCode, message, e);
    }
  }
  @Test
  public void initConstructor() {
    WatchListItem watchListItem1 = new WatchListItem("AAPL");
    WatchListItem watchListItem2 = new WatchListItem("ORCL");

    SortedSet<WatchListItem> techList = new TreeSet<WatchListItem>();
    techList.add(watchListItem1);
    techList.add(watchListItem2);
    WatchList watchList = new WatchList("technology", techList);
    watchList.getItems().add(watchListItem1);
    watchList.getItems().add(watchListItem2);
  }
Beispiel #30
0
  /**
   * Returns all supported sample rates.
   *
   * @return an array of sample rates, in Hertz, never <code>null</code>.
   */
  public Integer[] getSampleRates() {
    final String rawValue = this.properties.get(DEVICE_SAMPLERATES);
    final String[] values = rawValue.split(",\\s*");
    final SortedSet<Integer> result =
        new TreeSet<Integer>(
            NumberUtils.<Integer>createNumberComparator(false /* aSortAscending */));
    for (String value : values) {
      result.add(Integer.valueOf(value.trim()));
    }

    return result.toArray(new Integer[result.size()]);
  }