idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
17,000 | public static Polygon createDummyPolygon ( ) { Coordinate [ ] c = new Coordinate [ ] { new Coordinate ( 0.0 , 0.0 ) , new Coordinate ( 1.0 , 1.0 ) , new Coordinate ( 1.0 , 0.0 ) , new Coordinate ( 0.0 , 0.0 ) } ; LinearRing linearRing = gf ( ) . createLinearRing ( c ) ; return gf ( ) . createPolygon ( linearRing , null ) ; } | Creates a polygon that may help out as placeholder . |
17,001 | public static LineString createDummyLine ( ) { Coordinate [ ] c = new Coordinate [ ] { new Coordinate ( 0.0 , 0.0 ) , new Coordinate ( 1.0 , 1.0 ) , new Coordinate ( 1.0 , 0.0 ) } ; LineString lineString = gf ( ) . createLineString ( c ) ; return lineString ; } | Creates a line that may help out as placeholder . |
17,002 | public static double getPolygonArea ( int [ ] x , int [ ] y , int N ) { int i , j ; double area = 0 ; for ( i = 0 ; i < N ; i ++ ) { j = ( i + 1 ) % N ; area += x [ i ] * y [ j ] ; area -= y [ i ] * x [ j ] ; } area /= 2 ; return ( area < 0 ? - area : area ) ; } | Calculates the area of a polygon from its vertices . |
17,003 | public static double distance3d ( Coordinate c1 , Coordinate c2 , GeodeticCalculator geodeticCalculator ) { if ( Double . isNaN ( c1 . z ) || Double . isNaN ( c2 . z ) ) { throw new IllegalArgumentException ( "Missing elevation information in the supplied coordinates." ) ; } double deltaElev = Math . abs ( c1 . z - c2 . z ) ; double projectedDistance ; if ( geodeticCalculator != null ) { geodeticCalculator . setStartingGeographicPoint ( c1 . x , c1 . y ) ; geodeticCalculator . setDestinationGeographicPoint ( c2 . x , c2 . y ) ; projectedDistance = geodeticCalculator . getOrthodromicDistance ( ) ; } else { projectedDistance = c1 . distance ( c2 ) ; } double distance = NumericsUtilities . pythagoras ( projectedDistance , deltaElev ) ; return distance ; } | Calculates the 3d distance between two coordinates that have an elevation information . |
17,004 | public static Polygon lines2Polygon ( boolean checkValid , LineString ... lines ) { List < Coordinate > coordinatesList = new ArrayList < Coordinate > ( ) ; List < LineString > linesList = new ArrayList < LineString > ( ) ; for ( LineString tmpLine : lines ) { linesList . add ( tmpLine ) ; } LineString currentLine = linesList . get ( 0 ) ; linesList . remove ( 0 ) ; while ( linesList . size ( ) > 0 ) { Coordinate [ ] coordinates = currentLine . getCoordinates ( ) ; List < Coordinate > tmpList = Arrays . asList ( coordinates ) ; coordinatesList . addAll ( tmpList ) ; Point thePoint = currentLine . getEndPoint ( ) ; double minDistance = Double . MAX_VALUE ; LineString minDistanceLine = null ; boolean needFlip = false ; for ( LineString tmpLine : linesList ) { Point tmpStartPoint = tmpLine . getStartPoint ( ) ; double distance = thePoint . distance ( tmpStartPoint ) ; if ( distance < minDistance ) { minDistance = distance ; minDistanceLine = tmpLine ; needFlip = false ; } Point tmpEndPoint = tmpLine . getEndPoint ( ) ; distance = thePoint . distance ( tmpEndPoint ) ; if ( distance < minDistance ) { minDistance = distance ; minDistanceLine = tmpLine ; needFlip = true ; } } linesList . remove ( minDistanceLine ) ; if ( needFlip ) { minDistanceLine = ( LineString ) minDistanceLine . reverse ( ) ; } currentLine = minDistanceLine ; } Coordinate [ ] coordinates = currentLine . getCoordinates ( ) ; List < Coordinate > tmpList = Arrays . asList ( coordinates ) ; coordinatesList . addAll ( tmpList ) ; coordinatesList . add ( coordinatesList . get ( 0 ) ) ; LinearRing linearRing = gf ( ) . createLinearRing ( coordinatesList . toArray ( new Coordinate [ 0 ] ) ) ; Polygon polygon = gf ( ) . createPolygon ( linearRing , null ) ; if ( checkValid ) { if ( ! polygon . isValid ( ) ) { return null ; } } return polygon ; } | Joins two lines to a polygon . |
17,005 | public static List < Coordinate > getCoordinatesAtInterval ( LineString line , double interval , boolean keepExisting , double startFrom , double endAt ) { if ( interval <= 0 ) { throw new IllegalArgumentException ( "Interval needs to be > 0." ) ; } double length = line . getLength ( ) ; if ( startFrom < 0 ) { startFrom = 0.0 ; } if ( endAt < 0 ) { endAt = length ; } List < Coordinate > coordinatesList = new ArrayList < Coordinate > ( ) ; LengthIndexedLine indexedLine = new LengthIndexedLine ( line ) ; Coordinate [ ] existingCoordinates = null ; double [ ] indexOfExisting = null ; if ( keepExisting ) { existingCoordinates = line . getCoordinates ( ) ; indexOfExisting = new double [ existingCoordinates . length ] ; int i = 0 ; for ( Coordinate coordinate : existingCoordinates ) { double indexOf = indexedLine . indexOf ( coordinate ) ; indexOfExisting [ i ] = indexOf ; i ++ ; } } double runningLength = startFrom ; int currentIndexOfexisting = 1 ; while ( runningLength < endAt ) { if ( keepExisting && currentIndexOfexisting < indexOfExisting . length - 1 && runningLength > indexOfExisting [ currentIndexOfexisting ] ) { coordinatesList . add ( existingCoordinates [ currentIndexOfexisting ] ) ; currentIndexOfexisting ++ ; continue ; } Coordinate extractedPoint = indexedLine . extractPoint ( runningLength ) ; coordinatesList . add ( extractedPoint ) ; runningLength = runningLength + interval ; } Coordinate extractedPoint = indexedLine . extractPoint ( endAt ) ; coordinatesList . add ( extractedPoint ) ; return coordinatesList ; } | Returns the coordinates at a given interval along the line . |
17,006 | public static List < LineString > getSectionsAtInterval ( LineString line , double interval , double width , double startFrom , double endAt ) { if ( interval <= 0 ) { throw new IllegalArgumentException ( "Interval needs to be > 0." ) ; } double length = line . getLength ( ) ; if ( startFrom < 0 ) { startFrom = 0.0 ; } if ( endAt < 0 ) { endAt = length ; } double halfWidth = width / 2.0 ; List < LineString > linesList = new ArrayList < LineString > ( ) ; LengthIndexedLine indexedLine = new LengthIndexedLine ( line ) ; double runningLength = startFrom ; while ( runningLength < endAt ) { Coordinate centerCoordinate = indexedLine . extractPoint ( runningLength ) ; Coordinate leftCoordinate = indexedLine . extractPoint ( runningLength , - halfWidth ) ; Coordinate rightCoordinate = indexedLine . extractPoint ( runningLength , halfWidth ) ; LineString lineString = geomFactory . createLineString ( new Coordinate [ ] { leftCoordinate , centerCoordinate , rightCoordinate } ) ; linesList . add ( lineString ) ; runningLength = runningLength + interval ; } Coordinate centerCoordinate = indexedLine . extractPoint ( endAt ) ; Coordinate leftCoordinate = indexedLine . extractPoint ( endAt , - halfWidth ) ; Coordinate rightCoordinate = indexedLine . extractPoint ( endAt , halfWidth ) ; LineString lineString = geomFactory . createLineString ( new Coordinate [ ] { leftCoordinate , centerCoordinate , rightCoordinate } ) ; linesList . add ( lineString ) ; return linesList ; } | Returns the section line at a given interval along the line . |
17,007 | public static void scaleToRatio ( Rectangle2D fixed , Rectangle2D toScale , boolean doShrink ) { double origWidth = fixed . getWidth ( ) ; double origHeight = fixed . getHeight ( ) ; double toAdaptWidth = toScale . getWidth ( ) ; double toAdaptHeight = toScale . getHeight ( ) ; double scaleWidth = 0 ; double scaleHeight = 0 ; scaleWidth = toAdaptWidth / origWidth ; scaleHeight = toAdaptHeight / origHeight ; double scaleFactor ; if ( doShrink ) { scaleFactor = Math . min ( scaleWidth , scaleHeight ) ; } else { scaleFactor = Math . max ( scaleWidth , scaleHeight ) ; } double newWidth = origWidth * scaleFactor ; double newHeight = origHeight * scaleFactor ; double dw = ( toAdaptWidth - newWidth ) / 2.0 ; double dh = ( toAdaptHeight - newHeight ) / 2.0 ; double newX = toScale . getX ( ) + dw ; double newY = toScale . getY ( ) + dh ; double newW = toAdaptWidth - 2 * dw ; double newH = toAdaptHeight - 2 * dh ; toScale . setRect ( newX , newY , newW , newH ) ; } | Extends or shrinks a rectangle following the ration of a fixed one . |
17,008 | public static void scaleDownToFit ( Rectangle2D rectToFitIn , Rectangle2D toScale ) { double fitWidth = rectToFitIn . getWidth ( ) ; double fitHeight = rectToFitIn . getHeight ( ) ; double toScaleWidth = toScale . getWidth ( ) ; double toScaleHeight = toScale . getHeight ( ) ; if ( toScaleWidth > fitWidth ) { double factor = toScaleWidth / fitWidth ; toScaleWidth = fitWidth ; toScaleHeight = toScaleHeight / factor ; } if ( toScaleHeight > fitHeight ) { double factor = toScaleHeight / fitHeight ; toScaleHeight = fitHeight ; toScaleWidth = toScaleWidth / factor ; } toScale . setRect ( 0 , 0 , toScaleWidth , toScaleHeight ) ; } | Scales a rectangle down to fit inside the given one keeping the ratio . |
17,009 | public static Coordinate getLineWithPlaneIntersection ( Coordinate lC1 , Coordinate lC2 , Coordinate pC1 , Coordinate pC2 , Coordinate pC3 ) { double [ ] p = getPlaneCoefficientsFrom3Points ( pC1 , pC2 , pC3 ) ; double denominator = p [ 0 ] * ( lC1 . x - lC2 . x ) + p [ 1 ] * ( lC1 . y - lC2 . y ) + p [ 2 ] * ( lC1 . z - lC2 . z ) ; if ( denominator == 0.0 ) { return null ; } double u = ( p [ 0 ] * lC1 . x + p [ 1 ] * lC1 . y + p [ 2 ] * lC1 . z + p [ 3 ] ) / denominator ; double x = lC1 . x + ( lC2 . x - lC1 . x ) * u ; double y = lC1 . y + ( lC2 . y - lC1 . y ) * u ; double z = lC1 . z + ( lC2 . z - lC1 . z ) * u ; return new Coordinate ( x , y , z ) ; } | Get the intersection coordinate between a line and plane . |
17,010 | public static double getAngleBetweenLinePlane ( Coordinate a , Coordinate d , Coordinate b , Coordinate c ) { double [ ] rAD = { d . x - a . x , d . y - a . y , d . z - a . z } ; double [ ] rDB = { b . x - d . x , b . y - d . y , b . z - d . z } ; double [ ] rDC = { c . x - d . x , c . y - d . y , c . z - d . z } ; double [ ] n = { rDB [ 1 ] * rDC [ 2 ] - rDC [ 1 ] * rDB [ 2 ] , - 1 * ( rDB [ 0 ] * rDC [ 2 ] - rDC [ 0 ] * rDB [ 2 ] ) , rDB [ 0 ] * rDC [ 1 ] - rDC [ 0 ] * rDB [ 1 ] } ; double cosNum = n [ 0 ] * rAD [ 0 ] + n [ 1 ] * rAD [ 1 ] + n [ 2 ] * rAD [ 2 ] ; double cosDen = sqrt ( n [ 0 ] * n [ 0 ] + n [ 1 ] * n [ 1 ] + n [ 2 ] * n [ 2 ] ) * sqrt ( rAD [ 0 ] * rAD [ 0 ] + rAD [ 1 ] * rAD [ 1 ] + rAD [ 2 ] * rAD [ 2 ] ) ; double cos90MinAlpha = abs ( cosNum / cosDen ) ; double alpha = 90.0 - toDegrees ( acos ( cos90MinAlpha ) ) ; return alpha ; } | Calculates the angle between line and plane . |
17,011 | public static double getAngleInTriangle ( double a , double b , double c ) { double angle = Math . acos ( ( a * a + b * b - c * c ) / ( 2.0 * a * b ) ) ; return angle ; } | Uses the cosine rule to find an angle in radiants of a triangle defined by the length of its sides . |
17,012 | public static double angleBetween3D ( Coordinate c1 , Coordinate c2 , Coordinate c3 ) { double a = distance3d ( c2 , c1 , null ) ; double b = distance3d ( c2 , c3 , null ) ; double c = distance3d ( c1 , c3 , null ) ; double angleInTriangle = getAngleInTriangle ( a , b , c ) ; double degrees = toDegrees ( angleInTriangle ) ; return degrees ; } | Calculates the angle in degrees between 3 3D coordinates . |
17,013 | @ SuppressWarnings ( "unchecked" ) public static List < LineString > mergeLinestrings ( List < LineString > multiLines ) { LineMerger lineMerger = new LineMerger ( ) ; for ( int i = 0 ; i < multiLines . size ( ) ; i ++ ) { Geometry line = multiLines . get ( i ) ; lineMerger . add ( line ) ; } Collection < Geometry > merged = lineMerger . getMergedLineStrings ( ) ; List < LineString > mergedList = new ArrayList < > ( ) ; for ( Geometry geom : merged ) { mergedList . add ( ( LineString ) geom ) ; } return mergedList ; } | Tries to merge multilines when they are snapped properly . |
17,014 | public static List < Polygon > createSimpleDirectionArrow ( Geometry ... geometries ) { List < Polygon > polygons = new ArrayList < > ( ) ; for ( Geometry geometry : geometries ) { for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Geometry geometryN = geometry . getGeometryN ( i ) ; if ( geometryN instanceof LineString ) { LineString line = ( LineString ) geometryN ; polygons . addAll ( makeArrows ( line ) ) ; } else if ( geometryN instanceof Polygon ) { Polygon polygonGeom = ( Polygon ) geometryN ; LineString exteriorRing = polygonGeom . getExteriorRing ( ) ; polygons . addAll ( makeArrows ( exteriorRing ) ) ; int numInteriorRing = polygonGeom . getNumInteriorRing ( ) ; for ( int j = 0 ; j < numInteriorRing ; j ++ ) { LineString interiorRingN = polygonGeom . getInteriorRingN ( j ) ; polygons . addAll ( makeArrows ( interiorRingN ) ) ; } } } } return polygons ; } | Creates simple arrow polygons in the direction of the coordinates . |
17,015 | public boolean overlaps ( Location location ) { if ( location . getBeginPosition ( ) >= getBeginPosition ( ) && location . getBeginPosition ( ) <= getEndPosition ( ) ) return true ; if ( location . getBeginPosition ( ) <= getBeginPosition ( ) && location . getEndPosition ( ) >= getBeginPosition ( ) ) return true ; else { return false ; } } | 6361 .. 6539 6363 .. 6649 |
17,016 | private void fixRowsAndCols ( ) { rows = ( int ) Math . round ( ( north - south ) / ns_res ) ; if ( rows < 1 ) rows = 1 ; cols = ( int ) Math . round ( ( east - west ) / we_res ) ; if ( cols < 1 ) cols = 1 ; } | calculates rows and cols from the region and its resolution . |
17,017 | private double degreeToNumber ( String value ) { double number = - 1 ; String [ ] valueSplit = value . trim ( ) . split ( ":" ) ; if ( valueSplit . length == 3 ) { double deg = Double . parseDouble ( valueSplit [ 0 ] ) ; double min = Double . parseDouble ( valueSplit [ 1 ] ) ; double sec = Double . parseDouble ( valueSplit [ 2 ] ) ; number = deg + min / 60.0 + sec / 60.0 / 60.0 ; } else if ( valueSplit . length == 2 ) { double deg = Double . parseDouble ( valueSplit [ 0 ] ) ; double min = Double . parseDouble ( valueSplit [ 1 ] ) ; number = deg + min / 60.0 ; } else if ( valueSplit . length == 1 ) { number = Double . parseDouble ( valueSplit [ 0 ] ) ; } return number ; } | Transforms degree string into the decimal value . |
17,018 | private double [ ] xyResStringToNumbers ( String ewres , String nsres ) { double xres = - 1.0 ; double yres = - 1.0 ; if ( ewres . indexOf ( ':' ) != - 1 ) { xres = degreeToNumber ( ewres ) ; } else { xres = Double . parseDouble ( ewres ) ; } if ( nsres . indexOf ( ':' ) != - 1 ) { yres = degreeToNumber ( nsres ) ; } else { yres = Double . parseDouble ( nsres ) ; } return new double [ ] { xres , yres } ; } | Transforms a GRASS resolution string in metric or degree to decimal . |
17,019 | @ SuppressWarnings ( "nls" ) private double [ ] nsewStringsToNumbers ( String north , String south , String east , String west ) { double no = - 1.0 ; double so = - 1.0 ; double ea = - 1.0 ; double we = - 1.0 ; if ( north . indexOf ( "N" ) != - 1 || north . indexOf ( "n" ) != - 1 ) { north = north . substring ( 0 , north . length ( ) - 1 ) ; no = degreeToNumber ( north ) ; } else if ( north . indexOf ( "S" ) != - 1 || north . indexOf ( "s" ) != - 1 ) { north = north . substring ( 0 , north . length ( ) - 1 ) ; no = - degreeToNumber ( north ) ; } else { no = Double . parseDouble ( north ) ; } if ( south . indexOf ( "N" ) != - 1 || south . indexOf ( "n" ) != - 1 ) { south = south . substring ( 0 , south . length ( ) - 1 ) ; so = degreeToNumber ( south ) ; } else if ( south . indexOf ( "S" ) != - 1 || south . indexOf ( "s" ) != - 1 ) { south = south . substring ( 0 , south . length ( ) - 1 ) ; so = - degreeToNumber ( south ) ; } else { so = Double . parseDouble ( south ) ; } if ( west . indexOf ( "E" ) != - 1 || west . indexOf ( "e" ) != - 1 ) { west = west . substring ( 0 , west . length ( ) - 1 ) ; we = degreeToNumber ( west ) ; } else if ( west . indexOf ( "W" ) != - 1 || west . indexOf ( "w" ) != - 1 ) { west = west . substring ( 0 , west . length ( ) - 1 ) ; we = - degreeToNumber ( west ) ; } else { we = Double . parseDouble ( west ) ; } if ( east . indexOf ( "E" ) != - 1 || east . indexOf ( "e" ) != - 1 ) { east = east . substring ( 0 , east . length ( ) - 1 ) ; ea = degreeToNumber ( east ) ; } else if ( east . indexOf ( "W" ) != - 1 || east . indexOf ( "w" ) != - 1 ) { east = east . substring ( 0 , east . length ( ) - 1 ) ; ea = - degreeToNumber ( east ) ; } else { ea = Double . parseDouble ( east ) ; } return new double [ ] { no , so , ea , we } ; } | Transforms the GRASS bounds strings in metric or degree to decimal . |
17,020 | public int read ( ) throws IOException { if ( lookaheadChar == UNDEFINED ) { lookaheadChar = super . read ( ) ; } lastChar = lookaheadChar ; if ( super . ready ( ) ) { lookaheadChar = super . read ( ) ; } else { lookaheadChar = UNDEFINED ; } if ( lastChar == '\n' ) { lineCounter ++ ; } return lastChar ; } | Reads the next char from the input stream . |
17,021 | public int read ( char [ ] buf , int off , int len ) throws IOException { if ( len == 0 ) { return 0 ; } if ( lookaheadChar == UNDEFINED ) { if ( ready ( ) ) { lookaheadChar = super . read ( ) ; } else { return - 1 ; } } if ( lookaheadChar == - 1 ) { return - 1 ; } int cOff = off ; while ( len > 0 && ready ( ) ) { if ( lookaheadChar == - 1 ) { return cOff - off ; } else { buf [ cOff ++ ] = ( char ) lookaheadChar ; if ( lookaheadChar == '\n' ) { lineCounter ++ ; } lastChar = lookaheadChar ; lookaheadChar = super . read ( ) ; len -- ; } } return cOff - off ; } | Non - blocking reading of len chars into buffer buf starting at bufferposition off . |
17,022 | public long skip ( long n ) throws IllegalArgumentException , IOException { if ( lookaheadChar == UNDEFINED ) { lookaheadChar = super . read ( ) ; } if ( n < 0 ) { throw new IllegalArgumentException ( "negative argument not supported" ) ; } if ( n == 0 || lookaheadChar == END_OF_STREAM ) { return 0 ; } long skiped = 0 ; if ( n > 1 ) { skiped = super . skip ( n - 1 ) ; } lookaheadChar = super . read ( ) ; lineCounter = Integer . MIN_VALUE ; return skiped + 1 ; } | Skips char in the stream |
17,023 | public void sort ( double [ ] values , Object [ ] valuesToFollow ) { this . valuesToSort = values ; this . valuesToFollow = valuesToFollow ; number = values . length ; monitor . beginTask ( "Sorting..." , - 1 ) ; monitor . worked ( 1 ) ; quicksort ( 0 , number - 1 ) ; monitor . done ( ) ; } | Sorts an array of values and moves with the sort a second array . |
17,024 | private int [ ] [ ] createStationBasinsMatrix ( double [ ] statValues , int [ ] activeStationsPerBasin ) { int [ ] [ ] stationsBasins = new int [ stationCoordinates . size ( ) ] [ basinBaricenterCoordinates . size ( ) ] ; Set < Integer > bandsIdSet = bin2StationsListMap . keySet ( ) ; Integer [ ] bandsIdArray = ( Integer [ ] ) bandsIdSet . toArray ( new Integer [ bandsIdSet . size ( ) ] ) ; for ( int i = 0 ; i < basinBaricenterCoordinates . size ( ) ; i ++ ) { Coordinate basinBaricenterCoordinate = basinBaricenterCoordinates . get ( i ) ; int activeStationsForThisBasin = 0 ; for ( int j = 0 ; j < bandsIdArray . length ; j ++ ) { int bandId = bandsIdArray [ j ] ; List < Integer > stationIdsForBand = bin2StationsListMap . get ( bandId ) ; List < Integer > stationsToUse = extractStationsToUse ( basinBaricenterCoordinate , stationIdsForBand , stationId2CoordinateMap , statValues , stationid2StationindexMap ) ; if ( stationsToUse . size ( ) < pNum ) { pm . message ( "Found only " + stationsToUse . size ( ) + " for basin " + basinindex2basinidMap . get ( i ) + " and bandid " + bandId + "." ) ; } for ( Integer stationIdToEnable : stationsToUse ) { int stIndex = stationid2StationindexMap . get ( stationIdToEnable ) ; stationsBasins [ stIndex ] [ i ] = 1 ; } activeStationsForThisBasin = activeStationsForThisBasin + stationsToUse . size ( ) ; } activeStationsPerBasin [ i ] = activeStationsForThisBasin ; } return stationsBasins ; } | Creates the stations per basins matrix . |
17,025 | private void extractFromStationFeatures ( ) throws Exception { int stationIdIndex = - 1 ; int stationElevIndex = - 1 ; pm . beginTask ( "Filling the elevation and id arrays for the stations, ordering them in ascending elevation order." , stationCoordinates . size ( ) ) ; for ( int i = 0 ; i < stationCoordinates . size ( ) ; i ++ ) { pm . worked ( 1 ) ; SimpleFeature stationF = stationFeatures . get ( i ) ; Coordinate stationCoord = stationCoordinates . get ( i ) ; if ( stationIdIndex == - 1 ) { SimpleFeatureType featureType = stationF . getFeatureType ( ) ; stationIdIndex = featureType . indexOf ( fStationid ) ; stationElevIndex = featureType . indexOf ( fStationelev ) ; if ( stationIdIndex == - 1 ) { throw new IllegalArgumentException ( "Could not find the field: " + fStationid ) ; } if ( stationElevIndex == - 1 ) { throw new IllegalArgumentException ( "Could not find the field: " + fStationelev ) ; } } int id = ( ( Number ) stationF . getAttribute ( stationIdIndex ) ) . intValue ( ) ; double elev = ( ( Number ) stationF . getAttribute ( stationElevIndex ) ) . doubleValue ( ) ; statElev [ i ] = elev ; statId [ i ] = id ; stationId2CoordinateMap . put ( id , stationCoord ) ; } pm . done ( ) ; QuickSortAlgorithm qsA = new QuickSortAlgorithm ( pm ) ; qsA . sort ( statElev , statId ) ; } | Fills the elevation and id arrays for the stations ordering in ascending elevation order . |
17,026 | public int [ ] PixelsToTile ( int px , int py ) { int tx = ( int ) Math . ceil ( px / ( ( double ) tileSize ) - 1 ) ; int ty = ( int ) Math . ceil ( py / ( ( double ) tileSize ) - 1 ) ; return new int [ ] { tx , ty } ; } | Returns a tile covering region in given pixel coordinates |
17,027 | public int [ ] PixelsToRaster ( int px , int py , int zoom ) { int mapSize = tileSize << zoom ; return new int [ ] { px , mapSize - py } ; } | Move the origin of pixel coordinates to top - left corner |
17,028 | public int ZoomForPixelSize ( int pixelSize ) { for ( int i = 0 ; i < 30 ; i ++ ) { if ( pixelSize > Resolution ( i ) ) { if ( i != 0 ) { return i - 1 ; } else { return 0 ; } } } return 0 ; } | Maximal scaledown zoom of the pyramid closest to the pixelSize |
17,029 | public int [ ] GoogleTile ( double lat , double lon , int zoom ) { double [ ] meters = LatLonToMeters ( lat , lon ) ; int [ ] tile = MetersToTile ( meters [ 0 ] , meters [ 1 ] , zoom ) ; return this . GoogleTile ( tile [ 0 ] , tile [ 1 ] , zoom ) ; } | Converts a lat long coordinates to Google Tile Coordinates |
17,030 | public String QuadTree ( int tx , int ty , int zoom ) { String quadKey = "" ; ty = ( int ) ( ( Math . pow ( 2 , zoom ) - 1 ) - ty ) ; for ( int i = zoom ; i < 0 ; i -- ) { int digit = 0 ; int mask = 1 << ( i - 1 ) ; if ( ( tx & mask ) != 0 ) { digit += 1 ; } if ( ( ty & mask ) != 0 ) { digit += 2 ; } quadKey += ( digit + "" ) ; } return quadKey ; } | Converts TMS tile coordinates to Microsoft QuadTree |
17,031 | private void net ( WritableRandomIter hacksIter , WritableRandomIter netIter ) { pm . beginTask ( "Extraction of rivers of chosen order..." , nRows ) ; for ( int r = 0 ; r < nRows ; r ++ ) { for ( int c = 0 ; c < nCols ; c ++ ) { double value = hacksIter . getSampleDouble ( c , r , 0 ) ; if ( ! isNovalue ( value ) ) { if ( value <= hackOrder ) { netIter . setSample ( c , r , 0 , 2 ) ; } else { hacksIter . setSample ( c , r , 0 , HMConstants . doubleNovalue ) ; } } } pm . worked ( 1 ) ; } pm . done ( ) ; } | Return the map of the network with only the river of the choosen order . |
17,032 | public static ByteBuffer bytes ( String s , Charset charset ) { return ByteBuffer . wrap ( s . getBytes ( charset ) ) ; } | Encode a String in a ByteBuffer using the provided charset . |
17,033 | public void write ( Writer writer ) throws IOException { GFF3Writer . writeVersionPragma ( writer ) ; GFF3Writer . writeRegionPragma ( writer , entry . getPrimaryAccession ( ) , windowBeginPosition , windowEndPosition ) ; int ID = 0 ; if ( show . contains ( SHOW_GENE ) ) { locusTagGeneMap = new HashMap < String , GFF3Gene > ( ) ; geneNameGeneMap = new HashMap < String , GFF3Gene > ( ) ; } for ( Feature feature : entry . getFeatures ( ) ) { Long minPosition = feature . getLocations ( ) . getMinPosition ( ) ; Long maxPosition = feature . getLocations ( ) . getMaxPosition ( ) ; feature . getLocations ( ) . removeGlobalComplement ( ) ; String geneName = feature . getSingleQualifierValue ( Qualifier . GENE_QUALIFIER_NAME ) ; String locusTag = feature . getSingleQualifierValue ( Qualifier . LOCUS_TAG_QUALIFIER_NAME ) ; if ( show . contains ( SHOW_GENE ) ) { addGeneSegment ( geneName , locusTag , minPosition , maxPosition ) ; } if ( show . contains ( SHOW_FEATURE ) ) { ++ ID ; writeFeature ( writer , feature , geneName , locusTag , ID , minPosition , maxPosition ) ; for ( Location location : feature . getLocations ( ) . getLocations ( ) ) { int parentID = ID ; ++ ID ; writeFeatureSegment ( writer , feature , geneName , locusTag , location , parentID , ID ) ; } } } if ( show . contains ( SHOW_GENE ) ) { for ( GFF3Gene gene : locusTagGeneMap . values ( ) ) { ++ ID ; writeGene ( writer , gene , ID ) ; } for ( GFF3Gene gene : geneNameGeneMap . values ( ) ) { ++ ID ; writeGene ( writer , gene , ID ) ; } } if ( show . contains ( SHOW_CONTIG ) ) { Long contigPosition = 1L ; for ( Location location : entry . getSequence ( ) . getContigs ( ) ) { ++ ID ; contigPosition = writeContig ( writer , location , ID , contigPosition ) ; } } if ( show . contains ( SHOW_ASSEMBLY ) ) { for ( Assembly assembly : entry . getAssemblies ( ) ) { ++ ID ; writeAssembly ( writer , assembly , ID ) ; } } } | Writes the GFF3 file . |
17,034 | public static String trim ( String string , int pos ) { int len = string . length ( ) ; int leftPos = pos ; int rightPos = len ; for ( ; rightPos > 0 ; -- rightPos ) { char ch = string . charAt ( rightPos - 1 ) ; if ( ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r' ) { break ; } } for ( ; leftPos < rightPos ; ++ leftPos ) { char ch = string . charAt ( leftPos ) ; if ( ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r' ) { break ; } } if ( rightPos <= leftPos ) { return "" ; } return ( leftPos == 0 && rightPos == string . length ( ) ) ? string : string . substring ( leftPos , rightPos ) ; } | Removes all whitespace characters from the beginning and end of the string starting from the given position . |
17,035 | public static String trimRight ( String string ) { for ( int i = string . length ( ) ; i > 0 ; -- i ) { if ( string . charAt ( i - 1 ) != ' ' && string . charAt ( i - 1 ) != '\t' && string . charAt ( i - 1 ) != '\n' && string . charAt ( i - 1 ) != '\r' ) { return i == string . length ( ) ? string : string . substring ( 0 , i ) ; } } return "" ; } | Removes all whitespace characters from the end of the string . |
17,036 | public static String trimRight ( String string , int pos ) { int i = string . length ( ) ; for ( ; i > pos ; -- i ) { char charAt = string . charAt ( i - 1 ) ; if ( charAt != ' ' && charAt != '\t' && charAt != '\n' && charAt != '\r' ) { break ; } } if ( i <= pos ) { return "" ; } return ( 0 == pos && i == string . length ( ) ) ? string : string . substring ( pos , i ) ; } | Removes all whitespace characters from the end of the string starting from the given position . |
17,037 | public static String trimRight ( String string , char c ) { for ( int i = string . length ( ) ; i > 0 ; -- i ) { char charAt = string . charAt ( i - 1 ) ; if ( charAt != c && charAt != ' ' && charAt != '\t' && charAt != '\n' && charAt != '\r' ) { return i == string . length ( ) ? string : string . substring ( 0 , i ) ; } } return "" ; } | Removes all whitespace characters and instances of the given character from the end of the string . |
17,038 | public static String trimLeft ( String string ) { for ( int i = 0 ; i < string . length ( ) ; ++ i ) { char charAt = string . charAt ( i ) ; if ( charAt != ' ' && charAt != '\t' && charAt != '\n' && charAt != '\r' ) { return i == 0 ? string : string . substring ( i ) ; } } return string ; } | Removes all whitespace characters from the beginning of the string . |
17,039 | public static Vector < String > split ( String string , String regex ) { Vector < String > strings = new Vector < String > ( ) ; for ( String value : string . split ( new String ( regex ) ) ) { value = value . trim ( ) ; if ( ! value . equals ( "" ) ) { strings . add ( shrink ( value ) ) ; } } return strings ; } | Split the string into values using the regular expression removes whitespace from the beginning and end of the resultant strings and replaces runs of whitespace with a single space . |
17,040 | public static String shrink ( String string ) { if ( string == null ) { return null ; } string = string . trim ( ) ; return SHRINK . matcher ( string ) . replaceAll ( " " ) ; } | Trims the string and replaces runs of whitespace with a single space . |
17,041 | public static String shrink ( String string , char c ) { if ( string == null ) { return null ; } string = string . trim ( ) ; Pattern pattern = Pattern . compile ( "\\" + String . valueOf ( c ) + "{2,}" ) ; return pattern . matcher ( string ) . replaceAll ( String . valueOf ( c ) ) ; } | Trims the string and replaces runs of whitespace with a single character . |
17,042 | public static String remove ( String string , char c ) { return string . replaceAll ( String . valueOf ( c ) , "" ) ; } | Removes the characters from the string . |
17,043 | public static Date getYear ( String string ) { if ( string == null ) { return null ; } Date date = null ; try { date = ( ( SimpleDateFormat ) year . clone ( ) ) . parse ( string ) ; } catch ( ParseException ex ) { return null ; } return date ; } | Returns the year given a string in format yyyy . |
17,044 | private int getNeighbours ( int [ ] src1d , int i , int ox , int oy , int d_w , int d_h ) { int x , y , result ; x = ( i % d_w ) + ox ; y = ( i / d_w ) + oy ; if ( ( x < 0 ) || ( x >= d_w ) || ( y < 0 ) || ( y >= d_h ) ) { result = 0 ; } else { result = src1d [ y * d_w + x ] & 0x000000ff ; } return result ; } | getNeighbours will get the pixel value of i s neighbour that s ox and oy away from i if the point is outside the image then 0 is returned . This version gets from source image . |
17,045 | private int reduce ( int a , int [ ] labels ) { if ( labels [ a ] == a ) { return a ; } else { return reduce ( labels [ a ] , labels ) ; } } | Reduces the number of labels . |
17,046 | public static boolean playsAll ( Role role , String ... r ) { if ( role == null ) { return false ; } for ( String s : r ) { if ( ! role . value ( ) . contains ( s ) ) { return false ; } } return true ; } | Checks if all roles are played . |
17,047 | public static boolean plays ( Role role , String r ) { if ( r == null ) { throw new IllegalArgumentException ( "null role" ) ; } if ( role == null ) { return false ; } return role . value ( ) . contains ( r ) ; } | Checks if one role is played . |
17,048 | public static boolean inRange ( Range range , double val ) { return val >= range . min ( ) && val <= range . max ( ) ; } | Check if a certain value is in range |
17,049 | public void close ( ) { entry . close ( ) ; getBlockCounter ( ) . clear ( ) ; getSkipTagCounter ( ) . clear ( ) ; getCache ( ) . resetOrganismCache ( ) ; getCache ( ) . resetReferenceCache ( ) ; } | Release resources used by the reader . Help the GC to cleanup the heap |
17,050 | public static BufferedImage ByteBufferImage ( byte [ ] data , int width , int height ) { int [ ] bandoffsets = { 0 , 1 , 2 , 3 } ; DataBufferByte dbb = new DataBufferByte ( data , data . length ) ; WritableRaster wr = Raster . createInterleavedRaster ( dbb , width , height , width * 4 , 4 , bandoffsets , null ) ; int [ ] bitfield = { 8 , 8 , 8 , 8 } ; ColorSpace cs = ColorSpace . getInstance ( ColorSpace . CS_sRGB ) ; ColorModel cm = new ComponentColorModel ( cs , bitfield , true , false , Transparency . TRANSLUCENT , DataBuffer . TYPE_BYTE ) ; return new BufferedImage ( cm , wr , false , null ) ; } | create a buffered image from a set of color triplets |
17,051 | public static Window getRectangleAroundPoint ( Window activeRegion , double x , double y ) { double minx = activeRegion . getRectangle ( ) . getBounds2D ( ) . getMinX ( ) ; double ewres = activeRegion . getWEResolution ( ) ; double snapx = minx + ( Math . round ( ( x - minx ) / ewres ) * ewres ) ; double miny = activeRegion . getRectangle ( ) . getBounds2D ( ) . getMinY ( ) ; double nsres = activeRegion . getNSResolution ( ) ; double snapy = miny + ( Math . round ( ( y - miny ) / nsres ) * nsres ) ; double xmin = 0.0 ; double xmax = 0.0 ; double ymin = 0.0 ; double ymax = 0.0 ; if ( x >= snapx ) { xmin = snapx ; xmax = xmin + ewres ; } else { xmax = snapx ; xmin = xmax - ewres ; } if ( y <= snapy ) { ymax = snapy ; ymin = ymax - nsres ; } else { ymin = snapy ; ymax = ymin + nsres ; } return new Window ( xmin , xmax , ymin , ymax , 1 , 1 ) ; } | return the rectangle of the cell of the active region that surrounds the given coordinates |
17,052 | public static void rasterizePolygonGeometry ( Window active , Geometry polygon , RasterData raster , RasterData rasterToMap , double value , IHMProgressMonitor monitor ) { GeometryFactory gFactory = new GeometryFactory ( ) ; int rows = active . getRows ( ) ; int cols = active . getCols ( ) ; double delta = active . getWEResolution ( ) / 4.0 ; monitor . beginTask ( "rasterizing..." , rows ) ; for ( int i = 0 ; i < rows ; i ++ ) { monitor . worked ( 1 ) ; Coordinate west = rowColToCenterCoordinates ( active , i , 0 ) ; Coordinate east = rowColToCenterCoordinates ( active , i , cols - 1 ) ; LineString line = gFactory . createLineString ( new Coordinate [ ] { west , east } ) ; if ( polygon . intersects ( line ) ) { Geometry internalLines = polygon . intersection ( line ) ; Coordinate [ ] coords = internalLines . getCoordinates ( ) ; for ( int j = 0 ; j < coords . length ; j = j + 2 ) { Coordinate startC = new Coordinate ( coords [ j ] . x + delta , coords [ j ] . y ) ; Coordinate endC = new Coordinate ( coords [ j + 1 ] . x - delta , coords [ j + 1 ] . y ) ; int [ ] startcol = coordinateToNearestRowCol ( active , startC ) ; int [ ] endcol = coordinateToNearestRowCol ( active , endC ) ; if ( startcol == null || endcol == null ) { continue ; } for ( int k = startcol [ 1 ] ; k <= endcol [ 1 ] ; k ++ ) { if ( rasterToMap != null ) { raster . setValueAt ( i , k , rasterToMap . getValueAt ( i , k ) ) ; } else { raster . setValueAt ( i , k , value ) ; } } } } } } | Fill polygon areas mapping on a raster |
17,053 | public static boolean removeGrassRasterMap ( String mapsetPath , String mapName ) throws IOException { String mappaths [ ] = filesOfRasterMap ( mapsetPath , mapName ) ; for ( int j = 0 ; j < mappaths . length ; j ++ ) { File filetoremove = new File ( mappaths [ j ] ) ; if ( filetoremove . exists ( ) ) { if ( ! FileUtilities . deleteFileOrDir ( filetoremove ) ) { return false ; } } } return true ; } | Given the mapsetpath and the mapname the map is removed with all its accessor files |
17,054 | public static double [ ] rowColToNodeboundCoordinates ( Window active , int row , int col ) { double anorth = active . getNorth ( ) ; double awest = active . getWest ( ) ; double nsres = active . getNSResolution ( ) ; double ewres = active . getWEResolution ( ) ; double [ ] nsew = new double [ 4 ] ; nsew [ 0 ] = anorth - row * nsres ; nsew [ 1 ] = anorth - row * nsres - nsres ; nsew [ 2 ] = awest + col * ewres + ewres ; nsew [ 3 ] = awest + col * ewres ; return nsew ; } | Transforms row and column index of the active region into an array of the coordinates of the edgaes i . e . n s e w |
17,055 | public static double [ ] CalculateAcadExtrusion ( double [ ] coord_in , double [ ] xtru ) { double [ ] coord_out ; double dxt0 = 0D , dyt0 = 0D , dzt0 = 0D ; double dvx1 , dvx2 , dvx3 ; double dvy1 , dvy2 , dvy3 ; double dmod , dxt , dyt , dzt ; double aux = 1D / 64D ; double aux1 = Math . abs ( xtru [ 0 ] ) ; double aux2 = Math . abs ( xtru [ 1 ] ) ; dxt0 = coord_in [ 0 ] ; dyt0 = coord_in [ 1 ] ; dzt0 = coord_in [ 2 ] ; double xtruX , xtruY , xtruZ ; xtruX = xtru [ 0 ] ; xtruY = xtru [ 1 ] ; xtruZ = xtru [ 2 ] ; if ( ( aux1 < aux ) && ( aux2 < aux ) ) { dmod = Math . sqrt ( xtruZ * xtruZ + xtruX * xtruX ) ; dvx1 = xtruZ / dmod ; dvx2 = 0 ; dvx3 = - xtruX / dmod ; } else { dmod = Math . sqrt ( xtruY * xtruY + xtruX * xtruX ) ; dvx1 = - xtruY / dmod ; dvx2 = xtruX / dmod ; dvx3 = 0 ; } dvy1 = xtruY * dvx3 - xtruZ * dvx2 ; dvy2 = xtruZ * dvx1 - xtruX * dvx3 ; dvy3 = xtruX * dvx2 - xtruY * dvx1 ; dmod = Math . sqrt ( dvy1 * dvy1 + dvy2 * dvy2 + dvy3 * dvy3 ) ; dvy1 = dvy1 / dmod ; dvy2 = dvy2 / dmod ; dvy3 = dvy3 / dmod ; dxt = dvx1 * dxt0 + dvy1 * dyt0 + xtruX * dzt0 ; dyt = dvx2 * dxt0 + dvy2 * dyt0 + xtruY * dzt0 ; dzt = dvx3 * dxt0 + dvy3 * dyt0 + xtruZ * dzt0 ; coord_out = new double [ ] { dxt , dyt , dzt } ; dxt0 = 0 ; dyt0 = 0 ; dzt0 = 0 ; return coord_out ; } | Method that allows to apply the extrusion transformation of Autocad |
17,056 | public void deleteGeoTable ( String tableName ) throws Exception { String sql = "SELECT DropGeoTable('" + tableName + "');" ; try ( IHMStatement stmt = mConn . createStatement ( ) ) { stmt . execute ( sql ) ; } } | Delete a geo - table with all attached indexes and stuff . |
17,057 | public void runRawSqlToCsv ( String sql , File csvFile , boolean doHeader , String separator ) throws Exception { try ( BufferedWriter bw = new BufferedWriter ( new FileWriter ( csvFile ) ) ) { SpatialiteWKBReader wkbReader = new SpatialiteWKBReader ( ) ; try ( IHMStatement stmt = mConn . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( sql ) ) { IHMResultSetMetaData rsmd = rs . getMetaData ( ) ; int columnCount = rsmd . getColumnCount ( ) ; int geometryIndex = - 1 ; for ( int i = 1 ; i <= columnCount ; i ++ ) { if ( i > 1 ) { bw . write ( separator ) ; } String columnTypeName = rsmd . getColumnTypeName ( i ) ; String columnName = rsmd . getColumnName ( i ) ; bw . write ( columnName ) ; if ( ESpatialiteGeometryType . isGeometryName ( columnTypeName ) ) { geometryIndex = i ; } } bw . write ( "\n" ) ; while ( rs . next ( ) ) { for ( int j = 1 ; j <= columnCount ; j ++ ) { if ( j > 1 ) { bw . write ( separator ) ; } byte [ ] geomBytes = null ; if ( j == geometryIndex ) { geomBytes = rs . getBytes ( j ) ; } if ( geomBytes != null ) { try { Geometry geometry = wkbReader . read ( geomBytes ) ; bw . write ( geometry . toText ( ) ) ; } catch ( Exception e ) { Object object = rs . getObject ( j ) ; if ( object instanceof Clob ) { object = rs . getString ( j ) ; } if ( object != null ) { bw . write ( object . toString ( ) ) ; } else { bw . write ( "" ) ; } } } else { Object object = rs . getObject ( j ) ; if ( object instanceof Clob ) { object = rs . getString ( j ) ; } if ( object != null ) { bw . write ( object . toString ( ) ) ; } else { bw . write ( "" ) ; } } } bw . write ( "\n" ) ; } } } } | Execute a query from raw sql and put the result in a csv file . |
17,058 | public void read ( ) throws IOException { System . out . println ( "DwgFile.read() executed ..." ) ; setDwgVersion ( ) ; if ( dwgVersion . equals ( "R13" ) ) { dwgReader = new DwgFileV14Reader ( ) ; dwgReader . read ( this ) ; } else if ( dwgVersion . equals ( "R14" ) ) { dwgReader = new DwgFileV14Reader ( ) ; dwgReader . read ( this ) ; } else if ( dwgVersion . equals ( "R15" ) ) { dwgReader = new DwgFileV15Reader ( ) ; dwgReader . read ( this ) ; } else if ( dwgVersion . equals ( "Unknown" ) ) { throw new IOException ( "DWG version of the file is not supported." ) ; } } | Reads a DWG file and put its objects in the dwgObjects Vector This method is version independent |
17,059 | public void calculateCadModelDwgPolylines ( ) { for ( int i = 0 ; i < dwgObjects . size ( ) ; i ++ ) { DwgObject pol = ( DwgObject ) dwgObjects . get ( i ) ; if ( pol instanceof DwgPolyline2D ) { int flags = ( ( DwgPolyline2D ) pol ) . getFlags ( ) ; int firstHandle = ( ( DwgPolyline2D ) pol ) . getFirstVertexHandle ( ) ; int lastHandle = ( ( DwgPolyline2D ) pol ) . getLastVertexHandle ( ) ; Vector pts = new Vector ( ) ; Vector bulges = new Vector ( ) ; double [ ] pt = new double [ 3 ] ; for ( int j = 0 ; j < dwgObjects . size ( ) ; j ++ ) { DwgObject firstVertex = ( DwgObject ) dwgObjects . get ( j ) ; if ( firstVertex instanceof DwgVertex2D ) { int vertexHandle = firstVertex . getHandle ( ) ; if ( vertexHandle == firstHandle ) { int k = 0 ; while ( true ) { DwgObject vertex = ( DwgObject ) dwgObjects . get ( j + k ) ; int vHandle = vertex . getHandle ( ) ; if ( vertex instanceof DwgVertex2D ) { pt = ( ( DwgVertex2D ) vertex ) . getPoint ( ) ; pts . add ( new Point2D . Double ( pt [ 0 ] , pt [ 1 ] ) ) ; double bulge = ( ( DwgVertex2D ) vertex ) . getBulge ( ) ; bulges . add ( new Double ( bulge ) ) ; k ++ ; if ( vHandle == lastHandle && vertex instanceof DwgVertex2D ) { break ; } } else if ( vertex instanceof DwgSeqend ) { break ; } } } } } if ( pts . size ( ) > 0 ) { double [ ] bs = new double [ bulges . size ( ) ] ; for ( int j = 0 ; j < bulges . size ( ) ; j ++ ) { bs [ j ] = ( ( Double ) bulges . get ( j ) ) . doubleValue ( ) ; } ( ( DwgPolyline2D ) pol ) . setBulges ( bs ) ; Point2D [ ] points = new Point2D [ pts . size ( ) ] ; for ( int j = 0 ; j < pts . size ( ) ; j ++ ) { points [ j ] = ( Point2D ) pts . get ( j ) ; } ( ( DwgPolyline2D ) pol ) . setPts ( points ) ; } else { } } else if ( pol instanceof DwgPolyline3D ) { } else if ( pol instanceof DwgLwPolyline && ( ( DwgLwPolyline ) pol ) . getVertices ( ) != null ) { } } } | Configure the geometry of the polylines in a DWG file from the vertex list in this DWG file . This geometry is given by an array of Points Besides manage closed polylines and polylines with bulges in a GIS Data model . It means that the arcs of the polylines will be done through a curvature parameter called bulge associated with the points of the polyline . |
17,060 | public void blockManagement ( ) { Vector dwgObjectsWithoutBlocks = new Vector ( ) ; boolean addingToBlock = false ; for ( int i = 0 ; i < dwgObjects . size ( ) ; i ++ ) { try { DwgObject entity = ( DwgObject ) dwgObjects . get ( i ) ; if ( entity instanceof DwgArc && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgEllipse && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgCircle && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgPolyline2D && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgPolyline3D && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgLwPolyline && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgSolid && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgLine && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgPoint && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgMText && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgText && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgAttrib && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgAttdef && ! addingToBlock ) { dwgObjectsWithoutBlocks . add ( entity ) ; } else if ( entity instanceof DwgBlock ) { addingToBlock = true ; } else if ( entity instanceof DwgEndblk ) { addingToBlock = false ; } else if ( entity instanceof DwgBlockHeader ) { addingToBlock = true ; } else if ( entity instanceof DwgInsert && ! addingToBlock ) { } else { } } catch ( StackOverflowError e ) { e . printStackTrace ( ) ; System . out . println ( "Overflowerror at object: " + i ) ; } } dwgObjects = dwgObjectsWithoutBlocks ; } | Modify the geometry of the objects contained in the blocks of a DWG file and add these objects to the DWG object list . |
17,061 | public void initializeLayerTable ( ) { layerTable = new Vector ( ) ; layerNames = new Vector ( ) ; for ( int i = 0 ; i < dwgObjects . size ( ) ; i ++ ) { DwgObject obj = ( DwgObject ) dwgObjects . get ( i ) ; if ( obj instanceof DwgLayer ) { Vector layerTableRecord = new Vector ( ) ; layerTableRecord . add ( new Integer ( obj . getHandle ( ) ) ) ; layerTableRecord . add ( ( ( DwgLayer ) obj ) . getName ( ) ) ; layerTableRecord . add ( new Integer ( ( ( DwgLayer ) obj ) . getColor ( ) ) ) ; layerTable . add ( layerTableRecord ) ; layerNames . add ( ( ( DwgLayer ) obj ) . getName ( ) ) ; } } System . out . println ( "" ) ; } | Initialize a new Vector that contains the DWG file layers . Each layer have three parameters . These parameters are handle name and color |
17,062 | public int getColorByLayer ( DwgObject entity ) { int colorByLayer = 0 ; int layer = entity . getLayerHandle ( ) ; for ( int j = 0 ; j < layerTable . size ( ) ; j ++ ) { Vector layerTableRecord = ( Vector ) layerTable . get ( j ) ; int lHandle = ( ( Integer ) layerTableRecord . get ( 0 ) ) . intValue ( ) ; if ( lHandle == layer ) { colorByLayer = ( ( Integer ) layerTableRecord . get ( 2 ) ) . intValue ( ) ; } } return colorByLayer ; } | Returns the color of the layer of a DWG object |
17,063 | public void addDwgSectionOffset ( String key , int seek , int size ) { DwgSectionOffset dso = new DwgSectionOffset ( key , seek , size ) ; dwgSectionOffsets . add ( dso ) ; } | Add a DWG section offset to the dwgSectionOffsets vector |
17,064 | public int getDwgSectionOffset ( String key ) { int offset = 0 ; for ( int i = 0 ; i < dwgSectionOffsets . size ( ) ; i ++ ) { DwgSectionOffset dso = ( DwgSectionOffset ) dwgSectionOffsets . get ( i ) ; String ikey = dso . getKey ( ) ; if ( key . equals ( ikey ) ) { offset = dso . getSeek ( ) ; break ; } } return offset ; } | Returns the offset of DWG section given by its key |
17,065 | public void addDwgObjectOffset ( int handle , int offset ) { DwgObjectOffset doo = new DwgObjectOffset ( handle , offset ) ; dwgObjectOffsets . add ( doo ) ; } | Add a DWG object offset to the dwgObjectOffsets vector |
17,066 | protected void initValidator ( ) throws SQLException , IOException { EmblEntryValidationPlanProperty emblEntryValidationPlanProperty = new EmblEntryValidationPlanProperty ( ) ; emblEntryValidationPlanProperty . validationScope . set ( ValidationScope . getScope ( fileType ) ) ; emblEntryValidationPlanProperty . isDevMode . set ( testMode ) ; emblEntryValidationPlanProperty . isFixMode . set ( fixMode || fixDiagnoseMode ) ; emblEntryValidationPlanProperty . minGapLength . set ( min_gap_length ) ; emblEntryValidationPlanProperty . isRemote . set ( remote ) ; emblEntryValidationPlanProperty . fileType . set ( fileType ) ; emblEntryValidationPlanProperty . enproConnection . set ( con ) ; emblValidator = new EmblEntryValidationPlan ( emblEntryValidationPlanProperty ) ; emblValidator . addMessageBundle ( ValidationMessageManager . STANDARD_VALIDATION_BUNDLE ) ; emblValidator . addMessageBundle ( ValidationMessageManager . STANDARD_FIXER_BUNDLE ) ; gff3Validator = new GFF3ValidationPlan ( emblEntryValidationPlanProperty ) ; gff3Validator . addMessageBundle ( ValidationMessageManager . GFF3_VALIDATION_BUNDLE ) ; gaValidator = new GenomeAssemblyValidationPlan ( emblEntryValidationPlanProperty ) ; gaValidator . addMessageBundle ( ValidationMessageManager . GENOMEASSEMBLY_VALIDATION_BUNDLE ) ; gaValidator . addMessageBundle ( ValidationMessageManager . GENOMEASSEMBLY_FIXER_BUNDLE ) ; initWriters ( ) ; } | Inits the validator . |
17,067 | protected void initWriters ( ) throws IOException { String summarywriter = prefix == null ? "VAL_SUMMARY.txt" : prefix + "_" + "VAL_SUMMARY.txt" ; String infowriter = prefix == null ? "VAL_INFO.txt" : prefix + "_" + "VAL_INFO.txt" ; String errorwriter = prefix == null ? "VAL_ERROR.txt" : prefix + "_" + "VAL_ERROR.txt" ; String reportswriter = prefix == null ? "VAL_REPORTS.txt" : prefix + "_" + "VAL_REPORTS.txt" ; String fixwriter = prefix == null ? "VAL_FIXES.txt" : prefix + "_" + "VAL_FIXES.txt" ; summaryWriter = new PrintWriter ( summarywriter , "UTF-8" ) ; infoWriter = new PrintWriter ( infowriter , "UTF-8" ) ; errorWriter = new PrintWriter ( errorwriter , "UTF-8" ) ; reportWriter = new PrintWriter ( reportswriter , "UTF-8" ) ; fixWriter = new PrintWriter ( fixwriter , "UTF-8" ) ; } | separate method to instantiate so unit tests can call this |
17,068 | private List < ValidationPlanResult > validateFile ( File file , Writer writer ) throws IOException { List < ValidationPlanResult > messages = new ArrayList < ValidationPlanResult > ( ) ; ArrayList < Object > entryList = new ArrayList < Object > ( ) ; BufferedReader fileReader = null ; try { fileReader = new BufferedReader ( new FileReader ( file ) ) ; prepareReader ( fileReader , file . getName ( ) ) ; List < ValidationPlanResult > results = validateEntriesInReader ( writer , file , entryList ) ; ValidationPlanResult entrySetResult = validateEntry ( entryList ) ; if ( file != null ) { entrySetResult . setTargetOrigin ( file . getName ( ) ) ; } for ( ValidationPlanResult planResult : results ) { messages . add ( planResult ) ; } if ( ! entrySetResult . isValid ( ) ) { writeResultsToFile ( entrySetResult ) ; messages . add ( entrySetResult ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( fileReader != null ) fileReader . close ( ) ; } return messages ; } | Validate file . |
17,069 | private void prepareReader ( BufferedReader fileReader , String fileId ) { switch ( fileType ) { case EMBL : EmblEntryReader emblReader = new EmblEntryReader ( fileReader , EmblEntryReader . Format . EMBL_FORMAT , fileId ) ; emblReader . setCheckBlockCounts ( lineCount ) ; reader = emblReader ; break ; case GENBANK : reader = new GenbankEntryReader ( fileReader , fileId ) ; break ; case GFF3 : reader = new GFF3FlatFileEntryReader ( fileReader ) ; break ; case FASTA : reader = new FastaFileReader ( new FastaLineReader ( fileReader ) ) ; break ; case AGP : reader = new AGPFileReader ( new AGPLineReader ( fileReader ) ) ; break ; default : System . exit ( 0 ) ; break ; } } | Prepare reader . |
17,070 | private void writeResultsToFile ( ValidationPlanResult planResult ) throws IOException { for ( ValidationResult result : planResult . getResults ( ) ) { if ( result instanceof ExtendedResult ) { ExtendedResult extendedResult = ( ExtendedResult ) result ; if ( extendedResult . getExtension ( ) instanceof CdsFeatureTranslationCheck . TranslationReportInfo ) { FlatFileValidations . setCDSTranslationReport ( ( ExtendedResult < CdsFeatureTranslationCheck . TranslationReportInfo > ) extendedResult ) ; } } } for ( ValidationResult result : planResult . getResults ( ) ) { result . writeMessages ( errorWriter , Severity . ERROR , planResult . getTargetOrigin ( ) ) ; result . writeMessages ( infoWriter , Severity . INFO , planResult . getTargetOrigin ( ) ) ; result . writeMessages ( infoWriter , Severity . WARNING , planResult . getTargetOrigin ( ) ) ; result . writeMessages ( fixWriter , Severity . FIX , planResult . getTargetOrigin ( ) ) ; errorWriter . flush ( ) ; infoWriter . flush ( ) ; fixWriter . flush ( ) ; } for ( ValidationResult result : planResult . getResults ( ) ) { if ( result . isHasReportMessage ( ) ) { result . setWriteReportMessage ( true ) ; result . writeMessages ( reportWriter ) ; } } } | Write results to file . |
17,071 | protected Object getNextEntryFromReader ( Writer writer ) { try { parseError = false ; ValidationResult parseResult = reader . read ( ) ; if ( parseResult . getMessages ( "FT.10" ) . size ( ) >= 1 && ( fixMode || fixDiagnoseMode ) ) { parseResult . removeMessage ( "FT.10" ) ; } if ( parseResult . count ( ) != 0 ) { parseResults . add ( parseResult ) ; writer . write ( "\n" ) ; for ( ValidationMessage < Origin > validationMessage : parseResult . getMessages ( ) ) { validationMessage . writeMessage ( writer ) ; } parseError = true ; } if ( ! reader . isEntry ( ) ) { return null ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } return reader . getEntry ( ) ; } | Gets the next entry from reader . |
17,072 | private void setNetworkPipes ( boolean isAreaNotAllDry ) throws Exception { int length = inPipes . size ( ) ; networkPipes = new Pipe [ length ] ; SimpleFeatureIterator stationsIter = inPipes . features ( ) ; boolean existOut = false ; int tmpOutIndex = 0 ; try { int t = 0 ; while ( stationsIter . hasNext ( ) ) { SimpleFeature feature = stationsIter . next ( ) ; try { Number field = ( ( Number ) feature . getAttribute ( TrentoPFeatureType . ID_STR ) ) ; if ( field == null ) { pm . errorMessage ( msg . message ( "trentoP.error.number" ) + TrentoPFeatureType . ID_STR ) ; throw new IllegalArgumentException ( msg . message ( "trentoP.error.number" ) + TrentoPFeatureType . ID_STR ) ; } if ( field . equals ( pOutPipe ) ) { tmpOutIndex = t ; existOut = true ; } networkPipes [ t ] = new Pipe ( feature , pMode , isAreaNotAllDry , pm ) ; t ++ ; } catch ( NullPointerException e ) { pm . errorMessage ( msg . message ( "trentop.illegalNet" ) ) ; throw new IllegalArgumentException ( msg . message ( "trentop.illegalNet" ) ) ; } } } finally { stationsIter . close ( ) ; } if ( ! existOut ) { } networkPipes [ tmpOutIndex ] . setIdPipeWhereDrain ( 0 ) ; networkPipes [ tmpOutIndex ] . setIndexPipeWhereDrain ( - 1 ) ; int numberOfPoint = networkPipes [ tmpOutIndex ] . point . length - 1 ; findIdThatDrainsIntoIndex ( tmpOutIndex , networkPipes [ tmpOutIndex ] . point [ 0 ] ) ; findIdThatDrainsIntoIndex ( tmpOutIndex , networkPipes [ tmpOutIndex ] . point [ numberOfPoint ] ) ; List < Integer > missingId = new ArrayList < Integer > ( ) ; for ( Pipe pipe : networkPipes ) { if ( pipe . getIdPipeWhereDrain ( ) == null && pipe . getId ( ) != pOutPipe ) { missingId . add ( pipe . getId ( ) ) ; } } if ( missingId . size ( ) > 0 ) { String errorMsg = "One of the following pipes doesn't have a connected pipe towards the outlet: " + Arrays . toString ( missingId . toArray ( new Integer [ 0 ] ) ) ; pm . errorMessage ( msg . message ( errorMsg ) ) ; throw new IllegalArgumentException ( errorMsg ) ; } verifyNet ( networkPipes , pm ) ; } | Initializating the array . |
17,073 | public void verifyNet ( Pipe [ ] networkPipes , IHMProgressMonitor pm ) { boolean isOut = false ; if ( networkPipes != null ) { int length = networkPipes . length ; int kj ; for ( int i = 0 ; i < length ; i ++ ) { if ( networkPipes [ i ] . getIdPipeWhereDrain ( ) == 0 ) { isOut = true ; } if ( networkPipes [ i ] . getIndexPipeWhereDrain ( ) > length ) { pm . errorMessage ( msg . message ( "trentoP.error.pipe" ) ) ; throw new IllegalArgumentException ( msg . message ( "trentoP.error.pipe" ) ) ; } kj = i ; int count = 0 ; while ( networkPipes [ kj ] . getIdPipeWhereDrain ( ) != 0 ) { kj = networkPipes [ kj ] . getIndexPipeWhereDrain ( ) ; if ( kj > length ) { pm . errorMessage ( msg . message ( "trentoP.error.drainPipe" ) + kj ) ; throw new IllegalArgumentException ( msg . message ( "trentoP.error.drainPipe" ) + kj ) ; } count ++ ; if ( count > length ) { pm . errorMessage ( msg . message ( "trentoP.error.pipe" ) ) ; throw new IllegalArgumentException ( msg . message ( "trentoP.error.pipe" ) ) ; } } } if ( isOut == false ) { pm . errorMessage ( msg . message ( "trentoP.error.noout" ) ) ; throw new IllegalArgumentException ( msg . message ( "trentoP.error.noout" ) ) ; } } else { throw new IllegalArgumentException ( msg . message ( "trentoP.error.incorrectmatrix" ) ) ; } } | Verify if the network is consistent . |
17,074 | public boolean joinLine ( ) { if ( ! isCurrentLine ( ) ) { return false ; } if ( ! isNextLine ( ) ) { return false ; } if ( ! isNextTag ( ) ) { return true ; } if ( ! isCurrentTag ( ) ) { return false ; } return getCurrentTag ( ) . equals ( getNextTag ( ) ) ; } | Returns true if the next and current lines can be joined together either because they have the same tag or because the next line does not have a tag . |
17,075 | public String getCurrentLine ( ) { if ( ! isCurrentLine ( ) ) { return null ; } if ( isTag ( currentLine ) ) return FlatFileUtils . trimRight ( currentLine , getTagWidth ( currentLine ) ) ; else return currentLine . trim ( ) ; } | Return current line without tag . |
17,076 | public String getNextLine ( ) { if ( ! isNextLine ( ) ) { return null ; } if ( isTag ( nextLine ) ) return FlatFileUtils . trimRight ( nextLine , getTagWidth ( nextLine ) ) ; else return nextLine . trim ( ) ; } | Return next line without tag . |
17,077 | public String getCurrentMaskedLine ( ) { if ( ! isCurrentLine ( ) ) { return null ; } StringBuilder str = new StringBuilder ( ) ; int tagWidth = getTagWidth ( currentLine ) ; for ( int i = 0 ; i < tagWidth ; ++ i ) { str . append ( " " ) ; } if ( currentLine . length ( ) > tagWidth ) { str . append ( currentLine . substring ( tagWidth ) ) ; } return str . toString ( ) ; } | Return current line with tag masked with whitespace . |
17,078 | public String getNextMaskedLine ( ) { if ( ! isNextLine ( ) ) { return null ; } StringBuilder str = new StringBuilder ( ) ; int tagWidth = getTagWidth ( nextLine ) ; for ( int i = 0 ; i < tagWidth ; ++ i ) { str . append ( " " ) ; } if ( nextLine . length ( ) > tagWidth ) { str . append ( nextLine . substring ( tagWidth ) ) ; } return str . toString ( ) ; } | Return next line with tag masked with whitespace . |
17,079 | public String getCurrentShrinkedLine ( ) { if ( ! isCurrentLine ( ) ) { return null ; } String string = FlatFileUtils . trim ( currentLine , getTagWidth ( currentLine ) ) ; if ( string . equals ( "" ) ) { return null ; } return FlatFileUtils . shrink ( string ) ; } | Shrink and return the current line without tag . |
17,080 | public void propertyChange ( PropertyChangeEvent evt ) { if ( "progress" == evt . getPropertyName ( ) ) { int progress = ( Integer ) evt . getNewValue ( ) ; progressMonitor . setProgress ( progress ) ; if ( progressMonitor . isCanceled ( ) || task . isDone ( ) ) { if ( progressMonitor . isCanceled ( ) ) { task . cancel ( true ) ; } } } if ( "progressText" == evt . getPropertyName ( ) ) { String progressText = ( String ) evt . getNewValue ( ) ; progressMonitor . setNote ( progressText ) ; if ( progressMonitor . isCanceled ( ) || task . isDone ( ) ) { if ( progressMonitor . isCanceled ( ) ) { task . cancel ( true ) ; } } } } | Invoked when task s progress property changes . |
17,081 | public double [ ] positionAt ( int col , int row ) { if ( isInRaster ( col , row ) ) { GridGeometry2D gridGeometry = getGridGeometry ( ) ; Coordinate coordinate = CoverageUtilities . coordinateFromColRow ( col , row , gridGeometry ) ; return new double [ ] { coordinate . x , coordinate . y } ; } return null ; } | Get world position from col row . |
17,082 | public int [ ] gridAt ( double x , double y ) { if ( isInRaster ( x , y ) ) { GridGeometry2D gridGeometry = getGridGeometry ( ) ; int [ ] colRowFromCoordinate = CoverageUtilities . colRowFromCoordinate ( new Coordinate ( x , y ) , gridGeometry , null ) ; return colRowFromCoordinate ; } return null ; } | Get grid col and row from a world coordinate . |
17,083 | public void setValueAt ( int col , int row , double value ) { if ( makeNew ) { if ( isInRaster ( col , row ) ) { ( ( WritableRandomIter ) iter ) . setSample ( col , row , 0 , value ) ; } else { throw new RuntimeException ( "Setting value outside of raster." ) ; } } else { throw new RuntimeException ( "Writing not allowed." ) ; } } | Sets a raster value if the raster is writable . |
17,084 | public double [ ] surrounding ( int col , int row ) { GridNode node = new GridNode ( iter , cols , rows , xRes , yRes , col , row ) ; List < GridNode > surroundingNodes = node . getSurroundingNodes ( ) ; double [ ] surr = new double [ 8 ] ; for ( int i = 0 ; i < surroundingNodes . size ( ) ; i ++ ) { GridNode gridNode = surroundingNodes . get ( i ) ; if ( gridNode != null ) { surr [ i ] = gridNode . elevation ; } else { surr [ i ] = HMConstants . doubleNovalue ; } } return surr ; } | Get the values of the surrounding cells . |
17,085 | public void write ( String path ) throws Exception { if ( makeNew ) { RasterWriter . writeRaster ( path , buildRaster ( ) ) ; } else { throw new RuntimeException ( "Only new rasters can be dumped." ) ; } } | Write the raster to file . |
17,086 | public static Raster read ( String path ) throws Exception { GridCoverage2D coverage2d = RasterReader . readRaster ( path ) ; Raster raster = new Raster ( coverage2d ) ; return raster ; } | Read a raster from file . |
17,087 | private void checkDuplicateTokens ( MutableTemplateInfo templateInfo ) throws TemplateException { List < String > allTokenNames = new ArrayList < String > ( ) ; for ( TemplateTokenInfo tokenInfo : templateInfo . tokenInfos ) { if ( allTokenNames . contains ( tokenInfo . getName ( ) ) ) { throw new TemplateException ( "Token name '" + tokenInfo . getName ( ) + "' duplicated in template '" + templateInfo . name + "'." ) ; } else { allTokenNames . add ( tokenInfo . getName ( ) ) ; } } } | throws error if a token name appears twice - will bail as soon as one duplicate is hit |
17,088 | private void processGroups ( MutableTemplateInfo template ) throws TemplateException { List < TemplateTokenGroupInfo > groupInfos = template . groupInfo ; List < String > allGroupTokens = new ArrayList < String > ( ) ; for ( TemplateTokenGroupInfo groupInfo : groupInfos ) { for ( String newToken : groupInfo . getContainsString ( ) ) { if ( allGroupTokens . contains ( newToken ) ) { throw new TemplateException ( "Token " + newToken + " in template group : '" + groupInfo . getName ( ) + "' already exists in another group" ) ; } else { allGroupTokens . add ( newToken ) ; } } } List < String > containsList = new ArrayList < String > ( ) ; for ( TemplateTokenInfo tokenInfo : template . tokenInfos ) { if ( ! allGroupTokens . contains ( tokenInfo . getName ( ) ) ) { containsList . add ( tokenInfo . getName ( ) ) ; } } if ( containsList . size ( ) != 0 ) { TemplateTokenGroupInfo allOthersGroup = new TemplateTokenGroupInfo ( null , containsList , "" , true ) ; template . groupInfo . add ( allOthersGroup ) ; } for ( TemplateTokenGroupInfo groupInfo : template . groupInfo ) { groupInfo . setParentGroups ( template . tokenInfos ) ; } } | creates a group containing all tokens not contained in any other sections - an all others group |
17,089 | public void shrink ( ) { if ( c . length == length ) { return ; } char [ ] newc = new char [ length ] ; System . arraycopy ( c , 0 , newc , 0 , length ) ; c = newc ; } | Shrinks the capacity of the buffer to the current length if necessary . This method involves copying the data once! |
17,090 | public StringBuffer toStringBuffer ( ) { StringBuffer sb = new StringBuffer ( length ) ; sb . append ( c , 0 , length ) ; return sb ; } | Converts the contents of the buffer into a StringBuffer . This method involves copying the new data once! |
17,091 | public static GridCoverage2D createSubCoverageFromTemplate ( GridCoverage2D template , Envelope2D subregion , Double value , WritableRaster [ ] writableRasterHolder ) { RegionMap regionMap = getRegionParamsFromGridCoverage ( template ) ; double xRes = regionMap . getXres ( ) ; double yRes = regionMap . getYres ( ) ; double west = subregion . getMinX ( ) ; double south = subregion . getMinY ( ) ; double east = subregion . getMaxX ( ) ; double north = subregion . getMaxY ( ) ; int cols = ( int ) ( ( east - west ) / xRes ) ; int rows = ( int ) ( ( north - south ) / yRes ) ; ComponentSampleModel sampleModel = new ComponentSampleModel ( DataBuffer . TYPE_DOUBLE , cols , rows , 1 , cols , new int [ ] { 0 } ) ; WritableRaster writableRaster = RasterFactory . createWritableRaster ( sampleModel , null ) ; if ( value != null ) { double v = value ; for ( int y = 0 ; y < rows ; y ++ ) { for ( int x = 0 ; x < cols ; x ++ ) { writableRaster . setSample ( x , y , 0 , v ) ; } } } if ( writableRasterHolder != null ) writableRasterHolder [ 0 ] = writableRaster ; Envelope2D writeEnvelope = new Envelope2D ( template . getCoordinateReferenceSystem ( ) , west , south , east - west , north - south ) ; GridCoverageFactory factory = CoverageFactoryFinder . getGridCoverageFactory ( null ) ; GridCoverage2D coverage2D = factory . create ( "newraster" , writableRaster , writeEnvelope ) ; return coverage2D ; } | Create a subcoverage given a template coverage and an envelope . |
17,092 | public static int [ ] getRegionColsRows ( GridCoverage2D gridCoverage ) { GridGeometry2D gridGeometry = gridCoverage . getGridGeometry ( ) ; GridEnvelope2D gridRange = gridGeometry . getGridRange2D ( ) ; int height = gridRange . height ; int width = gridRange . width ; int [ ] params = new int [ ] { width , height } ; return params ; } | Get the array of rows and cols . |
17,093 | public static int [ ] getLoopColsRowsForSubregion ( GridCoverage2D gridCoverage , Envelope2D subregion ) throws Exception { GridGeometry2D gridGeometry = gridCoverage . getGridGeometry ( ) ; GridEnvelope2D subRegionGrid = gridGeometry . worldToGrid ( subregion ) ; int minCol = subRegionGrid . x ; int maxCol = subRegionGrid . x + subRegionGrid . width ; int minRow = subRegionGrid . y ; int maxRow = subRegionGrid . y + subRegionGrid . height ; return new int [ ] { minCol , maxCol , minRow , maxRow } ; } | Get the cols and rows ranges to use to loop the original gridcoverage . |
17,094 | public static int [ ] renderedImage2IntegerArray ( RenderedImage renderedImage , double multiply ) { int width = renderedImage . getWidth ( ) ; int height = renderedImage . getHeight ( ) ; int [ ] values = new int [ width * height ] ; RandomIter imageIter = RandomIterFactory . create ( renderedImage , null ) ; int index = 0 ; ; for ( int x = 0 ; x < width ; x ++ ) { for ( int y = 0 ; y < height ; y ++ ) { double sample = imageIter . getSampleDouble ( x , y , 0 ) ; sample = sample * multiply ; values [ index ++ ] = ( int ) sample ; } } imageIter . done ( ) ; return values ; } | Transform a double values rendered image in its integer array representation by scaling the values . |
17,095 | public static byte [ ] renderedImage2ByteArray ( RenderedImage renderedImage , boolean doRowsThenCols ) { int width = renderedImage . getWidth ( ) ; int height = renderedImage . getHeight ( ) ; byte [ ] values = new byte [ width * height ] ; RandomIter imageIter = RandomIterFactory . create ( renderedImage , null ) ; int index = 0 ; if ( doRowsThenCols ) { for ( int y = 0 ; y < height ; y ++ ) { for ( int x = 0 ; x < width ; x ++ ) { double sample = imageIter . getSampleDouble ( x , y , 0 ) ; values [ index ++ ] = ( byte ) sample ; } } } else { for ( int x = 0 ; x < width ; x ++ ) { for ( int y = 0 ; y < height ; y ++ ) { double sample = imageIter . getSampleDouble ( x , y , 0 ) ; values [ index ++ ] = ( byte ) sample ; } } } imageIter . done ( ) ; return values ; } | Transform a double values rendered image in its byte array . |
17,096 | public static void setNovalueBorder ( WritableRaster raster ) { int width = raster . getWidth ( ) ; int height = raster . getHeight ( ) ; for ( int c = 0 ; c < width ; c ++ ) { raster . setSample ( c , 0 , 0 , doubleNovalue ) ; raster . setSample ( c , height - 1 , 0 , doubleNovalue ) ; } for ( int r = 0 ; r < height ; r ++ ) { raster . setSample ( 0 , r , 0 , doubleNovalue ) ; raster . setSample ( width - 1 , r , 0 , doubleNovalue ) ; } } | Creates a border of novalues . |
17,097 | public static WritableRaster replaceNovalue ( RenderedImage renderedImage , double newValue ) { WritableRaster tmpWR = ( WritableRaster ) renderedImage . getData ( ) ; RandomIter pitTmpIterator = RandomIterFactory . create ( renderedImage , null ) ; int height = renderedImage . getHeight ( ) ; int width = renderedImage . getWidth ( ) ; for ( int y = 0 ; y < height ; y ++ ) { for ( int x = 0 ; x < width ; x ++ ) { if ( isNovalue ( pitTmpIterator . getSampleDouble ( x , y , 0 ) ) ) { tmpWR . setSample ( x , y , 0 , newValue ) ; } } } pitTmpIterator . done ( ) ; return tmpWR ; } | Replace the current internal novalue with a given value . |
17,098 | public static ROI prepareROI ( Geometry roi , AffineTransform mt2d ) throws Exception { Geometry rasterSpaceGeometry = JTS . transform ( roi , new AffineTransform2D ( mt2d . createInverse ( ) ) ) ; Geometry simplifiedGeometry = DouglasPeuckerSimplifier . simplify ( rasterSpaceGeometry , 1 ) ; return new ROIShape ( new FastLiteShape ( simplifiedGeometry ) ) ; } | Utility method for transforming a geometry ROI into the raster space using the provided affine transformation . |
17,099 | public static boolean isGrass ( String path ) { File file = new File ( path ) ; File cellFolderFile = file . getParentFile ( ) ; File mapsetFile = cellFolderFile . getParentFile ( ) ; File windFile = new File ( mapsetFile , "WIND" ) ; return cellFolderFile . getName ( ) . toLowerCase ( ) . equals ( "cell" ) && windFile . exists ( ) ; } | Checks if the given path is a GRASS raster file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.