Example usage for java.util HashSet contains

List of usage examples for java.util HashSet contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:mase.spec.SafeHybridExchanger.java

@Override
protected void mergeProcess(EvolutionState state) {
    super.mergeProcess(state);

    // add foreign individuals to the populations outside the stability threshold
    for (MetaPopulation mp : metaPops) {
        if (mp.age >= stabilityTime) {
            HashSet<MetaPopulation> current = new HashSet<MetaPopulation>();
            for (MetaPopulation mpf : metaPops) {
                if (mp != mpf && mpf.age >= stabilityTime) {
                    current.add(mpf);/*from  w ww .ja v  a2 s. c o m*/
                }
            }
            Iterator<Foreign> iter = mp.foreigns.iterator();
            while (iter.hasNext()) {
                Foreign next = iter.next();
                if (current.contains(next.origin)) {
                    current.remove(next.origin);
                } else {
                    iter.remove();
                }
            }
            for (MetaPopulation mpf : current) {
                mp.foreigns.add(new Foreign(mpf));
            }
        }
    }
}

From source file:com.liveramp.hank.storage.curly.AbstractCurlyPartitionUpdater.java

private Set<DomainVersion> detectCachedVersions(SortedSet<CueballFilePath> cueballCachedFiles,
        SortedSet<CurlyFilePath> curlyCachedFiles) throws IOException {
    // Record in a set all cached Cueball versions
    HashSet<Integer> cachedCueballVersions = new HashSet<Integer>();
    for (CueballFilePath cueballCachedFile : cueballCachedFiles) {
        cachedCueballVersions.add(cueballCachedFile.getVersion());
    }// w ww  .ja  v a 2s.  com
    // Compute cached Curly versions
    Set<DomainVersion> cachedVersions = new HashSet<DomainVersion>();
    for (CurlyFilePath curlyCachedFile : curlyCachedFiles) {
        // Check that the corresponding Cueball version is also cached
        if (cachedCueballVersions.contains(curlyCachedFile.getVersion())) {
            DomainVersion version = domain.getVersion(curlyCachedFile.getVersion());
            if (version != null) {
                cachedVersions.add(version);
            }
        }
    }
    return cachedVersions;
}

From source file:calliope.handler.post.AeseImportHandler.java

/**
 * Add a batch of annotations to the database
 * @param notes an array of annotation objects
 * @param clean if true remove old annotations for this docid
 * @throws AeseException //from  www.  j  a  v a2 s. co  m
 */
protected void addAnnotations(ArrayList<Annotation> notes, boolean clean) throws AeseException {
    String path = docID.get();
    Connection conn = Connector.getConnection();
    if (clean) {
        // remove all existing annotations for this document
        String[] docids = conn.listDocuments("annotations", path + "/.*");
        for (int i = 0; i < docids.length; i++)
            conn.removeFromDb("annotations", docids[i]);
    }
    // ensure that the annotations are all unique
    HashSet<String> unique = new HashSet<String>();
    String[] docids = conn.listDocuments("annotations", path + "/.*");
    for (int i = 0; i < docids.length; i++)
        unique.add(docids[i]);
    for (int i = 0; i < notes.size(); i++) {
        String docid = path + "/" + UUID.randomUUID().toString();
        while (unique.contains(docid))
            docid = path + "/" + UUID.randomUUID().toString();
        conn.putToDb("annotations", docid, notes.get(i).toString());
        unique.add(docid);
    }
}

From source file:controllers.ImageBrowser.java

public static void importAttributes(Project project, Path path, File file, boolean dataMode)
        throws IOException {
    if (!PermissionService.hasInheritedAccess(Security.getUser(), project,
            dataMode ? AccessType.EDIT_DATA_METADATA : AccessType.EDIT_ANALYSIS_METADATA))
        forbidden();/*w ww  . j a v a2  s.c o  m*/
    if (!PermissionService.userCanAccessPath(Security.getUser(), path))
        forbidden();

    DatabaseImage dbi = DatabaseImage.forPath(path);
    String data = FileUtils.readFileToString(file);

    Map<String, String> importedAttributes = ImportExportService.deserialzeAttributes(data);

    //remove all existing attributes
    //TODO rewrite this so that history is persisted
    List<ImageAttribute> existingAttributes = DatabaseImageService.attributesForImageAndMode(project, dbi,
            dataMode);
    for (ImageAttribute attr : existingAttributes) {
        if (attr.linkedAttribute != null) {
            attr.linkedAttribute.linkedAttribute = null;
            attr.linkedAttribute.save();
            attr.linkedAttribute = null;
        }
        attr.delete();
    }

    //if we're in analysis mode, we need to consider inherited attributes
    Map<String, List<ImageAttribute>> dataModeAttributes = DatabaseImageService
            .attributeMapForImageAndMode(project, dbi, !dataMode);
    HashSet<ImageAttribute> usedImageAttributes = new HashSet<ImageAttribute>();

    //get the imported attributes grouped by attributeName
    Map<String, List<String>> groupedAttributes = new HashMap<String, List<String>>();
    for (Entry<String, String> entry : importedAttributes.entrySet()) {
        if (!groupedAttributes.containsKey(entry.getKey()))
            groupedAttributes.put(entry.getKey(), new LinkedList<String>());
        groupedAttributes.get(entry.getKey()).add(entry.getValue());
    }
    for (Entry<String, List<String>> entry : groupedAttributes.entrySet()) {
        String attributeName = entry.getKey();
        for (String value : entry.getValue()) {
            List<ImageAttribute> existingAttributesForKey = dataModeAttributes.get(attributeName);
            ImageAttribute linkMe = null;
            if (dataModeAttributes.containsKey(attributeName)) {
                for (ImageAttribute existingAttr : existingAttributesForKey) {
                    if (!usedImageAttributes.contains(existingAttr)) {
                        linkMe = existingAttr;
                    }
                }
            }

            ImageAttribute newImageAttribute = dbi.addAttribute(project, attributeName, value, dataMode);
            if (linkMe != null) {
                usedImageAttributes.add(linkMe);
                newImageAttribute.linkedAttribute = linkMe;
                newImageAttribute.save();

                linkMe.linkedAttribute = newImageAttribute;
                linkMe.save();
            }
        }
    }

    jsonOk();
}

From source file:org.matsim.pt.analysis.RouteTimeDiagram.java

public void createGraph(final String filename, final TransitRoute route) {

    HashMap<Id, Integer> stopIndex = new HashMap<Id, Integer>();
    int idx = 0;/*w  w  w .ja  v a 2  s .co  m*/
    for (TransitRouteStop stop : route.getStops()) {
        stopIndex.put(stop.getStopFacility().getId(), idx);
        idx++;
    }

    HashSet<Id> vehicles = new HashSet<Id>();
    for (Departure dep : route.getDepartures().values()) {
        vehicles.add(dep.getVehicleId());
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    int numSeries = 0;
    double earliestTime = Double.POSITIVE_INFINITY;
    double latestTime = Double.NEGATIVE_INFINITY;

    for (Map.Entry<Id, List<Tuple<Id, Double>>> entry : this.positions.entrySet()) {
        if (vehicles.contains(entry.getKey())) {
            XYSeries series = new XYSeries("t", false, true);
            for (Tuple<Id, Double> pos : entry.getValue()) {
                Integer stopIdx = stopIndex.get(pos.getFirst());
                if (stopIdx != null) {
                    double time = pos.getSecond().doubleValue();
                    series.add(stopIdx.intValue(), time);
                    if (time < earliestTime) {
                        earliestTime = time;
                    }
                    if (time > latestTime) {
                        latestTime = time;
                    }
                }
            }
            dataset.addSeries(series);
            numSeries++;

        }
    }

    JFreeChart c = ChartFactory.createXYLineChart("Route-Time Diagram, Route = " + route.getId(), "stops",
            "time", dataset, PlotOrientation.VERTICAL, false, // legend?
            false, // tooltips?
            false // URLs?
    );
    c.setBackgroundPaint(new Color(1.0f, 1.0f, 1.0f, 1.0f));

    XYPlot p = (XYPlot) c.getPlot();

    p.getRangeAxis().setInverted(true);
    p.getRangeAxis().setRange(earliestTime, latestTime);
    XYItemRenderer renderer = p.getRenderer();
    for (int i = 0; i < numSeries; i++) {
        renderer.setSeriesPaint(i, Color.black);
    }

    try {
        ChartUtilities.saveChartAsPNG(new File(filename), c, 1024, 768, null, true, 9);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.parse.ParseRemoveOperation.java

@Override
public Object apply(Object oldValue, String key) {
    if (oldValue == null) {
        return new ArrayList<>();
    } else if (oldValue instanceof JSONArray) {
        ArrayList<Object> old = ParseFieldOperations.jsonArrayAsArrayList((JSONArray) oldValue);
        @SuppressWarnings("unchecked")
        ArrayList<Object> newValue = (ArrayList<Object>) this.apply(old, key);
        return new JSONArray(newValue);
    } else if (oldValue instanceof List) {
        ArrayList<Object> result = new ArrayList<>((List<?>) oldValue);
        result.removeAll(objects);//from   ww  w.j av a 2s .co  m

        // Remove the removed objects from "objects" -- the items remaining
        // should be ones that weren't removed by object equality.
        ArrayList<Object> objectsToBeRemoved = new ArrayList<>(objects);
        objectsToBeRemoved.removeAll(result);

        // Build up set of object IDs for any ParseObjects in the remaining objects-to-be-removed
        HashSet<String> objectIds = new HashSet<>();
        for (Object obj : objectsToBeRemoved) {
            if (obj instanceof ParseObject) {
                objectIds.add(((ParseObject) obj).getObjectId());
            }
        }

        // And iterate over "result" to see if any other ParseObjects need to be removed
        Iterator<Object> resultIterator = result.iterator();
        while (resultIterator.hasNext()) {
            Object obj = resultIterator.next();
            if (obj instanceof ParseObject && objectIds.contains(((ParseObject) obj).getObjectId())) {
                resultIterator.remove();
            }
        }
        return result;
    } else {
        throw new IllegalArgumentException("Operation is invalid after previous operation.");
    }
}

From source file:edu.upenn.mkse212.pennbook.server.FriendshipServiceImpl.java

public List<Map<String, String>> getOnlineFriendships(String userId) {
    UserServiceImpl userServ = UserServiceImpl.getServerInstance();
    userServ.setUserPresence(userId);/*  w w w .  j  av  a2  s. com*/
    HashSet<String> onlineUserIds = userServ.getPresentUsers();
    List<Map<String, String>> friendships = getFriendships(userId);
    List<Map<String, String>> friendsOnline = new ArrayList<Map<String, String>>();
    for (Map<String, String> friendship : friendships) {
        //System.out.println(friendship);
        String friendId = friendship.get(FRIEND_USER_ID_ATTR);
        if (onlineUserIds.contains(friendId))
            friendsOnline.add(friendship);
    }
    return friendsOnline;
}

From source file:com.yosanai.java.aws.console.DefaultAWSConnectionProvider.java

@Override
public String getInstanceDetails(String property, String separator, String... instanceIds) throws Exception {
    StringBuilder ret = new StringBuilder();
    List<String> instances = getInstances(null, false, instanceIds);
    if (!instances.isEmpty()) {
        HashSet<String> instanceIdsSet = new HashSet<String>(instances);
        DescribeInstancesResult result = getConnection().describeInstances();
        for (Reservation reservation : result.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                if (instanceIdsSet.contains(instance.getInstanceId())) {
                    String value = getInstanceDetail(property, instance);
                    if (StringUtils.isNotBlank(value)) {
                        if (0 < ret.length()) {
                            ret.append(separator);
                        }/*from www  .j av  a  2 s . c  om*/
                        ret.append(value);
                    }
                }
            }
        }
    }
    return ret.toString();
}

From source file:org.ng200.openolympus.services.TestingService.java

@Autowired
public TestingService(final SolutionService solutionService, final SolutionRepository solutionRepository,
        final UserRepository userRepository, final VerdictRepository verdictRepository,
        final StorageService storageService, final TaskContainerCache taskContainerCache) {
    super();//from  w w w .j  a  v  a  2  s  . c o  m
    this.verdictRepository = verdictRepository;
    this.taskContainerCache = taskContainerCache;

    this.dataProvider.setParameter("storageService", storageService);

    final HashSet<Verdict> alreadyScheduledJobs = new HashSet<>();
    this.verdictCheckSchedulingExecutorService.scheduleAtFixedRate(() -> {
        this.logInAsSystem();
        solutionService.getPendingVerdicts().stream()
                .filter((verdict) -> !alreadyScheduledJobs.contains(verdict)).sorted((l, r) -> {
                    if (l.isViewableWhenContestRunning() != r.isViewableWhenContestRunning()) {
                        // Schedule base tests first
                        return Boolean.compare(r.isViewableWhenContestRunning(),
                                l.isViewableWhenContestRunning());
                    }
                    return Long.compare(l.getId(), r.getId());
                }).forEach((verdict) -> {
                    alreadyScheduledJobs.add(verdict);
                    this.processVerdict(verdict);
                });
    }, 0, 100, TimeUnit.MILLISECONDS);
}

From source file:com.compomics.util.experiment.identification.psm_scoring.psm_scores.HyperScore.java

/**
 * Returns the hyperscore.//from  w w w. j  a v  a2  s.  c om
 *
 * @param peptide the peptide of interest
 * @param spectrum the spectrum of interest
 * @param annotationSettings the general spectrum annotation settings
 * @param specificAnnotationSettings the annotation settings specific to
 * this PSM
 * @param ionMatches the ion matches obtained from spectrum annotation
 *
 * @return the score of the match
 */
public double getScore(Peptide peptide, MSnSpectrum spectrum, AnnotationSettings annotationSettings,
        SpecificAnnotationSettings specificAnnotationSettings, ArrayList<IonMatch> ionMatches) {

    boolean peakMatched = false;
    Double coveredIntensity = 0.0;
    HashSet<Double> coveredMz = new HashSet<Double>(2);
    for (IonMatch ionMatch : ionMatches) {
        Ion ion = ionMatch.ion;
        Peak peak = ionMatch.peak;
        if (!coveredMz.contains(peak.mz)) {
            coveredIntensity += peak.intensity;
            coveredMz.add(peak.mz);
        }
        if (ion.getType() == Ion.IonType.PEPTIDE_FRAGMENT_ION) {
            PeptideFragmentIon peptideFragmentIon = (PeptideFragmentIon) ion;
            if (peptideFragmentIon.hasNeutralLosses() || peptideFragmentIon.getNumber() < 2) {
            } else {
                peakMatched = true;
            }
        }
    }
    if (!peakMatched) {
        return 0.0;
    }

    SpectrumIndex spectrumIndex = new SpectrumIndex();
    spectrumIndex = (SpectrumIndex) spectrum.getUrParam(spectrumIndex);
    if (spectrumIndex == null) {
        // Create new index
        spectrumIndex = new SpectrumIndex(spectrum.getPeakMap(),
                spectrum.getIntensityLimit(annotationSettings.getAnnotationIntensityLimit()),
                annotationSettings.getFragmentIonAccuracy(), annotationSettings.isFragmentIonPpm());
        spectrum.addUrParam(spectrumIndex);
    }

    Double totalIntensity = spectrumIndex.getTotalIntensity() - coveredIntensity;

    double xCorr = 0;
    HashSet<Integer> ionsForward = new HashSet<Integer>(1);
    HashSet<Integer> ionsRewind = new HashSet<Integer>(1);
    HashSet<Double> accountedFor = new HashSet<Double>(ionMatches.size());
    for (IonMatch ionMatch : ionMatches) {
        Peak peakI = ionMatch.peak;
        Double mz = peakI.mz;
        Ion ion = ionMatch.ion;
        if (ion.getType() == Ion.IonType.PEPTIDE_FRAGMENT_ION && !ion.hasNeutralLosses()
                && !accountedFor.contains(mz)) {
            PeptideFragmentIon peptideFragmentIon = (PeptideFragmentIon) ion;
            int number = peptideFragmentIon.getNumber();
            if (number > 1) {
                accountedFor.add(mz);
                Double x0I = peakI.intensity / totalIntensity;
                xCorr += x0I;
                if (ion.getType() == Ion.IonType.PEPTIDE_FRAGMENT_ION && !ion.hasNeutralLosses()) {
                    if (ion.getSubType() == PeptideFragmentIon.X_ION
                            || ion.getSubType() == PeptideFragmentIon.Y_ION
                            || ion.getSubType() == PeptideFragmentIon.Z_ION) {
                        ionsForward.add(number);
                    } else if (ion.getSubType() == PeptideFragmentIon.A_ION
                            || ion.getSubType() == PeptideFragmentIon.B_ION
                            || ion.getSubType() == PeptideFragmentIon.C_ION) {
                        ionsRewind.add(number);
                    }
                }
            }
        }
    }
    int nForward = ionsForward.size() / (Math.max(specificAnnotationSettings.getPrecursorCharge() - 1, 1));
    int nRewind = ionsRewind.size() / (Math.max(specificAnnotationSettings.getPrecursorCharge() - 1, 1));
    nForward = nForward > 20 ? 20 : nForward;
    nRewind = nRewind > 20 ? 20 : nRewind;
    long forwardFactorial = BasicMathFunctions.factorial(nForward);
    long rewindFactorial = BasicMathFunctions.factorial(nRewind);
    return xCorr * forwardFactorial * rewindFactorial;
}