idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
17,300 | 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 . | 101 | 24 |
17,301 | public SimpleFeatureCollection toFeatureCollection ( List < MonitoringPoint > monitoringPointsList ) { // create the feature type SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder ( ) ; // set the name b . setName ( "monitoringpoints" ) ; // add a geometry property b . add ( "the_geom" , Point . class ) ; // add some properties b . add ( "id" , Integer . class ) ; b . add ( "relatedid" , Integer . class ) ; b . add ( "pfaf" , String . class ) ; // build the type SimpleFeatureType type = b . buildFeatureType ( ) ; // create the feature SimpleFeatureBuilder builder = new SimpleFeatureBuilder ( type ) ; GeometryFactory gF = new GeometryFactory ( ) ; /* * insert them in inverse order to get them out of the collection in the same order as the * list */ 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 ( ) } ; // add the values builder . addAll ( values ) ; // build the feature with provided ID 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 . | 359 | 24 |
17,302 | 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 . | 71 | 5 |
17,303 | 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 . | 61 | 6 |
17,304 | 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 . | 98 | 8 |
17,305 | 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 . | 448 | 10 |
17,306 | 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 | 61 | 12 |
17,307 | 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 . | 90 | 12 |
17,308 | 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 . | 180 | 11 |
17,309 | public static Filter getIntersectsGeometryFilter ( String geomName , Geometry geometry ) throws CQLException { Filter result = CQL . toFilter ( "INTERSECTS(" + geomName + ", " + geometry . toText ( ) + " )" ) ; return result ; } | Creates an intersect filter . | 66 | 6 |
17,310 | 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 ; // ------------ generate a standard normal random variate (zvalue) ------------------- // perturb current value with normal random variable // CALL DRNNOA(1,zvalue) // generates a standard normal random deviate // ISML Stat Library 2 routine - Acceptance/rejection // Below returns a standard Gaussian random number based upon Numerical recipes gasdev and // Marsagalia-Bray Algorithm 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 ; } // was dlog() !!! work3 = Math . pow ( ( - 2.0 * Math . log ( work3 ) ) / work3 , 0.5 ) ; // natural log // pick one of two deviates at random (don't worry about trying to use both): ranval = rand . nextDouble ( ) ; if ( ranval < 0.5 ) { zvalue = work1 * work3 ; } else { zvalue = work2 * work3 ; } // ------------ done standard normal random variate generation ----------------- // calculate new decision variable value: new_value = x_cur + zvalue * r * x_range ; // check new value is within DV bounds. If not, bounds are reflecting. if ( new_value < x_min ) { new_value = x_min + ( x_min - new_value ) ; if ( new_value > x_max ) { // if reflection goes past x_max { value should be x_min since // without reflection the approach goes way past lower bound. // This keeps x close to lower bound when x_cur is close to lower bound // Practically speaking, this should never happen with r values <0.3 new_value = x_min ; } } else if ( new_value > x_max ) { new_value = x_max - ( new_value - x_max ) ; if ( new_value < x_min ) { // if reflection goes past x_min { value should be x_max for same reasons as above 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 . | 575 | 46 |
17,311 | 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 . | 360 | 8 |
17,312 | 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 . | 143 | 14 |
17,313 | 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 . | 484 | 11 |
17,314 | 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 | 395 | 4 |
17,315 | 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 . | 60 | 7 |
17,316 | 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 . | 446 | 12 |
17,317 | 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 ) ) ; //$NON-NLS-1$ } | Writes an image of maps drawn to a png file . | 130 | 13 |
17,318 | 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 ; } // we use the bounds top find the center 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 . | 657 | 11 |
17,319 | 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 | 38 | 12 |
17,320 | 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 . | 378 | 14 |
17,321 | 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 . | 167 | 9 |
17,322 | 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 ) { // multithreaded 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 ) ; /* * now recalculate the thresholds */ 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 . | 680 | 12 |
17,323 | 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 . | 151 | 23 |
17,324 | 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 ; } // triangles below a certain edge length are not adapted if ( maxLength < maxEdge ) { continue ; } } tinTree . insert ( geometry . getEnvelopeInternal ( ) , geometry ) ; } pm . done ( ) ; return tinTree ; } | Generate a spatial index on the tin geometries . | 252 | 12 |
17,325 | 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 . | 175 | 30 |
17,326 | 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 . | 87 | 39 |
17,327 | @ Override public final String readLine ( ) throws IOException { String str = null ; if ( buf_end - buf_pos <= 0 ) { if ( fillBuffer ( ) < 0 ) { // return null if we are at the end and there is nothing to read return null ; } } int lineend = - 1 ; for ( int i = buf_pos ; i < buf_end ; i ++ ) { if ( buffer [ i ] == ' ' ) { lineend = i ; break ; } } if ( lineend < 0 ) { StringBuffer input = new StringBuffer ( 256 ) ; int c ; while ( ( ( c = read ( ) ) != - 1 ) && ( c != ' ' ) ) { input . append ( ( char ) c ) ; } if ( ( c == - 1 ) && ( input . length ( ) == 0 ) ) { return null ; } return input . toString ( ) ; } if ( lineend > 0 && buffer [ lineend - 1 ] == ' ' ) { 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 . | 277 | 95 |
17,328 | public static String checkSameName ( List < String > strings , String string ) { int index = 1 ; for ( int i = 0 ; i < strings . size ( ) ; i ++ ) { if ( index == 10000 ) { // something odd is going on throw new RuntimeException ( ) ; } String existingString = strings . get ( i ) ; existingString = existingString . trim ( ) ; if ( existingString . trim ( ) . equals ( string . trim ( ) ) ) { // name exists, change the name of the entering if ( string . endsWith ( ")" ) ) { string = string . trim ( ) . replaceFirst ( "\\([0-9]+\\)$" , "(" + ( index ++ ) + ")" ) ; } else { string = string + " (" + ( index ++ ) + ")" ; } // start again i = 0 ; } } return string ; } | Checks if the list of strings supplied contains the supplied string . | 191 | 13 |
17,329 | 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 . | 196 | 11 |
17,330 | @ 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 . | 61 | 6 |
17,331 | 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 . | 108 | 13 |
17,332 | 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 | 134 | 13 |
17,333 | 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 . | 114 | 10 |
17,334 | 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 . | 110 | 10 |
17,335 | 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 | 328 | 13 |
17,336 | 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 . | 59 | 23 |
17,337 | @ Execute 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 ) ; // create new matrix 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" ) ) ; // Initialize new RasterData and set value WritableRaster tcaWR = CoverageUtilities . createWritableRaster ( cols , rows , Integer . class , null , HMConstants . intNovalue ) ; WritableRaster dirWR = CoverageUtilities . createWritableRaster ( cols , rows , Short . class , null , HMConstants . shortNovalue ) ; // it contains the analyzed cells 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 ; } // only if required executes this method 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 | 814 | 6 |
17,338 | 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 . | 326 | 7 |
17,339 | protected List < JavaFileObject > listClassesFromUrl ( URL base , String packageName ) throws IOException { //TODO this will only work with file:// not jar:// 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 . | 343 | 9 |
17,340 | 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 | 202 | 13 |
17,341 | public static AbstractTableModel getProperties ( final CSProperties p ) { return new AbstractTableModel ( ) { @ Override public int getRowCount ( ) { return p . keySet ( ) . size ( ) ; } @ Override public int getColumnCount ( ) { return 2 ; } @ Override public Object getValueAt ( int rowIndex , int columnIndex ) { if ( columnIndex == 0 ) { return " " + p . keySet ( ) . toArray ( ) [ rowIndex ] ; } else { return p . values ( ) . toArray ( ) [ rowIndex ] ; } } @ Override public boolean isCellEditable ( int rowIndex , int columnIndex ) { return columnIndex == 1 ; } @ Override 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 ( ) ) ; } } @ Override public String getColumnName ( int column ) { return column == 0 ? "Name" : "Value" ; } @ Override public Class < ? > getColumnClass ( int columnIndex ) { return String . class ; } } ; } | Get the KVP as table . | 282 | 7 |
17,342 | 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 . | 96 | 4 |
17,343 | 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 . | 116 | 8 |
17,344 | 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 . | 100 | 6 |
17,345 | 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 . | 62 | 6 |
17,346 | 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 . | 219 | 5 |
17,347 | 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 | 313 | 8 |
17,348 | 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 . | 41 | 8 |
17,349 | public static CSProperties properties ( Reader r , String name ) throws IOException { return new CSVProperties ( r , name ) ; } | Parse properties from a reader | 29 | 6 |
17,350 | 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 . | 125 | 10 |
17,351 | 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 | 84 | 6 |
17,352 | public static Properties properties ( CSProperties p ) { Properties pr = new Properties ( ) ; pr . putAll ( p ) ; return pr ; } | Convert CSProperties into Properties | 31 | 7 |
17,353 | public static CSTable table ( File file , String name ) throws IOException { return new FileTable ( file , name ) ; } | Parse a table from a given File . | 27 | 9 |
17,354 | public static CSTable table ( String s , String name ) throws IOException { return new StringTable ( s , name ) ; } | Parse a table from a Reader . | 27 | 8 |
17,355 | public static CSTable table ( URL url , String name ) throws IOException { return new URLTable ( url , name ) ; } | Create a CSTable from a URL source . | 27 | 9 |
17,356 | 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 . | 63 | 8 |
17,357 | 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 | 62 | 7 |
17,358 | 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 ( ) ) ; // header 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 . | 301 | 9 |
17,359 | 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 ( ) ) ; // final ExecutorService e = Executors.newFixedThreadPool(numproc); for ( final Compound c : t ) { e . submit ( new Runnable ( ) { @ Override 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 ( ) ; // e.shutdown(); } | Runs a set of Compounds in parallel . there are always numproc + 1 threads active . | 205 | 21 |
17,360 | 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 . | 200 | 8 |
17,361 | 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 . | 200 | 8 |
17,362 | 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 . | 55 | 4 |
17,363 | 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 . | 342 | 19 |
17,364 | 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 . | 72 | 8 |
17,365 | 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 . | 254 | 10 |
17,366 | 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 . | 266 | 15 |
17,367 | public static String runShellCommand ( Session session , String command ) throws JSchException , IOException { String remoteResponseStr = launchACommand ( session , command ) ; return remoteResponseStr ; } | Launch a shell command . | 42 | 5 |
17,368 | 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 . | 45 | 12 |
17,369 | public static void downloadFile ( Session session , String remoteFilePath , String localFilePath ) throws Exception { // exec 'scp -f rfile' remotely String command = "scp -f " + remoteFilePath ; Channel channel = session . openChannel ( "exec" ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; // get I/O streams for remote scp OutputStream out = channel . getOutputStream ( ) ; InputStream in = channel . getInputStream ( ) ; channel . connect ( ) ; byte [ ] buf = new byte [ 1024 ] ; // send '\0' buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; while ( true ) { int c = checkAck ( in ) ; if ( c != ' ' ) { break ; } // read '0644 ' in . read ( buf , 0 , 5 ) ; long filesize = 0L ; while ( true ) { if ( in . read ( buf , 0 , 1 ) < 0 ) { // error break ; } if ( buf [ 0 ] == ' ' ) break ; filesize = filesize * 10L + ( long ) ( buf [ 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 ) ; // send '\0' buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; // read a content of lfile 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 ) { // error break ; } fos . write ( buf , 0 , foo ) ; filesize -= foo ; if ( filesize == 0L ) break ; } fos . close ( ) ; if ( checkAck ( in ) != 0 ) { throw new RuntimeException ( ) ; } // send '\0' buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; } } | Download a remote file via scp . | 544 | 8 |
17,370 | public static void uploadFile ( Session session , String localFile , String remoteFile ) throws Exception { boolean ptimestamp = true ; // exec 'scp -t rfile' remotely String command = "scp " + ( ptimestamp ? "-p" : "" ) + " -t " + remoteFile ; Channel channel = session . openChannel ( "exec" ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; // get I/O streams for remote scp OutputStream out = channel . getOutputStream ( ) ; InputStream in = channel . getInputStream ( ) ; channel . connect ( ) ; if ( checkAck ( in ) != 0 ) { throw new RuntimeException ( ) ; } File _lfile = new File ( localFile ) ; if ( ptimestamp ) { command = "T " + ( _lfile . lastModified ( ) / 1000 ) + " 0" ; // The access time should be sent here, // but it is not accessible with JavaAPI ;-< command += ( " " + ( _lfile . lastModified ( ) / 1000 ) + " 0\n" ) ; out . write ( command . getBytes ( ) ) ; out . flush ( ) ; if ( checkAck ( in ) != 0 ) { throw new RuntimeException ( ) ; } } // send "C0644 filesize filename", where filename should not include '/' long filesize = _lfile . length ( ) ; command = "C0644 " + filesize + " " ; if ( localFile . lastIndexOf ( ' ' ) > 0 ) { command += localFile . substring ( localFile . lastIndexOf ( ' ' ) + 1 ) ; } else { command += localFile ; } command += "\n" ; out . write ( command . getBytes ( ) ) ; out . flush ( ) ; if ( checkAck ( in ) != 0 ) { throw new RuntimeException ( ) ; } // send a content of lfile FileInputStream fis = new FileInputStream ( localFile ) ; byte [ ] buf = new byte [ 1024 ] ; while ( true ) { int len = fis . read ( buf , 0 , buf . length ) ; if ( len <= 0 ) break ; out . write ( buf , 0 , len ) ; // out.flush(); } fis . close ( ) ; fis = null ; // send '\0' buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; if ( checkAck ( in ) != 0 ) { throw new RuntimeException ( ) ; } out . close ( ) ; channel . disconnect ( ) ; } | Upload a file to the remote host via scp . | 572 | 11 |
17,371 | public int readObjectHeaderV15 ( int [ ] data , int offset ) throws Exception { int bitPos = offset ; Integer mode = ( Integer ) DwgUtil . getBits ( data , 2 , bitPos ) ; bitPos = bitPos + 2 ; setMode ( mode . intValue ( ) ) ; Vector v = DwgUtil . getBitLong ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; int rnum = ( ( Integer ) v . get ( 1 ) ) . intValue ( ) ; setNumReactors ( rnum ) ; v = DwgUtil . testBit ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; boolean nolinks = ( ( Boolean ) v . get ( 1 ) ) . booleanValue ( ) ; setNoLinks ( nolinks ) ; v = DwgUtil . getBitShort ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; int color = ( ( Integer ) v . get ( 1 ) ) . intValue ( ) ; setColor ( color ) ; v = DwgUtil . getBitDouble ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; float ltscale = ( ( Double ) v . get ( 1 ) ) . floatValue ( ) ; Integer ltflag = ( Integer ) DwgUtil . getBits ( data , 2 , bitPos ) ; bitPos = bitPos + 2 ; Integer psflag = ( Integer ) DwgUtil . getBits ( data , 2 , bitPos ) ; bitPos = bitPos + 2 ; v = DwgUtil . getBitShort ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; int invis = ( ( Integer ) v . get ( 1 ) ) . intValue ( ) ; v = DwgUtil . getRawChar ( data , bitPos ) ; bitPos = ( ( Integer ) v . get ( 0 ) ) . intValue ( ) ; int weight = ( ( Integer ) v . get ( 1 ) ) . intValue ( ) ; return bitPos ; } | Reads the header of an object in a DWG file Version 15 | 509 | 14 |
17,372 | public List validateSLD ( InputSource xml ) { URL schemaURL = SLDValidator . class . getResource ( "/schemas/sld/StyledLayerDescriptor.xsd" ) ; return ResponseUtils . validate ( xml , schemaURL , false , entityResolver ) ; } | validate a . sld against the schema | 65 | 9 |
17,373 | public static void pipeMagnitude ( double [ ] magnitude , double [ ] whereDrain , IHMProgressMonitor pm ) { int count = 0 ; /* whereDrain Contiene gli indici degli stati riceventi. */ /* magnitude Contiene la magnitude dei vari stati. */ int length = magnitude . length ; /* Per ogni stato */ for ( int i = 0 ; i < length ; i ++ ) { count = 0 ; /* la magnitude viene posta pari a 1 */ magnitude [ i ] ++ ; int k = i ; /* * Si segue il percorso dell'acqua e si incrementa di 1 la mgnitude * di tutti gli stati attraversati prima di raggiungere l'uscita */ while ( whereDrain [ k ] != Constants . OUT_INDEX_PIPE && count < length ) { k = ( int ) whereDrain [ k ] ; magnitude [ k ] ++ ; count ++ ; } if ( count > length ) { pm . errorMessage ( msg . message ( "trentoP.error.pipe" ) ) ; throw new IllegalArgumentException ( msg . message ( "trentoP.error.pipe" ) ) ; } } } | Calculate the magnitudo of the several drainage area . | 276 | 13 |
17,374 | public static boolean verifyProjectType ( SimpleFeatureType schema , IHMProgressMonitor pm ) { String searchedField = PipesTrentoP . ID . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . DRAIN_AREA . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . INITIAL_ELEVATION . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . FINAL_ELEVATION . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . RUNOFF_COEFFICIENT . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . KS . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . MINIMUM_PIPE_SLOPE . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . AVERAGE_RESIDENCE_TIME . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . PIPE_SECTION_TYPE . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . AVERAGE_SLOPE . getAttributeName ( ) ; verifyFeatureKey ( findAttributeName ( schema , searchedField ) , searchedField , pm ) ; searchedField = PipesTrentoP . PER_AREA . getAttributeName ( ) ; String attributeName = findAttributeName ( schema , searchedField ) ; if ( attributeName != null ) { return true ; } return false ; } | Verify the schema . | 503 | 5 |
17,375 | private static void verifyFeatureKey ( String key , String searchedField , IHMProgressMonitor pm ) { if ( key == null ) { if ( pm != null ) { pm . errorMessage ( msg . message ( "trentoP.error.featureKey" ) + searchedField ) ; } throw new IllegalArgumentException ( msg . message ( "trentoP.error.featureKey" ) + searchedField ) ; } } | Verify if there is a key of a FeatureCollections . | 92 | 13 |
17,376 | public static ValidationMessage < Origin > message ( LineReader lineReader , Severity severity , String messageKey , Object ... params ) { return message ( lineReader . getCurrentLineNumber ( ) , severity , messageKey , params ) ; } | Creates a validation message . | 50 | 6 |
17,377 | public static void setCDSTranslationReport ( ExtendedResult < CdsFeatureTranslationCheck . TranslationReportInfo > cdsCheckResult ) { try { CdsFeatureTranslationCheck . TranslationReportInfo translationInfo = cdsCheckResult . getExtension ( ) ; StringWriter translationReportWriter = new StringWriter ( ) ; TranslationResult translationResult = translationInfo . getTranslationResult ( ) ; CdsFeature cdsFeature = translationInfo . getCdsFeature ( ) ; if ( translationResult != null && cdsFeature != null ) { String providedTranslation = cdsFeature . getTranslation ( ) ; new TranslationResultWriter ( translationResult , providedTranslation ) . write ( translationReportWriter ) ; String translationReport = translationReportWriter . toString ( ) ; StringWriter reportString = new StringWriter ( ) ; reportString . append ( "The results of the automatic translation are shown below.\n\n" ) ; CompoundLocation < Location > compoundLocation = translationInfo . getCdsFeature ( ) . getLocations ( ) ; reportString . append ( "Feature location : " ) ; reportString . append ( FeatureLocationWriter . renderCompoundLocation ( compoundLocation ) ) . append ( "\n" ) ; reportString . append ( "Base count : " ) . append ( Integer . toString ( translationResult . getBaseCount ( ) ) ) . append ( "\n" ) ; reportString . append ( "Translation length : " ) . append ( Integer . toString ( translationResult . getTranslation ( ) . length ( ) ) ) . append ( "\n\n" ) ; reportString . append ( "Translation table info : " ) ; TranslationTable translationTable = translationInfo . getTranslationTable ( ) ; String translationTableName = "NOT SET" ; String translationTableNumber = "NOT SET" ; if ( translationTable != null ) { translationTableName = translationTable . getName ( ) ; translationTableNumber = Integer . toString ( translationTable . getNumber ( ) ) ; } reportString . append ( "Table name - \"" ) . append ( translationTableName ) . append ( "\" " ) ; reportString . append ( "Table number - \"" ) . append ( translationTableNumber ) . append ( "\"\n\n" ) ; if ( translationReport != null && ! translationReport . isEmpty ( ) ) { reportString . append ( "The amino acid codes immediately below the dna triplets is the actual " + "translation based on the information you provided." ) ; List < Qualifier > providedtranslations = translationInfo . getCdsFeature ( ) . getQualifiers ( Qualifier . TRANSLATION_QUALIFIER_NAME ) ; if ( ! providedtranslations . isEmpty ( ) ) { reportString . append ( "\nThe second row of amino acid codes is the translation you provided in the CDS " + "feature. These translations should match." ) ; } reportString . append ( "\n\n" ) ; reportString . append ( translationReport ) ; } else { reportString . append ( "No translation made\n\n" ) ; } /** * set in all messages and the validation result - used differently in webapp to the command line tool */ cdsCheckResult . setReportMessage ( reportString . toString ( ) ) ; for ( ValidationMessage message : cdsCheckResult . getMessages ( ) ) { message . setReportMessage ( reportString . toString ( ) ) ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; } } | Takes all the messages in a CdsFeatureTranslationCheck ExtendedResult ValidationResult object and writes a report for the CDS translation . Uses extra information from the ExtendedResult . Have put this here as it uses Writers from the FF package and the embl - api - core package does not have access to these . | 749 | 64 |
17,378 | public void writeTemplateSpreadsheetDownloadFile ( List < TemplateTokenInfo > tokenNames , TemplateVariablesSet variablesSet , String filePath ) throws TemplateException { prepareWriter ( filePath ) ; writeDownloadSpreadsheetHeader ( tokenNames ) ; for ( int i = 1 ; i < variablesSet . getEntryCount ( ) + 1 ; i ++ ) { TemplateVariables entryVariables = variablesSet . getEntryValues ( i ) ; writeSpreadsheetVariableRow ( tokenNames , i , entryVariables ) ; } flushAndCloseWriter ( ) ; } | Writes the download file for variables for spreadsheet import | 116 | 10 |
17,379 | public void writeLargeTemplateSpreadsheetDownloadFile ( List < TemplateTokenInfo > tokenNames , int entryCount , TemplateVariables constants , String filePath ) throws TemplateException { prepareWriter ( filePath ) ; writeDownloadSpreadsheetHeader ( tokenNames ) ; for ( int i = 1 ; i < entryCount + 1 ; i ++ ) { writeSpreadsheetVariableRow ( tokenNames , i , constants ) ; } flushAndCloseWriter ( ) ; } | Used to write spreadsheets where entry number exceeds the MEGABULK size . Does not use the variables map stored in the database just writes constants . | 94 | 31 |
17,380 | public void writeDownloadSpreadsheetHeader ( List < TemplateTokenInfo > variableTokenNames ) { StringBuilder headerBuilder = new StringBuilder ( ) ; headerBuilder . append ( UPLOAD_COMMENTS ) ; headerBuilder . append ( "\n" ) ; for ( TemplateTokenInfo tokenInfo : variableTokenNames ) { if ( tokenInfo . getName ( ) . equals ( TemplateProcessorConstants . COMMENTS_TOKEN ) ) { headerBuilder . append ( "#The field '" + tokenInfo . getDisplayName ( ) + "' allows return characters. To add return characters add '<br>'; e.g. line1<br>line2" ) ; headerBuilder . append ( "\n" ) ; } } headerBuilder . append ( HEADER_TOKEN ) ; headerBuilder . append ( UPLOAD_DELIMITER ) ; for ( TemplateTokenInfo variable : variableTokenNames ) { headerBuilder . append ( variable . getDisplayName ( ) ) ; headerBuilder . append ( UPLOAD_DELIMITER ) ; } String headerLine = headerBuilder . toString ( ) ; headerLine = headerLine . substring ( 0 , headerLine . length ( ) - 1 ) ; //get rid of trailing delimiter this . lineWriter . println ( headerLine ) ; } | writes the header for the example download spreadsheet | 276 | 9 |
17,381 | @ Execute public void process ( ) throws Exception { if ( ! concatOr ( outTca == null , doReset ) ) { return ; } checkNull ( inPit , inFlow ) ; HashMap < String , Double > regionMap = CoverageUtilities . getRegionParamsFromGridCoverage ( inPit ) ; cols = regionMap . get ( CoverageUtilities . COLS ) . intValue ( ) ; rows = regionMap . get ( CoverageUtilities . ROWS ) . intValue ( ) ; xRes = regionMap . get ( CoverageUtilities . XRES ) ; yRes = regionMap . get ( CoverageUtilities . YRES ) ; RenderedImage pitfillerRI = inPit . getRenderedImage ( ) ; WritableRaster pitWR = CoverageUtilities . renderedImage2WritableRaster ( pitfillerRI , false ) ; RenderedImage flowRI = inFlow . getRenderedImage ( ) ; WritableRaster flowWR = CoverageUtilities . renderedImage2WritableRaster ( flowRI , true ) ; // Initialize new RasterData and set value WritableRaster tca3dWR = CoverageUtilities . createWritableRaster ( cols , rows , null , null , doubleNovalue ) ; tca3dWR = area3d ( pitWR , flowWR , tca3dWR ) ; outTca = CoverageUtilities . buildCoverage ( "tca3d" , tca3dWR , regionMap , //$NON-NLS-1$ inPit . getCoordinateReferenceSystem ( ) ) ; } | Calculates total contributing areas | 352 | 6 |
17,382 | public void readDwgSeqendV15 ( int [ ] data , int offset ) throws Exception { int bitPos = offset ; bitPos = readObjectHeaderV15 ( data , bitPos ) ; bitPos = readObjectTailV15 ( data , bitPos ) ; } | Read a Seqend in the DWG format Version 15 | 61 | 12 |
17,383 | public boolean isDownStreamOf ( PfafstetterNumber pfafstetterNumber ) { /* * all the upstreams will have same numbers until the last dot */ int lastDot = pfafstetterNumberString . lastIndexOf ( ' ' ) ; String pre = pfafstetterNumberString . substring ( 0 , lastDot + 1 ) ; String lastNum = pfafstetterNumberString . substring ( lastDot + 1 , pfafstetterNumberString . length ( ) ) ; int lastNumInt = Integer . parseInt ( lastNum ) ; if ( lastNumInt % 2 == 0 ) { // it has to be the last piece of a river, therefore no piece contained return false ; } else { /* * check if the passed one is upstream */ String pfaff = pfafstetterNumber . toString ( ) ; if ( pfaff . startsWith ( pre ) ) { // search for all those with a higher next number String lastPart = pfaff . substring ( lastDot + 1 , pfaff . length ( ) ) ; String lastPartParent = StringUtilities . REGEX_PATTER_DOT . split ( lastPart ) [ 0 ] ; if ( Integer . parseInt ( lastPartParent ) >= lastNumInt ) { return true ; } } } return false ; } | Checks if the actual pfafstetter object is downstream or not of the passed argument | 291 | 19 |
17,384 | public synchronized static boolean areConnectedUpstream ( PfafstetterNumber p1 , PfafstetterNumber p2 ) { List < Integer > p1OrdersList = p1 . getOrdersList ( ) ; List < Integer > p2OrdersList = p2 . getOrdersList ( ) ; int levelDiff = p1OrdersList . size ( ) - p2OrdersList . size ( ) ; if ( levelDiff == 0 ) { if ( p1 . toStringUpToLastLevel ( ) . equals ( p2 . toStringUpToLastLevel ( ) ) ) { int p1Last = p1OrdersList . get ( p1OrdersList . size ( ) - 1 ) ; int p2Last = p2OrdersList . get ( p2OrdersList . size ( ) - 1 ) ; if ( p2Last == p1Last + 1 || p2Last == p1Last + 2 ) { return p1Last % 2 != 0 ; } } } else if ( levelDiff == - 1 ) { if ( p2 . toString ( ) . startsWith ( p1 . toStringUpToLastLevel ( ) ) ) { int p2Last = p2OrdersList . get ( p2OrdersList . size ( ) - 1 ) ; if ( p2Last != 1 ) { return false ; } int p1Last = p1OrdersList . get ( p1OrdersList . size ( ) - 1 ) ; int p2LastMinus1 = p2OrdersList . get ( p2OrdersList . size ( ) - 2 ) ; if ( p2LastMinus1 == p1Last + 1 || p2Last == p1Last + 2 ) { return p1Last % 2 != 0 ; } } } return false ; } | Checks if two pfafstetter are connected upstream i . e . p1 is more downstream than p2 | 389 | 24 |
17,385 | private Number setFeatureField ( SimpleFeature pipe , String key ) { Number field = ( ( Number ) pipe . getAttribute ( key ) ) ; if ( field == null ) { pm . errorMessage ( msg . message ( "trentoP.error.number" ) + key ) ; throw new IllegalArgumentException ( msg . message ( "trentoP.error.number" ) + key ) ; } // return the Number return field ; } | Check if there is the field in a SimpleFeature and if it s a Number . | 96 | 17 |
17,386 | public void designPipe ( double [ ] [ ] diameters , double tau , double g , double maxd , double c , StringBuilder strWarnings ) { switch ( this . pipeSectionType ) { case 1 : designCircularPipe ( diameters , tau , g , maxd , strWarnings ) ; break ; case 2 : designRectangularPipe ( tau , g , maxd , c , strWarnings ) ; break ; case 3 : designTrapeziumPipe ( tau , g , maxd , c , strWarnings ) ; break ; default : designCircularPipe ( diameters , tau , g , maxd , strWarnings ) ; break ; } } | Calculate the dimension of the pipes . | 158 | 9 |
17,387 | private void designTrapeziumPipe ( double tau , double g , double maxd , double c , StringBuilder strWarnings ) { /* [cm] Base della sezione effettivamente adottata. */ double base ; /* * [%] Pendenza naturale, calcolata in funzione dei dati geometrici * della rete */ double naturalSlope ; /* [cm] Altezza del canale trapezoidale. */ double D ; /* * [%] Pendenza minima da adottare per il tratto che si sta * dimensionando. */ double ms ; /* DUE FORMULE */ /* * Dimensiona il diametro del tubo da adottare col criterio di * autopulizia, calcola altre grandezze correlate come la pendenza e il * grado di riempimento, e restituisce il riempimento effettivo nel * tratto progettato */ base = getHeight2 ( tau , g , maxd , c ) ; /* [%] pendenza minima per il tratto che si sta dimensionando. */ ms = getMinimumPipeSlope ( ) ; /* [%] Pendenza del terreno */ naturalSlope = METER2CM * ( initialElevation - finalElevation ) / lenght ; /* * Avvisa l'utente che il tratto che si sta progettando e in * contropendenza */ if ( naturalSlope < 0 ) { strWarnings . append ( msg . message ( "trentoP.warning.slope" ) + id ) ; } /* La pendenza del terreno deve essere superiore a quella minima ms */ if ( naturalSlope < ms ) { naturalSlope = ms ; } /* * Se la pendenza del terreno e maggiore di quella del tubo, allora la * pendenza del tubo viene posta uguale a quella del terreno. */ if ( naturalSlope > pipeSlope ) { pipeSlope = naturalSlope ; /* * Progetta la condotta assegnado una pendenza pari a quella del * terreno, calcola altre grandezze correlate come la pendenza e il * grado di riempimento, e restituisce il riempimento effettivo nel * tratto progettato */ base = getHeight2I ( naturalSlope , g , maxd , c ) ; } /* Diametro tubo [cm] */ D = diameter ; // Velocita media nella sezione [ m / s ] meanSpeed = ( discharge / CUBICMETER2LITER ) / ( emptyDegree * D * base / METER2CMSQUARED ) ; // Quota scavo all 'inizio del tubo [ m s . l . m . ] depthInitialPipe = getInitialElevation ( ) - diameter / METER2CM ; /* * Quota dello scavo alla fine del tubo calcolata considerando la * pendenza effettiva del tratto [ m s . l . m . ] */ depthFinalPipe = depthInitialPipe - getLenght ( ) * pipeSlope / METER2CM ; // Quota pelo libero all 'inizio del tubo [ m s . l . m . ] initialFreesurface = depthInitialPipe + emptyDegree * D / METER2CM ; // Quota pelo libero all 'inizio del tubo [ m s . l . m . ] finalFreesurface = depthFinalPipe + emptyDegree * D / METER2CM ; } | Chiama altre subroutine per dimensionare una sezione di tipo 3 ossia trapezioidale . | 836 | 29 |
17,388 | public double verifyEmptyDegree ( StringBuilder strWarnings , double q ) { /* Pari a A * ( Rh ^1/6 ) */ double B ; /* Anglo formato dalla sezione bagnata */ double thta ; /* Costante */ double known ; /* * [rad]Angolo formato dalla sezione bagnata, adottando un diametro * commerciale */ double newtheta = 0 ; B = ( q * sqrt ( WSPECIFICWEIGHT / 2.8 ) ) / ( CUBICMETER2LITER * getKs ( ) ) ; /* Angolo formato dalla sezione bagnata [rad] */ thta = 2 * acos ( 1 - 2 * 0.8 ) ; known = ( B * TWO_TENOVERTHREE ) / pow ( diameterToVerify / METER2CM , THIRTHEENOVERSIX ) ; /* * Angolo formato dalla sezione bagnata considerando un diametro * commerciale [rad] */ newtheta = Utility . thisBisection ( thta , known , ONEOVERSIX , minG , accuracy , jMax , pm , strWarnings ) ; /* Grado di riempimento del tubo */ emptyDegree = 0.5 * ( 1 - cos ( newtheta / 2 ) ) ; return newtheta ; } | Verify if the empty degree is greather than the 0 . 8 . | 308 | 15 |
17,389 | public static void addGpsLogDataPoint ( Connection connection , OmsGeopaparazziProject3To4Converter . GpsPoint point , long gpslogId ) throws Exception { Date timestamp = ETimeUtilities . INSTANCE . TIME_FORMATTER_LOCAL . parse ( point . utctime ) ; String insertSQL = "INSERT INTO " + TableDescriptions . TABLE_GPSLOG_DATA + "(" + // TableDescriptions . GpsLogsDataTableFields . COLUMN_ID . getFieldName ( ) + ", " + // TableDescriptions . GpsLogsDataTableFields . COLUMN_LOGID . getFieldName ( ) + ", " + // TableDescriptions . GpsLogsDataTableFields . COLUMN_DATA_LON . getFieldName ( ) + ", " + // TableDescriptions . GpsLogsDataTableFields . COLUMN_DATA_LAT . getFieldName ( ) + ", " + // TableDescriptions . GpsLogsDataTableFields . COLUMN_DATA_ALTIM . getFieldName ( ) + ", " + // TableDescriptions . GpsLogsDataTableFields . COLUMN_DATA_TS . getFieldName ( ) + // ") VALUES" + "(?,?,?,?,?,?)" ; try ( PreparedStatement writeStatement = connection . prepareStatement ( insertSQL ) ) { writeStatement . setLong ( 1 , point . id ) ; writeStatement . setLong ( 2 , gpslogId ) ; writeStatement . setDouble ( 3 , point . lon ) ; writeStatement . setDouble ( 4 , point . lat ) ; writeStatement . setDouble ( 5 , point . altim ) ; writeStatement . setLong ( 6 , timestamp . getTime ( ) ) ; writeStatement . executeUpdate ( ) ; } } | Adds a new XY entry to the gps table . | 415 | 11 |
17,390 | public static List < GpsLog > getLogsList ( IHMConnection connection ) throws Exception { List < GpsLog > logsList = new ArrayList <> ( ) ; String sql = "select " + // GpsLogsTableFields . COLUMN_ID . getFieldName ( ) + "," + // GpsLogsTableFields . COLUMN_LOG_STARTTS . getFieldName ( ) + "," + // GpsLogsTableFields . COLUMN_LOG_ENDTS . getFieldName ( ) + "," + // GpsLogsTableFields . COLUMN_LOG_TEXT . getFieldName ( ) + // " from " + TABLE_GPSLOGS ; // try ( IHMStatement statement = connection . createStatement ( ) ; IHMResultSet rs = statement . executeQuery ( sql ) ; ) { statement . setQueryTimeout ( 30 ) ; // set timeout to 30 sec. // first get the logs while ( rs . next ( ) ) { long id = rs . getLong ( 1 ) ; long startDateTimeString = rs . getLong ( 2 ) ; long endDateTimeString = rs . getLong ( 3 ) ; String text = rs . getString ( 4 ) ; GpsLog log = new GpsLog ( ) ; log . id = id ; log . startTime = startDateTimeString ; log . endTime = endDateTimeString ; log . text = text ; logsList . add ( log ) ; } } return logsList ; } | Get the list of available logs . | 329 | 7 |
17,391 | public static void collectDataForLog ( IHMConnection connection , GpsLog log ) throws Exception { long logId = log . id ; String query = "select " + // GpsLogsDataTableFields . COLUMN_DATA_LAT . getFieldName ( ) + "," + // GpsLogsDataTableFields . COLUMN_DATA_LON . getFieldName ( ) + "," + // GpsLogsDataTableFields . COLUMN_DATA_ALTIM . getFieldName ( ) + "," + // GpsLogsDataTableFields . COLUMN_DATA_TS . getFieldName ( ) + // " from " + TABLE_GPSLOG_DATA + " where " + // GpsLogsDataTableFields . COLUMN_LOGID . getFieldName ( ) + " = " + logId + " order by " + GpsLogsDataTableFields . COLUMN_DATA_TS . getFieldName ( ) ; try ( IHMStatement newStatement = connection . createStatement ( ) ; IHMResultSet result = newStatement . executeQuery ( query ) ; ) { newStatement . setQueryTimeout ( 30 ) ; while ( result . next ( ) ) { double lat = result . getDouble ( 1 ) ; double lon = result . getDouble ( 2 ) ; double altim = result . getDouble ( 3 ) ; long ts = result . getLong ( 4 ) ; GpsPoint gPoint = new GpsPoint ( ) ; gPoint . lon = lon ; gPoint . lat = lat ; gPoint . altim = altim ; gPoint . utctime = ts ; log . points . add ( gPoint ) ; } } } | Gather gps points data for a supplied log . | 376 | 11 |
17,392 | public static SshTunnelHandler openTunnel ( String remoteHost , String remoteSshUser , String remoteSshPwd , int localPort , int remotePort ) throws JSchException { int port = 22 ; JSch jsch = new JSch ( ) ; Session tunnelingSession = jsch . getSession ( remoteSshUser , remoteHost , port ) ; tunnelingSession . setPassword ( remoteSshPwd ) ; HMUserInfo lui = new HMUserInfo ( "" ) ; tunnelingSession . setUserInfo ( lui ) ; tunnelingSession . setConfig ( "StrictHostKeyChecking" , "no" ) ; tunnelingSession . setPortForwardingL ( localPort , "localhost" , remotePort ) ; tunnelingSession . connect ( ) ; tunnelingSession . openChannel ( "direct-tcpip" ) ; return new SshTunnelHandler ( tunnelingSession ) ; } | Open a tunnel to the remote host . | 202 | 8 |
17,393 | public static Vector getRawLong ( int [ ] data , int offset ) { Vector v = new Vector ( ) ; // TODO: Incorrecto. Repasar ... // _val = struct.unpack('<l', _long)[0] int val = 0 ; v . add ( new Integer ( offset + 32 ) ) ; v . add ( new Integer ( val ) ) ; return v ; } | Read a long value from a group of unsigned bytes | 85 | 10 |
17,394 | public static Vector getTextString ( int [ ] data , int offset ) throws Exception { int bitPos = offset ; int newBitPos = ( ( Integer ) DwgUtil . getBitShort ( data , bitPos ) . get ( 0 ) ) . intValue ( ) ; int len = ( ( Integer ) DwgUtil . getBitShort ( data , bitPos ) . get ( 1 ) ) . intValue ( ) ; bitPos = newBitPos ; int bitLen = len * 8 ; Object cosa = DwgUtil . getBits ( data , bitLen , bitPos ) ; String string ; if ( cosa instanceof byte [ ] ) { string = new String ( ( byte [ ] ) cosa ) ; } | Read a String from a group of unsigned bytes | 158 | 9 |
17,395 | public Iterator < Compound > toRootOrder ( final Compound c ) { return new Iterator < Compound > ( ) { Compound curr ; TreeNode n = node ( c ) ; Compound parent = c ; public boolean hasNext ( ) { return ! n . isRoot ( ) ; } public Compound next ( ) { if ( hasNext ( ) ) { curr = parent ; parent = n . parent ; n = node ( n . parent ) ; return curr ; } else { throw new NoSuchElementException ( ) ; } } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } | Returns all compounds from the Compound argument to the root of the tree following the path . | 137 | 18 |
17,396 | public void println ( String value ) { print ( value ) ; out . println ( ) ; out . flush ( ) ; newLine = true ; } | Print the string as the last value on the line . The value will be quoted if needed . | 31 | 19 |
17,397 | public void println ( String [ ] values ) { for ( int i = 0 ; i < values . length ; i ++ ) { print ( values [ i ] ) ; } out . println ( ) ; out . flush ( ) ; newLine = true ; } | Print a single line of comma separated values . The values will be quoted if needed . Quotes and newLine characters will be escaped . | 54 | 27 |
17,398 | public void printlnComment ( String comment ) { if ( this . strategy . isCommentingDisabled ( ) ) { return ; } if ( ! newLine ) { out . println ( ) ; } out . print ( this . strategy . getCommentStart ( ) ) ; out . print ( ' ' ) ; for ( int i = 0 ; i < comment . length ( ) ; i ++ ) { char c = comment . charAt ( i ) ; switch ( c ) { case ' ' : if ( i + 1 < comment . length ( ) && comment . charAt ( i + 1 ) == ' ' ) { i ++ ; } // break intentionally excluded. case ' ' : out . println ( ) ; out . print ( this . strategy . getCommentStart ( ) ) ; out . print ( ' ' ) ; break ; default : out . print ( c ) ; break ; } } out . println ( ) ; out . flush ( ) ; newLine = true ; } | Put a comment among the comma separated values . Comments will always begin on a new line and occupy a least one full line . The character specified to star comments and a space will be inserted at the beginning of each new line in the comment . | 204 | 48 |
17,399 | public void print ( String value ) { boolean quote = false ; if ( value . length ( ) > 0 ) { char c = value . charAt ( 0 ) ; if ( newLine && ( c < ' ' || ( c > ' ' && c < ' ' ) || ( c > ' ' && c < ' ' ) || ( c > ' ' ) ) ) { quote = true ; } if ( c == ' ' || c == ' ' || c == ' ' ) { quote = true ; } for ( int i = 0 ; i < value . length ( ) ; i ++ ) { c = value . charAt ( i ) ; if ( c == ' ' || c == this . strategy . getDelimiter ( ) || c == ' ' || c == ' ' ) { quote = true ; c = value . charAt ( value . length ( ) - 1 ) ; break ; } } if ( c == ' ' || c == ' ' || c == ' ' ) { quote = true ; } } else if ( newLine ) { // always quote an empty token that is the first // on the line, as it may be the only thing on the // line. If it were not quoted in that case, // an empty line has no tokens. quote = true ; } if ( newLine ) { newLine = false ; } else { out . print ( this . strategy . getDelimiter ( ) ) ; } if ( quote ) { out . print ( escapeAndQuote ( value ) ) ; } else { out . print ( value ) ; } out . flush ( ) ; } | Print the string as the next value on the line . The value will be quoted if needed . | 337 | 19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.