idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
17,100
public static GridCoverage2D mergeCoverages ( GridCoverage2D valuesMap , GridCoverage2D onMap ) { RegionMap valuesRegionMap = getRegionParamsFromGridCoverage ( valuesMap ) ; int cs = valuesRegionMap . getCols ( ) ; int rs = valuesRegionMap . getRows ( ) ; RegionMap onRegionMap = getRegionParamsFromGridCoverage ( onMap ) ; int tmpcs = onRegionMap . getCols ( ) ; int tmprs = onRegionMap . getRows ( ) ; if ( cs != tmpcs || rs != tmprs ) { throw new IllegalArgumentException ( "The raster maps have to be of equal size to be mapped." ) ; } RandomIter valuesIter = RandomIterFactory . create ( valuesMap . getRenderedImage ( ) , null ) ; WritableRaster outWR = renderedImage2WritableRaster ( onMap . getRenderedImage ( ) , false ) ; WritableRandomIter outIter = RandomIterFactory . createWritable ( outWR , null ) ; for ( int c = 0 ; c < cs ; c ++ ) { for ( int r = 0 ; r < rs ; r ++ ) { double value = valuesIter . getSampleDouble ( c , r , 0 ) ; if ( ! isNovalue ( value ) ) outIter . setSample ( c , r , 0 , value ) ; } } GridCoverage2D outCoverage = buildCoverage ( "merged" , outWR , onRegionMap , valuesMap . getCoordinateReferenceSystem ( ) ) ; return outCoverage ; }
Coverage merger .
17,101
public static double [ ] [ ] calculateHypsographic ( GridCoverage2D elevationCoverage , int bins , IHMProgressMonitor pm ) { if ( pm == null ) { pm = new DummyProgressMonitor ( ) ; } RegionMap regionMap = getRegionParamsFromGridCoverage ( elevationCoverage ) ; int cols = regionMap . getCols ( ) ; int rows = regionMap . getRows ( ) ; double xres = regionMap . getXres ( ) ; double yres = regionMap . getYres ( ) ; RandomIter elevIter = getRandomIterator ( elevationCoverage ) ; double maxRasterValue = Double . NEGATIVE_INFINITY ; double minRasterValue = Double . POSITIVE_INFINITY ; for ( int r = 0 ; r < rows ; r ++ ) { for ( int c = 0 ; c < cols ; c ++ ) { double value = elevIter . getSampleDouble ( c , r , 0 ) ; if ( isNovalue ( value ) ) { continue ; } maxRasterValue = max ( maxRasterValue , value ) ; minRasterValue = min ( minRasterValue , value ) ; } } double binWidth = ( maxRasterValue - minRasterValue ) / ( bins ) ; double [ ] pixelPerBinCount = new double [ bins ] ; double [ ] areaAtGreaterElevation = new double [ bins ] ; pm . beginTask ( "Performing calculation of hypsographic curve..." , rows ) ; for ( int r = 0 ; r < rows ; r ++ ) { for ( int c = 0 ; c < cols ; c ++ ) { double value = elevIter . getSampleDouble ( c , r , 0 ) ; if ( isNovalue ( value ) ) { continue ; } for ( int k = 0 ; k < pixelPerBinCount . length ; k ++ ) { double thres = minRasterValue + k * binWidth ; if ( value >= thres ) { pixelPerBinCount [ k ] = pixelPerBinCount [ k ] + 1 ; areaAtGreaterElevation [ k ] = areaAtGreaterElevation [ k ] + ( yres * xres ) ; } } } pm . worked ( 1 ) ; } pm . done ( ) ; double [ ] [ ] hypso = new double [ pixelPerBinCount . length ] [ 3 ] ; for ( int j = 0 ; j < hypso . length ; j ++ ) { hypso [ j ] [ 0 ] = minRasterValue + ( j * binWidth ) + ( binWidth / 2.0 ) ; hypso [ j ] [ 1 ] = areaAtGreaterElevation [ j ] / 1000000.0 ; } return hypso ; }
Calculates the hypsographic curve for the given raster using the supplied bins .
17,102
static public void zipFolder ( String srcFolder , String destZipFile , boolean addBaseFolder ) throws IOException { if ( new File ( srcFolder ) . isDirectory ( ) ) { try ( FileOutputStream fileWriter = new FileOutputStream ( destZipFile ) ; ZipOutputStream zip = new ZipOutputStream ( fileWriter ) ) { addFolderToZip ( "" , srcFolder , zip , addBaseFolder ) ; } } else { throw new IOException ( srcFolder + " is not a folder." ) ; } }
Compress a folder and its contents .
17,103
public static String unzipFolder ( String zipFile , String destFolder , boolean addTimeStamp ) throws IOException { String newFirstName = null ; try ( ZipFile zf = new ZipFile ( zipFile ) ) { Enumeration < ? extends ZipEntry > zipEnum = zf . entries ( ) ; String firstName = null ; while ( zipEnum . hasMoreElements ( ) ) { ZipEntry item = ( ZipEntry ) zipEnum . nextElement ( ) ; String itemName = item . getName ( ) ; if ( firstName == null ) { int firstSlash = itemName . indexOf ( '/' ) ; if ( firstSlash == - 1 ) { firstSlash = itemName . length ( ) ; } firstName = itemName . substring ( 0 , firstSlash ) ; newFirstName = firstName ; File baseFile = new File ( destFolder + File . separator + firstName ) ; if ( baseFile . exists ( ) ) { if ( addTimeStamp ) { newFirstName = firstName + "_" + new DateTime ( ) . toString ( HMConstants . dateTimeFormatterYYYYMMDDHHMMSScompact ) ; } else { throw new IOException ( "Not overwriting existing: " + baseFile ) ; } } } if ( firstName == null ) { throw new IOException ( ) ; } itemName = itemName . replaceFirst ( firstName , newFirstName ) ; if ( item . isDirectory ( ) ) { File newdir = new File ( destFolder + File . separator + itemName ) ; if ( ! newdir . mkdir ( ) ) throw new IOException ( ) ; } else { String newfilePath = destFolder + File . separator + itemName ; File newFile = new File ( newfilePath ) ; File parentFile = newFile . getParentFile ( ) ; if ( ! parentFile . exists ( ) ) { if ( ! parentFile . mkdirs ( ) ) throw new IOException ( ) ; } InputStream is = zf . getInputStream ( item ) ; FileOutputStream fos = new FileOutputStream ( newfilePath ) ; byte [ ] buffer = new byte [ 512 ] ; int readchars = 0 ; while ( ( readchars = is . read ( buffer ) ) != - 1 ) { fos . write ( buffer , 0 , readchars ) ; } is . close ( ) ; fos . close ( ) ; } } } return newFirstName ; }
Uncompress a compressed file to the contained structure .
17,104
public void setWorkingDirectory ( File dir ) { if ( ! dir . exists ( ) ) { throw new IllegalArgumentException ( dir + " doesn't exist." ) ; } pb . directory ( dir ) ; }
Set the working directory where the process get executed .
17,105
public int exec ( ) throws IOException { int exitValue = 0 ; List < String > argl = new ArrayList < String > ( ) ; argl . add ( executable . toString ( ) ) ; for ( Object a : args ) { if ( a != null ) { if ( a . getClass ( ) == String . class ) { argl . add ( a . toString ( ) ) ; } else if ( a . getClass ( ) == String [ ] . class ) { for ( String s : ( String [ ] ) a ) { if ( s != null && ! s . isEmpty ( ) ) { argl . add ( s ) ; } } } } } pb . command ( argl ) ; if ( log != null && log . isLoggable ( Level . INFO ) ) { log . info ( "Command : " + pb . command ( ) . toString ( ) ) ; } Process process = pb . start ( ) ; CountDownLatch latch = new CountDownLatch ( 2 ) ; Thread out_ = new Thread ( new Handler ( new BufferedReader ( new InputStreamReader ( process . getInputStream ( ) ) ) , stdout , latch ) ) ; Thread err_ = new Thread ( new Handler ( new BufferedReader ( new InputStreamReader ( process . getErrorStream ( ) ) ) , stderr , latch ) ) ; out_ . start ( ) ; err_ . start ( ) ; try { latch . await ( ) ; exitValue = process . waitFor ( ) ; } catch ( InterruptedException e ) { } finally { process . getInputStream ( ) . close ( ) ; process . getOutputStream ( ) . close ( ) ; process . getErrorStream ( ) . close ( ) ; process . destroy ( ) ; } return exitValue ; }
Process execution . This call blocks until the process is done .
17,106
private void addResult ( ValidationResult result ) { if ( result == null || result . count ( ) == 0 ) { return ; } this . results . add ( result ) ; }
Adds a validationResult to the results - if there are any messages
17,107
public List < ValidationMessage < Origin > > getMessages ( String messageKey , Severity severity ) { List < ValidationMessage < Origin > > messages = new ArrayList < ValidationMessage < Origin > > ( ) ; for ( ValidationResult result : results ) { for ( ValidationMessage < Origin > message : result . getMessages ( ) ) { if ( messageKey . equals ( message . getMessageKey ( ) ) && severity . equals ( message . getSeverity ( ) ) ) { messages . add ( message ) ; } } } return messages ; }
Finds validation messages by the message key and severity .
17,108
public static byte [ ] serialize ( Object obj ) throws IOException { try ( ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ) { ObjectOutputStream out = new ObjectOutputStream ( bos ) ; out . writeObject ( obj ) ; out . close ( ) ; return bos . toByteArray ( ) ; } }
Serialize an Object to disk .
17,109
public static < T > T deSerialize ( byte [ ] bytes , Class < T > adaptee ) throws Exception { ObjectInputStream in = new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; Object readObject = in . readObject ( ) ; return adaptee . cast ( readObject ) ; }
Deserialize a byte array to a given object .
17,110
public static void serializeToDisk ( File file , Object obj ) throws IOException { byte [ ] serializedObj = serialize ( obj ) ; try ( RandomAccessFile raFile = new RandomAccessFile ( file , "rw" ) ) { raFile . write ( serializedObj ) ; } }
Serialize an object to disk .
17,111
public static < T > T deSerializeFromDisk ( File file , Class < T > adaptee ) throws Exception { try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { long length = raf . length ( ) ; byte [ ] bytes = new byte [ ( int ) length ] ; int read = raf . read ( bytes ) ; if ( read != length ) { throw new IOException ( ) ; } ObjectInputStream in = new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; Object readObject = in . readObject ( ) ; return adaptee . cast ( readObject ) ; } }
Deserialize a file to a given object .
17,112
private void checkParametersAndRunEnergyBalance ( double [ ] rain , double [ ] [ ] T , double [ ] [ ] V , double [ ] [ ] P , double [ ] [ ] RH , double month , double day , double hour , double [ ] Abasin , double [ ] [ ] [ ] A , double [ ] [ ] [ ] EI , double [ ] [ ] DTd , double [ ] [ ] DTm , double [ ] [ ] canopy ) { double Dt = ( ( double ) tTimestep / ( double ) pInternaltimestep ) * 60.0 ; boolean hasNoStations = false ; double zmes_T = 2.0 ; double zmes_U = 2.0 ; double z0T = 0.005 ; double z0U = 0.05 ; double K = ka * ka / ( ( log ( zmes_U / z0U ) ) * ( log ( zmes_T / z0T ) ) ) ; double eps = 0.98 ; double Lc = 0.05 ; double Ksat = 3.0 ; double Ks = 5.55E-5 ; double aep = 50.0 ; double rho_g = 1600 ; double De = 0.4 ; double C_g = 890.0 ; double albedo_land = 0.2 ; double Ts_min = - 20.0 ; double Ts_max = 20.0 ; latitude = 46.6 * Math . PI / 180.0 ; longitude = 10.88 * Math . PI / 180.0 ; standard_time = - 1.0 ; sun ( hour , day ) ; for ( int i = 0 ; i < basinNum ; i ++ ) { calculateEnergyBalance ( i , month , hasNoStations , V [ i ] , canopy , T [ i ] , P [ i ] , RH [ i ] , rain , pTrain , pTsnow , Dt , A , Abasin , EI , DTd [ i ] , DTm [ i ] , K , eps , Lc , pRhosnow , Ksat , rho_g , De , C_g , aep , albedo_land , Ks , Ts_min , Ts_max ) ; } }
Method to check the input parameters .
17,113
public static BufferedReader getBufferedXMLReader ( InputStream stream , int xmlLookahead ) throws IOException { BufferedInputStream input = new BufferedInputStream ( stream ) ; input . mark ( xmlLookahead ) ; EncodingInfo encoding = new EncodingInfo ( ) ; XmlCharsetDetector . getCharsetAwareReader ( input , encoding ) ; Reader reader = XmlCharsetDetector . createReader ( input , encoding ) ; input . reset ( ) ; return getBufferedXMLReader ( reader , xmlLookahead ) ; }
Wraps an xml input xstream in a buffered reader specifying a lookahead that can be used to preparse some of the xml document resetting it back to its original state for actual parsing .
17,114
public static BufferedReader getBufferedXMLReader ( Reader reader , int xmlLookahead ) throws IOException { if ( ! ( reader instanceof BufferedReader ) ) { reader = new BufferedReader ( reader ) ; } reader . mark ( xmlLookahead ) ; return ( BufferedReader ) reader ; }
Wraps an xml reader in a buffered reader specifying a lookahead that can be used to preparse some of the xml document resetting it back to its original state for actual parsing .
17,115
private void validateCoefficients ( ) { if ( coefsValid ) return ; if ( n >= 2 ) { double xBar = ( double ) sumX / n ; double yBar = ( double ) sumY / n ; a1 = ( double ) ( ( n * sumXY - sumX * sumY ) / ( n * sumXX - sumX * sumX ) ) ; a0 = ( double ) ( yBar - a1 * xBar ) ; } else { a0 = a1 = Double . NaN ; } coefsValid = true ; }
Validate the coefficients .
17,116
public static synchronized void initializeDXF_SCHEMA ( CoordinateReferenceSystem crs ) { if ( DXF_POINTSCHEMA != null && DXF_POINTSCHEMA . getAttributeCount ( ) != 0 ) return ; SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder ( ) ; b . setName ( "dxfpointfile" ) ; b . setCRS ( crs ) ; b . add ( "the_geom" , Point . class ) ; b . add ( "LAYER" , String . class ) ; b . add ( "LTYPE" , String . class ) ; b . add ( "ELEVATION" , Double . class ) ; b . add ( "THICKNESS" , Double . class ) ; b . add ( "COLOR" , Integer . class ) ; b . add ( "TEXT" , String . class ) ; b . add ( "TEXT_HEIGHT" , Double . class ) ; b . add ( "TEXT_STYLE" , String . class ) ; DXF_POINTSCHEMA = b . buildFeatureType ( ) ; b = new SimpleFeatureTypeBuilder ( ) ; b . setName ( "dxflinefile" ) ; b . setCRS ( crs ) ; b . add ( "the_geom" , LineString . class ) ; b . add ( "LAYER" , String . class ) ; b . add ( "LTYPE" , String . class ) ; b . add ( "ELEVATION" , Double . class ) ; b . add ( "THICKNESS" , Double . class ) ; b . add ( "COLOR" , Integer . class ) ; b . add ( "TEXT" , String . class ) ; b . add ( "TEXT_HEIGHT" , Double . class ) ; b . add ( "TEXT_STYLE" , String . class ) ; DXF_LINESCHEMA = b . buildFeatureType ( ) ; b = new SimpleFeatureTypeBuilder ( ) ; b . setName ( "dxfpolygonfile" ) ; b . setCRS ( crs ) ; b . add ( "the_geom" , Polygon . class ) ; b . add ( "LAYER" , String . class ) ; b . add ( "LTYPE" , String . class ) ; b . add ( "ELEVATION" , Double . class ) ; b . add ( "THICKNESS" , Double . class ) ; b . add ( "COLOR" , Integer . class ) ; b . add ( "TEXT" , String . class ) ; b . add ( "TEXT_HEIGHT" , Double . class ) ; b . add ( "TEXT_STYLE" , String . class ) ; DXF_POLYGONSCHEMA = b . buildFeatureType ( ) ; }
Initialize a JUMP FeatureSchema to load dxf data keeping some graphic attributes .
17,117
private byte [ ] readClassData ( JavaFileObject classFile ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ 4096 ] ; InputStream classStream = classFile . openInputStream ( ) ; int n = classStream . read ( buf ) ; while ( n > 0 ) { bos . write ( buf , 0 , n ) ; n = classStream . read ( buf ) ; } classStream . close ( ) ; return bos . toByteArray ( ) ; }
Reads all class file data into a byte array from the given file object .
17,118
public static String [ ] getAllMarksArray ( ) { Set < String > keySet = markNamesToDef . keySet ( ) ; return ( String [ ] ) keySet . toArray ( new String [ keySet . size ( ) ] ) ; }
Getter for an array of all available marks .
17,119
public static void substituteMark ( Rule rule , String wellKnownMarkName ) { PointSymbolizer pointSymbolizer = StyleUtilities . pointSymbolizerFromRule ( rule ) ; Mark oldMark = SLD . mark ( pointSymbolizer ) ; Graphic graphic = SLD . graphic ( pointSymbolizer ) ; graphic . graphicalSymbols ( ) . clear ( ) ; Mark mark = StyleUtilities . sf . createMark ( ) ; mark . setWellKnownName ( StyleUtilities . ff . literal ( wellKnownMarkName ) ) ; if ( oldMark != null ) { mark . setFill ( oldMark . getFill ( ) ) ; mark . setStroke ( oldMark . getStroke ( ) ) ; } graphic . graphicalSymbols ( ) . add ( mark ) ; }
Change the mark shape in a rule .
17,120
public static void substituteExternalGraphics ( Rule rule , URL externalGraphicsUrl ) { String urlString = externalGraphicsUrl . toString ( ) ; String format = "" ; if ( urlString . toLowerCase ( ) . endsWith ( ".png" ) ) { format = "image/png" ; } else if ( urlString . toLowerCase ( ) . endsWith ( ".jpg" ) ) { format = "image/jpg" ; } else if ( urlString . toLowerCase ( ) . endsWith ( ".svg" ) ) { format = "image/svg+xml" ; } else { urlString = "" ; try { externalGraphicsUrl = new URL ( "file:" ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } } PointSymbolizer pointSymbolizer = StyleUtilities . pointSymbolizerFromRule ( rule ) ; Graphic graphic = SLD . graphic ( pointSymbolizer ) ; graphic . graphicalSymbols ( ) . clear ( ) ; ExternalGraphic exGraphic = sf . createExternalGraphic ( externalGraphicsUrl , format ) ; graphic . graphicalSymbols ( ) . add ( exGraphic ) ; }
Change the external graphic in a rule .
17,121
public static void changeMarkSize ( Rule rule , int newSize ) { PointSymbolizer pointSymbolizer = StyleUtilities . pointSymbolizerFromRule ( rule ) ; Graphic graphic = SLD . graphic ( pointSymbolizer ) ; graphic . setSize ( ff . literal ( newSize ) ) ; }
Changes the size of a mark inside a rule .
17,122
public static void changeRotation ( Rule rule , int newRotation ) { PointSymbolizer pointSymbolizer = StyleUtilities . pointSymbolizerFromRule ( rule ) ; Graphic graphic = SLD . graphic ( pointSymbolizer ) ; graphic . setRotation ( ff . literal ( newRotation ) ) ; }
Changes the rotation value inside a rule .
17,123
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public static void setOffset ( Symbolizer symbolizer , String text ) { if ( text . indexOf ( ',' ) == - 1 ) { return ; } String [ ] split = text . split ( "," ) ; if ( split . length != 2 ) { return ; } double xOffset = Double . parseDouble ( split [ 0 ] ) ; double yOffset = Double . parseDouble ( split [ 1 ] ) ; Expression geometry = symbolizer . getGeometry ( ) ; if ( geometry != null ) { if ( geometry instanceof FilterFunction_offset ) { FilterFunction_offset offsetFunction = ( FilterFunction_offset ) geometry ; List parameters = offsetFunction . getParameters ( ) ; parameters . set ( 1 , ff . literal ( xOffset ) ) ; parameters . set ( 2 , ff . literal ( yOffset ) ) ; } } else { Function function = ff . function ( "offset" , ff . property ( "the_geom" ) , ff . literal ( xOffset ) , ff . literal ( yOffset ) ) ; symbolizer . setGeometry ( function ) ; } }
Sets the offset in a symbolizer .
17,124
public static String styleToString ( Style style ) throws Exception { StyledLayerDescriptor sld = sf . createStyledLayerDescriptor ( ) ; UserLayer layer = sf . createUserLayer ( ) ; layer . setLayerFeatureConstraints ( new FeatureTypeConstraint [ ] { null } ) ; sld . addStyledLayer ( layer ) ; layer . addUserStyle ( style ) ; SLDTransformer aTransformer = new SLDTransformer ( ) ; aTransformer . setIndentation ( 4 ) ; String xml = aTransformer . transform ( sld ) ; return xml ; }
Converts a style to its string representation to be written to file .
17,125
public static StyleWrapper createStyleFromGraphic ( File graphicsPath ) throws IOException { String name = graphicsPath . getName ( ) ; ExternalGraphic exGraphic = null ; if ( name . toLowerCase ( ) . endsWith ( ".png" ) ) { exGraphic = sf . createExternalGraphic ( graphicsPath . toURI ( ) . toURL ( ) , "image/png" ) ; } else if ( name . toLowerCase ( ) . endsWith ( ".svg" ) ) { exGraphic = sf . createExternalGraphic ( graphicsPath . toURI ( ) . toURL ( ) , "image/svg+xml" ) ; } else if ( name . toLowerCase ( ) . endsWith ( ".sld" ) ) { StyledLayerDescriptor sld = readStyle ( graphicsPath ) ; Style style = SldUtilities . getDefaultStyle ( sld ) ; return new StyleWrapper ( style ) ; } if ( exGraphic == null ) { throw new IOException ( "Style could not be created!" ) ; } Graphic gr = sf . createDefaultGraphic ( ) ; gr . graphicalSymbols ( ) . clear ( ) ; gr . graphicalSymbols ( ) . add ( exGraphic ) ; Expression size = ff . literal ( 20 ) ; gr . setSize ( size ) ; Rule rule = sf . createRule ( ) ; PointSymbolizer pointSymbolizer = sf . createPointSymbolizer ( gr , null ) ; rule . symbolizers ( ) . add ( pointSymbolizer ) ; FeatureTypeStyle featureTypeStyle = sf . createFeatureTypeStyle ( ) ; featureTypeStyle . rules ( ) . add ( rule ) ; Style namedStyle = sf . createStyle ( ) ; namedStyle . featureTypeStyles ( ) . add ( featureTypeStyle ) ; namedStyle . setName ( FilenameUtils . removeExtension ( name ) ) ; return new StyleWrapper ( namedStyle ) ; }
Generates a style based on a graphic .
17,126
public static float [ ] getDash ( String dashStr ) { if ( dashStr == null ) { return null ; } String [ ] dashSplit = dashStr . split ( "," ) ; int size = dashSplit . length ; float [ ] dash = new float [ size ] ; try { for ( int i = 0 ; i < dash . length ; i ++ ) { dash [ i ] = Float . parseFloat ( dashSplit [ i ] . trim ( ) ) ; } return dash ; } catch ( NumberFormatException e ) { return null ; } }
Returns a dash array from a dash string .
17,127
public static String getDashString ( float [ ] dashArray ) { StringBuilder sb = null ; for ( float f : dashArray ) { if ( sb == null ) { sb = new StringBuilder ( String . valueOf ( f ) ) ; } else { sb . append ( "," ) ; sb . append ( String . valueOf ( f ) ) ; } } return sb . toString ( ) ; }
Converts teh array to string .
17,128
public static int sld2awtJoin ( String sldJoin ) { if ( sldJoin . equals ( lineJoinNames [ 1 ] ) ) { return BasicStroke . JOIN_BEVEL ; } else if ( sldJoin . equals ( "" ) || sldJoin . equals ( lineJoinNames [ 2 ] ) ) { return BasicStroke . JOIN_MITER ; } else if ( sldJoin . equals ( lineJoinNames [ 3 ] ) ) { return BasicStroke . JOIN_ROUND ; } else { throw new IllegalArgumentException ( "unsupported line join" ) ; } }
Convert a sld line join definition to the java awt value .
17,129
public static int sld2awtCap ( String sldCap ) { if ( sldCap . equals ( "" ) || sldCap . equals ( lineCapNames [ 1 ] ) ) { return BasicStroke . CAP_BUTT ; } else if ( sldCap . equals ( lineCapNames [ 2 ] ) ) { return BasicStroke . CAP_ROUND ; } else if ( sldCap . equals ( lineCapNames [ 3 ] ) ) { return BasicStroke . CAP_SQUARE ; } else { throw new IllegalArgumentException ( "unsupported line cap" ) ; } }
Convert a sld line cap definition to the java awt value .
17,130
public static Envelope scaleToWidth ( Envelope original , double newWidth ) { double width = original . getWidth ( ) ; double factor = newWidth / width ; double newHeight = original . getHeight ( ) * factor ; return new Envelope ( original . getMinX ( ) , original . getMinX ( ) + newWidth , original . getMinY ( ) , original . getMinY ( ) + newHeight ) ; }
Scale an envelope to have a given width .
17,131
public static int getDayOfYear ( Calendar cal , int type ) { int jday = cal . get ( Calendar . DAY_OF_YEAR ) ; int mo = cal . get ( java . util . Calendar . MONTH ) + 1 ; if ( type == CALENDAR_YEAR ) { return jday ; } else if ( type == SOLAR_YEAR ) { int day = cal . get ( Calendar . DAY_OF_MONTH ) ; return ( mo == 12 && day > 21 ) ? ( day - 21 ) : ( jday + 10 ) ; } else if ( type == WATER_YEAR ) { return ( mo > 9 ) ? ( jday - ( isLeapYear ( cal . get ( Calendar . YEAR ) ) ? 274 : 273 ) ) : ( jday + 92 ) ; } throw new IllegalArgumentException ( "getDayOfYear() type argument unknown" ) ; }
Get the Day of the year in WATER SOLAR or CALENDAR year .
17,132
public static double deltaHours ( int calUnit , int increments ) { if ( calUnit == Calendar . DATE ) { return 24 * increments ; } else if ( calUnit == Calendar . HOUR ) { return increments ; } else if ( calUnit == Calendar . MINUTE ) { return increments / 60 ; } else if ( calUnit == Calendar . SECOND ) { return increments / 3600 ; } return - 1 ; }
This used to be deltim in MMS .
17,133
protected ValidationMessage < Origin > reportError ( Origin origin , String messageKey , Object ... params ) { return reportMessage ( Severity . ERROR , origin , messageKey , params ) ; }
Creates an error validation message for the feature and adds it to the validation result .
17,134
protected ValidationMessage < Origin > reportFeatureError ( Origin origin , String messageKey , Feature feature , Object ... params ) { ValidationMessage < Origin > message = reportMessage ( Severity . ERROR , origin , messageKey , params ) ; appendLocusTadAndGeneIDToMessage ( feature , message ) ; return message ; }
Creates an error validation message for the feature and adds it to the validation result . If there are locus_tag or gene qualifiers the values of these will be added to the message as a curator comment .
17,135
public static void appendLocusTadAndGeneIDToMessage ( Feature feature , ValidationMessage < Origin > message ) { if ( SequenceEntryUtils . isQualifierAvailable ( Qualifier . LOCUS_TAG_QUALIFIER_NAME , feature ) ) { Qualifier locusTag = SequenceEntryUtils . getQualifier ( Qualifier . LOCUS_TAG_QUALIFIER_NAME , feature ) ; if ( locusTag . isValue ( ) ) { message . appendCuratorMessage ( "locus tag = " + locusTag . getValue ( ) ) ; } } if ( SequenceEntryUtils . isQualifierAvailable ( Qualifier . GENE_QUALIFIER_NAME , feature ) ) { Qualifier geneName = SequenceEntryUtils . getQualifier ( Qualifier . GENE_QUALIFIER_NAME , feature ) ; if ( geneName . isValue ( ) ) { message . appendCuratorMessage ( "gene = " + geneName . getValue ( ) ) ; } } }
If a feature had locus_tag or gene qualifiers - appends the value of these to the message as a curator comment . Useful for some submitters who want more of a handle on the origin than just a line number .
17,136
protected ValidationMessage < Origin > reportWarning ( Origin origin , String messageKey , Object ... params ) { return reportMessage ( Severity . WARNING , origin , messageKey , params ) ; }
Creates a warning validation message for the feature and adds it to the validation result .
17,137
protected ValidationMessage < Origin > reportMessage ( Severity severity , Origin origin , String messageKey , Object ... params ) { ValidationMessage < Origin > message = EntryValidations . createMessage ( origin , severity , messageKey , params ) ; message . getMessage ( ) ; result . append ( message ) ; return message ; }
Creates a validation message for the feature and adds it to the validation result .
17,138
private boolean isAlone ( Geometry geometryN ) { Coordinate [ ] coordinates = geometryN . getCoordinates ( ) ; if ( coordinates . length > 1 ) { Coordinate first = coordinates [ 0 ] ; Coordinate last = coordinates [ coordinates . length - 1 ] ; for ( SimpleFeature line : linesList ) { Geometry lineGeom = ( Geometry ) line . getDefaultGeometry ( ) ; int numGeometries = lineGeom . getNumGeometries ( ) ; for ( int i = 0 ; i < numGeometries ; i ++ ) { Geometry subGeom = lineGeom . getGeometryN ( i ) ; Coordinate [ ] lineCoordinates = subGeom . getCoordinates ( ) ; if ( lineCoordinates . length < 2 ) { continue ; } else { Coordinate tmpFirst = lineCoordinates [ 0 ] ; Coordinate tmpLast = lineCoordinates [ lineCoordinates . length - 1 ] ; if ( tmpFirst . distance ( first ) < SAMEPOINTTHRESHOLD || tmpFirst . distance ( last ) < SAMEPOINTTHRESHOLD || tmpLast . distance ( first ) < SAMEPOINTTHRESHOLD || tmpLast . distance ( last ) < SAMEPOINTTHRESHOLD ) { return false ; } } } } } return true ; }
Checks if the given geometry is connected to any other line .
17,139
public static void defaultSmoothShapefile ( String shapePath , String outPath ) throws Exception { PrintStreamProgressMonitor pm = new PrintStreamProgressMonitor ( System . out , System . err ) ; SimpleFeatureCollection initialFC = OmsShapefileFeatureReader . readShapefile ( shapePath ) ; OmsLineSmootherMcMaster smoother = new OmsLineSmootherMcMaster ( ) ; smoother . pm = pm ; smoother . pLimit = 10 ; smoother . inVector = initialFC ; smoother . pLookahead = 13 ; smoother . pDensify = 0.2 ; smoother . pSimplify = 0.01 ; smoother . process ( ) ; SimpleFeatureCollection smoothedFeatures = smoother . outVector ; OmsShapefileFeatureWriter . writeShapefile ( outPath , smoothedFeatures , pm ) ; }
An utility method to use the module with default values and shapefiles .
17,140
public double magnitudeSqr ( Object pt ) { double sum = 0.0 ; double [ ] coords = coords ( pt ) ; for ( int i = 0 ; i < dimensions ; i ++ ) { double c = coords [ i ] ; sum += c * c ; } return sum ; }
space point operations
17,141
public static byte [ ] generateSecretKey ( ) { final byte [ ] k = new byte [ KEY_LEN ] ; final SecureRandom random = new SecureRandom ( ) ; random . nextBytes ( k ) ; return k ; }
Generates a 32 - byte secret key .
17,142
private static void initialize ( ) { for ( int i = 0 ; i < 256 ; ++ i ) { long crc = i ; for ( int j = 8 ; j > 0 ; j -- ) { if ( ( crc & 1 ) == 1 ) crc = ( crc >>> 1 ) ^ polynomial ; else crc >>>= 1 ; } values [ i ] = crc ; } init_done = true ; }
Calculates a CRC value for a byte to be used by CRC calculation functions .
17,143
public static long calculateCRC32 ( byte [ ] buffer , int offset , int length ) { if ( ! init_done ) { initialize ( ) ; } for ( int i = offset ; i < offset + length ; i ++ ) { long tmp1 = ( crc >>> 8 ) & 0x00FFFFFFL ; long tmp2 = values [ ( int ) ( ( crc ^ Character . toUpperCase ( ( char ) buffer [ i ] ) ) & 0xff ) ] ; crc = tmp1 ^ tmp2 ; } return crc ; }
Calculates the CRC - 32 of a block of data all at once
17,144
private synchronized URLClassLoader getClassLoader ( ) { if ( modelClassLoader == null ) { List < File > jars = res . filterFiles ( "jar" ) ; List < File > cli_jars = getExtraResources ( ) ; List < File > dirs = res . filterDirectories ( ) ; List < URL > urls = new ArrayList < URL > ( ) ; try { for ( int i = 0 ; i < jars . size ( ) ; i ++ ) { urls . add ( jars . get ( i ) . toURI ( ) . toURL ( ) ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( "classpath entry from simulation: " + jars . get ( i ) ) ; } } for ( int i = 0 ; i < dirs . size ( ) ; i ++ ) { urls . add ( dirs . get ( i ) . toURI ( ) . toURL ( ) ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( "dir entry: " + dirs . get ( i ) ) ; } } for ( int i = 0 ; i < cli_jars . size ( ) ; i ++ ) { urls . add ( cli_jars . get ( i ) . toURI ( ) . toURL ( ) ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( "classpath entry from CLI: " + cli_jars . get ( i ) ) ; } } urls . add ( new URL ( "file:" + System . getProperty ( "oms.prj" ) + "/dist/" ) ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( "Sim loading classpath : " + "file:" + System . getProperty ( "oms.prj" ) + "/dist/" ) ; } } catch ( MalformedURLException ex ) { throw new ComponentException ( "Illegal resource:" + ex . getMessage ( ) ) ; } modelClassLoader = new URLClassLoader ( urls . toArray ( new URL [ 0 ] ) , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; } return modelClassLoader ; }
get the URL class loader for all the resources ( just for jar files
17,145
public static double getDistanceBetween ( IHMConnection connection , Coordinate p1 , Coordinate p2 , int srid ) throws Exception { if ( srid < 0 ) { srid = 4326 ; } GeometryFactory gf = new GeometryFactory ( ) ; LineString lineString = gf . createLineString ( new Coordinate [ ] { p1 , p2 } ) ; String sql = "select GeodesicLength(LineFromText(\"" + lineString . toText ( ) + "\"," + srid + "));" ; try ( IHMStatement stmt = connection . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( sql ) ; ) { if ( rs . next ( ) ) { double length = rs . getDouble ( 1 ) ; return length ; } throw new RuntimeException ( "Could not calculate distance." ) ; } }
Calculates the GeodesicLength between to points .
17,146
private boolean moveToNextTriggerpoint ( RandomIter triggerIter , RandomIter flowIter , int [ ] flowDirColRow ) { double tmpFlowValue = flowIter . getSampleDouble ( flowDirColRow [ 0 ] , flowDirColRow [ 1 ] , 0 ) ; if ( tmpFlowValue == 10 ) { return false ; } if ( ! ModelsEngine . go_downstream ( flowDirColRow , tmpFlowValue ) ) throw new ModelsIllegalargumentException ( "Unable to go downstream: " + flowDirColRow [ 0 ] + "/" + flowDirColRow [ 1 ] , this , pm ) ; while ( isNovalue ( triggerIter . getSampleDouble ( flowDirColRow [ 0 ] , flowDirColRow [ 1 ] , 0 ) ) ) { tmpFlowValue = flowIter . getSampleDouble ( flowDirColRow [ 0 ] , flowDirColRow [ 1 ] , 0 ) ; if ( tmpFlowValue == 10 ) { return false ; } if ( ! ModelsEngine . go_downstream ( flowDirColRow , tmpFlowValue ) ) throw new ModelsIllegalargumentException ( "Unable to go downstream: " + flowDirColRow [ 0 ] + "/" + flowDirColRow [ 1 ] , this , pm ) ; } return true ; }
Moves the flowDirColRow variable to the next trigger point .
17,147
public static void memclr ( byte [ ] array , int offset , int length ) { for ( int i = 0 ; i < length ; ++ i , ++ offset ) array [ offset ] = 0 ; }
Fill the given array with zeros .
17,148
public static byte [ ] zero_pad ( byte [ ] original , int block_size ) { if ( ( original . length % block_size ) == 0 ) { return original ; } byte [ ] result = new byte [ round_up ( original . length , block_size ) ] ; memcpy ( result , 0 , original , 0 , original . length ) ; return result ; }
Return a new array equal to original except zero - padded to an integral mulitple of blocks . If the original is already an integral multiple of blocks just return it .
17,149
public static boolean isSupportedVectorExtension ( String name ) { for ( String ext : supportedVectors ) { if ( name . toLowerCase ( ) . endsWith ( ext ) ) { return true ; } } return false ; }
Checks a given name of a file if it is a supported vector extension .
17,150
public static boolean isSupportedRasterExtension ( String name ) { for ( String ext : supportedRasters ) { if ( name . toLowerCase ( ) . endsWith ( ext ) ) { return true ; } } return false ; }
Checks a given name of a file if it is a supported raster extension .
17,151
public static GridCoverage2D readRaster ( String path ) throws Exception { OmsRasterReader reader = new OmsRasterReader ( ) ; reader . file = path ; reader . process ( ) ; GridCoverage2D geodata = reader . outRaster ; return geodata ; }
Utility method to quickly read a grid in default mode .
17,152
private void swap ( int i , int j ) { double [ ] temp = data [ i ] ; data [ i ] = data [ j ] ; data [ j ] = temp ; }
swap rows i and j
17,153
public Matrix transpose ( ) { Matrix A = new Matrix ( N , M ) ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { A . data [ j ] [ i ] = data [ i ] [ j ] ; } } return A ; }
create and return the transpose of the invoking matrix
17,154
public Matrix solve ( Matrix rhs ) { if ( M != N || rhs . M != N || rhs . N != 1 ) { throw new RuntimeException ( "Illegal matrix dimensions." ) ; } Matrix A = new Matrix ( this ) ; Matrix b = new Matrix ( rhs ) ; for ( int i = 0 ; i < N ; i ++ ) { int max = i ; for ( int j = i + 1 ; j < N ; j ++ ) { if ( Math . abs ( A . data [ j ] [ i ] ) > Math . abs ( A . data [ max ] [ i ] ) ) { max = j ; } } A . swap ( i , max ) ; b . swap ( i , max ) ; if ( A . data [ i ] [ i ] == 0.0 ) { throw new RuntimeException ( "Matrix is singular." ) ; } for ( int j = i + 1 ; j < N ; j ++ ) { b . data [ j ] [ 0 ] -= b . data [ i ] [ 0 ] * A . data [ j ] [ i ] / A . data [ i ] [ i ] ; } for ( int j = i + 1 ; j < N ; j ++ ) { double m = A . data [ j ] [ i ] / A . data [ i ] [ i ] ; for ( int k = i + 1 ; k < N ; k ++ ) { A . data [ j ] [ k ] -= A . data [ i ] [ k ] * m ; } A . data [ j ] [ i ] = 0.0 ; } } Matrix x = new Matrix ( N , 1 ) ; for ( int j = N - 1 ; j >= 0 ; j -- ) { double t = 0.0 ; for ( int k = j + 1 ; k < N ; k ++ ) { t += A . data [ j ] [ k ] * x . data [ k ] [ 0 ] ; } x . data [ j ] [ 0 ] = ( b . data [ j ] [ 0 ] - t ) / A . data [ j ] [ j ] ; } return x ; }
return x = A^ - 1 b assuming A is square and has full rank
17,155
public void print ( ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { System . out . printf ( "%9.4f " , data [ i ] [ j ] ) ; } System . out . println ( ) ; } }
print matrix to standard output
17,156
public void createTables ( boolean makeIndexes ) throws Exception { database . executeInsertUpdateDeleteSql ( "DROP TABLE IF EXISTS " + TABLE_TILES ) ; database . executeInsertUpdateDeleteSql ( "DROP TABLE IF EXISTS " + TABLE_METADATA ) ; database . executeInsertUpdateDeleteSql ( CREATE_TILES ) ; database . executeInsertUpdateDeleteSql ( CREATE_METADATA ) ; if ( makeIndexes ) { createIndexes ( ) ; } }
Create the mbtiles tables in the db .
17,157
public void fillMetadata ( float n , float s , float w , float e , String name , String format , int minZoom , int maxZoom ) throws Exception { String query = toMetadataQuery ( "name" , name ) ; database . executeInsertUpdateDeleteSql ( query ) ; query = toMetadataQuery ( "description" , name ) ; database . executeInsertUpdateDeleteSql ( query ) ; query = toMetadataQuery ( "format" , format ) ; database . executeInsertUpdateDeleteSql ( query ) ; query = toMetadataQuery ( "minZoom" , minZoom + "" ) ; database . executeInsertUpdateDeleteSql ( query ) ; query = toMetadataQuery ( "maxZoom" , maxZoom + "" ) ; database . executeInsertUpdateDeleteSql ( query ) ; query = toMetadataQuery ( "type" , "baselayer" ) ; database . executeInsertUpdateDeleteSql ( query ) ; query = toMetadataQuery ( "version" , "1.1" ) ; database . executeInsertUpdateDeleteSql ( query ) ; query = toMetadataQuery ( "bounds" , w + "," + s + "," + e + "," + n ) ; database . executeInsertUpdateDeleteSql ( query ) ; }
Populate the metadata table .
17,158
public synchronized void addTile ( int x , int y , int z , byte [ ] imageBytes ) throws Exception { database . execOnConnection ( connection -> { try ( IHMPreparedStatement pstmt = connection . prepareStatement ( insertTileSql ) ; ) { pstmt . setInt ( 1 , z ) ; pstmt . setInt ( 2 , x ) ; pstmt . setInt ( 3 , y ) ; pstmt . setBytes ( 4 , imageBytes ) ; pstmt . executeUpdate ( ) ; return "" ; } } ) ; }
Add a single tile .
17,159
public synchronized void addTilesInBatch ( List < Tile > tilesList ) throws Exception { database . execOnConnection ( connection -> { boolean autoCommit = connection . getAutoCommit ( ) ; connection . setAutoCommit ( false ) ; try ( IHMPreparedStatement pstmt = connection . prepareStatement ( insertTileSql ) ; ) { for ( Tile tile : tilesList ) { pstmt . setInt ( 1 , tile . z ) ; pstmt . setInt ( 2 , tile . x ) ; pstmt . setInt ( 3 , tile . y ) ; pstmt . setBytes ( 4 , tile . imageBytes ) ; pstmt . addBatch ( ) ; } pstmt . executeBatch ( ) ; return "" ; } finally { connection . setAutoCommit ( autoCommit ) ; } } ) ; }
Add a list of tiles in batch mode .
17,160
public byte [ ] getTile ( int tx , int tyOsm , int zoom ) throws Exception { int ty = tyOsm ; if ( tileRowType . equals ( "tms" ) ) { int [ ] tmsTileXY = MercatorUtils . osmTile2TmsTile ( tx , tyOsm , zoom ) ; ty = tmsTileXY [ 1 ] ; } int _ty = ty ; return database . execOnConnection ( connection -> { try ( IHMPreparedStatement statement = connection . prepareStatement ( SELECTQUERY ) ) { statement . setInt ( 1 , zoom ) ; statement . setInt ( 2 , tx ) ; statement . setInt ( 3 , _ty ) ; IHMResultSet resultSet = statement . executeQuery ( ) ; if ( resultSet . next ( ) ) { byte [ ] imageBytes = resultSet . getBytes ( 1 ) ; return imageBytes ; } } return null ; } ) ; }
Get a Tile s image bytes from the database .
17,161
public Envelope getBounds ( ) throws Exception { checkMetadata ( ) ; String boundsWSEN = metadataMap . get ( "bounds" ) ; String [ ] split = boundsWSEN . split ( "," ) ; double w = Double . parseDouble ( split [ 0 ] ) ; double s = Double . parseDouble ( split [ 1 ] ) ; double e = Double . parseDouble ( split [ 2 ] ) ; double n = Double . parseDouble ( split [ 3 ] ) ; return new Envelope ( w , e , s , n ) ; }
Get the db envelope .
17,162
public int [ ] getBoundsInTileIndex ( int zoomlevel ) throws Exception { String sql = "select min(tile_column), max(tile_column), min(tile_row), max(tile_row) from tiles where zoom_level=" + zoomlevel ; return database . execOnConnection ( connection -> { try ( IHMStatement statement = connection . createStatement ( ) ; IHMResultSet resultSet = statement . executeQuery ( sql ) ; ) { if ( resultSet . next ( ) ) { int minTx = resultSet . getInt ( 1 ) ; int maxTx = resultSet . getInt ( 2 ) ; int minTy = resultSet . getInt ( 3 ) ; int maxTy = resultSet . getInt ( 4 ) ; return new int [ ] { minTx , maxTx , minTy , maxTy } ; } } return null ; } ) ; }
Get the bounds of a zoomlevel in tile indexes .
17,163
public void out2in ( Object from , String from_out , Object ... tos ) { for ( Object co : tos ) { out2in ( from , from_out , co , from_out ) ; } }
Connects field1 of cmd1 with the same named fields in cmds
17,164
public void in2in ( String in , Object to , String to_in ) { controller . mapIn ( in , to , to_in ) ; }
Maps a Compound Input field to a internal simple input field .
17,165
public void in2in ( String in , Object ... to ) { for ( Object cmd : to ) { in2in ( in , cmd , in ) ; } }
Maps a compound input to an internal simple input field . Both fields have the same name .
17,166
public void field2in ( Object o , String field , Object to , String to_in ) { controller . mapInField ( o , field , to , to_in ) ; }
Maps a object s field to an In field
17,167
public void field2in ( Object o , String field , Object to ) { field = field . trim ( ) ; if ( field . indexOf ( ' ' ) > 0 ) { String [ ] fields = field . split ( "\\s+" ) ; for ( String f : fields ) { field2in ( o , f , to , f ) ; } } else { field2in ( o , field , to , field ) ; } }
Maps an object s field to a component s In field with the same name
17,168
public void out2field ( Object from , String from_out , Object o , String field ) { controller . mapOutField ( from , from_out , o , field ) ; }
Maps a component s Out field to an object field .
17,169
public void out2field ( Object from , String from_out , Object o ) { out2field ( from , from_out , o , from_out ) ; }
Maps a component Out field to an object s field . Both field have the same name .
17,170
public void out2out ( String out , Object to , String to_out ) { controller . mapOut ( out , to , to_out ) ; }
Maps a Compound Output field to a internal simple output field .
17,171
public void connect ( Object from , String from_out , Object to , String to_in ) { controller . connect ( from , from_out , to , to_in ) ; }
deprecated methods starting here .
17,172
protected void reportError ( ValidationResult result , String messageKey , Object ... params ) { reportMessage ( result , Severity . ERROR , messageKey , params ) ; }
Creates an error validation message for the sequence and adds it to the validation result .
17,173
protected void reportWarning ( ValidationResult result , String messageKey , Object ... params ) { reportMessage ( result , Severity . WARNING , messageKey , params ) ; }
Creates a warning validation message for the sequence and adds it to the validation result .
17,174
protected void reportMessage ( ValidationResult result , Severity severity , String messageKey , Object ... params ) { result . append ( EntryValidations . createMessage ( origin , severity , messageKey , params ) ) ; }
Creates a validation message for the sequence and adds it to the validation result .
17,175
private void calcInsolation ( double lambda , WritableRaster demWR , WritableRaster gradientWR , WritableRaster insolationWR , int day , double dx ) { double dayangb = ( 360 / 365.25 ) * ( day - 79.436 ) ; dayangb = Math . toRadians ( dayangb ) ; delta = getDeclination ( dayangb ) ; double ss = Math . acos ( - Math . tan ( delta ) * Math . tan ( lambda ) ) ; double hour = - ss + ( Math . PI / 48.0 ) ; while ( hour <= ss - ( Math . PI / 48 ) ) { omega = hour ; double sunVector [ ] = calcSunVector ( ) ; double zenith = calcZenith ( sunVector [ 2 ] ) ; double [ ] inverseSunVector = calcInverseSunVector ( sunVector ) ; double [ ] normalSunVector = calcNormalSunVector ( sunVector ) ; int height = demWR . getHeight ( ) ; int width = demWR . getWidth ( ) ; WritableRaster sOmbraWR = calculateFactor ( height , width , sunVector , inverseSunVector , normalSunVector , demWR , dx ) ; double mr = 1 / ( sunVector [ 2 ] + 0.15 * Math . pow ( ( 93.885 - zenith ) , ( - 1.253 ) ) ) ; for ( int j = 0 ; j < height ; j ++ ) { for ( int i = 0 ; i < width ; i ++ ) { calcRadiation ( i , j , demWR , sOmbraWR , insolationWR , sunVector , gradientWR , mr ) ; } } hour = hour + Math . PI / 24.0 ; } }
Evaluate the radiation .
17,176
public static boolean isCrsValid ( CoordinateReferenceSystem crs ) { if ( crs instanceof AbstractSingleCRS ) { AbstractSingleCRS aCrs = ( AbstractSingleCRS ) crs ; Datum datum = aCrs . getDatum ( ) ; ReferenceIdentifier name = datum . getName ( ) ; String code = name . getCode ( ) ; if ( code . equalsIgnoreCase ( "Unknown" ) ) { return false ; } } return true ; }
Checks if a crs is valid i . e . if it is not a wildcard default one .
17,177
@ SuppressWarnings ( "nls" ) public static void writeProjectionFile ( String filePath , String extention , CoordinateReferenceSystem crs ) throws IOException { String prjPath = null ; if ( extention != null && filePath . toLowerCase ( ) . endsWith ( "." + extention ) ) { int dotLoc = filePath . lastIndexOf ( "." ) ; prjPath = filePath . substring ( 0 , dotLoc ) ; prjPath = prjPath + ".prj" ; } else { if ( ! filePath . endsWith ( ".prj" ) ) { prjPath = filePath + ".prj" ; } else { prjPath = filePath ; } } try ( BufferedWriter bufferedWriter = new BufferedWriter ( new FileWriter ( prjPath ) ) ) { bufferedWriter . write ( crs . toWKT ( ) ) ; } }
Fill the prj file with the actual map projection .
17,178
public static void reproject ( CoordinateReferenceSystem from , CoordinateReferenceSystem to , Object [ ] geometries ) throws Exception { MathTransform mathTransform = CRS . findMathTransform ( from , to ) ; for ( int i = 0 ; i < geometries . length ; i ++ ) { geometries [ i ] = JTS . transform ( ( Geometry ) geometries [ i ] , mathTransform ) ; } }
Reproject a set of geometries
17,179
public static void reproject ( CoordinateReferenceSystem from , CoordinateReferenceSystem to , Coordinate [ ] coordinates ) throws Exception { MathTransform mathTransform = CRS . findMathTransform ( from , to ) ; for ( int i = 0 ; i < coordinates . length ; i ++ ) { coordinates [ i ] = JTS . transform ( coordinates [ i ] , coordinates [ i ] , mathTransform ) ; } }
Reproject a set of coordinates .
17,180
public static double getMetersAsWGS84 ( double meters , Coordinate c ) { GeodeticCalculator gc = new GeodeticCalculator ( DefaultGeographicCRS . WGS84 ) ; gc . setStartingGeographicPoint ( c . x , c . y ) ; gc . setDirection ( 90 , meters ) ; Point2D destinationGeographicPoint = gc . getDestinationGeographicPoint ( ) ; double degrees = Math . abs ( destinationGeographicPoint . getX ( ) - c . x ) ; return degrees ; }
Converts meters to degrees based on a given coordinate in 90 degrees direction .
17,181
private void createHoughPixels ( double [ ] [ ] [ ] houghValues , byte houghPixels [ ] ) { double d = - 1D ; for ( int j = 0 ; j < height ; j ++ ) { for ( int k = 0 ; k < width ; k ++ ) { if ( houghValues [ k ] [ j ] [ 0 ] > d ) { d = houghValues [ k ] [ j ] [ 0 ] ; } } } for ( int l = 0 ; l < height ; l ++ ) { for ( int i = 0 ; i < width ; i ++ ) { houghPixels [ i + l * width ] = ( byte ) Math . round ( ( houghValues [ i ] [ l ] [ 0 ] * 255D ) / d ) ; } } }
Convert Values in Hough Space to an 8 - Bit Image Space .
17,182
public void drawCircles ( double [ ] [ ] [ ] houghValues , byte [ ] circlespixels ) { int roiaddr = 0 ; for ( int y = offy ; y < offy + height ; y ++ ) { for ( int x = offx ; x < offx + width ; x ++ ) { circlespixels [ roiaddr ] = imageValues [ x + offset * y ] ; if ( circlespixels [ roiaddr ] != 0 ) circlespixels [ roiaddr ] = 100 ; else circlespixels [ roiaddr ] = 0 ; roiaddr ++ ; } } Coordinate [ ] centerPoints = getCenterPoints ( houghValues , maxCircles ) ; byte cor = - 1 ; int offset = width ; int offx = 0 ; int offy = 0 ; for ( int l = 0 ; l < maxCircles ; l ++ ) { int i = ( int ) centerPoints [ l ] . x ; int j = ( int ) centerPoints [ l ] . y ; for ( int k = - 10 ; k <= 10 ; ++ k ) { int p = ( j + k + offy ) * offset + ( i + offx ) ; if ( ! outOfBounds ( j + k + offy , i + offx ) ) circlespixels [ ( j + k + offy ) * offset + ( i + offx ) ] = cor ; if ( ! outOfBounds ( j + offy , i + k + offx ) ) circlespixels [ ( j + offy ) * offset + ( i + k + offx ) ] = cor ; } for ( int k = - 2 ; k <= 2 ; ++ k ) { if ( ! outOfBounds ( j - 2 + offy , i + k + offx ) ) circlespixels [ ( j - 2 + offy ) * offset + ( i + k + offx ) ] = cor ; if ( ! outOfBounds ( j + 2 + offy , i + k + offx ) ) circlespixels [ ( j + 2 + offy ) * offset + ( i + k + offx ) ] = cor ; if ( ! outOfBounds ( j + k + offy , i - 2 + offx ) ) circlespixels [ ( j + k + offy ) * offset + ( i - 2 + offx ) ] = cor ; if ( ! outOfBounds ( j + k + offy , i + 2 + offx ) ) circlespixels [ ( j + k + offy ) * offset + ( i + 2 + offx ) ] = cor ; } } }
Draw the circles found in the original image .
17,183
public String getSequence ( Long beginPosition , Long endPosition ) { byte [ ] sequenceByte = getSequenceByte ( beginPosition , endPosition ) ; if ( sequenceByte != null ) return new String ( sequenceByte ) ; return null ; }
Returns a subsequence string or null if the location is not valid .
17,184
private void set ( Matrix m ) { this . nRows = this . nCols = Math . min ( m . nRows , m . nCols ) ; this . values = m . values ; }
Set this square matrix from another matrix . Note that this matrix will reference the values of the argument matrix . If the values are not square only the upper left square is used .
17,185
protected void set ( double values [ ] [ ] ) { super . set ( values ) ; nRows = nCols = Math . min ( nRows , nCols ) ; }
Set this square matrix from a 2 - d array of values . If the values are not square only the upper left square is used .
17,186
public static void printMatrixData ( double [ ] [ ] matrix ) { int cols = matrix [ 0 ] . length ; int rows = matrix . length ; for ( int r = 0 ; r < rows ; r ++ ) { for ( int c = 0 ; c < cols ; c ++ ) { printer . print ( matrix [ r ] [ c ] ) ; printer . print ( separator ) ; } printer . println ( ) ; } }
Print data from a matrix .
17,187
public static String envelope2WKT ( org . locationtech . jts . geom . Envelope env ) { GeometryFactory gf = GeometryUtilities . gf ( ) ; Geometry geometry = gf . toGeometry ( env ) ; return geometry . toText ( ) ; }
Print the envelope as WKT .
17,188
public int read ( ) throws IOException { int b = 0 ; if ( fOffset < fLength ) { return fData [ fOffset ++ ] & 0xff ; } if ( fOffset == fEndOffset ) { return - 1 ; } if ( fOffset == fData . length ) { byte [ ] newData = new byte [ fOffset << 1 ] ; System . arraycopy ( fData , 0 , newData , 0 , fOffset ) ; fData = newData ; } b = fInputStream . read ( ) ; if ( b == - 1 ) { fEndOffset = fOffset ; return - 1 ; } fData [ fLength ++ ] = ( byte ) b ; fOffset ++ ; return b & 0xff ; }
Reads next byte from this stream . This byte is either being read from underlying InputStream or taken from the internal buffer in case it was already read at some point before .
17,189
public void close ( ) throws IOException { if ( fInputStream != null ) { fInputStream . close ( ) ; fInputStream = null ; fData = null ; } }
Closes underlying byte stream .
17,190
public String getTranslation ( ) { if ( codons == null ) { return "" ; } StringBuilder translation = new StringBuilder ( ) ; for ( Codon codon : codons ) { translation . append ( codon . getAminoAcid ( ) ) ; } return translation . toString ( ) ; }
Returns the translation including stop codons and trailing bases .
17,191
public String getConceptualTranslation ( ) { if ( codons == null ) { return "" ; } StringBuilder translation = new StringBuilder ( ) ; for ( int i = 0 ; i < conceptualTranslationCodons ; ++ i ) { Codon codon = codons . get ( i ) ; translation . append ( codon . getAminoAcid ( ) ) ; } return translation . toString ( ) ; }
Returns the translation excluding stop codons and trailing bases .
17,192
public static double [ ] gaussianSmooth ( double [ ] values , int kernelRadius ) throws Exception { int size = values . length ; double [ ] newValues = new double [ values . length ] ; double [ ] kernelData2D = makeGaussianKernel ( kernelRadius ) ; for ( int i = 0 ; i < kernelRadius ; i ++ ) { newValues [ i ] = values [ i ] ; } for ( int r = kernelRadius ; r < size - kernelRadius ; r ++ ) { double kernelSum = 0.0 ; double outputValue = 0.0 ; int k = 0 ; for ( int kc = - kernelRadius ; kc <= kernelRadius ; kc ++ , k ++ ) { double value = values [ r + kc ] ; if ( ! isNovalue ( value ) ) { outputValue = outputValue + value * kernelData2D [ k ] ; kernelSum = kernelSum + kernelData2D [ k ] ; } } newValues [ r ] = outputValue / kernelSum ; } for ( int i = size - kernelRadius ; i < size ; i ++ ) { newValues [ i ] = values [ i ] ; } return newValues ; }
Smooth an array of values with a gaussian blur .
17,193
public static double [ ] averageSmooth ( double [ ] values , int lookAhead ) throws Exception { int size = values . length ; double [ ] newValues = new double [ values . length ] ; for ( int i = 0 ; i < lookAhead ; i ++ ) { newValues [ i ] = values [ i ] ; } for ( int i = lookAhead ; i < size - lookAhead ; i ++ ) { double sum = 0.0 ; int k = 0 ; for ( int l = - lookAhead ; l <= lookAhead ; l ++ ) { double value = values [ i + l ] ; if ( ! isNovalue ( value ) ) { sum = sum + value ; k ++ ; } } newValues [ i ] = sum / k ; } for ( int i = size - lookAhead ; i < size ; i ++ ) { newValues [ i ] = values [ i ] ; } return newValues ; }
Smooth an array of values with an averaging moving window .
17,194
public Coordinate wgs84ToEnu ( Coordinate cLL ) { checkZ ( cLL ) ; Coordinate cEcef = wgs84ToEcef ( cLL ) ; Coordinate enu = ecefToEnu ( cEcef ) ; return enu ; }
Converts the wgs84 coordinate to ENU .
17,195
public Coordinate enuToWgs84 ( Coordinate enu ) { checkZ ( enu ) ; Coordinate cEcef = enuToEcef ( enu ) ; Coordinate wgs84 = ecefToWgs84 ( cEcef ) ; return wgs84 ; }
Converts the ENU coordinate to wgs84 .
17,196
public void convertGeometryFromEnuToWgs84 ( Geometry geometryEnu ) { Coordinate [ ] coordinates = geometryEnu . getCoordinates ( ) ; for ( int i = 0 ; i < coordinates . length ; i ++ ) { Coordinate wgs84 = enuToWgs84 ( coordinates [ i ] ) ; coordinates [ i ] . x = wgs84 . x ; coordinates [ i ] . y = wgs84 . y ; coordinates [ i ] . z = wgs84 . z ; } }
Converts a geometry from ENU to WGS .
17,197
public void convertGeometryFromWgsToEnu ( Geometry geometryWgs ) { Coordinate [ ] coordinates = geometryWgs . getCoordinates ( ) ; for ( int i = 0 ; i < coordinates . length ; i ++ ) { Coordinate enu = wgs84ToEnu ( coordinates [ i ] ) ; coordinates [ i ] . x = enu . x ; coordinates [ i ] . y = enu . y ; coordinates [ i ] . z = enu . z ; } }
Converts a geometry from WGS to ENU .
17,198
public Envelope convertEnvelopeFromWgsToEnu ( Envelope envelopeWgs ) { Polygon polygonEnu = GeometryUtilities . createPolygonFromEnvelope ( envelopeWgs ) ; convertGeometryFromWgsToEnu ( polygonEnu ) ; Envelope envelopeEnu = polygonEnu . getEnvelopeInternal ( ) ; return envelopeEnu ; }
Converts an envelope from WGS to ENU .
17,199
public synchronized Position goTo ( Double lon , Double lat , Double elev , Double azimuth , boolean animate ) { View view = getWwd ( ) . getView ( ) ; view . stopAnimations ( ) ; view . stopMovement ( ) ; Position eyePosition ; if ( lon == null || lat == null ) { Position currentEyePosition = wwd . getView ( ) . getCurrentEyePosition ( ) ; if ( currentEyePosition != null ) { lat = currentEyePosition . latitude . degrees ; lon = currentEyePosition . longitude . degrees ; } else { return null ; } } if ( elev == null ) { elev = wwd . getView ( ) . getCurrentEyePosition ( ) . getAltitude ( ) ; } if ( Double . isNaN ( elev ) ) { if ( ! Double . isNaN ( lastElevation ) ) { elev = lastElevation ; } else { elev = NwwUtilities . DEFAULT_ELEV ; } } eyePosition = NwwUtilities . toPosition ( lat , lon , elev ) ; if ( animate ) { view . goTo ( eyePosition , elev ) ; } else { view . setEyePosition ( eyePosition ) ; } if ( azimuth != null ) { Angle heading = Angle . fromDegrees ( azimuth ) ; view . setHeading ( heading ) ; } lastElevation = elev ; return eyePosition ; }
Move to a given location .