Example usage for java.util ArrayList forEach

List of usage examples for java.util ArrayList forEach

Introduction

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

Prototype

@Override
public void forEach(Consumer<? super E> action) 

Source Link

Usage

From source file:org.loklak.susi.SusiMind.java

/**
 * react on a user input: this causes the selection of deduction rules and the evaluation of the process steps
 * in every rule up to the moment where enough rules have been applied as consideration. The reaction may also
 * cause the evaluation of operational steps which may cause learning effects within the SusiMind.
 * @param query//from w w  w  .  jav  a 2  s  .c o m
 * @param maxcount
 * @return
 */
public List<SusiArgument> react(String query, int maxcount, String client, SusiThought observation) {
    // get the history a list of thoughts
    SusiArgument observation_argument = new SusiArgument();
    if (observation != null && observation.length() > 0)
        observation_argument.think(observation);
    ArrayList<SusiInteraction> interactions = this.logs.getInteractions(client);
    interactions.forEach(action -> observation_argument.think(action.recallDispute()));
    // perform a mindmeld to create a single thought out of the recalled argument
    // the mindmeld will squash the latest thoughts into one so it does not pile up to exponential growth
    SusiThought recall = observation_argument.mindmeld(false);

    // normalize the query
    query = SusiPhrase.normalizeExpression(query);

    // find an answer
    List<SusiArgument> answers = new ArrayList<>();
    List<SusiIdea> ideas = creativity(query, recall, 100);
    for (SusiIdea idea : ideas) {
        SusiArgument argument = idea.getRule().consideration(query, recall, idea.getIntent(), this, client);
        if (argument != null)
            answers.add(argument);
        if (answers.size() >= maxcount)
            break;
    }
    return answers;
}

From source file:com.globocom.grou.report.ts.opentsdb.OpenTSDBClient.java

private ArrayList<HashMap<String, Object>> doRequest(long testCreated, long testLastModified,
        List<Query> queries) {
    final ArrayList<HashMap<String, Object>> listOfResult = new ArrayList<>();
    queries.forEach(query -> {/*w  w  w.  j av  a2 s. c  o  m*/
        String aggr = query.aggregator;
        String ds = query.downsample;
        ObjectNode jBody = JsonNodeFactory.instance.objectNode();
        jBody.set("queries", mapper.valueToTree(Collections.singleton(query)));
        jBody.put("start", testCreated);
        jBody.put("end", testLastModified);

        String bodyRequest = jBody.toString();
        Request requestQuery = HTTP_CLIENT.preparePost(OPENTSDB_URL + "/api/query").setBody(bodyRequest)
                .setHeader(CONTENT_TYPE, APPLICATION_JSON.toString()).build();

        try {
            Response response = HTTP_CLIENT.executeRequest(requestQuery).get();
            String body = response.getResponseBody();
            ArrayList<HashMap<String, Object>> resultMap = mapper.readValue(body, typeRef);
            for (HashMap<String, Object> result : resultMap)
                result.put("aggr", aggr);
            resultMap.forEach(h -> listOfResult.add(renameMetricKey(h, aggr, ds)));
        } catch (InterruptedException | ExecutionException | IOException e) {
            if (LOGGER.isDebugEnabled())
                LOGGER.error(e.getMessage(), e);
        }
    });
    return listOfResult;
}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLMongoDB.java

@Override
public boolean dpGetPeriod(Date t1, Date t2, Dp dp, Set<String> configs, DpGetPeriodResult result) {
    // db.events.find({tag: "System1:Test_1_1.Value", ts: {$gt: ISODate("2016-07-28T09:00:00.000Z"), $lt: ISODate("2016-07-28T10:00:00.000Z")}}, {_id:0, tag:1, ts:1});
    JDebug.out.log(Level.INFO, "dpGetPeriod {0}-{1} dp={2} configs={3}",
            new Object[] { t1, t2, dp, configs.toString() });

    final SimpleDateFormat fmt = new SimpleDateFormat(TimeVar.FMT_DATE_JS_MS);
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));

    // columns/*  w ww.  j a va 2s. com*/
    final ArrayList<Dp> dps = createDpConfigAttrList(dp, configs);
    if (dps.isEmpty()) {
        JDebug.out.warning("dpGetPeriod without any valid config.");
        return false;
    }
    Document columns = new Document();
    columns.append("_id", 0);
    columns.append("ts", 1);
    dps.forEach((Dp x) -> {
        String c = attrMap.get(x.getAttribute());
        if (c != null)
            columns.append(c, 1);
    });

    // filter
    Document query = new Document();
    query.append("tag", getTagOfDp(dp));
    query.append("ts", new Document("$gte", t1).append("$lte", t2));

    // query
    FindIterable<Document> find = evcoll.find(query);
    find.projection(columns);
    find.forEach((Block<Document>) document -> {
        // { "ts" : { "$date" : 1469696660635 }, "value" : { "number" : 3.0 }, "status" : { "$numberLong" : "-9007199254738370303" }, "user" : 0 }
        //JDebug.out.info(document.toJson());
        Date ts = document.getDate("ts");
        Object value;
        for (int i = 0; i < dps.size(); i++) {
            try {
                final Dp attr = dps.get(i);
                switch (attr.getAttribute()) {
                case Value:
                    // value_number
                    value = document.get("value");
                    if (value instanceof Document) {
                        Document dval = (Document) value;
                        dval.keySet().forEach(type -> result.addValue(attr, ts, dval.get(type)));
                    }
                    break;
                case Status:
                    value = document.get("status");
                    result.addVariable(attr, ts, new Bit32Var(value));
                    break;

                case Status64:
                    value = document.get("status");
                    result.addVariable(attr, ts, new Bit64Var(value));
                    break;
                case Manager:
                    value = document.get("manager");
                    result.addVariable(attr, ts, Variable.newVariable(value));
                    break;
                case User:
                    value = document.get("user");
                    result.addVariable(attr, ts, Variable.newVariable(value));
                    break;
                case Stime:
                    value = ts;
                    result.addVariable(attr, ts, Variable.newVariable(value));
                    break;
                default:
                    JDebug.out.log(Level.SEVERE, "unhandeled config {0}", attr.getAttribute());
                }
            } catch (Exception ex) {
                JDebug.StackTrace(Level.SEVERE, ex);
            }
        }
    });

    return true;
}

From source file:pathwaynet.PathwayCalculator.java

private <E> void testForGivenListWithClustering(Graph<E, String> graph, Collection<E> componentsInGroup,
        Collection<E> componentsConsidered, int clusteringMethod, int test) {
    HashSet<E> componentsInGroupAvailable = new HashSet<>();
    componentsInGroupAvailable.addAll(componentsInGroup);
    componentsInGroupAvailable.retainAll(componentsConsidered);

    HierarchicalClusterer<E> clusterer = new HierarchicalClusterer(graph, componentsInGroupAvailable,
            clusteringMethod);//  w ww. ja  v  a2s  .  com
    ArrayList<ArrayList<E>> clusters = clusterer.getReasonableNumberOfClusters();

    ArrayList<TestResultForList> testResults = new ArrayList<>();
    clusters.forEach((componentsInCluster) -> {
        if (componentsInCluster.size() >= 2) {
            if (test == PERMUTATION_BASED)
                testResults.add(PathwayCalculator.this.testForGivenListPermutationBased(graph,
                        componentsInCluster, componentsConsidered, false));
            else if (test == WILCOXON_BASED)
                testResults.add(PathwayCalculator.this.testForGivenListWilcoxBased(graph, componentsInCluster,
                        componentsConsidered, false));
            else
                testResults.add(null);
        } else
            testResults.add(null);
    });

    for (int i = 0; i < testResults.size(); i++) {
        if (testResults.get(i) != null)
            System.out.println(clusters.get(i) + "\t" + testResults.get(i));
    }
}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java

@Override
public boolean dpGetPeriod(Date t1, Date t2, Dp dp, Set<String> configs, DpGetPeriodResult result) {
    JDebug.out.log(Level.INFO, "dpGetPeriod: {0}-{1} {2} {3}",
            new Object[] { t1, t2, dp.toString(), configs.toString() });
    try {/* ww  w  .  j  a  v a  2  s  . c  o  m*/
        Connection conn = dataSourceQuery.getConnection();
        if (conn != null) {
            // select columns                
            ArrayList<Dp> dps = createDpConfigAttrList(dp, configs);
            if (dps.isEmpty()) {
                JDebug.out.warning("dpGetPeriod without any valid config.");
                return false;
            }

            StringBuilder columns = new StringBuilder();
            dps.forEach((Dp x) -> {
                String c = attrMap.get(x.getAttribute());
                if (c != null)
                    columns.append(c).append(",");
            });

            // add the timestamp
            columns.append("ts AS TS");

            // datapoint element_id
            Object tag = this.getTagOfDp(dp);
            if (tag == null) {
                JDebug.out.log(Level.SEVERE, "dpGetPeriod with invalid datapoint {0}",
                        new Object[] { dp.toString() });
                return false;
            }

            // build sql statement
            String sql = String.format(this.sqlSelectStmt, columns);

            // query data
            int records = 0;
            JDebug.out.log(Level.FINE, "dpGetPeriod SQL={0}", sql);
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                // tag
                if (tag instanceof Long)
                    stmt.setLong(1, (Long) tag);
                else if (tag instanceof String) {
                    stmt.setString(1, (String) tag);
                }

                // timerange
                stmt.setTimestamp(2, new java.sql.Timestamp(t1.getTime()), cal);
                stmt.setTimestamp(3, new java.sql.Timestamp(t2.getTime()), cal);

                // execute
                //stmt.setFetchSize(1000);
                ResultSet rs = stmt.executeQuery();
                //ResultSetMetaData md = rs.getMetaData();

                Date ts;
                Object value;
                while (rs.next()) {
                    records++;
                    int c = 0;
                    ts = rs.getTimestamp("TS", cal);
                    for (int i = 0; i < dps.size(); i++) {
                        switch (dps.get(i).getAttribute()) {
                        case Value:
                            // value_number
                            value = rs.getObject(++c);
                            if (value != null)
                                result.addValue(dps.get(i), ts, value);
                            // value_string
                            value = rs.getObject(++c);
                            if (value != null)
                                result.addValue(dps.get(i), ts, value);
                            // value_timestamp
                            value = rs.getObject(++c);
                            if (value != null)
                                result.addValue(dps.get(i), ts, value);
                            break;
                        case Status:
                            value = rs.getObject(++c);
                            result.addVariable(dps.get(i), ts, new Bit32Var(value));
                            break;
                        case Status64:
                            value = rs.getObject(++c);
                            result.addVariable(dps.get(i), ts, new Bit64Var(value));
                            break;
                        case Manager:
                        case User:
                            value = rs.getObject(++c);
                            result.addValue(dps.get(i), ts, value);
                            break;
                        case Stime:
                            value = ts;
                            result.addValue(dps.get(i), ts, value);
                            break;
                        default:
                            c++;
                            JDebug.out.log(Level.SEVERE, "unhandeled config {0}", dps.get(i).getAttribute());
                        }
                    }
                }
            }
            JDebug.out.log(Level.FINE, "dpGetPeriod: {0} records", records);
            conn.close();
            return true;
        } else {
            JDebug.StackTrace(Level.SEVERE, "no connection!");
        }
    } catch (Exception ex) {
        JDebug.StackTrace(Level.SEVERE, ex);
    }
    return false;
}

From source file:pathwaynet.PathwayCalculator.java

private <E> TestResultForList testForGivenListPermutationBased(Graph<E, String> graph,
        Collection<E> componentsInGroup, Collection<E> componentsConsidered, boolean onlyFromSource) {
    // calculate and cache all distances
    DijkstraDistance<E, String> distances = new DijkstraDistance<>(graph);
    HashMap<E, Map<E, Number>> distancesMap = new HashMap<>();
    graph.getVertices().stream().forEach((component) -> {
        Map<E, Number> distancesFromThis = distances.getDistanceMap(component);
        distancesMap.put(component, distancesFromThis);
    });/*from   w ww. j  a v a2  s  . c om*/

    // generate in-group list and all-available list
    HashSet<E> componentsInGroupAvailable = new HashSet<>();
    componentsInGroupAvailable.addAll(graph.getVertices());
    componentsInGroupAvailable.retainAll(componentsConsidered);
    componentsInGroupAvailable.retainAll(componentsInGroup);
    HashSet<E> componentsAvailable = new HashSet<>();
    componentsAvailable.addAll(graph.getVertices());
    componentsAvailable.retainAll(componentsConsidered);

    // store within-group distances for the given list
    if (componentsInGroupAvailable.size() < 2
            || componentsInGroupAvailable.size() > componentsAvailable.size() - 2) {
        System.err.println(
                "ERROE! Please check your component list: too few or too many components in the list.");
        return new TestResultForList(Double.NaN, Double.NaN, Double.NaN);
    }
    ArrayList<Double> distInGroup = new ArrayList<>();
    componentsInGroupAvailable.forEach((component1) -> {
        componentsInGroupAvailable.forEach((component2) -> {
            Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource);
            if (!component1.equals(component2) && minDist != null) {
                distInGroup.add(minDist.doubleValue());
            }
        });
    });
    double[] distInGroupVector = new double[distInGroup.size()];
    for (int i = 0; i < distInGroup.size(); i++)
        distInGroupVector[i] = distInGroup.get(i);
    double meanInGroup = new Mean().evaluate(distInGroupVector);

    // permutations
    ArrayList<Double> meansInPermutGroups = new ArrayList<>();
    ArrayList<HashSet<E>> permutatedGroups = generatePermutatedGroups(componentsAvailable,
            componentsInGroupAvailable.size());
    permutatedGroups.forEach((componentsInPermutatedGroup) -> {
        ArrayList<Double> distInPermutGroup = new ArrayList<>();
        componentsInPermutatedGroup.forEach((component1) -> {
            componentsInPermutatedGroup.forEach((component2) -> {
                Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource);
                if (!component1.equals(component2) && minDist != null) {
                    distInPermutGroup.add(minDist.doubleValue());
                }
            });
        });
        double[] distInPermutGroupVector = new double[distInPermutGroup.size()];
        for (int i = 0; i < distInPermutGroup.size(); i++)
            distInPermutGroupVector[i] = distInPermutGroup.get(i);
        meansInPermutGroups.add(new Mean().evaluate(distInPermutGroupVector));
    });
    double[] meansInPermutGroupsVector = new double[meansInPermutGroups.size()];
    for (int i = 0; i < meansInPermutGroups.size(); i++)
        meansInPermutGroupsVector[i] = meansInPermutGroups.get(i);
    double medianPermut = new Median().evaluate(meansInPermutGroupsVector);
    double p = ((double) meansInPermutGroups.stream().filter(notGreaterThan(meanInGroup)).count())
            / meansInPermutGroups.size();

    return new TestResultForList(p, meanInGroup, medianPermut);
}

From source file:utybo.branchingstorytree.swing.editor.StoryNodesEditor.java

public void checkAllAvailable() {
    ArrayList<StorySingleNodeEditor> seen = new ArrayList<>();
    // Because the algorithm used can mark errors twice we use a set to ensure
    // it only contains each errored element once
    LinkedHashSet<StorySingleNodeEditor> toMarkAsError = new LinkedHashSet<>();
    for (StorySingleNodeEditor ssne : list) {
        for (StorySingleNodeEditor other : seen)
            if (other.matchesId(ssne)) {
                toMarkAsError.add(ssne);
                toMarkAsError.add(other);
                break;
            }/*from ww w.j  a v  a2s. c  om*/
        seen.add(ssne);
    }
    // Turn "seen" into the "everything is ok" list by removing all the errors
    seen.removeAll(toMarkAsError);
    seen.forEach(ssne -> {
        ssne.setStatus(Status.OK);
        ssne.getId().notifyOk();
    });
    toMarkAsError.forEach(ssne -> {
        ssne.setStatus(Status.ERROR);
        ssne.getId().notifyError();
    });
    jlist.repaint();
}

From source file:se.trixon.mapollage.Operation.java

private void addPolygon(String name, ArrayList<Coordinate> coordinates, Folder polygonFolder) {
    List<Point2D.Double> inputs = new ArrayList<>();
    coordinates.forEach((coordinate) -> {
        inputs.add(new Point2D.Double(coordinate.getLongitude(), coordinate.getLatitude()));
    });//w  w  w  . jav a2 s  .  c o  m

    try {
        List<Point2D.Double> convexHull = GrahamScan.getConvexHullDouble(inputs);
        Placemark placemark = polygonFolder.createAndAddPlacemark().withName(name);

        Style style = placemark.createAndAddStyle();
        LineStyle lineStyle = style.createAndSetLineStyle().withColor("00000000").withWidth(0.0);

        PolyStyle polyStyle = style.createAndSetPolyStyle().withColor("ccffffff")
                .withColorMode(ColorMode.RANDOM);

        Polygon polygon = placemark.createAndSetPolygon();
        Boundary boundary = polygon.createAndSetOuterBoundaryIs();
        LinearRing linearRing = boundary.createAndSetLinearRing();

        convexHull.forEach((node) -> {
            linearRing.addToCoordinates(node.x, node.y);

        });
    } catch (IllegalArgumentException e) {
        System.err.println(e);
    }
}

From source file:mercury.app.MercuryAppLoader.java

public ArrayList<MercuryApp> loadApp(File appFolder) {
    File appPropertyFile = new File(appFolder, APP_DEFINITION_FILENAME);
    ArrayList<MercuryApp> foundApps = new ArrayList<>();
    if (appPropertyFile.exists()) {
        try {/*from  w w  w  .j  av  a 2 s.co  m*/
            logger.info("Trying to read it...");
            MercuryLocalApp app = mapper.readValue(appPropertyFile, MercuryLocalApp.class);
            app.setAppPath(appFolder.getAbsolutePath());
            foundApps.add(app);
        } catch (IOException ex) {
            logger.warning("Couldn't read app : " + appFolder.getName());
            ex.printStackTrace();
            logger.log(Level.SEVERE, null, ex);
        }
    }
    File appPackageFile = new File(appFolder, APP_PACKAGE_DEF_FILENAME);
    if (appPackageFile.exists()) {
        try {
            MercuryLocalAppPackage appPackage = mapper.readValue(appPackageFile, MercuryLocalAppPackage.class);

            appPackage.getAppList().forEach(app -> {
                app.setAppPath(appFolder.getAbsolutePath());
                foundApps.add(app);

                foundApps.forEach(fapp -> System.out.println(fapp.getAppURL()));
            });

        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
    return foundApps;
}

From source file:treeNormalizer.structure.treeBucket.java

/**
 * entfernt einen interen Knoten (also den konkreten Knoten)
 *
 * @param node der Knoten//from   www  .j  ava 2 s. co m
 */
private void removeInternalNode(treeBucketNode node) {
    ArrayList<treeBucketNode> parents = node.getParents();
    node.disconnect();

    parents.forEach((parent) -> {
        propagadeNode(parent);
    });

    nodes.remove(node.getStoreId());
}