Example usage for java.util Collections min

List of usage examples for java.util Collections min

Introduction

In this page you can find the example usage for java.util Collections min.

Prototype

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) 

Source Link

Document

Returns the minimum element of the given collection, according to the natural ordering of its elements.

Usage

From source file:be.ugent.maf.cellmissy.analysis.singlecell.preprocessing.impl.SingleCellConditionPreProcessorImpl.java

@Override
public void generateShiftedCoordinatesRanges(SingleCellConditionDataHolder singleCellConditionDataHolder) {
    singleCellConditionDataHolder.getSingleCellWellDataHolders().stream()
            .forEach((singleCellWellDataHolder) -> {
                singleCellWellPreProcessor.generateShiftedCoordinatesRanges(singleCellWellDataHolder);
            });/*from  w  w w .java2s.  c o  m*/
    Double[][] transposedMatrix = AnalysisUtils
            .transpose2DArray(singleCellConditionDataHolder.getShiftedTrackCoordinatesMatrix());
    // compute the min and the max coordinates
    Double xMin = Collections.min(Arrays.asList(transposedMatrix[0]));
    Double xMax = Collections.max(Arrays.asList(transposedMatrix[0]));
    Double yMin = Collections.min(Arrays.asList(transposedMatrix[1]));
    Double yMax = Collections.max(Arrays.asList(transposedMatrix[1]));
    Double[][] shiftedCoordinatesRanges = new Double[2][2];
    shiftedCoordinatesRanges[0] = new Double[] { xMin, xMax };
    shiftedCoordinatesRanges[1] = new Double[] { yMin, yMax };
    singleCellConditionDataHolder.setShiftedCoordinatesRanges(shiftedCoordinatesRanges);
}

From source file:org.libreplan.business.planner.entities.TaskGroup.java

public IntraDayDate getSmallestStartDateFromChildren() {
    return Collections.min(getChildrenStartDates());
}

From source file:msi.gama.outputs.layers.charts.ChartJFreeChartOutputHeatmap.java

protected void resetRenderer(final IScope scope, final String serieid) {
    final XYBlockRenderer newr = (XYBlockRenderer) this.getOrCreateRenderer(scope, serieid);

    // newr.setSeriesStroke(0, new BasicStroke(0));
    final ChartDataSeries myserie = this.getChartdataset().getDataSeries(scope, serieid);

    if (myserie.getMycolor() != null) {
        newr.setSeriesPaint(0, myserie.getMycolor());
    }/*from   ww  w .  j  a v  a2  s. com*/
    if (myserie.getSValues(scope).size() > 0) {
        final double maxval = Collections.max(myserie.getSValues(scope));
        final double minval = Collections.min(myserie.getSValues(scope));
        Color cdeb = new Color(0, 0, 0, 0);
        if (myserie.getMyMincolor() != null)
            cdeb = myserie.getMyMincolor();
        Color cend = new Color(0.9f, 0.9f, 0.9f, 1.0f);
        if (myserie.getMycolor() != null)
            cend = myserie.getMycolor();

        LookupPaintScale paintscale = createLUT(100, (float) minval, (float) maxval, cdeb, cend);
        if (myserie.getMyMedcolor() != null)
            paintscale = createLUT(100, (float) minval, (float) maxval, cdeb, myserie.getMyMedcolor(), cend);

        newr.setPaintScale(paintscale);

        final NumberAxis scaleAxis = new NumberAxis(myserie.getName());
        scaleAxis.setAxisLinePaint(this.axesColor);
        scaleAxis.setTickMarkPaint(this.axesColor);
        scaleAxis.setTickLabelFont(this.getTickFont());
        scaleAxis.setRange(minval, maxval);
        scaleAxis.setAxisLinePaint(axesColor);
        scaleAxis.setLabelFont(getLabelFont());
        if (textColor != null) {
            scaleAxis.setLabelPaint(textColor);
            scaleAxis.setTickLabelPaint(textColor);
        }
        if (!this.getXTickValueVisible(scope)) {
            scaleAxis.setTickMarksVisible(false);
            scaleAxis.setTickLabelsVisible(false);

        }

        final PaintScaleLegend legend = new PaintScaleLegend(paintscale, scaleAxis);
        legend.setAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        legend.setAxisOffset(5.0);
        // legend.setMargin(new RectangleInsets(5, 5, 5, 5));
        // legend.setFrame(new BlockBorder(Color.red));
        // legend.setPadding(new RectangleInsets(10, 10, 10, 10));
        // legend.setStripWidth(10);
        legend.setPosition(RectangleEdge.RIGHT);
        legend.setBackgroundPaint(this.backgroundColor);
        // ArrayList<PaintScaleLegend> caxe=new
        // ArrayList<PaintScaleLegend>();
        // caxe.add(legend);
        // chart.setSubtitles(caxe);
        if (!this.series_label_position.equals("none"))
            chart.addSubtitle(legend);

    }
}

From source file:edu.usc.goffish.gopher.sample.N_Hop_Stat_Collector.java

@Override
public void compute(List<SubGraphMessage> subGraphMessages) {

    /**//w w w  .j  av  a2  s  .  c o  m
     * We do this in following steps.
     * Calculate stats for each subgraph.
     * Calculate aggregate stats for partition.
     * In this case a single sub-graph will do the aggregation
     * Aggregate partition level stats and combine at the smallest partition.
     */

    if (superStep == 0) {
        SubGraphMessage msg = subGraphMessages.get(0);
        String data = new String(msg.getData());

        String[] dataSplit = data.split("#");
        N = Integer.parseInt(dataSplit[0]);
        String[] vps = dataSplit[1].split(",");
        for (String vp : vps) {
            vantagePoints.add(vp.trim());
        }

        try {

            Iterable<? extends ISubgraphInstance> subgraphInstances = subgraph.getInstances(Long.MIN_VALUE,
                    Long.MAX_VALUE, PropertySet.EmptyPropertySet, subgraph.getEdgeProperties(), false);

            //                        sliceManager.readInstances(subgraph,
            //                        Long.MIN_VALUE, Long.MAX_VALUE,
            //                        PropertySet.EmptyPropertySet, subgraph.getEdgeProperties());

            for (ISubgraphInstance instance : subgraphInstances) {

                Map<String, DescriptiveStatistics> statsMap = new HashMap<String, DescriptiveStatistics>();

                for (TemplateEdge edge : subgraph.edges()) {

                    ISubgraphObjectProperties edgeProps = instance.getPropertiesForEdge(edge.getId());

                    Integer isExist = (Integer) edgeProps.getValue(IS_EXIST_PROP);
                    if (isExist == 1) {
                        String[] vantageIps = ((String) edgeProps.getValue(VANTAGE_IP_PROP)).split(",");
                        String[] latencies = ((String) edgeProps.getValue(LATENCY_PROP)).split(",");
                        String[] hops = ((String) edgeProps.getValue(HOP_PROP)).split(",");

                        Integer[] vantangeIdx = vantageIpIndex(vantageIps);
                        if (vantangeIdx == null) {
                            continue;
                        }

                        for (int i : vantangeIdx) {

                            String vantage = vantageIps[i];
                            String latency = latencies[i];
                            String hop = hops[i];

                            double latency_num = Double.parseDouble(latency);
                            int hop_num = Integer.parseInt(hop);

                            if (latency_num >= 0 && hop_num == N) {
                                if (statsMap.containsKey(vantage)) {

                                    statsMap.get(vantage).addValue(latency_num);

                                } else {

                                    DescriptiveStatistics statistics = new DescriptiveStatistics();
                                    statistics.addValue(latency_num);
                                    statsMap.put(vantage, statistics);

                                }
                            }
                            ;

                        }

                    }

                }

                int c = 0;
                StringBuffer msgBuffer = new StringBuffer();

                for (String v : statsMap.keySet()) {
                    c++;
                    DescriptiveStatistics statistics = statsMap.get(v);
                    String m = createMessageString(v, instance.getTimestampStart(), instance.getTimestampEnd(),
                            statistics.getStandardDeviation(), statistics.getMean(), statistics.getN());

                    if (c == statsMap.keySet().size()) {
                        msgBuffer.append(m);
                    } else {

                        msgBuffer.append(m).append("|");
                    }

                }

                SubGraphMessage subMsg = new SubGraphMessage(msgBuffer.toString().getBytes());

                sentMessage(partition.getId(), subMsg);

            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    } else if (superStep == 1) {
        //Ok here every sub-graph will receive message from its own partition.
        //Each message is belongs to a given some time span.
        Map<String, List<String[]>> vantageGroup = new HashMap<String, List<String[]>>();

        for (SubGraphMessage subGraphMessage : subGraphMessages) {

            String msgData = new String(subGraphMessage.getData());
            String[] dataParts = msgData.split("|");

            for (String data : dataParts) {
                String[] vantageParts = data.split(",");
                //Group by vantage point and startTime
                if (vantageGroup.containsKey(vantageParts[0] + "|" + vantageParts[1])) {
                    vantageGroup.get(vantageParts[0] + "|" + vantageParts[1]).add(vantageParts);
                } else {
                    ArrayList<String[]> arrayList = new ArrayList<String[]>();
                    arrayList.add(vantageParts);
                    vantageGroup.put(vantageParts[0] + "|" + vantageParts[1], arrayList);
                }

            }

        }

        for (String key : vantageGroup.keySet()) {

            if (!acquireLock(key)) {
                continue;
            }

            List<String[]> data = vantageGroup.get(key);

            double totalN = 0;
            double totalAvgVal = 0;

            double totalVar = 0;
            for (String[] d : data) {

                //average
                double mean = Double.parseDouble(d[4]);
                long sN = Long.parseLong(d[5]);
                totalN += sN;
                totalAvgVal += mean * sN;

                double sd = Double.parseDouble(d[3]);
                totalVar += ((double) sd * sd) / ((double) sN);

            }

            double avg = totalAvgVal / totalN;
            double newSD = Math.sqrt(totalVar);

            //create message
            //sent to all the partitions except me.
            String msg = key + "," + newSD + "," + avg + "," + totalN;

            for (int pid : partitions) {
                sentMessage(pid, new SubGraphMessage(msg.getBytes()));
            }

        }

    } else if (superStep >= 2) {

        if (partition.getId() == Collections.min(partitions)) {

            Map<String, List<String[]>> group = new HashMap<String, List<String[]>>();

            for (SubGraphMessage msg : subGraphMessages) {

                String data = new String(msg.getData());

                String[] dataParts = data.split(",");

                if (group.containsKey(dataParts[0])) {
                    group.get(dataParts[0]).add(dataParts);
                } else {
                    List<String[]> list = new ArrayList<String[]>();
                    list.add(dataParts);
                    group.put(dataParts[0], list);
                }

            }

            if (!acquireLock("" + partition.getId())) {
                voteToHalt();
                return;
            }

            PrintWriter writer;
            try {

                writer = new PrintWriter(new FileWriter("TimeSeriesStats.csv"));
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            for (String key : group.keySet()) {

                List<String[]> data = group.get(key);

                double totalN = 0;
                double totalAvgVal = 0;

                double totalVar = 0;
                for (String[] d : data) {

                    //average

                    //key + "," + newSD + "," + avg + "," + totalN;
                    double mean = Double.parseDouble(d[2]);
                    long sN = Long.parseLong(d[3]);
                    totalN += sN;
                    totalAvgVal += mean * sN;

                    double sd = Double.parseDouble(d[1]);
                    totalVar += ((double) sd * sd) / ((double) sN);

                }

                double avg = totalAvgVal / totalN;
                double newSD = Math.sqrt(totalVar);

                String vantage = key.split("|")[0];
                String timeStamp = key.split("|")[1];

                log(writer, vantage, timeStamp, avg, newSD);

            }
            writer.flush();
            voteToHalt();

        }
    }

}

From source file:explore.ArgminCorpusReader.java

@Override
public void getNext(JCas aJcas) throws CollectionException {
    try {// w  w w  . ja v  a  2  s .  c  om
        Map<String, Object> jsonData = this.documentsIterator.next();

        String htmlText = (String) jsonData.get(JsonCorpusUtil.TEXT);
        org.jsoup.nodes.Document cleanedText = Jsoup.parse(htmlText);
        String rawDocumentText = cleanedText.text();

        String file = (String) jsonData.get(JsonCorpusUtil.FILE);
        String documentId = file.replace(".json", "");
        String url = (String) jsonData.get(JsonCorpusUtil.URL);

        // original HTML version not required for TC experiment
        //            JCas view = jCas.createView(JsonCorpusUtil.VIEW_ORIGINAL_HTML);
        //            view.setDocumentText(htmlText);

        aJcas.setDocumentText(rawDocumentText);
        aJcas.setDocumentLanguage(this.language);

        DocumentMetaData metaData = DocumentMetaData.create(aJcas);
        metaData.setDocumentBaseUri("");
        metaData.setDocumentUri("/" + documentId);
        metaData.setDocumentTitle(url);
        metaData.setDocumentId(documentId);

        Map<Integer, Token> idxToTokenMapping = this.createIndexToTokenMapping(rawDocumentText);

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> userAnnotations = (List<Map<String, Object>>) jsonData
                .get(JsonCorpusUtil.USER_ANNOTATIONS);

        for (Map<String, Object> userAnnotation : userAnnotations) {

            String annotator = (String) userAnnotation.get(JsonCorpusUtil.ANNOTATOR);
            if (annotator.equals(this.annotator)) {

                @SuppressWarnings("unchecked")
                List<String> argUnits = (List<String>) userAnnotation.get(JsonCorpusUtil.ARGUMENTATION_UNITS);

                for (String argUnit : argUnits) {
                    String cleanedArgUnit = argUnit.replaceAll("\\s+", "");
                    Matcher matcher = JsonCorpusUtil.getRecognitionPattern().matcher(cleanedArgUnit);
                    if (!matcher.matches()) {
                        this.getLogger()
                                .warn(String.format("argument unit %s does not match the expected pattern %s",
                                        cleanedArgUnit, JsonCorpusUtil.getRecognitionPattern().pattern()));
                    } else {
                        // **************************************************
                        // coordinates of an argument unit:
                        String label = matcher.group(1);
                        String stringIndices = matcher.group(3).replaceAll("^,", "");
                        List<Integer> indices = CollectionUtils.parseIntList(stringIndices, ",");

                        int firstIndex = Collections.min(indices);
                        Token firstToken = idxToTokenMapping.get(firstIndex);

                        int lastIndex = Collections.max(indices);
                        Token lastToken = idxToTokenMapping.get(lastIndex);
                        // *****************************************************

                        // Read argument unit as Paragraph annotation
                        Paragraph para = new Paragraph(aJcas, firstToken.getBegin(), lastToken.getEnd());
                        para.addToIndexes();

                        // print some counts:
                        System.out.println("annotator: " + annotator);
                        counter++;
                        System.out
                                .println("AU " + counter + " -- argument unit text: " + para.getCoveredText());
                        System.out.println("label: " + label);
                        if (label.contains("claim")) {
                            claims++;
                        } else {
                            premises++;
                        }
                        System.out.println("premises " + premises + "\t claims " + claims);

                        NamedEntity outcome = new NamedEntity(aJcas, firstToken.getBegin(), lastToken.getEnd());
                        outcome.setValue(label);
                        outcome.addToIndexes();

                    } // matching was ok
                } // for argUnit : argUnits
                ++this.nextDocumentIdx;

            } // if annotator.equals(this.annotator)
        }
    } catch (final CASException e) {
        throw new CollectionException(e);
    } catch (final ResourceInitializationException e) {
        throw new CollectionException(e);
    } catch (final UIMAException e) {
        throw new CollectionException(e);
    }
}

From source file:com.puppycrawl.tools.checkstyle.checks.TranslationCheck.java

/**
 * Gets full name of resource bundle.//from w  ww  .j ava2  s  . c  om
 * Full name of resource bundle consists of bundle path and
 * full base name.
 * @param filesInResourceBundle a set of files in resource bundle.
 * @return full name of resource bundle.
 */
private String getFullBundleName(Set<File> filesInResourceBundle) {
    final String fullBundleName;

    final File firstTranslationFile = Collections.min(filesInResourceBundle);
    final String translationPath = firstTranslationFile.getPath();
    final String extension = getFileExtensions()[0];

    final Pattern pattern = Pattern.compile("^.+_[a-z]{2}" + extension + "$");
    final Matcher matcher = pattern.matcher(translationPath);
    if (matcher.matches()) {
        fullBundleName = translationPath.substring(0, translationPath.lastIndexOf('_'));
    } else {
        fullBundleName = translationPath.substring(0, translationPath.lastIndexOf('.'));
    }
    return fullBundleName;
}

From source file:org.onosproject.cpman.impl.DefaultMetricsDatabase.java

private double minMetric(String metricType, long startTime, long endTime) {
    double[] all = metrics(metricType, startTime, endTime);
    List list = Arrays.asList(ArrayUtils.toObject(all));
    return (double) Collections.min(list);
}

From source file:org.libreplan.business.planner.chart.ContiguousDaysLine.java

@SuppressWarnings("unchecked")
LocalDate min(LocalDate... dates) {
    return Collections.min(Arrays.asList(dates));
}

From source file:com.google.ie.web.controller.TagController.java

/**
 * Return a map containing the maximum and minimum weights of the tags in
 * the tag cloud data received as list//from  w ww . ja v a2s  .  c om
 * 
 * @param tags the list of tags to be searched for max and min weights
 * @return a map containing the maximum and minimum weights
 */
private Map<String, Long> getTheMaxAndMinWeights(List<Tag> tags) {
    long min = Collections.min(tags).getWeightage();
    long max = Collections.max(tags).getWeightage();
    Map<String, Long> mapOfMinMax = new HashMap<String, Long>();
    mapOfMinMax.put(WebConstants.MAX_WEIGHT, max);
    mapOfMinMax.put(WebConstants.MIN_WEIGHT, min);

    return mapOfMinMax;
}

From source file:org.sakaiproject.gradebookng.tool.panels.AssignmentStatisticsPanel.java

private String constructLowestLabel(final List<Double> allGrades, final Assignment assignment) {
    final double lowest = Collections.min(allGrades);
    final String lowestFormatted = FormatHelper.formatDoubleToDecimal(Double.valueOf(lowest));

    if (GradingType.PERCENTAGE.equals(this.gradingType)) {
        return (new StringResourceModel("label.percentage.valued", null, new Object[] { lowestFormatted }))
                .getString();/*from  ww w .j a v  a2s  .c  o  m*/
    }

    final Double total = assignment.getPoints();
    final String percentage = FormatHelper.formatDoubleAsPercentage(100 * (lowest / total.doubleValue()));

    return (new StringResourceModel("label.statistics.lowestvalue", null,
            new Object[] { lowestFormatted, FormatHelper.formatGrade(String.valueOf(total)), percentage }))
                    .getString();
}