idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
17,400 | private String escapeAndQuote ( String value ) { // the initial count is for the preceding and trailing quotes int count = 2 ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { switch ( value . charAt ( i ) ) { case ' ' : case ' ' : case ' ' : case ' ' : count ++ ; break ; default : break ; } } StringBuffer sb = new StringBuffer ( value . length ( ) + count ) ; sb . append ( strategy . getEncapsulator ( ) ) ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char c = value . charAt ( i ) ; if ( c == strategy . getEncapsulator ( ) ) { sb . append ( ' ' ) . append ( c ) ; continue ; } switch ( c ) { case ' ' : sb . append ( "\\n" ) ; break ; case ' ' : sb . append ( "\\r" ) ; break ; case ' ' : sb . append ( "\\\\" ) ; break ; default : sb . append ( c ) ; } } sb . append ( strategy . getEncapsulator ( ) ) ; return sb . toString ( ) ; } | Enclose the value in quotes and escape the quote and comma characters that are inside . | 269 | 17 |
17,401 | public static double calculateSlope ( GridNode node , double flowValue ) { double value = doubleNovalue ; if ( ! isNovalue ( flowValue ) ) { int flowDir = ( int ) flowValue ; if ( flowDir != 10 ) { Direction direction = Direction . forFlow ( flowDir ) ; double distance = direction . getDistance ( node . xRes , node . yRes ) ; double currentElevation = node . elevation ; double nextElevation = node . getElevationAt ( direction ) ; value = ( currentElevation - nextElevation ) / distance ; } } return value ; } | Calculates the slope of a given flowdirection value in currentCol and currentRow . | 135 | 18 |
17,402 | public static String [ ] getAvailablePortNames ( ) { SerialPort [ ] ports = SerialPort . getCommPorts ( ) ; String [ ] portNames = new String [ ports . length ] ; for ( int i = 0 ; i < portNames . length ; i ++ ) { String systemPortName = ports [ i ] . getSystemPortName ( ) ; portNames [ i ] = systemPortName ; } return portNames ; } | Getter for the available serial ports . | 93 | 8 |
17,403 | public static boolean isThisAGpsPort ( String port ) throws Exception { SerialPort comPort = SerialPort . getCommPort ( port ) ; comPort . openPort ( ) ; comPort . setComPortTimeouts ( SerialPort . TIMEOUT_READ_SEMI_BLOCKING , 100 , 0 ) ; int waitTries = 0 ; int parseTries = 0 ; while ( true && waitTries ++ < 10 && parseTries < 2 ) { while ( comPort . bytesAvailable ( ) == 0 ) Thread . sleep ( 500 ) ; byte [ ] readBuffer = new byte [ comPort . bytesAvailable ( ) ] ; int numRead = comPort . readBytes ( readBuffer , readBuffer . length ) ; if ( numRead > 0 ) { String data = new String ( readBuffer ) ; String [ ] split = data . split ( "\n" ) ; for ( String line : split ) { if ( SentenceValidator . isSentence ( line ) ) { return true ; } } parseTries ++ ; } } return false ; } | Makes a blocking check to find out if the given port supplies GPS data . | 227 | 16 |
17,404 | public InvertibleMatrix inverse ( ) throws MatrixException { InvertibleMatrix inverse = new InvertibleMatrix ( nRows ) ; IdentityMatrix identity = new IdentityMatrix ( nRows ) ; // Compute each column of the inverse matrix // using columns of the identity matrix. for ( int c = 0 ; c < nCols ; ++ c ) { ColumnVector col = solve ( identity . getColumn ( c ) , true ) ; inverse . setColumn ( col , c ) ; } return inverse ; } | Compute the inverse of this matrix . | 108 | 8 |
17,405 | public double determinant ( ) throws MatrixException { decompose ( ) ; // Each row exchange during forward elimination flips the sign // of the determinant, so check for an odd number of exchanges. double determinant = ( ( exchangeCount & 1 ) == 0 ) ? 1 : - 1 ; // Form the product of the diagonal elements of matrix U. for ( int i = 0 ; i < nRows ; ++ i ) { int pi = permutation [ i ] ; // permuted index determinant *= LU . at ( pi , i ) ; } return determinant ; } | Compute the determinant . | 121 | 6 |
17,406 | public double norm ( ) { double sum = 0 ; for ( int r = 0 ; r < nRows ; ++ r ) { for ( int c = 0 ; c < nCols ; ++ c ) { double v = values [ r ] [ c ] ; sum += v * v ; } } return ( double ) Math . sqrt ( sum ) ; } | Compute the Euclidean norm of this matrix . | 77 | 11 |
17,407 | private static boolean isleap ( double gpsTime ) { boolean isLeap = false ; double [ ] leaps = getleaps ( ) ; for ( int i = 0 ; i < leaps . length ; i += 1 ) { if ( gpsTime == leaps [ i ] ) { isLeap = true ; break ; } } return isLeap ; } | Test to see if a GPS second is a leap second | 77 | 11 |
17,408 | private static int countleaps ( double gpsTime , boolean accum_leaps ) { int i , nleaps ; double [ ] leaps = getleaps ( ) ; nleaps = 0 ; if ( accum_leaps ) { for ( i = 0 ; i < leaps . length ; i += 1 ) { if ( gpsTime + i >= leaps [ i ] ) { nleaps += 1 ; } } } else { for ( i = 0 ; i < leaps . length ; i += 1 ) { if ( gpsTime >= leaps [ i ] ) { nleaps += 1 ; } } } return nleaps ; } | Count number of leap seconds that have passed | 137 | 8 |
17,409 | private static boolean isunixtimeleap ( double unixTime ) { double gpsTime = unixTime - 315964800 ; gpsTime += countleaps ( gpsTime , true ) - 1 ; return isleap ( gpsTime ) ; } | Test to see if a unixtime second is a leap second | 58 | 13 |
17,410 | public static EGpsWeekDays gpsWeekTime2WeekDay ( double gpsWeekTime ) { int seconds = ( int ) gpsWeekTime ; // week starts with Sunday EGpsWeekDays day4Seconds = EGpsWeekDays . getDay4Seconds ( seconds ) ; return day4Seconds ; } | Convert GPS Week Time to the day of the week . | 67 | 12 |
17,411 | public static String gpsWeekTime2ISO8601 ( double gpsWeekTime ) { DateTime gps2unix = gpsWeekTime2DateTime ( gpsWeekTime ) ; return gps2unix . toString ( ISO8601Formatter ) ; } | Convert GPS Time to ISO8601 time string . | 59 | 11 |
17,412 | private void updateComponents ( ) { updatingComponents = true ; Font font = getFont ( ) ; fontList . setSelectedValue ( font . getName ( ) , true ) ; sizeList . setSelectedValue ( font . getSize ( ) , true ) ; boldCheckBox . setSelected ( font . isBold ( ) ) ; italicCheckBox . setSelected ( font . isItalic ( ) ) ; if ( previewText == null ) { previewLabel . setText ( font . getName ( ) ) ; } // set the font and fire a property change Font oldValue = previewLabel . getFont ( ) ; previewLabel . setFont ( font ) ; firePropertyChange ( "font" , oldValue , font ) ; updatingComponents = false ; } | Updates the font in the preview component according to the selected values . | 168 | 14 |
17,413 | public void setSelectionModel ( FontSelectionModel newModel ) { FontSelectionModel oldModel = selectionModel ; selectionModel = newModel ; oldModel . removeChangeListener ( labelUpdater ) ; newModel . addChangeListener ( labelUpdater ) ; firePropertyChange ( "selectionModel" , oldModel , newModel ) ; } | Set the model containing the selected font . | 74 | 8 |
17,414 | protected void fireChangeListeners ( ) { ChangeEvent ev = new ChangeEvent ( this ) ; Object [ ] l = listeners . getListeners ( ChangeListener . class ) ; for ( Object listener : l ) { ( ( ChangeListener ) listener ) . stateChanged ( ev ) ; } } | Fires the listeners registered with this model . | 61 | 9 |
17,415 | @ Execute public void process ( ) throws Exception { if ( ! concatOr ( outPit == null , doReset ) ) { return ; } checkNull ( inElev ) ; HashMap < String , Double > regionMap = CoverageUtilities . getRegionParamsFromGridCoverage ( inElev ) ; nCols = regionMap . get ( CoverageUtilities . COLS ) . intValue ( ) ; nRows = regionMap . get ( CoverageUtilities . ROWS ) . intValue ( ) ; xRes = regionMap . get ( CoverageUtilities . XRES ) ; yRes = regionMap . get ( CoverageUtilities . YRES ) ; elevationIter = CoverageUtilities . getRandomIterator ( inElev ) ; // output raster WritableRaster pitRaster = CoverageUtilities . createWritableRaster ( nCols , nRows , null , null , null ) ; pitIter = CoverageUtilities . getWritableRandomIterator ( pitRaster ) ; for ( int i = 0 ; i < nRows ; i ++ ) { if ( pm . isCanceled ( ) ) { return ; } for ( int j = 0 ; j < nCols ; j ++ ) { double value = elevationIter . getSampleDouble ( j , i , 0 ) ; if ( ! isNovalue ( value ) ) { pitIter . setSample ( j , i , 0 , value ) ; } else { pitIter . setSample ( j , i , 0 , PITNOVALUE ) ; } } } flood ( ) ; if ( pm . isCanceled ( ) ) { return ; } for ( int i = 0 ; i < nRows ; i ++ ) { if ( pm . isCanceled ( ) ) { return ; } for ( int j = 0 ; j < nCols ; j ++ ) { if ( dir [ j ] [ i ] == 0 ) { return ; } double value = pitIter . getSampleDouble ( j , i , 0 ) ; if ( value == PITNOVALUE || isNovalue ( value ) ) { pitIter . setSample ( j , i , 0 , doubleNovalue ) ; } } } pitIter . done ( ) ; outPit = CoverageUtilities . buildCoverage ( "pitfiller" , pitRaster , regionMap , inElev . getCoordinateReferenceSystem ( ) ) ; } | The pitfiller algorithm . | 521 | 6 |
17,416 | private void flood ( ) throws Exception { /* define directions */ // Initialise the vector to a supposed dimension, if the number of // unresolved pixel overload the vector there are a method which resized // the vectors. pitsStackSize = ( int ) ( nCols * nRows * 0.1 ) ; pstack = pitsStackSize ; dn = new int [ pitsStackSize ] ; currentPitRows = new int [ pitsStackSize ] ; currentPitCols = new int [ pitsStackSize ] ; ipool = new int [ pstack ] ; jpool = new int [ pstack ] ; firstCol = 0 ; firstRow = 0 ; lastCol = nCols ; lastRow = nRows ; setdf ( ) ; } | Takes the elevation matrix and calculate a matrix with pits filled using the flooding algorithm . | 160 | 17 |
17,417 | private void addPitToStack ( int row , int col ) { currentPitsCount = currentPitsCount + 1 ; if ( currentPitsCount >= pitsStackSize ) { pitsStackSize = ( int ) ( pitsStackSize + nCols * nRows * .1 ) + 2 ; currentPitRows = realloc ( currentPitRows , pitsStackSize ) ; currentPitCols = realloc ( currentPitCols , pitsStackSize ) ; dn = realloc ( dn , pitsStackSize ) ; } currentPitRows [ currentPitsCount ] = row ; currentPitCols [ currentPitsCount ] = col ; } | Adds a pit position to the stack . | 149 | 8 |
17,418 | private int resolveFlats ( int pitsCount ) { int stillPitsCount ; currentPitsCount = pitsCount ; do { if ( pm . isCanceled ( ) ) { return - 1 ; } pitsCount = currentPitsCount ; currentPitsCount = 0 ; for ( int ip = 1 ; ip <= pitsCount ; ip ++ ) { dn [ ip ] = 0 ; } for ( int k = 1 ; k <= 8 ; k ++ ) { for ( int pitIndex = 1 ; pitIndex <= pitsCount ; pitIndex ++ ) { double elevDelta = pitIter . getSampleDouble ( currentPitCols [ pitIndex ] , currentPitRows [ pitIndex ] , 0 ) - pitIter . getSampleDouble ( currentPitCols [ pitIndex ] + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 0 ] , currentPitRows [ pitIndex ] + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 1 ] , 0 ) ; if ( ( elevDelta >= 0. ) && ( ( dir [ currentPitCols [ pitIndex ] + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 0 ] ] [ currentPitRows [ pitIndex ] + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 1 ] ] != 0 ) && ( dn [ pitIndex ] == 0 ) ) ) dn [ pitIndex ] = k ; } } stillPitsCount = 1 ; /* location of point on stack with lowest elevation */ for ( int pitIndex = 1 ; pitIndex <= pitsCount ; pitIndex ++ ) { if ( dn [ pitIndex ] > 0 ) { dir [ currentPitCols [ pitIndex ] ] [ currentPitRows [ pitIndex ] ] = dn [ pitIndex ] ; } else { currentPitsCount ++ ; currentPitRows [ currentPitsCount ] = currentPitRows [ pitIndex ] ; currentPitCols [ currentPitsCount ] = currentPitCols [ pitIndex ] ; if ( pitIter . getSampleDouble ( currentPitCols [ currentPitsCount ] , currentPitRows [ currentPitsCount ] , 0 ) < pitIter . getSampleDouble ( currentPitCols [ stillPitsCount ] , currentPitRows [ stillPitsCount ] , 0 ) ) stillPitsCount = currentPitsCount ; } } // out.println("vdn n = " + n + "nis = " + nis); } while ( currentPitsCount < pitsCount ) ; return stillPitsCount ; } | Try to find a drainage direction for undefinite cell . | 586 | 12 |
17,419 | private int pool ( int row , int col , int prevNPool ) { int in ; int jn ; int npool = prevNPool ; if ( apool [ col ] [ row ] <= 0 ) { /* not already part of a pool */ if ( dir [ col ] [ row ] != - 1 ) { /* check only dir since dir was initialized */ /* not on boundary */ apool [ col ] [ row ] = pooln ; /* apool assigned pool number */ npool = npool + 1 ; // the number of pixel in the pool if ( npool >= pstack ) { if ( pstack < nCols * nRows ) { pstack = ( int ) ( pstack + nCols * nRows * .1 ) ; if ( pstack > nCols * nRows ) { /* Pool stack too large */ } ipool = realloc ( ipool , pstack ) ; jpool = realloc ( jpool , pstack ) ; } } ipool [ npool ] = row ; jpool [ npool ] = col ; for ( int k = 1 ; k <= 8 ; k ++ ) { in = row + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 1 ] ; jn = col + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 0 ] ; /* test if neighbor drains towards cell excluding boundaries */ if ( ( ( dir [ jn ] [ in ] > 0 ) && ( ( dir [ jn ] [ in ] - k == 4 ) || ( dir [ jn ] [ in ] - k == - 4 ) ) ) || ( ( dir [ jn ] [ in ] == 0 ) && ( pitIter . getSampleDouble ( jn , in , 0 ) >= pitIter . getSampleDouble ( col , row , 0 ) ) ) ) { /* so that adjacent flats get included */ npool = pool ( in , jn , npool ) ; } } } } return npool ; } | function to compute pool recursively and at the same time determine the minimum elevation of the edge . | 434 | 20 |
17,420 | private void setDirection ( double pitValue , int row , int col , int [ ] [ ] dir , double [ ] fact ) { dir [ col ] [ row ] = 0 ; /* This necessary to repeat passes after level raised */ double smax = 0.0 ; // examine adjacent cells first for ( int k = 1 ; k <= 8 ; k ++ ) { int cn = col + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 0 ] ; int rn = row + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 1 ] ; double pitN = pitIter . getSampleDouble ( cn , rn , 0 ) ; if ( isNovalue ( pitN ) ) { dir [ col ] [ row ] = - 1 ; break ; } if ( dir [ col ] [ row ] != - 1 ) { double slope = fact [ k ] * ( pitValue - pitN ) ; if ( slope > smax ) { smax = slope ; // maximum slope gives the drainage direction dir [ col ] [ row ] = k ; } } } } | Calculate the drainage direction with the D8 method . | 243 | 12 |
17,421 | private double [ ] calculateDirectionFactor ( double dx , double dy ) { // direction factor, where the components are 1/length double [ ] fact = new double [ 9 ] ; for ( int k = 1 ; k <= 8 ; k ++ ) { fact [ k ] = 1.0 / ( Math . sqrt ( DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 0 ] * dy * DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 0 ] * dy + DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 1 ] * DIR_WITHFLOW_EXITING_INVERTED [ k ] [ 1 ] * dx * dx ) ) ; } return fact ; } | Calculate the drainage direction factor . | 171 | 8 |
17,422 | private boolean assignFlowDirection ( GridNode current , GridNode diagonal , GridNode node1 , GridNode node2 ) { double diagonalSlope = abs ( current . getSlopeTo ( diagonal ) ) ; if ( node1 != null ) { double tmpSlope = abs ( diagonal . getSlopeTo ( node1 ) ) ; if ( diagonalSlope < tmpSlope ) { return false ; } } if ( node2 != null ) { double tmpSlope = abs ( diagonal . getSlopeTo ( node2 ) ) ; if ( diagonalSlope < tmpSlope ) { return false ; } } return true ; } | Checks if the path from the current to the first node is steeper than to the others . | 134 | 20 |
17,423 | private boolean nodeOk ( GridNode node ) { return node != null && ! assignedFlowsMap . isMarked ( node . col , node . row ) ; } | Checks if the node is ok . | 35 | 8 |
17,424 | public void run ( ) throws Exception { if ( ranges == null ) { throw new ModelsIllegalargumentException ( "No ranges have been defined for the parameter space." , this ) ; } createSwarm ( ) ; double [ ] previous = null ; while ( iterationStep <= maxIterations ) { updateSwarm ( ) ; if ( printStep ( ) ) { System . out . println ( prefix + " - ITER: " + iterationStep + " global best: " + globalBest + " - for positions: " + Arrays . toString ( globalBestLocations ) ) ; } if ( function . hasConverged ( globalBest , globalBestLocations , previous ) ) { break ; } previous = globalBestLocations . clone ( ) ; } } | Run the particle swarm engine . | 161 | 6 |
17,425 | public static boolean parametersInRange ( double [ ] parameters , double [ ] ... ranges ) { for ( int i = 0 ; i < ranges . length ; i ++ ) { if ( ! NumericsUtilities . isBetween ( parameters [ i ] , ranges [ i ] ) ) { return false ; } } return true ; } | Checks if the parameters are in the ranges . | 69 | 10 |
17,426 | public static < T > T convert ( Object from , Class < ? extends T > to , Params arg ) { if ( from == null ) { throw new NullPointerException ( "from" ) ; } if ( to == null ) { throw new NullPointerException ( "to" ) ; } if ( from . getClass ( ) == String . class && to . isArray ( ) ) { return new ArrayConverter ( ( String ) from ) . getArrayForType ( to ) ; } // get it from the internal cache. @ SuppressWarnings ( "unchecked" ) Converter < Object , T > c = co . get ( key ( from . getClass ( ) , to ) ) ; if ( c == null ) { // service provider lookup c = lookupConversionService ( from . getClass ( ) , to ) ; if ( c == null ) { throw new ComponentException ( "No Converter: " + from + " (" + from . getClass ( ) + ") -> " + to ) ; } co . put ( key ( from . getClass ( ) , to ) , c ) ; } Object param = null ; if ( arg != null ) { param = arg . get ( from . getClass ( ) , to ) ; } return ( T ) c . convert ( from , param ) ; } | Convert a String value into an object of a certain type | 284 | 12 |
17,427 | @ SuppressWarnings ( "unchecked" ) private static < T > Converter < Object , T > lookupConversionService ( Class from , Class to ) { for ( ConversionProvider converter : convServices ) { Converter c = converter . getConverter ( from , to ) ; if ( c != null ) { return c ; } } return null ; } | Lookup a conversion service | 78 | 5 |
17,428 | private static Class getArrayBaseType ( Class array ) { while ( array . isArray ( ) ) { array = array . getComponentType ( ) ; } return array ; } | Get the array base type | 37 | 5 |
17,429 | private static Date parse ( String date ) { for ( int i = 0 ; i < fmt . length ; i ++ ) { try { SimpleDateFormat df = new SimpleDateFormat ( fmt [ i ] ) ; return df . parse ( date ) ; } catch ( ParseException E ) { // keep trying } } throw new IllegalArgumentException ( date ) ; } | parse the date using the formats above . This is thread safe . | 77 | 13 |
17,430 | public void fixRowsAndCols ( ) { rows = ( int ) Math . round ( ( n - s ) / ns_res ) ; if ( rows < 1 ) rows = 1 ; cols = ( int ) Math . round ( ( e - w ) / we_res ) ; if ( cols < 1 ) cols = 1 ; } | calculate rows and cols from the region and its resolution . Round if required . | 75 | 18 |
17,431 | public static Point2D . Double snapToNextHigherInActiveRegionResolution ( double x , double y , Window activeWindow ) { double minx = activeWindow . getRectangle ( ) . getBounds2D ( ) . getMinX ( ) ; double ewres = activeWindow . getWEResolution ( ) ; double xsnap = minx + ( Math . ceil ( ( x - minx ) / ewres ) * ewres ) ; double miny = activeWindow . getRectangle ( ) . getBounds2D ( ) . getMinY ( ) ; double nsres = activeWindow . getNSResolution ( ) ; double ysnap = miny + ( Math . ceil ( ( y - miny ) / nsres ) * nsres ) ; return new Point2D . Double ( xsnap , ysnap ) ; } | Moves the point given by X and Y to be on the grid of the active region . | 185 | 19 |
17,432 | public static Window getActiveWindowFromMapset ( String mapsetPath ) { File windFile = new File ( mapsetPath + File . separator + GrassLegacyConstans . WIND ) ; if ( ! windFile . exists ( ) ) { return null ; } return new Window ( windFile . getAbsolutePath ( ) ) ; } | Get the active region window from the mapset | 73 | 9 |
17,433 | public static void writeActiveWindowToMapset ( String mapsetPath , Window window ) throws IOException { writeWindowFile ( mapsetPath + File . separator + GrassLegacyConstans . WIND , window ) ; } | Write active region window to the mapset | 48 | 8 |
17,434 | public static void writeDefaultWindowToLocation ( String locationPath , Window window ) throws IOException { writeWindowFile ( locationPath + File . separator + GrassLegacyConstans . PERMANENT_MAPSET + File . separator + GrassLegacyConstans . DEFAULT_WIND , window ) ; } | Write default region window to the PERMANENT mapset | 65 | 11 |
17,435 | public static Window adaptActiveRegionToEnvelope ( Envelope bounds , Window activeRegion ) { Point2D eastNorth = Window . snapToNextHigherInActiveRegionResolution ( bounds . getMaxX ( ) , bounds . getMaxY ( ) , activeRegion ) ; Point2D westsouth = Window . snapToNextHigherInActiveRegionResolution ( bounds . getMinX ( ) - activeRegion . getWEResolution ( ) , bounds . getMinY ( ) - activeRegion . getNSResolution ( ) , activeRegion ) ; Window tmp = new Window ( westsouth . getX ( ) , eastNorth . getX ( ) , westsouth . getY ( ) , eastNorth . getY ( ) , activeRegion . getWEResolution ( ) , activeRegion . getNSResolution ( ) ) ; // activeRegion.setExtent(tmp); return tmp ; } | Takes an envelope and an active region and creates a new region to match the bounds of the envelope but the resolutions of the active region . This is important if the region has to match some feature layer . The bounds are assured to contain completely the envelope . | 193 | 51 |
17,436 | public double [ ] cceua ( double s [ ] [ ] , double sf [ ] , double bl [ ] , double bu [ ] ) { int nps = s . length ; int nopt = s [ 0 ] . length ; int n = nps ; int m = nopt ; double alpha = 1.0 ; double beta = 0.5 ; // Assign the best and worst points: double sb [ ] = new double [ nopt ] ; double sw [ ] = new double [ nopt ] ; double fb = sf [ 0 ] ; double fw = sf [ n - 1 ] ; for ( int i = 0 ; i < nopt ; i ++ ) { sb [ i ] = s [ 0 ] [ i ] ; sw [ i ] = s [ n - 1 ] [ i ] ; } // Compute the centroid of the simplex excluding the worst point: double ce [ ] = new double [ nopt ] ; for ( int i = 0 ; i < nopt ; i ++ ) { ce [ i ] = 0 ; for ( int j = 0 ; j < n - 1 ; j ++ ) { ce [ i ] += s [ j ] [ i ] ; } ce [ i ] /= ( n - 1 ) ; } // Attempt a reflection point double snew [ ] = new double [ nopt ] ; for ( int i = 0 ; i < nopt ; i ++ ) { snew [ i ] = ce [ i ] + alpha * ( ce [ i ] - sw [ i ] ) ; } // Check if is outside the bounds: int ibound = 0 ; for ( int i = 0 ; i < nopt ; i ++ ) { if ( ( snew [ i ] - bl [ i ] ) < 0 ) { ibound = 1 ; } if ( ( bu [ i ] - snew [ i ] ) < 0 ) { ibound = 2 ; } } if ( ibound >= 1 ) { snew = randomSampler ( ) ; } double fnew = funct ( snew ) ; // Reflection failed; now attempt a contraction point: if ( fnew > fw ) { for ( int i = 0 ; i < nopt ; i ++ ) { snew [ i ] = sw [ i ] + beta * ( ce [ i ] - sw [ i ] ) ; } fnew = funct ( snew ) ; } // Both reflection and contraction have failed, attempt a random point; if ( fnew > fw ) { snew = randomSampler ( ) ; fnew = funct ( snew ) ; } double result [ ] = new double [ nopt + 1 ] ; for ( int i = 0 ; i < nopt ; i ++ ) { result [ i ] = snew [ i ] ; } result [ nopt ] = fnew ; return result ; } | bu upper bound | 611 | 3 |
17,437 | public static boolean deleteFileOrDirOnExit ( File filehandle ) { if ( filehandle . isDirectory ( ) ) { String [ ] children = filehandle . list ( ) ; for ( int i = 0 ; i < children . length ; i ++ ) { boolean success = deleteFileOrDir ( new File ( filehandle , children [ i ] ) ) ; if ( ! success ) { return false ; } } } filehandle . deleteOnExit ( ) ; return true ; } | Delete file or folder recursively on exit of the program | 101 | 12 |
17,438 | public static String readInputStreamToString ( InputStream inputStream ) { try { // Create the byte list to hold the data List < Byte > bytesList = new ArrayList < Byte > ( ) ; byte b = 0 ; while ( ( b = ( byte ) inputStream . read ( ) ) != - 1 ) { bytesList . add ( b ) ; } // Close the input stream and return bytes inputStream . close ( ) ; byte [ ] bArray = new byte [ bytesList . size ( ) ] ; for ( int i = 0 ; i < bArray . length ; i ++ ) { bArray [ i ] = bytesList . get ( i ) ; } String file = new String ( bArray ) ; return file ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } } | Read from an inoutstream and convert the readed stuff to a String . Usefull for text files that are available as streams . | 176 | 27 |
17,439 | public static String hexDigest ( String algorithm , File [ ] files ) { try { MessageDigest md = MessageDigest . getInstance ( algorithm ) ; byte [ ] buf = new byte [ 4096 ] ; for ( File f : files ) { FileInputStream in = new FileInputStream ( f ) ; int nread = in . read ( buf ) ; while ( nread > 0 ) { md . update ( buf , 0 , nread ) ; nread = in . read ( buf ) ; } in . close ( ) ; } return toHex ( md . digest ( buf ) ) ; } catch ( Exception ex ) { ex . printStackTrace ( System . out ) ; } return "<error>" ; } | Creates a hex encoded sha - 256 hash of all files . | 153 | 14 |
17,440 | public static boolean hasLevel ( ASpatialDb db , int levelNum ) throws Exception { String tablename = TABLENAME + levelNum ; return db . hasTable ( tablename ) ; } | Checks if the given level table exists . | 45 | 9 |
17,441 | public static List < LasLevel > getLasLevels ( ASpatialDb db , int levelNum , Envelope envelope ) throws Exception { String tableName = TABLENAME + levelNum ; List < LasLevel > lasLevels = new ArrayList <> ( ) ; String sql = "SELECT " + COLUMN_GEOM + "," + // COLUMN_ID + "," + COLUMN_SOURCE_ID + "," + COLUMN_AVG_ELEV + "," + // COLUMN_MIN_ELEV + "," + // COLUMN_MAX_ELEV + "," + // COLUMN_AVG_INTENSITY + "," + // COLUMN_MIN_INTENSITY + "," + // COLUMN_MAX_INTENSITY ; sql += " FROM " + tableName ; if ( envelope != null ) { double x1 = envelope . getMinX ( ) ; double y1 = envelope . getMinY ( ) ; double x2 = envelope . getMaxX ( ) ; double y2 = envelope . getMaxY ( ) ; sql += " WHERE " + db . getSpatialindexBBoxWherePiece ( tableName , null , x1 , y1 , x2 , y2 ) ; } String _sql = sql ; IGeometryParser gp = db . getType ( ) . getGeometryParser ( ) ; return db . execOnConnection ( conn -> { try ( IHMStatement stmt = conn . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( _sql ) ) { while ( rs . next ( ) ) { LasLevel lasLevel = new LasLevel ( ) ; lasLevel . level = levelNum ; int i = 1 ; Geometry geometry = gp . fromResultSet ( rs , i ++ ) ; if ( geometry instanceof Polygon ) { Polygon polygon = ( Polygon ) geometry ; lasLevel . polygon = polygon ; lasLevel . id = rs . getLong ( i ++ ) ; lasLevel . sourceId = rs . getLong ( i ++ ) ; lasLevel . avgElev = rs . getDouble ( i ++ ) ; lasLevel . minElev = rs . getDouble ( i ++ ) ; lasLevel . maxElev = rs . getDouble ( i ++ ) ; lasLevel . avgIntensity = rs . getShort ( i ++ ) ; lasLevel . minIntensity = rs . getShort ( i ++ ) ; lasLevel . maxIntensity = rs . getShort ( i ++ ) ; lasLevels . add ( lasLevel ) ; } } return lasLevels ; } } ) ; } | Query the las level table . | 574 | 6 |
17,442 | public static void handle ( File srcFile , AnnotationHandler ah ) throws Exception { FileInputStream fis = new FileInputStream ( srcFile ) ; FileChannel fc = fis . getChannel ( ) ; // Get a CharBuffer from the source file ByteBuffer bb = fc . map ( FileChannel . MapMode . READ_ONLY , 0 , fc . size ( ) ) ; CharsetDecoder cd = Charset . forName ( "8859_1" ) . newDecoder ( ) ; CharBuffer cb = cd . decode ( bb ) ; // handle the content. ah . start ( cb . toString ( ) ) ; handle ( cb . toString ( ) , ah ) ; ah . done ( ) ; fis . close ( ) ; } | Handle a file with an annotation handler . | 171 | 8 |
17,443 | public static void handle ( String s , AnnotationHandler ah ) { Map < String , Map < String , String > > l = new LinkedHashMap < String , Map < String , String > > ( ) ; Matcher m = annPattern . matcher ( s ) ; while ( m . find ( ) ) { // for (int i = 1; i <= m.groupCount(); i++) { // System.out.println("Group " + i + " '" + m.group(i) + "'"); // } String rest = s . substring ( m . end ( 0 ) ) . trim ( ) ; String srcLine = null ; if ( rest . indexOf ( ' ' ) > - 1 ) { srcLine = rest . substring ( 0 , rest . indexOf ( ' ' ) ) ; } else { srcLine = rest ; } Map < String , String > val = new LinkedHashMap < String , String > ( ) ; String annArgs = m . group ( 3 ) ; if ( annArgs == null ) { // no annotations arguments // e.g '@Function' } else if ( annArgs . indexOf ( ' ' ) > - 1 ) { // KVP annotation // e.g. '@Function(name="test", scope="global")' StringTokenizer t = new StringTokenizer ( annArgs , "," ) ; while ( t . hasMoreTokens ( ) ) { String arg = t . nextToken ( ) ; String key = arg . substring ( 0 , arg . indexOf ( ' ' ) ) ; String value = arg . substring ( arg . indexOf ( ' ' ) + 1 ) ; val . put ( key . trim ( ) , value . trim ( ) ) ; } } else { // single value annotation // e.g. '@Function("test"); val . put ( AnnotationHandler . VALUE , annArgs ) ; } l . put ( m . group ( 1 ) , val ) ; // If the next line also has an annotation // no source line will be passed into the handler if ( ! annTestPattern . matcher ( srcLine ) . find ( ) ) { ah . handle ( l , srcLine ) ; ah . log ( " Ann -> " + l ) ; ah . log ( " Src -> " + srcLine ) ; l = new LinkedHashMap < String , Map < String , String > > ( ) ; } } } | Handle a string with an annotation handler | 515 | 7 |
17,444 | public static void createPropertiesTable ( ASpatialDb database ) throws Exception { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "CREATE TABLE " ) ; sb . append ( PROPERTIESTABLE ) ; sb . append ( " (" ) ; sb . append ( ID ) ; sb . append ( " INTEGER PRIMARY KEY AUTOINCREMENT, " ) ; sb . append ( NAME ) . append ( " TEXT, " ) ; sb . append ( SIZE ) . append ( " REAL, " ) ; sb . append ( FILLCOLOR ) . append ( " TEXT, " ) ; sb . append ( STROKECOLOR ) . append ( " TEXT, " ) ; sb . append ( FILLALPHA ) . append ( " REAL, " ) ; sb . append ( STROKEALPHA ) . append ( " REAL, " ) ; sb . append ( SHAPE ) . append ( " TEXT, " ) ; sb . append ( WIDTH ) . append ( " REAL, " ) ; sb . append ( LABELSIZE ) . append ( " REAL, " ) ; sb . append ( LABELFIELD ) . append ( " TEXT, " ) ; sb . append ( LABELVISIBLE ) . append ( " INTEGER, " ) ; sb . append ( ENABLED ) . append ( " INTEGER, " ) ; sb . append ( ORDER ) . append ( " INTEGER," ) ; sb . append ( DASH ) . append ( " TEXT," ) ; sb . append ( MINZOOM ) . append ( " INTEGER," ) ; sb . append ( MAXZOOM ) . append ( " INTEGER," ) ; sb . append ( DECIMATION ) . append ( " REAL," ) ; sb . append ( THEME ) . append ( " TEXT" ) ; sb . append ( " );" ) ; String query = sb . toString ( ) ; database . executeInsertUpdateDeleteSql ( query ) ; } | Create the properties table . | 459 | 5 |
17,445 | public static Style createDefaultPropertiesForTable ( ASpatialDb database , String spatialTableUniqueName , String spatialTableLabelField ) throws Exception { StringBuilder sbIn = new StringBuilder ( ) ; sbIn . append ( "insert into " ) . append ( PROPERTIESTABLE ) ; sbIn . append ( " ( " ) ; sbIn . append ( NAME ) . append ( " , " ) ; sbIn . append ( SIZE ) . append ( " , " ) ; sbIn . append ( FILLCOLOR ) . append ( " , " ) ; sbIn . append ( STROKECOLOR ) . append ( " , " ) ; sbIn . append ( FILLALPHA ) . append ( " , " ) ; sbIn . append ( STROKEALPHA ) . append ( " , " ) ; sbIn . append ( SHAPE ) . append ( " , " ) ; sbIn . append ( WIDTH ) . append ( " , " ) ; sbIn . append ( LABELSIZE ) . append ( " , " ) ; sbIn . append ( LABELFIELD ) . append ( " , " ) ; sbIn . append ( LABELVISIBLE ) . append ( " , " ) ; sbIn . append ( ENABLED ) . append ( " , " ) ; sbIn . append ( ORDER ) . append ( " , " ) ; sbIn . append ( DASH ) . append ( " ," ) ; sbIn . append ( MINZOOM ) . append ( " ," ) ; sbIn . append ( MAXZOOM ) . append ( " ," ) ; sbIn . append ( DECIMATION ) ; sbIn . append ( " ) " ) ; sbIn . append ( " values " ) ; sbIn . append ( " ( " ) ; Style style = new Style ( ) ; style . name = spatialTableUniqueName ; style . labelfield = spatialTableLabelField ; if ( spatialTableLabelField != null && spatialTableLabelField . trim ( ) . length ( ) > 0 ) { style . labelvisible = 1 ; } sbIn . append ( style . insertValuesString ( ) ) ; sbIn . append ( " );" ) ; if ( database != null ) { String insertQuery = sbIn . toString ( ) ; database . executeInsertUpdateDeleteSql ( insertQuery ) ; } return style ; } | Create a default properties table for a spatial table . | 535 | 10 |
17,446 | public static void updateStyle ( ASpatialDb database , Style style ) throws Exception { StringBuilder sbIn = new StringBuilder ( ) ; sbIn . append ( "update " ) . append ( PROPERTIESTABLE ) ; sbIn . append ( " set " ) ; // sbIn.append(NAME).append("='").append(style.name).append("' , "); sbIn . append ( SIZE ) . append ( "=?," ) ; sbIn . append ( FILLCOLOR ) . append ( "=?," ) ; sbIn . append ( STROKECOLOR ) . append ( "=?," ) ; sbIn . append ( FILLALPHA ) . append ( "=?," ) ; sbIn . append ( STROKEALPHA ) . append ( "=?," ) ; sbIn . append ( SHAPE ) . append ( "=?," ) ; sbIn . append ( WIDTH ) . append ( "=?," ) ; sbIn . append ( LABELSIZE ) . append ( "=?," ) ; sbIn . append ( LABELFIELD ) . append ( "=?," ) ; sbIn . append ( LABELVISIBLE ) . append ( "=?," ) ; sbIn . append ( ENABLED ) . append ( "=?," ) ; sbIn . append ( ORDER ) . append ( "=?," ) ; sbIn . append ( DASH ) . append ( "=?," ) ; sbIn . append ( MINZOOM ) . append ( "=?," ) ; sbIn . append ( MAXZOOM ) . append ( "=?," ) ; sbIn . append ( DECIMATION ) . append ( "=?," ) ; sbIn . append ( THEME ) . append ( "=?" ) ; sbIn . append ( " where " ) ; sbIn . append ( NAME ) ; sbIn . append ( "='" ) ; sbIn . append ( style . name ) ; sbIn . append ( "';" ) ; Object [ ] objects = { style . size , style . fillcolor , style . strokecolor , style . fillalpha , style . strokealpha , style . shape , style . width , style . labelsize , style . labelfield , style . labelvisible , style . enabled , style . order , style . dashPattern , style . minZoom , style . maxZoom , style . decimationFactor , style . getTheme ( ) } ; String updateQuery = sbIn . toString ( ) ; database . executeInsertUpdateDeletePreparedSql ( updateQuery , objects ) ; } | Update a style definition . | 592 | 5 |
17,447 | private ArrayList < ArrayList < String > > parseString ( String text ) { ArrayList < ArrayList < String >> result = new ArrayList < ArrayList < String > > ( ) ; StringTokenizer linetoken = new StringTokenizer ( text , "\n" ) ; StringTokenizer token ; String current ; while ( linetoken . hasMoreTokens ( ) ) { current = linetoken . nextToken ( ) ; if ( current . contains ( "," ) ) { token = new StringTokenizer ( current , "," ) ; } else { token = new StringTokenizer ( current ) ; } ArrayList < String > line = new ArrayList < String > ( ) ; while ( token . hasMoreTokens ( ) ) { line . add ( token . nextToken ( ) ) ; } result . add ( line ) ; } return result ; } | turns the clipboard into a list of tokens each array list is a line each string in the list is a token in the line | 181 | 26 |
17,448 | private void addContents ( String text ) { int firstColSelected = table . getSelectedColumn ( ) ; int firstRowSelected = table . getSelectedRow ( ) ; int temp = firstColSelected ; if ( firstColSelected == - 1 || firstRowSelected == - 1 ) { return ; } ArrayList < ArrayList < String > > clipboard = parseString ( text ) ; for ( int i = 0 ; i < clipboard . size ( ) ; i ++ ) { for ( int j = 0 ; j < clipboard . get ( i ) . size ( ) ; j ++ ) { try { table . getModel ( ) . setValueAt ( clipboard . get ( i ) . get ( j ) , firstRowSelected , temp ++ ) ; } catch ( Exception e ) { } } temp = firstColSelected ; firstRowSelected ++ ; } } | this adds the text to the jtable | 187 | 8 |
17,449 | public void pasteClipboard ( ) { Transferable t = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . getContents ( null ) ; try { if ( t != null && t . isDataFlavorSupported ( DataFlavor . stringFlavor ) ) { addContents ( ( String ) t . getTransferData ( DataFlavor . stringFlavor ) ) ; table . repaint ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } | this is the function that adds the clipboard contents to the table | 111 | 12 |
17,450 | public String getControlType ( Object control ) { if ( control == null || ! ( control instanceof ScreenAnnotation ) ) return null ; if ( showPanControls && controlPan . equals ( control ) ) return AVKey . VIEW_PAN ; else if ( showLookControls && controlLook . equals ( control ) ) return AVKey . VIEW_LOOK ; else if ( showHeadingControls && controlHeadingLeft . equals ( control ) ) return AVKey . VIEW_HEADING_LEFT ; else if ( showHeadingControls && controlHeadingRight . equals ( control ) ) return AVKey . VIEW_HEADING_RIGHT ; else if ( showZoomControls && controlZoomIn . equals ( control ) ) return AVKey . VIEW_ZOOM_IN ; else if ( showZoomControls && controlZoomOut . equals ( control ) ) return AVKey . VIEW_ZOOM_OUT ; else if ( showPitchControls && controlPitchUp . equals ( control ) ) return AVKey . VIEW_PITCH_UP ; else if ( showPitchControls && controlPitchDown . equals ( control ) ) return AVKey . VIEW_PITCH_DOWN ; else if ( showFovControls && controlFovNarrow . equals ( control ) ) return AVKey . VIEW_FOV_NARROW ; else if ( showFovControls && controlFovWide . equals ( control ) ) return AVKey . VIEW_FOV_WIDE ; else if ( showVeControls && controlVeUp . equals ( control ) ) return AVKey . VERTICAL_EXAGGERATION_UP ; else if ( showVeControls && controlVeDown . equals ( control ) ) return AVKey . VERTICAL_EXAGGERATION_DOWN ; return null ; } | Get the control type associated with the given object or null if unknown . | 394 | 14 |
17,451 | public void highlight ( Object control ) { // Manage highlighting of controls. if ( this . currentControl == control ) return ; // same thing selected // Turn off highlight if on. if ( this . currentControl != null ) { this . currentControl . getAttributes ( ) . setImageOpacity ( - 1 ) ; // use default opacity this . currentControl = null ; } // Turn on highlight if object selected. if ( control != null && control instanceof ScreenAnnotation ) { this . currentControl = ( ScreenAnnotation ) control ; this . currentControl . getAttributes ( ) . setImageOpacity ( 1 ) ; } } | Specifies the control to highlight . Any currently highlighted control is un - highlighted . | 132 | 16 |
17,452 | protected Object getImageSource ( String control ) { if ( control . equals ( AVKey . VIEW_PAN ) ) return IMAGE_PAN ; else if ( control . equals ( AVKey . VIEW_LOOK ) ) return IMAGE_LOOK ; else if ( control . equals ( AVKey . VIEW_HEADING_LEFT ) ) return IMAGE_HEADING_LEFT ; else if ( control . equals ( AVKey . VIEW_HEADING_RIGHT ) ) return IMAGE_HEADING_RIGHT ; else if ( control . equals ( AVKey . VIEW_ZOOM_IN ) ) return IMAGE_ZOOM_IN ; else if ( control . equals ( AVKey . VIEW_ZOOM_OUT ) ) return IMAGE_ZOOM_OUT ; else if ( control . equals ( AVKey . VIEW_PITCH_UP ) ) return IMAGE_PITCH_UP ; else if ( control . equals ( AVKey . VIEW_PITCH_DOWN ) ) return IMAGE_PITCH_DOWN ; else if ( control . equals ( AVKey . VIEW_FOV_WIDE ) ) return IMAGE_FOV_WIDE ; else if ( control . equals ( AVKey . VIEW_FOV_NARROW ) ) return IMAGE_FOV_NARROW ; else if ( control . equals ( AVKey . VERTICAL_EXAGGERATION_UP ) ) return IMAGE_VE_UP ; else if ( control . equals ( AVKey . VERTICAL_EXAGGERATION_DOWN ) ) return IMAGE_VE_DOWN ; return null ; } | Get a control image source . | 349 | 6 |
17,453 | protected Point computeLocation ( Rectangle viewport , Rectangle controls ) { double x ; double y ; if ( this . locationCenter != null ) { x = this . locationCenter . x - controls . width / 2 ; y = this . locationCenter . y - controls . height / 2 ; } else if ( this . position . equals ( AVKey . NORTHEAST ) ) { x = viewport . getWidth ( ) - controls . width - this . borderWidth ; y = viewport . getHeight ( ) - controls . height - this . borderWidth ; } else if ( this . position . equals ( AVKey . SOUTHEAST ) ) { x = viewport . getWidth ( ) - controls . width - this . borderWidth ; y = 0d + this . borderWidth ; } else if ( this . position . equals ( AVKey . NORTHWEST ) ) { x = 0d + this . borderWidth ; y = viewport . getHeight ( ) - controls . height - this . borderWidth ; } else if ( this . position . equals ( AVKey . SOUTHWEST ) ) { x = 0d + this . borderWidth ; y = 0d + this . borderWidth ; } else // use North East as default { x = viewport . getWidth ( ) - controls . width - this . borderWidth ; y = viewport . getHeight ( ) - controls . height - this . borderWidth ; } if ( this . locationOffset != null ) { x += this . locationOffset . x ; y += this . locationOffset . y ; } return new Point ( ( int ) x , ( int ) y ) ; } | Compute the screen location of the controls overall rectangle bottom right corner according to either the location center if not null or the screen position . | 348 | 27 |
17,454 | public static ValidationMessage < Origin > error ( String messageKey , Object ... params ) { return ValidationMessage . message ( Severity . ERROR , messageKey , params ) ; } | Creates a ValidationMessage - severity ERROR | 38 | 9 |
17,455 | public static ValidationMessage < Origin > warning ( String messageKey , Object ... params ) { return ValidationMessage . message ( Severity . WARNING , messageKey , params ) ; } | Creates a ValidationMessage - severity WARNING | 38 | 9 |
17,456 | public static ValidationMessage < Origin > info ( String messageKey , Object ... params ) { return ValidationMessage . message ( Severity . INFO , messageKey , params ) ; } | Creates a ValidationMessage - severity INFO | 38 | 9 |
17,457 | public void writeMessage ( Writer writer , String targetOrigin ) throws IOException { writeMessage ( writer , messageFormatter , targetOrigin ) ; } | Writes the message with an additional target origin . | 30 | 10 |
17,458 | protected void set ( double values [ ] ) { this . nRows = values . length ; this . nCols = 1 ; this . values = new double [ nRows ] [ 1 ] ; for ( int r = 0 ; r < nRows ; ++ r ) { this . values [ r ] [ 0 ] = values [ r ] ; } } | Set this column vector from an array of values . | 77 | 10 |
17,459 | public List < String > getAttributesNames ( ) { SimpleFeatureType featureType = feature . getFeatureType ( ) ; List < AttributeDescriptor > attributeDescriptors = featureType . getAttributeDescriptors ( ) ; List < String > attributeNames = new ArrayList < String > ( ) ; for ( AttributeDescriptor attributeDescriptor : attributeDescriptors ) { String name = attributeDescriptor . getLocalName ( ) ; attributeNames . add ( name ) ; } return attributeNames ; } | Getter for the list of attribute names . | 111 | 9 |
17,460 | @ SuppressWarnings ( "unchecked" ) public < T > T getAttribute ( String attrName , Class < T > adaptee ) { if ( attrName == null ) { return null ; } if ( adaptee == null ) { adaptee = ( Class < T > ) String . class ; } Object attribute = feature . getAttribute ( attrName ) ; if ( attribute == null ) { return null ; } if ( attribute instanceof Number ) { Number num = ( Number ) attribute ; if ( adaptee . isAssignableFrom ( Double . class ) ) { return adaptee . cast ( num . doubleValue ( ) ) ; } else if ( adaptee . isAssignableFrom ( Float . class ) ) { return adaptee . cast ( num . floatValue ( ) ) ; } else if ( adaptee . isAssignableFrom ( Integer . class ) ) { return adaptee . cast ( num . intValue ( ) ) ; } else if ( adaptee . isAssignableFrom ( Long . class ) ) { return adaptee . cast ( num . longValue ( ) ) ; } else if ( adaptee . isAssignableFrom ( String . class ) ) { return adaptee . cast ( num . toString ( ) ) ; } else { throw new IllegalArgumentException ( ) ; } } else if ( attribute instanceof String ) { if ( adaptee . isAssignableFrom ( Double . class ) ) { try { Double parsed = Double . parseDouble ( ( String ) attribute ) ; return adaptee . cast ( parsed ) ; } catch ( Exception e ) { return null ; } } else if ( adaptee . isAssignableFrom ( Float . class ) ) { try { Float parsed = Float . parseFloat ( ( String ) attribute ) ; return adaptee . cast ( parsed ) ; } catch ( Exception e ) { return null ; } } else if ( adaptee . isAssignableFrom ( Integer . class ) ) { try { Integer parsed = Integer . parseInt ( ( String ) attribute ) ; return adaptee . cast ( parsed ) ; } catch ( Exception e ) { return null ; } } else if ( adaptee . isAssignableFrom ( String . class ) ) { return adaptee . cast ( attribute ) ; } else { throw new IllegalArgumentException ( ) ; } } else if ( attribute instanceof Geometry ) { return null ; } else { throw new IllegalArgumentException ( "Can't adapt attribute of type: " + attribute . getClass ( ) . getCanonicalName ( ) ) ; } } | Gets an attribute from the feature table adapting to the supplied class . | 550 | 14 |
17,461 | public boolean intersects ( Geometry geometry , boolean usePrepared ) { if ( ! getEnvelope ( ) . intersects ( geometry . getEnvelopeInternal ( ) ) ) { return false ; } if ( usePrepared ) { if ( preparedGeometry == null ) { preparedGeometry = PreparedGeometryFactory . prepare ( getGeometry ( ) ) ; } return preparedGeometry . intersects ( geometry ) ; } else { return getGeometry ( ) . intersects ( geometry ) ; } } | Check for intersection . | 109 | 4 |
17,462 | public boolean covers ( Geometry geometry , boolean usePrepared ) { if ( ! getEnvelope ( ) . covers ( geometry . getEnvelopeInternal ( ) ) ) { return false ; } if ( usePrepared ) { if ( preparedGeometry == null ) { preparedGeometry = PreparedGeometryFactory . prepare ( getGeometry ( ) ) ; } return preparedGeometry . covers ( geometry ) ; } else { return getGeometry ( ) . covers ( geometry ) ; } } | Check for cover . | 105 | 4 |
17,463 | private double calcAerodynamic ( double displacement , double roughness , double Zref , double windSpeed , double snowWaterEquivalent ) { double ra = 0.0 ; double d_Lower ; double K2 ; double Z0_Lower ; double tmp_wind ; // only a value of these quantities are input of the method: // - wind speed // - relative humidity // - Zref // - ra tmp_wind = windSpeed ; K2 = VON_K * VON_K ; if ( displacement > Zref ) Zref = displacement + Zref + roughness ; /* No OverStory, thus maximum one soil layer */ // for bare soil // if (iveg == Nveg) { // Z0_Lower = Z0_SOIL; //Z0_SOIL is the soil roughness // d_Lower = 0; // } else { //with vegetation Z0_Lower = roughness ; d_Lower = displacement ; // } if cycle is deleted thinking that bare soil is a vegetation type with roughness and // displacement /* With snow on the surface */ if ( snowWaterEquivalent > 0 ) { windSpeed = Math . log ( ( 2. + Z0_SNOW ) / Z0_SNOW ) / Math . log ( Zref / Z0_SNOW ) ; ra = Math . log ( ( 2. + Z0_SNOW ) / Z0_SNOW ) * Math . log ( Zref / Z0_SNOW ) / K2 ; } else { /* No snow on the surface*/ windSpeed = Math . log ( ( 2. + Z0_Lower ) / Z0_Lower ) / Math . log ( ( Zref - d_Lower ) / Z0_Lower ) ; ra = Math . log ( ( 2. + ( 1.0 / 0.63 - 1.0 ) * d_Lower ) / Z0_Lower ) * Math . log ( ( 2. + ( 1.0 / 0.63 - 1.0 ) * d_Lower ) / ( 0.1 * Z0_Lower ) ) / K2 ; } if ( tmp_wind > 0. ) { windSpeed *= tmp_wind ; ra /= tmp_wind ; } else { windSpeed *= tmp_wind ; ra = HUGE_RESIST ; pm . message ( "Aerodinamic resistance is set to the maximum value!" ) ; } return ra ; } | Calculates the aerodynamic resistance for the vegetation layer . | 514 | 12 |
17,464 | public static LinkedHashMap < String , List < String > > getTablesSorted ( List < String > allTableNames , boolean doSort ) { LinkedHashMap < String , List < String > > tablesMap = new LinkedHashMap <> ( ) ; tablesMap . put ( USERDATA , new ArrayList < String > ( ) ) ; tablesMap . put ( STYLE , new ArrayList < String > ( ) ) ; tablesMap . put ( METADATA , new ArrayList < String > ( ) ) ; tablesMap . put ( INTERNALDATA , new ArrayList < String > ( ) ) ; tablesMap . put ( SPATIALINDEX , new ArrayList < String > ( ) ) ; for ( String tableName : allTableNames ) { tableName = tableName . toLowerCase ( ) ; if ( spatialindexTables . contains ( tableName ) || tableName . startsWith ( startsWithIndexTables ) ) { List < String > list = tablesMap . get ( SPATIALINDEX ) ; list . add ( tableName ) ; continue ; } if ( tableName . startsWith ( startsWithStyleTables ) ) { List < String > list = tablesMap . get ( STYLE ) ; list . add ( tableName ) ; continue ; } if ( metadataTables . contains ( tableName ) ) { List < String > list = tablesMap . get ( METADATA ) ; list . add ( tableName ) ; continue ; } if ( internalDataTables . contains ( tableName ) ) { List < String > list = tablesMap . get ( INTERNALDATA ) ; list . add ( tableName ) ; continue ; } List < String > list = tablesMap . get ( USERDATA ) ; list . add ( tableName ) ; } if ( doSort ) { for ( List < String > values : tablesMap . values ( ) ) { Collections . sort ( values ) ; } } return tablesMap ; } | Sorts all supplied table names by type . | 421 | 9 |
17,465 | public static void createTables ( Connection connection ) throws IOException , SQLException { StringBuilder sB = new StringBuilder ( ) ; sB . append ( "CREATE TABLE " ) ; sB . append ( TABLE_BOOKMARKS ) ; sB . append ( " (" ) ; sB . append ( COLUMN_ID ) ; sB . append ( " INTEGER PRIMARY KEY, " ) ; sB . append ( COLUMN_LON ) . append ( " REAL NOT NULL, " ) ; sB . append ( COLUMN_LAT ) . append ( " REAL NOT NULL," ) ; sB . append ( COLUMN_ZOOM ) . append ( " REAL NOT NULL," ) ; sB . append ( COLUMN_NORTHBOUND ) . append ( " REAL NOT NULL," ) ; sB . append ( COLUMN_SOUTHBOUND ) . append ( " REAL NOT NULL," ) ; sB . append ( COLUMN_WESTBOUND ) . append ( " REAL NOT NULL," ) ; sB . append ( COLUMN_EASTBOUND ) . append ( " REAL NOT NULL," ) ; sB . append ( COLUMN_TEXT ) . append ( " TEXT NOT NULL " ) ; sB . append ( ");" ) ; String CREATE_TABLE_BOOKMARKS = sB . toString ( ) ; sB = new StringBuilder ( ) ; sB . append ( "CREATE INDEX bookmarks_x_by_y_idx ON " ) ; sB . append ( TABLE_BOOKMARKS ) ; sB . append ( " ( " ) ; sB . append ( COLUMN_LON ) ; sB . append ( ", " ) ; sB . append ( COLUMN_LAT ) ; sB . append ( " );" ) ; String CREATE_INDEX_BOOKMARKS_X_BY_Y = sB . toString ( ) ; try ( Statement statement = connection . createStatement ( ) ) { statement . setQueryTimeout ( 30 ) ; // set timeout to 30 sec. statement . executeUpdate ( CREATE_TABLE_BOOKMARKS ) ; statement . executeUpdate ( CREATE_INDEX_BOOKMARKS_X_BY_Y ) ; } catch ( Exception e ) { throw new IOException ( e . getLocalizedMessage ( ) ) ; } } | Create bookmarks tables . | 528 | 5 |
17,466 | public static String checkCompatibilityIssues ( String sql ) { sql = sql . replaceAll ( "LONG PRIMARY KEY AUTOINCREMENT" , "INTEGER PRIMARY KEY AUTOINCREMENT" ) ; sql = sql . replaceAll ( "AUTO_INCREMENT" , "AUTOINCREMENT" ) ; return sql ; } | Check for compatibility issues with other databases . | 79 | 8 |
17,467 | void mapOut ( String out , Object comp , String comp_out ) { if ( comp == ca . getComponent ( ) ) { throw new ComponentException ( "cannot connect 'Out' with itself for " + out ) ; } ComponentAccess ac_dest = lookup ( comp ) ; FieldAccess destAccess = ( FieldAccess ) ac_dest . output ( comp_out ) ; FieldAccess srcAccess = ( FieldAccess ) ca . output ( out ) ; checkFA ( destAccess , comp , comp_out ) ; checkFA ( srcAccess , ca . getComponent ( ) , out ) ; FieldContent data = srcAccess . getData ( ) ; data . tagLeaf ( ) ; data . tagOut ( ) ; destAccess . setData ( data ) ; dataSet . add ( data ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . log ( Level . CONFIG , String . format ( "@Out(%s) -> @Out(%s)" , srcAccess , destAccess ) ) ; } // ens.fireMapOut(srcAccess, destAccess); } | Map two output fields . | 233 | 5 |
17,468 | void mapIn ( String in , Object comp , String comp_in ) { if ( comp == ca . getComponent ( ) ) { throw new ComponentException ( "cannot connect 'In' with itself for " + in ) ; } ComponentAccess ac_dest = lookup ( comp ) ; FieldAccess destAccess = ( FieldAccess ) ac_dest . input ( comp_in ) ; checkFA ( destAccess , comp , comp_in ) ; FieldAccess srcAccess = ( FieldAccess ) ca . input ( in ) ; checkFA ( srcAccess , ca . getComponent ( ) , in ) ; FieldContent data = srcAccess . getData ( ) ; data . tagLeaf ( ) ; data . tagIn ( ) ; destAccess . setData ( data ) ; dataSet . add ( data ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( String . format ( "@In(%s) -> @In(%s)" , srcAccess , destAccess ) ) ; } // ens.fireMapIn(srcAccess, destAccess); } | Map two input fields . | 229 | 5 |
17,469 | void mapInVal ( Object val , Object to , String to_in ) { if ( val == null ) { throw new ComponentException ( "Null value for " + name ( to , to_in ) ) ; } if ( to == ca . getComponent ( ) ) { throw new ComponentException ( "field and component ar ethe same for mapping :" + to_in ) ; } ComponentAccess ca_to = lookup ( to ) ; Access to_access = ca_to . input ( to_in ) ; checkFA ( to_access , to , to_in ) ; ca_to . setInput ( to_in , new FieldValueAccess ( to_access , val ) ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( String . format ( "Value(%s) -> @In(%s)" , val . toString ( ) , to_access . toString ( ) ) ) ; } } | Directly map a value to a input field . | 204 | 10 |
17,470 | void mapInField ( Object from , String from_field , Object to , String to_in ) { if ( to == ca . getComponent ( ) ) { throw new ComponentException ( "wrong connect:" + from_field ) ; } ComponentAccess ca_to = lookup ( to ) ; Access to_access = ca_to . input ( to_in ) ; checkFA ( to_access , to , to_in ) ; try { FieldContent . FA f = new FieldContent . FA ( from , from_field ) ; ca_to . setInput ( to_in , new FieldObjectAccess ( to_access , f , ens ) ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( String . format ( "Field(%s) -> @In(%s)" , f . toString ( ) , to_access . toString ( ) ) ) ; } } catch ( Exception E ) { throw new ComponentException ( "No such field '" + from . getClass ( ) . getCanonicalName ( ) + "." + from_field + "'" ) ; } } | Map an input field . | 241 | 5 |
17,471 | void mapOutField ( Object from , String from_out , Object to , String to_field ) { if ( from == ca . getComponent ( ) ) { throw new ComponentException ( "wrong connect:" + to_field ) ; } ComponentAccess ca_from = lookup ( from ) ; Access from_access = ca_from . output ( from_out ) ; checkFA ( from_access , from , from_out ) ; try { FieldContent . FA f = new FieldContent . FA ( to , to_field ) ; ca_from . setOutput ( from_out , new FieldObjectAccess ( from_access , f , ens ) ) ; if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( String . format ( "@Out(%s) -> field(%s)" , from_access , f . toString ( ) ) ) ; } } catch ( Exception E ) { throw new ComponentException ( "No such field '" + to . getClass ( ) . getCanonicalName ( ) + "." + to_field + "'" ) ; } } | Map a object to an output field . | 235 | 8 |
17,472 | void connect ( Object from , String from_out , Object to , String to_in ) { // add them to the set of commands if ( from == to ) { throw new ComponentException ( "src == dest." ) ; } if ( to_in == null || from_out == null ) { throw new ComponentException ( "Some field arguments are null" ) ; } ComponentAccess ca_from = lookup ( from ) ; ComponentAccess ca_to = lookup ( to ) ; Access from_access = ca_from . output ( from_out ) ; checkFA ( from_access , from , from_out ) ; Access to_access = ca_to . input ( to_in ) ; checkFA ( to_access , to , to_in ) ; if ( ! canConnect ( from_access , to_access ) ) { throw new ComponentException ( "Type/Access mismatch, Cannot connect: " + from + ' ' + to_in + " -> " + to + ' ' + from_out ) ; } // src data object FieldContent data = from_access . getData ( ) ; data . tagIn ( ) ; data . tagOut ( ) ; dataSet . add ( data ) ; to_access . setData ( data ) ; // connect the two if ( checkCircular ) { validator . addConnection ( from , to ) ; validator . checkCircular ( ) ; } if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( String . format ( "@Out(%s) -> @In(%s)" , from_access . toString ( ) , to_access . toString ( ) ) ) ; } // ens.fireConnect(from_access, to_access); } | Connect out to in | 370 | 4 |
17,473 | void feedback ( Object from , String from_out , Object to , String to_in ) { // add them to the set of commands if ( from == to ) { throw new ComponentException ( "src == dest." ) ; } if ( to_in == null || from_out == null ) { throw new ComponentException ( "Some field arguments are null" ) ; } ComponentAccess ca_from = lookup ( from ) ; ComponentAccess ca_to = lookup ( to ) ; Access from_access = ca_from . output ( from_out ) ; checkFA ( from_access , from , from_out ) ; Access to_access = ca_to . input ( to_in ) ; checkFA ( to_access , to , to_in ) ; if ( ! canConnect ( from_access , to_access ) ) { throw new ComponentException ( "Type/Access mismatch, Cannot connect: " + from + ' ' + to_in + " -> " + to + ' ' + from_out ) ; } // src data object FieldContent data = from_access . getData ( ) ; data . tagIn ( ) ; data . tagOut ( ) ; // dataSet.add(data); to_access . setData ( data ) ; // connect the two ca_from . setOutput ( from_out , new AsyncFieldAccess ( from_access ) ) ; ca_to . setInput ( to_in , new AsyncFieldAccess ( to_access ) ) ; if ( checkCircular ) { // val.addConnection(from, to); // val.checkCircular(); } if ( log . isLoggable ( Level . CONFIG ) ) { log . config ( String . format ( "feedback @Out(%s) -> @In(%s)" , from_access . toString ( ) , to_access . toString ( ) ) ) ; } // ens.fireConnect(from_access, to_access); } | Feedback connect out to in | 416 | 6 |
17,474 | void callAnnotated ( Class < ? extends Annotation > ann , boolean lazy ) { for ( ComponentAccess p : oMap . values ( ) ) { p . callAnnotatedMethod ( ann , lazy ) ; } } | Call an annotated method . | 48 | 6 |
17,475 | public double addPoint ( double x , double y ) { pts . add ( new Coordinate ( x , y ) ) ; return selection = pts . size ( ) - 1 ; } | add a control point return index of new control point | 38 | 10 |
17,476 | public void setPoint ( double x , double y ) { if ( selection >= 0 ) { Coordinate coordinate = new Coordinate ( x , y ) ; pts . set ( selection , coordinate ) ; } } | set selected control point | 43 | 4 |
17,477 | public static Object sim ( String file , String ll , String cmd ) throws Exception { String f = CLI . readFile ( file ) ; Object o = CLI . createSim ( f , false , ll ) ; return CLI . invoke ( o , cmd ) ; } | Executes a simulation . | 54 | 5 |
17,478 | public static void groovy ( String file , String ll , String cmd ) throws Exception { String f = CLI . readFile ( file ) ; Object o = CLI . createSim ( f , true , ll ) ; } | Executed plain groovy . | 45 | 6 |
17,479 | public static String readFile ( String name ) throws IOException { StringBuilder b = new StringBuilder ( ) ; BufferedReader r = new BufferedReader ( new FileReader ( name ) ) ; String line ; while ( ( line = r . readLine ( ) ) != null ) { b . append ( line ) . append ( ' ' ) ; } r . close ( ) ; return b . toString ( ) ; } | Read a file and provide its content as String . | 89 | 10 |
17,480 | public static Object createSim ( String script , boolean groovy , String ll ) throws Exception { setOMSProperties ( ) ; Level . parse ( ll ) ; // may throw IAE String prefix = groovy ? "" : "import static oms3.SimConst.*\n" + "def __sb__ = new oms3.SimBuilder(logging:'" + ll + "')\n" + "__sb__." ; ClassLoader parent = Thread . currentThread ( ) . getContextClassLoader ( ) ; Binding b = new Binding ( ) ; b . setVariable ( "oms_version" , System . getProperty ( "oms.version" ) ) ; b . setVariable ( "oms_home" , System . getProperty ( "oms.home" ) ) ; b . setVariable ( "oms_prj" , System . getProperty ( "oms.prj" ) ) ; GroovyShell shell = new GroovyShell ( new GroovyClassLoader ( parent ) , b ) ; return shell . evaluate ( prefix + script ) ; } | Create a simulation object . | 227 | 5 |
17,481 | private Object getPropertyTypeValue ( Class propertyType , Object value ) { if ( propertyType . equals ( String . class ) ) { return value . toString ( ) ; } else if ( propertyType . equals ( Boolean . class ) || propertyType . equals ( Boolean . TYPE ) ) { Boolean arg = null ; if ( value instanceof Boolean ) { arg = ( Boolean ) value ; } else { arg = Boolean . parseBoolean ( value . toString ( ) ) ; } return arg ; } else if ( propertyType . equals ( Short . class ) || propertyType . equals ( Short . TYPE ) ) { Short arg = null ; if ( value instanceof Short ) { arg = ( Short ) value ; } else { arg = Short . parseShort ( value . toString ( ) ) ; } return arg ; } else if ( propertyType . equals ( Integer . class ) || propertyType . equals ( Integer . TYPE ) ) { Integer arg = null ; if ( value instanceof Integer ) { arg = ( Integer ) value ; } else { arg = Integer . parseInt ( value . toString ( ) ) ; } return arg ; } else if ( propertyType . equals ( Long . class ) || propertyType . equals ( Long . TYPE ) ) { Long arg = null ; if ( value instanceof Long ) { arg = ( Long ) value ; } else { arg = Long . parseLong ( value . toString ( ) ) ; } return arg ; } else if ( propertyType . equals ( Float . class ) || propertyType . equals ( Float . TYPE ) ) { Float arg = null ; if ( value instanceof Float ) { arg = ( Float ) value ; } else { arg = Float . parseFloat ( value . toString ( ) ) ; } return arg ; } else if ( propertyType . equals ( Double . class ) || propertyType . equals ( Double . TYPE ) ) { Double arg = null ; if ( value instanceof Double ) { arg = ( Double ) value ; } else { arg = Double . parseDouble ( value . toString ( ) ) ; } return arg ; } else { // Object return value ; } } | converts ths incoming value to an object for the property type . | 449 | 14 |
17,482 | public static < T , K , V > Map < K , V > toMap ( Stream < T > stream , Function < T , K > keySupplier , Function < T , V > valueSupplier ) { return stream . collect ( Collectors . toMap ( keySupplier , valueSupplier ) ) ; } | Collect stream to map . | 67 | 5 |
17,483 | public static < T , K , R > Map < R , List < T > > toMapGroupBy ( Stream < T > stream , Function < T , R > groupingFunction ) { return stream . collect ( Collectors . groupingBy ( groupingFunction ) ) ; // to get a set: Collectors.groupingBy(groupingFunction, Collectors.toSet()) } | Collect a map by grouping based on the object s field . | 79 | 12 |
17,484 | public static < T > Map < Boolean , List < T > > toMapPartition ( Stream < T > stream , Predicate < T > predicate ) { return stream . collect ( Collectors . partitioningBy ( predicate ) ) ; } | Split a stream into a map with true and false . | 50 | 11 |
17,485 | public static < T > T findAny ( Stream < T > stream , Predicate < T > predicate ) { Optional < T > element = stream . filter ( predicate ) . findAny ( ) ; return element . orElse ( null ) ; } | Find an element in the stream . | 51 | 7 |
17,486 | public void createSpatialTable ( String tableName , int tableSrid , String geometryFieldData , String [ ] fieldData ) throws Exception { createSpatialTable ( tableName , tableSrid , geometryFieldData , fieldData , null , false ) ; } | Creates a spatial table with default values for foreign keys and index . | 55 | 14 |
17,487 | public void createSpatialIndex ( String tableName , String geomColumnName ) throws Exception { if ( geomColumnName == null ) { geomColumnName = "the_geom" ; } String realColumnName = getProperColumnNameCase ( tableName , geomColumnName ) ; String realTableName = getProperTableNameCase ( tableName ) ; String sql = "CREATE SPATIAL INDEX ON " + realTableName + "(" + realColumnName + ");" ; execOnConnection ( connection -> { try ( IHMStatement stmt = connection . createStatement ( ) ) { stmt . execute ( sql . toString ( ) ) ; } return null ; } ) ; } | Create a spatial index . | 153 | 5 |
17,488 | public void insertGeometry ( String tableName , Geometry geometry , String epsg ) throws Exception { String epsgStr = "4326" ; if ( epsg == null ) { epsgStr = epsg ; } GeometryColumn gc = getGeometryColumnsForTable ( tableName ) ; String sql = "INSERT INTO " + tableName + " (" + gc . geometryColumnName + ") VALUES (ST_GeomFromText(?, " + epsgStr + "))" ; execOnConnection ( connection -> { try ( IHMPreparedStatement pStmt = connection . prepareStatement ( sql ) ) { pStmt . setString ( 1 , geometry . toText ( ) ) ; pStmt . executeUpdate ( ) ; } return null ; } ) ; } | Insert a geometry into a table . | 177 | 7 |
17,489 | public boolean isTableSpatial ( String tableName ) throws Exception { GeometryColumn geometryColumns = getGeometryColumnsForTable ( tableName ) ; return geometryColumns != null ; } | Checks if a table is spatial . | 41 | 8 |
17,490 | public List < Geometry > getGeometriesIn ( String tableName , Envelope envelope , String ... prePostWhere ) throws Exception { List < Geometry > geoms = new ArrayList < Geometry > ( ) ; List < String > wheres = new ArrayList <> ( ) ; String pre = "" ; String post = "" ; String where = "" ; if ( prePostWhere != null && prePostWhere . length == 3 ) { if ( prePostWhere [ 0 ] != null ) pre = prePostWhere [ 0 ] ; if ( prePostWhere [ 1 ] != null ) post = prePostWhere [ 1 ] ; if ( prePostWhere [ 2 ] != null ) { where = prePostWhere [ 2 ] ; wheres . add ( where ) ; } } GeometryColumn gCol = getGeometryColumnsForTable ( tableName ) ; String sql = "SELECT " + pre + gCol . geometryColumnName + post + " FROM " + tableName ; if ( envelope != null ) { double x1 = envelope . getMinX ( ) ; double y1 = envelope . getMinY ( ) ; double x2 = envelope . getMaxX ( ) ; double y2 = envelope . getMaxY ( ) ; wheres . add ( getSpatialindexBBoxWherePiece ( tableName , null , x1 , y1 , x2 , y2 ) ) ; } if ( wheres . size ( ) > 0 ) { sql += " WHERE " + DbsUtilities . joinBySeparator ( wheres , " AND " ) ; } String _sql = sql ; IGeometryParser geometryParser = getType ( ) . getGeometryParser ( ) ; return execOnConnection ( connection -> { try ( IHMStatement stmt = connection . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( _sql ) ) { while ( rs . next ( ) ) { Geometry geometry = geometryParser . fromResultSet ( rs , 1 ) ; geoms . add ( geometry ) ; } return geoms ; } } ) ; } | Get the geometries of a table inside a given envelope . | 445 | 13 |
17,491 | public List < Geometry > getGeometriesIn ( String tableName , Geometry intersectionGeometry , String ... prePostWhere ) throws Exception { List < Geometry > geoms = new ArrayList < Geometry > ( ) ; List < String > wheres = new ArrayList <> ( ) ; String pre = "" ; String post = "" ; String where = "" ; if ( prePostWhere != null && prePostWhere . length == 3 ) { if ( prePostWhere [ 0 ] != null ) pre = prePostWhere [ 0 ] ; if ( prePostWhere [ 1 ] != null ) post = prePostWhere [ 1 ] ; if ( prePostWhere [ 2 ] != null ) { where = prePostWhere [ 2 ] ; wheres . add ( where ) ; } } GeometryColumn gCol = getGeometryColumnsForTable ( tableName ) ; String sql = "SELECT " + pre + gCol . geometryColumnName + post + " FROM " + tableName ; if ( intersectionGeometry != null ) { intersectionGeometry . setSRID ( gCol . srid ) ; wheres . add ( getSpatialindexGeometryWherePiece ( tableName , null , intersectionGeometry ) ) ; } if ( wheres . size ( ) > 0 ) { sql += " WHERE " + DbsUtilities . joinBySeparator ( wheres , " AND " ) ; } IGeometryParser geometryParser = getType ( ) . getGeometryParser ( ) ; String _sql = sql ; return execOnConnection ( connection -> { try ( IHMStatement stmt = connection . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( _sql ) ) { while ( rs . next ( ) ) { Geometry geometry = geometryParser . fromResultSet ( rs , 1 ) ; geoms . add ( geometry ) ; } return geoms ; } } ) ; } | Get the geometries of a table intersecting a given geometry . | 407 | 14 |
17,492 | public static boolean fEq ( float a , float b , float epsilon ) { if ( isNaN ( a ) && isNaN ( b ) ) { return true ; } float diffAbs = abs ( a - b ) ; return a == b ? true : diffAbs < epsilon ? true : diffAbs / Math . max ( abs ( a ) , abs ( b ) ) < epsilon ; } | Returns true if two floats are considered equal based on an supplied epsilon . | 90 | 16 |
17,493 | public static double logGamma ( double x ) { double ret ; if ( Double . isNaN ( x ) || ( x <= 0.0 ) ) { ret = Double . NaN ; } else { double g = 607.0 / 128.0 ; double sum = 0.0 ; for ( int i = LANCZOS . length - 1 ; i > 0 ; -- i ) { sum = sum + ( LANCZOS [ i ] / ( x + i ) ) ; } sum = sum + LANCZOS [ 0 ] ; double tmp = x + g + .5 ; ret = ( ( x + .5 ) * log ( tmp ) ) - tmp + HALF_LOG_2_PI + log ( sum / x ) ; } return ret ; } | Gamma function ported from the apache math package . | 167 | 11 |
17,494 | public static List < int [ ] > getNegativeRanges ( double [ ] x ) { int firstNegative = - 1 ; int lastNegative = - 1 ; List < int [ ] > rangeList = new ArrayList < int [ ] > ( ) ; for ( int i = 0 ; i < x . length ; i ++ ) { double xValue = x [ i ] ; if ( firstNegative == - 1 && xValue < 0 ) { firstNegative = i ; } else if ( firstNegative != - 1 && lastNegative == - 1 && xValue > 0 ) { lastNegative = i - 1 ; } if ( i == x . length - 1 && firstNegative != - 1 && lastNegative == - 1 ) { // need to close the range with the last value available, even if negative lastNegative = i ; } if ( firstNegative != - 1 && lastNegative != - 1 ) { rangeList . add ( new int [ ] { firstNegative , lastNegative } ) ; firstNegative = - 1 ; lastNegative = - 1 ; } } return rangeList ; } | Get the range index for which x is negative . | 241 | 10 |
17,495 | public static double [ ] range2Bins ( double min , double max , int binsNum ) { double delta = ( max - min ) / binsNum ; double [ ] bins = new double [ binsNum + 1 ] ; int count = 0 ; double running = min ; for ( int i = 0 ; i < binsNum ; i ++ ) { bins [ count ] = running ; running = running + delta ; count ++ ; } bins [ binsNum ] = max ; return bins ; } | Creates an array of equal bin from a range and the number of bins . | 102 | 16 |
17,496 | public static double [ ] range2Bins ( double min , double max , double step , boolean doLastEqual ) { double intervalsDouble = ( max - min ) / step ; int intervals = ( int ) intervalsDouble ; double rest = intervalsDouble - intervals ; if ( rest > D_TOLERANCE ) { intervals ++ ; } double [ ] bins = new double [ intervals + 1 ] ; int count = 0 ; double running = min ; for ( int i = 0 ; i < intervals ; i ++ ) { bins [ count ] = running ; running = running + step ; count ++ ; } if ( doLastEqual ) { bins [ intervals ] = running ; } else { bins [ intervals ] = max ; } return bins ; } | Creates an array of bins from a range and a step to use . | 156 | 15 |
17,497 | private void verifyInput ( ) { if ( inData == null || inStations == null ) { throw new NullPointerException ( msg . message ( "kriging.stationproblem" ) ) ; } if ( pMode < 0 || pMode > 1 ) { throw new IllegalArgumentException ( msg . message ( "kriging.defaultMode" ) ) ; } if ( defaultVariogramMode != 0 && defaultVariogramMode != 1 ) { throw new IllegalArgumentException ( msg . message ( "kriging.variogramMode" ) ) ; } if ( defaultVariogramMode == 0 ) { if ( pVariance == 0 || pIntegralscale [ 0 ] == 0 || pIntegralscale [ 1 ] == 0 || pIntegralscale [ 2 ] == 0 ) { pm . errorMessage ( msg . message ( "kriging.noParam" ) ) ; pm . errorMessage ( "varianza " + pVariance ) ; pm . errorMessage ( "Integral scale x " + pIntegralscale [ 0 ] ) ; pm . errorMessage ( "Integral scale y " + pIntegralscale [ 1 ] ) ; pm . errorMessage ( "Integral scale z " + pIntegralscale [ 2 ] ) ; } } if ( defaultVariogramMode == 1 ) { if ( pNug == 0 || pS == 0 || pA == 0 ) { pm . errorMessage ( msg . message ( "kriging.noParam" ) ) ; pm . errorMessage ( "Nugget " + pNug ) ; pm . errorMessage ( "Sill " + pS ) ; pm . errorMessage ( "Range " + pA ) ; } } if ( ( pMode == 0 ) && inInterpolate == null ) { throw new ModelsIllegalargumentException ( msg . message ( "kriging.noPoint" ) , this , pm ) ; } if ( pMode == 1 && inInterpolationGrid == null ) { throw new ModelsIllegalargumentException ( "The gridded interpolation needs a gridgeometry in input." , this , pm ) ; } } | Verify the input of the model . | 457 | 8 |
17,498 | private LinkedHashMap < Integer , Coordinate > getCoordinate ( int nStaz , SimpleFeatureCollection collection , String idField ) throws Exception { LinkedHashMap < Integer , Coordinate > id2CoordinatesMap = new LinkedHashMap < Integer , Coordinate > ( ) ; FeatureIterator < SimpleFeature > iterator = collection . features ( ) ; Coordinate coordinate = null ; try { while ( iterator . hasNext ( ) ) { SimpleFeature feature = iterator . next ( ) ; int name = ( ( Number ) feature . getAttribute ( idField ) ) . intValue ( ) ; coordinate = ( ( Geometry ) feature . getDefaultGeometry ( ) ) . getCentroid ( ) . getCoordinate ( ) ; double z = 0 ; if ( fPointZ != null ) { try { z = ( ( Number ) feature . getAttribute ( fPointZ ) ) . doubleValue ( ) ; } catch ( NullPointerException e ) { pm . errorMessage ( msg . message ( "kriging.noPointZ" ) ) ; throw new Exception ( msg . message ( "kriging.noPointZ" ) ) ; } } coordinate . z = z ; id2CoordinatesMap . put ( name , coordinate ) ; } } finally { iterator . close ( ) ; } return id2CoordinatesMap ; } | Extract the coordinate of a FeatureCollection in a HashMap with an ID as a key . | 287 | 19 |
17,499 | private double variogram ( double c0 , double a , double sill , double rx , double ry , double rz ) { if ( isNovalue ( rz ) ) { rz = 0 ; } double value = 0 ; double h2 = Math . sqrt ( rx * rx + rz * rz + ry * ry ) ; if ( pSemivariogramType == 0 ) { value = c0 + sill * ( 1 - Math . exp ( - ( h2 * h2 ) / ( a * a ) ) ) ; } if ( pSemivariogramType == 1 ) { // primotest semivariogram value = c0 + sill * ( 1 - Math . exp ( - ( h2 ) / ( a ) ) ) ; } return value ; } | The gaussian variogram | 171 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.