Example usage for java.lang Float NaN

List of usage examples for java.lang Float NaN

Introduction

In this page you can find the example usage for java.lang Float NaN.

Prototype

float NaN

To view the source code for java.lang Float NaN.

Click Source Link

Document

A constant holding a Not-a-Number (NaN) value of type float .

Usage

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * @param points input array for longitude and latitude
 *               double[number_of_points][2] and sorted latitude then longitude
 * @return array of .gri file values corresponding to the
 * points provided/*ww w  . j av a2 s  .  c om*/
 */
public float[] getValues3(double[][] points, int bufferSize) {
    //confirm inputs since they come from somewhere else
    if (points == null || points.length == 0) {
        return null;
    }

    if (subgrids != null) {
        return getValuesSubgrids(points, bufferSize);
    }

    //use preloaded grid data if available
    Grid g = Grid.getLoadedGrid(filename);
    if (g != null && g.grid_data != null) {
        return g.getValues2(points);
    }

    int length = points.length;
    int size, i;
    byte[] b;

    RandomAccessFile afile = null;

    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        //do not cache subgrids (using getValues2)
        if (!subgrid && afile.length() < 80 * 1024 * 1024) {
            try {
                afile.close();
                afile = null;
            } catch (Exception e) {
            }
            return getValues2(points);
        }

        byte[] buffer = new byte[bufferSize]; //must be multiple of 64
        Long bufferOffset = afile.length();

        float[] ret = new float[points.length];

        //get cell numbers
        long[][] cells = new long[points.length][2];
        for (int j = 0; j < points.length; j++) {
            if (Double.isNaN(points[j][0]) || Double.isNaN(points[j][1])) {
                cells[j][0] = -1;
                cells[j][1] = j;
            } else {
                cells[j][0] = getcellnumber(points[j][0], points[j][1]);
                cells[j][1] = j;
            }
        }
        java.util.Arrays.sort(cells, new Comparator<long[]>() {

            @Override
            public int compare(long[] o1, long[] o2) {
                if (o1[0] == o2[0]) {
                    return o1[1] > o2[1] ? 1 : -1;
                } else {
                    return o1[0] > o2[0] ? 1 : -1;
                }
            }
        });

        if (datatype.equalsIgnoreCase("BYTE")) {
            size = 1;
            for (i = 0; i < length; i++) {
                if (i > 0 && cells[i - 1][0] == cells[i][0]) {
                    ret[(int) cells[i][1]] = ret[(int) cells[i - 1][1]];
                    continue;
                }
                if (cells[i][0] >= 0) {
                    ret[(int) cells[i][1]] = getByte(afile, buffer, bufferOffset, cells[i][0] * size);
                } else {
                    ret[(int) cells[i][1]] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("UBYTE")) {
            size = 1;
            for (i = 0; i < length; i++) {
                if (i > 0 && cells[i - 1][0] == cells[i][0]) {
                    ret[(int) cells[i][1]] = ret[(int) cells[i - 1][1]];
                    continue;
                }
                if (cells[i][0] >= 0) {
                    ret[(int) cells[i][1]] = getByte(afile, buffer, bufferOffset, cells[i][0] * size);
                    if (ret[(int) cells[i][1]] < 0) {
                        ret[(int) cells[i][1]] += 256;
                    }
                } else {
                    ret[(int) cells[i][1]] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            size = 2;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                if (i > 0 && cells[i - 1][0] == cells[i][0]) {
                    ret[(int) cells[i][1]] = ret[(int) cells[i - 1][1]];
                    continue;
                }
                if (cells[i][0] >= 0) {
                    bufferOffset = getBytes(afile, buffer, bufferOffset, cells[i][0] * (long) size, b);
                    if (byteorderLSB) {
                        ret[(int) cells[i][1]] = (short) (((0xFF & b[1]) << 8) | (b[0] & 0xFF));
                    } else {
                        ret[(int) cells[i][1]] = (short) (((0xFF & b[0]) << 8) | (b[1] & 0xFF));
                    }
                } else {
                    ret[(int) cells[i][1]] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            size = 4;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                if (i > 0 && cells[i - 1][0] == cells[i][0]) {
                    ret[(int) cells[i][1]] = ret[(int) cells[i - 1][1]];
                    continue;
                }
                if (cells[i][0] >= 0) {
                    bufferOffset = getBytes(afile, buffer, bufferOffset, cells[i][0] * (long) size, b);
                    if (byteorderLSB) {
                        ret[(int) cells[i][1]] = ((0xFF & b[3]) << 24)
                                | ((0xFF & b[2]) << 16) + ((0xFF & b[1]) << 8) + (b[0] & 0xFF);
                    } else {
                        ret[(int) cells[i][1]] = ((0xFF & b[0]) << 24)
                                | ((0xFF & b[1]) << 16) + ((0xFF & b[2]) << 8) + ((0xFF & b[3]) & 0xFF);
                    }
                } else {
                    ret[(int) cells[i][1]] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            size = 8;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                if (i > 0 && cells[i - 1][0] == cells[i][0]) {
                    ret[(int) cells[i][1]] = ret[(int) cells[i - 1][1]];
                    continue;
                }
                if (cells[i][0] >= 0) {
                    bufferOffset = getBytes(afile, buffer, bufferOffset, cells[i][0] * (long) size, b);
                    if (byteorderLSB) {
                        ret[(int) cells[i][1]] = ((long) (0xFF & b[7]) << 56) + ((long) (0xFF & b[6]) << 48)
                                + ((long) (0xFF & b[5]) << 40) + ((long) (0xFF & b[4]) << 32)
                                + ((long) (0xFF & b[3]) << 24) + ((long) (0xFF & b[2]) << 16)
                                + ((long) (0xFF & b[1]) << 8) + (0xFF & b[0]);
                    } else {
                        ret[(int) cells[i][1]] = ((long) (0xFF & b[0]) << 56) + ((long) (0xFF & b[1]) << 48)
                                + ((long) (0xFF & b[2]) << 40) + ((long) (0xFF & b[3]) << 32)
                                + ((long) (0xFF & b[4]) << 24) + ((long) (0xFF & b[5]) << 16)
                                + ((long) (0xFF & b[6]) << 8) + (0xFF & b[7]);
                    }
                } else {
                    ret[(int) cells[i][1]] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            size = 4;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                if (i > 0 && cells[i - 1][0] == cells[i][0]) {
                    ret[(int) cells[i][1]] = ret[(int) cells[i - 1][1]];
                    continue;
                }
                if (cells[i][0] >= 0) {
                    bufferOffset = getBytes(afile, buffer, bufferOffset, cells[i][0] * (long) size, b);
                    ByteBuffer bb = ByteBuffer.wrap(b);
                    if (byteorderLSB) {
                        bb.order(ByteOrder.LITTLE_ENDIAN);
                    }
                    ret[(int) cells[i][1]] = bb.getFloat();
                } else {
                    ret[(int) cells[i][1]] = Float.NaN;
                }

            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            size = 8;
            b = new byte[8];
            for (i = 0; i < length; i++) {
                if (i > 0 && cells[i - 1][0] == cells[i][0]) {
                    ret[(int) cells[i][1]] = ret[(int) cells[i - 1][1]];
                    continue;
                }
                if (cells[i][0] >= 0) {
                    getBytes(afile, buffer, bufferOffset, cells[i][0] * (long) size, b);
                    ByteBuffer bb = ByteBuffer.wrap(b);
                    if (byteorderLSB) {
                        bb.order(ByteOrder.LITTLE_ENDIAN);
                    }
                    ret[(int) cells[i][1]] = (float) bb.getDouble();

                } else {
                    ret[(int) cells[i][1]] = Float.NaN;
                }
            }
        } else {
            logger.error("datatype not supported in Grid.getValues: " + datatype);
            // / should not happen; catch anyway...
            for (i = 0; i < length; i++) {
                ret[i] = Float.NaN;
            }
        }
        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
        return ret;
    } catch (Exception e) {
        logger.error("error getting grid file values", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return null;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#subtract(java.lang.Object, java.lang.Number, java.lang.Class)}.
 */// w  w w. j  av  a2 s .c o  m
@SuppressWarnings("unchecked")
@Test
public void testSubtractObjectNumberClassOfT() {
    assertEquals("null", null, subtract(null, null, null));
    assertEquals("null", null, subtract("123.456", null, null));
    assertEquals("null", null, subtract("123.456", 1, null));
    assertEquals("null", null, subtract("", 10, null));
    assertEquals("null", null, subtract(null, 10, null));
    assertEquals("null", null, subtract(123.456, 10, null));
    assertEquals("123.456 - .456", (Object) 123, subtract(123.456, .456, int.class));
    assertEquals("123.456 - .456: Float", (Object) 123f, subtract(123.456, .456, Float.class));

    assertEquals("123.912 - .456: Float", (Object) 123.456d, subtract(123.912, .456, Double.class));
    assertEquals("123.912 - .456: Float", (Object) 123, subtract(123.912, .456, Integer.class));

    assertEquals("123.456 - .456: Float", (Object) Float.class,
            subtract(123.912d, .456, Float.class).getClass());
    assertEquals("123.456 - .456: Float", (Object) Float.class,
            subtract(123.456, .456d, Float.class).getClass());
    for (Class<?> type : NUMBERS) {
        try {
            Object expected = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            assertEquals("null: default: " + type.getSimpleName(), valueOf(null, typeOfN),
                    subtract(null, null, typeOfN));
            assertEquals("123.456: " + type.getSimpleName(), valueOf(123.912 - .456, typeOfN),
                    subtract("123.912", .456, typeOfN));
            assertEquals("123.456 - NaN: " + type.getSimpleName(), valueOf(123.456, typeOfN),
                    subtract(123.456, Float.NaN, typeOfN));
            assertEquals("NaN - 123.456: " + type.getSimpleName(), valueOf(123.456, typeOfN),
                    subtract("NaN", 123.456, typeOfN));
            assertEquals("invalid - 123.456: " + type.getSimpleName(), valueOf(123.456, typeOfN),
                    subtract("not a number", 123.456, typeOfN));
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = valueOf(-Double.MAX_VALUE, typeOfN);
            } else if (ClassUtils.isPrimitiveOrWrapper(type)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = new BigDecimal("123.456").subtract(INFINITY_DOUBLE);
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("123.456 - Infinity: " + type.getSimpleName(), expected,
                    subtract(123.456, Double.POSITIVE_INFINITY, typeOfN));

            if (ObjectUtils.isAny(wrapper, Float.class)) {
                expected = valueOf("Infinity", typeOfN);
            } else if (ClassUtils.isPrimitiveOrWrapper(type)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = INFINITY_DOUBLE.subtract(new BigDecimal("123.456"));
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("Infinity - 123.456: " + type.getSimpleName(), expected,
                    subtract("Infinity", 123.456, typeOfN));
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:gov.noaa.pfel.coastwatch.Projects.java

/**
 * KFM - This is the second group of files from Kushner (see f:/programs/kfm, 
 * processed starting 2007-03-27). This is biological data.
 * <ul>/*  www. j  a v a  2s . c  om*/
 * <li>I converted the .mdb file to separate tab-separated value files,
 *    one per table, in MS Access (see instructions below --
 *    or with &lt;65,000 rows just use clipboard to move data) with extension .tab.
 *   <p>In the future: to export Access tables to a format we like (tab separated ASCII files):
 *   <ul>
 *   <li>In Access, select the specified table
 *     <ul>
 *     <li>Choose "File : Export"
 *     <li>Pick the table
 *     <li>Choose "Save as type: Text Files"
 *     <li>Change the file's extension to .tab
 *     <li>Don't check "Save formatted"
 *     <li>Click "Export All"
 *     </ul>
 *   <li>Check "Delimited"
 *   <li>Click "Next"
 *   <li>Check "Tab"
 *   <li>Check "Include Field Names on First Row"
 *   <li>Choose "Text Qualifier: none"
 *   <li>Click "Next"
 *   <li>Click "Finish"
 *   </ul>
 * <li>In CoStat, I removed extraneous columns from .tab files and save as .tsv so 
 *   <br> data .tsv files are: col 1)siteName, 2) year, 3+) data columns
 *   <br> site .tsv file is: col 1)island, 2) siteName, 
 *       3) lat(deg. N), 4) lon(deg. E), 5) depth(m)
 *   <br>(lat and lon are just degree and minute info -- as before, at Kushner's
 *     request, no seconds data.
 * <li> In this method, load site table, and process a data file
 *    (convert siteName to Lon, Lat, Depth) and save as .nc file with metadata.
 * </ul>
 *
 * <p>In 2007-03-29 email, David Kushner said in response to my questions:
 * <pre>
        
I'm working on converting the latest KFM data files to another format
and adding metadata. It's going pretty well. I have a few questions...
        
***
I presume that I should obscure the exact locations of the stations by
just releasing the degrees and minutes (not seconds) for the lat and lon
values, as before.  If that has changed, please let me know.
  YES, THAT WORKS WELL FOR NOW AND APPRECIATE YOUR FORESIGHT ON THIS
***
Where does the Species number come from?  Is this your internal
numbering system -- a number that you have assigned to each species? Or,
are they standardized numbers from some standard numbering system?
  THEY ARE OUR INTERNAL NUMBER SYSTEM.  THEY DON'T CHANGE BUT THE
SPECIES NAMES DO WAY TOO OFTEN.  I ONLY INCLUDED THESE THINKING THEY MAY BE
USEFUL FOR YOU TO ORGANIZE THE DATA, BUT IF NOT NO WORRIES...  THEY MAY
COME IN HANDY TO HAVE LINKED IF WE UPDATE THE DATA EVERY YEAR AND THE NAMES
CHANGE.  PERHAPS I SHOULD SEND YOU A TABLE THAT HAS THE SPECIES CODE,
SPECIES NAME, AND COMMON NAME AND YOU CAN LINK THEM THIS WAY WHICH IS WHAT
WE DO.  WHATEVER YOU THINK IS BEST.
        
***
Is the reference information the same as for the temperature data?  If
not, please let me know how you want it to appear. The information
currently is:  YES, THE SAME.  WE ARE WORKING ON THE NPS WEB SITE NOW AND
THOSE LINKS MAY CHANGE, BUT I WILL NOTIFY YOU IF THEY DO.
        
        
Channel Islands National Parks Inventory and Monitoring information:
http://www.nature.nps.gov/im/units/chis/
(changing in early 2007 to http://nature.nps.gov/im/units/medn ).
Kelp Forest Monitoring Protocols:
http://www.nature.nps.gov/im/units/chis/Reports_PDF/Marine/KFM-HandbookVol1.pdf
        
.
        
***
Is the "courtesy" information still:
"Channel Islands National Park, National Park Service"?
        
[I take his no-comment as tacit acceptance.]
***
Should the license/disclaimer still be:
"National Park Service Disclaimer: " +
"The National Park Service shall not be held liable for " +
"improper or incorrect use of the data described and/or contained " +
"herein. These data and related graphics are not legal documents and " +
"are not intended to be used as such. The information contained in " +
"these data is dynamic and may change over time. The data are not " +
"better than the original sources from which they were derived. It is "  +
"the responsibility of the data user to use the data appropriately and " +
"consistent within the limitation of geospatial data in general and " +
"these data in particular. The related graphics are intended to aid " +
"the data user in acquiring relevant data; it is not appropriate to " +
"use the related graphics as data. The National Park Service gives no " +
"warranty, expressed or implied, as to the accuracy, reliability, or " +
"completeness of these data. It is strongly recommended that these " +
"data are directly acquired from an NPS server and not indirectly " +
"through other sources which may have changed the data in some way. " +
"Although these data have been processed successfully on computer " +
"systems at the National Park Service, no warranty expressed or " +
"implied is made regarding the utility of the data on other systems " +
"for general or scientific purposes, nor shall the act of distribution "  +
"constitute any such warranty. This disclaimer applies both to " +
"individual use of the data and aggregate use with other data.";
        
[I take his no-comment as tacit acceptance.]
</pre>
 * <p>I added the following info to the KFM_Site_Info.tsv file based
 *   on info in emails from Kushner:
 *   <br> San Miguel, Miracle Mile, 34.0166666666667, -120.4, 10
 *   <br>That station didn't have a temperature logger, so there wasn't
 *   an entry in the station file, but there is
 *   biological data for the station.
 * @throws Exception if trouble
 */
public static void kfmBiological() throws Exception {
    String2.log("\n*** Projects.kfmBiological");

    //'_' in tsvNames will be converted to ' ' for tempID below
    //Station .nc files will be stored in subdirectories named tsvName.
    String tsvDir = "c:/programs/kfm/";
    //order not important
    String tsvNames[] = { "KFM_5m_Quadrat", "KFM_Quadrat", "KFM_Random_Point", "KFM_Transect" };

    //read KFM_Site_Info.tsv: col 0)island e.g., "Anacapa", 1=siteID (e.g., Admiral's Reef)", 
    //  2) lat(deg. N), 3) lon(deg. E), 4) depth(m)
    Table site = new Table();
    site.readASCII(tsvDir + "KFM_Site_Info.tsv");
    StringArray sitePa = (StringArray) site.getColumn(1);
    Test.ensureEqual(site.getStringData(0, 0), "San Miguel", "");
    Test.ensureEqual(sitePa.get(0), "Wyckoff Ledge", "");
    Test.ensureEqual(site.getFloatData(2, 0), 34.0166666666667f, ""); //lat, !!! already rounded to nearest minute at Kushner's request
    Test.ensureEqual(site.getFloatData(3, 0), -120.383333333333f, ""); //lon, !!! already rounded to nearest minute at Kushner's request
    Test.ensureEqual(site.getFloatData(4, 0), 13, ""); //depth

    //go through the source tab-separated-value files
    StringArray missingSites = new StringArray();
    for (int tsvI = 0; tsvI < tsvNames.length; tsvI++) {
        String tsvName = tsvNames[tsvI];
        String2.log("processing " + tsvDir + tsvName + ".tsv");

        //empty the results directory
        File2.deleteAllFiles(tsvDir + tsvName + "/");

        //read datafile into a table
        //col 0)siteName, e.g., "Admiral's Reef", 1) year 2+) data columns
        Table data = new Table();
        data.readASCII(tsvDir + tsvName + ".tsv");
        int dataNRows = data.nRows();

        //create x,y,z,t,id columns  (numeric coordinate columns are all doubles)
        DoubleArray xPa = new DoubleArray(dataNRows, false);
        DoubleArray yPa = new DoubleArray(dataNRows, false);
        DoubleArray zPa = new DoubleArray(dataNRows, false);
        DoubleArray tPa = new DoubleArray(dataNRows, false);
        StringArray idPa = new StringArray(dataNRows, false);
        for (int row = 0; row < dataNRows; row++) {
            String tSiteName = data.getStringData(0, row);
            int siteRow = sitePa.indexOf(tSiteName);
            if (siteRow == -1) {
                int tpo = missingSites.indexOf(tSiteName);
                if (tpo == -1)
                    missingSites.add(tSiteName);
                siteRow = 0; //clumsy, but lets me collect all the missing sites
            }

            xPa.add(site.getNiceDoubleData(3, siteRow));
            yPa.add(site.getNiceDoubleData(2, siteRow));
            zPa.add(site.getNiceDoubleData(4, siteRow));
            //they are just year #'s. no time zone issues.
            //Times are vague (may to oct), so assign to July 1 (middle of year).
            String tYear = data.getStringData(1, row);
            Test.ensureEqual(tYear.length(), 4, "Unexpected year=" + tYear + " on row=" + row);
            tPa.add(Calendar2.isoStringToEpochSeconds(tYear + "-07-01"));
            idPa.add(site.getStringData(0, siteRow) + " (" + tSiteName + ")");
        }

        //put x,y,z,t,id columns in place
        data.removeColumn(0);
        data.addColumn(0, "LON", xPa, new Attributes());
        data.addColumn(1, "LAT", yPa, new Attributes());
        data.addColumn(2, "DEPTH", zPa, new Attributes());
        data.addColumn(3, "TIME", tPa, new Attributes());
        data.addColumn(4, "ID", idPa, new Attributes());
        data.columnAttributes(4).set("long_name", "Station Identifier");
        //data.columnAttributes(4).set("units", DataHelper.UNITLESS);

        //remove the year column
        Test.ensureEqual(data.getColumnName(5), "Year", "Unexpected col 5 name.");
        data.removeColumn(5);

        //add metadata for data columns
        //standardNames from http://cfconventions.org/Data/cf-standard-names/27/build/cf-standard-name-table.html
        //none seem relevant here
        for (int col = 5; col < data.nColumns(); col++) {
            String pm2 = " per square meter"; //must be all lowercase
            String colName = data.getColumnName(col);
            if (colName.toLowerCase().endsWith(pm2)) {
                colName = colName.substring(0, colName.length() - pm2.length());
                data.setColumnName(col, colName);
                data.columnAttributes(col).set("long_name", colName);
                data.columnAttributes(col).set("units", "m-2");
            } else if (colName.equals("Species")) {
                data.columnAttributes(col).set("long_name", "Species");
                //data.columnAttributes(col).set("units", DataHelper.UNITLESS);
            } else if (colName.equals("SpeciesName")) {
                data.columnAttributes(col).set("long_name", "Species Name");
                //data.columnAttributes(col).set("units", DataHelper.UNITLESS);
            } else if (colName.equals("CommonName")) {
                data.columnAttributes(col).set("long_name", "Common Name");
                //data.columnAttributes(col).set("units", DataHelper.UNITLESS);
            } else if (colName.equals("Percent Cover")) {
                data.columnAttributes(col).set("long_name", colName);
                //data.columnAttributes(col).set("units", DataHelper.UNITLESS);
            } else {
                Test.error("Unexpected column name=" + colName);
            }
            //data.columnAttributes(col).set("long_name", "Sea Temperature");
            //data.columnAttributes(col).set("standard_name", "sea_water_temperature");
        }

        //summaries are verbatim (except for the first few words) 
        //from c:\content\kushner\NOAA Web page KFM protocol descriptions.doc
        //from Kushner's 2007-04-11 email.
        String summary = null;
        if (tsvName.equals("KFM_5m_Quadrat"))
            summary = "This dataset from the Channel Islands National Park's Kelp Forest Monitoring Program has measurements of the abundance of selected rare, clumped, sedentary indicator species. "
                    + "The summary data presented here represents the mean density per square meter. "
                    + "Sampling is conducted annually between the months of May-October, "
                    + "so the Time data in this file is July 1 of each year (a nominal value). "
                    + "The original measurements were taken at various depths, "
                    + "so the Depth data in this file is the depth of the station's temperature logger, which is a typical depth.";
        else if (tsvName.equals("KFM_Quadrat"))
            summary = "This dataset from the Channel Islands National Park's Kelp Forest Monitoring Program has measurements of the abundance (density) of relatively abundant selected sedentary indicator species. "
                    + "The summary data presented here represents the mean density per square meter. "
                    + "Sampling is conducted annually between the months of May-October, "
                    + "so the Time data in this file is July 1 of each year (a nominal value). "
                    + "The actual measurements were taken at various depths, "
                    + "so the Depth data in this file is the depth of the station's temperature logger, which is a typical depth.";
        else if (tsvName.equals("KFM_Random_Point"))
            summary = "This dataset from the Channel Islands National Park's Kelp Forest Monitoring Program has estimates of substrate composition and percent cover of selected algal and invertebrate taxa. "
                    + "The summary data presented here represents the mean percent cover of the indicator species at the site. "
                    + "Sampling is conducted annually between the months of May-October, "
                    + "so the Time data in this file is July 1 of each year (a nominal value). "
                    + "The actual measurements were taken at various depths, "
                    + "so the Depth data in this file is the depth of the station's temperature logger, which is a typical depth.";
        else if (tsvName.equals("KFM_Transect"))
            summary = "This dataset from the Channel Islands National Park's Kelp Forest Monitoring Program has measurements of the abundance and distribution of rare and clumped organisms not adequately sampled by quadrats. "
                    + "The summary data presented here represents the mean density per square meter. "
                    + "Sampling is conducted annually between the months of May-October, "
                    + "so the Time data in this file is July 1 of each year (a nominal value). "
                    + "The actual measurements were taken at various depths, "
                    + "so the Depth data in this file is the depth of the station's temperature logger, which is a typical depth.";
        else
            Test.error("Unexpected tsvName=" + tsvName);

        //sort by id, x,y,z,t
        data.sort(new int[] { 4, 0, 1, 2, 3 }, new boolean[] { true, true, true, true, true });
        int sppCol = 6;
        String2.log("sppCol name = " + data.getColumnName(sppCol));
        int commonCol = 7;
        String2.log("commonCol name = " + data.getColumnName(commonCol));
        int dataCol = 8;
        String2.log("dataCol name = " + data.getColumnName(dataCol));

        //find unique spp
        IntArray sppIndices = new IntArray();
        StringArray uniqueSpp = (StringArray) data.getColumn(sppCol).makeIndices(sppIndices);
        int nUniqueSpp = uniqueSpp.size();
        for (int sp = 0; sp < nUniqueSpp; sp++) {
            String newName = convertSpeciesName(uniqueSpp.get(sp));
            newName = String2.replaceAll(newName + " " + data.getColumnName(dataCol), ' ', '_');
            uniqueSpp.set(sp, newName);
        }
        String2.log("uniqueSpp = " + uniqueSpp);

        //find unique years
        IntArray yearIndices = new IntArray();
        PrimitiveArray uniqueYear = data.getColumn(3).makeIndices(yearIndices);
        int nUniqueYear = uniqueYear.size();
        String2.log("uniqueYear = " + uniqueYear);

        //make a separate file for each station
        int startRow = 0;
        for (int row = 1; row <= dataNRows; row++) { //yes 1..=
            //id changed?
            if (row == dataNRows || //test this first
                    !data.getStringData(4, startRow).equals(data.getStringData(4, row))) {

                //make stationTable x,y,z(constant), t, col for each sp
                Table stationTable = new Table();
                data.globalAttributes().copyTo(stationTable.globalAttributes());
                for (int col = 0; col < 5; col++) {
                    stationTable.addColumn(col, data.getColumnName(col),
                            PrimitiveArray.factory(data.getColumn(col).elementClass(), dataCol, false),
                            (Attributes) data.columnAttributes(col).clone());
                }
                for (int col = 0; col < nUniqueSpp; col++) {
                    stationTable.addColumn(5 + col, uniqueSpp.get(col), new FloatArray(),
                            (Attributes) data.columnAttributes(dataCol).clone());
                    stationTable.columnAttributes(5 + col).set("long_name",
                            String2.replaceAll(uniqueSpp.get(col), '_', ' '));
                    int rowWithThisSpp = sppIndices.indexOf("" + col);
                    stationTable.columnAttributes(5 + col).set("comment",
                            "Common name: " + data.getStringData(commonCol, rowWithThisSpp));
                }

                //fill the stationTable with axis info and blanks
                for (int tRow = 0; tRow < nUniqueYear; tRow++) {
                    //x,y,z,t,id
                    stationTable.getColumn(0).addDouble(data.getDoubleData(0, startRow));
                    stationTable.getColumn(1).addDouble(data.getDoubleData(1, startRow));
                    stationTable.getColumn(2).addDouble(data.getDoubleData(2, startRow));
                    stationTable.getColumn(3).addDouble(uniqueYear.getDouble(tRow));
                    stationTable.getColumn(4).addString(data.getStringData(4, startRow));
                    //spp
                    for (int col = 0; col < nUniqueSpp; col++)
                        stationTable.getColumn(5 + col).addFloat(Float.NaN);
                }

                //fill the stationTable with data
                for (int tRow = startRow; tRow < row; tRow++) {
                    float d = data.getFloatData(dataCol, tRow);
                    if (d < -9000)
                        Test.error("d=" + d + " is < -9000.");
                    stationTable.setFloatData(5 + sppIndices.get(tRow), yearIndices.get(tRow), d);
                }

                //setAttributes
                String id = data.getStringData(4, startRow); //e.g., "San Miguel (Wyckoff Ledge)"
                int pPo = id.indexOf('(');
                Test.ensureNotEqual(pPo, -1, "'(' in id=" + id);
                String island = id.substring(0, pPo - 1);
                String station = id.substring(pPo + 1, id.length() - 1);
                stationTable.setAttributes(0, 1, 2, 3, //x,y,z,t
                        String2.replaceAll(tsvName, '_', ' ') + " (Channel Islands)", //bold title
                        //don't make specific to this station; when aggregated, just one boldTitle will be used
                        //", " + island + ", " + station + ")", 
                        "Station", //cdmDataType
                        DataHelper.ERD_CREATOR_EMAIL, DataHelper.ERD_CREATOR_NAME, DataHelper.ERD_CREATOR_URL,
                        DataHelper.ERD_PROJECT, tsvName, //id    //don't make specific to this station; when aggregated, just one id will be used
                        "GCMD Science Keywords", //keywordsVocabulary,
                        //see http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html
                        //there are plands and invertebrates, so habitat seems closest keyword
                        "Oceans > Marine Biology > Marine Habitat", //keywords

                        //references   from 2006-12-19 email from Kushner
                        "Channel Islands National Parks Inventory and Monitoring information: "
                                + "http://nature.nps.gov/im/units/medn . "
                                + "Kelp Forest Monitoring Protocols: "
                                + "http://www.nature.nps.gov/im/units/chis/Reports_PDF/Marine/KFM-HandbookVol1.pdf .",

                        //summary  from 2006-12-19 email from Kushner
                        summary,
                        //my old summary
                        //"Temperatures were recorded by David Kushner (David_Kushner@nps.gov) " + 
                        //    "using Onset Computer Corp. temperature loggers, accurate to +/- 0.2 C. The raw time values " +
                        //    "(Pacific Daylight Savings Time) were converted to Zulu time by adding 7 hours and then stored in this file. " +
                        //    "LAT and LON values were stored without seconds values to obscure the station's exact location.",

                        //courtesy, see 2006-12-12 email, but order reversed to current in 2006-12-19 email from Kushner
                        "Channel Islands National Park, National Park Service", null); //timeLongName     use default long name

                //add the National Park Service disclaimer from 2006-12-19 email
                String license = stationTable.globalAttributes().getString("license")
                        + "  National Park Service Disclaimer: "
                        + "The National Park Service shall not be held liable for "
                        + "improper or incorrect use of the data described and/or contained "
                        + "herein. These data and related graphics are not legal documents and "
                        + "are not intended to be used as such. The information contained in "
                        + "these data is dynamic and may change over time. The data are not "
                        + "better than the original sources from which they were derived. It is "
                        + "the responsibility of the data user to use the data appropriately and "
                        + "consistent within the limitation of geospatial data in general and "
                        + "these data in particular. The related graphics are intended to aid "
                        + "the data user in acquiring relevant data; it is not appropriate to "
                        + "use the related graphics as data. The National Park Service gives no "
                        + "warranty, expressed or implied, as to the accuracy, reliability, or "
                        + "completeness of these data. It is strongly recommended that these "
                        + "data are directly acquired from an NPS server and not indirectly "
                        + "through other sources which may have changed the data in some way. "
                        + "Although these data have been processed successfully on computer "
                        + "systems at the National Park Service, no warranty expressed or "
                        + "implied is made regarding the utility of the data on other systems "
                        + "for general or scientific purposes, nor shall the act of distribution "
                        + "constitute any such warranty. This disclaimer applies both to "
                        + "individual use of the data and aggregate use with other data.";
                stationTable.globalAttributes().set("license", license);

                //fix up the attributes
                stationTable.globalAttributes().set("acknowledgement",
                        stationTable.globalAttributes().getString("acknowledgement") + ", "
                                + "Channel Islands National Park, National Park Service");

                //review the table
                if (tsvI == 0 && (startRow == 0 || row == dataNRows)) {
                    String2.log(stationTable.toString(100));
                    String2.pressEnterToContinue("Check if the file (above) is ok, then...");
                }
                String2.log("  startRow=" + startRow + " end=" + (row - 1) + " island=" + island + " station="
                        + station);

                //save the data table    
                String tFileName = tsvDir + tsvName + "/" + tsvName + "_" + String2.replaceAll(island, " ", "")
                        + "_" + String2.replaceAll(station, " ", "") + ".nc";
                tFileName = String2.replaceAll(tFileName, ' ', '_');
                tFileName = String2.replaceAll(tFileName, "'", "");
                stationTable.saveAs4DNcWithStringVariable(tFileName, 0, 1, 2, 3, 4);

                startRow = row;
            }
        }
    }
    if (missingSites.size() > 0) {
        String2.log("\n*** Projects.kfmBiological FAILED. Missing sites=" + missingSites);
    } else {
        String2.log("\n*** Projects.kfmBiological finished successfully.");
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#valueOf(java.lang.Object)}.
 */// w  w w  .j  a  v  a  2s  .  c om
@SuppressWarnings("unchecked")
@Test
public void testValueOfObject() {
    try {
        for (Class<?> type : NUMBERS) {
            Object o = null;
            Object expected = null;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);

            assertEquals("null", expected, valueOf(null));

            o = Float.NaN;
            expected = o;
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o));

            o = Double.NaN;
            expected = o;
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o));

            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                o = wrapper.getMethod("valueOf", String.class).invoke(null, "123.456");
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                o = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                o = c.newInstance(BigInteger.class.equals(type) ? "123" : "123.456");
            }
            expected = o;
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o));

            o = INFINITY_DOUBLE.pow(2);
            expected = o;
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), o,
                    valueOf(o));

            o = INFINITY_DOUBLE.pow(2).negate();
            expected = o;
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), o,
                    valueOf(o));

            o = INFINITY_DOUBLE.pow(2).toBigInteger();
            expected = o;
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), o,
                    valueOf(o));

            o = INFINITY_DOUBLE.pow(2).toBigInteger().negate();
            expected = o;
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), o,
                    valueOf(o));

            o = "";
            expected = null;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "not a number.";
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = new Object[] { 1, 2, 3 };
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "NaN";
            expected = Double.NaN;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "Infinity";
            expected = Double.POSITIVE_INFINITY;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "-Infinity";
            expected = Double.NEGATIVE_INFINITY;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "123.456f";
            expected = (Float) 123.456f;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "123.456d";
            expected = (Double) 123.456d;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "1.23456E2d";
            expected = (Double) 123.456d;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "1.23456E+2d";
            expected = (Double) 123.456d;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "1000000000000";
            expected = 1000000000000L;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "1E12";
            expected = (Float) 1000000000000f;
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));

            o = "1E600";
            expected = new BigDecimal("1E600");
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected, valueOf(o));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:au.org.ala.layers.intersect.Grid.java

private float[] getValuesSubgrids(double[][] points, int bufferSize) {
    int[] subgrid = new int[points.length];
    int[] subgridCounts = new int[subgrids.size()];

    //match points to subgrids
    int anySubgrid = -1;
    for (int i = 0; i < points.length; i++) {
        subgrid[i] = -1;/*from  w  w  w . j  a  v  a2s .c  o  m*/
        for (int j = 0; j < subgrids.size(); j++) {
            Grid g = subgrids.get(j);
            if (g.xmin <= points[i][0] && g.xmax >= points[i][0] && g.ymin <= points[i][1]
                    && g.ymax >= points[i][1]) {
                subgrid[i] = j;
                subgridCounts[j]++;
                anySubgrid = j;
                break;
            }
        }
    }

    //do not need to split because only 1 subgrid
    if (anySubgrid >= 0 && subgridCounts[anySubgrid] == points.length) {
        return subgrids.get(anySubgrid).getValues3(points, bufferSize);
    } else {
        //intersect
        float[] values = new float[points.length];
        for (int i = 0; i < values.length; i++) {
            values[i] = Float.NaN;
        }

        //no intersection
        if (anySubgrid == -1) {
            return values;
        }

        for (int i = 0; i < subgridCounts.length; i++) {
            if (subgridCounts[i] > 0) {
                //build new points array
                double[][] newpoints = new double[subgridCounts[i]][2];
                int p = 0;
                for (int j = 0; j < points.length; j++) {
                    if (subgrid[j] == i) {
                        newpoints[p] = points[j];
                        p++;
                    }
                }

                //intersect
                float[] subValues = subgrids.get(i).getValues3(newpoints, bufferSize);

                //write back intersect values
                p = 0;
                for (int j = 0; j < points.length; j++) {
                    if (subgrid[j] == i) {
                        values[j] = subValues[p];
                        p++;
                    }
                }
            }
        }

        return values;
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#valueOf(java.lang.Object, java.lang.Class)}.
 *//*w ww .jav a  2 s.  c o  m*/
@SuppressWarnings("unchecked")
@Test
public void testValueOfObjectClassOfT() {
    assertEquals("null", valueOf(null, null, false), valueOf(null, null));
    try {
        for (Class<?> type : NUMBERS) {
            Object o = null;
            assertEquals("null: " + type.getSimpleName(), valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = Float.NaN;
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = Double.NaN;
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "1");
                } else {
                    o = valueType.getField("ONE").get(null);
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        valueOf(o, (Class<? extends Number>) type, false),
                        valueOf(o, (Class<? extends Number>) type));
            }

            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "-123");
                } else {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("-123");
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        valueOf(o, (Class<? extends Number>) type, false),
                        valueOf(o, (Class<? extends Number>) type));
            }

            for (Class<?> valueType : OBJECTS) {
                if (ObjectUtils.isAny(valueType, Double.class, Float.class)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "123.456");
                } else if (BigDecimal.class.equals(valueType)) {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("123.456");
                } else {
                    continue;
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        valueOf(o, (Class<? extends Number>) type, false),
                        valueOf(o, (Class<? extends Number>) type));
            }

            for (Class<?> valueType : OBJECTS) {
                if (ObjectUtils.isAny(valueType, Double.class, Float.class)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "-123.456");
                } else if (BigDecimal.class.equals(valueType)) {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("-123.456");
                } else {
                    continue;
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        valueOf(o, (Class<? extends Number>) type, false),
                        valueOf(o, (Class<? extends Number>) type));
            }

            o = INFINITY_DOUBLE.pow(2);
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = INFINITY_DOUBLE.pow(2).negate();
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = INFINITY_DOUBLE.pow(2).toBigInteger();
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = INFINITY_DOUBLE.pow(2).toBigInteger().negate();
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "1";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "-123456E-3";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "Infinity";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "-Infinity";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:gdsc.smlm.ij.plugins.PeakFit.java

/**
 * Locate the peaks in the configured image source. Results are saved to the configured output.
 * <p>/*w  w  w .j a v a 2  s .  c  o  m*/
 * This must be called after initialisation with an image source. Note that each call to this method must be
 * preceded with initialisation to prepare the image and output options.
 */
public void run() {
    if (source == null)
        return;

    int totalFrames = source.getFrames();

    ImageStack stack = null;
    if (showProcessedFrames)
        stack = new ImageStack(bounds.width, bounds.height);

    // Do not crop the region from the source if the bounds match the source dimensions
    Rectangle cropBounds = (bounds.x == 0 && bounds.y == 0 && bounds.width == source.getWidth()
            && bounds.height == source.getHeight()) ? null : bounds;

    // Use the FitEngine to allow multi-threading.
    FitEngine engine = createFitEngine(FastMath.min(totalFrames, Prefs.getThreads()));

    final int step = (totalFrames > 400) ? totalFrames / 200 : 2;

    boolean shutdown = false;
    int slice = 0;
    while (!shutdown) {
        // Noise can optionally be estimated from the entire frame
        float[] data = (ignoreBoundsForNoise) ? source.next() : source.next(cropBounds);
        if (data == null)
            break;

        if (++slice % step == 0) {
            IJ.showProgress(slice, totalFrames);
            IJ.showStatus("Slice: " + slice + " / " + totalFrames);
        }

        float noise = Float.NaN;
        if (ignoreBoundsForNoise) {
            noise = FitWorker.estimateNoise(data, source.getWidth(), source.getHeight(),
                    config.getNoiseMethod());

            // Crop the data to the region
            data = ImageConverter.getData(data, source.getWidth(), source.getHeight(), bounds, null);
        }

        if (showProcessedFrames) {
            stack.addSlice(
                    String.format("Frame %d - %d", source.getStartFrameNumber(), source.getEndFrameNumber()),
                    data);
        }

        // Get the frame number from the source to allow for interlaced and aggregated data
        engine.run(createJob(source.getStartFrameNumber(), source.getEndFrameNumber(), data, bounds, noise));

        if (escapePressed())
            shutdown = true;
    }

    engine.end(shutdown);
    time = engine.getTime();

    if (showProcessedFrames)
        Utils.display("Processed frames", stack);

    showResults();

    source.close();
}

From source file:org.chromium.chrome.browser.tab.Tab.java

/**
 * Cleans up all internal state, destroying any {@link NativePage} or {@link ContentViewCore}
 * currently associated with this {@link Tab}.  This also destroys the native counterpart
 * to this class, which means that all subclasses should erase their native pointers after
 * this method is called.  Once this call is made this {@link Tab} should no longer be used.
 *//*from  w  w  w . jav a2s  .  c o  m*/
public void destroy() {
    mIsInitialized = false;
    // Update the title before destroying the tab. http://b/5783092
    updateTitle();

    if (mTabUma != null)
        mTabUma.onDestroy();

    for (TabObserver observer : mObservers)
        observer.onDestroyed(this);
    mObservers.clear();

    NativePage currentNativePage = mNativePage;
    mNativePage = null;
    destroyNativePageInternal(currentNativePage);
    destroyContentViewCore(true);

    // Destroys the native tab after destroying the ContentView but before destroying the
    // InfoBarContainer. The native tab should be destroyed before the infobar container as
    // destroying the native tab cleanups up any remaining infobars. The infobar container
    // expects all infobars to be cleaned up before its own destruction.
    assert mNativeTabAndroid != 0;
    nativeDestroy(mNativeTabAndroid);
    assert mNativeTabAndroid == 0;

    if (mInfoBarContainer != null) {
        mInfoBarContainer.destroy();
        mInfoBarContainer = null;
    }

    mPreviousTopControlsOffsetY = Float.NaN;
    mPreviousBottomControlsOffsetY = Float.NaN;
    mPreviousContentOffsetY = Float.NaN;

    mNeedsReload = false;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#valueOf(java.lang.Object, java.lang.Class, boolean)}.
 *///  w ww  .  ja  v  a 2  s .  c  o  m
@SuppressWarnings("unchecked")
@Test
public void testValueOfObjectClassOfTBoolean() {
    assertEquals("null", null, valueOf(null, null, false));
    assertEquals("null: fallback", null, valueOf(null, null, true));
    try {
        for (Class<?> type : NUMBERS) {
            Object o = null;
            Object expected = null;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (type.isPrimitive())
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0");
            assertEquals("null: " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0");
            } else {
                expected = wrapper.getField("ZERO").get(null);
            }
            assertEquals("null: fallback: " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("null: typeEquals: " + type.getSimpleName(),
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = Float.NaN;
            expected = !type.isPrimitive() ? null
                    : wrapper.getMethod("valueOf", String.class).invoke(null, "0");
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class))
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "NaN");
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "NaN");
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0");
            } else {
                expected = wrapper.getField("ZERO").get(null);
            }
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = Double.NaN;
            expected = !type.isPrimitive() ? null
                    : wrapper.getMethod("valueOf", String.class).invoke(null, "0");
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class))
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "NaN");
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "NaN");
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0");
            } else {
                expected = wrapper.getField("ZERO").get(null);
            }
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "1");
            } else {
                expected = wrapper.getField("ONE").get(null);
            }

            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "1");
                } else {
                    o = valueType.getField("ONE").get(null);
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                        valueOf(o, (Class<? extends Number>) type, false));
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                        valueOf(o, (Class<? extends Number>) type, true));
                assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type,
                        ClassUtils.primitiveToWrapper(expected.getClass()),
                        valueOf(o, (Class<? extends Number>) type, true).getClass());
            }

            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance("-123");
            }
            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "-123");
                } else {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("-123");
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                        valueOf(o, (Class<? extends Number>) type, false));
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                        valueOf(o, (Class<? extends Number>) type, true));
                assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type,
                        ClassUtils.primitiveToWrapper(expected.getClass()),
                        valueOf(o, (Class<? extends Number>) type, true).getClass());
            }

            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "123.456");
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance(BigInteger.class.equals(type) ? "123" : "123.456");
            }
            for (Class<?> valueType : OBJECTS) {
                if (ObjectUtils.isAny(valueType, Double.class, Float.class)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "123.456");
                } else if (BigDecimal.class.equals(valueType)) {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("123.456");
                } else {
                    continue;
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                        valueOf(o, (Class<? extends Number>) type, false));
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                        valueOf(o, (Class<? extends Number>) type, true));
                assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type,
                        ClassUtils.primitiveToWrapper(expected.getClass()),
                        valueOf(o, (Class<? extends Number>) type, true).getClass());
            }

            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123.456");
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance(BigInteger.class.equals(type) ? "-123" : "-123.456");
            }
            for (Class<?> valueType : OBJECTS) {
                if (ObjectUtils.isAny(valueType, Double.class, Float.class)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "-123.456");
                } else if (BigDecimal.class.equals(valueType)) {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("-123.456");
                } else {
                    continue;
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                        valueOf(o, (Class<? extends Number>) type, false));
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                        valueOf(o, (Class<? extends Number>) type, true));
                assertEquals(o + "(" + o.getClass() + "): typeEquals: " + type,
                        ClassUtils.primitiveToWrapper(expected.getClass()),
                        valueOf(o, (Class<? extends Number>) type, true).getClass());
            }

            o = INFINITY_DOUBLE.pow(2);
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.pow(2).toBigInteger()
                        : INFINITY_DOUBLE.pow(2);
            }
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("Huge: (" + o.getClass() + "): typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = INFINITY_DOUBLE.pow(2).negate();
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("NEGATIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.pow(2).toBigInteger().negate()
                        : INFINITY_DOUBLE.pow(2).negate();
            }
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("Huge: (" + o.getClass() + "): typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = INFINITY_DOUBLE.pow(2).toBigInteger();
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.pow(2).toBigInteger()
                        : INFINITY_DOUBLE.pow(2);
            }
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("Huge: (" + o.getClass() + "): typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = INFINITY_DOUBLE.pow(2).toBigInteger().negate();
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("NEGATIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.pow(2).toBigInteger().negate()
                        : INFINITY_DOUBLE.pow(2).negate();
            }
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("Huge: (" + o.getClass() + "): typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = "";
            expected = !type.isPrimitive() ? null
                    : wrapper.getMethod("valueOf", String.class).invoke(null, "0");
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "0");
            } else {
                expected = wrapper.getField("ZERO").get(null);
            }
            assertEquals("\"" + o + "\": fallback: " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("\"" + o + "\": typeEquals: " + type.getSimpleName(),
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = "1";
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "1");
            } else {
                expected = wrapper.getField("ONE").get(null);
            }
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("\"" + o + "\": typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = "-123456E-3";
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123.456");
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "-123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance(BigInteger.class.equals(type) ? "-123" : "-123.456");
            }
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("\"" + o + "\": typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = "Infinity";
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.toBigInteger() : INFINITY_DOUBLE;
            }
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("\"" + o + "\": typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());

            o = "-Infinity";
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("NEGATIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = BigInteger.class.equals(type) ? INFINITY_DOUBLE.toBigInteger().negate()
                        : INFINITY_DOUBLE.negate();
            }
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, false));
            assertEquals("\"" + o + "\": " + type.getSimpleName(), expected,
                    valueOf(o, (Class<? extends Number>) type, true));
            assertEquals("\"" + o + "\": typeEquals: " + type,
                    ClassUtils.primitiveToWrapper(expected.getClass()),
                    valueOf(o, (Class<? extends Number>) type, true).getClass());
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:me.ccrama.redditslide.Views.SubsamplingScaleImageView.java

/**
 * Convert screen to source x coordinate.
 *//*from   w  w w.  j av a  2s . co m*/
private float viewToSourceX(float vx) {
    if (vTranslate == null) {
        return Float.NaN;
    }
    return (vx - vTranslate.x) / scale;
}