code
stringlengths
73
34.1k
label
stringclasses
1 value
public static GridCoverage2D mergeCoverages( GridCoverage2D valuesMap, GridCoverage2D onMap ) { RegionMap valuesRegionMap = getRegionParamsFromGridCoverage(valuesMap); int cs = valuesRegionMap.getCols(); int rs = valuesRegionMap.getRows(); RegionMap onRegionMap = getRegionParamsFromGridC...
java
public static double[][] calculateHypsographic( GridCoverage2D elevationCoverage, int bins, IHMProgressMonitor pm ) { if (pm == null) { pm = new DummyProgressMonitor(); } RegionMap regionMap = getRegionParamsFromGridCoverage(elevationCoverage); int cols = regionMap.getCols();...
java
static public void zipFolder( String srcFolder, String destZipFile, boolean addBaseFolder ) throws IOException { if (new File(srcFolder).isDirectory()) { try (FileOutputStream fileWriter = new FileOutputStream(destZipFile); ZipOutputStream zip = new ZipOutputStream(fileWriter)) {...
java
public static String unzipFolder( String zipFile, String destFolder, boolean addTimeStamp ) throws IOException { String newFirstName = null; try (ZipFile zf = new ZipFile(zipFile)) { Enumeration< ? extends ZipEntry> zipEnum = zf.entries(); String firstName = null; w...
java
public void setWorkingDirectory(File dir) { if (!dir.exists()) { throw new IllegalArgumentException(dir + " doesn't exist."); } pb.directory(dir); }
java
public int exec() throws IOException { int exitValue = 0; List<String> argl = new ArrayList<String>(); argl.add(executable.toString()); for (Object a : args) { if (a != null) { if (a.getClass() == String.class) { argl.add(a.toString()); ...
java
private void addResult(ValidationResult result) { if (result == null || result.count() == 0) { return; } this.results.add(result); }
java
public List<ValidationMessage<Origin>> getMessages(String messageKey, Severity severity) { List<ValidationMessage<Origin>> messages = new ArrayList<ValidationMessage<Origin>>(); for (ValidationResult result : results) { for (ValidationMessage<Origin> message : result.getMessages()) { ...
java
public static byte[] serialize( Object obj ) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(obj); out.close(); return bos.toByteArray(); } }
java
public static <T> T deSerialize( byte[] bytes, Class<T> adaptee ) throws Exception { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object readObject = in.readObject(); return adaptee.cast(readObject); }
java
public static void serializeToDisk( File file, Object obj ) throws IOException { byte[] serializedObj = serialize(obj); try (RandomAccessFile raFile = new RandomAccessFile(file, "rw")) { raFile.write(serializedObj); } }
java
public static <T> T deSerializeFromDisk( File file, Class<T> adaptee ) throws Exception { try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { long length = raf.length(); // System.out.println(length + "/" + (int) length); byte[] bytes = new byte[(int) length]; ...
java
private void checkParametersAndRunEnergyBalance( double[] rain, double[][] T, double[][] V, double[][] P, double[][] RH, double month, double day, double hour, double[] Abasin, double[][][] A, double[][][] EI, double[][] DTd, double[][] DTm, double[][] canopy ) { double Dt = ((double) t...
java
public static BufferedReader getBufferedXMLReader(InputStream stream, int xmlLookahead) throws IOException { // create a buffer so we can reset the input stream BufferedInputStream input = new BufferedInputStream(stream); input.mark(xmlLookahead); // create object to hold e...
java
public static BufferedReader getBufferedXMLReader(Reader reader, int xmlLookahead) throws IOException { // ensure the reader is a buffered reader if (!(reader instanceof BufferedReader)) { reader = new BufferedReader(reader); } // mark the input stream r...
java
private void validateCoefficients() { if (coefsValid) return; if (n >= 2) { double xBar = (double) sumX / n; double yBar = (double) sumY / n; a1 = (double) ((n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX)); a0 = (double) (yBar - a1 * xB...
java
public static synchronized void initializeDXF_SCHEMA( CoordinateReferenceSystem crs ) { if (DXF_POINTSCHEMA != null && DXF_POINTSCHEMA.getAttributeCount() != 0) return; SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setName("dxfpointfile"); b.setCRS(crs); ...
java
private byte[] readClassData(JavaFileObject classFile) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; InputStream classStream = classFile.openInputStream(); int n = classStream.read(buf); while (n > 0) { bos....
java
public static String[] getAllMarksArray() { Set<String> keySet = markNamesToDef.keySet(); return (String[]) keySet.toArray(new String[keySet.size()]); }
java
public static void substituteMark( Rule rule, String wellKnownMarkName ) { PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Mark oldMark = SLD.mark(pointSymbolizer); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.graphicalSymbols().clear(); ...
java
public static void substituteExternalGraphics( Rule rule, URL externalGraphicsUrl ) { String urlString = externalGraphicsUrl.toString(); String format = ""; if (urlString.toLowerCase().endsWith(".png")) { format = "image/png"; } else if (urlString.toLowerCase().endsWith(".jpg...
java
public static void changeMarkSize( Rule rule, int newSize ) { PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.setSize(ff.literal(newSize)); // Mark oldMark = SLDs.mark(pointSymbolizer); // old...
java
public static void changeRotation( Rule rule, int newRotation ) { PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.setRotation(ff.literal(newRotation)); // Mark oldMark = SLDs.mark(pointSymbolizer); ...
java
@SuppressWarnings({"rawtypes", "unchecked"}) public static void setOffset( Symbolizer symbolizer, String text ) { if (text.indexOf(',') == -1) { return; } String[] split = text.split(","); if (split.length != 2) { return; } double xOffset = Dou...
java
public static String styleToString( Style style ) throws Exception { StyledLayerDescriptor sld = sf.createStyledLayerDescriptor(); UserLayer layer = sf.createUserLayer(); layer.setLayerFeatureConstraints(new FeatureTypeConstraint[]{null}); sld.addStyledLayer(layer); layer.addUser...
java
public static StyleWrapper createStyleFromGraphic( File graphicsPath ) throws IOException { String name = graphicsPath.getName(); ExternalGraphic exGraphic = null; if (name.toLowerCase().endsWith(".png")) { exGraphic = sf.createExternalGraphic(graphicsPath.toURI().toURL(), "image/png...
java
public static float[] getDash( String dashStr ) { if (dashStr == null) { return null; } String[] dashSplit = dashStr.split(","); //$NON-NLS-1$ int size = dashSplit.length; float[] dash = new float[size]; try { for( int i = 0; i < dash.length; i++ )...
java
public static String getDashString( float[] dashArray ) { StringBuilder sb = null; for( float f : dashArray ) { if (sb == null) { sb = new StringBuilder(String.valueOf(f)); } else { sb.append(","); sb.append(String.valueOf(f)); ...
java
public static int sld2awtJoin( String sldJoin ) { if (sldJoin.equals(lineJoinNames[1])) { return BasicStroke.JOIN_BEVEL; } else if (sldJoin.equals("") || sldJoin.equals(lineJoinNames[2])) { return BasicStroke.JOIN_MITER; } else if (sldJoin.equals(lineJoinNames[3])) { ...
java
public static int sld2awtCap( String sldCap ) { if (sldCap.equals("") || sldCap.equals(lineCapNames[1])) { return BasicStroke.CAP_BUTT; } else if (sldCap.equals(lineCapNames[2])) { return BasicStroke.CAP_ROUND; } else if (sldCap.equals(lineCapNames[3])) { retu...
java
public static Envelope scaleToWidth( Envelope original, double newWidth ) { double width = original.getWidth(); double factor = newWidth / width; double newHeight = original.getHeight() * factor; return new Envelope(original.getMinX(), original.getMinX() + newWidth, original.getMinY(),...
java
public static int getDayOfYear(Calendar cal, int type) { int jday = cal.get(Calendar.DAY_OF_YEAR); int mo = cal.get(java.util.Calendar.MONTH) + 1; if (type == CALENDAR_YEAR) { return jday; } else if (type == SOLAR_YEAR) { int day = cal.get(Calendar.DAY_OF_MONTH); ...
java
public static double deltaHours(int calUnit, int increments) { if (calUnit == Calendar.DATE) { return 24 * increments; } else if (calUnit == Calendar.HOUR) { return increments; } else if (calUnit == Calendar.MINUTE) { return increments / 60; } else if ...
java
protected ValidationMessage<Origin> reportError(Origin origin, String messageKey, Object... params) { return reportMessage(Severity.ERROR, origin, messageKey, params); }
java
protected ValidationMessage<Origin> reportFeatureError(Origin origin, String messageKey, Feature feature, Object... params) { ValidationMessage<Origin> message = reportMessage(Severity.ERROR, origin, messageKey, params); appendLocusTadAndGeneIDToMessage(feature, message); return message; ...
java
public static void appendLocusTadAndGeneIDToMessage(Feature feature, ValidationMessage<Origin> message) { if (SequenceEntryUtils.isQualifierAvailable(Qualifier.LOCUS_TAG_QUALIFIER_NAME, feature)) { Qualifier locusTag = SequenceEntryUtils.getQualifier(Qualifier.LOCUS_TAG_QUALIFIER_NAME, feature); ...
java
protected ValidationMessage<Origin> reportWarning(Origin origin, String messageKey, Object... params) { return reportMessage(Severity.WARNING, origin, messageKey, params); }
java
protected ValidationMessage<Origin> reportMessage(Severity severity, Origin origin, String messageKey, Object... params) { ValidationMessage<Origin> message = EntryValidations.createMessage(origin, severity, messageKey, params); message.getMessage(); // System.out.println("message = " + messag...
java
private boolean isAlone( Geometry geometryN ) { Coordinate[] coordinates = geometryN.getCoordinates(); if (coordinates.length > 1) { Coordinate first = coordinates[0]; Coordinate last = coordinates[coordinates.length - 1]; for( SimpleFeature line : linesList ) { ...
java
public static void defaultSmoothShapefile( String shapePath, String outPath ) throws Exception { PrintStreamProgressMonitor pm = new PrintStreamProgressMonitor(System.out, System.err); SimpleFeatureCollection initialFC = OmsShapefileFeatureReader.readShapefile(shapePath); OmsLineSmootherMcMaste...
java
@Override public double magnitudeSqr( Object pt ) { double sum = 0.0; double[] coords = coords(pt); for( int i = 0; i < dimensions; i++ ) { double c = coords[i]; sum += c * c; } return sum; }
java
public static byte[] generateSecretKey() { final byte[] k = new byte[KEY_LEN]; final SecureRandom random = new SecureRandom(); random.nextBytes(k); return k; }
java
private static void initialize() { for (int i = 0; i < 256; ++i) { long crc = i; for (int j = 8; j > 0; j--) { if ((crc & 1) == 1) crc = (crc >>> 1) ^ polynomial; else crc >>>= 1; } values[i] = crc; } init_done = true; }
java
public static long calculateCRC32(byte[] buffer, int offset, int length) { if (!init_done) { initialize(); } for (int i = offset; i < offset + length; i++) { long tmp1 = (crc >>> 8) & 0x00FFFFFFL; long tmp2 = values[(int) ((crc ^ Character.toUpperCase((char) buffer[i])) & 0xff)]; crc = tmp1 ^ tmp...
java
private synchronized URLClassLoader getClassLoader() { if (modelClassLoader == null) { List<File> jars = res.filterFiles("jar"); // jars as defined in List<File> cli_jars = getExtraResources(); // cli extra jars List<File> dirs = res.filterDirectories(); // testing ...
java
public static double getDistanceBetween( IHMConnection connection, Coordinate p1, Coordinate p2, int srid ) throws Exception { if (srid < 0) { srid = 4326; } GeometryFactory gf = new GeometryFactory(); LineString lineString = gf.createLineString(new Coordinate[]{p1, p2}); ...
java
private boolean moveToNextTriggerpoint( RandomIter triggerIter, RandomIter flowIter, int[] flowDirColRow ) { double tmpFlowValue = flowIter.getSampleDouble(flowDirColRow[0], flowDirColRow[1], 0); if (tmpFlowValue == 10) { return false; } if (!ModelsEngine.go_downstream(flowDi...
java
public static void memclr( byte[] array, int offset, int length ) { for( int i = 0; i < length; ++i, ++offset ) array[offset] = 0; }
java
public static byte[] zero_pad( byte[] original, int block_size ) { if ((original.length % block_size) == 0) { return original; } byte[] result = new byte[round_up(original.length, block_size)]; memcpy(result, 0, original, 0, original.length); // Unnecessary - jvm se...
java
public static boolean isSupportedVectorExtension( String name ) { for( String ext : supportedVectors ) { if (name.toLowerCase().endsWith(ext)) { return true; } } return false; }
java
public static boolean isSupportedRasterExtension( String name ) { for( String ext : supportedRasters ) { if (name.toLowerCase().endsWith(ext)) { return true; } } return false; }
java
public static GridCoverage2D readRaster( String path ) throws Exception { OmsRasterReader reader = new OmsRasterReader(); reader.file = path; reader.process(); GridCoverage2D geodata = reader.outRaster; return geodata; }
java
private void swap(int i, int j) { double[] temp = data[i]; data[i] = data[j]; data[j] = temp; }
java
public Matrix transpose() { Matrix A = new Matrix(N, M); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { A.data[j][i] = data[i][j]; } } return A; }
java
public Matrix solve(Matrix rhs) { if (M != N || rhs.M != N || rhs.N != 1) { throw new RuntimeException("Illegal matrix dimensions."); } // create copies of the data Matrix A = new Matrix(this); Matrix b = new Matrix(rhs); // Gaussian elimination with partial...
java
public void print() { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { System.out.printf("%9.4f ", data[i][j]); } System.out.println(); } }
java
public void createTables( boolean makeIndexes ) throws Exception { database.executeInsertUpdateDeleteSql("DROP TABLE IF EXISTS " + TABLE_TILES); database.executeInsertUpdateDeleteSql("DROP TABLE IF EXISTS " + TABLE_METADATA); database.executeInsertUpdateDeleteSql(CREATE_TILES); database....
java
public void fillMetadata( float n, float s, float w, float e, String name, String format, int minZoom, int maxZoom ) throws Exception { // type = baselayer // version = 1.1 // descritpion = name String query = toMetadataQuery("name", name); database.executeInsertUpdat...
java
public synchronized void addTile( int x, int y, int z, byte[] imageBytes ) throws Exception { database.execOnConnection(connection -> { try (IHMPreparedStatement pstmt = connection.prepareStatement(insertTileSql);) { pstmt.setInt(1, z); pstmt.setInt(2, x); ...
java
public synchronized void addTilesInBatch( List<Tile> tilesList ) throws Exception { database.execOnConnection(connection -> { boolean autoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); try (IHMPreparedStatement pstmt = connection.prepareStatement(insert...
java
public byte[] getTile( int tx, int tyOsm, int zoom ) throws Exception { int ty = tyOsm; if (tileRowType.equals("tms")) { int[] tmsTileXY = MercatorUtils.osmTile2TmsTile(tx, tyOsm, zoom); ty = tmsTileXY[1]; } int _ty = ty; return database.execOnConnection(c...
java
public Envelope getBounds() throws Exception { checkMetadata(); String boundsWSEN = metadataMap.get("bounds"); String[] split = boundsWSEN.split(","); double w = Double.parseDouble(split[0]); double s = Double.parseDouble(split[1]); double e = Double.parseDouble(split[2])...
java
public int[] getBoundsInTileIndex( int zoomlevel ) throws Exception { String sql = "select min(tile_column), max(tile_column), min(tile_row), max(tile_row) from tiles where zoom_level=" + zoomlevel; return database.execOnConnection(connection -> { try (IHMStatement statement ...
java
public void out2in(Object from, String from_out, Object... tos) { for (Object co : tos) { out2in(from, from_out, co, from_out); } }
java
public void in2in(String in, Object to, String to_in) { controller.mapIn(in, to, to_in); }
java
public void in2in(String in, Object... to) { for (Object cmd : to) { in2in(in, cmd, in); } }
java
public void field2in(Object o, String field, Object to, String to_in) { controller.mapInField(o, field, to, to_in); }
java
public void field2in(Object o, String field, Object to) { field = field.trim(); if (field.indexOf(' ') > 0) { // maybe multiple field names given String[] fields = field.split("\\s+"); for (String f : fields) { field2in(o, f, to, f); } ...
java
public void out2field(Object from, String from_out, Object o, String field) { controller.mapOutField(from, from_out, o, field); }
java
public void out2field(Object from, String from_out, Object o) { out2field(from, from_out, o, from_out); }
java
public void out2out(String out, Object to, String to_out) { controller.mapOut(out, to, to_out); }
java
@Deprecated public void connect(Object from, String from_out, Object to, String to_in) { controller.connect(from, from_out, to, to_in); }
java
protected void reportError(ValidationResult result, String messageKey, Object... params) { reportMessage(result, Severity.ERROR, messageKey, params); }
java
protected void reportWarning(ValidationResult result, String messageKey, Object... params) { reportMessage(result, Severity.WARNING, messageKey, params); }
java
protected void reportMessage(ValidationResult result, Severity severity, String messageKey, Object... params) { result.append(EntryValidations.createMessage(origin, severity, messageKey, params)); }
java
private void calcInsolation( double lambda, WritableRaster demWR, WritableRaster gradientWR, WritableRaster insolationWR, int day, double dx ) { // calculating the day angle // double dayang = 2 * Math.PI * (day - 1) / 365.0; double dayangb = (360 / 365.25) * (day - 79.436); ...
java
public static boolean isCrsValid( CoordinateReferenceSystem crs ) { if (crs instanceof AbstractSingleCRS) { AbstractSingleCRS aCrs = (AbstractSingleCRS) crs; Datum datum = aCrs.getDatum(); ReferenceIdentifier name = datum.getName(); String code = name.getCode(); ...
java
@SuppressWarnings("nls") public static void writeProjectionFile( String filePath, String extention, CoordinateReferenceSystem crs ) throws IOException { /* * fill a prj file */ String prjPath = null; if (extention != null && filePath.toLowerCase().endsWith("." +...
java
public static void reproject( CoordinateReferenceSystem from, CoordinateReferenceSystem to, Object[] geometries ) throws Exception { MathTransform mathTransform = CRS.findMathTransform(from, to); for( int i = 0; i < geometries.length; i++ ) { geometries[i] = JTS.transform((Geome...
java
public static void reproject( CoordinateReferenceSystem from, CoordinateReferenceSystem to, Coordinate[] coordinates ) throws Exception { MathTransform mathTransform = CRS.findMathTransform(from, to); for( int i = 0; i < coordinates.length; i++ ) { coordinates[i] = JTS.transform...
java
public static double getMetersAsWGS84( double meters, Coordinate c ) { GeodeticCalculator gc = new GeodeticCalculator(DefaultGeographicCRS.WGS84); gc.setStartingGeographicPoint(c.x, c.y); gc.setDirection(90, meters); Point2D destinationGeographicPoint = gc.getDestinationGeographicPoint()...
java
private void createHoughPixels( double[][][] houghValues, byte houghPixels[] ) { double d = -1D; for( int j = 0; j < height; j++ ) { for( int k = 0; k < width; k++ ) { if (houghValues[k][j][0] > d) { d = houghValues[k][j][0]; } ...
java
public void drawCircles( double[][][] houghValues, byte[] circlespixels ) { // Copy original input pixels into output // circle location display image and // combine with saturation at 100 int roiaddr = 0; for( int y = offy; y < offy + height; y++ ) { for( int x = of...
java
public String getSequence(Long beginPosition, Long endPosition) { byte[] sequenceByte = getSequenceByte(beginPosition, endPosition); if (sequenceByte != null) return new String(sequenceByte); return null; }
java
private void set(Matrix m) { this.nRows = this.nCols = Math.min(m.nRows, m.nCols); this.values = m.values; }
java
protected void set(double values[][]) { super.set(values); nRows = nCols = Math.min(nRows, nCols); }
java
public static void printMatrixData(double[][] matrix) { int cols = matrix[0].length; int rows = matrix.length; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { printer.print(matrix[r][c]); printer.print(separator); } ...
java
public static String envelope2WKT(org.locationtech.jts.geom.Envelope env) { GeometryFactory gf = GeometryUtilities.gf(); Geometry geometry = gf.toGeometry(env); return geometry.toText(); }
java
public int read() throws IOException { int b = 0; // Byte to be read is already in out buffer, simply returning it if (fOffset < fLength) { return fData[fOffset++] & 0xff; } /* * End of the stream is reached. * I also believe that in certain cases ...
java
public void close() throws IOException { if (fInputStream != null) { fInputStream.close(); fInputStream = null; fData = null; } }
java
public String getTranslation() { if (codons == null) { return ""; } StringBuilder translation = new StringBuilder(); for (Codon codon : codons) { translation.append(codon.getAminoAcid()); } return translation.toString(); }
java
public String getConceptualTranslation() { if (codons == null) { return ""; } StringBuilder translation = new StringBuilder(); for (int i = 0 ; i < conceptualTranslationCodons ; ++i) { Codon codon = codons.get(i); translation.append(codon.getAm...
java
public static double[] gaussianSmooth( double[] values, int kernelRadius ) throws Exception { int size = values.length; double[] newValues = new double[values.length]; double[] kernelData2D = makeGaussianKernel(kernelRadius); for( int i = 0; i < kernelRadius; i++ ) { newValue...
java
public static double[] averageSmooth( double[] values, int lookAhead ) throws Exception { int size = values.length; double[] newValues = new double[values.length]; for( int i = 0; i < lookAhead; i++ ) { newValues[i] = values[i]; } for( int i = lookAhead; i < size - lo...
java
public Coordinate wgs84ToEnu( Coordinate cLL ) { checkZ(cLL); Coordinate cEcef = wgs84ToEcef(cLL); Coordinate enu = ecefToEnu(cEcef); return enu; }
java
public Coordinate enuToWgs84( Coordinate enu ) { checkZ(enu); Coordinate cEcef = enuToEcef(enu); Coordinate wgs84 = ecefToWgs84(cEcef); return wgs84; }
java
public void convertGeometryFromEnuToWgs84( Geometry geometryEnu ) { Coordinate[] coordinates = geometryEnu.getCoordinates(); for( int i = 0; i < coordinates.length; i++ ) { Coordinate wgs84 = enuToWgs84(coordinates[i]); coordinates[i].x = wgs84.x; coordinates[i].y = w...
java
public void convertGeometryFromWgsToEnu( Geometry geometryWgs ) { Coordinate[] coordinates = geometryWgs.getCoordinates(); for( int i = 0; i < coordinates.length; i++ ) { Coordinate enu = wgs84ToEnu(coordinates[i]); coordinates[i].x = enu.x; coordinates[i].y = enu.y; ...
java
public Envelope convertEnvelopeFromWgsToEnu( Envelope envelopeWgs ) { Polygon polygonEnu = GeometryUtilities.createPolygonFromEnvelope(envelopeWgs); convertGeometryFromWgsToEnu(polygonEnu); Envelope envelopeEnu = polygonEnu.getEnvelopeInternal(); return envelopeEnu; }
java
public synchronized Position goTo( Double lon, Double lat, Double elev, Double azimuth, boolean animate ) { View view = getWwd().getView(); view.stopAnimations(); view.stopMovement(); Position eyePosition; if (lon == null || lat == null) { Position currentEyePosition...
java