Example usage for java.util LinkedHashMap size

List of usage examples for java.util LinkedHashMap size

Introduction

In this page you can find the example usage for java.util LinkedHashMap size.

Prototype

int size();

Source Link

Document

Returns the number of key-value mappings in this map.

Usage

From source file:org.peerfact.impl.service.aggregation.skyeye.visualization.SkyNetVisualization.java

public void updateDisplayedMetrics(long time, LinkedHashMap<String, MetricsAggregate> simulatorMetrics,
        LinkedHashMap<String, MetricsAggregate> rootMetrics/*
                                                           * , double
                                                           * nodeCounter
                                                           */) {
    if (activated && displayedMetrics.size() > 0) {
        Iterator<String> nameIter = simulatorMetrics.keySet().iterator();
        String name = null;/*from w  w w.  j a v a2 s.co m*/
        while (nameIter.hasNext()) {
            name = nameIter.next();
            if (displayedMetrics.containsKey(name)) {
                DeviationSet[] values = null;
                if (rootMetrics.size() > 0) {
                    DeviationSet[] temp = { new DeviationSet(simulatorMetrics.get(name).getAverage()),
                            new DeviationSet(rootMetrics.get(name).getAverage(),
                                    rootMetrics.get(name).getStandardDeviation()),
                            new DeviationSet(rootMetrics.get(name).getMinimum()),
                            new DeviationSet(rootMetrics.get(name).getMaximum()) };
                    values = temp;
                } else {
                    DeviationSet[] temp = { new DeviationSet(simulatorMetrics.get(name).getAverage()),
                            new DeviationSet(0), new DeviationSet(0), new DeviationSet(0), };
                    values = temp;
                }
                String[] metricNames = { "Real " + name, "Measured " + name, "Min_Measured" + name,
                        "Max_Measured" + name };

                MetricsPlot temp = displayedMetrics.remove(name);
                temp.updatePlot(name, new DataSet(VisualizationType.Metric, time / 1000, values, metricNames));
                displayedMetrics.put(name, temp);
                updatePlotInWindow(time, name);
            }
        }
        validate();
        repaint();
    }
}

From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

private void orderAndFilterOutTheActiveLog(LinkedHashMap<FTPFile, String> retList) {
    if (retList.size() > 0) {
        String[] ordList = retList.values().toArray(new String[retList.size()]);
        Arrays.sort(ordList);/*from  w w w  .j av  a  2 s  . c  o  m*/
        String activeLogName = ordList[ordList.length - 1];
        for (FTPFile fFile : retList.keySet().toArray(new FTPFile[retList.size()])) {
            if (retList.get(fFile).equals(activeLogName)) {
                retList.remove(fFile);
                break;
            }
        }
    }
}

From source file:com.simiacryptus.mindseye.applications.ObjectLocationBase.java

/**
 * Run.//  w  ww  .jav  a2s .c  o m
 *
 * @param log the log
 */
public void run(@Nonnull final NotebookOutput log) {
    //    @Nonnull String logName = "cuda_" + log.getName() + ".log";
    //    log.p(log.file((String) null, logName, "GPU Log"));
    //    CudaSystem.addLog(new PrintStream(log.file(logName)));

    ImageClassifierBase classifier = getClassifierNetwork();
    Layer classifyNetwork = classifier.getNetwork();

    ImageClassifierBase locator = getLocatorNetwork();
    Layer locatorNetwork = locator.getNetwork();
    ArtistryUtil.setPrecision((DAGNetwork) classifyNetwork, Precision.Float);
    ArtistryUtil.setPrecision((DAGNetwork) locatorNetwork, Precision.Float);

    Tensor[][] inputData = loadImages_library();
    //    Tensor[][] inputData = loadImage_Caltech101(log);
    double alphaPower = 0.8;

    final AtomicInteger index = new AtomicInteger(0);
    Arrays.stream(inputData).limit(10).forEach(row -> {
        log.h3("Image " + index.getAndIncrement());
        final Tensor img = row[0];
        log.p(log.image(img.toImage(), ""));
        Result classifyResult = classifyNetwork.eval(new MutableResult(row));
        Result locationResult = locatorNetwork.eval(new MutableResult(row));
        Tensor classification = classifyResult.getData().get(0);
        List<CharSequence> categories = classifier.getCategories();
        int[] sortedIndices = IntStream.range(0, categories.size()).mapToObj(x -> x)
                .sorted(Comparator.comparing(i -> -classification.get(i))).mapToInt(x -> x).limit(10).toArray();
        logger.info(Arrays.stream(sortedIndices)
                .mapToObj(
                        i -> String.format("%s: %s = %s%%", i, categories.get(i), classification.get(i) * 100))
                .reduce((a, b) -> a + "\n" + b).orElse(""));
        LinkedHashMap<CharSequence, Tensor> vectors = new LinkedHashMap<>();
        List<CharSequence> predictionList = Arrays.stream(sortedIndices).mapToObj(categories::get)
                .collect(Collectors.toList());
        Arrays.stream(sortedIndices).limit(6).forEach(category -> {
            CharSequence name = categories.get(category);
            log.h3(name);
            Tensor alphaTensor = renderAlpha(alphaPower, img, locationResult, classification, category);
            log.p(log.image(img.toRgbImageAlphaMask(0, 1, 2, alphaTensor), ""));
            vectors.put(name, alphaTensor.unit());
        });

        Tensor avgDetection = vectors.values().stream().reduce((a, b) -> a.add(b)).get()
                .scale(1.0 / vectors.size());
        Array2DRowRealMatrix covarianceMatrix = new Array2DRowRealMatrix(predictionList.size(),
                predictionList.size());
        for (int x = 0; x < predictionList.size(); x++) {
            for (int y = 0; y < predictionList.size(); y++) {
                Tensor l = vectors.get(predictionList.get(x));
                Tensor r = vectors.get(predictionList.get(y));

                covarianceMatrix.setEntry(x, y,
                        null == l || null == r ? 0 : (l.minus(avgDetection)).dot(r.minus(avgDetection)));
            }
        }
        @Nonnull
        final EigenDecomposition decomposition = new EigenDecomposition(covarianceMatrix);

        for (int objectVector = 0; objectVector < 10; objectVector++) {
            log.h3("Eigenobject " + objectVector);
            double eigenvalue = decomposition.getRealEigenvalue(objectVector);
            RealVector eigenvector = decomposition.getEigenvector(objectVector);
            Tensor detectionRegion = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> {
                Tensor tensor = vectors.get(predictionList.get(i));
                return null == tensor ? null : tensor.scale(eigenvector.getEntry(i));
            }).filter(x -> null != x).reduce((a, b) -> a.add(b)).get();
            detectionRegion = detectionRegion.scale(255.0 / detectionRegion.rms());
            CharSequence categorization = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> {
                CharSequence category = predictionList.get(i);
                double component = eigenvector.getEntry(i);
                return String.format("<li>%s = %.4f</li>", category, component);
            }).reduce((a, b) -> a + "" + b).get();
            log.p(String.format("Object Detected: <ol>%s</ol>", categorization));
            log.p("Object Eigenvalue: " + eigenvalue);
            log.p("Object Region: " + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion), ""));
            log.p("Object Region Compliment: "
                    + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion.scale(-1)), ""));
        }

        //      final int[] orderedVectors = IntStream.range(0, 10).mapToObj(x -> x)
        //        .sorted(Comparator.comparing(x -> -decomposition.getRealEigenvalue(x))).mapToInt(x -> x).toArray();
        //      IntStream.range(0, orderedVectors.length)
        //        .mapToObj(i -> {
        //            //double realEigenvalue = decomposition.getRealEigenvalue(orderedVectors[i]);
        //            return decomposition.getEigenvector(orderedVectors[i]).toArray();
        //          }
        //        ).toArray(i -> new double[i][]);

        log.p(String.format(
                "<table><tr><th>Cosine Distance</th>%s</tr>%s</table>", Arrays.stream(sortedIndices).limit(10)
                        .mapToObj(col -> "<th>" + categories.get(col) + "</th>").reduce((a, b) -> a + b).get(),
                Arrays.stream(sortedIndices).limit(10).mapToObj(r -> {
                    return String.format("<tr><td>%s</td>%s</tr>", categories.get(r),
                            Arrays.stream(sortedIndices).limit(10).mapToObj(col -> {
                                Tensor l = vectors.get(categories.get(r));
                                Tensor r2 = vectors.get(categories.get(col));
                                return String.format("<td>%.4f</td>",
                                        (null == l || null == r2) ? 0 : Math.acos(l.dot(r2)));
                            }).reduce((a, b) -> a + b).get());
                }).reduce((a, b) -> a + b).orElse("")));
    });

    log.setFrontMatterProperty("status", "OK");
}

From source file:com.netflix.imfutility.itunes.audio.AudioMapXmlProvider.java

/**
 * Gets pan parameter for track.//www.j  a va2s.c  o  m
 * <p></p>
 * Example: pan=4c|c0=c0|c1=c1|c2=c2|c3=c3,aformat=channel_layouts=FL+FR+FC+LFE
 *
 * @param track audio track
 * @return pan parameter for track
 */
private String getPanParameter(LinkedHashMap<String, ChannelType> track) {
    int[] i = { 0 };
    StringJoiner aformat = new StringJoiner("+", ",aformat=channel_layouts=", ""); // ,aformat=channel_layouts=
    StringBuilder panParameter = new StringBuilder("pan="); // pan=
    panParameter.append(track.size()).append("c"); // pan=4c
    track.forEach((chName, channel) -> {
        panParameter.append("|c").append(i[0]).append("="); // pan=4c|c0=

        // gets channel number in amerge channels sequence
        int sequencedChannel = sequencedTrackChannelNumbers.indexOf(
                getIntermediateKey(channel.getCPLVirtualTrackId(), channel.getCPLVirtualTrackChannel() - 1));
        if (sequencedChannel == -1) {
            throw new ConversionException(String.format(
                    "Audio Virtual TrackId \"%s\" with channel number \"%d\" was not found in CPL.",
                    channel.getCPLVirtualTrackId(), channel.getCPLVirtualTrackChannel()));
        }
        panParameter.append("c").append(sequencedChannel); // pan=4c|c0=c0

        aformat.add(chName); // ,aformat=channel_layouts=FL

        i[0]++;
    });
    panParameter.append(aformat); // pan=4c|c0=c0|c1=c1|c2=c2|c3=c3,aformat=channel_layouts=FL+FR+FC+LFE

    return panParameter.toString();
}

From source file:org.modmine.web.ModMineSearchResultsController.java

/**
 * {@inheritDoc}//ww w .jav a 2 s .c  om
 */
@Override
public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());

    ModMineSearch.initModMineSearch(im);
    LinkedHashMap<Submission, Integer> submissions = new LinkedHashMap<Submission, Integer>();

    String searchTerm = request.getParameter("searchTerm");
    LOG.info("SEARCH TERM: '" + searchTerm + "'");
    if (!StringUtils.isBlank(searchTerm) && !searchTerm.trim().equals('*')) {
        Map<Integer, Float> searchResults = ModMineSearch.runLuceneSearch(searchTerm);

        Set<Integer> objectIds = searchResults.keySet();

        LOG.info("SEARCH HITS: " + searchResults.size());

        Map<Integer, Submission> objMap = new HashMap<Integer, Submission>();
        for (InterMineObject obj : im.getObjectStore().getObjectsByIds(objectIds)) {
            objMap.put(obj.getId(), (Submission) obj);
        }
        LOG.info("SEARCH - OBJS: " + objMap.size());

        for (Map.Entry<Integer, Float> entry : searchResults.entrySet()) {
            //make sure scores are in the range [1, 10]
            submissions.put(objMap.get(entry.getKey()),
                    new Integer(Math.round(Math.max(0.1F, Math.min(1, entry.getValue())) * 10)));
        }
    }
    LOG.info("SEARCH SUBS: " + submissions.size());
    request.setAttribute("submissions", submissions);

    request.setAttribute("searchTerm", "THE SEARCH TERM");
    if (searchTerm != null) {
        context.putAttribute("searchTerm", searchTerm);
        context.putAttribute("submissions", request.getAttribute("submissions"));

        if (submissions.size() == ModMineSearch.MAX_HITS) {
            context.putAttribute("displayMax", ModMineSearch.MAX_HITS);
        }
    }
    return null;
}

From source file:ubic.gemma.visualization.ExperimentalDesignVisualizationServiceImpl.java

/**
 * Test method for now, shows how this can be used.
 * /*from   ww  w . j  ava 2 s . c om*/
 * @param e
 */
protected void plotExperimentalDesign(ExpressionExperiment e) {
    LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> layout = getExperimentalDesignLayout(
            e);

    List<String> efStrings = new ArrayList<String>();
    List<String> baStrings = new ArrayList<String>();
    List<double[]> rows = new ArrayList<double[]>();
    boolean first = true;
    int i = 0;
    for (BioAssayValueObject ba : layout.keySet()) {
        baStrings.add(ba.getName());

        int j = 0;
        for (ExperimentalFactor ef : layout.get(ba).keySet()) {
            if (first) {
                double[] nextRow = new double[layout.size()];
                rows.add(nextRow);
                efStrings.add(ef.getName() + " ( id=" + ef.getId() + ")"); // make sure they are unique.
            }
            double d = layout.get(ba).get(ef);

            rows.get(j)[i] = d;
            j++;
        }
        i++;
        first = false;
    }

    double[][] mat = rows.toArray(new double[][] {});

    DoubleMatrix<String, String> data = DoubleMatrixFactory.dense(mat);
    data.setRowNames(efStrings);
    data.setColumnNames(baStrings);

    ColorMatrix<String, String> cm = new ColorMatrix<String, String>(data, ColorMap.GREENRED_COLORMAP,
            Color.GRAY);

    try {
        writeImage(cm, File.createTempFile(e.getShortName() + "_", ".png"));
    } catch (IOException e1) {
        throw new RuntimeException(e1);
    }
}

From source file:com.google.gwt.emultest.java.util.LinkedHashMapTest.java

/**
 * Test method for 'java.util.LinkedHashMap.putAll(Map)'.
 *///from w  w  w .j a va 2s  .  c om
public void testPutAll() {
    LinkedHashMap<String, String> srcMap = new LinkedHashMap<String, String>();
    checkEmptyLinkedHashMapAssumptions(srcMap);

    srcMap.put(KEY_1, VALUE_1);
    srcMap.put(KEY_2, VALUE_2);
    srcMap.put(KEY_3, VALUE_3);

    // Make sure that the data is copied correctly
    LinkedHashMap<String, String> dstMap = new LinkedHashMap<String, String>();
    checkEmptyLinkedHashMapAssumptions(dstMap);

    dstMap.putAll(srcMap);
    assertEquals(srcMap.size(), dstMap.size());
    assertTrue(dstMap.containsKey(KEY_1));
    assertTrue(dstMap.containsValue(VALUE_1));
    assertFalse(dstMap.containsKey(KEY_1.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_1.toUpperCase(Locale.ROOT)));

    assertTrue(dstMap.containsKey(KEY_2));
    assertTrue(dstMap.containsValue(VALUE_2));
    assertFalse(dstMap.containsKey(KEY_2.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_2.toUpperCase(Locale.ROOT)));

    assertTrue(dstMap.containsKey(KEY_3));
    assertTrue(dstMap.containsValue(VALUE_3));
    assertFalse(dstMap.containsKey(KEY_3.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_3.toUpperCase(Locale.ROOT)));

    // Check that an empty map does not blow away the contents of the
    // destination map
    LinkedHashMap<String, String> emptyMap = new LinkedHashMap<String, String>();
    checkEmptyLinkedHashMapAssumptions(emptyMap);
    dstMap.putAll(emptyMap);
    assertTrue(dstMap.size() == srcMap.size());

    // Check that put all overwrite any existing mapping in the destination map
    srcMap.put(KEY_1, VALUE_2);
    srcMap.put(KEY_2, VALUE_3);
    srcMap.put(KEY_3, VALUE_1);

    dstMap.putAll(srcMap);
    assertEquals(dstMap.size(), srcMap.size());
    assertEquals(dstMap.get(KEY_1), VALUE_2);
    assertEquals(dstMap.get(KEY_2), VALUE_3);
    assertEquals(dstMap.get(KEY_3), VALUE_1);

    // Check that a putAll does adds data but does not remove it

    srcMap.put(KEY_4, VALUE_4);
    dstMap.putAll(srcMap);
    assertEquals(dstMap.size(), srcMap.size());
    assertTrue(dstMap.containsKey(KEY_4));
    assertTrue(dstMap.containsValue(VALUE_4));
    assertEquals(dstMap.get(KEY_1), VALUE_2);
    assertEquals(dstMap.get(KEY_2), VALUE_3);
    assertEquals(dstMap.get(KEY_3), VALUE_1);
    assertEquals(dstMap.get(KEY_4), VALUE_4);

    dstMap.putAll(dstMap);
}

From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

private void showInGuiNumberOfLogsFromServers(LinkedHashMap<FTPFile, String> retList)
        throws InterruptedException, InvocationTargetException {
    if (retList.size() == 0) {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override/*w w  w .  j ava  2 s  .c  o  m*/
            public void run() {
                gui.listHandlingProgressBar.setValue(100);
                gui.listHandlingProgressBar.setIndeterminate(false);
                gui.listHandlingProgressBar.setString(I18n.text("No logs..."));
            }
        });
    } else {
        final String msg1 = I18n.textf("Log Folders: %numberoffolders", retList.size());
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                // listHandlingProgressBar.setValue(10);
                // listHandlingProgressBar.setIndeterminate(true);
                gui.listHandlingProgressBar.setString(msg1);
            }
        });
    }
}

From source file:Simulator.PerformanceCalculation.java

JPanel minmaxwaitTime2(boolean minCheck) {
    LinkedHashSet no = new LinkedHashSet();
    LinkedHashMap<Integer, ArrayList<Double>> wait1 = new LinkedHashMap<>();

    for (Map.Entry<Integer, TraceObject> entry : l.getLocalTrace().entrySet()) {
        TraceObject traceObject = entry.getValue();

        if (wait1.get(traceObject.getSurgeonId()) == null) {
            ArrayList details = new ArrayList();
            details.add(traceObject.getWaitTime2());
            wait1.put(traceObject.getSurgeonId(), details);
        } else {/*from  w ww  .  jav a2  s  .  c  o m*/
            wait1.get(traceObject.getSurgeonId()).add(traceObject.getWaitTime2());
        }

        no.add(traceObject.getSurgeonId());
    }

    XYSeriesCollection dataset = new XYSeriesCollection();

    LinkedHashMap<Integer, Double> average = new LinkedHashMap<>();

    for (Map.Entry<Integer, ArrayList<Double>> entry : wait1.entrySet()) {
        Integer integer = entry.getKey();
        ArrayList<Double> arrayList = entry.getValue();
        double value = 0;
        if (minCheck) {
            value = Collections.min(arrayList);
            value = value / 600;
        } else {
            value = Collections.max(arrayList);
            value = value / 600;
        }

        average.put(integer, value);
    }

    XYSeries series = new XYSeries("Surgeon Minimum Wait Time 2");
    for (int i = 1; i <= average.size(); i++) {
        series.add(i, average.get(i));
    }
    dataset.addSeries(series);
    String name;
    if (minCheck) {
        name = "Minimum";
    } else {
        name = "Maximum";
    }
    // Generate the graph
    JFreeChart chart = ChartFactory.createXYLineChart(name + " Wait Time 2 For Patients", // Title
            "Surgeon ID", // x-axis Label
            "Time (Days)", // y-axis Label
            dataset, // Dataset
            PlotOrientation.VERTICAL, // Plot Orientation
            true, // Show Legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );

    XYPlot xyPlot = (XYPlot) chart.getPlot();

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyPlot.getRenderer();
    renderer.setBaseShapesVisible(true);
    NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
    domain.setVerticalTickLabels(true);

    return new ChartPanel(chart);
}

From source file:Simulator.PerformanceCalculation.java

JPanel minmaxwaitTime1(boolean minCheck) {
    LinkedHashSet no = new LinkedHashSet();
    LinkedHashMap<Integer, ArrayList<Double>> wait1 = new LinkedHashMap<>();

    for (Map.Entry<Integer, TraceObject> entry : l.getLocalTrace().entrySet()) {
        TraceObject traceObject = entry.getValue();

        if (wait1.get(traceObject.getSurgeonId()) == null) {
            ArrayList details = new ArrayList();
            details.add(traceObject.getWaitTime1());
            wait1.put(traceObject.getSurgeonId(), details);
        } else {/* w  w  w .  ja v  a 2  s .c o  m*/
            wait1.get(traceObject.getSurgeonId()).add(traceObject.getWaitTime1());
        }

        no.add(traceObject.getSurgeonId());
    }

    XYSeriesCollection dataset = new XYSeriesCollection();

    LinkedHashMap<Integer, Double> average = new LinkedHashMap<>();

    for (Map.Entry<Integer, ArrayList<Double>> entry : wait1.entrySet()) {
        Integer integer = entry.getKey();
        ArrayList<Double> arrayList = entry.getValue();
        double value = 0;
        if (minCheck) {
            value = Collections.min(arrayList);
            value = value / 600;
        } else {
            value = Collections.max(arrayList);
            value = value / 600;
        }

        average.put(integer, value);
    }

    XYSeries series = new XYSeries("Surgeon Minimum Wait Time 1");
    for (int i = 1; i <= average.size(); i++) {
        series.add(i, average.get(i));
    }
    dataset.addSeries(series);
    String name;
    if (minCheck) {
        name = "Minimum";
    } else {
        name = "Maximum";
    }
    // Generate the graph
    JFreeChart chart = ChartFactory.createXYLineChart(name + " Wait Time 1 For Patients", // Title
            "Surgeon ID", // x-axis Label
            "Time (Days)", // y-axis Label
            dataset, // Dataset
            PlotOrientation.VERTICAL, // Plot Orientation
            true, // Show Legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );

    XYPlot xyPlot = (XYPlot) chart.getPlot();

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyPlot.getRenderer();
    renderer.setBaseShapesVisible(true);
    NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
    domain.setVerticalTickLabels(true);

    return new ChartPanel(chart);
}