Example usage for java.util ListIterator hasNext

List of usage examples for java.util ListIterator hasNext

Introduction

In this page you can find the example usage for java.util ListIterator hasNext.

Prototype

boolean hasNext();

Source Link

Document

Returns true if this list iterator has more elements when traversing the list in the forward direction.

Usage

From source file:com.edgenius.wiki.render.macro.ProgressMacro.java

protected void replaceHTML(HTMLNode node, ListIterator<HTMLNode> iter, RenderContext context) {
    if (node.getPair() == null) {
        log.warn("Unexpect case: No close tag for " + this.getClass().getName());
        return;/* w  ww  .ja v  a 2 s. c o  m*/
    }
    node.getPair().reset("", true);

    String value = null, height = null, width = null, text = "";

    if (node.getStyle() != null) {
        height = node.getStyle().get("height");
        width = node.getStyle().get("width");
    }
    if (DEFAULT_HEIGHT.equalsIgnoreCase(height)) {
        height = null;
    }
    if (DEFAULT_WIDTH.equalsIgnoreCase(width)) {
        width = null;
    }

    //reset all inside node to blank
    //!!! Here changes ListIterator cursor position!!!
    HTMLNode reqireText = null;
    HTMLNode subnode;
    for (; iter.hasNext();) {
        subnode = iter.next();
        if (subnode == node.getPair())
            break;

        if (!subnode.isTextNode()) {
            if (subnode.getAttributes() != null) {
                if (subnode.getAttributes().get("class").equalsIgnoreCase("value")
                        && subnode.getStyle() != null) {
                    value = subnode.getStyle().get("width");
                } else if (subnode.getAttributes().get("class").equalsIgnoreCase("text")) {
                    reqireText = subnode.getPair();
                }
            }
            if (reqireText != null && reqireText == subnode) {
                reqireText = null;
            }
            subnode.reset("", true);
            if (subnode.getPair() != null)
                subnode.getPair().reset("", true);
        } else {
            if (reqireText != null) {
                text += subnode.getText();
            }
            subnode.reset("", true);
        }
    }

    if (DEFAULT_VALUE.equalsIgnoreCase(value)) {
        value = null;
    }

    StringBuffer sb = new StringBuffer("{progress");
    boolean dirty = false;
    if (value != null) {
        dirty = true;
        sb.append(":complete=").append(value);
    }
    if (width != null) {
        sb.append(dirty ? "|" : ":").append("width=").append(GwtUtils.removeUnit(width));
        dirty = true;
    }
    if (height != null) {
        sb.append(dirty ? "|" : ":").append("height=").append(GwtUtils.removeUnit(height));
        dirty = true;
    }
    if (!StringUtils.isBlank(text)) {
        sb.append(dirty ? "|" : ":").append("text=").append(text.trim());
        dirty = true;
    }
    sb.append("}");

    node.reset(sb.toString(), true);
}

From source file:ipnat.skel.Strahler.java

/**
 * This method is called when the plugin is loaded.
 *
 * @param arg/*from   w  w  w  . ja va2 s.  c om*/
 *            the arguments as specified in {@code plugins.config}
 *
 */
@Override
public void run(final String arg) {

    // Retrieve analysis image and its ROI
    srcImp = WindowManager.getCurrentImage();
    if (!validRequirements(srcImp))
        return;

    title = srcImp.getTitle();
    rootRoi = srcImp.getRoi();
    validRootRoi = (rootRoi != null && rootRoi.getType() == Roi.RECTANGLE);

    // TODO: 3D Roots are special. We need to:
    // 1) Check if ROI is associated with all slices or just one
    // 2) Ignore counts above/below the ROI, as needed
    // 3) Extend ip operations to stack
    if (srcImp.getNSlices() > 1) {
        final String warning = "3D images are currently supported with the following limitations:\n"
                + "    - 'Root-protecting' ROIs are not yet supported\n"
                + "    - Lengths are estimated from Z-projections\n \n"
                + "These issues will be addressed in future releases.";
        if (IJ.macroRunning())
            IJ.log(warning);
        else
            IJ.showMessage("Warning", warning);
        validRootRoi = false;
    }

    // Retrieve grayscale image for intensity-based pruning of skel. loops
    if (!getSettings())
        return;

    // Work on a skeletonized copy since we'll be modifing the image
    if (rootRoi != null)
        srcImp.killRoi();
    final ImagePlus imp = srcImp.duplicate();
    if (rootRoi != null)
        srcImp.setRoi(rootRoi);
    ip = imp.getProcessor();
    skeletonizeWithoutHermits(imp);

    // Initialize ResultsTable: main and detailed info
    final ResultsTable rt = Utils.getTable(STRAHLER_TABLE);
    final ResultsTable logrt = Utils.getTable(VERBOSE_TABLE);

    // Analyze root
    ImagePlus rootImp;
    ImageProcessor rootIp = null;
    SkeletonResult rootResult = null;
    ArrayList<Point> rootEndpointsList = null;
    int nRootEndpoints = 0, nRootJunctions = 0;

    if (validRootRoi && verbose) {

        // Duplicate entire canvas. Ignore tree(s) outside ROI
        rootImp = imp.duplicate();
        rootIp = rootImp.getProcessor();
        rootIp.setValue(0.0);
        rootIp.fillOutside(rootRoi);

        // Get root properties
        final AnalyzeSkeleton_ root = new AnalyzeSkeleton_();
        root.setup("", rootImp);
        rootResult = root.run(pruneChoice, false, false, grayscaleImp, true, false);
        rootImp.flush();

        // We assume ROI contains only end-point branches, slab voxels and
        // no junction points. We'll thus remove end-points at ROI
        // boundaries
        nRootJunctions = sum(rootResult.getJunctions());
        rootEndpointsList = rootResult.getListOfEndPoints();
        final ListIterator<Point> it = rootEndpointsList.listIterator();
        final Rectangle r = rootRoi.getBounds();
        while (it.hasNext()) {
            final Point p = it.next();
            if (p.x == r.x || p.y == r.y || p.x == (int) (r.x + r.getWidth() - 1)
                    || p.y == (int) (r.y + r.getHeight() - 1))
                it.remove();
        }
        rootResult.setListOfEndPoints(rootEndpointsList);
        nRootEndpoints = rootEndpointsList.size();

    }

    // Initialize display images. Use Z-projections to populate
    // iteration stack when dealing with 3D skeletons
    final int nSlices = imp.getNSlices();
    ZProjector zp = null;

    final ImageStack iterationStack = new ImageStack(imp.getWidth(), imp.getHeight());
    if (nSlices > 1) {
        zp = new ZProjector(imp);
        zp.setMethod(ZProjector.MAX_METHOD);
        zp.setStartSlice(1);
        zp.setStopSlice(nSlices);
    }

    // Initialize AnalyzeSkeleton_
    final AnalyzeSkeleton_ as = new AnalyzeSkeleton_();
    as.setup("", imp);

    // Perform the iterative pruning
    int order = 1, nEndpoints = 0, nJunctions = 0, nJunctions2 = 0;
    ArrayList<Point> endpointsList = null, junctionsList = null;
    String errorMsg = "";

    do {

        IJ.showStatus("Retrieving measurements for order " + order + "...");
        IJ.showProgress(order, getMaxOrder());

        // (Re)skeletonize image
        if (order > 1)
            skeletonizeWithoutHermits(imp);

        // Get properties of loop-resolved tree(s)
        final SkeletonResult sr = as.run(pruneChoice, false, false, grayscaleImp, true, false);
        nEndpoints = sum(sr.getEndPoints());
        nJunctions = sum(sr.getJunctions());

        if (order == 1) {
            // Remember initial properties
            endpointsList = sr.getListOfEndPoints();
            junctionsList = sr.getListOfJunctionVoxels();

            // Do not include root in 1st order calculations
            nEndpoints -= nRootEndpoints;
            nJunctions -= nRootJunctions;
        }

        // Is it worth proceeding?
        if (nEndpoints == 0 || nJunctions2 == nJunctions) {
            errorMsg = "Error! Iteration " + order + " aborted: ";
            errorMsg += (nEndpoints == 0) ? "No end-poins found" : "Unsolved loop(s) detected";
            break;
        }

        // Add current tree(s) to debug animation
        ImageProcessor ipd;
        if (nSlices > 1) {
            zp.doProjection();
            ipd = zp.getProjection().getProcessor();
        } else {
            ipd = ip.duplicate();
        }
        iterationStack.addSlice("Order " + IJ.pad(order, 2), ipd);

        // Report properties of pruned structures
        if (verbose) {
            logrt.incrementCounter();
            logrt.addValue("Image", title);
            logrt.addValue("Structure", "Skel. at iteration " + Integer.toString(order));
            logrt.addValue("Notes", errorMsg);
            logrt.addValue("# Trees", sr.getNumOfTrees());
            logrt.addValue("# Branches", sum(sr.getBranches()));
            logrt.addValue("# End-points", nEndpoints);
            logrt.addValue("# Junctions", nJunctions);
            logrt.addValue("# Triple points", sum(sr.getTriples()));
            logrt.addValue("# Quadruple points", sum(sr.getQuadruples()));
            logrt.addValue("Average branch length", average(sr.getAverageBranchLength()));
        }

        // Remember main results
        nJunctions2 = nJunctions;

        // Eliminate end-points
        as.run(pruneChoice, true, false, grayscaleImp, true, false, rootRoi);

    } while (order++ <= getMaxOrder() && nJunctions > 0);

    // Set counter to the de facto order
    order -= 1;

    // Append root properties to log table
    if (validRootRoi && verbose) {

        // Check if ROI contains unexpected structures
        final String msg = (nRootJunctions > 0) ? "Warning: ROI contains ramified root(s)"
                : "Root-branches inferred from ROI";
        logrt.incrementCounter();
        logrt.addValue("Image", title);
        logrt.addValue("Structure", "Root");
        logrt.addValue("Notes", msg);
        logrt.addValue("# Trees", rootResult.getNumOfTrees());
        logrt.addValue("# Branches", sum(rootResult.getBranches()));
        logrt.addValue("# End-points", nRootEndpoints);
        logrt.addValue("# Junctions", nRootJunctions);
        logrt.addValue("# Triple points", sum(rootResult.getTriples()));
        logrt.addValue("# Quadruple points", sum(rootResult.getQuadruples()));
        logrt.addValue("Average branch length", average(rootResult.getAverageBranchLength()));

    }

    // Safety check
    if (iterationStack == null || iterationStack.getSize() < 1) {
        error("Enable \"detailed\" mode and check " + VERBOSE_TABLE + " for details.");
        return;
    }

    // Create iteration stack
    final Calibration cal = srcImp.getCalibration();
    final ImagePlus imp2 = new ImagePlus("StrahlerIteration_" + title, iterationStack);
    imp2.setCalibration(cal);
    if (outIS) {
        if (validRootRoi) {
            iterationStack.addSlice("Root", rootIp);
            paintPoints(iterationStack, rootEndpointsList, 255, "Root end-points");
            imp2.setRoi(rootRoi);
        }
        paintPoints(iterationStack, endpointsList, 255, "End-points");
        paintPoints(iterationStack, junctionsList, 255, "Junction-points");
    }

    // Generate Strahler mask
    zp = new ZProjector(imp2);
    zp.setMethod(ZProjector.SUM_METHOD);
    zp.setStartSlice(1);
    zp.setStopSlice(order);
    zp.doProjection();
    final ImageProcessor ip3 = zp.getProjection().getProcessor().convertToShortProcessor(false);
    clearPoints(ip3, junctionsList); // disconnect branches
    ip3.multiply(1 / 255.0); // map intensities to Strahler orders
    final ImagePlus imp3 = new ImagePlus("StrahlerMask_" + title, ip3);
    imp3.setCalibration(cal);

    // Measure segmented orders
    double prevNbranches = Double.NaN;
    for (int i = 1; i <= order; i++) {

        // Segment branches by order
        final ImagePlus maskImp = imp3.duplicate(); // Calibration is
        // retained
        IJ.setThreshold(maskImp, i, i);
        IJ.run(maskImp, "Convert to Mask", "");

        // Analyze segmented order
        final AnalyzeSkeleton_ maskAs = new AnalyzeSkeleton_();
        maskAs.setup("", maskImp);
        final SkeletonResult maskSr = maskAs.run(pruneChoice, false, false, grayscaleImp, true, false);
        maskImp.flush();

        // Since all branches are disconnected at this stage, the n. of
        // branches is
        // the same as the # the trees unless zero-branches trees exist,
        // i.e., trees
        // with no slab voxels (defined by just an end-point). We will
        // ignore those
        // trees if the user requested it
        final int nBranches = (erodeIsolatedPixels) ? sum(maskSr.getBranches()) : maskSr.getNumOfTrees();

        // Log measurements
        rt.incrementCounter();
        rt.addValue("Image", title);
        rt.addValue("Strahler Order", i);
        rt.addValue("# Branches", nBranches);
        rt.addValue("Ramification ratios", prevNbranches / nBranches);
        rt.addValue("Average branch length", average(maskSr.getAverageBranchLength()));
        rt.addValue("Unit", cal.getUnit());
        String noteMsg = "";
        if (i == 1) {
            noteMsg = (erodeIsolatedPixels) ? "Ignoring" : "Including";
            noteMsg += " single-point arbors...";
        }
        rt.addValue("Notes", noteMsg);

        // Remember results for previous order
        prevNbranches = nBranches;

    }

    // Append any errors to last row
    rt.addValue("Notes", errorMsg);

    // Display outputs
    if (!tabular) {
        if (outIS)
            imp2.show();
        ip3.setMinAndMax(0, order);
        ColorMaps.applyMagmaColorMap(imp3, 200, false);
        if (validRootRoi)
            imp3.setRoi(rootRoi);
        imp3.show();
        addCalibrationBar(imp3, Math.min(order, 5), "Black");
    }
    if (verbose)
        logrt.show(VERBOSE_TABLE);
    rt.show(STRAHLER_TABLE);

    IJ.showProgress(0, 0);
    IJ.showTime(imp, imp.getStartTime(), "Strahler Analysis concluded... ");
    imp.flush();

}

From source file:com.ibm.asset.trails.action.ShowConfirmation.java

@UserRole(userRole = UserRoleType.READER)
public String deleteSelectedLicenses() {
    List<License> llLicense = getRecon().getLicenseList();
    ListIterator<License> lliLicense = null;
    License llTemp;//from   w w w.j  av a2  s.c o  m

    List<Report> lReport = new ArrayList<Report>();
    lReport.add(new Report("License baseline", "licenseBaseline"));
    setReportList(lReport);

    if (llLicense == null) {
        llLicense = new ArrayList<License>();
    }

    for (String lsLicenseId : selectedLicenseId) {
        lliLicense = llLicense.listIterator();

        while (lliLicense.hasNext()) {
            llTemp = lliLicense.next();

            if (llTemp.getId().compareTo(Long.valueOf(lsLicenseId)) == 0) {
                lliLicense.remove();
                break;
            }
        }
    }

    getRecon().setLicenseList(llLicense);
    recon.setAutomated(automated);
    recon.setManual(manual);
    recon.setRunon(runon);
    if (getMaxLicenses() != null && getMaxLicenses().trim().length() > 0) {
        recon.setMaxLicenses(new Integer(maxLicenses));
    }
    recon.setPer(per);

    return "license";
}

From source file:io.bibleget.BibleGetDB.java

public boolean renewMetaData() {
    if (instance.connect()) {
        try {//from w ww . j  ava  2  s.c o m
            DatabaseMetaData dbMeta;
            dbMeta = instance.conn.getMetaData();
            try (ResultSet rs3 = dbMeta.getTables(null, null, "METADATA", null)) {
                if (rs3.next()) {
                    //System.out.println("Table METADATA exists...");
                    try (Statement stmt = instance.conn.createStatement()) {
                        HTTPCaller myHTTPCaller = new HTTPCaller();
                        String myResponse;
                        myResponse = myHTTPCaller.getMetaData("biblebooks");
                        if (myResponse != null) {
                            JsonReader jsonReader = Json.createReader(new StringReader(myResponse));
                            JsonObject json = jsonReader.readObject();
                            JsonArray arrayJson = json.getJsonArray("results");
                            if (arrayJson != null) {
                                ListIterator pIterator = arrayJson.listIterator();
                                while (pIterator.hasNext()) {
                                    try (Statement stmt1 = instance.conn.createStatement()) {
                                        int index = pIterator.nextIndex();
                                        JsonArray currentJson = (JsonArray) pIterator.next();
                                        String biblebooks_str = currentJson.toString(); //.replaceAll("\"", "\\\\\"");
                                        //System.out.println("BibleGetDB line 267: BIBLEBOOKS"+Integer.toString(index)+"='"+biblebooks_str+"'");
                                        String stmt_str = "UPDATE METADATA SET BIBLEBOOKS"
                                                + Integer.toString(index) + "='" + biblebooks_str
                                                + "' WHERE ID=0";
                                        //System.out.println("executing update: "+stmt_str);
                                        int update = stmt1.executeUpdate(stmt_str);
                                        //System.out.println("executeUpdate resulted in: "+Integer.toString(update));
                                        stmt1.close();
                                    }
                                }
                            }

                            arrayJson = json.getJsonArray("languages");
                            if (arrayJson != null) {
                                try (Statement stmt2 = instance.conn.createStatement()) {
                                    String languages_str = arrayJson.toString(); //.replaceAll("\"", "\\\\\"");
                                    String stmt_str = "UPDATE METADATA SET LANGUAGES='" + languages_str
                                            + "' WHERE ID=0";
                                    int update = stmt2.executeUpdate(stmt_str);
                                    stmt2.close();
                                }
                            }
                        }

                        myResponse = myHTTPCaller.getMetaData("bibleversions");
                        if (myResponse != null) {
                            JsonReader jsonReader = Json.createReader(new StringReader(myResponse));
                            JsonObject json = jsonReader.readObject();
                            JsonObject objJson = json.getJsonObject("validversions_fullname");
                            if (objJson != null) {
                                String bibleversions_str = objJson.toString(); //.replaceAll("\"", "\\\\\"");
                                try (Statement stmt3 = instance.conn.createStatement()) {
                                    String stmt_str = "UPDATE METADATA SET VERSIONS='" + bibleversions_str
                                            + "' WHERE ID=0";
                                    int update = stmt3.executeUpdate(stmt_str);
                                    stmt3.close();
                                }

                                Set<String> versionsabbrev = objJson.keySet();
                                if (!versionsabbrev.isEmpty()) {
                                    String versionsabbrev_str = "";
                                    for (String s : versionsabbrev) {
                                        versionsabbrev_str += ("".equals(versionsabbrev_str) ? "" : ",") + s;
                                    }

                                    myResponse = myHTTPCaller
                                            .getMetaData("versionindex&versions=" + versionsabbrev_str);
                                    if (myResponse != null) {
                                        jsonReader = Json.createReader(new StringReader(myResponse));
                                        json = jsonReader.readObject();
                                        objJson = json.getJsonObject("indexes");
                                        if (objJson != null) {
                                            for (String name : objJson.keySet()) {
                                                JsonObjectBuilder tempBld = Json.createObjectBuilder();
                                                JsonObject book_num = objJson.getJsonObject(name);
                                                tempBld.add("book_num", book_num.getJsonArray("book_num"));
                                                tempBld.add("chapter_limit",
                                                        book_num.getJsonArray("chapter_limit"));
                                                tempBld.add("verse_limit",
                                                        book_num.getJsonArray("verse_limit"));
                                                JsonObject temp = tempBld.build();
                                                String versionindex_str = temp.toString(); //.replaceAll("\"", "\\\\\"");
                                                //add new column to METADATA table name+"IDX" VARCHAR(5000)
                                                //update METADATA table SET name+"IDX" = versionindex_str
                                                try (ResultSet rs1 = dbMeta.getColumns(null, null, "METADATA",
                                                        name + "IDX")) {
                                                    boolean updateFlag = false;
                                                    if (rs1.next()) {
                                                        //column already exists
                                                        updateFlag = true;
                                                    } else {
                                                        try (Statement stmt4 = instance.conn
                                                                .createStatement()) {
                                                            String sql = "ALTER TABLE METADATA ADD COLUMN "
                                                                    + name + "IDX VARCHAR(5000)";
                                                            boolean colAdded = stmt4.execute(sql);
                                                            if (colAdded == false) {
                                                                int count = stmt4.getUpdateCount();
                                                                if (count == -1) {
                                                                    //System.out.println("The result is a ResultSet object or there are no more results.");
                                                                } else if (count == 0) {
                                                                    //0 rows affected
                                                                    updateFlag = true;
                                                                }
                                                            }
                                                            stmt4.close();
                                                        }
                                                    }
                                                    if (updateFlag) {
                                                        try (Statement stmt5 = instance.conn
                                                                .createStatement()) {
                                                            String sql1 = "UPDATE METADATA SET " + name
                                                                    + "IDX='" + versionindex_str
                                                                    + "' WHERE ID=0";
                                                            boolean rowsUpdated = stmt5.execute(sql1);
                                                            stmt5.close();
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }

                                }

                            }
                        }

                        stmt.close();
                    }
                }
                rs3.close();
            }
            instance.disconnect();
        } catch (SQLException ex) {
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        return true;
    }
    return false;
}

From source file:com.impetus.kundera.query.KunderaQueryParser.java

private void buildFrom() {
    ListIterator<Expression> fromIter = null;
    if (query.isSelectStatement() && query.getSelectStatement().hasFromClause()) {
        FromClause fromClause = (FromClause) query.getSelectStatement().getFromClause();
        fromIter = fromClause.children().iterator();

    } else if (query.isUpdateStatement()) {
        fromIter = query.getUpdateStatement().getUpdateClause().children().iterator();

    }//from ww w.j a  va  2 s .com
    if (query.isDeleteStatement()) {
        fromIter = query.getDeleteStatement().getDeleteClause().children().iterator();

    }

    if (fromIter != null) {
        while (fromIter.hasNext()) {
            String textObj = fromIter.next().toActualText().trim();

            if (!StringUtils.isEmpty(textObj)) {
                query.setFrom(textObj);
                break;
            }

        }
    }
}

From source file:com.bringcommunications.etherpay.Payment_Processor.java

private void cancel_client_messages(Payment_Processor_Client client) {
    synchronized (monitor) {
        Integer count = client_map.get(client);
        int no_entries = (count == null) ? 0 : count.intValue();
        ListIterator<Payment_Message> sit = send_message_list.listIterator();
        while (sit.hasNext() && no_entries > 0) {
            if (sit.next().client.equals(client)) {
                --no_entries;//w  w w. ja v  a 2  s. co  m
                sit.remove();
            }
        }
        ListIterator<Payment_Message> bit = balance_message_list.listIterator();
        while (bit.hasNext() && no_entries > 0) {
            if (bit.next().client.equals(client)) {
                --no_entries;
                bit.remove();
            }
        }
        count = new Integer(no_entries);
        client_map.put(client, count);
    }
}

From source file:vteaexploration.plottools.panels.XYExplorationPanel.java

public void makeOverlayImage(ArrayList gates, int x, int y, int xAxis, int yAxis) {
    //convert gate to chart x,y path

    Gate gate;//from   ww  w  . j av  a 2s .c om
    ListIterator<Gate> gate_itr = gates.listIterator();

    //.get

    int total = 0;
    int gated = 0;
    int selected = 0;
    int gatedSelected = 0;

    int gatecount = gates.size();

    while (gate_itr.hasNext()) {
        gate = gate_itr.next();
        if (gate.getSelected()) {
            Path2D path = gate.createPath2DInChartSpace();

            ArrayList<MicroObject> result = new ArrayList<MicroObject>();

            ArrayList<MicroObject> volumes = (ArrayList) this.plotvalues.get(1);
            MicroObjectModel volume;

            double xValue = 0;
            double yValue = 0;

            ListIterator<MicroObject> it = volumes.listIterator();
            try {
                while (it.hasNext()) {
                    volume = it.next();
                    if (volume != null) {
                        xValue = ((Number) processPosition(xAxis, (MicroObject) volume)).doubleValue();
                        yValue = ((Number) processPosition(yAxis, (MicroObject) volume)).doubleValue();
                        if (path.contains(xValue, yValue)) {
                            result.add((MicroObject) volume);
                        }
                    }
                }
            } catch (NullPointerException e) {
            }
            ;

            Overlay overlay = new Overlay();

            int count = 0;
            BufferedImage placeholder = new BufferedImage(impoverlay.getWidth(), impoverlay.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);

            ImageStack gateOverlay = new ImageStack(impoverlay.getWidth(), impoverlay.getHeight());

            selected = getSelectedObjects();

            total = volumes.size();

            gated = getGatedObjects(impoverlay);

            gatedSelected = getGatedSelected(impoverlay);

            for (int i = 0; i <= impoverlay.getNSlices(); i++) {
                BufferedImage selections = new BufferedImage(impoverlay.getWidth(), impoverlay.getHeight(),
                        BufferedImage.TYPE_INT_ARGB);

                Graphics2D g2 = selections.createGraphics();

                ImageRoi ir = new ImageRoi(0, 0, placeholder);
                ListIterator<MicroObject> vitr = result.listIterator();

                while (vitr.hasNext()) {
                    try {
                        MicroObject vol = (MicroObject) vitr.next();

                        int[] x_pixels = vol.getXPixelsInRegion(i);
                        int[] y_pixels = vol.getYPixelsInRegion(i);

                        for (int c = 0; c < x_pixels.length; c++) {

                            g2.setColor(gate.getColor());
                            g2.drawRect(x_pixels[c], y_pixels[c], 1, 1);
                        }
                        ir = new ImageRoi(0, 0, selections);
                        count++;

                    } catch (NullPointerException e) {
                    }
                }

                ir.setPosition(i);
                ir.setOpacity(0.4);
                overlay.add(ir);

                gateOverlay.addSlice(ir.getProcessor());

                java.awt.Font f = new Font("Arial", Font.BOLD, 12);
                BigDecimal percentage = new BigDecimal(selected);
                BigDecimal totalBD = new BigDecimal(total);
                percentage = percentage.divide(totalBD, 4, BigDecimal.ROUND_UP);

                BigDecimal percentageGated = new BigDecimal(gated);
                BigDecimal totalGatedBD = new BigDecimal(total);
                percentageGated = percentageGated.divide(totalGatedBD, 4, BigDecimal.ROUND_UP);

                BigDecimal percentageGatedSelected = new BigDecimal(gatedSelected);
                BigDecimal totalGatedSelectedBD = new BigDecimal(total);
                percentageGatedSelected = percentageGatedSelected.divide(totalGatedSelectedBD, 4,
                        BigDecimal.ROUND_UP);

                // System.out.println("PROFILING: gate fraction: " + percentage.toString());
                if (impoverlay.getWidth() > 256) {

                    TextRoi textTotal = new TextRoi(5, 10,
                            selected + "/" + total + " gated (" + 100 * percentage.doubleValue() + "%)");

                    if (gated > 0) {
                        textTotal = new TextRoi(5, 10, selected + "/" + total + " total ("
                                + 100 * percentage.doubleValue() + "%)" + "; " + gated + "/" + total + " roi ("
                                + 100 * percentageGated.doubleValue() + "%)" + "; " + gatedSelected + "/"
                                + total + " overlap (" + 100 * percentageGatedSelected.doubleValue() + "%)", f);
                    }
                    //TextRoi textImageGated = new TextRoi(5, 18, selected + "/" + total + " gated objects (" + 100 * percentage.doubleValue() + "%)", f);
                    textTotal.setPosition(i);
                    //textImageGated.setPosition(i);
                    overlay.add(textTotal);
                } else {
                    f = new Font("Arial", Font.PLAIN, 10);
                    TextRoi line1 = new TextRoi(5, 5,
                            selected + "/" + total + " gated" + "(" + 100 * percentage.doubleValue() + "%)", f);
                    overlay.add(line1);
                    if (gated > 0) {
                        f = new Font("Arial", Font.PLAIN, 10);
                        TextRoi line2 = new TextRoi(5, 18,
                                gated + "/" + total + " roi (" + 100 * percentageGated.doubleValue() + "%)", f);
                        overlay.add(line2);
                        TextRoi line3 = new TextRoi(5, 31, gatedSelected + "/" + total + " overlap ("
                                + 100 * percentageGatedSelected.doubleValue() + "%)", f);
                        overlay.add(line3);
                    }
                    line1.setPosition(i);

                }
            }
            impoverlay.setOverlay(overlay);

            //ImagePlus gateMaskImage = new ImagePlus("gates", gateOverlay);

            //gateMaskImage.show();

            gate.setGateOverlayStack(gateOverlay);

        }

        impoverlay.draw();
        impoverlay.setTitle(this.getTitle());

        if (impoverlay.getDisplayMode() != IJ.COMPOSITE) {
            impoverlay.setDisplayMode(IJ.COMPOSITE);
        }

        if (impoverlay.getSlice() == 1) {
            impoverlay.setZ(Math.round(impoverlay.getNSlices() / 2));
        } else {
            impoverlay.setSlice(impoverlay.getSlice());
        }
        impoverlay.show();
    }
}

From source file:umontreal.iro.lecuyer.charts.HistogramSeriesCollection.java

public String toLatex(double XScale, double YScale, double XShift, double YShift, double xmin, double xmax,
        double ymin, double ymax) {

    // Calcule les bornes reelles du graphique, en prenant en compte la position des axes
    xmin = Math.min(XShift, xmin);
    xmax = Math.max(XShift, xmax);
    ymin = Math.min(YShift, ymin);
    ymax = Math.max(YShift, ymax);

    CustomHistogramDataset tempSeriesCollection = (CustomHistogramDataset) seriesCollection;
    Formatter formatter = new Formatter(Locale.US);
    double var;
    double margin = ((XYBarRenderer) renderer).getMargin();

    for (int i = tempSeriesCollection.getSeriesCount() - 1; i >= 0; i--) {
        List temp = tempSeriesCollection.getBins(i);
        ListIterator iter = temp.listIterator();

        Color color = (Color) renderer.getSeriesPaint(i);
        String colorString = detectXColorClassic(color);
        if (colorString == null) {
            colorString = "color" + i;
            formatter.format("\\definecolor{%s}{rgb}{%.2f, %.2f, %.2f}%n", colorString, color.getRed() / 255.0,
                    color.getGreen() / 255.0, color.getBlue() / 255.0);
        }//from w  w w . j a  va 2  s  . co m

        HistogramBin currentBin = null;
        while (iter.hasNext()) {
            double currentMargin;
            currentBin = (HistogramBin) iter.next();
            currentMargin = ((margin * (currentBin.getEndBoundary() - currentBin.getStartBoundary()))) * XScale;
            if ((currentBin.getStartBoundary() >= xmin && currentBin.getStartBoundary() <= xmax)
                    && (currentBin.getCount() >= ymin && currentBin.getCount() <= ymax)) {
                var = Math.min(currentBin.getEndBoundary(), xmax);
                if (filled[i]) {
                    formatter.format(
                            "\\filldraw [line width=%.2fpt, opacity=%.2f, color=%s] ([xshift=%.4f] %.4f, %.4f) rectangle ([xshift=-%.4f] %.4f, %.4f); %%%n",
                            lineWidth[i], (color.getAlpha() / 255.0), colorString, currentMargin,
                            (currentBin.getStartBoundary() - XShift) * XScale, 0.0, currentMargin,
                            (var - XShift) * XScale, (currentBin.getCount() - YShift) * YScale);
                } else {
                    formatter.format(
                            "\\draw [line width=%.2fpt, color=%s] ([xshift=%.4f] %.4f, %.4f) rectangle ([xshift=-%.4f] %.4f, %.4f); %%%n",
                            lineWidth[i], colorString, currentMargin,
                            (currentBin.getStartBoundary() - XShift) * XScale, 0.0, currentMargin,
                            (var - XShift) * XScale, (currentBin.getCount() - YShift) * YScale);
                }
            } else if ((currentBin.getStartBoundary() >= xmin && currentBin.getStartBoundary() <= xmax)
                    && (currentBin.getCount() >= ymin && currentBin.getCount() > ymax)) { // Cas ou notre rectangle ne peut pas etre affiche en entier (trop haut)
                var = Math.min(currentBin.getEndBoundary(), xmax);
                if (filled[i]) {
                    formatter.format(
                            "\\filldraw [line width=%.2fpt,  opacity=%.2f, color=%s] ([xshift=%.4f] %.4f, %.4f) rectangle ([xshift=-%.4f] %.4f, %.4f); %%%n",
                            lineWidth[i], (color.getAlpha() / 255.0), colorString, currentMargin,
                            (currentBin.getStartBoundary() - XShift) * XScale, 0.0, currentMargin,
                            (var - XShift) * XScale, (ymax - YShift) * YScale);
                    formatter.format(
                            "\\draw [line width=%.2fpt, color=%s, style=dotted] ([xshift=%.4f] %.4f, %.4f) rectangle ([yshift=3mm, xshift=-%.4f] %.4f, %.4f); %%%n",
                            lineWidth[i], colorString, currentMargin,
                            (currentBin.getStartBoundary() - XShift) * XScale, (ymax - YShift) * YScale,
                            currentMargin, (var - XShift) * XScale, (ymax - YShift) * YScale);
                } else {
                    formatter.format(
                            "\\draw [line width=%.2fpt, color=%s] ([xshift=%.4f] %.4f, %.4f) rectangle ([xshift=-%.4f] %.4f, %.4f); %%%n",
                            lineWidth[i], colorString, currentMargin,
                            (currentBin.getStartBoundary() - XShift) * XScale, 0.0, currentMargin,
                            (var - XShift) * XScale, (ymax - YShift) * YScale);

                    formatter.format(
                            "\\draw [line width=%.2fpt, color=%s, style=dotted] ([xshift=%.4f] %.4f, %.4f) rectangle ([yshift=3mm, xshift=-%.4f] %.4f, %.4f); %%%n",
                            lineWidth[i], colorString, currentMargin,
                            (currentBin.getStartBoundary() - XShift) * XScale, (ymax - YShift) * YScale,
                            currentMargin, (var - XShift) * XScale, (ymax - YShift) * YScale);
                }
            }
        }
    }
    return formatter.toString();
}

From source file:com.bwc.ora.models.Lrp.java

public List<XYSeries> getFWHMForLRPPeaks(XYSeries lrpPeaks, XYSeries lrpSeries) {
    LinkedList<XYSeries> seriesList = new LinkedList<>();
    List<XYDataItem> pointList = (List<XYDataItem>) lrpSeries.getItems();
    List<XYDataItem> peakList = (List<XYDataItem>) lrpPeaks.getItems();
    //iterate through the peaks, process FWHM for each peak
    for (XYDataItem peak : peakList) {
        //grab index of the closest point to the peak
        int peakIndex = -1;
        for (XYDataItem pnt : pointList) {
            peakIndex++;/*  www .  j  av  a2  s.c om*/
            if (Math.abs(pnt.getXValue() - peak.getXValue()) < 0.6D) {
                break;
            }
        }
        //calculate point with Y value of valley to the left of peak
        XYDataItem leftValleyPoint = null;
        ListIterator<XYDataItem> it = pointList.listIterator(peakIndex);
        double prevY = peak.getYValue();
        while (it.hasPrevious()) {
            XYDataItem leftPoint = it.previous();
            if (leftPoint.getYValue() <= prevY) {
                prevY = leftPoint.getYValue();
                leftValleyPoint = leftPoint;
            } else {
                break;
            }
        }
        //calculate point with Y value of valley to the right of peak
        XYDataItem rightValleyPoint = null;
        it = pointList.listIterator(peakIndex);
        prevY = peak.getYValue();
        while (it.hasNext()) {
            XYDataItem rightPoint = it.next();
            if (rightPoint.getYValue() <= prevY) {
                prevY = rightPoint.getYValue();
                rightValleyPoint = rightPoint;
            } else {
                break;
            }
        }
        //determine half max Y value
        double halfMaxYValue;
        if (rightValleyPoint.getYValue() == leftValleyPoint.getYValue()) {
            halfMaxYValue = peak.getYValue() - ((peak.getYValue() - leftValleyPoint.getYValue()) / 2D);
        } else if (rightValleyPoint.getYValue() > leftValleyPoint.getYValue()) {
            halfMaxYValue = peak.getYValue() - ((peak.getYValue() - rightValleyPoint.getYValue()) / 2D);
        } else {
            halfMaxYValue = peak.getYValue() - ((peak.getYValue() - leftValleyPoint.getYValue()) / 2D);
        }
        //determine the X value on both sides of the peak that corresponds to the half max Y value
        double leftX = pointList.get(0).getXValue(), rightX = pointList.get(pointList.size() - 1).getXValue();
        XYDataItem prevPoint = pointList.get(peakIndex);
        it = pointList.listIterator(peakIndex);
        while (it.hasPrevious()) {
            XYDataItem leftPoint = it.previous();
            if (leftPoint.getYValue() == halfMaxYValue) {
                leftX = leftPoint.getXValue();
                break;
            } else {
                if (leftPoint.getYValue() < halfMaxYValue) {
                    //                        System.out.println("Left X for peak (" + peak.getXValue() + "," + peak.getYValue() + "): ");
                    leftX = calculateXFromYForLineWithTwoPoints(leftPoint, prevPoint, halfMaxYValue);
                    //                        System.out.println("    Left X: (" + leftX + "," + halfMaxYValue + "): ");
                    break;
                } else {
                    prevPoint = leftPoint;
                }
            }
        }
        prevPoint = pointList.get(peakIndex);
        it = pointList.listIterator(peakIndex);
        while (it.hasNext()) {
            XYDataItem rightPoint = it.next();
            if (rightPoint.getYValue() == halfMaxYValue) {
                rightX = rightPoint.getXValue();
                break;
            } else {
                if (rightPoint.getYValue() < halfMaxYValue) {
                    //                        System.out.println("Right X for peak (" + peak.getXValue() + "," + peak.getYValue() + "): ");
                    rightX = calculateXFromYForLineWithTwoPoints(rightPoint, prevPoint, halfMaxYValue);
                    //                        System.out.println("    Right X: (" + leftX + "," + halfMaxYValue + "): ");
                    break;
                } else {
                    prevPoint = rightPoint;
                }
            }
        }
        //store the two points for the half max full width line for this peak
        XYSeries peakSeries = new XYSeries("(" + peak.getXValue() + "," + peak.getYValue() + ")FWHM");
        peakSeries.add(leftX, halfMaxYValue);
        peakSeries.add(rightX, halfMaxYValue);
        seriesList.add(peakSeries);
    }
    return seriesList;
}

From source file:codeswarm.code_swarm.java

/**
 * TODO This could be made to look a lot better.
 *//*from   w  w  w.  j  a  v  a 2s .  c o m*/
public void drawPopular() {
    CopyOnWriteArrayList<FileNode> al = new CopyOnWriteArrayList<FileNode>();
    noStroke();
    textFont(font);
    textAlign(RIGHT, TOP);
    fill(255, 200);
    text("Popular Nodes (touches):", width - 120, 0);
    for (int i = 0; i < nodes.size(); i++) {
        FileNode fn = nodes.get(i);
        if (fn.qualifies()) {
            // Insertion Sort
            if (al.size() > 0) {
                int j = 0;
                for (; j < al.size(); j++) {
                    if (fn.compareTo(al.get(j)) <= 0) {
                        continue;
                    } else {
                        break;
                    }
                }
                al.add(j, fn);
            } else {
                al.add(fn);
            }
        }
    }

    int i = 1;
    ListIterator<FileNode> it = al.listIterator();
    while (it.hasNext()) {
        FileNode n = it.next();
        // Limit to the top 10.
        if (i <= 10) {
            text(n.getName() + "  (" + n.getTouches() + ")", width - 100, 10 * i++);
        } else if (i > 10) {
            break;
        }
    }
}