idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
17,300 | public static GridCoverage2D cut ( GridCoverage2D raster , GridCoverage2D mask ) throws Exception { OmsCutOut cutDrain = new OmsCutOut ( ) ; cutDrain . inRaster = raster ; cutDrain . inMask = mask ; cutDrain . process ( ) ; return cutDrain . outRaster ; } | Cut a raster on a mask using the default parameters . |
17,301 | private void addMessage ( ValidationMessage < Origin > message ) { if ( message == null ) { return ; } if ( null != defaultOrigin ) { message . addOrigin ( defaultOrigin ) ; } this . messages . add ( message ) ; } | Adds a validation message to the result . |
17,302 | public int count ( Severity severity ) { int result = 0 ; if ( severity == null ) { return result ; } for ( ValidationMessage < Origin > message : messages ) { if ( severity . equals ( message . getSeverity ( ) ) ) { result ++ ; } } return result ; } | Counts validation messages by its severity . |
17,303 | public void removeMessage ( String messageId ) { Collection < ValidationMessage < Origin > > toRemove = new ArrayList < ValidationMessage < Origin > > ( ) ; for ( ValidationMessage < Origin > message : messages ) { if ( messageId . equals ( message . getMessageKey ( ) ) ) { toRemove . add ( message ) ; } } messages . removeAll ( toRemove ) ; } | removes all messages with a specified message id |
17,304 | public int compareTo ( Object o ) { BoundablePair nd = ( BoundablePair ) o ; if ( distance < nd . distance ) return - 1 ; if ( distance > nd . distance ) return 1 ; return 0 ; } | Compares two pairs based on their minimum distances |
17,305 | double b ( int i , double t ) { switch ( i ) { case - 2 : return ( ( ( - t + 3 ) * t - 3 ) * t + 1 ) / 6 ; case - 1 : return ( ( ( 3 * t - 6 ) * t ) * t + 4 ) / 6 ; case 0 : return ( ( ( - 3 * t + 3 ) * t + 3 ) * t + 1 ) / 6 ; case 1 : return ( t * t * t ) / 6 ; } return 0 ; } | the basis function for a cubic B spline |
17,306 | private Coordinate p ( int i , double t ) { double px = 0 ; double py = 0 ; for ( int j = - 2 ; j <= 1 ; j ++ ) { Coordinate coordinate = pts . get ( i + j ) ; px += b ( j , t ) * coordinate . x ; py += b ( j , t ) * coordinate . y ; } return new Coordinate ( px , py ) ; } | evaluate a point on the B spline |
17,307 | public static void oddEvenSort ( List < Double > listToBeSorted , List < Double > listThatFollowsTheSort ) { for ( int i = 0 ; i < listToBeSorted . size ( ) / 2 ; i ++ ) { for ( int j = 0 ; j + 1 < listToBeSorted . size ( ) ; j += 2 ) if ( listToBeSorted . get ( j ) > listToBeSorted . get ( j + 1 ) ) { double tmpa = listToBeSorted . get ( j ) ; listToBeSorted . set ( j , listToBeSorted . get ( j + 1 ) ) ; listToBeSorted . set ( j + 1 , tmpa ) ; if ( listThatFollowsTheSort != null ) { double tmpb = listThatFollowsTheSort . get ( j ) ; listThatFollowsTheSort . set ( j , listThatFollowsTheSort . get ( j + 1 ) ) ; listThatFollowsTheSort . set ( j + 1 , tmpb ) ; } } for ( int j = 1 ; j + 1 < listToBeSorted . size ( ) ; j += 2 ) if ( listToBeSorted . get ( j ) > listToBeSorted . get ( j + 1 ) ) { double tmpa = listToBeSorted . get ( j ) ; listToBeSorted . set ( j , listToBeSorted . get ( j + 1 ) ) ; listToBeSorted . set ( j + 1 , tmpa ) ; if ( listThatFollowsTheSort != null ) { double tmpb = listThatFollowsTheSort . get ( j ) ; listThatFollowsTheSort . set ( j , listThatFollowsTheSort . get ( j + 1 ) ) ; listThatFollowsTheSort . set ( j + 1 , tmpb ) ; } } } } | Sorts two lists regarding to the sort of the first |
17,308 | protected double simpson ( ) { double s = 0f ; double st = 0f ; double ost = 0f ; double os = 0f ; for ( int i = 1 ; i < maxsteps ; i ++ ) { st = trapezoid ( i ) ; s = ( 4f * st - ost ) / 3f ; if ( i > 5 ) { if ( Math . abs ( s - os ) < accuracy * Math . abs ( os ) || ( s == 0f && os == 0f ) ) { return s ; } } os = s ; ost = st ; } return 0d ; } | Calculate the integral with the simpson method of the equation implemented in the method equation |
17,309 | protected double trapezoid ( int n ) { double x = 0 ; double tnm = 0 ; double sum = 0 ; double del = 0 ; int it = 0 ; int j = 0 ; if ( n == 1 ) { strapezoid = 0.5f * ( upperlimit - lowerlimit ) * ( equation ( lowerlimit ) + equation ( upperlimit ) ) ; } else { it = ( int ) Math . pow ( 2.0 , n - 1 ) ; tnm = ( double ) it ; del = ( upperlimit - lowerlimit ) / tnm ; x = lowerlimit + 0.5f * del ; for ( sum = 0f , j = 1 ; j <= it ; j ++ , x += del ) { if ( x >= upperlimit ) { System . out . println ( "hoi" ) ; } sum += equation ( x ) ; } strapezoid = ( double ) ( 0.5f * ( strapezoid + ( upperlimit - lowerlimit ) * sum / tnm ) ) ; } return strapezoid ; } | Calculate the integral with the trapezoidal algorithm of the equation implemented in the method equation |
17,310 | public static double [ ] tileLatLonBounds ( int tx , int ty , int zoom , int tileSize ) { double [ ] bounds = tileBounds3857 ( tx , ty , zoom , tileSize ) ; double [ ] mins = metersToLatLon ( bounds [ 0 ] , bounds [ 1 ] ) ; double [ ] maxs = metersToLatLon ( bounds [ 2 ] , bounds [ 3 ] ) ; return new double [ ] { mins [ 1 ] , maxs [ 0 ] , maxs [ 1 ] , mins [ 0 ] } ; } | Get lat - long bounds from tile index . |
17,311 | public static double metersYToLatitude ( double y ) { return Math . toDegrees ( Math . atan ( Math . sinh ( y / EQUATORIALRADIUS ) ) ) ; } | Convert a meter measure to a latitude |
17,312 | public void addGeometryXYColumnAndIndex ( String tableName , String geomColName , String geomType , String epsg , boolean avoidIndex ) throws Exception { String epsgStr = "4326" ; if ( epsg != null ) { epsgStr = epsg ; } String geomTypeStr = "LINESTRING" ; if ( geomType != null ) { geomTypeStr = geomType ; } if ( geomColName == null ) { geomColName = ASpatialDb . DEFAULT_GEOM_FIELD_NAME ; } String _geomColName = geomColName ; String _epsgStr = epsgStr ; String _geomTypeStr = geomTypeStr ; pgDb . execOnConnection ( connection -> { try ( IHMStatement stmt = connection . createStatement ( ) ) { String sql = sqlTemplates . addGeometryColumn ( tableName , _geomColName , _epsgStr , _geomTypeStr , "2" ) ; stmt . execute ( sql ) ; if ( ! avoidIndex ) { sql = sqlTemplates . createSpatialIndex ( tableName , _geomColName ) ; stmt . execute ( sql ) ; } } return null ; } ) ; } | Adds a geometry column to a table . |
17,313 | public BufferedImage getTile ( int x , int y , int z ) throws Exception { try ( PreparedStatement statement = connection . prepareStatement ( SELECTQUERY ) ) { statement . setInt ( 1 , z ) ; statement . setInt ( 2 , x ) ; statement . setInt ( 3 , y ) ; ResultSet resultSet = statement . executeQuery ( ) ; if ( resultSet . next ( ) ) { byte [ ] imageBytes = resultSet . getBytes ( 1 ) ; boolean orig = ImageIO . getUseCache ( ) ; ImageIO . setUseCache ( false ) ; InputStream in = new ByteArrayInputStream ( imageBytes ) ; BufferedImage bufferedImage = ImageIO . read ( in ) ; ImageIO . setUseCache ( orig ) ; return bufferedImage ; } } return null ; } | Get a Tile image from the database . |
17,314 | public static BufferedImage readGridcoverageImageForTile ( AbstractGridCoverage2DReader reader , int x , int y , int zoom , CoordinateReferenceSystem resampleCrs ) throws IOException { double north = tile2lat ( y , zoom ) ; double south = tile2lat ( y + 1 , zoom ) ; double west = tile2lon ( x , zoom ) ; double east = tile2lon ( x + 1 , zoom ) ; Coordinate ll = new Coordinate ( west , south ) ; Coordinate ur = new Coordinate ( east , north ) ; try { CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS . WGS84 ; MathTransform transform = CRS . findMathTransform ( sourceCRS , resampleCrs ) ; ll = JTS . transform ( ll , null , transform ) ; ur = JTS . transform ( ur , null , transform ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } BufferedImage image = ImageUtilities . imageFromReader ( reader , TILESIZE , TILESIZE , ll . x , ur . x , ll . y , ur . y , resampleCrs ) ; return image ; } | Read the image of a tile from a generic geotools coverage reader . |
17,315 | public int [ ] convertToArray ( ) { int [ ] p = new int [ size ] ; for ( int j = 0 ; j < height ; ++ j ) { for ( int i = 0 ; i < width ; ++ i ) { p [ ( j * width ) + i ] = pixels [ i ] [ j ] ; } } return p ; } | Converts the 2D array into a 1D array of pixel values . |
17,316 | public void generatePixels ( HashSet < Point > pix ) { for ( int j = 0 ; j < height ; ++ j ) { for ( int i = 0 ; i < width ; ++ i ) { pixels [ i ] [ j ] = BACKGROUND ; } } convertToPixels ( pix ) ; } | Generates a new 2D array of pixels from a hash set of foreground pixels . |
17,317 | public void convertToPixels ( HashSet < Point > pix ) { Iterator < Point > it = pix . iterator ( ) ; while ( it . hasNext ( ) ) { Point p = it . next ( ) ; pixels [ p . x ] [ p . y ] = FOREGROUND ; } } | Adds the pixels from a hash set to the 2D array of pixels . |
17,318 | public void generateForegroundEdge ( ) { foregroundEdgePixels . clear ( ) ; Point p ; for ( int n = 0 ; n < height ; ++ n ) { for ( int m = 0 ; m < width ; ++ m ) { if ( pixels [ m ] [ n ] == FOREGROUND ) { p = new Point ( m , n ) ; for ( int j = - 1 ; j < 2 ; ++ j ) { for ( int i = - 1 ; i < 2 ; ++ i ) { if ( ( p . x + i >= 0 ) && ( p . x + i < width ) && ( p . y + j >= 0 ) && ( p . y + j < height ) ) { if ( ( pixels [ p . x + i ] [ p . y + j ] == BACKGROUND ) && ( ! foregroundEdgePixels . contains ( p ) ) ) { foregroundEdgePixels . add ( p ) ; } } } } } } } } | Generates the foreground edge hash set from the 2D array of pixels . |
17,319 | public void generateBackgroundEdgeFromForegroundEdge ( ) { backgroundEdgePixels . clear ( ) ; Point p , p2 ; Iterator < Point > it = foregroundEdgePixels . iterator ( ) ; while ( it . hasNext ( ) ) { p = new Point ( it . next ( ) ) ; for ( int j = - 1 ; j < 2 ; ++ j ) { for ( int i = - 1 ; i < 2 ; ++ i ) { if ( ( p . x + i >= 0 ) && ( p . x + i < width ) && ( p . y + j >= 0 ) && ( p . y + j < height ) ) { p2 = new Point ( p . x + i , p . y + j ) ; if ( pixels [ p2 . x ] [ p2 . y ] == BACKGROUND ) { backgroundEdgePixels . add ( p2 ) ; } } } } } } | Generates the background edge hash set from the foreground edge hash set and the 2D array of pixels . |
17,320 | public String nextValue ( ) throws IOException { Token tkn = nextToken ( ) ; String ret = null ; switch ( tkn . type ) { case TT_TOKEN : case TT_EORECORD : ret = tkn . content . toString ( ) ; break ; case TT_EOF : ret = null ; break ; case TT_INVALID : default : throw new IOException ( "(line " + getLineNumber ( ) + ") invalid parse sequence" ) ; } return ret ; } | Parses the CSV according to the given strategy and returns the next csv - value as string . |
17,321 | public String [ ] getLine ( ) throws IOException { String [ ] ret = EMPTY_STRING_ARRAY ; record . clear ( ) ; while ( true ) { reusableToken . reset ( ) ; nextToken ( reusableToken ) ; switch ( reusableToken . type ) { case TT_TOKEN : record . add ( reusableToken . content . toString ( ) ) ; break ; case TT_EORECORD : record . add ( reusableToken . content . toString ( ) ) ; break ; case TT_EOF : if ( reusableToken . isReady ) { record . add ( reusableToken . content . toString ( ) ) ; } else { ret = null ; } break ; case TT_INVALID : default : throw new IOException ( "(line " + getLineNumber ( ) + ") invalid parse sequence" ) ; } if ( reusableToken . type != TT_TOKEN ) { break ; } } if ( ! record . isEmpty ( ) ) { ret = ( String [ ] ) record . toArray ( new String [ record . size ( ) ] ) ; } return ret ; } | Parses from the current point in the stream til the end of the current line . |
17,322 | Token nextToken ( Token tkn ) throws IOException { wsBuf . clear ( ) ; int lastChar = in . readAgain ( ) ; int c = in . read ( ) ; boolean eol = isEndOfLine ( c ) ; c = in . readAgain ( ) ; while ( strategy . getIgnoreEmptyLines ( ) && eol && ( lastChar == '\n' || lastChar == ExtendedBufferedReader . UNDEFINED ) && ! isEndOfFile ( lastChar ) ) { lastChar = c ; c = in . read ( ) ; eol = isEndOfLine ( c ) ; c = in . readAgain ( ) ; if ( isEndOfFile ( c ) ) { tkn . type = TT_EOF ; return tkn ; } } if ( isEndOfFile ( lastChar ) || ( lastChar != strategy . getDelimiter ( ) && isEndOfFile ( c ) ) ) { tkn . type = TT_EOF ; return tkn ; } while ( ! tkn . isReady ) { while ( isWhitespace ( c ) && ! eol ) { wsBuf . append ( ( char ) c ) ; c = in . read ( ) ; eol = isEndOfLine ( c ) ; } if ( c == strategy . getCommentStart ( ) ) { in . readLine ( ) ; tkn = nextToken ( tkn . reset ( ) ) ; } else if ( c == strategy . getDelimiter ( ) ) { tkn . type = TT_TOKEN ; tkn . isReady = true ; } else if ( eol ) { tkn . type = TT_EORECORD ; tkn . isReady = true ; } else if ( c == strategy . getEncapsulator ( ) ) { encapsulatedTokenLexer ( tkn , c ) ; } else if ( isEndOfFile ( c ) ) { tkn . type = TT_EOF ; tkn . isReady = true ; } else { if ( ! strategy . getIgnoreLeadingWhitespaces ( ) ) { tkn . content . append ( wsBuf ) ; } simpleTokenLexer ( tkn , c ) ; } } return tkn ; } | Returns the next token . |
17,323 | private Token simpleTokenLexer ( Token tkn , int c ) throws IOException { for ( ; ; ) { if ( isEndOfLine ( c ) ) { tkn . type = TT_EORECORD ; tkn . isReady = true ; break ; } else if ( isEndOfFile ( c ) ) { tkn . type = TT_EOF ; tkn . isReady = true ; break ; } else if ( c == strategy . getDelimiter ( ) ) { tkn . type = TT_TOKEN ; tkn . isReady = true ; break ; } else if ( c == '\\' && strategy . getUnicodeEscapeInterpretation ( ) && in . lookAhead ( ) == 'u' ) { tkn . content . append ( ( char ) unicodeEscapeLexer ( c ) ) ; } else if ( c == strategy . getEscape ( ) ) { tkn . content . append ( ( char ) readEscape ( c ) ) ; } else { tkn . content . append ( ( char ) c ) ; } c = in . read ( ) ; } if ( strategy . getIgnoreTrailingWhitespaces ( ) ) { tkn . content . trimTrailingWhitespace ( ) ; } return tkn ; } | A simple token lexer |
17,324 | private Token encapsulatedTokenLexer ( Token tkn , int c ) throws IOException { int startLineNumber = getLineNumber ( ) ; for ( ; ; ) { c = in . read ( ) ; if ( c == '\\' && strategy . getUnicodeEscapeInterpretation ( ) && in . lookAhead ( ) == 'u' ) { tkn . content . append ( ( char ) unicodeEscapeLexer ( c ) ) ; } else if ( c == strategy . getEscape ( ) ) { tkn . content . append ( ( char ) readEscape ( c ) ) ; } else if ( c == strategy . getEncapsulator ( ) ) { if ( in . lookAhead ( ) == strategy . getEncapsulator ( ) ) { c = in . read ( ) ; tkn . content . append ( ( char ) c ) ; } else { for ( ; ; ) { c = in . read ( ) ; if ( c == strategy . getDelimiter ( ) ) { tkn . type = TT_TOKEN ; tkn . isReady = true ; return tkn ; } else if ( isEndOfFile ( c ) ) { tkn . type = TT_EOF ; tkn . isReady = true ; return tkn ; } else if ( isEndOfLine ( c ) ) { tkn . type = TT_EORECORD ; tkn . isReady = true ; return tkn ; } else if ( ! isWhitespace ( c ) ) { throw new IOException ( "(line " + getLineNumber ( ) + ") invalid char between encapsulated token end delimiter" ) ; } } } } else if ( isEndOfFile ( c ) ) { throw new IOException ( "(startline " + startLineNumber + ")" + "eof reached before encapsulated token finished" ) ; } else { tkn . content . append ( ( char ) c ) ; } } } | An encapsulated token lexer |
17,325 | protected int unicodeEscapeLexer ( int c ) throws IOException { int ret = 0 ; c = in . read ( ) ; code . clear ( ) ; try { for ( int i = 0 ; i < 4 ; i ++ ) { c = in . read ( ) ; if ( isEndOfFile ( c ) || isEndOfLine ( c ) ) { throw new NumberFormatException ( "number too short" ) ; } code . append ( ( char ) c ) ; } ret = Integer . parseInt ( code . toString ( ) , 16 ) ; } catch ( NumberFormatException e ) { throw new IOException ( "(line " + getLineNumber ( ) + ") Wrong unicode escape sequence found '" + code . toString ( ) + "'" + e . toString ( ) ) ; } return ret ; } | Decodes Unicode escapes . |
17,326 | private boolean isEndOfLine ( int c ) throws IOException { if ( c == '\r' ) { if ( in . lookAhead ( ) == '\n' ) { c = in . read ( ) ; } } return ( c == '\n' ) ; } | Greedy - accepts \ n and \ r \ n This checker consumes silently the second control - character ... |
17,327 | private WritableRaster skyviewfactor ( WritableRaster pitWR , double res ) { normalVectorWR = normalVector ( pitWR , res ) ; WritableRaster skyviewFactorWR = CoverageUtilities . createWritableRaster ( cols , rows , null , pitWR . getSampleModel ( ) , 0.0 ) ; pm . beginTask ( msg . message ( "skyview.calculating" ) , 35 ) ; for ( int i = 0 ; i < 360 - 10 ; i = i + 10 ) { azimuth = Math . toRadians ( i * 1.0 ) ; WritableRaster skyViewWR = CoverageUtilities . createWritableRaster ( cols , rows , null , pitWR . getSampleModel ( ) , Math . toRadians ( maxSlope ) ) ; for ( int j = ( int ) maxSlope ; j >= 0 ; j -- ) { elevation = Math . toRadians ( j * 1.0 ) ; double [ ] sunVector = calcSunVector ( ) ; double [ ] inverseSunVector = calcInverseSunVector ( sunVector ) ; double [ ] normalSunVector = calcNormalSunVector ( sunVector ) ; calculateFactor ( rows , cols , sunVector , inverseSunVector , normalSunVector , pitWR , skyViewWR , res ) ; } for ( int t = normalVectorWR . getMinY ( ) ; t < normalVectorWR . getMinY ( ) + normalVectorWR . getHeight ( ) ; t ++ ) { for ( int k = normalVectorWR . getMinX ( ) ; k < normalVectorWR . getMinX ( ) + normalVectorWR . getWidth ( ) ; k ++ ) { double tmp = skyViewWR . getSampleDouble ( k , t , 0 ) ; skyViewWR . setSample ( k , t , 0 , Math . cos ( tmp ) * Math . cos ( tmp ) * 10.0 / 360.0 ) ; } } for ( int q = 0 ; q < skyviewFactorWR . getWidth ( ) ; q ++ ) { for ( int k = 0 ; k < skyviewFactorWR . getHeight ( ) ; k ++ ) { double tmp = skyviewFactorWR . getSampleDouble ( q , k , 0 ) ; skyviewFactorWR . setSample ( q , k , 0 , tmp + skyViewWR . getSampleDouble ( q , k , 0 ) ) ; } } pm . worked ( 1 ) ; } pm . done ( ) ; return skyviewFactorWR ; } | Calculate the skyview factor . |
17,328 | protected WritableRaster shadow ( int x , int y , WritableRaster tmpWR , WritableRaster pitWR , double res , double [ ] normalSunVector , double [ ] inverseSunVector , double [ ] sunVector ) { int n = 0 ; double zcompare = - Double . MAX_VALUE ; double dx = ( inverseSunVector [ 0 ] * n ) ; double dy = ( inverseSunVector [ 1 ] * n ) ; int nCols = tmpWR . getWidth ( ) ; int nRows = tmpWR . getHeight ( ) ; int idx = ( int ) ( x + dx ) ; int jdy = ( int ) ( y + dy ) ; double vectorToOrigin [ ] = new double [ 3 ] ; while ( idx >= 0 && idx <= nCols - 1 && jdy >= 0 && jdy <= nRows - 1 ) { vectorToOrigin [ 0 ] = dx * res ; vectorToOrigin [ 1 ] = dy * res ; vectorToOrigin [ 2 ] = pitWR . getSampleDouble ( idx , jdy , 0 ) ; double zprojection = scalarProduct ( vectorToOrigin , normalSunVector ) ; double nGrad [ ] = normalVectorWR . getPixel ( idx , jdy , new double [ 3 ] ) ; double cosinc = scalarProduct ( sunVector , nGrad ) ; double elevRad = elevation ; if ( ( cosinc >= 0 ) && ( zprojection > zcompare ) ) { tmpWR . setSample ( idx , jdy , 0 , elevRad ) ; zcompare = zprojection ; } n = n + 1 ; dy = ( inverseSunVector [ 1 ] * n ) ; dx = ( inverseSunVector [ 0 ] * n ) ; idx = ( int ) Math . round ( x + dx ) ; jdy = ( int ) Math . round ( y + dy ) ; } return tmpWR ; } | Calculate the angle . |
17,329 | public boolean connectIfPossible ( MonitoringPoint monitoringPoint ) { if ( ID == monitoringPoint . getRelatedID ( ) ) { pfafRelatedMonitoringPointsTable . put ( monitoringPoint . getPfatstetterNumber ( ) . toString ( ) , monitoringPoint ) ; return true ; } return false ; } | Tries to connect another monitoringpoint if that one has a related id equal to that of this object . That way it would be possible to add more than one point as related . |
17,330 | public MonitoringPoint getRelatedMonitoringPoint ( String pfafStetter ) { if ( pfafStetter != null ) { return pfafRelatedMonitoringPointsTable . get ( pfafStetter ) ; } else { Set < String > keySet = pfafRelatedMonitoringPointsTable . keySet ( ) ; for ( String key : keySet ) { return pfafRelatedMonitoringPointsTable . get ( key ) ; } return null ; } } | Get the related monitoringpoint . If there are more than one the pfafstetter number is used to chose . |
17,331 | public SimpleFeatureCollection toFeatureCollection ( List < MonitoringPoint > monitoringPointsList ) { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder ( ) ; b . setName ( "monitoringpoints" ) ; b . add ( "the_geom" , Point . class ) ; b . add ( "id" , Integer . class ) ; b . add ( "relatedid" , Integer . class ) ; b . add ( "pfaf" , String . class ) ; SimpleFeatureType type = b . buildFeatureType ( ) ; SimpleFeatureBuilder builder = new SimpleFeatureBuilder ( type ) ; GeometryFactory gF = new GeometryFactory ( ) ; DefaultFeatureCollection newCollection = new DefaultFeatureCollection ( ) ; for ( int i = 0 ; i < monitoringPointsList . size ( ) ; i ++ ) { MonitoringPoint mp = monitoringPointsList . get ( monitoringPointsList . size ( ) - i - 1 ) ; Object [ ] values = new Object [ ] { gF . createPoint ( mp . getPosition ( ) ) , mp . getID ( ) , mp . getRelatedID ( ) , mp . getPfatstetterNumber ( ) . toString ( ) } ; builder . addAll ( values ) ; SimpleFeature feature = builder . buildFeature ( type . getTypeName ( ) + "." + i ) ; newCollection . add ( feature ) ; } return newCollection ; } | Create a featurecollection from a list of monitoringpoints . Based on the position of the points and some of their attributes . |
17,332 | public long skip ( long n ) throws IOException { long ret = pos + n ; if ( ret < 0 ) { ret = 0 ; pos = 0 ; } else if ( ret > blob . size ) { ret = blob . size ; pos = blob . size ; } else { pos = ( int ) ret ; } return ret ; } | Skip over blob data . |
17,333 | public int read ( ) throws IOException { byte b [ ] = new byte [ 1 ] ; int n = blob . read ( b , 0 , pos , b . length ) ; if ( n > 0 ) { pos += n ; return b [ 0 ] ; } return - 1 ; } | Read single byte from blob . |
17,334 | public int read ( byte b [ ] , int off , int len ) throws IOException { if ( off + len > b . length ) { len = b . length - off ; } if ( len < 0 ) { return - 1 ; } if ( len == 0 ) { return 0 ; } int n = blob . read ( b , off , pos , len ) ; if ( n > 0 ) { pos += n ; return n ; } return - 1 ; } | Read slice of byte array from blob . |
17,335 | public List < Rasterlite2Coverage > getRasterCoverages ( boolean doOrder ) throws Exception { List < Rasterlite2Coverage > rasterCoverages = new ArrayList < Rasterlite2Coverage > ( ) ; String orderBy = " ORDER BY " + Rasterlite2Coverage . COVERAGE_NAME ; if ( ! doOrder ) { orderBy = "" ; } String sql = "SELECT " + Rasterlite2Coverage . COVERAGE_NAME + ", " + Rasterlite2Coverage . TITLE + ", " + Rasterlite2Coverage . SRID + ", " + Rasterlite2Coverage . COMPRESSION + ", " + Rasterlite2Coverage . EXTENT_MINX + ", " + Rasterlite2Coverage . EXTENT_MINY + ", " + Rasterlite2Coverage . EXTENT_MAXX + ", " + Rasterlite2Coverage . EXTENT_MAXY + " FROM " + Rasterlite2Coverage . TABLENAME + orderBy ; return database . execOnConnection ( connection -> { try ( IHMStatement stmt = connection . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( sql ) ) { while ( rs . next ( ) ) { int i = 1 ; String coverageName = rs . getString ( i ++ ) ; String title = rs . getString ( i ++ ) ; int srid = rs . getInt ( i ++ ) ; String compression = rs . getString ( i ++ ) ; double minX = rs . getDouble ( i ++ ) ; double minY = rs . getDouble ( i ++ ) ; double maxX = rs . getDouble ( i ++ ) ; double maxY = rs . getDouble ( i ++ ) ; Rasterlite2Coverage rc = new Rasterlite2Coverage ( database , coverageName , title , srid , compression , minX , minY , maxX , maxY ) ; rasterCoverages . add ( rc ) ; } return rasterCoverages ; } } ) ; } | Get the list of available raster coverages . |
17,336 | public void readDwgEndblkV15 ( int [ ] data , int offset ) throws Exception { int bitPos = offset ; bitPos = readObjectHeaderV15 ( data , bitPos ) ; bitPos = readObjectTailV15 ( data , bitPos ) ; } | Read a Endblk in the DWG format Version 15 |
17,337 | public static Filter getBboxFilter ( String attribute , BoundingBox bbox ) throws CQLException { double w = bbox . getMinX ( ) ; double e = bbox . getMaxX ( ) ; double s = bbox . getMinY ( ) ; double n = bbox . getMaxY ( ) ; return getBboxFilter ( attribute , w , e , s , n ) ; } | Create a bounding box filter from a bounding box . |
17,338 | public static Filter getBboxFilter ( String attribute , double west , double east , double south , double north ) throws CQLException { if ( attribute == null ) { attribute = "the_geom" ; } StringBuilder sB = new StringBuilder ( ) ; sB . append ( "BBOX(" ) ; sB . append ( attribute ) ; sB . append ( "," ) ; sB . append ( west ) ; sB . append ( "," ) ; sB . append ( south ) ; sB . append ( "," ) ; sB . append ( east ) ; sB . append ( "," ) ; sB . append ( north ) ; sB . append ( ")" ) ; Filter bboxFilter = CQL . toFilter ( sB . toString ( ) ) ; return bboxFilter ; } | Create a bounding box filter from the bounds coordinates . |
17,339 | public static Filter getIntersectsGeometryFilter ( String geomName , Geometry geometry ) throws CQLException { Filter result = CQL . toFilter ( "INTERSECTS(" + geomName + ", " + geometry . toText ( ) + " )" ) ; return result ; } | Creates an intersect filter . |
17,340 | private double neigh_value ( double x_cur , double x_min , double x_max , double r ) { double ranval , zvalue , new_value ; double work3 , work2 = 0 , work1 = 0 ; double x_range = x_max - x_min ; work3 = 2.0 ; while ( work3 >= 1.0 || work3 == 0.0 ) { ranval = rand . nextDouble ( ) ; work1 = 2.0 * ranval - 1.0 ; ranval = rand . nextDouble ( ) ; work2 = 2.0 * ranval - 1.0 ; work3 = work1 * work1 + work2 * work2 ; } work3 = Math . pow ( ( - 2.0 * Math . log ( work3 ) ) / work3 , 0.5 ) ; ranval = rand . nextDouble ( ) ; if ( ranval < 0.5 ) { zvalue = work1 * work3 ; } else { zvalue = work2 * work3 ; } new_value = x_cur + zvalue * r * x_range ; if ( new_value < x_min ) { new_value = x_min + ( x_min - new_value ) ; if ( new_value > x_max ) { new_value = x_min ; } } else if ( new_value > x_max ) { new_value = x_max - ( new_value - x_max ) ; if ( new_value < x_min ) { new_value = x_max ; } } return new_value ; } | Purpose is to generate a neighboring decision variable value for a single decision variable value being perturbed by the DDS optimization algorithm . New DV value respects the upper and lower DV bounds . Coded by Bryan Tolson Nov 2005 . |
17,341 | private void calchillshade ( WritableRaster pitWR , WritableRaster hillshadeWR , WritableRaster gradientWR , double dx ) { pAzimuth = Math . toRadians ( pAzimuth ) ; pElev = Math . toRadians ( pElev ) ; double [ ] sunVector = calcSunVector ( ) ; double [ ] normalSunVector = calcNormalSunVector ( sunVector ) ; double [ ] inverseSunVector = calcInverseSunVector ( sunVector ) ; int rows = pitWR . getHeight ( ) ; int cols = pitWR . getWidth ( ) ; WritableRaster sOmbraWR = calculateFactor ( rows , cols , sunVector , inverseSunVector , normalSunVector , pitWR , dx ) ; pm . beginTask ( msg . message ( "hillshade.calculating" ) , rows * cols ) ; for ( int j = 1 ; j < rows - 1 ; j ++ ) { for ( int i = 1 ; i < cols - 1 ; i ++ ) { double [ ] ng = gradientWR . getPixel ( i , j , new double [ 3 ] ) ; double cosinc = scalarProduct ( sunVector , ng ) ; if ( cosinc < 0 ) { sOmbraWR . setSample ( i , j , 0 , 0 ) ; } hillshadeWR . setSample ( i , j , 0 , ( int ) ( 212.5 * ( cosinc * sOmbraWR . getSample ( i , j , 0 ) + pMinDiffuse ) ) ) ; pm . worked ( 1 ) ; } } pm . done ( ) ; } | Evaluate the hillshade . |
17,342 | public static double getMeanSlope ( List < ProfilePoint > points ) { double meanSlope = 0 ; int num = 0 ; for ( int i = 0 ; i < points . size ( ) - 1 ; i ++ ) { ProfilePoint p1 = points . get ( i ) ; ProfilePoint p2 = points . get ( i + 1 ) ; double dx = p2 . progressive - p1 . progressive ; double dy = p2 . elevation - p1 . elevation ; double tmpSlope = dy / dx ; meanSlope = meanSlope + tmpSlope ; num ++ ; } meanSlope = meanSlope / num ; return meanSlope ; } | Calculates the mean slope of a given set of profilepoints . |
17,343 | public static double [ ] getLastVisiblePointData ( List < ProfilePoint > profile ) { if ( profile . size ( ) < 2 ) { throw new IllegalArgumentException ( "A profile needs to have at least 2 points." ) ; } ProfilePoint first = profile . get ( 0 ) ; double baseElev = first . getElevation ( ) ; Coordinate baseCoord = new Coordinate ( 0 , 0 ) ; double minAzimuthAngle = Double . POSITIVE_INFINITY ; double maxAzimuthAngle = Double . NEGATIVE_INFINITY ; ProfilePoint minAzimuthPoint = null ; ProfilePoint maxAzimuthPoint = null ; for ( int i = 1 ; i < profile . size ( ) ; i ++ ) { ProfilePoint currentPoint = profile . get ( i ) ; double currentElev = currentPoint . getElevation ( ) ; if ( HMConstants . isNovalue ( currentElev ) ) { continue ; } currentElev = currentElev - baseElev ; double currentProg = currentPoint . getProgressive ( ) ; Coordinate currentCoord = new Coordinate ( currentProg , currentElev ) ; double azimuth = GeometryUtilities . azimuth ( baseCoord , currentCoord ) ; if ( azimuth <= minAzimuthAngle ) { minAzimuthAngle = azimuth ; minAzimuthPoint = currentPoint ; } if ( azimuth >= maxAzimuthAngle ) { maxAzimuthAngle = azimuth ; maxAzimuthPoint = currentPoint ; } } if ( minAzimuthPoint == null || maxAzimuthPoint == null ) { return null ; } return new double [ ] { minAzimuthPoint . elevation , minAzimuthPoint . position . x , minAzimuthPoint . position . y , minAzimuthPoint . progressive , minAzimuthAngle , maxAzimuthPoint . elevation , maxAzimuthPoint . position . x , maxAzimuthPoint . position . y , maxAzimuthPoint . progressive , maxAzimuthAngle , } ; } | Return last visible point data for a profile points list . |
17,344 | private void checkMetagenomeSource ( Origin origin , SourceFeature source ) { List < Qualifier > metagenomeSourceQual = source . getQualifiers ( Qualifier . METAGENOME_SOURCE_QUALIFIER_NAME ) ; if ( metagenomeSourceQual != null && ! metagenomeSourceQual . isEmpty ( ) ) { Qualifier envSample = source . getSingleQualifier ( Qualifier . ENVIRONMENTAL_SAMPLE_QUALIFIER_NAME ) ; if ( envSample == null ) { reportError ( origin , ENV_SAMPLE_REQUIRED ) ; } if ( metagenomeSourceQual . size ( ) > 1 ) { reportError ( origin , MORE_THAN_ONE_METAGENOME_SOURCE ) ; } String metegenomeSource = metagenomeSourceQual . get ( 0 ) . getValue ( ) ; if ( metegenomeSource == null || ( ! metegenomeSource . contains ( "metagenome" ) && metegenomeSource . contains ( "Metagenome" ) ) ) { reportError ( origin , INVALID_METAGENOME_SOURCE , metegenomeSource ) ; } List < Taxon > taxon = getEmblEntryValidationPlanProperty ( ) . taxonHelper . get ( ) . getTaxonsByScientificName ( metegenomeSource ) ; if ( taxon == null || taxon . isEmpty ( ) || taxon . get ( 0 ) . getTaxId ( ) == 408169L || ! getEmblEntryValidationPlanProperty ( ) . taxonHelper . get ( ) . isOrganismMetagenome ( metegenomeSource ) ) { reportError ( origin , INVALID_METAGENOME_SOURCE , metegenomeSource ) ; } } } | ENA - 2825 |
17,345 | public void addFeaturePath ( String featurePath , String filter ) { if ( ! featurePaths . contains ( featurePath ) ) { featurePaths . add ( featurePath ) ; if ( filter == null ) { filter = "" ; } featureFilter . add ( filter ) ; } } | Add a new feature file path . |
17,346 | public BufferedImage drawImageWithNewMapContent ( ReferencedEnvelope ref , int imageWidth , int imageHeight , double buffer ) { MapContent content = new MapContent ( ) ; content . setTitle ( "dump" ) ; if ( forceCrs != null ) { content . getViewport ( ) . setCoordinateReferenceSystem ( forceCrs ) ; content . getViewport ( ) . setBounds ( ref ) ; } synchronized ( synchronizedLayers ) { for ( Layer layer : synchronizedLayers ) { content . addLayer ( layer ) ; } } StreamingRenderer renderer = new StreamingRenderer ( ) ; renderer . setMapContent ( content ) ; if ( buffer > 0.0 ) { ref = new ReferencedEnvelope ( ref ) ; ref . expandBy ( buffer , buffer ) ; } double envW = ref . getWidth ( ) ; double envH = ref . getHeight ( ) ; if ( envW < envH ) { double newEnvW = envH * ( double ) imageWidth / ( double ) imageHeight ; double delta = newEnvW - envW ; ref . expandBy ( delta / 2 , 0 ) ; } else { double newEnvH = envW * ( double ) imageHeight / ( double ) imageWidth ; double delta = newEnvH - envH ; ref . expandBy ( 0 , delta / 2.0 ) ; } Rectangle imageBounds = new Rectangle ( 0 , 0 , imageWidth , imageHeight ) ; BufferedImage dumpImage = new BufferedImage ( imageWidth , imageHeight , BufferedImage . TYPE_INT_RGB ) ; Graphics2D g2d = dumpImage . createGraphics ( ) ; g2d . fillRect ( 0 , 0 , imageWidth , imageHeight ) ; g2d . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; renderer . paint ( g2d , imageBounds , ref ) ; return dumpImage ; } | Draw the map on an image creating a new MapContent . |
17,347 | public void dumpPngImage ( String imagePath , ReferencedEnvelope bounds , int imageWidth , int imageHeight , double buffer , int [ ] rgbCheck ) throws IOException { BufferedImage dumpImage = drawImageWithNewMapContent ( bounds , imageWidth , imageHeight , buffer ) ; boolean dumpIt = true ; if ( rgbCheck != null ) dumpIt = ! isAllOfCheckColor ( rgbCheck , dumpImage ) ; if ( dumpIt ) ImageIO . write ( dumpImage , "png" , new File ( imagePath ) ) ; } | Writes an image of maps drawn to a png file . |
17,348 | public void dumpPngImageForScaleAndPaper ( String imagePath , ReferencedEnvelope bounds , double scale , EPaperFormat paperFormat , Double dpi , BufferedImage legend , int legendX , int legendY , String scalePrefix , float scaleSize , int scaleX , int scaleY ) throws Exception { if ( dpi == null ) { dpi = 72.0 ; } Coordinate centre = bounds . centre ( ) ; double boundsXExtension = paperFormat . width ( ) / 1000.0 * scale ; double boundsYExtension = paperFormat . height ( ) / 1000.0 * scale ; Coordinate ll = new Coordinate ( centre . x - boundsXExtension / 2.0 , centre . y - boundsYExtension / 2.0 ) ; Coordinate ur = new Coordinate ( centre . x + boundsXExtension / 2.0 , centre . y + boundsYExtension / 2.0 ) ; Envelope tmpEnv = new Envelope ( ll , ur ) ; bounds = new ReferencedEnvelope ( tmpEnv , bounds . getCoordinateReferenceSystem ( ) ) ; int imageWidth = ( int ) ( paperFormat . width ( ) / 25.4 * dpi ) ; int imageHeight = ( int ) ( paperFormat . height ( ) / 25.4 * dpi ) ; BufferedImage dumpImage = drawImage ( bounds , imageWidth , imageHeight , 0 ) ; Graphics2D graphics = ( Graphics2D ) dumpImage . getGraphics ( ) ; graphics . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; if ( shapesFile != null && shapesFile . exists ( ) ) { applyShapes ( graphics ) ; } if ( legend != null ) { graphics . drawImage ( legend , null , legendX , legendY ) ; } if ( scalePrefix != null ) { Font scaleFont = graphics . getFont ( ) . deriveFont ( scaleSize ) ; graphics . setFont ( scaleFont ) ; FontMetrics fontMetrics = graphics . getFontMetrics ( scaleFont ) ; String scaleString = scalePrefix + "1:" + ( int ) scale ; Rectangle2D stringBounds = fontMetrics . getStringBounds ( scaleString , graphics ) ; double width = stringBounds . getWidth ( ) ; double height = stringBounds . getHeight ( ) ; graphics . setColor ( Color . white ) ; double border = 5 ; graphics . fillRect ( ( int ) scaleX , ( int ) ( scaleY - height + 2 * border ) , ( int ) ( width + 3 * border ) , ( int ) ( height + 2 * border ) ) ; graphics . setColor ( Color . black ) ; graphics . drawString ( scaleString , ( int ) scaleX + 5 , ( int ) scaleY ) ; } ImageIO . write ( dumpImage , "png" , new File ( imagePath ) ) ; } | Create an image for a given paper size and scale . |
17,349 | public double distance ( Object pt1 , Object pt2 ) { Object p = newCopy ( pt1 ) ; subtract ( p , pt2 ) ; return magnitude ( p ) ; } | not used directly in algorithm but useful - override for good performance |
17,350 | private void makeCellsFlowReady ( int iteration , GridNode pitfillExitNode , List < GridNode > cellsToMakeFlowReady , BitMatrix allPitsPositions , WritableRandomIter pitIter , float delta ) { iteration ++ ; double exitElevation = pitfillExitNode . elevation ; List < GridNode > connected = new ArrayList < > ( ) ; for ( GridNode checkNode : cellsToMakeFlowReady ) { List < GridNode > validSurroundingNodes = checkNode . getValidSurroundingNodes ( ) ; for ( GridNode gridNode : validSurroundingNodes ) { if ( ! pitfillExitNode . equals ( gridNode ) && allPitsPositions . isMarked ( gridNode . col , gridNode . row ) && gridNode . elevation == exitElevation ) { if ( ! connected . contains ( gridNode ) ) connected . add ( gridNode ) ; } } } if ( connected . size ( ) == 0 ) { return ; } for ( GridNode gridNode : connected ) { double newElev = ( double ) ( gridNode . elevation + delta * ( double ) iteration ) ; gridNode . setValueInMap ( pitIter , newElev ) ; } List < GridNode > updatedConnected = new ArrayList < > ( ) ; for ( GridNode gridNode : connected ) { GridNode updatedNode = new GridNode ( pitIter , gridNode . cols , gridNode . rows , gridNode . xRes , gridNode . yRes , gridNode . col , gridNode . row ) ; updatedConnected . add ( updatedNode ) ; } makeCellsFlowReady ( iteration , pitfillExitNode , updatedConnected , allPitsPositions , pitIter , delta ) ; } | Make cells flow ready by creating a slope starting from the output cell . |
17,351 | public void setStartCoordinates ( List < Coordinate > coordinateList ) { generateTin ( coordinateList ) ; for ( int i = 0 ; i < tinGeometries . length ; i ++ ) { Coordinate [ ] coordinates = tinGeometries [ i ] . getCoordinates ( ) ; if ( ! tinCoordinateList . contains ( coordinates [ 0 ] ) ) { tinCoordinateList . add ( coordinates [ 0 ] ) ; } if ( ! tinCoordinateList . contains ( coordinates [ 1 ] ) ) { tinCoordinateList . add ( coordinates [ 1 ] ) ; } if ( ! tinCoordinateList . contains ( coordinates [ 2 ] ) ) { tinCoordinateList . add ( coordinates [ 2 ] ) ; } } didInitialize = true ; } | Sets the initial coordinates to start with . |
17,352 | public void filterOnAllData ( final ALasDataManager lasHandler ) throws Exception { final ConcurrentSkipListSet < Double > angleSet = new ConcurrentSkipListSet < Double > ( ) ; final ConcurrentSkipListSet < Double > distanceSet = new ConcurrentSkipListSet < Double > ( ) ; if ( isFirstStatsCalculation ) { pm . beginTask ( "Calculating initial statistics..." , tinGeometries . length ) ; } else { pm . beginTask ( "Filtering all data on seeds tin..." , tinGeometries . length ) ; } try { final List < Coordinate > newTotalLeftOverCoordinateList = new ArrayList < Coordinate > ( ) ; if ( threadsNum > 1 ) { ThreadedRunnable tRun = new ThreadedRunnable ( threadsNum , null ) ; for ( final Geometry tinGeom : tinGeometries ) { tRun . executeRunnable ( new Runnable ( ) { public void run ( ) { List < Coordinate > leftOverList = runFilterOnAllData ( lasHandler , angleSet , distanceSet , tinGeom ) ; synchronized ( newTotalLeftOverCoordinateList ) { newTotalLeftOverCoordinateList . addAll ( leftOverList ) ; } } } ) ; } tRun . waitAndClose ( ) ; } else { for ( final Geometry tinGeom : tinGeometries ) { List < Coordinate > leftOverList = runFilterOnAllData ( lasHandler , angleSet , distanceSet , tinGeom ) ; newTotalLeftOverCoordinateList . addAll ( leftOverList ) ; } } pm . done ( ) ; leftOverCoordinateList . clear ( ) ; leftOverCoordinateList . addAll ( newTotalLeftOverCoordinateList ) ; if ( angleSet . size ( ) > 1 ) { calculatedAngleThreshold = getMedianFromSet ( angleSet ) ; pm . message ( "Calculated angle threshold: " + calculatedAngleThreshold + " (range: " + angleSet . first ( ) + " to " + angleSet . last ( ) + ")" ) ; } else if ( angleSet . size ( ) == 0 ) { return ; } else { calculatedAngleThreshold = angleSet . first ( ) ; pm . message ( "Single angle left: " + calculatedAngleThreshold ) ; } if ( distanceSet . size ( ) > 1 ) { calculatedDistanceThreshold = getMedianFromSet ( distanceSet ) ; pm . message ( "Calculated distance threshold: " + calculatedDistanceThreshold + " (range: " + distanceSet . first ( ) + " to " + distanceSet . last ( ) + ")" ) ; } else if ( distanceSet . size ( ) == 0 ) { return ; } else { calculatedDistanceThreshold = distanceSet . first ( ) ; pm . message ( "Single distance left: " + calculatedDistanceThreshold ) ; } if ( isFirstStatsCalculation ) { isFirstStatsCalculation = false ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } | Filter data on thresholds of all available data on the tin . |
17,353 | private void generateTin ( List < Coordinate > coordinateList ) { pm . beginTask ( "Generate tin..." , - 1 ) ; DelaunayTriangulationBuilder b = new DelaunayTriangulationBuilder ( ) ; b . setSites ( coordinateList ) ; Geometry tinTriangles = b . getTriangles ( gf ) ; tinGeometries = new Geometry [ tinTriangles . getNumGeometries ( ) ] ; for ( int i = 0 ; i < tinTriangles . getNumGeometries ( ) ; i ++ ) { tinGeometries [ i ] = tinTriangles . getGeometryN ( i ) ; } pm . done ( ) ; } | Generate a tin from a given coords list . The internal tin geoms array is set from the result . |
17,354 | public STRtree generateTinIndex ( Double maxEdgeLength ) { double maxEdge = maxEdgeLength != null ? maxEdgeLength : 0.0 ; pm . beginTask ( "Creating tin indexes..." , tinGeometries . length ) ; final STRtree tinTree = new STRtree ( tinGeometries . length ) ; for ( Geometry geometry : tinGeometries ) { if ( maxEdgeLength != null ) { Coordinate [ ] coordinates = geometry . getCoordinates ( ) ; double maxLength = distance3d ( coordinates [ 0 ] , coordinates [ 1 ] , null ) ; double tmpLength = distance3d ( coordinates [ 1 ] , coordinates [ 2 ] , null ) ; if ( tmpLength > maxLength ) { maxLength = tmpLength ; } tmpLength = distance3d ( coordinates [ 2 ] , coordinates [ 0 ] , null ) ; if ( tmpLength > maxLength ) { maxLength = tmpLength ; } if ( maxLength < maxEdge ) { continue ; } } tinTree . insert ( geometry . getEnvelopeInternal ( ) , geometry ) ; } pm . done ( ) ; return tinTree ; } | Generate a spatial index on the tin geometries . |
17,355 | private Coordinate [ ] getOrderedNodes ( Coordinate c , Coordinate coordinate1 , Coordinate coordinate2 , Coordinate coordinate3 ) { double d = distance3d ( c , coordinate1 , null ) ; Coordinate nearest = coordinate1 ; Coordinate c2 = coordinate2 ; Coordinate c3 = coordinate3 ; double d2 = distance3d ( c , coordinate2 , null ) ; if ( d2 < d ) { nearest = coordinate2 ; d = d2 ; c2 = coordinate1 ; c3 = coordinate3 ; } double d3 = distance3d ( c , coordinate3 , null ) ; if ( d3 < d ) { nearest = coordinate3 ; c2 = coordinate1 ; c3 = coordinate2 ; } return new Coordinate [ ] { nearest , c2 , c3 } ; } | Order coordinates to have the first coordinate in the array as the nearest to a given coordinate c . The second and third are not ordered but randomly added . |
17,356 | public void seek ( long pos ) throws IOException { int n = ( int ) ( real_pos - pos ) ; if ( n >= 0 && n <= buf_end ) { buf_pos = buf_end - n ; } else { raf . seek ( pos ) ; buf_end = 0 ; buf_pos = 0 ; real_pos = raf . getFilePointer ( ) ; } } | If the sought position is within the buffer - simply sets the current buffer position so the next read will be from the buffer . Otherwise seeks in the RAF and reset the buffer end and current positions . |
17,357 | public final String readLine ( ) throws IOException { String str = null ; if ( buf_end - buf_pos <= 0 ) { if ( fillBuffer ( ) < 0 ) { return null ; } } int lineend = - 1 ; for ( int i = buf_pos ; i < buf_end ; i ++ ) { if ( buffer [ i ] == '\n' ) { lineend = i ; break ; } } if ( lineend < 0 ) { StringBuffer input = new StringBuffer ( 256 ) ; int c ; while ( ( ( c = read ( ) ) != - 1 ) && ( c != '\n' ) ) { input . append ( ( char ) c ) ; } if ( ( c == - 1 ) && ( input . length ( ) == 0 ) ) { return null ; } return input . toString ( ) ; } if ( lineend > 0 && buffer [ lineend - 1 ] == '\r' ) { str = new String ( buffer , 0 , buf_pos , lineend - buf_pos - 1 ) ; } else { str = new String ( buffer , 0 , buf_pos , lineend - buf_pos ) ; } buf_pos = lineend + 1 ; return str ; } | This method first decides if the buffer still contains unread contents . If it doesn t the buffer needs to be filled up . If the new line delimiter can be found in the buffer then a new line is read from the buffer and converted into String . Otherwise it will simply call the read method to read byte by byte . Although the code of the latter portion is similar to the original readLine performance is better here because the read method is buffered in the new class . |
17,358 | public static String checkSameName ( List < String > strings , String string ) { int index = 1 ; for ( int i = 0 ; i < strings . size ( ) ; i ++ ) { if ( index == 10000 ) { throw new RuntimeException ( ) ; } String existingString = strings . get ( i ) ; existingString = existingString . trim ( ) ; if ( existingString . trim ( ) . equals ( string . trim ( ) ) ) { if ( string . endsWith ( ")" ) ) { string = string . trim ( ) . replaceFirst ( "\\([0-9]+\\)$" , "(" + ( index ++ ) + ")" ) ; } else { string = string + " (" + ( index ++ ) + ")" ; } i = 0 ; } } return string ; } | Checks if the list of strings supplied contains the supplied string . |
17,359 | public static List < String > splitString ( String string , int limit ) { List < String > list = new ArrayList < String > ( ) ; char [ ] chars = string . toCharArray ( ) ; boolean endOfString = false ; int start = 0 ; int end = start ; while ( start < chars . length - 1 ) { int charCount = 0 ; int lastSpace = 0 ; while ( charCount < limit ) { if ( chars [ charCount + start ] == ' ' ) { lastSpace = charCount ; } charCount ++ ; if ( charCount + start == string . length ( ) ) { endOfString = true ; break ; } } end = endOfString ? string . length ( ) : ( lastSpace > 0 ) ? lastSpace + start : charCount + start ; list . add ( string . substring ( start , end ) ) ; start = end + 1 ; } return list ; } | Splits a string by char limit not breaking works . |
17,360 | @ SuppressWarnings ( "resource" ) public static Scanner streamToScanner ( InputStream stream , String delimiter ) { java . util . Scanner s = new java . util . Scanner ( stream ) . useDelimiter ( delimiter ) ; return s ; } | Get scanner from input stream . |
17,361 | public static double [ ] stringToDoubleArray ( String string , String separator ) { if ( separator == null ) { separator = "," ; } String [ ] stringSplit = string . trim ( ) . split ( separator ) ; double [ ] array = new double [ stringSplit . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { array [ i ] = Double . parseDouble ( stringSplit [ i ] . trim ( ) ) ; } return array ; } | Convert a string containing a list of numbers into its array . |
17,362 | public String getTextDescription ( ) { StringBuilder builder = new StringBuilder ( name ) ; builder . append ( " " ) ; List < Location > locationList = new ArrayList < Location > ( locations . getLocations ( ) ) ; Collections . sort ( locationList , new LocationComparator ( LocationComparator . START_LOCATION ) ) ; for ( Location location : locationList ) { builder . append ( " " ) ; builder . append ( location . getBeginPosition ( ) ) ; builder . append ( "-" ) ; builder . append ( location . getEndPosition ( ) ) ; } return builder . toString ( ) ; } | The feature name and location as a string - handy for text summary |
17,363 | public byte [ ] seal ( byte [ ] plaintext ) { final byte [ ] nonce = box . nonce ( plaintext ) ; final byte [ ] ciphertext = box . seal ( nonce , plaintext ) ; final byte [ ] combined = new byte [ nonce . length + ciphertext . length ] ; System . arraycopy ( nonce , 0 , combined , 0 , nonce . length ) ; System . arraycopy ( ciphertext , 0 , combined , nonce . length , ciphertext . length ) ; return combined ; } | Encrypt the plaintext with the given key . |
17,364 | public Optional < byte [ ] > open ( byte [ ] ciphertext ) { if ( ciphertext . length < SecretBox . NONCE_SIZE ) { return Optional . empty ( ) ; } final byte [ ] nonce = Arrays . copyOfRange ( ciphertext , 0 , SecretBox . NONCE_SIZE ) ; final byte [ ] x = Arrays . copyOfRange ( ciphertext , SecretBox . NONCE_SIZE , ciphertext . length ) ; return box . open ( nonce , x ) ; } | Decrypt the ciphertext with the given key . |
17,365 | public void readDwgVertex3DV15 ( int [ ] data , int offset ) throws Exception { int bitPos = offset ; bitPos = readObjectHeaderV15 ( data , bitPos ) ; Vector v = DwgUtil . getRawChar ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; int flags = ( ( Integer ) v . get ( 1 ) ) . intValue ( ) ; this . flags = flags ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double x = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double y = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; double z = ( ( Double ) v . get ( 1 ) ) . doubleValue ( ) ; double [ ] coord = new double [ ] { x , y , z } ; point = new double [ ] { x , y , z } ; bitPos = readObjectTailV15 ( data , bitPos ) ; } | Read a Vertex3D in the DWG format Version 15 |
17,366 | public static void addPrj ( String folder , String epsg ) throws Exception { OmsFileIterator fiter = new OmsFileIterator ( ) ; fiter . inFolder = folder ; fiter . pCode = epsg ; fiter . process ( ) ; } | Utility to add to all found files in a given folder the prj file following the supplied epsg . |
17,367 | public void process ( ) throws Exception { if ( ! concatOr ( outFlow == null , doReset ) ) { return ; } checkNull ( inFlow , inPit ) ; RegionMap regionMap = CoverageUtilities . getRegionParamsFromGridCoverage ( inPit ) ; cols = regionMap . getCols ( ) ; rows = regionMap . getRows ( ) ; xRes = regionMap . getXres ( ) ; yRes = regionMap . getYres ( ) ; dxySqrt = Math . sqrt ( xRes * xRes + yRes * yRes ) ; RenderedImage pitfillerRI = inPit . getRenderedImage ( ) ; WritableRaster pitfillerWR = CoverageUtilities . renderedImage2DoubleWritableRaster ( pitfillerRI , true ) ; RenderedImage flowRI = inFlow . getRenderedImage ( ) ; WritableRaster flowWR = CoverageUtilities . renderedImage2ShortWritableRaster ( flowRI , true ) ; RandomIter pitRandomIter = RandomIterFactory . create ( pitfillerWR , null ) ; double [ ] orderedelev = new double [ cols * rows ] ; int [ ] indexes = new int [ cols * rows ] ; int nelev = 0 ; for ( int r = 0 ; r < rows ; r ++ ) { if ( pm . isCanceled ( ) ) { return ; } for ( int c = 0 ; c < cols ; c ++ ) { double pitValue = pitRandomIter . getSampleDouble ( c , r , 0 ) ; int pos = ( r * cols ) + c ; orderedelev [ pos ] = pitValue ; indexes [ pos ] = pos + 1 ; if ( ! isNovalue ( pitValue ) ) { nelev = nelev + 1 ; } } } QuickSortAlgorithm t = new QuickSortAlgorithm ( pm ) ; t . sort ( orderedelev , indexes ) ; pm . message ( msg . message ( "draindir.initializematrix" ) ) ; WritableRaster tcaWR = CoverageUtilities . createWritableRaster ( cols , rows , Integer . class , null , HMConstants . intNovalue ) ; WritableRaster dirWR = CoverageUtilities . createWritableRaster ( cols , rows , Short . class , null , HMConstants . shortNovalue ) ; WritableRaster deviationsWR = CoverageUtilities . createWritableRaster ( cols , rows , Double . class , null , null ) ; BitMatrix analizedMatrix = new BitMatrix ( cols , rows ) ; if ( doLad ) { orlandiniD8LAD ( indexes , deviationsWR , analizedMatrix , pitfillerWR , flowWR , tcaWR , dirWR , nelev ) ; } else { orlandiniD8LTD ( indexes , deviationsWR , analizedMatrix , pitfillerWR , flowWR , tcaWR , dirWR , nelev ) ; if ( pm . isCanceled ( ) ) { return ; } if ( inFlownet != null ) { newDirections ( pitfillerWR , dirWR ) ; } } if ( pm . isCanceled ( ) ) { return ; } outFlow = CoverageUtilities . buildCoverage ( "draindir" , dirWR , regionMap , inPit . getCoordinateReferenceSystem ( ) ) ; outTca = CoverageUtilities . buildCoverage ( "tca" , tcaWR , regionMap , inPit . getCoordinateReferenceSystem ( ) ) ; } | Calculates new drainage directions |
17,368 | public static void fillProjectMetadata ( Connection connection , String name , String description , String notes , String creationUser ) throws Exception { Date creationDate = new Date ( ) ; if ( name == null ) { name = "project-" + ETimeUtilities . INSTANCE . TIME_FORMATTER_LOCAL . format ( creationDate ) ; } if ( description == null ) { description = EMPTY_VALUE ; } if ( notes == null ) { notes = EMPTY_VALUE ; } if ( creationUser == null ) { creationUser = "dummy user" ; } insertPair ( connection , MetadataTableFields . KEY_NAME . getFieldName ( ) , name ) ; insertPair ( connection , MetadataTableFields . KEY_DESCRIPTION . getFieldName ( ) , description ) ; insertPair ( connection , MetadataTableFields . KEY_NOTES . getFieldName ( ) , notes ) ; insertPair ( connection , MetadataTableFields . KEY_CREATIONTS . getFieldName ( ) , String . valueOf ( creationDate . getTime ( ) ) ) ; insertPair ( connection , MetadataTableFields . KEY_LASTTS . getFieldName ( ) , EMPTY_VALUE ) ; insertPair ( connection , MetadataTableFields . KEY_CREATIONUSER . getFieldName ( ) , creationUser ) ; insertPair ( connection , MetadataTableFields . KEY_LASTUSER . getFieldName ( ) , EMPTY_VALUE ) ; } | Populate the project metadata table . |
17,369 | protected List < JavaFileObject > listClassesFromUrl ( URL base , String packageName ) throws IOException { if ( base == null ) { throw new NullPointerException ( "base == null" ) ; } List < JavaFileObject > list = new ArrayList < JavaFileObject > ( ) ; URLConnection connection = base . openConnection ( ) ; connection . connect ( ) ; String encoding = connection . getContentEncoding ( ) ; if ( encoding == null ) { encoding = "UTF-8" ; } BufferedReader reader = new BufferedReader ( new InputStreamReader ( connection . getInputStream ( ) , encoding ) ) ; try { String curLine ; do { curLine = reader . readLine ( ) ; if ( curLine != null && curLine . endsWith ( ".class" ) ) { try { String curSimpleName = curLine . substring ( 0 , curLine . length ( ) - ".class" . length ( ) ) ; String binaryName ; if ( packageName == null ) { binaryName = curSimpleName ; } else { binaryName = packageName + "." + curSimpleName ; } list . add ( new UrlJavaFileObject ( curLine , new URL ( base , curLine ) , Kind . CLASS , binaryName ) ) ; } catch ( URISyntaxException e ) { throw new IOException ( "Error parsing URL " + curLine + "." , e ) ; } } } while ( curLine != null ) ; } finally { reader . close ( ) ; } return list ; } | Lists all files at a specified URL . |
17,370 | public static int [ ] sliceByTime ( CSTable table , int timeCol , Date start , Date end ) { if ( end . before ( start ) ) { throw new IllegalArgumentException ( "end<start" ) ; } if ( timeCol < 0 ) { throw new IllegalArgumentException ( "timeCol :" + timeCol ) ; } int s = - 1 ; int e = - 1 ; int i = - 1 ; for ( String [ ] col : table . rows ( ) ) { i ++ ; Date d = Conversions . convert ( col [ timeCol ] , Date . class ) ; if ( s == - 1 && ( start . before ( d ) || start . equals ( d ) ) ) { s = i ; } if ( e == - 1 && ( end . before ( d ) || end . equals ( d ) ) ) { e = i ; break ; } } return new int [ ] { s , e } ; } | Get a slice of rows out of the table matching the time window |
17,371 | public static AbstractTableModel getProperties ( final CSProperties p ) { return new AbstractTableModel ( ) { public int getRowCount ( ) { return p . keySet ( ) . size ( ) ; } public int getColumnCount ( ) { return 2 ; } public Object getValueAt ( int rowIndex , int columnIndex ) { if ( columnIndex == 0 ) { return " " + p . keySet ( ) . toArray ( ) [ rowIndex ] ; } else { return p . values ( ) . toArray ( ) [ rowIndex ] ; } } public boolean isCellEditable ( int rowIndex , int columnIndex ) { return columnIndex == 1 ; } public void setValueAt ( Object aValue , int rowIndex , int columnIndex ) { if ( columnIndex == 1 ) { String [ ] keys = p . keySet ( ) . toArray ( new String [ 0 ] ) ; p . put ( keys [ rowIndex ] , aValue . toString ( ) ) ; } } public String getColumnName ( int column ) { return column == 0 ? "Name" : "Value" ; } public Class < ? > getColumnClass ( int columnIndex ) { return String . class ; } } ; } | Get the KVP as table . |
17,372 | public static String toArrayString ( String [ ] arr ) { StringBuilder b = new StringBuilder ( ) ; b . append ( '{' ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { b . append ( arr [ i ] ) ; if ( i < arr . length - 1 ) { b . append ( ',' ) ; } } b . append ( '}' ) ; return b . toString ( ) ; } | Create array string . |
17,373 | public static Double [ ] getColumnDoubleValues ( CSTable t , String columnName ) { int col = columnIndex ( t , columnName ) ; if ( col == - 1 ) { throw new IllegalArgumentException ( "No such column: " + columnName ) ; } List < Double > l = new ArrayList < Double > ( ) ; for ( String [ ] s : t . rows ( ) ) { l . add ( new Double ( s [ col ] ) ) ; } return l . toArray ( new Double [ 0 ] ) ; } | Get a column as an int array . |
17,374 | public static Date getDate ( CSProperties p , String key ) throws ParseException { String val = p . get ( key ) . toString ( ) ; if ( val == null ) { throw new IllegalArgumentException ( key ) ; } String f = p . getInfo ( key ) . get ( KEY_FORMAT ) ; DateFormat fmt = new SimpleDateFormat ( f == null ? ISO8601 : f ) ; return fmt . parse ( val ) ; } | Get a value as date . |
17,375 | public static int getInt ( CSProperties p , String key ) throws ParseException { String val = p . get ( key ) . toString ( ) ; if ( val == null ) { throw new IllegalArgumentException ( key ) ; } return Integer . parseInt ( val ) ; } | Get a value as integer . |
17,376 | public static void print ( CSProperties props , PrintWriter out ) { out . println ( PROPERTIES + "," + CSVParser . printLine ( props . getName ( ) ) ) ; for ( String key : props . getInfo ( ) . keySet ( ) ) { out . println ( " " + CSVParser . printLine ( key , props . getInfo ( ) . get ( key ) ) ) ; } out . println ( ) ; for ( String key : props . keySet ( ) ) { out . println ( PROPERTY + "," + CSVParser . printLine ( key , props . get ( key ) . toString ( ) ) ) ; for ( String key1 : props . getInfo ( key ) . keySet ( ) ) { out . println ( " " + CSVParser . printLine ( key1 , props . getInfo ( key ) . get ( key1 ) ) ) ; } out . println ( ) ; } out . println ( ) ; out . flush ( ) ; } | Print CSProperties . |
17,377 | public static void print ( CSTable table , PrintWriter out ) { out . println ( TABLE + "," + CSVParser . printLine ( table . getName ( ) ) ) ; for ( String key : table . getInfo ( ) . keySet ( ) ) { out . println ( CSVParser . printLine ( key , table . getInfo ( ) . get ( key ) ) ) ; } if ( table . getColumnCount ( ) < 1 ) { out . flush ( ) ; return ; } out . print ( HEADER ) ; for ( int i = 1 ; i <= table . getColumnCount ( ) ; i ++ ) { out . print ( "," + table . getColumnName ( i ) ) ; } out . println ( ) ; Map < String , String > m = table . getColumnInfo ( 1 ) ; for ( String key : m . keySet ( ) ) { out . print ( key ) ; for ( int i = 1 ; i <= table . getColumnCount ( ) ; i ++ ) { out . print ( "," + table . getColumnInfo ( i ) . get ( key ) ) ; } out . println ( ) ; } for ( String [ ] row : table . rows ( ) ) { for ( int i = 1 ; i < row . length ; i ++ ) { out . print ( "," + row [ i ] ) ; } out . println ( ) ; } out . println ( ) ; out . flush ( ) ; } | Print a CSTable to a PrintWriter |
17,378 | public static void save ( CSTable table , File file ) throws IOException { PrintWriter w = new PrintWriter ( file ) ; print ( table , w ) ; w . close ( ) ; } | Saves a table to a file . |
17,379 | public static CSProperties properties ( Reader r , String name ) throws IOException { return new CSVProperties ( r , name ) ; } | Parse properties from a reader |
17,380 | public static CSProperties properties ( Reader [ ] r , String name ) throws IOException { CSVProperties p = new CSVProperties ( r [ 0 ] , name ) ; for ( int i = 1 ; i < r . length ; i ++ ) { CSVParser csv = new CSVParser ( r [ i ] , CSVStrategy . DEFAULT_STRATEGY ) ; locate ( csv , name , PROPERTIES , PROPERTIES1 ) ; p . readProps ( csv ) ; r [ i ] . close ( ) ; } return p ; } | Create a CSProperty from an array of reader . |
17,381 | public static void merge ( CSProperties base , CSProperties overlay ) { for ( String key : overlay . keySet ( ) ) { if ( base . getInfo ( key ) . containsKey ( "public" ) ) { base . put ( key , overlay . get ( key ) ) ; } else { throw new IllegalArgumentException ( "Not public: " + key ) ; } } } | Merges two Properties respects permissions |
17,382 | public static Properties properties ( CSProperties p ) { Properties pr = new Properties ( ) ; pr . putAll ( p ) ; return pr ; } | Convert CSProperties into Properties |
17,383 | public static CSTable table ( File file , String name ) throws IOException { return new FileTable ( file , name ) ; } | Parse a table from a given File . |
17,384 | public static CSTable table ( String s , String name ) throws IOException { return new StringTable ( s , name ) ; } | Parse a table from a Reader . |
17,385 | public static CSTable table ( URL url , String name ) throws IOException { return new URLTable ( url , name ) ; } | Create a CSTable from a URL source . |
17,386 | public static boolean columnExist ( CSTable table , String name ) { for ( int i = 1 ; i <= table . getColumnCount ( ) ; i ++ ) { if ( table . getColumnName ( i ) . startsWith ( name ) ) { return true ; } } return false ; } | Check if a column exist in table . |
17,387 | public static int columnIndex ( CSTable table , String name ) { for ( int i = 1 ; i <= table . getColumnCount ( ) ; i ++ ) { if ( table . getColumnName ( i ) . equals ( name ) ) { return i ; } } return - 1 ; } | Gets a column index by name |
17,388 | public static CSTable extractColumns ( CSTable table , String ... colNames ) { int [ ] idx = { } ; for ( String name : colNames ) { idx = add ( idx , columnIndexes ( table , name ) ) ; } if ( idx . length == 0 ) { throw new IllegalArgumentException ( "No such column names: " + Arrays . toString ( colNames ) ) ; } List < String > cols = new ArrayList < String > ( ) ; for ( String name : colNames ) { cols . addAll ( columnNames ( table , name ) ) ; } MemoryTable t = new MemoryTable ( ) ; t . setName ( table . getName ( ) ) ; t . getInfo ( ) . putAll ( table . getInfo ( ) ) ; t . setColumns ( cols . toArray ( new String [ 0 ] ) ) ; for ( int i = 0 ; i < idx . length ; i ++ ) { t . getColumnInfo ( i + 1 ) . putAll ( table . getColumnInfo ( idx [ i ] ) ) ; } String [ ] r = new String [ idx . length ] ; for ( String [ ] row : table . rows ( ) ) { rowStringValues ( row , idx , r ) ; t . addRow ( ( Object [ ] ) r ) ; } return t ; } | Extract the columns and create another table . |
17,389 | private static void par_ief ( CompList < ? > t , int numproc ) throws Exception { if ( numproc < 1 ) { throw new IllegalArgumentException ( "numproc" ) ; } final CountDownLatch latch = new CountDownLatch ( t . list ( ) . size ( ) ) ; for ( final Compound c : t ) { e . submit ( new Runnable ( ) { public void run ( ) { try { ComponentAccess . callAnnotated ( c , Initialize . class , true ) ; c . execute ( ) ; ComponentAccess . callAnnotated ( c , Finalize . class , true ) ; } catch ( Throwable E ) { e . shutdownNow ( ) ; } latch . countDown ( ) ; } } ) ; } latch . await ( ) ; } | Runs a set of Compounds in parallel . there are always numproc + 1 threads active . |
17,390 | public void addInput ( String fieldName , String type , String description , String defaultValue , String uiHint ) { if ( fieldName == null ) { throw new IllegalArgumentException ( "field name is mandatory" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "field type is mandatory" ) ; } if ( description == null ) { description = "No description available" ; } FieldData fieldData = new FieldData ( ) ; fieldData . isIn = true ; fieldData . fieldName = fieldName ; fieldData . fieldType = type ; fieldData . fieldDescription = description ; fieldData . fieldValue = defaultValue ; fieldData . guiHints = uiHint ; if ( ! inputsList . contains ( fieldData ) ) { inputsList . add ( fieldData ) ; } else { throw new IllegalArgumentException ( "Duplicated field: " + fieldName ) ; } } | Adds an input field to the module . |
17,391 | public void addOutput ( String fieldName , String type , String description , String defaultValue , String uiHint ) { if ( fieldName == null ) { throw new IllegalArgumentException ( "field name is mandatory" ) ; } if ( type == null ) { throw new IllegalArgumentException ( "field type is mandatory" ) ; } if ( description == null ) { description = "No description available" ; } FieldData fieldData = new FieldData ( ) ; fieldData . isIn = false ; fieldData . fieldName = fieldName ; fieldData . fieldType = type ; fieldData . fieldDescription = description ; fieldData . fieldValue = defaultValue ; fieldData . guiHints = uiHint ; if ( ! outputsList . contains ( fieldData ) ) { outputsList . add ( fieldData ) ; } else { throw new IllegalArgumentException ( "Duplicated field: " + fieldName ) ; } } | Adds an output field to the module . |
17,392 | public static String getPreference ( String preferenceKey , String defaultValue ) { Preferences preferences = Preferences . userRoot ( ) . node ( PREFS_NODE_NAME ) ; String preference = preferences . get ( preferenceKey , defaultValue ) ; return preference ; } | Get from preference . |
17,393 | public static String getProcessPid ( Session session , String userName , String grep1 , String grep2 ) throws JSchException , IOException { String command = "ps aux | grep \"" + grep1 + "\" | grep -v grep" ; String remoteResponseStr = launchACommand ( session , command ) ; if ( remoteResponseStr . length ( ) == 0 ) { return null ; } List < String > pidsList = new ArrayList < > ( ) ; String [ ] linesSplit = remoteResponseStr . split ( "\n" ) ; for ( String line : linesSplit ) { if ( ! line . contains ( grep2 ) ) { continue ; } String [ ] psSplit = line . split ( "\\s+" ) ; if ( psSplit . length < 3 ) { throw new JSchException ( "Could not retrieve process data. Result was: " + line ) ; } String user = psSplit [ 0 ] ; if ( userName != null && ! user . equals ( userName ) ) { continue ; } String pid = psSplit [ 1 ] ; try { Integer . parseInt ( pid ) ; } catch ( Exception e ) { throw new JSchException ( "The pid is invalid: " + pid ) ; } pidsList . add ( pid ) ; } if ( pidsList . size ( ) > 1 ) { throw new JSchException ( "More than one process was identified with the given filters. Check your filters." ) ; } else if ( pidsList . size ( ) == 0 ) { return null ; } return pidsList . get ( 0 ) ; } | Get the pid of a process identified by a consequent grepping on a ps aux command . |
17,394 | public static void killProcessByPid ( Session session , int pid ) throws Exception { String command = "kill -9 " + pid ; String remoteResponseStr = launchACommand ( session , command ) ; if ( remoteResponseStr . length ( ) == 0 ) { return ; } else { new Exception ( remoteResponseStr ) ; } } | Kills a process using its pid . |
17,395 | public static String getRunningDockerContainerId ( Session session , String containerName ) throws JSchException , IOException { String command = "docker ps | grep " + containerName ; String remoteResponseStr = launchACommand ( session , command ) ; if ( remoteResponseStr . length ( ) == 0 ) { return null ; } List < String > containerIdsList = new ArrayList < > ( ) ; String [ ] linesSplit = remoteResponseStr . split ( "\n" ) ; for ( String line : linesSplit ) { String [ ] psSplit = line . split ( "\\s+" ) ; if ( psSplit . length < 3 ) { throw new JSchException ( "Could not retrieve container data. Result was: " + line ) ; } String cid = psSplit [ 0 ] ; containerIdsList . add ( cid ) ; } if ( containerIdsList . size ( ) > 1 ) { throw new JSchException ( "More than one container was identified with the given filters. Check your filters." ) ; } else if ( containerIdsList . size ( ) == 0 ) { return null ; } return containerIdsList . get ( 0 ) ; } | Get the container id of a running docker container . |
17,396 | private static String launchACommand ( Session session , String command ) throws JSchException , IOException { Channel channel = session . openChannel ( "exec" ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; channel . setInputStream ( null ) ; ( ( ChannelExec ) channel ) . setErrStream ( System . err ) ; InputStream in = channel . getInputStream ( ) ; channel . connect ( ) ; StringBuilder sb = new StringBuilder ( ) ; byte [ ] tmp = new byte [ 1024 ] ; while ( true ) { while ( in . available ( ) > 0 ) { int i = in . read ( tmp , 0 , 1024 ) ; if ( i < 0 ) break ; sb . append ( new String ( tmp , 0 , i ) ) ; } if ( channel . isClosed ( ) ) { if ( in . available ( ) > 0 ) continue ; System . out . println ( "exitstatus: " + channel . getExitStatus ( ) ) ; break ; } try { Thread . sleep ( 1000 ) ; } catch ( Exception ee ) { } } channel . disconnect ( ) ; String remoteResponseStr = sb . toString ( ) . trim ( ) ; return remoteResponseStr ; } | Launch a command on the remote host and exit once the command is done . |
17,397 | public static String runShellCommand ( Session session , String command ) throws JSchException , IOException { String remoteResponseStr = launchACommand ( session , command ) ; return remoteResponseStr ; } | Launch a shell command . |
17,398 | public static String runDemonShellCommand ( Session session , String command ) throws JSchException , IOException { String remoteResponseStr = launchACommandAndExit ( session , command ) ; return remoteResponseStr ; } | Run a daemon command or commands that do not exit quickly . |
17,399 | public static void downloadFile ( Session session , String remoteFilePath , String localFilePath ) throws Exception { String command = "scp -f " + remoteFilePath ; Channel channel = session . openChannel ( "exec" ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; OutputStream out = channel . getOutputStream ( ) ; InputStream in = channel . getInputStream ( ) ; channel . connect ( ) ; byte [ ] buf = new byte [ 1024 ] ; buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; while ( true ) { int c = checkAck ( in ) ; if ( c != 'C' ) { break ; } in . read ( buf , 0 , 5 ) ; long filesize = 0L ; while ( true ) { if ( in . read ( buf , 0 , 1 ) < 0 ) { break ; } if ( buf [ 0 ] == ' ' ) break ; filesize = filesize * 10L + ( long ) ( buf [ 0 ] - '0' ) ; } String file = null ; for ( int i = 0 ; ; i ++ ) { in . read ( buf , i , 1 ) ; if ( buf [ i ] == ( byte ) 0x0a ) { file = new String ( buf , 0 , i ) ; break ; } } System . out . println ( "filesize=" + filesize + ", file=" + file ) ; buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; FileOutputStream fos = new FileOutputStream ( localFilePath ) ; int foo ; while ( true ) { if ( buf . length < filesize ) foo = buf . length ; else foo = ( int ) filesize ; foo = in . read ( buf , 0 , foo ) ; if ( foo < 0 ) { break ; } fos . write ( buf , 0 , foo ) ; filesize -= foo ; if ( filesize == 0L ) break ; } fos . close ( ) ; if ( checkAck ( in ) != 0 ) { throw new RuntimeException ( ) ; } buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; } } | Download a remote file via scp . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.