idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
17,000 | 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 ; // We don't want to scale up } } } return 0 ; } | Maximal scaledown zoom of the pyramid closest to the pixelSize | 71 | 13 |
17,001 | 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 | 79 | 11 |
17,002 | 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 | 121 | 10 |
17,003 | private void net ( WritableRandomIter hacksIter , WritableRandomIter netIter ) { // calculates the max order of basin (max hackstream value) 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 the hack value is in the asked range * => keep it as net */ 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 . | 199 | 16 |
17,004 | public static ByteBuffer bytes ( String s , Charset charset ) { return ByteBuffer . wrap ( s . getBytes ( charset ) ) ; } | Encode a String in a ByteBuffer using the provided charset . | 33 | 14 |
17,005 | 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 ( ) ; // Remove global complement. 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 . | 556 | 8 |
17,006 | 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 != ' ' && ch != ' ' && ch != ' ' ) { break ; } } for ( ; leftPos < rightPos ; ++ leftPos ) { char ch = string . charAt ( leftPos ) ; if ( ch != ' ' && ch != ' ' && ch != ' ' && ch != ' ' ) { 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 . | 185 | 20 |
17,007 | public static String trimRight ( String string ) { for ( int i = string . length ( ) ; i > 0 ; -- i ) { if ( string . charAt ( i - 1 ) != ' ' && string . charAt ( i - 1 ) != ' ' && string . charAt ( i - 1 ) != ' ' && string . charAt ( i - 1 ) != ' ' ) { return i == string . length ( ) ? string : string . substring ( 0 , i ) ; } } return "" ; } | Removes all whitespace characters from the end of the string . | 111 | 13 |
17,008 | 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 != ' ' && charAt != ' ' && charAt != ' ' ) { 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 . | 117 | 18 |
17,009 | 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 != ' ' && charAt != ' ' && charAt != ' ' ) { 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 . | 105 | 19 |
17,010 | public static String trimLeft ( String string ) { for ( int i = 0 ; i < string . length ( ) ; ++ i ) { char charAt = string . charAt ( i ) ; if ( charAt != ' ' && charAt != ' ' && charAt != ' ' && charAt != ' ' ) { return i == 0 ? string : string . substring ( i ) ; } } return string ; } | Removes all whitespace characters from the beginning of the string . | 89 | 13 |
17,011 | 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 . | 81 | 32 |
17,012 | 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 . | 47 | 15 |
17,013 | 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 . | 78 | 15 |
17,014 | public static String remove ( String string , char c ) { return string . replaceAll ( String . valueOf ( c ) , "" ) ; } | Removes the characters from the string . | 30 | 8 |
17,015 | 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 . | 65 | 12 |
17,016 | 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 ; // d_w and d_h are assumed to be set to the y = ( i / d_w ) + oy ; // width and height of scr1d 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 . | 151 | 40 |
17,017 | private int reduce ( int a , int [ ] labels ) { if ( labels [ a ] == a ) { return a ; } else { return reduce ( labels [ a ] , labels ) ; } } | Reduces the number of labels . | 42 | 7 |
17,018 | 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 . | 57 | 8 |
17,019 | 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 . | 57 | 8 |
17,020 | public static boolean inRange ( Range range , double val ) { return val >= range . min ( ) && val <= range . max ( ) ; } | Check if a certain value is in range | 31 | 8 |
17,021 | 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 | 57 | 14 |
17,022 | 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 | 177 | 12 |
17,023 | 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 ; } // why do I have to put ymin, Rectangle requires the upper left // corner?????!!!! Is it a BUG // in the Rectangle2D class? or docu? // Rectangle2D rect = new Rectangle2D.Double(xmin, ymin, ewres, 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 | 365 | 15 |
17,024 | 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 ) ; //$NON-NLS-1$ for ( int i = 0 ; i < rows ; i ++ ) { monitor . worked ( 1 ) ; // do scan line to fill the polygon 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 ) { // vertex is outside of the region, ignore it continue ; } /* * the part in between has to be filled */ 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 | 496 | 9 |
17,025 | public static boolean removeGrassRasterMap ( String mapsetPath , String mapName ) throws IOException { // list of files to remove String mappaths [ ] = filesOfRasterMap ( mapsetPath , mapName ) ; // first delete the list above, which are just files 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 | 138 | 19 |
17,026 | 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 | 161 | 29 |
17,027 | 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 | 649 | 13 |
17,028 | 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 . | 60 | 12 |
17,029 | 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 ) { // write it as it comes 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 . | 526 | 17 |
17,030 | 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 | 189 | 22 |
17,031 | 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 ) { /* double[] p = ((DwgInsert) entity).getInsertionPoint(); Point2D point = new Point2D.Double(p[0], p[1]); double[] scale = ((DwgInsert) entity).getScale(); double rot = ((DwgInsert) entity).getRotation(); int blockHandle = ((DwgInsert) entity).getBlockHeaderHandle(); manageInsert(point, scale, rot, blockHandle, i, dwgObjectsWithoutBlocks);*/ } else { // System.out.println("Detectado dwgObject pendiente de implementar"); } } 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 . | 717 | 27 |
17,032 | 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 | 192 | 26 |
17,033 | 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 | 129 | 11 |
17,034 | 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 | 52 | 14 |
17,035 | 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 | 109 | 11 |
17,036 | 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 | 47 | 14 |
17,037 | 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 . | 400 | 6 |
17,038 | 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 | 256 | 12 |
17,039 | 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 . | 253 | 4 |
17,040 | 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 . | 191 | 4 |
17,041 | private void writeResultsToFile ( ValidationPlanResult planResult ) throws IOException { /** * first set any report messages (probably exceptional that the * translation report needs to get set outside the embl-api-core package * due to the need for embl-ff writers **/ 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 ) ; } } } // then look at writing the files 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 ) ; // turn report writing on for // this writer result . writeMessages ( reportWriter ) ; } } } | Write results to file . | 353 | 5 |
17,042 | 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" ) ; // writer fixes automatically if quotes are not given for qualifier value in fix/fix_diagnose mode. } 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 . | 209 | 8 |
17,043 | 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 { /* * extract the value of the ID which is the position (minus * 1) in the array. */ 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 ) { } // set the id where drain of the outlet. networkPipes [ tmpOutIndex ] . setIdPipeWhereDrain ( 0 ) ; networkPipes [ tmpOutIndex ] . setIndexPipeWhereDrain ( - 1 ) ; // start to construct the net. 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 . | 640 | 6 |
17,044 | public boolean joinLine ( ) { if ( ! isCurrentLine ( ) ) { return false ; } if ( ! isNextLine ( ) ) { return false ; } if ( ! isNextTag ( ) ) { return true ; // no next tag -> continue block } if ( ! isCurrentTag ( ) ) { return false ; // no current tag -> new block } // compare current and next tag 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 . | 100 | 30 |
17,045 | 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 . | 62 | 6 |
17,046 | 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 . | 62 | 6 |
17,047 | 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 . | 109 | 10 |
17,048 | 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 . | 109 | 10 |
17,049 | 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 . | 74 | 11 |
17,050 | public void propertyChange ( PropertyChangeEvent evt ) { if ( "progress" == evt . getPropertyName ( ) ) { int progress = ( Integer ) evt . getNewValue ( ) ; progressMonitor . setProgress ( progress ) ; // String message = String.format("Completed %d%%.\n", progress); // progressMonitor.setNote(message); 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 . | 209 | 9 |
17,051 | 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 . | 85 | 7 |
17,052 | 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 . | 90 | 10 |
17,053 | 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 . | 93 | 14 |
17,054 | 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 . | 150 | 8 |
17,055 | 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 . | 54 | 7 |
17,056 | 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 . | 51 | 7 |
17,057 | 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 | 127 | 19 |
17,058 | 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 ( ) ) ) { //if its not already in another group, add containsList . add ( tokenInfo . getName ( ) ) ; } } if ( containsList . size ( ) != 0 ) { TemplateTokenGroupInfo allOthersGroup = new TemplateTokenGroupInfo ( null , containsList , "" , true ) ; //this will have a group order of '0' by default and will appear at the top when sorted 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 | 324 | 18 |
17,059 | 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! | 53 | 23 |
17,060 | 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! | 38 | 21 |
17,061 | 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 ) { // autobox only once 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 . | 427 | 13 |
17,062 | 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 . | 98 | 9 |
17,063 | 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 . | 149 | 17 |
17,064 | 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 . | 156 | 16 |
17,065 | 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 . | 228 | 11 |
17,066 | 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 . | 148 | 8 |
17,067 | 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 . | 172 | 12 |
17,068 | public static ROI prepareROI ( Geometry roi , AffineTransform mt2d ) throws Exception { // transform the geometry to raster space so that we can use it as a ROI source Geometry rasterSpaceGeometry = JTS . transform ( roi , new AffineTransform2D ( mt2d . createInverse ( ) ) ) ; // simplify the geometry so that it's as precise as the coverage, excess coordinates // just make it slower to determine the point in polygon relationship Geometry simplifiedGeometry = DouglasPeuckerSimplifier . simplify ( rasterSpaceGeometry , 1 ) ; // build a shape using a fast point in polygon wrapper return new ROIShape ( new FastLiteShape ( simplifiedGeometry ) ) ; } | Utility method for transforming a geometry ROI into the raster space using the provided affine transformation . | 162 | 21 |
17,069 | 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 . | 95 | 14 |
17,070 | 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 ( ) ) ; //$NON-NLS-1$ return outCoverage ; } | Coverage merger . | 363 | 4 |
17,071 | 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 ( ) ; /* * calculate the maximum and minimum value of the raster data */ 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 ) ; } } /* * subdivide the whole value range in bins and count the number of pixels in each bin */ 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 . | 638 | 18 |
17,072 | 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 ) ; //$NON-NLS-1$ } } else { throw new IOException ( srcFolder + " is not a folder." ) ; } } | Compress a folder and its contents . | 121 | 8 |
17,073 | 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 . | 542 | 11 |
17,074 | 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 . | 46 | 10 |
17,075 | 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 in_ = new Thread(new Handler(stdin, // new OutputStreamWriter(process.getOutputStream()), latch)); 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 ( ) ; // in_.start(); try { latch . await ( ) ; exitValue = process . waitFor ( ) ; } catch ( InterruptedException e ) { // throw new RuntimeException(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 . | 430 | 12 |
17,076 | 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 | 39 | 13 |
17,077 | 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 . | 121 | 11 |
17,078 | 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 . | 70 | 7 |
17,079 | 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 . | 67 | 11 |
17,080 | 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 . | 64 | 7 |
17,081 | public static < T > T deSerializeFromDisk ( File file , Class < T > adaptee ) throws Exception { try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { long length = raf . length ( ) ; // System.out.println(length + "/" + (int) 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 . | 156 | 10 |
17,082 | 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 ; /* * some hardcoded variables */ boolean hasNoStations = false ; double zmes_T = 2.0 ; // quota misura temperatura,pressione e umidita' double zmes_U = 2.0 ; // quota misura velocita' vento [m] double z0T = 0.005 ; // [m] roughness length della temperatura double z0U = 0.05 ; // [m] roughness length del vento double K = ka * ka / ( ( log ( zmes_U / z0U ) ) * ( log ( zmes_T / z0T ) ) ) ; double eps = 0.98 ; // emissivita' neve double Lc = 0.05 ; // ritenzione capillare double Ksat = 3.0 ; // 5.55; // conducibilita' idraulica della neve a saturazione double Ks = 5.55E-5 ; // conducibilita' termica superficiale della neve double aep = 50.0 ; // albedo extinction parameter (kg/m2==mm) double rho_g = 1600 ; // densita' del suolo [kg/m3] double De = 0.4 ; // suolo termicamente attivo double C_g = 890.0 ; // capacita' termica del suolo [J/(kg K)] double albedo_land = 0.2 ; double Ts_min = - 20.0 ; double Ts_max = 20.0 ; // TODO check parameters and add to the model parameter latitude = 46.6 * Math . PI / 180.0 ; // [rad] longitude = 10.88 * Math . PI / 180.0 ; // [rad] standard_time = - 1.0 ; // differenza rispetto a UMT [h] /* * start calculations */ 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 . | 686 | 7 |
17,083 | public static BufferedReader getBufferedXMLReader ( InputStream stream , int xmlLookahead ) throws IOException { // create a buffer so we can reset the input stream BufferedInputStream input = new BufferedInputStream ( stream ) ; input . mark ( xmlLookahead ) ; // create object to hold encoding info EncodingInfo encoding = new EncodingInfo ( ) ; // call this method to set the encoding info XmlCharsetDetector . getCharsetAwareReader ( input , encoding ) ; // call this method to create the reader Reader reader = XmlCharsetDetector . createReader ( input , encoding ) ; // rest the input 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 . | 162 | 40 |
17,084 | public static BufferedReader getBufferedXMLReader ( Reader reader , int xmlLookahead ) throws IOException { // ensure the reader is a buffered reader if ( ! ( reader instanceof BufferedReader ) ) { reader = new BufferedReader ( reader ) ; } // mark the input stream 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 . | 80 | 38 |
17,085 | 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 . | 124 | 5 |
17,086 | 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 . | 615 | 18 |
17,087 | 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 . | 114 | 16 |
17,088 | 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 . | 55 | 10 |
17,089 | 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 . | 174 | 8 |
17,090 | 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 . | 260 | 8 |
17,091 | public static void changeMarkSize ( Rule rule , int newSize ) { PointSymbolizer pointSymbolizer = StyleUtilities . pointSymbolizerFromRule ( rule ) ; Graphic graphic = SLD . graphic ( pointSymbolizer ) ; graphic . setSize ( ff . literal ( newSize ) ) ; // Mark oldMark = SLDs.mark(pointSymbolizer); // oldMark.setSize(ff.literal(newSize)); // Graphic graphic = SLDs.graphic(pointSymbolizer); } | Changes the size of a mark inside a rule . | 114 | 10 |
17,092 | public static void changeRotation ( Rule rule , int newRotation ) { PointSymbolizer pointSymbolizer = StyleUtilities . pointSymbolizerFromRule ( rule ) ; Graphic graphic = SLD . graphic ( pointSymbolizer ) ; graphic . setRotation ( ff . literal ( newRotation ) ) ; // Mark oldMark = SLDs.mark(pointSymbolizer); // oldMark.setSize(ff.literal(newRotation)); } | Changes the rotation value inside a rule . | 102 | 8 |
17,093 | @ 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 . | 249 | 9 |
17,094 | 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 . | 135 | 14 |
17,095 | 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 . | 433 | 9 |
17,096 | public static float [ ] getDash ( String dashStr ) { if ( dashStr == null ) { return null ; } String [ ] dashSplit = dashStr . split ( "," ) ; //$NON-NLS-1$ 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 . | 127 | 9 |
17,097 | 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 . | 92 | 8 |
17,098 | 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 . | 136 | 15 |
17,099 | 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 . | 134 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.