Example usage for java.util ArrayList contains

List of usage examples for java.util ArrayList contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this list contains the specified element.

Usage

From source file:org.loklak.harvester.TwitterScraper.java

/**
 * Filter Posts(here tweets) according to values.
 *   image: filter tweets with images, neglect 'tweets without images'
 *   video: filter tweets also having video and other values like image. For only value as video,
 *          tweets with videos are filtered in prepareUrl() method
 *//*from w  w  w . j  a v  a2  s  . c  o  m*/
private static boolean filterPosts(ArrayList<String> filterList, Map<String, prop> props, Set<String> videos,
        Set<String> images) {
    Matcher matchVideo1;
    Matcher matchVideo2;
    Pattern[] videoUrlPatterns = { Pattern.compile("youtu.be\\/[0-9A-z]+"),
            Pattern.compile("youtube.com\\/watch?v=[0-9A-z]+") };

    // Filter tweets with videos and others
    if (filterList.contains("video") && filterList.size() > 1) {
        matchVideo1 = videoUrlPatterns[0].matcher(props.get("tweettext").value);
        matchVideo2 = videoUrlPatterns[1].matcher(props.get("tweettext").value);

        if (!matchVideo1.find() && !matchVideo2.find() && videos.size() < 1) {
            return false;
        }
    }

    // Filter tweets with images
    if (filterList.contains("image") && images.size() < 1) {
        return false;
    }

    //TODO: Add more filters

    return true;
}

From source file:mitm.common.security.ca.CSVRequestConverter.java

private void readHeader(CSVReader reader) throws IOException, RequestConverterException {
    String[] headers = reader.readNext();

    if (headers == null) {
        throw new IOException("No header found.");
    }//from  w w  w.j a v  a 2  s  . c om

    ArrayList<Column> columns = new ArrayList<Column>();

    for (String header : headers) {
        header = MiscStringUtils.restrictLength(header, MAX_COLUMN_NAME_LENGTH, true);

        Column column = getColumn(header);

        if (column == null) {
            throw new RequestConverterException("There is no column named "
                    + MiscStringUtils.toAscii(MiscStringUtils.removeControlChars(header)));
        }

        if (columns.contains(column)) {
            throw new RequestConverterException("Column " + column + " is already used.");
        }

        columns.add(column);
    }

    columnOrder = new Column[columns.size()];

    columnOrder = columns.toArray(columnOrder);
}

From source file:de.dfki.mmf.planner.modalityplanner.score.UserInfoScorer.java

/**
 * avoid using a specific modality if possible
 * @param modalityTypeList/*from ww  w  . ja  va2 s.c om*/
 * @param modalityRepresentation
 */
public void avoidCertainModalityUsage(ArrayList<ModalityType> modalityTypeList,
        ModalityRepresentation modalityRepresentation) {
    for (PhraseComponent argument : modalityRepresentation.getPhraseComponents()) {
        if (argument.getPowerSetModality() != null
                && !argument.getPowerSetModality().getModalitySet().isEmpty()) {
            //go over set of currently chosen modalities and check if the modality which should be avoided is part of the set
            for (ModalityType powerSetModalityType : argument.getPowerSetModality().getModalitySet()) {
                if (modalityTypeList.contains(powerSetModalityType)) {
                    //check if current argument can be expressed with other modalities, if so: softscore-1
                    for (ModalityType mapModalityType : argument.getModalityRepresentationMap().keySet()) {
                        if (!modalityTypeList.contains(mapModalityType)
                                && argument.getModalityRepresentationMap().get(mapModalityType) > 0.5) {
                            avoidSpecificModScore -= 1;
                        }
                    }
                }
            }
            //worst case: all modalities which should be avoided are actually used
            maxReducedScore -= modalityTypeList.size();
        }
    }
}

From source file:ELK.ELKController.java

private ArrayList<String> extractTags(String tags) {

    // probably more efficent ways to do this.
    ///* ww w. ja  v a 2s.co  m*/
    // whitespace = re.compile('\s')

    tags = tags.replaceAll("\\s", "");
    String tagArray[] = tags.split(",");

    // let's clean it up, removing the empty string and removing dups
    ArrayList<String> cleaned = new ArrayList<String>();
    for (String tag : tagArray) {
        if (!tag.equals("") && !cleaned.contains(tag)) {
            cleaned.add(tag);
        }
    }

    return cleaned;
}

From source file:Interface.CommunityAdminWorkArea.BestCitizen.java

private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalculateActionPerformed
    // TODO add your handling code here:
    Date toDate1 = jDateChooser1.getDate();
    Date toDate2 = jDateChooser2.getDate();
    if ((toDate1 == null) || (toDate2 == null)) {
        JOptionPane.showMessageDialog(null, "Invalid date..Kindly enter valid date.");
        return;//from ww  w  .  j  a v a  2s.c  o m

    }

    long fromDate = (jDateChooser1.getDate().getTime()) / (1000 * 60 * 60 * 24);
    long toDate = (jDateChooser2.getDate().getTime()) / (1000 * 60 * 60 * 24);
    //String citizenRewards = null;

    ArrayList<CitizenEmployee> citizenEmployeeList = new ArrayList<>();

    for (WorkRequest request : organization.getWorkQueue().getWorkRequestList()) {

        long requestDate = (request.getRequestDate().getTime()) / (1000 * 60 * 60 * 24);

        if ((requestDate >= fromDate) && (requestDate <= toDate)) {

            Employee ee = request.getSender().getEmployee();
            if (ee instanceof CitizenEmployee) {
                CitizenEmployee c = (CitizenEmployee) ee;
                if (!citizenEmployeeList.contains(c)) {
                    c.calculateTotalRewardPointsForCitizen();
                    citizenEmployeeList.add(c);
                }
            }
        }
        //            else{
        //
        //                JOptionPane.showMessageDialog(null, "There are no records for this search criteria.");
        //            }

    }

    if (citizenEmployeeList.isEmpty()) {
        JOptionPane.showMessageDialog(null, "There are no records for this search criteria.");
    }

    ArrayList<CitizenEmployee> citizenEmployee = calculateTopThreeCitizenByRewardPoints(citizenEmployeeList);

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.setValue(citizenEmployee.get(0).getCurrentRewardPoints(), "Citizens",
            citizenEmployee.get(0).getName());
    dataset.setValue(citizenEmployee.get(1).getCurrentRewardPoints(), "Citizens",
            citizenEmployee.get(1).getName());
    dataset.setValue(citizenEmployee.get(2).getCurrentRewardPoints(), "Citizens",
            citizenEmployee.get(2).getName());

    JFreeChart chart = ChartFactory.createBarChart3D("Types of food collected", "Top 3 citizen",
            "Number of reward points", dataset, PlotOrientation.VERTICAL, false, true, false);
    CategoryPlot plot = chart.getCategoryPlot();
    plot.setRangeGridlinePaint(Color.BLUE);
    ChartFrame frame = new ChartFrame("Bar Chart for Types of food collected", chart);
    frame.setVisible(true);
    frame.setSize(450, 350);

}

From source file:fr.cirad.mgdb.exporting.markeroriented.EigenstratExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs,
        ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms,
        int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    // long before = System.currentTimeMillis();

    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);
    File snpFile = null;/*from  w  w  w . j  a  v a  2 s  .c om*/

    try {
        snpFile = File.createTempFile("snpFile", "");
        FileWriter snpFileWriter = new FileWriter(snpFile);

        ZipOutputStream zos = new ZipOutputStream(outputStream);
        if (ByteArrayOutputStream.class.isAssignableFrom(outputStream.getClass()))
            zos.setLevel(ZipOutputStream.STORED);

        if (readyToExportFiles != null)
            for (String readyToExportFile : readyToExportFiles.keySet()) {
                zos.putNextEntry(new ZipEntry(readyToExportFile));
                InputStream inputStream = readyToExportFiles.get(readyToExportFile);
                byte[] dataBlock = new byte[1024];
                int count = inputStream.read(dataBlock, 0, 1024);
                while (count != -1) {
                    zos.write(dataBlock, 0, count);
                    count = inputStream.read(dataBlock, 0, 1024);
                }
            }

        MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
        int markerCount = markerCursor.count();

        List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs);

        ArrayList<String> individualList = new ArrayList<String>();
        StringBuffer indFileContents = new StringBuffer();

        for (int i = 0; i < sampleIDs.size(); i++) {
            Individual individual = individuals.get(i);
            if (!individualList.contains(individual.getId())) {
                individualList.add(individual.getId());
                indFileContents
                        .append(individual.getId() + "\t" + getIndividualGenderCode(sModule, individual.getId())
                                + "\t" + (individual.getPopulation() == null ? "." : individual.getPopulation())
                                + LINE_SEPARATOR);
            }
        }

        String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals";
        zos.putNextEntry(new ZipEntry(exportName + ".ind"));
        zos.write(indFileContents.toString().getBytes());

        zos.putNextEntry(new ZipEntry(exportName + ".eigenstratgeno"));

        int avgObjSize = (Integer) mongoTemplate
                .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats()
                .get("avgObjSize");
        int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;
        short nProgress = 0, nPreviousProgress = 0;
        long nLoadedMarkerCount = 0;

        while (markerCursor.hasNext()) {
            int nLoadedMarkerCountInLoop = 0;
            Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>();
            boolean fStartingNewChunk = true;
            markerCursor.batchSize(nChunkSize);
            while (markerCursor.hasNext()
                    && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) {
                DBObject exportVariant = markerCursor.next();
                DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
                markerChromosomalPositions.put((Comparable) exportVariant.get("_id"),
                        refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":"
                                + refPos.get(ReferencePosition.FIELDNAME_START_SITE));
                nLoadedMarkerCountInLoop++;
                fStartingNewChunk = false;
            }

            List<Comparable> currentMarkers = new ArrayList<Comparable>(markerChromosomalPositions.keySet());
            LinkedHashMap<VariantData, Collection<VariantRunData>> variantsAndRuns = MgdbDao.getSampleGenotypes(
                    mongoTemplate, sampleIDs, currentMarkers, true,
                    null /*new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_SEQUENCE).and(new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_START_SITE))*/); // query mongo db for matching genotypes
            for (VariantData variant : variantsAndRuns.keySet()) // read data and write results into temporary files (one per sample)
            {
                Comparable variantId = variant.getId();

                List<String> chromAndPos = Helper.split(markerChromosomalPositions.get(variantId), ":");
                if (chromAndPos.size() == 0)
                    LOG.warn("Chromosomal position not found for marker " + variantId);
                // LOG.debug(marker + "\t" + (chromAndPos.length == 0 ? "0" : chromAndPos[0]) + "\t" + 0 + "\t" + (chromAndPos.length == 0 ? 0l : Long.parseLong(chromAndPos[1])) + LINE_SEPARATOR);
                if (markerSynonyms != null) {
                    Comparable syn = markerSynonyms.get(variantId);
                    if (syn != null)
                        variantId = syn;
                }
                snpFileWriter.write(variantId + "\t" + (chromAndPos.size() == 0 ? "0" : chromAndPos.get(0))
                        + "\t" + 0 + "\t" + (chromAndPos.size() == 0 ? 0l : Long.parseLong(chromAndPos.get(1)))
                        + LINE_SEPARATOR);

                Map<String, List<String>> individualGenotypes = new LinkedHashMap<String, List<String>>();
                Collection<VariantRunData> runs = variantsAndRuns.get(variant);
                if (runs != null)
                    for (VariantRunData run : runs)
                        for (Integer sampleIndex : run.getSampleGenotypes().keySet()) {
                            SampleGenotype sampleGenotype = run.getSampleGenotypes().get(sampleIndex);
                            String individualId = individuals
                                    .get(sampleIDs
                                            .indexOf(new SampleId(run.getId().getProjectId(), sampleIndex)))
                                    .getId();

                            Integer gq = null;
                            try {
                                gq = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_GQ);
                            } catch (Exception ignored) {
                            }
                            if (gq != null && gq < nMinimumGenotypeQuality)
                                continue;

                            Integer dp = null;
                            try {
                                dp = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_DP);
                            } catch (Exception ignored) {
                            }
                            if (dp != null && dp < nMinimumReadDepth)
                                continue;

                            String gtCode = sampleGenotype.getCode();
                            List<String> storedIndividualGenotypes = individualGenotypes.get(individualId);
                            if (storedIndividualGenotypes == null) {
                                storedIndividualGenotypes = new ArrayList<String>();
                                individualGenotypes.put(individualId, storedIndividualGenotypes);
                            }
                            storedIndividualGenotypes.add(gtCode);
                        }

                for (int j = 0; j < individualList
                        .size(); j++ /* we use this list because it has the proper ordering*/) {
                    String individualId = individualList.get(j);
                    List<String> genotypes = individualGenotypes.get(individualId);
                    HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes
                    int highestGenotypeCount = 0;
                    String mostFrequentGenotype = null;
                    if (genotypes != null)
                        for (String genotype : genotypes) {
                            if (genotype.length() == 0)
                                continue; /* skip missing genotypes */

                            int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                            if (gtCount > highestGenotypeCount) {
                                highestGenotypeCount = gtCount;
                                mostFrequentGenotype = genotype;
                            }
                            genotypeCounts.put(genotype, gtCount);
                        }

                    List<String> alleles = mostFrequentGenotype == null ? new ArrayList<String>()
                            : variant.getAllelesFromGenotypeCode(mostFrequentGenotype);

                    int nOutputCode = 0;
                    if (mostFrequentGenotype == null)
                        nOutputCode = 9;
                    else
                        for (String all : Helper.split(mostFrequentGenotype, "/"))
                            if ("0".equals(all))
                                nOutputCode++;
                    if (j == 0 && variant.getKnownAlleleList().size() > 2)
                        warningFileWriter.write("- Variant " + variant.getId()
                                + " is multi-allelic. Make sure Eigenstrat genotype encoding specifications are suitable for you.\n");
                    zos.write(("" + nOutputCode).getBytes());

                    if (genotypeCounts.size() > 1 || alleles.size() > 2) {
                        if (genotypeCounts.size() > 1)
                            warningFileWriter.write("- Dissimilar genotypes found for variant "
                                    + (variantId == null ? variant.getId() : variantId) + ", individual "
                                    + individualId + ". Exporting most frequent: " + nOutputCode + "\n");
                        if (alleles.size() > 2)
                            warningFileWriter.write("- More than 2 alleles found for variant "
                                    + (variantId == null ? variant.getId() : variantId) + ", individual "
                                    + individualId + ". Exporting only the first 2 alleles.\n");
                    }
                }
                zos.write((LINE_SEPARATOR).getBytes());
            }

            if (progress.hasAborted())
                return;

            nLoadedMarkerCount += nLoadedMarkerCountInLoop;
            nProgress = (short) (nLoadedMarkerCount * 100 / markerCount);
            if (nProgress > nPreviousProgress) {
                // if (nProgress%5 == 0)
                //    LOG.info("============= exportData: " + nProgress + "% =============" + (System.currentTimeMillis() - before)/1000 + "s");
                progress.setCurrentStepProgress(nProgress);
                nPreviousProgress = nProgress;
            }
        }

        snpFileWriter.close();
        zos.putNextEntry(new ZipEntry(exportName + ".snp"));
        BufferedReader in = new BufferedReader(new FileReader(snpFile));
        String sLine;
        while ((sLine = in.readLine()) != null)
            zos.write((sLine + "\n").getBytes());
        in.close();

        warningFileWriter.close();
        if (warningFile.length() > 0) {
            zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
            int nWarningCount = 0;
            in = new BufferedReader(new FileReader(warningFile));
            while ((sLine = in.readLine()) != null) {
                zos.write((sLine + "\n").getBytes());
                nWarningCount++;
            }
            LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
            in.close();
        }
        warningFile.delete();

        zos.close();
        progress.setCurrentStepProgress((short) 100);
    } finally {
        if (snpFile != null && snpFile.exists())
            snpFile.delete();
    }
}

From source file:com.sec.ose.osi.ui.frm.main.report.project.JListProjectWithPopup.java

@SuppressWarnings("deprecation")
private void deleteSelectedItems() {
    Object[] selectedItems = this.getSelectedValues();
    log.debug("deleteSelectedItems: num: " + selectedItems.length);

    if (selectedItems == null || selectedItems.length <= 0)
        return;//from  www.  j a v  a  2s. c o  m

    log.debug("try to delete: " + selectedItems);
    ProjectListModel selectedModel = this.getProjectListModel();

    ArrayList<String> deleteProjectNames = new ArrayList<String>();

    for (int i = 0; i < selectedItems.length; i++) {
        deleteProjectNames.add(selectedItems[i].toString());
        boolean refresh = false;
        if (i == selectedItems.length - 1)
            refresh = true;
        selectedModel.removeElement(selectedItems[i], refresh);
    }

    Collection<OSIProjectInfo> allManagedprojectList = OSIProjectInfoMgr.getInstance().getManagedProjectInfo()
            .getProjects();

    for (OSIProjectInfo xProjectInfo : allManagedprojectList) {
        if (deleteProjectNames.contains(xProjectInfo.getProjectName())) {
            xProjectInfo.setManaged(false);
            log.debug("delected: " + xProjectInfo.getProjectName());
        }
    }
    OSIProjectInfoMgr.getInstance().rebuildManagedProjectInfo();

}

From source file:info.savestate.saveybot.JSONFileManipulator.java

public String nameList(boolean largeResponse) {
    JSONArray json = getJSON();/*from  ww  w.j a v  a2s.  c o m*/
    ArrayList<String> names = new ArrayList<>();
    for (int i = 0; i < json.length(); i++) {
        JSONObject savestate = json.getJSONObject(i);
        String name = savestate.getString("name");
        if (!names.contains(name))
            names.add(name);
    }
    if (largeResponse) {
        StringBuilder sb = new StringBuilder();
        names.stream().forEach((String name) -> {
            sb.append(name).append(", ");
        });
        String returnString = sb.toString();
        return "SaveyBot's personal dongs!! :D :D :D/ : "
                + returnString.substring(0, returnString.length() - 2);
    } else {
        return "SaveyBot has " + names.size() + " personal dongs!! :D :D :D/";
    }
}

From source file:gr.iit.demokritos.cru.cps.ai.ComputationalCreativityMetrics.java

public double AvgSemDist(Set<String> top) {
    float dist = 0;
    int i = 0;/*  w  w  w.j av  a 2s.  c  o  m*/
    ArrayList<String> examined = new ArrayList<String>();
    if (language.equalsIgnoreCase("el")) {
        for (String key : top) {
            for (String other : top) {
                if (!key.equalsIgnoreCase(other)) {
                    if (!key.equalsIgnoreCase("") && !other.equalsIgnoreCase("") && !examined.contains(other)) {
                        dist += wnel.getDistance(key, other);
                        i++;
                    }
                    // System.out.println(key + " " + other + " " + wnel.getDistance(key, other));
                }
            }
            examined.add(key);
        }
    } else if (language.equalsIgnoreCase("de")) {
        for (String key : top) {
            for (String other : top) {
                // System.out.println(key+" "+other+" "+pos+" ");
                if (!key.equalsIgnoreCase(other) && !examined.contains(other)) {
                    dist += wnde.getDistance(key, other);
                    i++;
                }
            }
            examined.add(key);
        }
    } else {
        for (String key : top) {
            String pos = wn.getCommonPos(key);
            for (String other : top) {
                if (!key.equalsIgnoreCase(other) && pos != null && !examined.contains(other)) {
                    dist += wn.getDistance(key, other);
                    //System.out.println(dist+" "+top.size());
                    i++;
                }
            }
            //System.out.println("examined "+key);
            examined.add(key);
        }
        //System.out.println(i);
    }
    //get the distance of one term to every other term in the document
    if (dist == 0) {
        return 0;
    }
    return dist / i;
}

From source file:Interface.CommunityAdminWorkArea.BestRestaurant.java

private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalculateActionPerformed
    // TODO add your handling code here:

    Date toDate1 = jDateChooser1.getDate();
    Date toDate2 = jDateChooser2.getDate();
    if ((toDate1 == null) || (toDate2 == null)) {
        JOptionPane.showMessageDialog(null, "Invalid date..Kindly enter valid date.");
        return;// w w w .  j  av  a2 s  . c  o m
    }

    long fromDate = (jDateChooser1.getDate().getTime()) / (1000 * 60 * 60 * 24);
    long toDate = (jDateChooser2.getDate().getTime()) / (1000 * 60 * 60 * 24);
    //String citizenRewards = null;
    ArrayList<RestaurantEmployee> restaurantEmployeeList = new ArrayList<>();

    for (WorkRequest request : organization.getWorkQueue().getWorkRequestList()) {

        long requestDate = (request.getRequestDate().getTime()) / (1000 * 60 * 60 * 24);

        if ((requestDate >= fromDate) && (requestDate <= toDate)) {

            Employee ee = request.getSender().getEmployee();
            if (ee instanceof RestaurantEmployee) {
                RestaurantEmployee c = (RestaurantEmployee) ee;
                if (!restaurantEmployeeList.contains(c)) {
                    c.calculateTotalRewardPointsForCitizen();
                    restaurantEmployeeList.add(c);
                }
            }
        }
        //            else{
        //
        //                JOptionPane.showMessageDialog(null, "There are no records for this search criteria.");
        //            }

    }

    if (restaurantEmployeeList.isEmpty()) {
        JOptionPane.showMessageDialog(null, "There are no records for this search criteria.");
    }

    ArrayList<RestaurantEmployee> restaurantEmployee = calculateTopThreeRestaurantByRewardPoints(
            restaurantEmployeeList);

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.setValue(restaurantEmployee.get(0).getCurrentRewardPoints(), "Commercial body",
            restaurantEmployee.get(0).getName());
    dataset.setValue(restaurantEmployee.get(1).getCurrentRewardPoints(), "Commercial body",
            restaurantEmployee.get(1).getName());
    dataset.setValue(restaurantEmployee.get(2).getCurrentRewardPoints(), "Commercial body",
            restaurantEmployee.get(2).getName());

    JFreeChart chart = ChartFactory.createBarChart3D("Types of food collected", "Top 3 Restaurant",
            "Number of reward points", dataset, PlotOrientation.VERTICAL, false, true, false);
    CategoryPlot plot = chart.getCategoryPlot();
    plot.setRangeGridlinePaint(Color.BLUE);
    ChartFrame frame = new ChartFrame("Bar Chart for best Restaurant", chart);
    frame.setVisible(true);
    frame.setSize(450, 350);
}