Example usage for java.util ArrayList stream

List of usage examples for java.util ArrayList stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:org.sleuthkit.autopsy.imagegallery.ImageGalleryModule.java

/**
 *
 * @param file// w  w  w  . j av a2  s. c o m
 *
 * @return true if the file had a TSK_FILE_TYPE_SIG attribute on a
 *         TSK_GEN_INFO that is in the supported list. False if there was an
 *         unsupported attribute, null if no attributes were found
 */
static Boolean hasSupportedMimeType(AbstractFile file) {
    try {
        ArrayList<BlackboardAttribute> fileSignatureAttrs = file
                .getGenInfoAttributes(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_FILE_TYPE_SIG);
        if (fileSignatureAttrs.isEmpty() == false) {
            return fileSignatureAttrs.stream().anyMatch(attr -> supportedMimes.contains(attr.getValueString()));
        }
    } catch (TskCoreException ex) {
        LOGGER.log(Level.INFO, "failed to read TSK_FILE_TYPE_SIG attribute for " + file.getName(), ex);
    }
    return null;
}

From source file:org.apache.sysml.hops.codegen.opt.PlanAnalyzer.java

private static InterestingPoint[] getMaterializationPointsExt(HashSet<Long> roots, HashSet<Long> partition,
        ArrayList<Long> M, CPlanMemoTable memo) {
    //collect categories of interesting points
    ArrayList<InterestingPoint> tmp = new ArrayList<>();
    tmp.addAll(getMaterializationPointConsumers(M, partition, memo));
    tmp.addAll(getTemplateChangePoints(partition, memo));

    //reduce to distinct hop->hop pairs (see equals of interesting points)
    InterestingPoint[] ret = tmp.stream().distinct().toArray(InterestingPoint[]::new);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Partition materialization points (extended): " + Arrays.toString(ret));
    }//  w  w  w.  j  a va2s .  co m

    return ret;
}

From source file:org.moe.gradle.remote.Server.java

public static String getRemotePath(@NotNull URI root, @NotNull Path relative) throws IOException {
    Require.nonNull(root);// w ww .  j a  v a 2  s .c om
    Require.nonNull(relative);

    if (relative.toString().contains("..")) {
        throw new IOException("Relative path points to extenral directory: " + relative);
    }

    ArrayList<String> comps = new ArrayList<>();
    for (Path path : relative) {
        comps.add(path.getFileName().toString());
    }

    try {
        return new URI(root.getPath() + "/" + comps.stream().collect(Collectors.joining("/"))).getPath();
    } catch (URISyntaxException e) {
        throw new GradleException(e.getMessage(), e);
    }
}

From source file:com.simiacryptus.util.lang.CodeUtil.java

/**
 * Gets heapCopy text.//from   w w  w. j a va 2  s  .co  m
 *
 * @param callingFrame the calling frame
 * @return the heapCopy text
 * @throws IOException the io exception
 */
public static String getInnerText(@javax.annotation.Nonnull final StackTraceElement callingFrame)
        throws IOException {
    try {
        @javax.annotation.Nonnull
        final File file = com.simiacryptus.util.lang.CodeUtil.findFile(callingFrame);
        assert null != file;
        final int start = callingFrame.getLineNumber() - 1;
        final List<String> allLines = Files.readAllLines(file.toPath());
        final String txt = allLines.get(start);
        @javax.annotation.Nonnull
        final String indent = com.simiacryptus.util.lang.CodeUtil.getIndent(txt);
        @javax.annotation.Nonnull
        final ArrayList<String> lines = new ArrayList<>();
        for (int i = start + 1; i < allLines.size()
                && (com.simiacryptus.util.lang.CodeUtil.getIndent(allLines.get(i)).length() > indent.length()
                        || allLines.get(i).trim().isEmpty()); i++) {
            final String line = allLines.get(i);
            lines.add(line.substring(Math.min(indent.length(), line.length())));
        }
        return lines.stream().collect(Collectors.joining("\n"));
    } catch (@javax.annotation.Nonnull final Throwable e) {
        return "";
    }
}

From source file:act.installer.brenda.BrendaChebiOntology.java

/**
 * This method processes relatioships "is subtype of" to produce a mapping between each application and its main
 * application, used subsequently (outside of this) to compute each ontology's main application.
 * @param isSubtypeOfRelationships map {chebi id -> subtype's chebi ids}
 * @param applicationChebiId main application's chebi id
 * @return a map {application's chebi id -> related main application's chebi ids}
 *///from   w  ww .ja v a  2s . co m
public static Map<String, Set<String>> getApplicationToMainApplicationsMap(
        Map<String, Set<String>> isSubtypeOfRelationships, String applicationChebiId) {

    // Compute the set of main applications. These are the ontologies that are subtypes of the ontology 'application'.
    Set<String> mainApplicationsChebiId = isSubtypeOfRelationships.get(applicationChebiId);

    // Compute the initial list of applications to visit from the set of main applications.
    ArrayList<String> applicationsToVisit = new ArrayList<>(mainApplicationsChebiId);

    // For each main application, map it to a set containing only itself.
    Map<String, Set<String>> applicationToMainApplicationsMap = applicationsToVisit.stream()
            .collect(Collectors.toMap(e -> e, Collections::singleton));

    // Then visit all applications in a BFS fashion, appending new applications to visit to the applicationsToVisit
    // and propagating/merging the set of main applications as we progress down the relationship graph.
    int currentIndex = 0;
    while (currentIndex < applicationsToVisit.size()) {

        String currentApplication = applicationsToVisit.get(currentIndex);
        Set<String> subApplications = isSubtypeOfRelationships.get(currentApplication);

        if (subApplications != null) {
            // add all sub-applications to the set of applications to visit
            applicationsToVisit.addAll(subApplications);
            for (String subApplication : subApplications) {
                Set<String> mainApplicationsSet = applicationToMainApplicationsMap.get(subApplication);
                if (mainApplicationsSet == null) {
                    mainApplicationsSet = new HashSet<>();
                    applicationToMainApplicationsMap.put(subApplication, mainApplicationsSet);
                }
                mainApplicationsSet.addAll(applicationToMainApplicationsMap.get(currentApplication));
            }
        }
        currentIndex++;
    }

    return applicationToMainApplicationsMap;
}

From source file:sbu.srl.rolextract.SpockDataReader.java

public static void generateSEMAFORFrameAnnotation(ArrayList<Sentence> arrSentence, String frameElementsFileName,
        String rawSentencesFileName, int offset) throws FileNotFoundException {
    Set<String> roles = getRoleLabels(arrSentence); // without NONE!
    PrintWriter writer = new PrintWriter(frameElementsFileName);
    PrintWriter sentWriter = new PrintWriter(rawSentencesFileName);
    int sentCounter = 0;
    //int offset = 2780;
    System.out.println("Generating semafor frame annotation , size :" + arrSentence.size());
    for (int i = 0; i < arrSentence.size(); i++) {
        Sentence currentSentence = arrSentence.get(i);
        if (currentSentence.isAnnotated()) {
            // Is there a positive role?
            int cntRole = 0; // Number of roles
            String frame = currentSentence.getProcessName();
            String lexicalUnitFrames = currentSentence.getLexicalUnitFrame();
            String lexicalUnitIndexRange = currentSentence.getLexicalUnitFrameRange();
            String formLexicalUnitFrame = currentSentence.getLexicalUnitFormFrame();

            StringBuilder roleSpanStrBuilder = new StringBuilder();
            for (String role : roles) {
                ArrayList<ArgumentSpan> spans = currentSentence.getMultiClassAnnotatedArgumentSpan(role, -1);
                if (!spans.isEmpty()) {
                    cntRole++;//from www  .  ja  v  a2s . c o  m
                    ArgumentSpan maxSpan = spans.stream()
                            .max(Comparator.comparing(arg -> arg.getEndIdx() - arg.getStartIdx() + 1)).get();
                    if (maxSpan.getStartIdx() != maxSpan.getEndIdx()) {
                        roleSpanStrBuilder.append(role).append("\t")
                                .append((maxSpan.getStartIdx() - 1) + ":" + (maxSpan.getEndIdx() - 1))
                                .append("\t");
                    } else {
                        roleSpanStrBuilder.append(role).append("\t").append((maxSpan.getStartIdx() - 1))
                                .append("\t");
                    }
                }
                // if there is more than one then select the longer one
                // group by start + end id
                // count number of roles
                // lexical unit == process name
                // sentence number
                // role span pairs
            }
            if (cntRole > 0) {
                StringBuilder frameElementsStrB = new StringBuilder();
                frameElementsStrB.append(cntRole + +1).append("\t").append(frame).append("\t")
                        .append(lexicalUnitFrames).append("\t").append(lexicalUnitIndexRange).append("\t")
                        .append(formLexicalUnitFrame).append("\t").append((sentCounter + offset)).append("\t")
                        .append(roleSpanStrBuilder.toString().trim());
                writer.println(frameElementsStrB.toString());
                sentWriter.println(currentSentence.getRawText().trim());
                sentCounter++;
            }
        }
    }
    writer.close();
    sentWriter.close();
}

From source file:sbu.srl.rolextract.SBURolePredict.java

public static void performPredictionEasySRL(String testObjFile, String testSentenceListFile,
        String outputFileName, String modelFileName, String foldDir)
        throws IOException, FileNotFoundException, ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    ArrayList<Sentence> sentences = (ArrayList<Sentence>) FileUtil.deserializeFromFile(testObjFile);
    new SRLWrapper().doPredictProcessRoleCCG(testSentenceListFile, outputFileName, modelFileName,
            foldDir.concat("/test/easySrlOut"), Constant.SRL_CCG, true, false);
    for (int i = 0; i < sentences.size(); i++) {
        System.out.println("SENTENCE : " + i + sentences.get(i).getRawText());
        Sentence currentSentence = sentences.get(i);
        ArrayList<ArgumentSpan> spans = currentSentence.getAllAnnotatedArgumentSpan();
        HashMap<String, String> argumentSpanThatHasAnnotation = currentSentence
                .getAllArgumentsThatHaveAnnotation();
        spans = (ArrayList<ArgumentSpan>) spans.stream().distinct().collect(toList());
        //if (knownAnnotation) {
        spans = (ArrayList<ArgumentSpan>) spans.stream()
                .filter(s -> argumentSpanThatHasAnnotation
                        .get(currentSentence.getId() + "_" + s.getStartIdx() + "_" + s.getEndIdx()) != null)
                .collect(toList());/*  w  w w  . ja v  a  2  s . c  o  m*/
        //}
        HashMap<String, ArrayList<ArgumentSpan>> roleArgPrediction = new HashMap<String, ArrayList<ArgumentSpan>>();
        if (spans.size() == 0) {
            continue;
        }

        List<ParseResult> parseResult = SentenceUtil.readEasySRLJSONdata(foldDir.concat("/test/easySrlOut"));
        for (int j = 0; j < spans.size(); j++) {
            HashMap<String, Double> roleProbPair = new HashMap<String, Double>();
            HashMap<String, String> roleVectorPair = new HashMap<String, String>();
            ArgumentSpan currentSpan = spans.get(j);
            String text = currentSpan.getText();
            ParseResult sentParseResult = parseResult.get(i);
            int x = 0;

            if (sentParseResult.getParseScore() == -1.0) {
                //currentSpan.setRoleProbPair(roleProbPair);
                currentSpan.predictRoleType(true);
                currentSpan.setRolePredicted("NONE");
                roleProbPair.put("NONE", 1.0);
                currentSpan.setRoleProbPair(roleProbPair);
            } else {
                Object bestOverlap = getBestArgument(sentParseResult, text);
                if (bestOverlap != null) {
                    //currentSpan.setRoleProbPair(roleProbPair);
                    String rolePredicted = "";
                    if (bestOverlap instanceof Predicate) {
                        rolePredicted = "trigger";
                        roleProbPair.put(rolePredicted, ((Predicate) bestOverlap).getScore());
                    } else {
                        try {
                            System.out.println(((Argument) bestOverlap).getLabel());
                            String label = ((Argument) bestOverlap).getLabel();

                            if (label.equalsIgnoreCase("ARG0") || label.equalsIgnoreCase("CAU")) {
                                rolePredicted = "enabler";
                            } else if (label.equalsIgnoreCase("ARG1")) {
                                rolePredicted = "undergoer";
                            } else if (label.equalsIgnoreCase("ARG2") || label.equalsIgnoreCase("PNC")) {
                                rolePredicted = "result";
                            } else {
                                rolePredicted = "NONE";
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println(bestOverlap.getClass().toString());
                        }
                        roleProbPair.put(rolePredicted, ((Argument) bestOverlap).getArgScore());
                    }
                    currentSpan.predictRoleType(true);
                    currentSpan.setRolePredicted(rolePredicted);
                    currentSpan.setRoleProbPair(roleProbPair);
                } else {
                    currentSpan.predictRoleType(true);
                    currentSpan.setRolePredicted("NONE");
                    roleProbPair.put("NONE", 1.0);
                    currentSpan.setRoleProbPair(roleProbPair);
                }

            }

            if (roleArgPrediction.get(currentSpan.getRolePredicted()) != null) {
                ArrayList<ArgumentSpan> predictedSpan = roleArgPrediction.get(currentSpan.getRolePredicted());
                predictedSpan.add(currentSpan);
                roleArgPrediction.put(currentSpan.getRolePredicted(), predictedSpan);
            } else {
                ArrayList<ArgumentSpan> predictedSpan = new ArrayList<ArgumentSpan>();
                predictedSpan.add(currentSpan);
                roleArgPrediction.put(currentSpan.getRolePredicted(), predictedSpan);
            }
        }
        if (roleArgPrediction == null) {
            System.out.println("Something is going wrong here");
            System.exit(0);
        }
        currentSentence.setRoleArgPrediction(roleArgPrediction);
    }

    // populateProbabilityILP(procDataAnnArr);
    // make unique of the SAME arguments,  based on startID and endID
    if (testObjFile.contains("gold")) {
        FileUtil.serializeToFile(sentences, testObjFile.replace("gold", "easysrlpredict"));
    } else {

        FileUtil.serializeToFile(sentences, testObjFile.replace("test.", "easysrlpredict."));
    }
}

From source file:delfos.rs.trustbased.WeightedGraph.java

public static final AdjMatrixEdgeWeightedDigraph inverseOfEdgeValue(
        AdjMatrixEdgeWeightedDigraph distanceGraph) {

    AdjMatrixEdgeWeightedDigraph weightGraph = new AdjMatrixEdgeWeightedDigraph(distanceGraph.V());

    List<DirectedEdge> allEdges = IntStream.range(0, distanceGraph.V()).boxed().map(vertex -> {
        Iterable<DirectedEdge> iterator = distanceGraph.adj(vertex);
        ArrayList<DirectedEdge> listOfEdges = new ArrayList<>();
        for (DirectedEdge edge : iterator) {
            listOfEdges.add(edge);/*from  ww w .  j  av  a  2 s .  c  o m*/
        }
        return listOfEdges;
    }).flatMap(listOfEdges -> listOfEdges.stream()).collect(Collectors.toList());

    List<DirectedEdge> allEdgesConverted = allEdges.stream().map(edge -> {
        final double weight = edge.weight();

        double distance = 1 / weight;

        if (weight == 0) {
            distance = Double.POSITIVE_INFINITY;
        }

        return new DirectedEdge(edge.from(), edge.to(), distance);
    }).collect(Collectors.toList());

    allEdgesConverted.forEach(edge -> weightGraph.addEdge(edge));
    return weightGraph;
}

From source file:org.zalando.problem.JacksonStackTraceProcessor.java

@Override
public Collection<StackTraceElement> process(final Collection<StackTraceElement> collection) {
    final ArrayList<StackTraceElement> elements = new ArrayList<>(collection);

    return elements.stream()
            .filter(startsWith("sun.reflect", "java.lang.reflect", "com.fasterxml.jackson").negate())
            .findFirst().map(elements::indexOf).map(subList(elements)).orElse(elements);
}

From source file:com.microsoft.azure.utility.compute.TestCleanupTask.java

private void removeRGs(ArrayList<ResourceGroupExtended> groups) {
    groups.stream().filter(new Predicate<ResourceGroupExtended>() {
        @Override//w  ww  .j  av a2  s . c  o  m
        public boolean test(ResourceGroupExtended rg) {
            return rg.getName().startsWith("javatest");
        }
    }).forEach(new Consumer<ResourceGroupExtended>() {
        @Override
        public void accept(ResourceGroupExtended rg) {
            try {
                resourceManagementClient.getResourceGroupsOperations().beginDeleting(rg.getName());
                log.info("removed rg: " + rg.getName());
            } catch (Exception e) {
                log.info(e.toString());
            }
        }
    });
}