Example usage for java.util Collections max

List of usage examples for java.util Collections max

Introduction

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

Prototype

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

Source Link

Document

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

Usage

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

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

From source file:de.tudarmstadt.ukp.dkpro.core.mallet.topicmodel.MalletTopicModelInferencer.java

/**
 * Assign topics according to the following formula:
 * <p>//from   w w w  .j  a  va 2s .c o  m
 * Topic proportion must be at least the maximum topic's proportion divided by the maximum
 * number of topics to be assigned. In addition, the topic proportion must not lie under the
 * minTopicProb. If more topics comply with these criteria, only retain the n
 * (maxTopicAssignments) largest values.
 *
 * @param topicDistribution
 *            a double array containing the document's topic proportions
 * @return an array of integers pointing to the topics assigned to the document
 */
private int[] assignTopics(final double[] topicDistribution) {
    /*
     * threshold is the largest value divided by the maximum number of topics or the fixed
     * number set as minTopicProb parameter.
     */
    double threshold = Math.max(
            Collections.max(Arrays.asList(ArrayUtils.toObject(topicDistribution))) / maxTopicAssignments,
            minTopicProb);

    /*
     * assign indexes for values that are above threshold
     */
    List<Integer> indexes = new ArrayList<>(topicDistribution.length);
    for (int i = 0; i < topicDistribution.length; i++) {
        if (topicDistribution[i] >= threshold) {
            indexes.add(i);
        }
    }

    /*
     * Reduce assignments to maximum number of allowed assignments.
     */
    if (indexes.size() > maxTopicAssignments) {

        /* sort index list by corresponding values */
        Collections.sort(indexes, new Comparator<Integer>() {
            @Override
            public int compare(Integer aO1, Integer aO2) {
                return Double.compare(topicDistribution[aO1], topicDistribution[aO2]);
            }
        });

        while (indexes.size() > maxTopicAssignments) {
            indexes.remove(0);
        }
    }

    return ArrayUtils.toPrimitive(indexes.toArray(new Integer[indexes.size()]));
}

From source file:explore.ArgminCorpusReader.java

@Override
public void getNext(JCas aJcas) throws CollectionException {
    try {//from 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:org.libreplan.business.planner.entities.TaskGroup.java

public IntraDayDate getBiggestEndDateFromChildren() {
    return Collections.max(getChildrenEndDates());
}

From source file:com.androchill.call411.MainActivity.java

private Phone getHardwareSpecs() {
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    PhoneBuilder pb = new PhoneBuilder();
    pb.setModelNumber(Build.MODEL);/*from   w  ww.j a  v a2s.c  om*/
    pb.setManufacturer(Build.MANUFACTURER);

    Process p = null;
    String board_platform = "No data available";
    try {
        p = new ProcessBuilder("/system/bin/getprop", "ro.chipname").redirectErrorStream(true).start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        while ((line = br.readLine()) != null) {
            board_platform = line;
        }
        p.destroy();
    } catch (IOException e) {
        e.printStackTrace();
        board_platform = "No data available";
    }

    pb.setProcessor(board_platform);
    ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(mInfo);
    pb.setRam((int) (mInfo.totalMem / 1048576L));
    pb.setBatteryCapacity(getBatteryCapacity());
    pb.setTalkTime(-1);
    pb.setDimensions("No data available");

    WindowManager mWindowManager = getWindowManager();
    Display mDisplay = mWindowManager.getDefaultDisplay();
    Point mPoint = new Point();
    mDisplay.getSize(mPoint);
    pb.setScreenResolution(mPoint.x + " x " + mPoint.y + " pixels");

    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    mDisplay.getMetrics(mDisplayMetrics);
    int mDensity = mDisplayMetrics.densityDpi;
    pb.setScreenSize(
            Math.sqrt(Math.pow(mPoint.x / (double) mDensity, 2) + Math.pow(mPoint.y / (double) mDensity, 2)));

    Camera camera = Camera.open(0);
    android.hardware.Camera.Parameters params = camera.getParameters();
    List sizes = params.getSupportedPictureSizes();
    Camera.Size result = null;

    ArrayList<Integer> arrayListForWidth = new ArrayList<Integer>();
    ArrayList<Integer> arrayListForHeight = new ArrayList<Integer>();

    for (int i = 0; i < sizes.size(); i++) {
        result = (Camera.Size) sizes.get(i);
        arrayListForWidth.add(result.width);
        arrayListForHeight.add(result.height);
    }
    if (arrayListForWidth.size() != 0 && arrayListForHeight.size() != 0) {
        pb.setCameraMegapixels(
                Collections.max(arrayListForHeight) * Collections.max(arrayListForWidth) / (double) 1000000);
    } else {
        pb.setCameraMegapixels(-1);
    }
    camera.release();

    pb.setPrice(-1);
    pb.setWeight(-1);
    pb.setSystem("Android " + Build.VERSION.RELEASE);

    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    StatFs statInternal = new StatFs(Environment.getRootDirectory().getAbsolutePath());
    double storageSize = ((stat.getBlockSizeLong() * stat.getBlockCountLong())
            + (statInternal.getBlockSizeLong() * statInternal.getBlockCountLong())) / 1073741824L;
    pb.setStorageOptions(storageSize + " GB");
    TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE));
    String operatorName = telephonyManager.getNetworkOperatorName();
    if (operatorName.length() == 0)
        operatorName = "No data available";
    pb.setCarrier(operatorName);
    pb.setNetworkFrequencies("No data available");
    pb.setImage(null);
    return pb.createPhone();
}

From source file:com.seleniumtests.browserfactory.BrowserInfo.java

/**
 * Find the most suitable driver when using chrome browser
 * @throws IOException/*from ww  w.  j a  va 2  s.c o  m*/
 */
private void addChromeDriverFile() throws IOException {
    List<String> driverFiles = getDriverFiles();
    driverFiles = driverFiles.stream().filter(s -> s.contains("chrome-") && s.startsWith("chromedriver_"))
            .map(s -> s.replace(".exe", "")).sorted().collect(Collectors.toList());

    if (driverFiles.isEmpty()) {
        throw new ConfigurationException("no chromedriver in resources");
    }

    Map<Integer, String> driverVersion = new HashMap<>();

    for (String fileName : driverFiles) {
        Matcher matcher = REG_CHROME_VERSION.matcher(fileName);
        if (matcher.matches()) {
            int minVersion = Integer.parseInt(matcher.group(1));
            int maxVersion = Integer.parseInt(matcher.group(2));
            if (maxVersion < minVersion) {
                throw new ConfigurationException(String.format(
                        "Chrome driver file %s version is incorrect, max version should be > to min version",
                        fileName));
            } else {
                for (int i = minVersion; i <= maxVersion; i++) {
                    driverVersion.put(i, fileName);
                }
            }
        } else {
            throw new ConfigurationException(String.format(
                    "Driver %s is excluded as it does not match the pattern 'chromedriver_<version>_chrome-<minVersion>-<maxVersion>'",
                    fileName));
        }
    }

    int chromeVersion = Integer.parseInt(version.split("\\.")[0]);
    driverFileName = driverVersion.get(chromeVersion);

    // when chrome version is greater than driver version, take the last driver and display warning as something may go wrong
    if (driverFileName == null && chromeVersion > Collections.max(driverVersion.keySet())) {
        driverFileName = driverFiles.get(driverFiles.size() - 1);

        logger.warn("--------------------------------------------------------------------");
        logger.warn(String.format(
                "Chrome version %d does not have any associated driver, update seleniumRobot version, the latest driver has been used",
                chromeVersion));
        logger.warn("--------------------------------------------------------------------");
    } else if (driverFileName == null) {
        throw new ConfigurationException(String.format(
                "Chrome version %d does not have any associated driver, update seleniumRobot version",
                chromeVersion));
    }
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.doseresponse.generic.GenericDRInputController.java

/**
 * Create model for overview table (top one). Contains all imported data.
 *
 * @return/*  ww  w  .java2 s .  c o  m*/
 */
private NonEditableTableModel createTableModel(List<DoseResponsePair> importedData) {
    int maxReplicates = Collections.max(getNumberOfReplicates(importedData));
    Object[][] data = new Object[importedData.size()][maxReplicates + 2];

    for (int rowIndex = 0; rowIndex < importedData.size(); rowIndex++) {
        data[rowIndex][0] = rowIndex + 1;
        data[rowIndex][1] = importedData.get(rowIndex).getDose();
        //not all row have the maximum number of columns
        for (int columnIndex = 2; columnIndex < maxReplicates + 2; columnIndex++) {
            try {
                data[rowIndex][columnIndex] = importedData.get(rowIndex).getResponses().get(columnIndex - 2);
            } catch (IndexOutOfBoundsException e) {
                data[rowIndex][columnIndex] = "";
            }
        }
    }

    // array of column names for table model
    String[] columnNames = new String[maxReplicates + 2];
    columnNames[0] = "Condition number";
    columnNames[1] = "Dose";
    for (int x = 2; x < columnNames.length; x++) {
        columnNames[x] = "Repl " + (x - 1);
    }

    NonEditableTableModel nonEditableTableModel = new NonEditableTableModel();
    nonEditableTableModel.setDataVector(data, columnNames);
    return nonEditableTableModel;
}

From source file:com.mycompany.complexity.tool.mvn.TreeLayout.java

private int calculateDimensionY(Collection<V> roots) {
    int size;//from ww w  . j av  a  2  s .co m
    List<Integer> maxSize = new ArrayList<>();
    for (V v : roots) {
        size = 0;
        int childrenNum = graph.getSuccessors(v).size();

        if (childrenNum != 0) {
            for (V element : getOrderedSucessors(v)) {
                if (!alreadyCalculatedY.contains(element)) {
                    alreadyCalculatedY.add(element);
                    size += calculateDimensionY(element) + this.distY;
                }
            }
        }
        size = Math.max(0, size - this.distY);
        maxSize.add(size);
    }
    return Collections.max(maxSize);
}

From source file:gov.nih.nci.firebird.data.SupplementalInvestigatorDataForm.java

@Transient
private Date getMostRecentPhrpCertificationDate() {
    Iterable<TrainingCertificate> certificatesWithEffectiveDates = getPhrpCertificatesWithEffectiveDates();
    Iterable<Date> certificateDates = getPhrpCertificateDates(certificatesWithEffectiveDates);
    return Iterables.isEmpty(certificateDates) ? null : Collections.max(Lists.newArrayList(certificateDates));
}

From source file:org.jahia.ajax.gwt.helper.PublicationHelper.java

/**
 * Get the publication status information for a particular path.
 *
 *
 *
 * @param node               to get publication info from
 * @param currentUserSession/*from w ww  . j a va 2s .c  o  m*/
 * @param includesReferences
 * @param includesSubnodes
 * @return a GWTJahiaPublicationInfo object filled with the right status for the publication state of this path
 * @throws org.jahia.ajax.gwt.client.service.GWTJahiaServiceException
 *          in case of any RepositoryException
 */
public Map<String, GWTJahiaPublicationInfo> getAggregatedPublicationInfosByLanguage(JCRNodeWrapper node,
        Set<String> languages, JCRSessionWrapper currentUserSession, boolean includesReferences,
        boolean includesSubnodes) throws GWTJahiaServiceException {
    try {
        HashMap<String, GWTJahiaPublicationInfo> infos = new HashMap<String, GWTJahiaPublicationInfo>(
                languages.size());

        for (String language : languages) {
            PublicationInfo pubInfo = publicationService.getPublicationInfo(node.getIdentifier(),
                    Collections.singleton(language), includesReferences, includesSubnodes, false,
                    currentUserSession.getWorkspace().getName(), Constants.LIVE_WORKSPACE).get(0);
            if (!includesSubnodes) {
                // We don't include subnodes, but we still need the translation nodes to get the correct status
                final JCRSessionWrapper unlocalizedSession = JCRSessionFactory.getInstance()
                        .getCurrentUserSession();

                final JCRNodeWrapper nodeByIdentifier = unlocalizedSession
                        .getNodeByIdentifier(node.getIdentifier());
                String langNodeName = "j:translation_" + language;
                if (nodeByIdentifier.hasNode(langNodeName)) {
                    JCRNodeWrapper next = nodeByIdentifier.getNode(langNodeName);
                    PublicationInfo translationInfo = publicationService
                            .getPublicationInfo(next.getIdentifier(), Collections.singleton(language),
                                    includesReferences, false, false,
                                    currentUserSession.getWorkspace().getName(), Constants.LIVE_WORKSPACE)
                            .get(0);
                    pubInfo.getRoot().addChild(translationInfo.getRoot());
                }
            }

            GWTJahiaPublicationInfo gwtInfo = new GWTJahiaPublicationInfo(pubInfo.getRoot().getUuid(),
                    pubInfo.getRoot().getStatus());
            //                if (pubInfo.getRoot().isLocked()  ) {
            //                gwtInfo.setLocked(true);
            //                }
            String translationNodeName = pubInfo.getRoot().getChildren().size() > 0
                    ? "/j:translation_" + language
                    : null;
            for (PublicationInfoNode sub : pubInfo.getRoot().getChildren()) {
                if (sub.getPath().contains(translationNodeName)) {
                    if (sub.getStatus() > gwtInfo.getStatus()) {
                        gwtInfo.setStatus(sub.getStatus());
                    }
                    if (gwtInfo.getStatus() == GWTJahiaPublicationInfo.UNPUBLISHED
                            && sub.getStatus() != GWTJahiaPublicationInfo.UNPUBLISHED) {
                        gwtInfo.setStatus(sub.getStatus());
                    }
                    if (sub.isLocked()) {
                        gwtInfo.setLocked(true);
                    }
                    if (sub.isWorkInProgress()) {
                        gwtInfo.setWorkInProgress(true);
                    }
                }
            }

            gwtInfo.setIsAllowedToPublishWithoutWorkflow(node.hasPermission("publish"));
            gwtInfo.setIsNonRootMarkedForDeletion(
                    gwtInfo.getStatus() == GWTJahiaPublicationInfo.MARKED_FOR_DELETION
                            && !node.isNodeType("jmix:markedForDeletionRoot"));

            if (gwtInfo.getStatus() == GWTJahiaPublicationInfo.PUBLISHED) {
                // the item status is published: check if the tree status or references are modified or unpublished
                Set<Integer> status = pubInfo.getTreeStatus(language);
                boolean overrideStatus = !status.isEmpty()
                        && Collections.max(status) > GWTJahiaPublicationInfo.PUBLISHED;
                if (!overrideStatus) {
                    // check references
                    for (PublicationInfo refInfo : pubInfo.getAllReferences()) {
                        status = refInfo.getTreeStatus(language);
                        if (!status.isEmpty() && Collections.max(status) > GWTJahiaPublicationInfo.PUBLISHED) {
                            overrideStatus = true;
                            break;
                        }
                    }
                }
                if (overrideStatus) {
                    gwtInfo.setStatus(GWTJahiaPublicationInfo.MODIFIED);
                }
            }

            infos.put(language, gwtInfo);
        }
        return infos;
    } catch (RepositoryException e) {
        logger.error("repository exception", e);
        throw new GWTJahiaServiceException("Cannot get publication status for node " + node.getPath()
                + ". Cause: " + e.getLocalizedMessage(), e);
    }

}