signature:
public class Bearing { /** * Computes distance ( in km ) , azimuth ( degrees clockwise positive
 * from North , 0 to 360 ) , and back azimuth ( degrees clockwise positive
 * from North , 0 to 360 ) , from latitude - longituide point pt1 to
 * latitude - longituide pt2 . < p >
 * Algorithm from U . S . National Geodetic Survey , FORTRAN program " inverse , "
 * subroutine " INVER1 , " by L . PFEIFER and JOHN G . GERGEN .
 * See http : / / www . ngs . noaa . gov / TOOLS / Inv _ Fwd / Inv _ Fwd . html
 * < P > Original documentation :
 * < br > SOLUTION OF THE GEODETIC INVERSE PROBLEM AFTER T . VINCENTY
 * < br > MODIFIED RAINSFORD ' S METHOD WITH HELMERT ' S ELLIPTICAL TERMS
 * < br > EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL
 * < br > STANDPOINT / FOREPOINT MUST NOT BE THE GEOGRAPHIC POLE
 * Reference ellipsoid is the WGS - 84 ellipsoid .
 * < br > See http : / / www . colorado . edu / geography / gcraft / notes / datum / elist . html
 * Requires close to 1.4 E - 5 seconds wall clock time per call
 * on a 550 MHz Pentium with Linux 7.2.
 * @ param e Earth object ( defines radius and flattening )
 * @ param lat1 Lat of point 1
 * @ param lon1 Lon of point 1
 * @ param lat2 Lat of point 2
 * @ param lon2 Lon of point 2
 * @ param result put result here , or null to allocate
 * @ return a Bearing object with distance ( in km ) , azimuth from
 * pt1 to pt2 ( degrees , 0 = north , clockwise positive ) */
public static Bearing calculateBearing ( Earth e , double lat1 , double lon1 , double lat2 , double lon2 , Bearing result ) { } }

implementation:
if ( result == null ) { result = new Bearing ( ) ; } if ( ( lat1 == lat2 ) && ( lon1 == lon2 ) ) { result . distance = 0 ; result . azimuth = 0 ; result . backazimuth = 0 ; return result ; } A = e . getMajor ( ) ; F = e . getFlattening ( ) ; R = 1.0 - F ; // Algorithm from National Geodetic Survey , FORTRAN program " inverse , "
// subroutine " INVER1 , " by L . PFEIFER and JOHN G . GERGEN .
// http : / / www . ngs . noaa . gov / TOOLS / Inv _ Fwd / Inv _ Fwd . html
// Conversion to JAVA from FORTRAN was made with as few changes as possible
// to avoid errors made while recasting form , and to facilitate any future
// comparisons between the original code and the altered version in Java .
// Original documentation :
// SOLUTION OF THE GEODETIC INVERSE PROBLEM AFTER T . VINCENTY
// MODIFIED RAINSFORD ' S METHOD WITH HELMERT ' S ELLIPTICAL TERMS
// EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL
// STANDPOINT / FOREPOINT MUST NOT BE THE GEOGRAPHIC POLE
// A IS THE SEMI - MAJOR AXIS OF THE REFERENCE ELLIPSOID
// F IS THE FLATTENING ( NOT RECIPROCAL ) OF THE REFERNECE ELLIPSOID
// LATITUDES GLAT1 AND GLAT2
// AND LONGITUDES GLON1 AND GLON2 ARE IN RADIANS POSITIVE NORTH AND EAST
// FORWARD AZIMUTHS AT BOTH POINTS RETURNED IN RADIANS FROM NORTH
// Reference ellipsoid is the WGS - 84 ellipsoid .
// See http : / / www . colorado . edu / geography / gcraft / notes / datum / elist . html
// FAZ is forward azimuth in radians from pt1 to pt2;
// BAZ is backward azimuth from point 2 to 1;
// S is distance in meters .
// Conversion to JAVA from FORTRAN was made with as few changes as possible
// to avoid errors made while recasting form , and to facilitate any future
// comparisons between the original code and the altered version in Java .
// IMPLICIT REAL * 8 ( A - H , O - Z )
// COMMON / CONST / PI , RAD
// COMMON / ELIPSOID / A , F
double GLAT1 = rad * lat1 ; double GLAT2 = rad * lat2 ; double TU1 = R * Math . sin ( GLAT1 ) / Math . cos ( GLAT1 ) ; double TU2 = R * Math . sin ( GLAT2 ) / Math . cos ( GLAT2 ) ; double CU1 = 1. / Math . sqrt ( TU1 * TU1 + 1. ) ; double SU1 = CU1 * TU1 ; double CU2 = 1. / Math . sqrt ( TU2 * TU2 + 1. ) ; double S = CU1 * CU2 ; double BAZ = S * TU2 ; double FAZ = BAZ * TU1 ; double GLON1 = rad * lon1 ; double GLON2 = rad * lon2 ; double X = GLON2 - GLON1 ; double D , SX , CX , SY , CY , Y , SA , C2A , CZ , E , C ; int loopCnt = 0 ; do { loopCnt ++ ; // Check for an infinite loop
if ( loopCnt > 1000 ) { throw new IllegalArgumentException ( "Too many iterations calculating bearing:" + lat1 + " " + lon1 + " " + lat2 + " " + lon2 ) ; } SX = Math . sin ( X ) ; CX = Math . cos ( X ) ; TU1 = CU2 * SX ; TU2 = BAZ - SU1 * CU2 * CX ; SY = Math . sqrt ( TU1 * TU1 + TU2 * TU2 ) ; CY = S * CX + FAZ ; Y = Math . atan2 ( SY , CY ) ; SA = S * SX / SY ; C2A = - SA * SA + 1. ; CZ = FAZ + FAZ ; if ( C2A > 0. ) { CZ = - CZ / C2A + CY ; } E = CZ * CZ * 2. - 1. ; C = ( ( - 3. * C2A + 4. ) * F + 4. ) * C2A * F / 16. ; D = X ; X = ( ( E * CY * C + CZ ) * SY * C + Y ) * SA ; X = ( 1. - C ) * X * F + GLON2 - GLON1 ; // IF ( DABS ( D - X ) . GT . EPS ) GO TO 100
} while ( Math . abs ( D - X ) > EPS ) ; if ( loopCnt > maxLoopCnt ) { maxLoopCnt = loopCnt ; // System . err . println ( " loopCnt : " + loopCnt ) ;
} FAZ = Math . atan2 ( TU1 , TU2 ) ; BAZ = Math . atan2 ( CU1 * SX , BAZ * CX - SU1 * CU2 ) + Math . PI ; X = Math . sqrt ( ( 1. / R / R - 1. ) * C2A + 1. ) + 1. ; X = ( X - 2. ) / X ; C = 1. - X ; C = ( X * X / 4. + 1. ) / C ; D = ( 0.375 * X * X - 1. ) * X ; X = E * CY ; S = 1. - E - E ; S = ( ( ( ( SY * SY * 4. - 3. ) * S * CZ * D / 6. - X ) * D / 4. + CZ ) * SY * D + Y ) * C * A * R ; result . distance = S / 1000.0 ; // meters to km
result . azimuth = FAZ * deg ; // radians to degrees
if ( result . azimuth < 0.0 ) { result . azimuth += 360.0 ; // reset azs from - 180 to 180 to 0 to 360
} result . backazimuth = BAZ * deg ; // radians to degrees ; already in 0 to 360 range
return result ;


signature:
public class Bearing { /** * Test the calculations - forward and back
 * @ param args non used */
public static void main ( String [ ] args ) { } }

implementation:
// Bearing workBearing = new Bearing ( ) ;
LatLonPointImpl pt1 = new LatLonPointImpl ( 40 , - 105 ) ; LatLonPointImpl pt2 = new LatLonPointImpl ( 37.4 , - 118.4 ) ; Bearing b = calculateBearing ( pt1 , pt2 , null ) ; System . out . println ( "Bearing from " + pt1 + " to " + pt2 + " = \n\t" + b ) ; LatLonPointImpl pt3 = new LatLonPointImpl ( ) ; pt3 = findPoint ( pt1 , b . getAngle ( ) , b . getDistance ( ) , pt3 ) ; System . out . println ( "using first point, angle and distance, found second point at " + pt3 ) ; pt3 = findPoint ( pt2 , b . getBackAzimuth ( ) , b . getDistance ( ) , pt3 ) ; System . out . println ( "using second point, backazimuth and distance, found first point at " + pt3 ) ; /* uncomment for timing tests
 for ( int j = 0 ; j < 10 ; j + + ) {
 long t1 = System . currentTimeMillis ( ) ;
 for ( int i = 0 ; i < 30000 ; i + + ) {
 workBearing = Bearing . calculateBearing ( 42.5 , - 93.0,
 48.9 , - 117.09 , workBearing ) ;
 long t2 = System . currentTimeMillis ( ) ;
 System . err . println ( " time : " + ( t2 - t1 ) ) ; */


signature:
public class Bearing { /** * Calculate a position given an azimuth and distance from
 * another point .
 * @ param e Earth object ( defines radius and flattening )
 * @ param pt1 Point 1
 * @ param az azimuth ( degrees )
 * @ param dist distance from the point ( km )
 * @ param result Object to use if non - null
 * @ return The LatLonPoint
 * @ see # findPoint ( double , double , double , double , LatLonPointImpl ) */
public static LatLonPointImpl findPoint ( Earth e , LatLonPoint pt1 , double az , double dist , LatLonPointImpl result ) { } }

implementation: return findPoint ( e , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , az , dist , result ) ;


signature:
public class Bearing { /** * Calculate a position given an azimuth and distance from
 * another point . Uses default Earth .
 * @ param pt1 Point 1
 * @ param az azimuth ( degrees )
 * @ param dist distance from the point ( km )
 * @ param result Object to use if non - null
 * @ return The LatLonPoint
 * @ see # findPoint ( double , double , double , double , LatLonPointImpl ) */
public static LatLonPointImpl findPoint ( LatLonPoint pt1 , double az , double dist , LatLonPointImpl result ) { } }

implementation: return findPoint ( defaultEarth , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , az , dist , result ) ;


signature:
public class Bearing { /** * Calculate a position given an azimuth and distance from
 * another point . See details , below . Uses default Earth .
 * @ param lat1 latitude of starting point
 * @ param lon1 longitude of starting point
 * @ param az forward azimuth ( degrees )
 * @ param dist distance from the point ( km )
 * @ param result Object to use if non - null
 * @ return the position as a LatLonPointImpl */
public static LatLonPointImpl findPoint ( double lat1 , double lon1 , double az , double dist , LatLonPointImpl result ) { } }

implementation: return findPoint ( defaultEarth , lat1 , lon1 , az , dist , result ) ;


signature:
public class Bearing { /** * Calculate a position given an azimuth and distance from
 * another point .
 * Algorithm from National Geodetic Survey , FORTRAN program " forward , "
 * subroutine " DIRCT1 , " by stephen j . frakes .
 * http : / / www . ngs . noaa . gov / TOOLS / Inv _ Fwd / Inv _ Fwd . html
 * < p > Original documentation :
 * < pre >
 * SOLUTION OF THE GEODETIC DIRECT PROBLEM AFTER T . VINCENTY
 * MODIFIED RAINSFORD ' S METHOD WITH HELMERT ' S ELLIPTICAL TERMS
 * EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL
 * < / pre >
 * @ param e Earth object ( defines radius and flattening )
 * @ param lat1 latitude of starting point
 * @ param lon1 longitude of starting point
 * @ param az forward azimuth ( degrees )
 * @ param dist distance from the point ( km )
 * @ param result Object to use if non - null
 * @ return the position as a LatLonPointImpl */
public static LatLonPointImpl findPoint ( Earth e , double lat1 , double lon1 , double az , double dist , LatLonPointImpl result ) { } }

implementation:
if ( result == null ) { result = new LatLonPointImpl ( ) ; } if ( ( dist == 0 ) ) { result . setLatitude ( lat1 ) ; result . setLongitude ( lon1 ) ; return result ; } A = e . getMajor ( ) ; F = e . getFlattening ( ) ; R = 1.0 - F ; // Algorithm from National Geodetic Survey , FORTRAN program " forward , "
// subroutine " DIRCT1 , " by stephen j . frakes .
// http : / / www . ngs . noaa . gov / TOOLS / Inv _ Fwd / Inv _ Fwd . html
// Conversion to JAVA from FORTRAN was made with as few changes as
// possible to avoid errors made while recasting form , and
// to facilitate any future comparisons between the original
// code and the altered version in Java .
// Original documentation :
// SUBROUTINE DIRCT1 ( GLAT1 , GLON1 , GLAT2 , GLON2 , FAZ , BAZ , S )
// SOLUTION OF THE GEODETIC DIRECT PROBLEM AFTER T . VINCENTY
// MODIFIED RAINSFORD ' S METHOD WITH HELMERT ' S ELLIPTICAL TERMS
// EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL
// A IS THE SEMI - MAJOR AXIS OF THE REFERENCE ELLIPSOID
// F IS THE FLATTENING OF THE REFERENCE ELLIPSOID
// LATITUDES AND LONGITUDES IN RADIANS POSITIVE NORTH AND EAST
// AZIMUTHS IN RADIANS CLOCKWISE FROM NORTH
// GEODESIC DISTANCE S ASSUMED IN UNITS OF SEMI - MAJOR AXIS A
// PROGRAMMED FOR CDC - 6600 BY LCDR L . PFEIFER NGS ROCKVILLE MD 20FEB75
// MODIFIED FOR SYSTEM 360 BY JOHN G GERGEN NGS ROCKVILLE MD 750608
if ( az < 0.0 ) { az += 360.0 ; // reset azs from - 180 to 180 to 0 to 360
} double FAZ = az * rad ; double GLAT1 = lat1 * rad ; double GLON1 = lon1 * rad ; double S = dist * 1000. ; // convert to meters
double TU = R * Math . sin ( GLAT1 ) / Math . cos ( GLAT1 ) ; double SF = Math . sin ( FAZ ) ; double CF = Math . cos ( FAZ ) ; double BAZ = 0. ; if ( CF != 0 ) { BAZ = Math . atan2 ( TU , CF ) * 2 ; } double CU = 1. / Math . sqrt ( TU * TU + 1. ) ; double SU = TU * CU ; double SA = CU * SF ; double C2A = - SA * SA + 1. ; double X = Math . sqrt ( ( 1. / R / R - 1. ) * C2A + 1. ) + 1. ; X = ( X - 2. ) / X ; double C = 1. - X ; C = ( X * X / 4. + 1 ) / C ; double D = ( 0.375 * X * X - 1. ) * X ; TU = S / R / A / C ; double Y = TU ; double SY , CY , CZ , E , GLAT2 , GLON2 ; do { SY = Math . sin ( Y ) ; CY = Math . cos ( Y ) ; CZ = Math . cos ( BAZ + Y ) ; E = CZ * CZ * 2. - 1. ; C = Y ; X = E * CY ; Y = E + E - 1. ; Y = ( ( ( SY * SY * 4. - 3. ) * Y * CZ * D / 6. + X ) * D / 4. - CZ ) * SY * D + TU ; } while ( Math . abs ( Y - C ) > EPS ) ; BAZ = CU * CY * CF - SU * SY ; C = R * Math . sqrt ( SA * SA + BAZ * BAZ ) ; D = SU * CY + CU * SY * CF ; GLAT2 = Math . atan2 ( D , C ) ; C = CU * CY - SU * SY * CF ; X = Math . atan2 ( SY * SF , C ) ; C = ( ( - 3. * C2A + 4. ) * F + 4. ) * C2A * F / 16. ; D = ( ( E * CY * C + CZ ) * SY * C + Y ) * SA ; GLON2 = GLON1 + X - ( 1. - C ) * D * F ; BAZ = ( Math . atan2 ( SA , BAZ ) + Math . PI ) * deg ; result . setLatitude ( GLAT2 * deg ) ; result . setLongitude ( GLON2 * deg ) ; return result ;


signature:
public class SourcePicture { /** * method to invoke with a filename or URL of a picture that is to be loaded
 * a new thread . This is handy to update the screen while the loading chuggs along in the background .
 * @ paramimageUrlThe URL of the image to be loaded
 * @ parampriorityThe Thread priority for this thread .
 * @ paramrotationThe rotation 0-360 to be used on this picture */
public void loadPictureInThread ( URL imageUrl , int priority , double rotation ) { } }

implementation: if ( pictureStatusCode == LOADING ) { stopLoadingExcept ( imageUrl ) ; } this . imageUrl = imageUrl ; this . rotation = rotation ; LoadThread t = new LoadThread ( this ) ; t . setPriority ( priority ) ; t . start ( ) ;


signature:
public class SourcePicture { /** * method to invoke with a filename or URL of a picture that is to be loaded in
 * the main thread . */
public void loadPicture ( URL imageUrl , double rotation ) { } }

implementation: if ( pictureStatusCode == LOADING ) { stopLoadingExcept ( imageUrl ) ; } this . imageUrl = imageUrl ; this . rotation = rotation ; loadPicture ( ) ;


signature:
public class SourcePicture { /** * loads a picture from the URL in the imageUrl object into the sourcePictureBufferedImage
 * object and updates the status when done or failed . */
public void loadPicture ( ) { } }

implementation:
Tools . log ( "SourcePicture.loadPicture: " + imageUrl . toString ( ) + " loaded into SourcePicture object: " + Integer . toString ( this . hashCode ( ) ) ) ; // Tools . freeMem ( ) ;
setStatus ( LOADING , "Loading: " + imageUrl . toString ( ) ) ; abortFlag = false ; try { // Java 1.4 way with a Listener
ImageInputStream iis = ImageIO . createImageInputStream ( imageUrl . openStream ( ) ) ; Iterator i = ImageIO . getImageReaders ( iis ) ; if ( ! i . hasNext ( ) ) { throw new IOException ( "No Readers Available!" ) ; } reader = ( ImageReader ) i . next ( ) ; // grab the first one
reader . addIIOReadProgressListener ( imageProgressListener ) ; reader . setInput ( iis ) ; sourcePictureBufferedImage = null ; // try {
sourcePictureBufferedImage = reader . read ( 0 ) ; // just get the first image
/* } catch ( OutOfMemoryError e ) {
 Tools . log ( " SourcePicture caught an OutOfMemoryError while loading an image . " ) ;
 iis . close ( ) ;
 reader . removeIIOReadProgressListener ( imageProgressListener ) ;
 reader . dispose ( ) ;
 setStatus ( ERROR , " Out of Memory Error while reading " + imageUrl . toString ( ) ) ;
 sourcePictureBufferedImage = null ;
 / / PictureCache . clear ( ) ;
 JOptionPane . showMessageDialog ( null , / / deliberately null or it swaps the window
 " outOfMemoryError " ,
 " genericError " ,
 JOptionPane . ERROR _ MESSAGE ) ;
 System . gc ( ) ;
 System . runFinalization ( ) ;
 Tools . log ( " JPO has now run a garbage collection and finalization . " ) ;
 return ; */
iis . close ( ) ; reader . removeIIOReadProgressListener ( imageProgressListener ) ; // Tools . log ( " ! ! dispose being called ! ! " ) ;
reader . dispose ( ) ; if ( ! abortFlag ) { if ( rotation != 0 ) { setStatus ( ROTATING , "Rotating: " + imageUrl . toString ( ) ) ; int xRot = sourcePictureBufferedImage . getWidth ( ) / 2 ; int yRot = sourcePictureBufferedImage . getHeight ( ) / 2 ; AffineTransform rotateAf = AffineTransform . getRotateInstance ( Math . toRadians ( rotation ) , xRot , yRot ) ; AffineTransformOp op = new AffineTransformOp ( rotateAf , AffineTransformOp . TYPE_BILINEAR ) ; Rectangle2D newBounds = op . getBounds2D ( sourcePictureBufferedImage ) ; // a simple AffineTransform would give negative top left coordinates - - >
// do another transform to get 0,0 as top coordinates again .
double minX = newBounds . getMinX ( ) ; double minY = newBounds . getMinY ( ) ; AffineTransform translateAf = AffineTransform . getTranslateInstance ( minX * ( - 1 ) , minY * ( - 1 ) ) ; rotateAf . preConcatenate ( translateAf ) ; op = new AffineTransformOp ( rotateAf , AffineTransformOp . TYPE_BILINEAR ) ; newBounds = op . getBounds2D ( sourcePictureBufferedImage ) ; // this piece of code is so essential ! ! ! Otherwise the internal image format
// is totally altered and either the AffineTransformOp decides it doesn ' t
// want to rotate the image or web browsers can ' t read the resulting image .
BufferedImage targetImage = new BufferedImage ( ( int ) newBounds . getWidth ( ) , ( int ) newBounds . getHeight ( ) , BufferedImage . TYPE_3BYTE_BGR ) ; sourcePictureBufferedImage = op . filter ( sourcePictureBufferedImage , targetImage ) ; } setStatus ( READY , "Loaded: " + imageUrl . toString ( ) ) ; PictureCache . add ( imageUrl , ( SourcePicture ) this . clone ( ) ) ; } else { setStatus ( ERROR , "Aborted: " + imageUrl . toString ( ) ) ; sourcePictureBufferedImage = null ; } } catch ( IOException e ) { setStatus ( ERROR , "Error while reading " + imageUrl . toString ( ) ) ; sourcePictureBufferedImage = null ; }


signature:
public class SourcePicture { /** * this method can be invoked to stop the current reader */
public void stopLoading ( ) { } }

implementation:
if ( imageUrl == null ) return ; // SourcePicture has never been used yet
Tools . log ( "SourcePicture.stopLoading: called on " + imageUrl ) ; if ( pictureStatusCode == LOADING ) { reader . abort ( ) ; abortFlag = true ; // reader . dispose ( ) ;
// setStatus ( ERROR , " Cache Loading was stopped " + imageUrl . toString ( ) ) ;
// sourcePictureBufferedImage = null ;
// actually the thread reading the image continues
}


signature:
public class SourcePicture { /** * this method can be invoked to stop the current reader except if it
 * is reading the desired file . It returns true is the desired file
 * is being loaded . Otherwise it returns false . */
public boolean stopLoadingExcept ( URL exemptionURL ) { } }

implementation:
if ( imageUrl == null ) return false ; // has never been used yet
if ( pictureStatusCode != LOADING ) { Tools . log ( "SourcePicture.stopLoadingExcept: called but pointless since image is not LOADING: " + imageUrl . toString ( ) ) ; return false ; } if ( ! exemptionURL . toString ( ) . equals ( imageUrl . toString ( ) ) ) { Tools . log ( "SourcePicture.stopLoadingExcept: called with Url " + exemptionURL . toString ( ) + " --> stopping loading of " + imageUrl . toString ( ) ) ; stopLoading ( ) ; return true ; } else return false ;


signature:
public class SourcePicture { /** * return the size of the image or Zero if there is none */
public Dimension getSize ( ) { } }

implementation: if ( sourcePictureBufferedImage != null ) return new Dimension ( sourcePictureBufferedImage . getWidth ( ) , sourcePictureBufferedImage . getHeight ( ) ) ; else return new Dimension ( 0 , 0 ) ;


signature:
public class SourcePicture { /** * method to register the listening object of the status events */
public void addListener ( SourcePictureListener listener ) { } }

implementation: Tools . log ( "SourcePicture.addListener: listener added on SourcePicture " + Integer . toString ( this . hashCode ( ) ) + " of class: " + listener . getClass ( ) . toString ( ) ) ; sourcePictureListeners . add ( listener ) ; // showListeners ( ) ;


signature:
public class SourcePicture { /** * method to register the listening object of the status events */
public void removeListener ( SourcePictureListener listener ) { } }

implementation: Tools . log ( "SourcePicture.removeListener: listener removed from SourcePicture " + Integer . toString ( this . hashCode ( ) ) + " of class: " + listener . getClass ( ) . toString ( ) ) ; sourcePictureListeners . remove ( listener ) ; // showListeners ( ) ;


signature:
public class SourcePicture { /** * Method that sets the status of the ScalablePicture object and notifies
 * intereasted objects of a change in status ( not built yet ) . */
private void setStatus ( int statusCode , String statusMessage ) { } }

implementation:
Tools . log ( "\nSourcePicture.setStatus: sending status: " + statusMessage ) ; pictureStatusCode = statusCode ; pictureStatusMessage = statusMessage ; Vector nonmodifiedVector = ( Vector ) sourcePictureListeners . clone ( ) ; Enumeration e = nonmodifiedVector . elements ( ) ; while ( e . hasMoreElements ( ) ) { // ( ( SourcePictureListener ) e . nextElement ( ) )
// . sourceStatusChange ( pictureStatusCode , pictureStatusMessage , this ) ;
SourcePictureListener spl = ( ( SourcePictureListener ) e . nextElement ( ) ) ; spl . sourceStatusChange ( pictureStatusCode , pictureStatusMessage , this ) ; Tools . log ( "\nSourcePicture.setStatus: sending status: " + statusMessage + " to " + spl . getClass ( ) . toString ( ) ) ; }


signature:
public class SourcePicture { /** * sets the buffered image . Unusual method use with care . */
public void setSourceBufferedImage ( BufferedImage img , String statusMessage ) { } }

implementation: sourcePictureBufferedImage = img ; setStatus ( READY , statusMessage ) ;


signature:
public class Access { /** * Construct the standard THREDDS access URI for this dataset access method ,
 * resolved agaisnt the parent catalog if the URI is relative .
 * @ return the standard fully resolved THREDDS access URI for this dataset access method , or null if error . */
public URI getStandardUri ( ) { } }

implementation: try { Catalog cat = dataset . getParentCatalog ( ) ; if ( cat == null ) return new URI ( getUnresolvedUrlName ( ) ) ; return cat . resolveUri ( getUnresolvedUrlName ( ) ) ; } catch ( java . net . URISyntaxException e ) { throw new RuntimeException ( "Error parsing URL= " + getUnresolvedUrlName ( ) ) ; }


signature:
public class DataDescriptor { /** * for associated fields */
DataDescriptor makeAssociatedField ( int bitWidth ) { } }

implementation: DataDescriptor assDD = new DataDescriptor ( ) ; assDD . name = name + "_associated_field" ; assDD . units = "" ; assDD . refVal = 0 ; assDD . scale = 0 ; assDD . bitWidth = bitWidth ; assDD . type = 0 ; assDD . f = 0 ; assDD . x = 31 ; assDD . y = 22 ; assDD . fxy = ( short ) ( ( f << 14 ) + ( x << 8 ) + ( y ) ) ; return assDD ;


signature:
public class DataDescriptor { /** * Transfer info from the " proto message " to another message with the exact same structure .
 * @ param fromList transfer from here
 * @ param toList to here */
static public void transferInfo ( List < DataDescriptor > fromList , List < DataDescriptor > toList ) { } }

implementation:
// get info from proto message
if ( fromList . size ( ) != toList . size ( ) ) throw new IllegalArgumentException ( "list sizes dont match " + fromList . size ( ) + " != " + toList . size ( ) ) ; for ( int i = 0 ; i < fromList . size ( ) ; i ++ ) { DataDescriptor from = fromList . get ( i ) ; DataDescriptor to = toList . get ( i ) ; to . refersTo = from . refersTo ; to . name = from . name ; if ( from . getSubKeys ( ) != null ) transferInfo ( from . getSubKeys ( ) , to . getSubKeys ( ) ) ; }


signature:
public class DataDescriptor { /** * count the bits used by the data in this dd and its children
 * only accurate for not compressed , and not variable length
 * @ return bits used by the data in the file */
int countBits ( ) { } }

implementation:
int total_nbits = 0 ; total_nbytesCDM = 0 ; for ( DataDescriptor dd : subKeys ) { if ( dd . subKeys != null ) { total_nbits += dd . countBits ( ) ; total_nbytesCDM += dd . total_nbytesCDM ; } else if ( dd . f == 0 ) { total_nbits += dd . bitWidth ; total_nbytesCDM += dd . getByteWidthCDM ( ) ; } } // replication
if ( replication > 1 ) { total_nbits *= replication ; total_nbytesCDM *= replication ; } return total_nbits ;


signature:
public class DataDescriptor { /** * LOOK need different hashCode , reader assumes using object id */
public boolean equals2 ( Object o ) { } }

implementation: if ( this == o ) return true ; if ( o == null || getClass ( ) != o . getClass ( ) ) return false ; DataDescriptor that = ( DataDescriptor ) o ; if ( fxy != that . fxy ) return false ; if ( replication != that . replication ) return false ; if ( type != that . type ) return false ; if ( subKeys != null ? ! subKeys . equals ( that . subKeys ) : that . subKeys != null ) return false ; return true ;


signature:
public class DataDescriptor { /** * has to use hashCode2 , so cant use list . hashCode ( ) */
private int getListHash ( ) { } }

implementation: if ( subKeys == null ) return 0 ; int result = 1 ; for ( DataDescriptor e : subKeys ) result = 31 * result + ( e == null ? 0 : e . hashCode2 ( ) ) ; return result ;


signature:
public class DbaseFile { /** * Load the dbase file header .
 * @ return 0 for success , - 1 for failure */
private int loadHeader ( ) { } }

implementation:
if ( headerLoaded ) return 0 ; InputStream s = stream ; if ( s == null ) return - 1 ; try { BufferedInputStream bs = new BufferedInputStream ( s ) ; ds = new DataInputStream ( bs ) ; /* read the header as one block of bytes */
Header = new byte [ 32 ] ; ds . readFully ( Header ) ; // System . out . println ( " dbase header is " + Header ) ;
if ( Header [ 0 ] == '<' ) { // looks like html coming back to us !
close ( ds ) ; return - 1 ; } filetype = Header [ 0 ] ; /* 4 bytes for number of records is in little endian */
nrecords = Swap . swapInt ( Header , 4 ) ; nbytesheader = Swap . swapShort ( Header , 8 ) ; /* read in the Field Descriptors */
/* have to figure how many there are from
 * the header size . Should be nbytesheader / 32 - 1 */
nfields = ( nbytesheader / 32 ) - 1 ; if ( nfields < 1 ) { System . out . println ( "nfields = " + nfields ) ; System . out . println ( "nbytesheader = " + nbytesheader ) ; return - 1 ; } FieldDesc = new DbaseFieldDesc [ nfields ] ; data = new DbaseData [ nfields ] ; for ( int i = 0 ; i < nfields ; i ++ ) { FieldDesc [ i ] = new DbaseFieldDesc ( ds , filetype ) ; data [ i ] = new DbaseData ( FieldDesc [ i ] , nrecords ) ; } /* read the last byte of the header ( 0x0d ) */
ds . readByte ( ) ; headerLoaded = true ; } catch ( java . io . IOException e ) { close ( s ) ; return - 1 ; } return 0 ;


signature:
public class DbaseFile { /** * Load the dbase file data .
 * @ return 0 for success , - 1 for failure */
private int loadData ( ) { } }

implementation:
if ( ! headerLoaded ) return - 1 ; if ( dataLoaded ) return 0 ; InputStream s = stream ; if ( s == null ) return - 1 ; try { /* read in the data */
for ( int i = 0 ; i < nrecords ; i ++ ) { /* read the data record indicator */
byte recbyte = ds . readByte ( ) ; if ( recbyte == 0x20 ) { for ( int j = 0 ; j < nfields ; j ++ ) { data [ j ] . readRowN ( ds , i ) ; } } else { /* a deleted record */
nrecords -- ; i -- ; } } dataLoaded = true ; } catch ( java . io . IOException e ) { close ( s ) ; return - 1 ; } finally { close ( s ) ; } return 0 ;


signature:
public class DbaseFile { /** * Extract the data for a given field by name .
 * @ param Name String with the name of the field to retrieve .
 * @ return A DbaseData object if the name was found or null if not found */
public DbaseData getField ( String Name ) { } }

implementation: for ( int i = 0 ; i < nfields ; i ++ ) { if ( FieldDesc [ i ] . Name . equals ( Name ) ) return data [ i ] ; } return null ;


signature:
public class DbaseFile { /** * Extract the double array of data for a field by Name .
 * @ param Name String with the name of the field to retrieve
 * @ return A double [ ] if valid numeric field , otherwise null */
public double [ ] getDoublesByName ( String Name ) { } }

implementation: DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) == DbaseData . TYPE_CHAR ) { String [ ] s = d . getStrings ( ) ; double [ ] dd = new double [ s . length ] ; for ( int i = 0 ; i < s . length ; i ++ ) { dd [ i ] = Double . valueOf ( s [ i ] ) ; } return dd ; } if ( d . getType ( ) == DbaseData . TYPE_BOOLEAN ) { boolean [ ] b = d . getBooleans ( ) ; double [ ] dd = new double [ b . length ] ; for ( int i = 0 ; i < b . length ; i ++ ) { if ( b [ i ] ) { dd [ i ] = 1 ; } else { dd [ i ] = 0 ; } } return dd ; } return d . getDoubles ( ) ;


signature:
public class DbaseFile { /** * Extract the string array of data for a field by Name .
 * @ param Name String with the name of the field to retrieve
 * @ return A String [ ] if valid character field , otherwise null */
public String [ ] getStringsByName ( String Name ) { } }

implementation: DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) != DbaseData . TYPE_CHAR ) return null ; return d . getStrings ( ) ;


signature:
public class DbaseFile { /** * Extract the boolean array of data for a field by Name .
 * @ param Name String with the name of the field to retrieve
 * @ return A boolean [ ] if valid character field , otherwise null */
public boolean [ ] getBooleansByName ( String Name ) { } }

implementation: DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) != DbaseData . TYPE_BOOLEAN ) return null ; return d . getBooleans ( ) ;


signature:
public class DbaseFile { /** * Get the name of a field by column number .
 * @ param i The column number of the field name .
 * @ return A String with the field name or null if out of bounds */
public String getFieldName ( int i ) { } }

implementation: if ( i >= nfields || i < 0 ) { return null ; } return ( FieldDesc [ i ] . Name ) ;


signature:
public class DbaseFile { /** * Get a list of all the field names in the dbase file
 * @ return A String array of all the field names */
public String [ ] getFieldNames ( ) { } }

implementation: String [ ] s = new String [ nfields ] ; for ( int i = 0 ; i < nfields ; i ++ ) { s [ i ] = getFieldName ( i ) ; } return s ;


signature:
public class DbaseFile { /** * Test program , dumps a Dbase file to stdout . */
public static void main ( String [ ] args ) { } }

implementation:
if ( args . length < 1 ) { System . out . println ( "filename or URL required" ) ; System . exit ( - 1 ) ; } for ( String s : args ) { System . out . println ( "*** Dump of Dbase " + s + ":" ) ; try { DbaseFile dbf = new DbaseFile ( s ) ; // load ( ) method reads all data at once
if ( dbf . loadHeader ( ) != 0 ) { System . out . println ( "Error loading header" + s ) ; System . exit ( - 1 ) ; } // output schema as [ type0 field0 , type1 field1 , . . . ]
String [ ] fieldNames = dbf . getFieldNames ( ) ; System . out . print ( "[" ) ; int nf = dbf . getNumFields ( ) ; DbaseData [ ] dbd = new DbaseData [ nf ] ; for ( int field = 0 ; field < nf ; field ++ ) { dbd [ field ] = dbf . getField ( field ) ; switch ( dbd [ field ] . getType ( ) ) { case DbaseData . TYPE_BOOLEAN : System . out . print ( "boolean " ) ; break ; case DbaseData . TYPE_CHAR : System . out . print ( "String " ) ; break ; case DbaseData . TYPE_NUMERIC : System . out . print ( "double " ) ; break ; } System . out . print ( fieldNames [ field ] ) ; if ( field < nf - 1 ) System . out . print ( ", " ) ; } System . out . println ( "]" ) ; if ( dbf . loadData ( ) != 0 ) { System . out . println ( "Error loading data" + s ) ; System . exit ( - 1 ) ; } // output data
for ( int rec = 0 ; rec < dbf . getNumRecords ( ) ; rec ++ ) { for ( int field = 0 ; field < nf ; field ++ ) { System . out . print ( dbd [ field ] . getData ( rec ) ) ; if ( field < nf - 1 ) System . out . print ( ", " ) ; else System . out . println ( ) ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; break ; } }


signature:
public class DapNode { /** * attributes are not allowed on some node types */
public Map < String , DapAttribute > getAttributes ( ) { } }

implementation: if ( attributes == null ) attributes = new HashMap < String , DapAttribute > ( ) ; return attributes ;


signature:
public class DapNode { /** * This may occur after initial construction */
synchronized public DapAttribute setAttribute ( DapAttribute attr ) throws DapException { } }

implementation: if ( attributes == null ) attributes = new HashMap < String , DapAttribute > ( ) ; DapAttribute old = attributes . get ( attr . getShortName ( ) ) ; attributes . put ( attr . getShortName ( ) , attr ) ; attr . setParent ( this ) ; return old ;


signature:
public class DapNode { /** * Used by AbstractDSP to suppress certain attributes .
 * @ param attr
 * @ throws DapException */
public synchronized void removeAttribute ( DapAttribute attr ) throws DapException { } }

implementation: if ( this . attributes == null ) return ; String name = attr . getShortName ( ) ; if ( this . attributes . containsKey ( name ) ) this . attributes . remove ( name ) ;


signature:
public class DapNode { /** * Closest containing group
 * @ returns closest group not equal to this
 * or null if this is a DapDataset */
public DapGroup getGroup ( ) { } }

implementation:
if ( this . sort == DapSort . DATASET ) return null ; // Walk the parent node until we find a group
DapNode group = parent ; while ( group != null ) { switch ( group . getSort ( ) ) { case DATASET : case GROUP : return ( DapGroup ) group ; default : group = group . getParent ( ) ; break ; } } return ( DapGroup ) group ;


signature:
public class DapNode { /** * Closest containing group , structure , sequence
 * @ returns closest container */
public DapNode getContainer ( ) { } }

implementation: DapNode parent = this . parent ; switch ( getSort ( ) ) { default : break ; case ENUMCONST : parent = ( ( DapEnumConst ) this ) . getParent ( ) . getContainer ( ) ; break ; case ATTRIBUTE : case ATTRIBUTESET : case OTHERXML : parent = ( ( DapAttribute ) this ) . getParent ( ) ; if ( parent instanceof DapVariable ) parent = parent . getContainer ( ) ; break ; case MAP : parent = ( ( DapMap ) this ) . getVariable ( ) . getContainer ( ) ; break ; } return parent ;


signature:
public class DapNode { /** * Set the parent DapNode ; may sometimes be same as container ,
 * but not always ( think attributes or maps ) .
 * Invariant : parent must be either a group or a variable .
 * We can infer the container , so set that also .
 * @ param parent the proposed parent node */
public void setParent ( DapNode parent ) { } }

implementation: assert this . parent == null ; assert ( ( this . getSort ( ) == DapSort . ENUMCONST && parent . getSort ( ) == DapSort . ENUMERATION ) || parent . getSort ( ) . isa ( DapSort . GROUP ) || parent . getSort ( ) == DapSort . VARIABLE || parent . getSort ( ) == DapSort . STRUCTURE || parent . getSort ( ) == DapSort . SEQUENCE || this . getSort ( ) == DapSort . ATTRIBUTE || this . getSort ( ) == DapSort . ATTRIBUTESET ) ; this . parent = parent ;


signature:
public class DapNode { /** * Here , escaped means backslash escaped short name
 * @ return escaped name */
public String getEscapedShortName ( ) { } }

implementation: if ( this . escapedname == null ) this . escapedname = Escape . backslashEscape ( getShortName ( ) , null ) ; return this . escapedname ;


signature:
public class DapNode { /** * Compute the path upto , and including
 * some specified containing node ( null = > root )
 * The containing node is included as is this node .
 * @ return ordered list of parent nodes */
public List < DapNode > getPath ( ) { } }

implementation: List < DapNode > path = new ArrayList < DapNode > ( ) ; DapNode current = this ; for ( ; ; ) { path . add ( 0 , current ) ; current = current . getParent ( ) ; if ( current == null ) break ; } return path ;


signature:
public class DapNode { /** * Get the transitive list of containers
 * Not including this node
 * @ return list of container nodes */
public List < DapNode > getContainerPath ( ) { } }

implementation: List < DapNode > path = new ArrayList < DapNode > ( ) ; DapNode current = this . getContainer ( ) ; for ( ; ; ) { path . add ( 0 , current ) ; if ( current . getContainer ( ) == null ) break ; current = current . getContainer ( ) ; } return path ;


signature:
public class DapNode { /** * Get the transitive list of containing groups
 * Possibly including this node
 * @ return list of group nodes */
public List < DapGroup > getGroupPath ( ) { } }

implementation: List < DapGroup > path = new ArrayList < DapGroup > ( ) ; DapNode current = this ; for ( ; ; ) { if ( current . getSort ( ) == DapSort . GROUP || current . getSort ( ) == DapSort . DATASET ) path . add ( 0 , ( DapGroup ) current ) ; if ( current . getContainer ( ) == null ) break ; current = current . getContainer ( ) ; } return path ;


signature:
public class DapNode { /** * Compute the FQN of this node */
public String computefqn ( ) { } }

implementation:
List < DapNode > path = getPath ( ) ; // excludes root / wrt
StringBuilder fqn = new StringBuilder ( ) ; DapNode parent = path . get ( 0 ) ; for ( int i = 1 ; i < path . size ( ) ; i ++ ) { // start at 1 to skip root
DapNode current = path . get ( i ) ; // Depending on what parent is , use different delimiters
switch ( parent . getSort ( ) ) { case DATASET : case GROUP : case ENUMERATION : fqn . append ( '/' ) ; fqn . append ( Escape . backslashEscape ( current . getShortName ( ) , "/." ) ) ; break ; // These use ' . '
case STRUCTURE : case SEQUENCE : case ENUMCONST : case VARIABLE : fqn . append ( '.' ) ; fqn . append ( current . getEscapedShortName ( ) ) ; break ; default : // Others should never happen
throw new IllegalArgumentException ( "Illegal FQN parent" ) ; } parent = current ; } return fqn . toString ( ) ;


signature:
public class DapNode { /** * Misc . Methods */
public boolean isTopLevel ( ) { } }

implementation: return parent == null || parent . getSort ( ) == DapSort . DATASET || parent . getSort ( ) == DapSort . GROUP ;


signature:
public class CFRadialAdapter { /** * TypedDatasetFactoryIF */
public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { } }

implementation: String convStr = ncd . findAttValueIgnoreCase ( null , "Conventions" , null ) ; if ( ( null != convStr ) && convStr . startsWith ( "CF/Radial" ) ) return this ; return null ;


signature:
public class CFRadialAdapter { /** * _ more _
 * @ param nds _ more _
 * @ param var _ more _ */
protected void addRadialVariable ( NetcdfDataset nds , Variable var ) { } }

implementation: RadialVariable rsvar = null ; String vName = var . getShortName ( ) ; int tIdx = var . findDimensionIndex ( "time" ) ; int rIdx = var . findDimensionIndex ( "range" ) ; int ptsIdx = var . findDimensionIndex ( "n_points" ) ; if ( ( ( tIdx == 0 ) && ( rIdx == 1 ) ) || ( ptsIdx == 0 ) ) { VariableSimpleIF v = new MyRadialVariableAdapter ( vName , var . getAttributes ( ) ) ; rsvar = makeRadialVariable ( nds , v , var ) ; } if ( rsvar != null ) { dataVariables . add ( rsvar ) ; }


signature:
public class CFRadialAdapter { /** * _ more _
 * @ return _ more _ */
public String getInfo ( ) { } }

implementation: StringBuffer sbuff = new StringBuffer ( ) ; sbuff . append ( "CFRadial2Dataset\n" ) ; sbuff . append ( super . getDetailInfo ( ) ) ; sbuff . append ( "\n\n" ) ; sbuff . append ( parseInfo . toString ( ) ) ; return sbuff . toString ( ) ;


signature:
public class D4DSP { /** * Compilation */
protected void build ( String document , byte [ ] serialdata , ByteOrder order ) throws DapException { } }

implementation: DapDataset dmr = parseDMR ( document ) ; if ( DEBUG || DUMPDMR ) { System . err . println ( "\n+++++++++++++++++++++" ) ; System . err . println ( dmr ) ; System . err . println ( "+++++++++++++++++++++\n" ) ; } if ( DEBUG || DUMPDAP ) { ByteBuffer data = ByteBuffer . wrap ( serialdata ) ; System . err . println ( "+++++++++++++++++++++" ) ; System . err . println ( "\n---------------------" ) ; DapDump . dumpbytes ( data , false ) ; System . err . println ( "\n---------------------\n" ) ; } build ( dmr , serialdata , order ) ;


signature:
public class D4DSP { /** * Build the data from the incoming serial data
 * Note that some DSP ' s will not use
 * @ param dmr
 * @ param serialdata
 * @ param order
 * @ throws DapException */
protected void build ( DapDataset dmr , byte [ ] serialdata , ByteOrder order ) throws DapException { } }

implementation:
setDMR ( dmr ) ; // " Compile " the databuffer section of the server response
this . databuffer = ByteBuffer . wrap ( serialdata ) . order ( order ) ; D4DataCompiler compiler = new D4DataCompiler ( this , getChecksumMode ( ) , getOrder ( ) , this . databuffer ) ; compiler . compile ( ) ;


signature:
public class WriterStationObsDataset { /** * not tested */
private void write ( StationObsDataset sobsDataset ) throws IOException { } }

implementation:
createGlobalAttributes ( ) ; createStations ( sobsDataset . getStations ( ) ) ; ncfile . addGlobalAttribute ( "time_coverage_start" , dateFormatter . toDateTimeStringISO ( sobsDataset . getStartDate ( ) ) ) ; ncfile . addGlobalAttribute ( "time_coverage_end" , dateFormatter . toDateTimeStringISO ( sobsDataset . getEndDate ( ) ) ) ; createDataVariables ( sobsDataset . getDataVariables ( ) ) ; // global attributes
List gatts = sobsDataset . getGlobalAttributes ( ) ; for ( int i = 0 ; i < gatts . size ( ) ; i ++ ) { Attribute att = ( Attribute ) gatts . get ( i ) ; ncfile . addGlobalAttribute ( att ) ; } // done with define mode
ncfile . create ( ) ; // write out the station info
writeStationData ( sobsDataset . getStations ( ) ) ; // now write the observations
if ( ! ( Boolean ) ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ) throw new IllegalStateException ( "can't add record variable" ) ; int [ ] origin = new int [ 1 ] ; int [ ] originTime = new int [ 2 ] ; int recno = 0 ; ArrayStructureW sArray = null ; ArrayObject . D1 timeArray = new ArrayObject . D1 ( DataType . STRING , String . class , false , 1 ) ; DataIterator diter = sobsDataset . getDataIterator ( 1000 * 1000 ) ; while ( diter . hasNext ( ) ) { StationObsDatatype sobs = ( StationObsDatatype ) diter . nextData ( ) ; StructureData recordData = sobs . getData ( ) ; // needs to be wrapped as an ArrayStructure , even though we are only writing one at a time .
if ( sArray == null ) sArray = new ArrayStructureW ( recordData . getStructureMembers ( ) , new int [ ] { 1 } ) ; sArray . setStructureData ( recordData , 0 ) ; // date is handled specially
timeArray . set ( 0 , dateFormatter . toDateTimeStringISO ( sobs . getObservationTimeAsDate ( ) ) ) ; // write the recno record
origin [ 0 ] = recno ; originTime [ 0 ] = recno ; try { ncfile . write ( "record" , origin , sArray ) ; ncfile . writeStringData ( timeName , originTime , timeArray ) ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; throw new IllegalStateException ( e ) ; } recno ++ ; } ncfile . close ( ) ;


signature:
public class PreferencesExt { /** * Get the object that has the specified key .
 * This returns the object itself , not a copy , so
 * if you change the bean and call store . save ( ) , any changes to the object will be saved ,
 * even without calling putBean ( ) . If you want to change the object without saving the
 * changes , you must make a copy of the object yourself .
 * @ param key get the object with this key .
 * @ param def the default value to be returned in the event that this
 * preference node has no value associated with < tt > key < / tt > .
 * @ return the value associated with < tt > key < / tt > , or < tt > def < / tt >
 * if no value is associated with < tt > key < / tt > .
 * @ throws IllegalStateException if this node ( or an ancestor ) has been
 * removed with the { @ link # removeNode ( ) } method .
 * @ throws NullPointerException if key is < tt > null < / tt > . ( A
 * < tt > null < / tt > default < i > is < / i > permitted . ) */
public Object getBean ( String key , Object def ) { } }

implementation:
if ( key == null ) throw new NullPointerException ( "Null key" ) ; if ( isRemoved ( ) ) throw new IllegalStateException ( "Node has been removed." ) ; synchronized ( lock ) { Object result = null ; try { result = _getObject ( key ) ; if ( result != null ) { if ( result instanceof Bean . Collection ) result = ( ( Bean . Collection ) result ) . getCollection ( ) ; else if ( result instanceof Bean ) result = ( ( Bean ) result ) . getObject ( ) ; } } catch ( Exception e ) { // Ignoring exception causes default to be returned
} return ( result == null ? def : result ) ; }


signature:
public class PreferencesExt { /** * Stores an object using simple bean properties .
 * If the exact key and value are already in
 * the storedDefaults ( using equals ( ) to test for equality ) , then it is not
 * stored .
 * @ param key key with which the specified value is to be associated .
 * @ param newValue store this bean .
 * @ throws NullPointerException if key or value is < tt > null < / tt > .
 * @ throws IllegalStateException if this node ( or an ancestor ) has been
 * removed with the { @ link # removeNode ( ) } method . */
public void putBean ( String key , Object newValue ) { } }

implementation:
// if matches a stored Default , dont store
Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , new Bean ( newValue ) ) ;


signature:
public class PreferencesExt { /** * Stores a Collection of beans . The beans are stored using simple bean properties .
 * The collection of beans must all be of the same class .
 * @ param key key with which the specified collection is to be associated .
 * @ param newValue store this collection of beans .
 * @ throws NullPointerException if key or value is < tt > null < / tt > .
 * @ throws IllegalStateException if this node ( or an ancestor ) has been
 * removed with the { @ link # removeNode ( ) } method . */
public void putBeanCollection ( String key , Collection newValue ) { } }

implementation:
// if matches a stored Default , dont store
Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , new Bean . Collection ( newValue ) ) ;


signature:
public class PreferencesExt { /** * Stores an object using XMLEncoder / XMLDecoder . Use this for arbitrary objects .
 * If the exact key and value are already in
 * the storedDefaults ( using equals ( ) to test for equality ) , then it is not
 * stored .
 * @ param key key with which the specified value is to be associated .
 * @ param newValue store this bean object .
 * @ throws NullPointerException if key or value is < tt > null < / tt > .
 * @ throws IllegalStateException if this node ( or an ancestor ) has been
 * removed with the { @ link # removeNode ( ) } method . */
public void putBeanObject ( String key , Object newValue ) { } }

implementation:
// if matches a stored Default , dont store
Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , newValue ) ;


signature:
public class PreferencesExt { /** * Get an arrayList . This returns a copy of the stored list .
 * @ param key key whose associated value is to be returned .
 * @ param def the value to be returned in the event that this
 * preference node has no value associated with < tt > key < / tt > .
 * @ return the value associated with < tt > key < / tt > , or < tt > def < / tt >
 * if no value is associated with < tt > key < / tt > . */
public List getList ( String key , List def ) { } }

implementation: try { Object bean = getBean ( key , def ) ; return ( List ) bean ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; }


signature:
public class PreferencesExt { /** * Implements < tt > AbstractPreferences < / tt > < tt > childrenNamesSpi ( ) < / tt > method .
 * Find all children nodes of this node ( or of identically named nodes in
 * storedDefaults ) */
protected String [ ] childrenNamesSpi ( ) { } }

implementation: HashSet allKids = new HashSet ( children . keySet ( ) ) ; PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKids . addAll ( sd . childrenNamesSpi ( absolutePath ( ) ) ) ; ArrayList list = new ArrayList ( allKids ) ; Collections . sort ( list ) ; String result [ ] = new String [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) result [ i ] = list . get ( i ) . toString ( ) ; return result ;


signature:
public class PreferencesExt { /** * / * Find all children nodes of named node ( or of identically named nodes in
 * storedDefaults ) */
protected Collection childrenNamesSpi ( String nodePath ) { } }

implementation: HashSet allKids = new HashSet ( ) ; try { if ( nodeExists ( nodePath ) ) { PreferencesExt node = ( PreferencesExt ) node ( nodePath ) ; allKids . addAll ( node . children . keySet ( ) ) ; } } catch ( java . util . prefs . BackingStoreException e ) { } PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKids . addAll ( sd . childrenNamesSpi ( nodePath ) ) ; return allKids ;


signature:
public class PreferencesExt { /** * / * Find all key names of this node ( or of identically named nodes in
 * storedDefaults )
 * ( The returned array will be of size zero if this node has no preferences . )
 * It is guaranteed that this node has not been removed .
 * This method is invoked with the lock on this node held . */
protected String [ ] keysSpi ( ) throws BackingStoreException { } }

implementation:
HashSet allKeys = new HashSet ( keyValues . keySet ( ) ) ; // show ( " allKeys1 " , allKeys ) ;
PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKeys . addAll ( sd . keysSpi ( absolutePath ( ) ) ) ; // show ( " allKeys2 " , allKeys ) ;
ArrayList list = new ArrayList ( allKeys ) ; Collections . sort ( list ) ; // show ( " allKeys3 " , list ) ;
String result [ ] = new String [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) result [ i ] = list . get ( i ) . toString ( ) ; return result ;


signature:
public class PreferencesExt { /** * / * Find all keys of named node ( or of identically named nodes in
 * storedDefaults ) */
protected Collection keysSpi ( String nodePath ) { } }

implementation:
HashSet allKeys = new HashSet ( ) ; try { if ( nodeExists ( nodePath ) ) { PreferencesExt node = ( PreferencesExt ) node ( nodePath ) ; // show ( " subKeys1 " + nodePath , node . keyValues . keySet ( ) ) ;
allKeys . addAll ( node . keyValues . keySet ( ) ) ; } } catch ( java . util . prefs . BackingStoreException e ) { } PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) { allKeys . addAll ( sd . keysSpi ( nodePath ) ) ; // show ( " subKeys2 " , allKeys ) ;
} return allKeys ;


signature:
public class PreferencesExt { /** * Returns the named child of this preference node , creating it if it does not
 * already exist . It is guaranteed that name is non - null , non - empty , does not
 * contain the slash character ( ' / ' ) , and is no longer than
 * Preferences . MAX _ NAME _ LENGTH characters . Also , it is guaranteed that this node
 * has not been removed . ( The implementor needn ' t check for any of these things . )
 * Finally , it is guaranteed that the named node has not been returned by a
 * previous invocation of this method or getChild ( String ) after the last time
 * that it was removed . In other words , a cached value will always be used in
 * preference to invoking this method . Subclasses need not maintain their own
 * cache of previously returned children .
 * The implementer must ensure that the returned node has not been removed .
 * If a like - named child of this node was previously removed , the implementer
 * must return a newly constructed AbstractPreferences node ; once removed , an
 * AbstractPreferences node cannot be " resuscitated . "
 * If this method causes a node to be created , this node is not guaranteed to
 * be persistent until the flush method is invoked on this node or one of its
 * ancestors ( or descendants ) .
 * This method is invoked with the lock on this node held . */
protected AbstractPreferences childSpi ( String name ) { } }

implementation: PreferencesExt child ; if ( null != ( child = ( PreferencesExt ) children . get ( name ) ) ) return child ; child = new PreferencesExt ( this , name ) ; children . put ( name , child ) ; child . newNode = true ; return child ;


signature:
public class PreferencesExt { /** * / * Gets the value with this keyName , if not found , look in storedDefaults .
 * Return the value associated with the specified key at this preference node ,
 * or null if there is no association for this key , or the association cannot be
 * determined at this time . It is guaranteed that key is non - null . Also , it is
 * guaranteed that this node has not been removed . ( The implementor needn ' t
 * check for either of these things . )
 * Generally speaking , this method should not throw an exception under any
 * circumstances . If , however , if it does throw an exception , the exception
 * will be intercepted and treated as a null return value .
 * This method is invoked with the lock on this node held . */
protected String getSpi ( String keyName ) { } }

implementation: Object o = _getObject ( keyName ) ; return ( o == null ) ? null : o . toString ( ) ;


signature:
public class PreferencesExt { /** * / * Stores the value with this key , if not already in storedDefaults .
 * Put the given key - value association into this preference node . It is guaranteed
 * that key and value are non - null and of legal length . Also , it is guaranteed
 * that this node has not been removed . ( The implementor needn ' t check for any of these things . )
 * This method is invoked with the lock on this node held . */
protected void putSpi ( String key , String newValue ) { } }

implementation:
// if matches a stored Default , dont store
String oldValue = getSpi ( key ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , newValue ) ;


signature:
public class PreferencesExt { /** * / * removes node , no effect on storedDefaults
 * Removes this preference node , invalidating it and any preferences that
 * it contains . The named child will have no descendants at the time this
 * invocation is made ( i . e . , the Preferences . removeNode ( ) method invokes
 * this method repeatedly in a bottom - up fashion , removing each of a node ' s
 * descendants before removing the node itself ) .
 * This method is invoked with the lock held on this node and its parent (
 * and all ancestors that are being removed as a result of a single invocation
 * to Preferences . removeNode ( ) ) .
 * The removal of a node needn ' t become persistent until the flush method is
 * invoked on this node ( or an ancestor ) . */
protected void removeNodeSpi ( ) throws BackingStoreException { } }

implementation:
// System . out . println ( " removeNodeSpi : " + name ( ) ) ;
if ( parent != null ) { if ( null == parent . children . remove ( name ( ) ) ) System . out . println ( "ERROR PreferencesExt.removeNodeSpi :" + name ( ) ) ; }


signature:
public class PreferencesExt { /** * assume key non - null , locked node */
private Object _getObject ( String keyName ) { } }

implementation:
Object result = null ; try { result = keyValues . get ( keyName ) ; if ( result == null ) { // if failed , check the stored Defaults
PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) result = sd . getObjectFromNode ( absolutePath ( ) , keyName ) ; } } catch ( Exception e ) { // Ignoring exception causes default to be returned
} return result ;


signature:
public class Grib2Record { /** * isolate dependencies here - in case we have a " minimal I / O " mode where not all fields are available */
public float [ ] readData ( RandomAccessFile raf ) throws IOException { } }

implementation: Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drss . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drss . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drss . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( gds . isThin ( ) ) data = QuasiRegular . convertQuasiGrid ( data , gds . getNptsInLine ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , GribData . getInterpolationMethod ( ) ) ; lastRecordRead = this ; return data ;


signature:
public class Grib2Record { /** * debugging - do not use */
@ Nullable public int [ ] readRawData ( RandomAccessFile raf ) throws IOException { } }

implementation: Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drss . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drss . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drss . getDrs ( raf ) ; return reader . getRawData ( raf , bms , gdrs ) ;


signature:
public class Grib2Record { /** * Read data array
 * @ param raf from this RandomAccessFile
 * @ param drsPos Grib2SectionDataRepresentation starts here
 * @ return data as float [ ] array
 * @ throws IOException on read error */
public float [ ] readData ( RandomAccessFile raf , long drsPos ) throws IOException { } }

implementation: raf . seek ( drsPos ) ; Grib2SectionDataRepresentation drs = new Grib2SectionDataRepresentation ( raf ) ; Grib2SectionBitMap bms = new Grib2SectionBitMap ( raf ) ; Grib2SectionData dataSection = new Grib2SectionData ( raf ) ; Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drs . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drs . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drs . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( gds . isThin ( ) ) data = QuasiRegular . convertQuasiGrid ( data , gds . getNptsInLine ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , GribData . getInterpolationMethod ( ) ) ; lastRecordRead = this ; return data ;


signature:
public class Grib2Record { /** * Read data array : use when you want to be independent of the GribRecord
 * @ param raf from this RandomAccessFile
 * @ param drsPos Grib2SectionDataRepresentation starts here
 * @ param bmsPos if non - zero , use the bms that starts here
 * @ param gdsNumberPoints gdss . getNumberPoints ( )
 * @ param scanMode gds . scanMode
 * @ param nx gds . nx
 * @ return data as float [ ] array
 * @ throws IOException on read error */
public static float [ ] readData ( RandomAccessFile raf , long drsPos , long bmsPos , int gdsNumberPoints , int scanMode , int nx , int ny , int [ ] nptsInLine ) throws IOException { } }

implementation: raf . seek ( drsPos ) ; Grib2SectionDataRepresentation drs = new Grib2SectionDataRepresentation ( raf ) ; Grib2SectionBitMap bms = new Grib2SectionBitMap ( raf ) ; Grib2SectionData dataSection = new Grib2SectionData ( raf ) ; if ( bmsPos > 0 ) bms = Grib2SectionBitMap . factory ( raf , bmsPos ) ; Grib2DataReader reader = new Grib2DataReader ( drs . getDataTemplate ( ) , gdsNumberPoints , drs . getDataPoints ( ) , scanMode , nx , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drs . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( nptsInLine != null ) data = QuasiRegular . convertQuasiGrid ( data , nptsInLine , nx , ny , GribData . getInterpolationMethod ( ) ) ; if ( getlastRecordRead ) lastRecordRead = Grib2RecordScanner . findRecordByDrspos ( raf , drsPos ) ; return data ;


signature:
public class DSPPrinter { /** * Print data from a DSP
 * - optionally constrained
 * @ throws DapException */
public DSPPrinter print ( ) throws DapException { } }

implementation: DapDataset dmr = this . dsp . getDMR ( ) ; if ( this . ce == null ) this . ce = CEConstraint . getUniversal ( dmr ) ; this . printer . setIndent ( 0 ) ; List < DapVariable > topvars = dmr . getTopVariables ( ) ; for ( int i = 0 ; i < topvars . size ( ) ; i ++ ) { DapVariable top = topvars . get ( i ) ; List < Slice > slices = this . ce . getConstrainedSlices ( top ) ; if ( this . ce . references ( top ) ) { DataCursor data = dsp . getVariableData ( top ) ; printVariable ( data , slices ) ; } } printer . eol ( ) ; return this ;


signature:
public class DSPPrinter { /** * Print an arbitrary DataVariable using a constraint .
 * Handling newlines is a bit tricky
 * so the rule is that the
 * last newline is elided and left
 * for the caller to print .
 * Exceptions : ?
 * @ param data - the cursor to print
 * @ throws DapException Note that the PrintWriter and CEConstraint are global . */
protected void printVariable ( DataCursor data , List < Slice > slices ) throws DapException { } }

implementation:
DapVariable dapv = ( DapVariable ) data . getTemplate ( ) ; if ( data . isScalar ( ) ) { assert slices == Slice . SCALARSLICES ; printScalar ( data ) ; } else { // not scalar
printArray ( data , slices ) ; }


signature:
public class DSPPrinter { /** * Print a single structure or sequence or record instance
 * @ param datav
 * @ throws DapException */
protected void printCompoundInstance ( DataCursor datav ) throws DapException { } }

implementation:
// Index index = datav . getIndex ( ) ;
DapStructure dstruct = ( DapStructure ) ( ( DapVariable ) datav . getTemplate ( ) ) . getBaseType ( ) ; switch ( datav . getScheme ( ) ) { case STRUCTURE : case RECORD : List < DapVariable > dfields = dstruct . getFields ( ) ; for ( int f = 0 ; f < dfields . size ( ) ; f ++ ) { DapVariable field = dfields . get ( f ) ; List < Slice > fieldslices = this . ce . getConstrainedSlices ( field ) ; DataCursor fdata = datav . readField ( f ) ; printVariable ( fdata , fieldslices ) ; } break ; case SEQUENCE : DapSequence dseq = ( DapSequence ) dstruct ; long count = datav . getRecordCount ( ) ; for ( long r = 0 ; r < count ; r ++ ) { DataCursor dr = datav . readRecord ( r ) ; printer . marginPrint ( "[" ) ; printer . eol ( ) ; printer . indent ( ) ; printCompoundInstance ( dr ) ; printer . outdent ( ) ; printer . marginPrint ( "]" ) ; } break ; default : throw new DapException ( "Unexpected data cursor scheme:" + datav . getScheme ( ) ) ; }


signature:
public class Geostationary { /** * copy constructor - avoid clone ! ! */
@ Override public ProjectionImpl constructCopy ( ) { } }

implementation:
// constructor takes sweep _ angle _ axis , so need to translate between
// scan geometry and sweep _ angle _ axis first
// GOES : x
// GEOS : y
String sweepAxisAngle = GEOSTransform . scanGeomToSweepAngleAxis ( navigation . scan_geom ) ; return new Geostationary ( navigation . sub_lon_degrees , sweepAxisAngle , geoCoordinateScaleFactor ) ;


signature:
public class NcMLWriter { /** * Writes an NcML element to a string .
 * @ param elem an NcML element .
 * @ return the string that represents the NcML document . */
public String writeToString ( Element elem ) { } }

implementation: try ( StringWriter writer = new StringWriter ( ) ) { writeToWriter ( elem , writer ) ; return writer . toString ( ) ; } catch ( IOException e ) { throw new AssertionError ( "CAN'T HAPPEN: StringWriter.close() is a no-op." , e ) ; }


signature:
public class NcMLWriter { /** * Writes an NcML element to an output file .
 * @ param elem an NcML element .
 * @ param outFile the file to write the NcML document to .
 * @ throws IOException if there ' s any problem writing . */
public void writeToFile ( Element elem , File outFile ) throws IOException { } }

implementation: try ( OutputStream outStream = new BufferedOutputStream ( new FileOutputStream ( outFile , false ) ) ) { writeToStream ( elem , outStream ) ; }


signature:
public class NcMLWriter { /** * Writes an NcML element to an output stream .
 * @ param elem an NcML element .
 * @ param outStream the stream to write the NcML document to . Will be closed at end of the method .
 * @ throws IOException if there ' s any problem writing . */
public void writeToStream ( Element elem , OutputStream outStream ) throws IOException { } }

implementation: try ( Writer writer = new BufferedWriter ( new OutputStreamWriter ( new BufferedOutputStream ( outStream ) , xmlFormat . getEncoding ( ) ) ) ) { writeToWriter ( elem , writer ) ; }


signature:
public class NcMLWriter { /** * Writes an NcML element to a Writer .
 * @ param elem an NcML element .
 * @ param writer the Writer to write the NcML document to . Will be closed at end of the method .
 * @ throws IOException if there ' s any problem writing . */
public void writeToWriter ( Element elem , Writer writer ) throws IOException { } }

implementation:
xmlOutputter . setFormat ( xmlFormat ) ; elem . detach ( ) ; // In case this element had previously been added to a Document .
xmlOutputter . output ( new Document ( elem ) , writer ) ;


signature:
public class NcMLWriter { /** * / / / / / Element creation / / / / / */
public Element makeExplicitNetcdfElement ( NetcdfFile ncFile , String location ) { } }

implementation: Element netcdfElem = makeNetcdfElement ( ncFile , location ) ; netcdfElem . addContent ( 0 , new Element ( "explicit" , namespace ) ) ; return netcdfElem ;


signature:
public class NcMLWriter { /** * enum Typedef */
public Element makeEnumTypedefElement ( EnumTypedef etd ) { } }

implementation:
Element typeElem = new Element ( "enumTypedef" , namespace ) ; typeElem . setAttribute ( "name" , etd . getShortName ( ) ) ; typeElem . setAttribute ( "type" , etd . getBaseType ( ) . toString ( ) ) ; // Use a TreeMap so that the key - value pairs are emitted in a consistent order .
TreeMap < Integer , String > map = new TreeMap < > ( etd . getMap ( ) ) ; for ( Map . Entry < Integer , String > entry : map . entrySet ( ) ) { typeElem . addContent ( new Element ( "enum" , namespace ) . setAttribute ( "key" , Integer . toString ( entry . getKey ( ) ) ) . addContent ( entry . getValue ( ) ) ) ; } return typeElem ;


signature:
public class NcMLWriter { /** * Only for shared dimensions . */
public Element makeDimensionElement ( Dimension dim ) throws IllegalArgumentException { } }

implementation: if ( ! dim . isShared ( ) ) { throw new IllegalArgumentException ( "Cannot create private dimension: " + "in NcML, <dimension> elements are always shared." ) ; } Element dimElem = new Element ( "dimension" , namespace ) ; dimElem . setAttribute ( "name" , dim . getShortName ( ) ) ; dimElem . setAttribute ( "length" , Integer . toString ( dim . getLength ( ) ) ) ; if ( dim . isUnlimited ( ) ) dimElem . setAttribute ( "isUnlimited" , "true" ) ; return dimElem ;


signature:
public class NcMLWriter { /** * Creates a { @ code < values > } element from the variable ' s data .
 * @ param variable the variable to read values from
 * @ param allowRegular { @ code true } if regular values should be represented with { @ code start } , { @ code increment } ,
 * and { @ code npts } attributes instead of space - separated Element text . Has no effect if the data isn ' t regular .
 * @ return the { @ code < values > } element .
 * @ throws IOException if there was an I / O error when reading the variable ' s data . */
public Element makeValuesElement ( Variable variable , boolean allowRegular ) throws IOException { } }

implementation:
Element elem = new Element ( "values" , namespace ) ; StringBuilder buff = new StringBuilder ( ) ; Array a = variable . read ( ) ; if ( variable . getDataType ( ) == DataType . CHAR ) { char [ ] data = ( char [ ] ) a . getStorage ( ) ; elem . setText ( new String ( data ) ) ; } else if ( variable . getDataType ( ) == DataType . STRING ) { elem . setAttribute ( "separator" , "|" ) ; int count = 0 ; for ( IndexIterator iter = a . getIndexIterator ( ) ; iter . hasNext ( ) ; ) { if ( count ++ > 0 ) { buff . append ( "|" ) ; } buff . append ( iter . getObjectNext ( ) ) ; } elem . setText ( buff . toString ( ) ) ; } else { // check to see if regular
if ( allowRegular && ( a . getRank ( ) == 1 ) && ( a . getSize ( ) > 2 ) ) { Index ima = a . getIndex ( ) ; double start = a . getDouble ( ima . set ( 0 ) ) ; double incr = a . getDouble ( ima . set ( 1 ) ) - start ; boolean isRegular = true ; for ( int i = 2 ; i < a . getSize ( ) ; i ++ ) { double v1 = a . getDouble ( ima . set ( i ) ) ; double v0 = a . getDouble ( ima . set ( i - 1 ) ) ; if ( ! ucar . nc2 . util . Misc . nearlyEquals ( v1 - v0 , incr ) ) isRegular = false ; } if ( isRegular ) { elem . setAttribute ( "start" , Double . toString ( start ) ) ; elem . setAttribute ( "increment" , Double . toString ( incr ) ) ; elem . setAttribute ( "npts" , Long . toString ( variable . getSize ( ) ) ) ; return elem ; } } // not regular
boolean isRealType = ( variable . getDataType ( ) == DataType . DOUBLE ) || ( variable . getDataType ( ) == DataType . FLOAT ) ; IndexIterator iter = a . getIndexIterator ( ) ; buff . append ( isRealType ? iter . getDoubleNext ( ) : iter . getIntNext ( ) ) ; while ( iter . hasNext ( ) ) { buff . append ( " " ) ; buff . append ( isRealType ? iter . getDoubleNext ( ) : iter . getIntNext ( ) ) ; } elem . setText ( buff . toString ( ) ) ; } // not string
return elem ;


signature:
public class NcMeasureType { /** * wml2 : MeasurementTVP / wml2 : value */
public static MeasureType initValue ( MeasureType value , PointFeature pointFeat , VariableSimpleIF dataVar ) throws IOException { } }

implementation:
// TEXT
StructureMembers . Member firstDataMember = pointFeat . getDataAll ( ) . findMember ( dataVar . getShortName ( ) ) ; assert firstDataMember != null : String . format ( "%s appeared in the list of data variables but not in the StructureData." , dataVar . getShortName ( ) ) ; Array dataArray = pointFeat . getDataAll ( ) . getArray ( firstDataMember ) ; assert dataArray . getSize ( ) == 1 : String . format ( "Expected array to be scalar, but its shape was %s." , Arrays . toString ( dataArray . getShape ( ) ) ) ; double dataVal = dataArray . getDouble ( 0 ) ; value . setDoubleValue ( dataVal ) ; return value ;


signature:
public class McIDASAreaTransformBuilder { /** * Make the coordinate transform
 * @ param ctv the coordinate transform variable
 * @ return the coordinate transform */
public ProjectionCT makeCoordinateTransform ( AttributeContainer ctv , String units ) { } }

implementation:
int [ ] area = getIntArray ( ctv , McIDASAreaProjection . ATTR_AREADIR ) ; int [ ] nav = getIntArray ( ctv , McIDASAreaProjection . ATTR_NAVBLOCK ) ; int [ ] aux = null ; if ( ctv . findAttributeIgnoreCase ( McIDASAreaProjection . ATTR_AUXBLOCK ) != null ) { aux = getIntArray ( ctv , McIDASAreaProjection . ATTR_AUXBLOCK ) ; } // not clear if its ok if aux is null , coverity is complaining
McIDASAreaProjection proj = new McIDASAreaProjection ( area , nav , aux ) ; return new ProjectionCT ( ctv . getName ( ) , "FGDC" , proj ) ;


signature:
public class McIDASAreaTransformBuilder { /** * get the int array from the variable attribute
 * @ param ctv coordinate transform variable
 * @ param attName the attribute name
 * @ return the int array */
private int [ ] getIntArray ( AttributeContainer ctv , String attName ) { } }

implementation: Attribute att = ctv . findAttribute ( attName ) ; if ( att == null ) { throw new IllegalArgumentException ( "McIDASArea coordTransformVariable " + ctv . getName ( ) + " must have " + attName + " attribute" ) ; } Array arr = att . getValues ( ) ; return ( int [ ] ) arr . get1DJavaArray ( int . class ) ;


signature:
public class NcepLocalTables { /** * Vert */
@ Override public VertCoordType getVertUnit ( int code ) { } }

implementation:
switch ( code ) { case 235 : return new VertCoordType ( code , "0.1 C" , null , true ) ; case 237 : return new VertCoordType ( code , "m" , null , true ) ; case 238 : return new VertCoordType ( code , "m" , null , true ) ; case 241 : return new VertCoordType ( code , "count" , null , true ) ; // eg see NCEP World Watch datasets
default : return super . getVertUnit ( code ) ; }


signature:
public class NcepLocalTables { /** * shared by all instances */
@ Override @ Nullable public String getStatisticName ( int id ) { } }

implementation: if ( id < 192 ) return super . getStatisticName ( id ) ; if ( statName == null ) statName = initTable410 ( ) ; if ( statName == null ) return null ; return statName . get ( id ) ;


signature:
public class NcepLocalTables { /** * shared by all instances */
@ Override @ Nullable public String getGeneratingProcessName ( int genProcess ) { } }

implementation: if ( genProcessMap == null ) genProcessMap = NcepTables . getNcepGenProcess ( ) ; if ( genProcessMap == null ) return null ; return genProcessMap . get ( genProcess ) ;


signature:
public class NcepLocalTables { /** * see http : / / www . nco . ncep . noaa . gov / pmb / docs / grib2 / grib2 _ doc . shtml */
private Map < String , String > initCodes ( ) { } }

implementation: codeMap . put ( "3.1.204" , "Curvilinear_Orthogonal" ) ; codeMap . put ( "4.3.192" , "Forecast Confidence Indicator" ) ; codeMap . put ( "4.3.193" , "Bias Corrected Ensemble Forecast" ) ; codeMap . put ( "4.5.200" , "Entire atmosphere layer" ) ; codeMap . put ( "4.5.201" , "Entire ocean layer" ) ; codeMap . put ( "4.5.204" , "Highest tropospheric freezing level" ) ; codeMap . put ( "4.5.206" , "Grid scale cloud bottom level" ) ; codeMap . put ( "4.5.207" , "Grid scale cloud top level" ) ; codeMap . put ( "4.5.209" , "Boundary layer cloud bottom level" ) ; codeMap . put ( "4.5.210" , "Boundary layer cloud top level" ) ; codeMap . put ( "4.5.211" , "Boundary layer cloud layer" ) ; codeMap . put ( "4.5.212" , "Low cloud bottom level" ) ; codeMap . put ( "4.5.213" , "Low cloud top level" ) ; codeMap . put ( "4.5.214" , "Low cloud layer" ) ; codeMap . put ( "4.5.215" , "Cloud ceiling" ) ; codeMap . put ( "4.5.220" , "Planetary Boundary Layer" ) ; codeMap . put ( "4.5.221" , "Layer Between Two Hybrid Levels" ) ; codeMap . put ( "4.5.222" , "Middle cloud bottom level" ) ; codeMap . put ( "4.5.223" , "Middle cloud top level" ) ; codeMap . put ( "4.5.224" , "Middle cloud layer" ) ; codeMap . put ( "4.5.232" , "High cloud bottom level" ) ; codeMap . put ( "4.5.233" , "High cloud top level" ) ; codeMap . put ( "4.5.234" , "High cloud layer" ) ; codeMap . put ( "4.5.235" , "Ocean isotherm level" ) ; codeMap . put ( "4.5.236" , "Layer between two depths below ocean surface" ) ; codeMap . put ( "4.5.237" , "Bottom of ocean mixed layer" ) ; codeMap . put ( "4.5.238" , "Bottom of ocean isothermal layer" ) ; codeMap . put ( "4.5.239" , "Layer Ocean Surface and 26C Ocean Isothermal Level" ) ; codeMap . put ( "4.5.240" , "Ocean Mixed Layer" ) ; codeMap . put ( "4.5.241" , "Ordered Sequence of Data" ) ; codeMap . put ( "4.5.242" , "Convective cloud bottom level" ) ; codeMap . put ( "4.5.243" , "Convective cloud top level" ) ; codeMap . put ( "4.5.244" , "Convective cloud layer" ) ; codeMap . put ( "4.5.245" , "Lowest level of the wet bulb zero" ) ; codeMap . put ( "4.5.246" , "Maximum equivalent potential temperature level" ) ; codeMap . put ( "4.5.247" , "Equilibrium level" ) ; codeMap . put ( "4.5.248" , "Shallow convective cloud bottom level" ) ; codeMap . put ( "4.5.249" , "Shallow convective cloud top level" ) ; codeMap . put ( "4.5.251" , "Deep convective cloud bottom level" ) ; codeMap . put ( "4.5.252" , "Deep convective cloud top level" ) ; codeMap . put ( "4.5.253" , "Lowest bottom level of supercooled liquid water layer" ) ; codeMap . put ( "4.5.254" , "Highest top level of supercooled liquid water layer" ) ; codeMap . put ( "4.6.192" , "Perturbed Ensemble Member" ) ; codeMap . put ( "4.7.192" , "Unweighted Mode of All Members" ) ; codeMap . put ( "4.7.193" , "Percentile value (10%) of All Members" ) ; codeMap . put ( "4.7.194" , "Percentile value (50%) of All Members" ) ; codeMap . put ( "4.7.195" , "Percentile value (90%) of All Members" ) ; codeMap . put ( "4.10.192" , "Climatological Mean Value" ) ; codeMap . put ( "4.10.193" , "Average of N forecasts" ) ; codeMap . put ( "4.10.194" , "Average of N uninitialized analyses" ) ; codeMap . put ( "4.10.195" , "Average of forecast accumulations" ) ; codeMap . put ( "4.10.196" , "Average of successive forecast accumulations" ) ; codeMap . put ( "4.10.197" , "Average of forecast averages" ) ; codeMap . put ( "4.10.198" , "Average of successive forecast averages" ) ; codeMap . put ( "4.10.199" , "Climatological Average of N analyses, each a year apart" ) ; codeMap . put ( "4.10.200" , "Climatological Average of N forecasts, each a year apart" ) ; codeMap . put ( "4.10.201" , "Climatological Root Mean Square difference between N forecasts and their verifying analyses, each a year apart" ) ; codeMap . put ( "4.10.202" , "Climatological Standard Deviation of N forecasts from the mean of the same N forecasts, for forecasts one year apart" ) ; codeMap . put ( "4.10.203" , "Climatological Standard Deviation of N analyses from the mean of the same N analyses, for analyses one year apart" ) ; codeMap . put ( "4.10.204" , "Average of forecast accumulations" ) ; codeMap . put ( "4.10.205" , "Average of forecast averages" ) ; codeMap . put ( "4.10.206" , "Average of forecast accumulations" ) ; codeMap . put ( "4.10.207" , "Average of forecast averages" ) ; return codeMap ;


signature:
public class CatGenAndWrite { /** * Need a few test cases :
 * 1 ) Anne ' s TDR case - catalog a collection of TDS served data .
 * 2 ) Catalog a collection of local data files .
 * @ param args */
public static void main1 ( String [ ] args ) { } }

implementation:
// Test case 2 : local data files .
String collectionPath = "C:/Ethan/data/mlode" ; String startPath = "grid/NCEP" ; String catWriteDirPath = "C:/Ethan/data/tmpTest" ; if ( args . length == 3 ) { collectionPath = args [ 0 ] ; startPath = args [ 1 ] ; catWriteDirPath = args [ 2 ] ; } File catWriteDir = new File ( catWriteDirPath ) ; File collectionFile = new File ( collectionPath ) ; CrawlableDataset collectionCrDs = new CrawlableDatasetFile ( collectionFile ) ; InvService service = new InvService ( "myServer" , "File" , collectionCrDs . getPath ( ) + "/" , null , null ) ; CrawlableDatasetFilter filter = null ; CrawlableDataset topCatCrDs = collectionCrDs . getDescendant ( startPath ) ; CatGenAndWrite cgaw = new CatGenAndWrite ( "DATA" , "My data" , "" , service , collectionCrDs , topCatCrDs , filter , null , catWriteDir ) ; try { cgaw . genCatAndSubCats ( topCatCrDs ) ; } catch ( IOException e ) { log . error ( "I/O error generating and writing catalogs at and under \"" + topCatCrDs . getPath ( ) + "\": " + e . getMessage ( ) ) ; return ; }


signature:
public class SI { /** * Factory method for constructing a base unit .
 * @ param name The name of the unit .
 * @ param symbol The symbol for the unit .
 * @ param quantity The base quantity of the unit .
 * @ return The base unit corresponding to the arguments . */
private static BaseUnit bu ( final String name , final String symbol , final BaseQuantity quantity ) throws NameException , UnitExistsException { } }

implementation: return BaseUnit . getOrCreate ( UnitName . newUnitName ( name , null , symbol ) , quantity ) ;


signature:
public class SI { /** * Factory method for constructing a derived unit .
 * @ param name The name of the unit .
 * @ param symbol The symbol for the unit .
 * @ param definition The definition of the unit .
 * @ return The derived unit corresponding to the arguments . */
private static Unit du ( final String name , final String symbol , final Unit definition ) throws NameException { } }

implementation: return definition . clone ( UnitName . newUnitName ( name , null , symbol ) ) ;


signature:
public class SI { /** * Returns the base unit database of the SI .
 * @ return The base unit database of the SI .
 * @ throws NameException Bad unit name .
 * @ throws UnitExistsException Attempt to redefine an existing unit .
 * @ throws NoSuchUnitException Necessary unit not found . */
private static UnitDBImpl baseUnitDB ( ) throws NameException , UnitExistsException , NoSuchUnitException { } }

implementation: final UnitDBImpl db = new UnitDBImpl ( 9 , 9 ) ; db . addUnit ( AMPERE ) ; db . addUnit ( CANDELA ) ; db . addUnit ( KELVIN ) ; db . addUnit ( KILOGRAM ) ; db . addUnit ( METER ) ; db . addUnit ( MOLE ) ; db . addUnit ( SECOND ) ; db . addUnit ( RADIAN ) ; db . addUnit ( STERADIAN ) ; db . addAlias ( "metre" , "meter" ) ; return db ;


signature:
public class SI { /** * Returns the derived unit database of the SI .
 * @ return The derived unit database of the SI .
 * @ throws NameException Bad unit name .
 * @ throws UnitExistsException Attempt to redefine an existing unit .
 * @ throws NoSuchUnitException Necessary unit not found . */
private static UnitDBImpl derivedUnitDB ( ) throws NameException , UnitExistsException , NoSuchUnitException { } }

implementation: final UnitDBImpl db = new UnitDBImpl ( 42 , 43 ) ; db . addUnit ( HERTZ ) ; db . addUnit ( NEWTON ) ; db . addUnit ( PASCAL ) ; db . addUnit ( JOULE ) ; db . addUnit ( WATT ) ; db . addUnit ( COULOMB ) ; db . addUnit ( VOLT ) ; db . addUnit ( FARAD ) ; db . addUnit ( OHM ) ; db . addUnit ( SIEMENS ) ; db . addUnit ( WEBER ) ; db . addUnit ( TESLA ) ; db . addUnit ( HENRY ) ; db . addUnit ( DEGREE_CELSIUS ) ; db . addUnit ( LUMEN ) ; db . addUnit ( LUX ) ; db . addUnit ( BECQUEREL ) ; db . addUnit ( GRAY ) ; db . addUnit ( SIEVERT ) ; db . addUnit ( MINUTE ) ; db . addUnit ( HOUR ) ; db . addUnit ( DAY ) ; db . addUnit ( ARC_DEGREE ) ; db . addUnit ( ARC_MINUTE ) ; db . addUnit ( ARC_SECOND ) ; db . addUnit ( LITER ) ; db . addUnit ( METRIC_TON ) ; db . addUnit ( NAUTICAL_MILE ) ; db . addUnit ( KNOT ) ; db . addUnit ( ANGSTROM ) ; db . addUnit ( ARE ) ; db . addUnit ( HECTARE ) ; db . addUnit ( BARN ) ; db . addUnit ( BAR ) ; db . addUnit ( GAL ) ; db . addUnit ( CURIE ) ; db . addUnit ( ROENTGEN ) ; db . addUnit ( RAD ) ; db . addUnit ( REM ) ; db . addAlias ( "litre" , "liter" , "l" ) ; db . addAlias ( "tonne" , "metric ton" ) ; db . addSymbol ( "tne" , "tonne" ) ; return db ;


signature:
public class SI { /** * Returns an instance of the SI system of units .
 * @ return An instance of the SI system of units .
 * @ throws UnitSystemException Couldn ' t create an instance of the SI system of units . */
public static synchronized SI instance ( ) throws UnitSystemException { } }

implementation: if ( si == null ) { try { si = new SI ( ) ; } catch ( final UnitException e ) { throw new UnitSystemException ( "Couldn't initialize class SI" , e ) ; } } return si ;


signature:
public class InvDatasetFcFmrc { /** * / * @ Override / / overriding superclass - WHY ?
 * public void update ( CollectionUpdateType force ) {
 * fmrc . update ( ) ; / / so when is work done ? */
protected void update ( CollectionUpdateType force ) throws IOException { } }

implementation:
// this may be called from a background thread , or from checkState ( ) request thread
logger . debug ( "update {} force={}" , name , force ) ; boolean changed ; MFileCollectionManager dcm ; switch ( force ) { case always : case test : dcm = ( MFileCollectionManager ) getDatasetCollectionManager ( ) ; changed = dcm . scan ( false ) ; if ( changed ) super . update ( force ) ; break ; case never : return ; default : super . update ( force ) ; }


signature:
public class InvDatasetFcFmrc { /** * called by DataRootHandler . makeDynamicCatalog ( ) when the catref is requested */
@ Override public CatalogBuilder makeCatalog ( String match , String orgPath , URI catURI ) throws IOException { } }

implementation: logger . debug ( "FMRC make catalog for " + match + " " + catURI ) ; State localState = checkState ( ) ; try { if ( ( match == null ) || ( match . length ( ) == 0 ) ) { return makeCatalogTop ( catURI , localState ) ; } else if ( match . equals ( RUNS ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Runs ) ) return makeCatalogRuns ( catURI , localState ) ; else if ( match . equals ( OFFSET ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantOffsets ) ) return makeCatalogOffsets ( catURI , localState ) ; else if ( match . equals ( FORECAST ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantForecasts ) ) return makeCatalogForecasts ( catURI , localState ) ; else if ( match . startsWith ( FILES ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Files ) ) { return makeCatalogFiles ( catURI , localState , datasetCollection . getFilenames ( ) , true ) ; } } catch ( Exception e ) { logger . error ( "Error making catalog for " + configPath , e ) ; } return null ;


signature: public class InvDatasetFcFmrc { @ Override protected DatasetBuilder makeDatasetTop ( URI catURI , State localState ) { } }

implementation:
DatasetBuilder top = new DatasetBuilder ( null ) ; top . transferInheritedMetadata ( parent ) ; // make all inherited metadata local
top . setName ( name ) ; top . addServiceToCatalog ( virtualService ) ; ThreddsMetadata tmi = top . getInheritableMetadata ( ) ; // LOOK allow to change ? ?
tmi . set ( Dataset . FeatureType , FeatureType . GRID . toString ( ) ) ; // override GRIB
tmi . set ( Dataset . ServiceName , virtualService . getName ( ) ) ; if ( localState . coverage != null ) tmi . set ( Dataset . GeospatialCoverage , localState . coverage ) ; if ( localState . dateRange != null ) tmi . set ( Dataset . TimeCoverage , localState . dateRange ) ; if ( localState . vars != null ) tmi . set ( Dataset . VariableGroups , localState . vars ) ; if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . TwoD ) ) { DatasetBuilder twoD = new DatasetBuilder ( top ) ; twoD . setName ( "Forecast Model Run Collection (2D time coordinates)" ) ; String myname = name + "_" + FMRC ; myname = StringUtil2 . replace ( myname , ' ' , "_" ) ; twoD . put ( Dataset . UrlPath , this . configPath + "/" + myname ) ; twoD . put ( Dataset . Id , this . configPath + "/" + myname ) ; twoD . addToList ( Dataset . Documentation , new Documentation ( null , null , null , "summary" , "Forecast Model Run Collection (2D time coordinates)." ) ) ; top . addDataset ( twoD ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Best ) ) { DatasetBuilder best = new DatasetBuilder ( top ) ; best . setName ( "Best Time Series" ) ; String myname = name + "_" + BEST ; myname = StringUtil2 . replace ( myname , ' ' , "_" ) ; best . put ( Dataset . UrlPath , this . configPath + "/" + myname ) ; best . put ( Dataset . Id , this . configPath + "/" + myname ) ; best . addToList ( Dataset . Documentation , new Documentation ( null , null , null , "summary" , "Best time series, taking the data from the most recent run available." ) ) ; top . addDataset ( best ) ; } if ( config . fmrcConfig . getBestDatasets ( ) != null ) { for ( FeatureCollectionConfig . BestDataset bd : config . fmrcConfig . getBestDatasets ( ) ) { DatasetBuilder ds = new DatasetBuilder ( top ) ; ds . setName ( bd . name ) ; String myname = name + "_" + bd . name ; myname = StringUtil2 . replace ( myname , ' ' , "_" ) ; ds . put ( Dataset . UrlPath , this . configPath + "/" + myname ) ; ds . put ( Dataset . Id , this . configPath + "/" + myname ) ; ds . addToList ( Dataset . Documentation , new Documentation ( null , null , null , "summary" , "Best time series, excluding offset hours less than " + bd . greaterThan ) ) ; top . addDataset ( ds ) ; } } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Runs ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( RUN_TITLE ) ; ds . setHref ( getCatalogHref ( RUNS ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantForecasts ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( FORECAST_TITLE ) ; ds . setHref ( getCatalogHref ( FORECAST ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantOffsets ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( OFFSET_TITLE ) ; ds . setHref ( getCatalogHref ( OFFSET ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Files ) && ( topDirectory != null ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( FILES ) ; ds . setHref ( getCatalogHref ( FILES ) ) ; top . addDataset ( ds ) ; } return top ;


signature:
public class CoordAxisHelper { /** * Given a coordinate interval , find what grid element matches it .
 * @ param target interval in this coordinate system
 * @ param bounded if true , always return a valid index . otherwise can return < 0 or > n - 1
 * @ return index of grid point containing it , or < 0 or > n - 1 if outside grid area */
int findCoordElement ( double [ ] target , boolean bounded ) { } }

implementation:
switch ( axis . getSpacing ( ) ) { case regularInterval : // can use midpoint
return findCoordElementRegular ( ( target [ 0 ] + target [ 1 ] ) / 2 , bounded ) ; case contiguousInterval : // can use midpoint
return findCoordElementContiguous ( ( target [ 0 ] + target [ 1 ] ) / 2 , bounded ) ; case discontiguousInterval : // cant use midpoint
return findCoordElementDiscontiguousInterval ( target , bounded ) ; } throw new IllegalStateException ( "unknown spacing" + axis . getSpacing ( ) ) ;


signature:
public class CoordAxisHelper { /** * same contract as findCoordElement ( ) */
private int findCoordElementRegular ( double coordValue , boolean bounded ) { } }

implementation:
int n = axis . getNcoords ( ) ; if ( n == 1 && bounded ) return 0 ; double distance = coordValue - axis . getCoordEdge1 ( 0 ) ; double exactNumSteps = distance / axis . getResolution ( ) ; // int index = ( int ) Math . round ( exactNumSteps ) ; / / ties round to + Inf
int index = ( int ) exactNumSteps ; // truncate down
if ( bounded && index < 0 ) return 0 ; if ( bounded && index >= n ) return n - 1 ; // check that found point is within interval
if ( index >= 0 && index < n ) { double lower = axis . getCoordEdge1 ( index ) ; double upper = axis . getCoordEdge2 ( index ) ; if ( axis . isAscending ( ) ) { assert lower <= coordValue : lower + " should be le " + coordValue ; assert upper >= coordValue : upper + " should be ge " + coordValue ; } else { assert lower >= coordValue : lower + " should be ge " + coordValue ; assert upper <= coordValue : upper + " should be le " + coordValue ; } } return index ;


signature:
public class CoordAxisHelper { /** * Performs a binary search to find the index of the element of the array whose value is contained in the contiguous intervals .
 * irregularPoint , / / irregular spaced points ( values , npts ) , edges halfway between coords
 * contiguousInterval , / / irregular contiguous spaced intervals ( values , npts ) , values are the edges , and there are npts + 1 , coord halfway between edges
 * same contract as findCoordElement ( ) */
private int findCoordElementContiguous ( double target , boolean bounded ) { } }

implementation:
int n = axis . getNcoords ( ) ; // double resolution = ( values [ n - 1 ] - values [ 0 ] ) / ( n - 1 ) ;
// int startGuess = ( int ) Math . round ( ( target - values [ 0 ] ) / resolution ) ;
int low = 0 ; int high = n - 1 ; if ( axis . isAscending ( ) ) { // Check that the point is within range
if ( target < axis . getCoordEdge1 ( 0 ) ) return bounded ? 0 : - 1 ; else if ( target > axis . getCoordEdgeLast ( ) ) return bounded ? n - 1 : n ; // do a binary search to find the nearest index
int mid ; while ( high > low + 1 ) { mid = ( low + high ) / 2 ; // binary search
if ( contains ( target , mid , true ) ) return mid ; else if ( axis . getCoordEdge2 ( mid ) < target ) low = mid ; else high = mid ; } return contains ( target , low , true ) ? low : high ; } else { // descending
// Check that the point is within range
if ( target > axis . getCoordEdge1 ( 0 ) ) return bounded ? 0 : - 1 ; else if ( target < axis . getCoordEdgeLast ( ) ) return bounded ? n - 1 : n ; // do a binary search to find the nearest index
int mid ; while ( high > low + 1 ) { mid = ( low + high ) / 2 ; // binary search
if ( contains ( target , mid , false ) ) return mid ; else if ( axis . getCoordEdge2 ( mid ) < target ) high = mid ; else low = mid ; } return contains ( target , low , false ) ? low : high ; }


signature:
public class CoordAxisHelper { /** * LOOK not using bounded */
private int findCoordElementDiscontiguousInterval ( double target , boolean bounded ) { } }

implementation:
int idx = findSingleHit ( target ) ; if ( idx >= 0 ) return idx ; if ( idx == - 1 ) return - 1 ; // no hits
// multiple hits = choose closest to the midpoint
return findClosest ( target ) ;


signature:
public class CoordAxisHelper { /** * LOOK not using bounded */
private int findCoordElementDiscontiguousInterval ( double [ ] target , boolean bounded ) { } }

implementation: for ( int i = 0 ; i < axis . getNcoords ( ) ; i ++ ) { double edge1 = axis . getCoordEdge1 ( i ) ; double edge2 = axis . getCoordEdge2 ( i ) ; if ( Misc . nearlyEquals ( edge1 , target [ 0 ] ) && Misc . nearlyEquals ( edge2 , target [ 1 ] ) ) return i ; } return - 1 ;


signature:
public class CoordAxisHelper { /** * return index if only one match , if no matches return - 1 , if > 1 match return - nhits */
private int findSingleHit ( double target ) { } }

implementation: int hits = 0 ; int idxFound = - 1 ; int n = axis . getNcoords ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( contains ( target , i ) ) { hits ++ ; idxFound = i ; } } if ( hits == 1 ) return idxFound ; if ( hits == 0 ) return - 1 ; return - hits ;


signature:
public class CoordAxisHelper { /** * if its a tie , use the larger one */
private int findClosest ( double target ) { } }

implementation: double minDiff = Double . MAX_VALUE ; double useValue = Double . MIN_VALUE ; int idxFound = - 1 ; for ( int i = 0 ; i < axis . getNcoords ( ) ; i ++ ) { double coord = axis . getCoordMidpoint ( i ) ; double diff = Math . abs ( coord - target ) ; if ( diff < minDiff || ( diff == minDiff && coord > useValue ) ) { minDiff = diff ; idxFound = i ; useValue = coord ; } } return idxFound ;


signature: public class CoordAxisHelper { public Optional < CoverageCoordAxisBuilder > subset ( double minValue , double maxValue , int stride ) { } }

implementation: return subsetValues ( minValue , maxValue , stride ) ;


signature:
public class CoordAxisHelper { /** * look must handle discon interval different */
private Optional < CoverageCoordAxisBuilder > subsetValues ( double minValue , double maxValue , int stride ) { } }

implementation: if ( axis . getSpacing ( ) == CoverageCoordAxis . Spacing . discontiguousInterval ) return subsetValuesDiscontinuous ( minValue , maxValue , stride ) ; double lower = axis . isAscending ( ) ? Math . min ( minValue , maxValue ) : Math . max ( minValue , maxValue ) ; double upper = axis . isAscending ( ) ? Math . max ( minValue , maxValue ) : Math . min ( minValue , maxValue ) ; int minIndex = findCoordElement ( lower , false ) ; int maxIndex = findCoordElement ( upper , false ) ; if ( minIndex >= axis . getNcoords ( ) ) return Optional . empty ( String . format ( "no points in subset: lower %f > end %f" , lower , axis . getEndValue ( ) ) ) ; if ( maxIndex < 0 ) return Optional . empty ( String . format ( "no points in subset: upper %f < start %f" , upper , axis . getStartValue ( ) ) ) ; if ( minIndex < 0 ) minIndex = 0 ; if ( maxIndex >= axis . getNcoords ( ) ) maxIndex = axis . getNcoords ( ) - 1 ; int count = maxIndex - minIndex + 1 ; if ( count <= 0 ) throw new IllegalArgumentException ( "no points in subset" ) ; try { return Optional . of ( subsetByIndex ( new Range ( minIndex , maxIndex , stride ) ) ) ; } catch ( InvalidRangeException e ) { return Optional . empty ( e . getMessage ( ) ) ; }


signature:
public class CoordAxisHelper { /** * Range must be contained in this range */
@ Nonnull CoverageCoordAxisBuilder subsetByIndex ( Range range ) throws InvalidRangeException { } }

implementation:
int ncoords = range . length ( ) ; if ( range . last ( ) >= axis . getNcoords ( ) ) throw new InvalidRangeException ( "range.last() >= axis.getNcoords()" ) ; double resolution = 0.0 ; int count2 = 0 ; double [ ] values = axis . getValues ( ) ; // will be null for regular
double [ ] subsetValues = null ; switch ( axis . getSpacing ( ) ) { case regularInterval : case regularPoint : resolution = range . stride ( ) * axis . getResolution ( ) ; break ; case irregularPoint : subsetValues = new double [ ncoords ] ; for ( int i : range ) subsetValues [ count2 ++ ] = values [ i ] ; break ; case contiguousInterval : subsetValues = new double [ ncoords + 1 ] ; // need npts + 1
for ( int i : range ) subsetValues [ count2 ++ ] = values [ i ] ; subsetValues [ count2 ] = values [ range . last ( ) + 1 ] ; break ; case discontiguousInterval : subsetValues = new double [ 2 * ncoords ] ; // need 2 * npts
for ( int i : range ) { subsetValues [ count2 ++ ] = values [ 2 * i ] ; subsetValues [ count2 ++ ] = values [ 2 * i + 1 ] ; } break ; } // subset ( int ncoords , double start , double end , double [ ] values )
CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder ( axis ) ; builder . subset ( ncoords , axis . getCoordMidpoint ( range . first ( ) ) , axis . getCoordMidpoint ( range . last ( ) ) , resolution , subsetValues ) ; builder . setRange ( range ) ; return builder ;


signature:
public class TdsInit { /** * http : / / stackoverflow . com / questions / 24660408 / how - can - i - get - intellij - debugger - to - allow - my - apps - shutdown - hooks - to - run ? lq = 1
 * " Unfortunately , you can ' t use breakpoints in your shutdown hook body when you use Stop button : these breakpoints are silently ignored . " */
@ Override public void destroy ( ) { } }

implementation:
System . out . printf ( "TdsInit.destroy() is called%n" ) ; // prefs
try { store . save ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; startupLog . error ( "TdsInit: Prefs save failed" , ioe ) ; } // background threads
if ( cdmDiskCacheTimer != null ) cdmDiskCacheTimer . cancel ( ) ; FileCache . shutdown ( ) ; // this handles background threads for all instances of FileCache
DiskCache2 . exit ( ) ; // this handles background threads for all instances of DiskCache2
thredds . inventory . bdb . MetadataManager . closeAll ( ) ; executor . shutdownNow ( ) ; /* try {
 catalogWatcher . close ( ) ;
 } catch ( IOException ioe ) {
 ioe . printStackTrace ( ) ;
 startupLog . error ( " catalogWatcher close failed " , ioe ) ; */
// open file caches
RandomAccessFile . shutdown ( ) ; NetcdfDataset . shutdown ( ) ; // memory caches
GribCdmIndex . shutdown ( ) ; datasetManager . setDatasetTracker ( null ) ; // closes the existing tracker
collectionUpdater . shutdown ( ) ; startupLog . info ( "TdsInit shutdown" ) ; MDC . clear ( ) ;