Example usage for java.util TreeSet add

List of usage examples for java.util TreeSet add

Introduction

In this page you can find the example usage for java.util TreeSet add.

Prototype

public boolean add(E e) 

Source Link

Document

Adds the specified element to this set if it is not already present.

Usage

From source file:net.sf.jabref.model.database.BibtexDatabase.java

public TreeSet<String> getAllVisibleFields() {
    TreeSet<String> allFields = new TreeSet<>();
    for (BibtexEntry e : getEntries()) {
        allFields.addAll(e.getFieldNames());
    }/*w w w  .  java2  s . c om*/
    TreeSet<String> toberemoved = new TreeSet<>();
    for (String field : allFields) {
        if (field.startsWith("__")) {
            toberemoved.add(field);
        }
    }

    for (String field : toberemoved) {
        allFields.remove(field);
    }
    return allFields;
}

From source file:com.github.wellcomer.query3.core.Autocomplete.java

/**
    ?.   ?,  TreeSet ?  ? ?. ? TreeSet   .
        /*w w  w  .jav a 2  s  .c  o  m*/
    @param queryList ?? ?.
    @param scanModifiedOnly ?   ?.
    @param mergePrevious ?? ?  ??  .
*/
public void autolearn(QueryList queryList, boolean scanModifiedOnly, boolean mergePrevious) throws IOException {

    FileTime timestamp;
    long modifiedSince = 0;
    Path timestampFilePath = Paths.get(filePath, ".timestamp");

    if (scanModifiedOnly) { //   
        try { //  ?   ? ?
            timestamp = Files.getLastModifiedTime(timestampFilePath);
            modifiedSince = timestamp.toMillis();
        } catch (IOException e) { //    ?    ? 
            Files.createFile(timestampFilePath);
        }
    }

    HashMap<String, TreeSet<String>> fields = new HashMap<>(); //  - ? ?,  -  ? 
    Iterator<Query> queryIterator = queryList.iterator(modifiedSince); // ? ?? ? ?  ?

    String k, v;

    while (queryIterator.hasNext()) {

        Query query = queryIterator.next();

        for (Map.Entry<String, String> entry : query.entrySet()) {

            k = entry.getKey().toLowerCase();
            v = entry.getValue().trim();

            if (v.length() < 2)
                continue;

            if (!fields.containsKey(k)) {

                TreeSet<String> treeSet = new TreeSet<>();

                try {
                    if (mergePrevious) { // ? ?  
                        List<String> lines = Files.readAllLines(Paths.get(filePath, k), charset);
                        treeSet.addAll(lines);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                fields.put(k, treeSet);
            }
            TreeSet<String> treeSet = fields.get(k);
            treeSet.add(v);
        }
    }

    for (Map.Entry<String, TreeSet<String>> entry : fields.entrySet()) {

        k = entry.getKey();
        ArrayList<String> lines = new ArrayList<>(fields.get(k));

        FileWriter fileWriter = new FileWriter(Paths.get(filePath, k).toString());
        fileWriter.write(StringUtils.join(lines, System.getProperty("line.separator")));
        fileWriter.flush();
        fileWriter.close();
    }

    try {
        Files.setLastModifiedTime(timestampFilePath, FileTime.fromMillis(System.currentTimeMillis()));
    } catch (IOException e) {
        if (e.getClass().getSimpleName().equals("NoSuchFileException"))
            Files.createFile(timestampFilePath);
        e.printStackTrace();
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.messaging.ViewSentEmailsDA.java

@EntryPoint
public ActionForward viewSentEmails(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) {/*from  w w w.  ja v a  2s.c  om*/
    final String senderParam = request.getParameter("senderId");
    if (senderParam != null && !senderParam.isEmpty()) {
        return viewSentEmails(mapping, request, senderParam);
    }

    final User userView = Authenticate.getUser();
    final Set<Sender> sendersGroups = new TreeSet<Sender>(Sender.COMPARATOR_BY_FROM_NAME);
    final TreeSet<ExecutionCourseSender> sendersGroupsCourses = new TreeSet<ExecutionCourseSender>(
            ExecutionCourseSender.COMPARATOR_BY_EXECUTION_COURSE_SENDER);
    for (final Sender sender : Bennu.getInstance().getUtilEmailSendersSet()) {
        boolean allow = sender.getMembers().isMember(userView);
        boolean isExecutionCourseSender = sender instanceof ExecutionCourseSender;
        if (allow && !isExecutionCourseSender) {
            sendersGroups.add(sender);
        }
        if (allow && isExecutionCourseSender) {
            sendersGroupsCourses.add((ExecutionCourseSender) sender);
        }
    }
    if (isSenderUnique(sendersGroups, sendersGroupsCourses)) {
        if (sendersGroupsCourses.size() == 1) {
            return viewSentEmails(mapping, request, (sendersGroupsCourses.iterator().next()).getExternalId());
        } else {
            return viewSentEmails(mapping, request, sendersGroups.iterator().next().getExternalId());
        }
    }
    request.setAttribute("sendersGroups", sendersGroups);
    request.setAttribute("sendersGroupsCourses", sendersGroupsCourses);

    final Person person = AccessControl.getPerson();
    if (person != null && person.hasRole(RoleType.MANAGER)) {
        SearchSendersBean searchSendersBean = getRenderedObject("searchSendersBean");
        if (searchSendersBean == null) {
            searchSendersBean = new SearchSendersBean();
        }
        request.setAttribute("searchSendersBean", searchSendersBean);
    }

    return mapping.findForward("view.sent.emails");
}

From source file:com.digipom.manteresting.android.processor.json.NailsJsonProcessor.java

@Override
public ArrayList<ContentProviderOperation> parse(JSONObject response, Meta meta) throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final TreeSet<Integer> nailIds = new TreeSet<Integer>();
    final Cursor nails = resolver.query(ManterestingContract.Nails.CONTENT_URI, new String[] { Nails.NAIL_ID },
            null, null, Nails.NAIL_ID + " DESC");
    int greatestOfExisting = Integer.MIN_VALUE;

    if (nails != null && !nails.isClosed()) {
        try {//from   w w w .j a v a  2s . co  m
            nails.moveToFirst();

            final int idColumn = nails.getColumnIndex(Nails.NAIL_ID);

            while (!nails.isAfterLast()) {
                final int nailId = nails.getInt(idColumn);
                nailIds.add(nailId);
                greatestOfExisting = nailId > greatestOfExisting ? nailId : greatestOfExisting;
                nails.moveToNext();
            }
        } finally {
            if (nails != null) {
                nails.close();
            }
        }
    }

    final JSONArray objects = response.getJSONArray("objects");
    int smallestOfNew = Integer.MAX_VALUE;

    for (int i = 0; i < objects.length(); i++) {
        final JSONObject nailObject = objects.getJSONObject(i);

        final boolean isPrivate = nailObject.getJSONObject("workbench").getBoolean("private");

        if (!isPrivate) {
            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Nails.CONTENT_URI);
            final int nailId = nailObject.getInt("id");
            smallestOfNew = nailId < smallestOfNew ? nailId : smallestOfNew;

            builder.withValue(Nails.NAIL_ID, nailId);
            builder.withValue(Nails.NAIL_JSON, nailObject.toString());

            batch.add(builder.build());
            nailIds.add(nailId);
        }
    }

    // If more than LIMIT were fetched, and this was the initial fetch, then
    // we flush everything in the DB before adding the new nails (as
    // otherwise we would introduce a gap).
    if (meta.nextOffset == meta.nextLimit // For initial fetch
            && smallestOfNew > greatestOfExisting) {
        if (LoggerConfig.canLog(Log.DEBUG)) {
            Log.d(TAG, "Flushing all existing nails on initial fetch, so as to avoid a gap.");
        }

        resolver.delete(Nails.CONTENT_URI, null, null);
    } else {
        // If more than 500 nails, find the 500th biggest and delete those
        // after it.
        if (nailIds.size() > MAX_COUNT) {
            Iterator<Integer> it = nailIds.descendingIterator();

            for (int i = 0; i < MAX_COUNT; i++) {
                it.next();
            }

            final Integer toDelete = it.next();

            if (LoggerConfig.canLog(Log.DEBUG)) {
                Log.d(TAG, "deleting from nails where NAIL_ID is less than or equal to " + toDelete);
            }

            SelectionBuilder selectionBuilder = new SelectionBuilder();
            selectionBuilder.where(ManterestingContract.Nails.NAIL_ID + " <= ?",
                    new String[] { String.valueOf(toDelete) });
            resolver.delete(ManterestingContract.Nails.CONTENT_URI, selectionBuilder.getSelection(),
                    selectionBuilder.getSelectionArgs());
        }
    }

    return batch;
}

From source file:com.clearspring.analytics.stream.frequency.CountMinSketchTest.java

@Test
public void merge() throws CMSMergeException {
    int numToMerge = 5;
    int cardinality = 1000000;

    double epsOfTotalCount = 0.0001;
    double confidence = 0.99;
    int seed = 7364181;

    int maxScale = 20;
    Random r = new Random();
    TreeSet<Integer> vals = new TreeSet<Integer>();

    CountMinSketch baseline = new CountMinSketch(epsOfTotalCount, confidence, seed);
    CountMinSketch[] sketchs = new CountMinSketch[numToMerge];
    for (int i = 0; i < numToMerge; i++) {
        sketchs[i] = new CountMinSketch(epsOfTotalCount, confidence, seed);
        for (int j = 0; j < cardinality; j++) {
            int scale = r.nextInt(maxScale);
            int val = r.nextInt(1 << scale);
            vals.add(val);
            sketchs[i].add(val, 1);
            baseline.add(val, 1);
        }//from  w ww .ja v  a2  s.c  o  m
    }

    CountMinSketch merged = CountMinSketch.merge(sketchs);

    assertEquals(baseline.size(), merged.size());
    assertEquals(baseline.getConfidence(), merged.getConfidence(), baseline.getConfidence() / 100);
    assertEquals(baseline.getRelativeError(), merged.getRelativeError(), baseline.getRelativeError() / 100);
    for (int val : vals) {
        assertEquals(baseline.estimateCount(val), merged.estimateCount(val));
    }
}

From source file:mi.RankInfo.java

void computeDistRanksFromRef() {
    int i, j, k;//from   w w w  .  jav  a 2 s  .  c om

    TreeSet<DistInfo> nnList;

    DistInfo distInfo;

    for (j = 0; j < numRefPoints; j++) {
        FloatByteRcd b = this.r[j];
        nnList = new TreeSet<>();

        System.out.println("Computing distance info for ref-point: " + j);

        for (i = 0; i < numPoints; i++) {

            FloatByteRcd a = this.o[i];

            float dist = computeDistSquared(a.getVec(), b.getVec());
            distInfo = new DistInfo(i, j, dist);

            nnList.add(distInfo);
        }

        if (i % 1000 == 0)
            System.out.println("Trimming distance info for point: " + j);

        Iterator<DistInfo> iter = nnList.iterator();
        // Get the best-k
        for (k = 0; k < nTop; k++) {
            DistInfo nnInfo = iter.next();
            rinfos[nnInfo.refId].add(new RankInfo(nnInfo.id, k + 1));
        }
    }
}

From source file:com.excilys.soja.server.handler.ServerHandler.java

/**
 * Handle SEND command//from   w w  w . j  a  v a2 s.  c om
 * 
 * @param sendFrame
 * @throws SocketException
 */
public void handleSend(Channel channel, Frame sendFrame) throws SocketException {
    String topic = sendFrame.getHeaderValue(HEADER_DESTINATION);

    synchronized (authentication) {
        if (!authentication.canSend(clientsSessionToken.get(channel), topic)) {
            sendError(channel, "Can't send message",
                    "You're not allowed to send a message to the topic" + topic);
            return;
        }
    }

    // Retrieve subscribers for the given topic
    Set<Subscription> subscriptions = null;
    subscriptions = subscriptionManager.retrieveSubscriptionsByTopic(topic);

    if (subscriptions != null && subscriptions.size() > 0) {
        // Construct the MESSAGE frame
        MessageFrame messageFrame = new MessageFrame(topic, sendFrame.getBody(), null);

        // Add content-type if it was present on the SEND command
        String contentType = sendFrame.getHeaderValue(HEADER_CONTENT_TYPE);
        if (contentType != null) {
            messageFrame.setContentType(contentType);
        }

        // Add user keys if there was some on the SEND command
        Set<String> userKeys = sendFrame.getHeader().allKeys(SEND_USER_HEADERS_FILTER);
        for (String userKey : userKeys) {
            messageFrame.getHeader().put(userKey, sendFrame.getHeaderValue(userKey));
        }

        // Create a set of subscription which will be used for ACKs requests
        TreeSet<Long> acks = new TreeSet<Long>();

        // Send the message frame to each subscriber
        for (Subscription subscription : subscriptions) {
            // If an ack is needed for this client, add the subscription to the ACKs queue.
            if (subscription.getAckMode() != Ack.AUTO) {
                acks.add(subscription.getSubscriptionId());
            }

            messageFrame.setHeaderValue(HEADER_SUBSCRIPTION, subscription.getSubscriptionId().toString());
            sendFrame(subscription.getChannel(), messageFrame);
        }

        if (acks.size() > 0) {
            synchronized (waitingAcks) {
                String messageId = messageFrame.getMessageId();
                waitingAcks.put(messageId, new AckWaiting(channel, acks, sendFrame));
            }
        } else {
            sendReceiptIfRequested(channel, sendFrame);
            return;
        }
    }
    sendReceiptIfRequested(channel, sendFrame);
}

From source file:net.sf.jabref.importer.TextAnalyzer.java

private void guessBibtexFields(String text) {

    TreeSet<Substring> usedParts = new TreeSet<>();

    text = "  " + text + "  ";

    String[] split;//w  ww .  jav  a2  s. c  o m

    // Look for the year:
    String year = null;
    String yearRx = "(\\s|\\()\\d\\d\\d\\d(\\.|,|\\))";
    String[] cand = getMatches(text, yearRx);
    if (cand.length == 1) {
        // Only one four-digit number, so we guess that is the year.
        year = clean(cand[0]);
        int pos = text.indexOf(year);
        usedParts.add(new Substring("year", pos, pos + year.length()));
        LOGGER.debug("Guessing 'year': '" + year + "'");
    } else if (cand.length > 1) {
        // More than one four-digit numbers, so we look for one giving a reasonable year:

        int good = -1;
        int yearFound = -1;
        for (int i = 0; i < cand.length; i++) {
            int number = Integer.parseInt(cand[i].trim());
            if (number == yearFound) {
                continue;
            }
            if (number < 2500) {
                if (good == -1) {
                    good = i;
                    yearFound = number;
                } else {
                    // More than one found. Be a bit more specific.
                    if ((yearFound < FUTURE_YEAR) && (number < FUTURE_YEAR)) {
                        good = -1;
                        break; // Give up, both seem good enough.
                    } else if ((yearFound >= FUTURE_YEAR) && (number < FUTURE_YEAR)) {
                        good = i;
                        yearFound = number;
                    }
                }
            }
        }
        if (good >= 0) {
            year = clean(cand[good]);
            int pos = text.indexOf(year);
            usedParts.add(new Substring("year", pos, pos + year.length()));
            LOGGER.debug("Guessing 'year': '" + year + "'");
        }
    }

    // Look for Pages:
    String pages;
    String pagesRx = "\\s(\\d{1,4})( ??)-( ??)(\\d{1,4})(\\.|,|\\s)";
    cand = getMatches(text, pagesRx);
    if (cand.length == 1) {
        pages = clean(cand[0].replaceAll("-|( - )", "--"));
        int pos = text.indexOf(cand[0]);
        usedParts.add(new Substring("pages", pos, pos + year.length()));
        LOGGER.debug("Guessing 'pages': '" + pages + "'");
    } else if (cand.length > 1) {
        int found = -1;
        for (int i = 0; i < cand.length; i++) {
            split = clean(cand[i].replaceAll("\\s", "")).split("-");
            //   Util.pr("Pg: "+pages);
            int first = Integer.parseInt(split[0]);
            int second = Integer.parseInt(split[1]);
            if ((second - first) > 3) {
                found = i;
                break;
            }
        }
        if (found >= 0) {
            pages = clean(cand[found].replaceAll("-|( - )", "--"));
            int pos = text.indexOf(cand[found]);
            LOGGER.debug("Guessing 'pages': '" + pages + "'");
            usedParts.add(new Substring("pages", pos, pos + pages.length()));
        }
    }

    //String journalRx = "(\\.|\\n)\\s??([a-zA-Z\\. ]{8,30}+)((vol\\.|Vol\\.|Volume|volume))??(.??)(\\d{1,3})(\\.|,|\\s)";
    String journal;
    String volume;
    String journalRx = "(,|\\.|\\n)\\s??([a-zA-Z\\. ]{8,30}+)((.){0,2})((vol\\.|Vol\\.|Volume|volume))??\\s??(\\d{1,3})(\\.|,|\\s|:)";
    cand = getMatches(text, journalRx);
    if (cand.length > 0) {
        //Util.pr("guessing 'journal': '" + cand[0] + "'");
        cand[0] = cand[0].trim();
        int pos = cand[0].lastIndexOf(' ');
        if (pos > 0) {
            volume = clean(cand[0].substring(pos + 1));
            LOGGER.debug("Guessing 'volume': '" + volume + "'");
            journal = clean(cand[0].substring(0, pos));
            //Util.pr("guessing 'journal': '" + journal + "'");
            pos = journal.lastIndexOf(' ');
            if (pos > 0) {
                String last = journal.substring(pos + 1).toLowerCase();
                if ("volume".equals(last) || "vol".equals(last) || "v".equals(last)) {
                    journal = clean(journal.substring(0, pos));
                }
            }
            pos = text.indexOf(journal);
            usedParts.add(new Substring("journal", pos, pos + journal.length()));
            LOGGER.debug("Guessing 'journal': '" + journal + "'");
        }
        //Util.pr("Journal? '"+cand[0]+"'");
    } else {
        // No journal found. Maybe the year precedes the volume? Try another regexp:
    }

    // Then try to find title and authors.
    Substring ss;
    Vector<String> free = new Vector<>();
    int piv = 0;
    for (Substring usedPart : usedParts) {
        ss = usedPart;
        if ((ss.begin() - piv) > 10) {
            LOGGER.debug("... " + text.substring(piv, ss.begin()));
            free.add(clean(text.substring(piv, ss.begin())));
        }
        piv = ss.end();
    }
    if ((text.length() - piv) > 10) {
        free.add(clean(text.substring(piv)));
    }
    LOGGER.debug("Free parts:");
    for (String s : free) {
        LOGGER.debug(": '" + s + "'");
    }
}

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

public void testTreeSetSerialization() {
    TreeSet<String> treeSet = new TreeSet<String>();
    treeSet.add("Value1");
    String json = oson.toJson(treeSet);
    assertEquals("[\"Value1\"]", json);
}

From source file:com.clearspring.analytics.stream.frequency.ConservativeAddSketchTest.java

/**
 * The merging guarantees are a little different for us. Sometimes it is
 * better to split and merge and sometimes not. As long as we are more
 * accurate than the regular version though, I am happy.
 *//*from   w w  w  . j  a  v  a 2 s  .c o m*/
@Test
public void merge() throws CountMinSketch.CMSMergeException {
    int numToMerge = 5;
    int cardinality = 1000000;

    double epsOfTotalCount = 0.0001;
    double confidence = 0.99;
    int seed = 7364181;

    int maxScale = 20;
    Random r = new Random();
    TreeSet<Integer> vals = new TreeSet<Integer>();

    CountMinSketch baseline = new ConservativeAddSketch(epsOfTotalCount, confidence, seed);
    CountMinSketch stdMinSketch = new CountMinSketch(epsOfTotalCount, confidence, seed);
    CountMinSketch[] sketchs = new CountMinSketch[numToMerge];
    for (int i = 0; i < numToMerge; i++) {
        sketchs[i] = new ConservativeAddSketch(epsOfTotalCount, confidence, seed);
        for (int j = 0; j < cardinality; j++) {
            int scale = r.nextInt(maxScale);
            int val = r.nextInt(1 << scale);
            if (vals.add(val)) {
                sketchs[i].add(val, 1);
                baseline.add(val, 1);
                stdMinSketch.add(val, 1);
            }
        }
    }

    CountMinSketch merged = CountMinSketch.merge(sketchs);

    assertEquals(baseline.size(), merged.size());
    assertEquals(baseline.getConfidence(), merged.getConfidence(), baseline.getConfidence() / 100);
    assertEquals(baseline.getRelativeError(), merged.getRelativeError(), baseline.getRelativeError() / 100);
    for (int val : vals) {
        long base = baseline.estimateCount(val);
        long merge = merged.estimateCount(val);
        long std = stdMinSketch.estimateCount(val);
        assertTrue(1 <= base);
        assertTrue(base <= std);
        assertTrue(1 <= merge);
        assertTrue(merge <= std);
    }
}