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:de.tudarmstadt.tk.statistics.importer.ExternalResultsReader.java

public static List<SampleData> splitData(SampleData data, StatsConfig config) {

    List<SampleData> splitted = new ArrayList<SampleData>();

    //Use lists instead of sets to maintain order of model metadata
    ArrayList<String> featureSets = new ArrayList<String>();
    ArrayList<String> classifiers = new ArrayList<String>();
    for (Pair<String, String> metadata : data.getModelMetadata()) {
        if (!classifiers.contains(metadata.getLeft())) {
            classifiers.add(metadata.getLeft());
        }/* ww  w  . j a  va 2 s .co m*/
        if (!featureSets.contains(metadata.getRight())) {
            featureSets.add(metadata.getRight());
        }
    }

    //Only separate data if there's more than one independent variable
    if (!(featureSets.size() > 1 && classifiers.size() > 1)) {
        splitted.add(data);
        return splitted;
    }

    List<String> it = (config
            .getFixIndependentVariable() == StatsConfigConstants.INDEPENDENT_VARIABLES_VALUES.Classifier)
                    ? classifiers
                    : featureSets;
    for (String fixed : it) {
        ArrayList<Pair<String, String>> modelMetadata = new ArrayList<Pair<String, String>>();
        HashMap<String, ArrayList<ArrayList<Double>>> samples = new HashMap<String, ArrayList<ArrayList<Double>>>();
        HashMap<String, ArrayList<Double>> sampleAverages = new HashMap<String, ArrayList<Double>>();
        for (int i = 0; i < data.getModelMetadata().size(); i++) {
            Pair<String, String> model = data.getModelMetadata().get(i);
            boolean eq = (config
                    .getFixIndependentVariable() == StatsConfigConstants.INDEPENDENT_VARIABLES_VALUES.Classifier)
                            ? model.getLeft().equals(fixed)
                            : model.getRight().equals(fixed);
            if (eq) {
                modelMetadata.add(model);
                for (String measure : data.getSamples().keySet()) {
                    if (!samples.containsKey(measure)) {
                        samples.put(measure, new ArrayList<ArrayList<Double>>());
                        sampleAverages.put(measure, new ArrayList<Double>());
                    }
                    samples.get(measure).add(data.getSamples().get(measure).get(i));
                    sampleAverages.get(measure).add(data.getSamplesAverage().get(measure).get(i));
                }
            }
        }
        ArrayList<Pair<String, String>> baselineModelData = new ArrayList<Pair<String, String>>();
        if (data.isBaselineEvaluation()) {
            Pair<String, String> baselineModel = null;
            for (int i = 0; i < data.getBaselineModelMetadata().size(); i++) {
                boolean eq = (config
                        .getFixIndependentVariable() == StatsConfigConstants.INDEPENDENT_VARIABLES_VALUES.Classifier)
                                ? data.getBaselineModelMetadata().get(i).getLeft().equals(fixed)
                                : data.getBaselineModelMetadata().get(i).getRight().equals(fixed);
                if (eq) {
                    baselineModel = data.getBaselineModelMetadata().get(i);
                    break;
                }
            }
            if (baselineModel != null) {
                baselineModelData.add(baselineModel);
                int modelIndex = modelMetadata.indexOf(baselineModel);
                modelMetadata.remove(modelIndex);
                modelMetadata.add(0, baselineModel);
                for (String measure : data.getSamples().keySet()) {
                    ArrayList<Double> s = samples.get(measure).get(modelIndex);
                    samples.get(measure).remove(modelIndex);
                    samples.get(measure).add(0, s);
                    double a = sampleAverages.get(measure).get(modelIndex);
                    sampleAverages.get(measure).remove(modelIndex);
                    sampleAverages.get(measure).add(0, a);
                }
            } else {
                logger.log(Level.ERROR,
                        "Missing baseline model! Please check if baseline indicators are set correctly in the input file, and if they correspond correctly to the fixIndependentVariable property in the configuration. In case of both varying feature sets and classifiers, baseline indicators have to be set multiple times.");
                System.err.println(
                        "Missing baseline model! Please check if baseline indicators are set correctly in the input file, and if they correspond correctly to the fixIndependentVariable property in the configuration. In case of both varying feature sets and classifiers, baseline indicators have to be set multiple times.");
                System.exit(1);
            }
        }
        SampleData newData = new SampleData(null, samples, sampleAverages, data.getDatasetNames(),
                modelMetadata, baselineModelData, data.getPipelineType(), data.getnFolds(),
                data.getnRepetitions());
        splitted.add(newData);
    }
    return splitted;
}

From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java

private static void dirListing(File source, ArrayList<File> list_to_copy) throws IOException {
    ArrayList<File> bucket = new ArrayList<File>();
    ArrayList<File> next_bucket = new ArrayList<File>();
    bucket.add(source);/* w ww  .  j av  a  2  s  .c o  m*/

    File bucket_item;
    File[] list_content;

    while (true) {
        for (int pos_b = 0; pos_b < bucket.size(); pos_b++) {
            bucket_item = bucket.get(pos_b).getCanonicalFile();

            if (FileUtils.isSymlink(bucket_item)) {
                continue;
            }

            if (list_to_copy.contains(bucket_item)) {
                continue;
            }
            if (bucket_item.isDirectory()) {
                list_content = bucket_item.listFiles();
                for (int pos_lc = 0; pos_lc < list_content.length; pos_lc++) {
                    next_bucket.add(list_content[pos_lc]);
                }
            }
            list_to_copy.add(bucket_item);
        }
        if (next_bucket.isEmpty()) {
            return;
        }
        bucket.clear();
        bucket.addAll(next_bucket);
        next_bucket.clear();
    }
}

From source file:eulermind.importer.LineNode.java

private static void brokenSentencesToTree(LineNode root) {

    //????//from  w w  w .  j a  v a  2 s. c  o  m
    ArrayList<Integer> lineStarts = new ArrayList<>();
    String combinedLine = "";
    for (int i = 0; i < root.getChildCount(); i++) {
        lineStarts.add(combinedLine.length());
        combinedLine += root.getChildAt(i).m_trimLine + (i < root.getChildCount() - 1 ? " " : "");
    }
    lineStarts.add(combinedLine.length()); //

    //???
    BreakIterator boundary = BreakIterator.getSentenceInstance(getStringULocale(combinedLine));
    boundary.setText(combinedLine);

    ArrayList<Integer> icuSentenceStarts = new ArrayList<>();
    for (int icuSentenceStart = boundary.first(); icuSentenceStart != BreakIterator.DONE; //icuSentenceStartcombinedLine.length()
            icuSentenceStart = boundary.next()) {

        icuSentenceStarts.add(icuSentenceStart);
    }

    //???
    Iterator<Integer> lineStartIter = lineStarts.iterator();
    while (lineStartIter.hasNext()) {
        Integer lineStart = lineStartIter.next();
        if (!(icuSentenceStarts.contains(lineStart - 1) || icuSentenceStarts.contains(lineStart))) {
            lineStartIter.remove();
        }
    }

    assert (lineStarts.contains(combinedLine.length()));

    //???
    //1 ????, ?linsStarts.size == 2 (0combinedLine.length())  root.getChildCount >= 2
    //2 ????
    if (lineStarts.size() == 2 && root.getChildCount() >= 2 || lineStarts.size() - 1 == root.getChildCount()) {
        return;
    }

    assert (lineStarts.size() - 1 < root.getChildCount());

    root.removeAllChildren();

    //??
    // ??
    // ????
    for (int lineIdx = 0; lineIdx < lineStarts.size() - 1; lineIdx++) {
        int lineStart = lineStarts.get(lineIdx);
        int lineEnd = lineStarts.get(lineIdx + 1);

        int firstSentenceInThisLine = 0;
        int firstSentenceInNextLine = 0;

        for (firstSentenceInThisLine = 0; firstSentenceInThisLine < icuSentenceStarts.size()
                - 1; firstSentenceInThisLine++) {
            int sentenceStart = icuSentenceStarts.get(firstSentenceInThisLine);
            if (lineStart <= sentenceStart && sentenceStart < lineEnd) {
                break;
            }
        }

        for (firstSentenceInNextLine = firstSentenceInThisLine
                + 1; firstSentenceInNextLine < icuSentenceStarts.size() - 1; firstSentenceInNextLine++) {
            int sentenceStart = icuSentenceStarts.get(firstSentenceInNextLine);
            if (sentenceStart >= lineEnd) {
                break;
            }
        }

        assert firstSentenceInNextLine - firstSentenceInThisLine >= 1;

        if (firstSentenceInNextLine - firstSentenceInThisLine == 1) {
            int sentenceStart = icuSentenceStarts.get(firstSentenceInThisLine);
            int sentenceEnd = icuSentenceStarts.get(firstSentenceInNextLine);

            LineNode lineNode = new LineNode(combinedLine.substring(sentenceStart, sentenceEnd));
            root.add(lineNode);

        } else {
            LineNode lineNode = new LineNode("p");
            for (int sentence = firstSentenceInThisLine; sentence < firstSentenceInNextLine; sentence++) {
                int sentenceStart = icuSentenceStarts.get(sentence);
                int sentenceEnd = icuSentenceStarts.get(sentence + 1);

                LineNode sentenceNode = new LineNode(combinedLine.substring(sentenceStart, sentenceEnd));
                lineNode.add(sentenceNode);
            }
            root.add(lineNode);
        }
    }
    //s_logger.info("ccccccccccc: {}", lineTreeToString(root));
}

From source file:com.ibm.bi.dml.runtime.matrix.GMR.java

/**
 * /*from   w ww.  j  a  v  a  2s  . c om*/
 * @param job
 * @param instructionsInMapper
 * @param inputs
 * @param rlens
 * @param clens
 * @throws DMLRuntimeException 
 * @throws DMLUnsupportedOperationException 
 */
private static void setupDistributedCache(JobConf job, String instMap, String instRed, String[] inputs,
        long[] rlens, long[] clens) throws DMLUnsupportedOperationException, DMLRuntimeException {
    //concatenate mapper and reducer instructions
    String allInsts = (instMap != null && !instMap.trim().isEmpty()) ? instMap : null;
    if (allInsts == null)
        allInsts = instRed;
    else if (instRed != null && !instRed.trim().isEmpty())
        allInsts = allInsts + Instruction.INSTRUCTION_DELIM + instRed;

    //setup distributed cache inputs (at least one)
    if (allInsts != null && !allInsts.trim().isEmpty() && InstructionUtils.isDistributedCacheUsed(allInsts)) {
        //get all indexes of distributed cache inputs
        ArrayList<Byte> indexList = new ArrayList<Byte>();
        String[] inst = allInsts.split(Instruction.INSTRUCTION_DELIM);
        for (String tmp : inst) {
            if (InstructionUtils.isDistributedCacheUsed(tmp)) {
                ArrayList<Byte> tmpindexList = new ArrayList<Byte>();

                MRInstruction mrinst = MRInstructionParser.parseSingleInstruction(tmp);
                if (mrinst instanceof IDistributedCacheConsumer)
                    ((IDistributedCacheConsumer) mrinst).addDistCacheIndex(tmp, tmpindexList);

                //copy distinct indexes only (prevent redundant add to distcache)
                for (Byte tmpix : tmpindexList)
                    if (!indexList.contains(tmpix))
                        indexList.add(tmpix);
            }
        }

        //construct index and path strings
        ArrayList<String> pathList = new ArrayList<String>(); // list of paths to be placed in Distributed cache
        StringBuilder indexString = new StringBuilder(); // input indices to be placed in Distributed Cache (concatenated) 
        StringBuilder pathString = new StringBuilder(); // input paths to be placed in Distributed Cache (concatenated) 
        for (byte index : indexList) {
            if (pathList.size() > 0) {
                indexString.append(Instruction.INSTRUCTION_DELIM);
                pathString.append(Instruction.INSTRUCTION_DELIM);
            }
            pathList.add(inputs[index]);
            indexString.append(index);
            pathString.append(inputs[index]);
        }

        //configure mr job with distcache indexes
        MRJobConfiguration.setupDistCacheInputs(job, indexString.toString(), pathString.toString(), pathList);

        //clean in-memory cache (prevent job interference in local mode)
        if (InfrastructureAnalyzer.isLocalMode(job))
            MRBaseForCommonInstructions.resetDistCache();
    }
}

From source file:net.estinet.gFeatures.API.Minigame.Resource.java

public void copyWorld(File source, File target) {
    try {/*from ww  w . j ava2 s . com*/
        ArrayList<String> ignore = new ArrayList<String>(Arrays.asList("uid.dat", "session.dat"));
        if (!ignore.contains(source.getName())) {
            if (source.isDirectory()) {
                if (!target.exists())
                    target.mkdirs();
                String files[] = source.list();
                for (String file : files) {
                    File srcFile = new File(source, file);
                    File destFile = new File(target, file);
                    copyWorld(srcFile, destFile);
                }
            } else {
                InputStream in = new FileInputStream(source);
                OutputStream out = new FileOutputStream(target);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = in.read(buffer)) > 0)
                    out.write(buffer, 0, length);
                in.close();
                out.close();
            }
        }
    } catch (IOException e) {

    }
}

From source file:Main.java

public static String[] getStorageDirectories() {
    String[] dirs = null;//from  ww  w .j av  a2s  . co  m
    BufferedReader bufReader = null;
    ArrayList<String> list = new ArrayList<String>();
    list.add(Environment.getExternalStorageDirectory().getPath());

    List<String> typeWL = Arrays.asList("vfat", "exfat", "sdcardfs", "fuse");
    List<String> typeBL = Arrays.asList("tmpfs");
    String[] mountWL = { "/mnt", "/Removable" };
    String[] mountBL = { "/mnt/secure", "/mnt/shell", "/mnt/asec", "/mnt/obb", "/mnt/media_rw/extSdCard",
            "/mnt/media_rw/sdcard", "/storage/emulated" };
    String[] deviceWL = { "/dev/block/vold", "/dev/fuse", "/mnt/media_rw/extSdCard" };

    try {
        bufReader = new BufferedReader(new FileReader("/proc/mounts"));
        String line;
        while ((line = bufReader.readLine()) != null) {

            StringTokenizer tokens = new StringTokenizer(line, " ");
            String device = tokens.nextToken();
            String mountpoint = tokens.nextToken();
            String type = tokens.nextToken();

            // skip if already in list or if type/mountpoint is blacklisted
            if (list.contains(mountpoint) || typeBL.contains(type) || StartsWith(mountBL, mountpoint))
                continue;

            // check that device is in whitelist, and either type or mountpoint is in a whitelist
            if (StartsWith(deviceWL, device) && (typeWL.contains(type) || StartsWith(mountWL, mountpoint)))
                list.add(mountpoint);
        }

        dirs = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            dirs[i] = list.get(i);
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    } finally {
        if (bufReader != null) {
            try {
                bufReader.close();
            } catch (IOException e) {
            }
        }
    }
    return dirs;
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step8GoldDataAggregator.java

public static File printHashMap(Map<String, Annotations> annotations, int numberOfAnnotators) {

    File dir = new File(TEMP_DIR);
    CSVPrinter csvFilePrinter;//w w  w .j a v a2s.c  o m
    FileWriter fileWriter;
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator('\n').withDelimiter(',').withQuote(null);

    File filename = null;
    try {
        filename = File.createTempFile(TEMP_CSV, EXT, dir);
        fileWriter = new FileWriter(filename);
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
        int count = 0;
        for (Map.Entry entry : annotations.entrySet()) {
            Annotations votes = (Annotations) entry.getValue();
            //Create the CSVFormat object with "\n" as a record delimiter
            if (votes == null) {
                throw new IllegalStateException("There are no votes for " + entry.getKey());
            }
            ArrayList<Integer> trueAnnotators = (ArrayList<Integer>) votes.trueAnnotations;
            ArrayList<Integer> falseAnnotators = (ArrayList<Integer>) votes.falseAnnotations;
            if (trueAnnotators.size() + falseAnnotators.size() < 5) {
                try {
                    throw new IllegalStateException(
                            "There are " + trueAnnotators.size() + " true and " + falseAnnotators.size()
                                    + " false and annotations for " + entry.getKey() + " element");
                } catch (IllegalStateException ex) {
                    ex.printStackTrace();
                }
            }
            List<String> votesString = Arrays.asList(new String[numberOfAnnotators]);
            for (int i = 0; i < numberOfAnnotators; i++) {
                if (trueAnnotators.contains(i)) {
                    votesString.set(i, "true");
                } else if (falseAnnotators.contains(i)) {
                    votesString.set(i, "false");
                } else
                    votesString.set(i, "");
            }

            if (votesString.size() != numberOfAnnotators) {
                throw new IllegalStateException(
                        "Number of annotators is " + votesString.size() + " expected " + numberOfAnnotators);
            } else {
                csvFilePrinter.printRecord(votesString);
            }

            if (count % 1000 == 0) {
                System.out.println("Processed " + count + " instances");
            }
            count++;

        }
        fileWriter.flush();
        fileWriter.close();
        csvFilePrinter.close();

    } catch (Exception e) {
        System.out.println("Error in CsvFileWriter !!!");
        e.printStackTrace();
    }
    System.out.println("Wrote to temporary file " + filename);

    return filename;

}

From source file:es.pode.modificador.presentacion.configurar.objetos.ruta.IndicarRutaControllerImpl.java

/**
 * @see es.pode.modificador.presentacion.configurar.objetos.ruta.IndicarRutaController#aadirObjeto(org.apache.struts.action.ActionMapping, es.pode.modificador.presentacion.configurar.objetos.ruta.AAdirObjetoForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w  w  w.  j  a  v  a 2 s  .c  o  m
public final void aadirObjeto(ActionMapping mapping,
        es.pode.modificador.presentacion.configurar.objetos.ruta.AAdirObjetoForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (form != null && form.getPath() != null && !(form.getPath().equals(""))) {
        String path = form.getPath();
        ConfiguracionTarea configuracion = getConfigurarModificacionSession(request).getConfiguracion();
        if (configuracion == null) {
            ConfiguracionTarea tarea = new ConfiguracionTarea();
            tarea.setObjetos(new Objects());
            tarea.setCambios(new Changes());
            tarea.getObjetos().setObjetos(new ODE[0]);
            tarea.getObjetos().setPaths(new Folder[0]);
            tarea.getCambios().setCambios(new Change[0]);
            getConfigurarModificacionSession(request).setConfiguracion(tarea);
            configuracion = tarea;
        }

        //         Folder nuevosObjetos[];
        Folder objetos[] = null;

        if (configuracion.getObjetos() != null && configuracion.getObjetos().getPaths() != null) {
            objetos = configuracion.getObjetos().getPaths();
        }
        //            nuevosObjetos = new Folder[objetos.length + 1];
        //         } else {
        //            nuevosObjetos = new Folder[1];
        //         }
        Folder nuevo = new Folder(path.trim(), null);

        if (objetos != null) {
            // Comprobamos si el objeto ya estaba en la lista.
            ArrayList listaObjetos = new ArrayList(Arrays.asList(objetos));
            if (!listaObjetos.contains(nuevo)) {
                //Aado nuevo path a la lista
                listaObjetos.add(nuevo);
                configuracion.getObjetos().setPaths((Folder[]) listaObjetos.toArray(new Folder[] {}));
            } else {
                throw new ValidatorException("{indicarRuta.repeated}");
            }
        }
    } else {
        throw new ValidatorException("{indicarRuta.empty}");
    }
}

From source file:com.onpositive.semantic.words3.MultiHashMap.java

public boolean containsValue(Object value) {
    Set pairs = super.entrySet();

    if (pairs == null)
        return false;

    Iterator pairsIterator = pairs.iterator();
    while (pairsIterator.hasNext()) {
        Map.Entry keyValuePair = (Map.Entry) (pairsIterator.next());
        ArrayList list = (ArrayList) (keyValuePair.getValue());
        if (list.contains(value))
            return true;
    }//  w ww . ja va 2s. c o m
    return false;
}

From source file:io.fabric8.profiles.Profiles.java

private void collectProfileNames(ArrayList<String> target, String profileName) throws IOException {
    if (target.contains(profileName)) {
        return;//from  ww  w.j  a v a 2  s . c  o  m
    }

    Path path = getProfilePath(profileName);
    if (!Files.exists(path)) {
        throw new IOException("Profile directory does not exists: " + path);
    }
    Properties props = new Properties();
    Path agentProperties = path.resolve("io.fabric8.agent.properties");
    if (Files.exists(agentProperties)) {
        props = readPropertiesFile(agentProperties);
    }

    String parents = props.getProperty("attribute.parents", "default".equals(profileName) ? "" : "default");
    for (String parent : parents.split(",")) {
        parent = parent.trim();
        if (!parent.isEmpty()) {
            collectProfileNames(target, parent);
        }
    }

    target.add(profileName);
}