Example usage for java.util HashSet size

List of usage examples for java.util HashSet size

Introduction

In this page you can find the example usage for java.util HashSet size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:org.ihtsdo.classifier.ClassificationRunner.java

/**
 * Gets the roles./*from  w w w.  j av  a 2  s.  c  om*/
 *
 * @param parentConcepts the parent concepts
 * @return the roles
 * @throws Exception the exception
 */
private int[] getRoles(HashSet<String> parentConcepts) throws IOException, ClassificationException {
    HashSet<String> roles = new HashSet<String>();
    for (String statedRel : statedRelationships) {
        File relationshipFile = new File(statedRel);
        GetDescendants getDesc = new GetDescendants(parentConcepts, relationshipFile, null);
        getDesc.execute();
        roles.addAll(getDesc.getDescendants());
        getDesc = null;
    }
    roles.add(GetDescendants.ISA_SCTID);
    int[] result = new int[roles.size()];
    int resIdx = 0;
    for (String role : roles) {
        Integer integer = conStrList.get(role);
        if (integer != null) {
            result[resIdx] = integer;
        } else {
            throw new ClassificationException("No entry for " + role + " in conStrList.");
        }
        resIdx++;
    }
    roles = null;
    Arrays.sort(result);
    return result;
}

From source file:compare.handler.get.CompareGetHandler.java

/**
 * Format the requested URN version as HTML
 * @param request the original http request
 * @param response the response to write to
 * @param urn the original request urn//w w w  .  j  a v a  2 s .c o m
 * @throws CompareException if the response could not be written
 */
protected void handleGetVersion(HttpServletRequest request, HttpServletResponse response, String urn)
        throws CompareException, CalliopeException {
    String version1 = request.getParameter(Params.VERSION1);
    if (version1 == null) {
        try {
            response.getWriter().println("<p>version1 parameter required</p>");
        } catch (Exception e) {
            throw new CompareException(e);
        }
    } else {
        String selectedVersions = request.getParameter(Params.SELECTED_VERSIONS);
        //System.out.println("version1="+version1);
        EcdosisVersion corTex = doGetResourceVersion(Database.CORTEX, urn, version1);
        // 1. get corcodes and styles
        String[] corCodes = request.getParameterValues(Params.CORCODE);
        String[] styles = request.getParameterValues(Params.STYLE);
        HashSet<String> styleSet = new HashSet<String>();
        for (int i = 0; i < styles.length; i++)
            styleSet.add(styles[i]);
        try {
            for (int i = 0; i < corCodes.length; i++) {
                String ccResource = Utils.canonisePath(urn, corCodes[i]);
                EcdosisVersion ev = doGetResourceVersion(Database.CORCODE, ccResource, version1);
                Comment comment = new Comment();
                comment.addText("version-length: " + ev.getVersionLength());
                response.setCharacterEncoding("UTF-8");
                response.getWriter().println(comment.toString());
                styleSet.add(ev.getStyle());
                corCodes[i] = ev.getVersionString();
            }
        } catch (Exception e) {
            // this won't ever happen because UTF-8 is always supported
            throw new CompareException(e);
        }
        // 2. add mergeids if needed
        if (selectedVersions != null && selectedVersions.length() > 0) {
            corCodes = addMergeIds(corCodes, corTex.getMVD(), version1, selectedVersions);
            styleSet.add("diffs/default");
        }
        // 3. recompute styles array (docids)
        styles = new String[styleSet.size()];
        styleSet.toArray(styles);
        // 4. convert style names to actual corforms
        styles = fetchStyles(styles);
        // 5. call the native library to format it
        JSONResponse html = new JSONResponse(JSONResponse.HTML);
        String text = corTex.getVersionString();
        int res = new AeseFormatter().format(text, corCodes, styles, html);
        if (res == 0)
            throw new CompareException("formatting failed");
        else {
            response.setContentType("text/html;charset=UTF-8");
            try {
                Comment comment = new Comment();
                comment.addText("styles: ");
                for (int i = 0; i < styles.length; i++)
                    comment.addText(styles[i]);
                response.getWriter().println(comment.toString());
                response.getWriter().println(html.getBody());
            } catch (Exception e) {
                throw new CompareException(e);
            }
        }
    }
}

From source file:com.cloudera.impala.catalog.HdfsTable.java

/**
 * Drops the partition having the given partition spec from HdfsTable. Cleans up its
 * metadata from all the mappings used to speed up partition pruning/lookup.
 * Also updates partition column statistics. Given partitionSpec must match exactly
 * one partition.//  w w w.  j a v a  2 s.c  o m
 * Returns the HdfsPartition that was dropped. If the partition does not exist, returns
 * null.
 *
 * Note: This method is not thread safe because it modifies the list of partitions
 * and the HdfsTable's partition metadata.
 */
public HdfsPartition dropPartition(List<TPartitionKeyValue> partitionSpec) {
    HdfsPartition partition = getPartitionFromThriftPartitionSpec(partitionSpec);
    // Check if the partition does not exist.
    if (partition == null || !partitions_.remove(partition))
        return null;
    totalHdfsBytes_ -= partition.getSize();
    Preconditions.checkArgument(partition.getPartitionValues().size() == numClusteringCols_);
    Long partitionId = partition.getId();
    // Remove the partition id from the list of partition ids and other mappings.
    partitionIds_.remove(partitionId);
    partitionMap_.remove(partitionId);
    for (int i = 0; i < partition.getPartitionValues().size(); ++i) {
        ColumnStats stats = getColumns().get(i).getStats();
        LiteralExpr literal = partition.getPartitionValues().get(i);
        // Check if this is a null literal.
        if (literal instanceof NullLiteral) {
            nullPartitionIds_.get(i).remove(partitionId);
            stats.setNumNulls(stats.getNumNulls() - 1);
            if (nullPartitionIds_.get(i).isEmpty()) {
                stats.setNumDistinctValues(stats.getNumDistinctValues() - 1);
            }
            continue;
        }
        HashSet<Long> partitionIds = partitionValuesMap_.get(i).get(literal);
        // If there are multiple partition ids corresponding to a literal, remove
        // only this id. Otherwise, remove the <literal, id> pair.
        if (partitionIds.size() > 1)
            partitionIds.remove(partitionId);
        else {
            partitionValuesMap_.get(i).remove(literal);
            stats.setNumDistinctValues(stats.getNumDistinctValues() - 1);
        }
    }
    return partition;
}

From source file:org.cytobank.acs.core.TableOfContents.java

/**
 * Returns an array of all unique <code>FileResourceIdentifier</code>s contained within this <code>TableOfContents</code> instance
 * that have been identified as project workspaces.
 *
 * @return an array of all the <code>FileResourceIdentifier</code>s that are project workspaces
 * @throws InvalidIndexException If there is a problem with the <code>TableOfContents</code>
 * @throws URISyntaxException If there is a problem with any of the URIs contained within the <code>TableOfContents</code> or if the URI is a duplicate
 * @throws InvalidAssociationException if there is an invalid association
 * @see RelationshipTypes#isProjectWorkspace
 *//* w  w w  .  j  a v a 2  s . c  om*/
public FileResourceIdentifier[] getProjectWorkspaces()
        throws InvalidAssociationException, InvalidIndexException, URISyntaxException {
    HashSet<FileResourceIdentifier> projectWorkspaces = new HashSet<FileResourceIdentifier>();

    // Find all fileResource associations and add the associated file to projectWorkspaces
    // if that association relationship is a project workspace.
    for (FileResourceIdentifier fileResource : fileResourceIdentifiers) {
        for (Association association : fileResource.associations) {
            if (RelationshipTypes.isProjectWorkspace(association.getRelationship())) {
                projectWorkspaces.add(association.getAssociatedTo());
            }
        }
    }

    FileResourceIdentifier[] results = new FileResourceIdentifier[projectWorkspaces.size()];
    projectWorkspaces.toArray(results);

    return results;
}

From source file:och.comp.db.base.BaseDb.java

protected void createTables() {

    HashMap<Class<?>, HashSet<Class<?>>> waiters = new HashMap<>();

    //fill waiters
    for (Class<?> type : mappers) {

        if (!BaseMapperWithTables.class.isAssignableFrom(type))
            continue;
        if (type.equals(BaseMapperWithTables.class))
            continue;

        HashSet<Class<?>> waitFor = new HashSet<>();
        CreateTablesAfter waitForAnn = type.getAnnotation(CreateTablesAfter.class);
        if (waitForAnn != null) {
            waitFor.addAll(list(waitForAnn.value()));
        }/*  w ww  .j a v  a 2  s. c  o  m*/

        waiters.put(type, waitFor);
    }

    //do creates
    int mappersToCreate = 0;
    ArrayList<String> mappersWithErrors = new ArrayList<>();
    while (waiters.size() > 0) {

        //create
        HashSet<Class<?>> created = new HashSet<>();
        for (Entry<Class<?>, HashSet<Class<?>>> entry : waiters.entrySet()) {
            if (entry.getValue().size() == 0) {

                Class<?> type = entry.getKey();
                created.add(type);

                try (SqlSession session = sessionFactory.openSession()) {

                    Object mapper = session.getMapper(type);
                    if (mapper instanceof BaseMapperWithTables) {

                        SQLDialect dialectType = type.getAnnotation(SQLDialect.class);
                        String mapperDialect = dialectType == null ? null : dialectType.value();
                        if (mapperDialect == null)
                            mapperDialect = DB_DEFAULT;
                        if (dialect.equals(mapperDialect)) {
                            mappersToCreate++;
                            ((BaseMapperWithTables) mapper).createTables();
                        }
                    }

                } catch (Exception e) {
                    if (props.getBoolVal(db_debug_LogSql)) {
                        log.error("can't createTables: " + e);
                    }
                    mappersWithErrors.add(type.getName());
                }

            }
        }

        if (created.size() == 0)
            throw new IllegalStateException("no mapper to create. all mappers is waitnig: " + waiters);

        //clean
        for (Class<?> type : created) {
            waiters.remove(type);
            for (Entry<Class<?>, HashSet<Class<?>>> entry : waiters.entrySet()) {
                entry.getValue().remove(type);
            }
        }
    }

    //check results
    if (!isEmpty(mappersWithErrors))
        log.info("can't create tables for " + mappersWithErrors);
    isNewTables = mappersToCreate > 0 && isEmpty(mappersWithErrors);

}

From source file:gr.demokritos.iit.cru.creativity.reasoning.diagrammatic.DiagrammaticComputationalTools.java

public HashSet<String> FindRelations(ArrayList<String> tri, int difficulty, String category)
        throws InstantiationException, IllegalAccessException, SQLException, ClassNotFoundException, Exception {
    HashSet<String> relations = new HashSet<String>();
    HashSet<String> TempRelations = new HashSet<String>();
    HashSet<String> newConcepts = new HashSet<String>();
    ArrayList<String> triple = new ArrayList<String>();

    ///---------translate
    for (String s : tri) {
        String h = Translator.bingTranslate(s, this.language, "en", "general");
        if (wn.getCommonPos(h) == null) {
            // System.out.println(s + " out " + h);
            return newConcepts; //if any element of the triple cannot be translated, relations cannot be found
        }//from  www .  ja va  2s .co m
        triple.add(h);
    }
    // System.out.println(triple);
    //run abstraction for relation to find new relations and work with them
    String relation = triple.get(2);
    for (int i = 0; i < difficulty; i++) {
        TempRelations = ConceptGraphAbstractionEngine(relation);
        if (TempRelations.isEmpty()) {
            break;
        }
        relations = TempRelations;
        int pointer = new Random().nextInt(relations.size());
        int c = 0;
        for (String k : relations) {
            if (c == pointer) {
                relation = k;
            }
            c = c + 1;
        }
    }
    //take the similar concepts to the subject and the object of the triple
    if (category.equalsIgnoreCase("subsumption")) {
        newConcepts = ConceptGraphPolymerismEngine(triple.get(0));//wn.getMeronyms(triple.get(0));
        newConcepts.addAll(ConceptGraphPolymerismEngine(triple.get(1)));//wn.getMeronyms(triple.get(1));
    } else if (category.equalsIgnoreCase("supersumption")) {
        newConcepts = ConceptGraphAbstractionEngine(triple.get(0));// wn.getHyponymsAndHypernyms(triple.get(0));
        newConcepts.addAll(ConceptGraphAbstractionEngine(triple.get(1)));//wn.getHyponymsAndHypernyms(triple.get(1)));
    }
    System.out.println("new concepts " + newConcepts);
    //take concepts that have the relations found
    //  System.out.println("newConc " + newConcepts);
    for (String r : relations) {
        System.out.println(r);
        //System.out.println("relations " + r);
        HashSet<String> temp = FactRetriever(r, "relation");
        for (String g : temp) {
            //keep the subject and the object of the triples
            newConcepts.add(g.split("---")[0]);
            newConcepts.add(g.split("---")[1]);///////////////!!!!!!check if subj/obj=''
        }
    }

    //find relations based on the new concepts
    HashSet<String> newRelations = new HashSet<String>();
    for (String s : newConcepts) {
        // System.out.println("concepts " + s);
        newRelations.addAll(FactRetriever(s, "object"));
        newRelations.addAll(FactRetriever(s, "subject"));
    }
    // System.out.println("newRels " + newRelations);
    /*
     HashSet<String> rels = new HashSet<String>();
     ///---------translate
     if (!this.language.equalsIgnoreCase("en")) {
     for (String s : newRelations) {
     System.out.println(s);
     String n = Translator.bingTranslate(s, "en", this.language, "general");
     if (wn.getCommonPos(n) == null) {//if the word is not english
     rels.add(n);
     }
     }
     } else {
     rels.addAll(newRelations);
     }*/
    return newRelations;
}

From source file:cz.cas.lib.proarc.webapp.server.rest.DigitalObjectResource.java

/**
 * Moves members from a source object to a destination object.
 * @param srcParentPid PID of source//  www.j a  v a  2s .  com
 * @param dstParentPid PID of destination
 * @param batchId optional batch import ID
 * @param movePids member PIDs to move
 * @return the list of updated members
 */
@PUT
@Path(DigitalObjectResourceApi.MEMBERS_PATH + '/' + DigitalObjectResourceApi.MEMBERS_MOVE_PATH)
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_JSON })
public SmartGwtResponse<Item> moveMembers(
        @FormParam(DigitalObjectResourceApi.MEMBERS_MOVE_SRCPID) String srcParentPid,
        @FormParam(DigitalObjectResourceApi.MEMBERS_MOVE_DSTPID) String dstParentPid,
        @FormParam(DigitalObjectResourceApi.MEMBERS_ITEM_BATCHID) Integer batchId,
        @FormParam(DigitalObjectResourceApi.MEMBERS_ITEM_PID) List<String> movePids)
        throws IOException, DigitalObjectException, FedoraClientException {

    if (srcParentPid == null) {
        throw RestException.plainText(Status.BAD_REQUEST, "Missing source PID!");
    }
    if (dstParentPid == null) {
        throw RestException.plainText(Status.BAD_REQUEST, "Missing target PID!");
    }
    if (srcParentPid.equals(dstParentPid)) {
        throw RestException.plainText(Status.BAD_REQUEST, "src == dst!");
    }
    if (movePids == null || movePids.isEmpty()) {
        throw RestException.plainText(Status.BAD_REQUEST, "Missing children PIDs!");
    }

    HashSet<String> movePidSet = new HashSet<String>(movePids);
    if (movePidSet.isEmpty()) {
        return new SmartGwtResponse<Item>(Collections.<Item>emptyList());
    } else if (movePidSet.size() != movePids.size()) {
        throw RestException.plainText(Status.BAD_REQUEST, "Duplicate children in the request!");
    }
    if (movePidSet.contains(dstParentPid)) {
        throw RestException.plainText(Status.BAD_REQUEST, "The target parent listed as child!");
    }

    Batch batch = batchId == null ? null : importManager.get(batchId);
    DigitalObjectHandler srcHandler = findHandler(srcParentPid, batch, false);
    deleteMembers(srcHandler, movePidSet);

    // XXX loadLocalSearchItems
    Map<String, Item> memberSearchMap = loadSearchItems(movePidSet);
    DigitalObjectHandler dstHandler = findHandler(dstParentPid, batch, false);
    List<Item> added = addMembers(dstHandler, movePids, memberSearchMap);

    srcHandler.commit();
    dstHandler.commit();
    SmartGwtResponse<Item> result = new SmartGwtResponse<Item>(added);
    return result;
}

From source file:gr.demokritos.iit.cru.creativity.reasoning.diagrammatic.DiagrammaticComputationalTools.java

public HashSet<String> FindConcepts(String concept, int difficulty, String category)
        throws InstantiationException, IllegalAccessException, SQLException, ClassNotFoundException, Exception {
    HashSet<String> concepts = new HashSet<String>();
    HashSet<String> TempConcepts = new HashSet<String>();

    ///---------translate
    concept = Translator.bingTranslate(concept, this.language, "en", "general");
    if (wn.getCommonPos(concept) == null) { ////new addition if the word cannot be translated to english
        return concepts;
    }/*  w w  w . ja v  a 2 s .  c o m*/

    if (category.equalsIgnoreCase("equivalence")) {
        //to be done
    } else if (category.equalsIgnoreCase("subsumption")) {
        for (int i = 0; i < difficulty; i++) {//for the given dificculty, abstract as many times
            TempConcepts = ConceptGraphPolymerismEngine(concept); //polymerism doesn't return many
            if (TempConcepts.isEmpty()) {
                break;
            }
            concepts = TempConcepts;//define the temporary conecpts as new conecpts in case the next concepts are empty
            //take one concept at random from the abstraction, and make it the new concept
            int pointer = new Random().nextInt(concepts.size());
            int c = 0;
            for (String k : concepts) {
                if (c == pointer) {
                    concept = k;
                }
                c = c + 1;
            }
        }
    } else if (category.equalsIgnoreCase("supersumption")) {
        for (int i = 0; i < difficulty; i++) {
            TempConcepts = ConceptGraphAbstractionEngine(concept);
            if (TempConcepts.isEmpty()) {
                break;
            }
            concepts = TempConcepts;//define the temporary concepts as new conecpts in case the next concepts are empty
            //take one concept at random from the abstraction, and make it the new concept
            int pointer = new Random().nextInt(concepts.size());
            int c = 0;
            for (String k : concepts) {
                if (c == pointer) {
                    concept = k;
                }
                c = c + 1;
            }
        }
    } else {
        String type = "subject";
        //take alternatively the object of the subject and the subject of the object until diff is reached
        for (int i = 0; i < difficulty; i++) {
            TempConcepts = FactRetriever(concept, type);
            if (TempConcepts.isEmpty()) {
                break;
            }
            concepts = TempConcepts;
            int pointer = new Random().nextInt(concepts.size());
            int c = 0;
            for (String k : concepts) {
                if (c == pointer) {
                    if (type.equalsIgnoreCase("subject")) {
                        if (!k.split("---")[1].isEmpty()) {
                            concept = k.split("---")[1];//take the object
                            type = "object";
                        }
                    } else {
                        if (!k.split("---")[0].isEmpty()) {
                            concept = k.split("---")[0];//take the subject
                            type = "subject";
                        }
                    }
                }
                c = c + 1;
            }
        }
    }
    HashSet<String> finCon = new HashSet<String>();

    ///---------translate
    if (!this.language.equalsIgnoreCase("en")) {
        for (String s : concepts) {
            String n = Translator.bingTranslate(s, "en", this.language, "general");
            if (wn.getCommonPos(n) == null) {//if the word is not english
                finCon.add(n);
            }
        }
    } else {
        finCon.addAll(concepts);
    }
    return finCon;
}

From source file:org.madsonic.service.LastFMService.java

public List<MediaFile> updateTopTrackEntries(String artist, int limit, int userGroupId) {

    //TODO: check & scan with service

    List<MediaFile> topTrackSongs = new ArrayList<MediaFile>();
    HashSet<MediaFile> hs = new HashSet<MediaFile>();
    List<LastFMArtistTopTrack> topTracks = getTopTrackArtist(artist);

    if (topTracks.size() < 1) {
        updateTopTrackArtist(artist);/*www  .j  a va  2s. com*/
        if (topTracks.size() < 1) {

        }
        topTracks = getTopTrackArtist(artist);
    }

    for (LastFMArtistTopTrack track : topTracks) {
        MediaFile requested = null;
        List<MediaFile> searchResult = getSearchresult(track.getArtistname(), track.getSongname(), userGroupId);

        if (searchResult != null && searchResult.size() != 0) {
            requested = mediaFileService.getMediaFile(searchResult.get(0).getId(), userGroupId);
        }
        if (requested != null) {
            if (requested.getRank() != track.getRank()) {
                requested.setRank(track.getRank());
                mediaFileDao.createOrUpdateMediaFile(requested);
            }
            hs.add(requested);

            if (hs.size() > limit) {
                break;
            }
        }
    }
    // Filter out duplicates
    topTrackSongs.clear();
    topTrackSongs.addAll(hs);

    // Sort by Rank 
    Comparator<MediaFile> comparator = new MediaFileRankComparator();
    Set<MediaFile> set = new TreeSet<MediaFile>(comparator);
    set.addAll(topTrackSongs);
    topTrackSongs = new ArrayList<MediaFile>(set);

    return topTrackSongs;
}

From source file:org.apache.solr.handler.component.FacetComponent.java

@Override
public void prepare(ResponseBuilder rb) throws IOException {
    if (rb.req.getParams().getBool(FacetParams.FACET, false)) {
        rb.setNeedDocSet(true);// w  w  w .  j av a2  s  .c o m
        rb.doFacets = true;

        // Deduplicate facet params
        ModifiableSolrParams params = new ModifiableSolrParams();
        SolrParams origParams = rb.req.getParams();
        Iterator<String> iter = origParams.getParameterNamesIterator();
        while (iter.hasNext()) {
            String paramName = iter.next();
            // Deduplicate the list with LinkedHashSet, but _only_ for facet params.
            if (!paramName.startsWith(FacetParams.FACET)) {
                params.add(paramName, origParams.getParams(paramName));
                continue;
            }
            HashSet<String> deDupe = new LinkedHashSet<>(Arrays.asList(origParams.getParams(paramName)));
            params.add(paramName, deDupe.toArray(new String[deDupe.size()]));

        }
        rb.req.setParams(params);

        // Initialize context
        FacetContext.initContext(rb);
    }
}