_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q174400
CDMUtil.containsVLEN
test
static public boolean containsVLEN(List<Dimension> dimset) { if(dimset == null) return false; for(Dimension dim : dimset) { if(dim.isVariableLength()) return true; } return false; }
java
{ "resource": "" }
q174401
CDMUtil.computeEffectiveShape
test
static public int[] computeEffectiveShape(List<DapDimension> dimset) { if(dimset == null || dimset.size() == 0) return new int[0]; int effectiverank = dimset.size(); int[] shape = new int[effectiverank]; for(int i = 0; i < effectiverank; i++) { shape[i] = (int) dimset.get(i).getSize(); } return shape; }
java
{ "resource": "" }
q174402
TimeUnit.add
test
public Date add( Date d) { Calendar cal = Calendar.getInstance(); cal.setTime( d); cal.add( Calendar.SECOND, (int) getValueInSeconds()); return cal.getTime(); }
java
{ "resource": "" }
q174403
ScaledUnit.myMultiplyBy
test
@Override protected Unit myMultiplyBy(final Unit that) throws MultiplyException { return that instanceof ScaledUnit ? new ScaledUnit(getScale() * ((ScaledUnit) that).getScale(), getUnit().multiplyBy(((ScaledUnit) that).getUnit())) : new ScaledUnit(getScale(), getUnit().multiplyBy(that)); }
java
{ "resource": "" }
q174404
ScaledUnit.myDivideBy
test
@Override protected Unit myDivideBy(final Unit that) throws OperationException { return that instanceof ScaledUnit ? new ScaledUnit(getScale() / ((ScaledUnit) that).getScale(), getUnit().divideBy(((ScaledUnit) that).getUnit())) : new ScaledUnit(getScale(), getUnit().divideBy(that)); }
java
{ "resource": "" }
q174405
ScaledUnit.myDivideInto
test
@Override protected Unit myDivideInto(final Unit that) throws OperationException { return that instanceof ScaledUnit ? new ScaledUnit(((ScaledUnit) that).getScale() / getScale(), getUnit().divideInto(((ScaledUnit) that).getUnit())) : new ScaledUnit(1 / getScale(), getUnit().divideInto(that)); }
java
{ "resource": "" }
q174406
ScaledUnit.myRaiseTo
test
@Override protected Unit myRaiseTo(final int power) throws RaiseException { return new ScaledUnit(Math.pow(getScale(), power), getUnit().raiseTo( power)); }
java
{ "resource": "" }
q174407
ScaledUnit.toDerivedUnit
test
public double toDerivedUnit(final double amount) throws ConversionException { if (!(_unit instanceof DerivableUnit)) { throw new ConversionException(this, getDerivedUnit()); } return ((DerivableUnit) _unit).toDerivedUnit(amount * getScale()); }
java
{ "resource": "" }
q174408
ScaledUnit.toDerivedUnit
test
public float[] toDerivedUnit(final float[] input, final float[] output) throws ConversionException { final float scale = (float) getScale(); for (int i = input.length; --i >= 0;) { output[i] = input[i] * scale; } if (!(_unit instanceof DerivableUnit)) { throw new ConversionException(this, getDerivedUnit()); } return ((DerivableUnit) getUnit()).toDerivedUnit(output, output); }
java
{ "resource": "" }
q174409
ScaledUnit.fromDerivedUnit
test
public double fromDerivedUnit(final double amount) throws ConversionException { if (!(_unit instanceof DerivableUnit)) { throw new ConversionException(getDerivedUnit(), this); } return ((DerivableUnit) getUnit()).fromDerivedUnit(amount) / getScale(); }
java
{ "resource": "" }
q174410
ScaledUnit.getCanonicalString
test
public String getCanonicalString() { return DerivedUnitImpl.DIMENSIONLESS.equals(_unit) ? Double.toString(getScale()) : Double.toString(getScale()) + " " + _unit.toString(); }
java
{ "resource": "" }
q174411
GribDataReader.readData
test
public Array readData(SectionIterable want) throws IOException, InvalidRangeException { if (vindex instanceof PartitionCollectionImmutable.VariableIndexPartitioned) return readDataFromPartition((PartitionCollectionImmutable.VariableIndexPartitioned) vindex, want); else return readDataFromCollection(vindex, want); }
java
{ "resource": "" }
q174412
GribDataReader.readData2
test
public Array readData2(CoordsSet want, RangeIterator yRange, RangeIterator xRange) throws IOException { if (vindex instanceof PartitionCollectionImmutable.VariableIndexPartitioned) return readDataFromPartition2((PartitionCollectionImmutable.VariableIndexPartitioned) vindex, want, yRange, xRange); else return readDataFromCollection2(vindex, want, yRange, xRange); }
java
{ "resource": "" }
q174413
StationTimeSeriesCollectionImpl.flatten
test
@Override public PointFeatureCollection flatten(List<String> stationNames, CalendarDateRange dateRange, List<VariableSimpleIF> varList) throws IOException { if ((stationNames == null) || (stationNames.size() == 0)) return new StationTimeSeriesCollectionFlattened(this, dateRange); List<StationFeature> subsetStations = getStationHelper().getStationFeaturesFromNames(stationNames); return new StationTimeSeriesCollectionFlattened(new StationSubset(this, subsetStations), dateRange); }
java
{ "resource": "" }
q174414
InvCatalog.findService
test
public InvService findService(String name) { if (name == null) return null; for (InvService s : services) { if (name.equals(s.getName())) return s; // look for nested servers if (s.getServiceType() == ServiceType.COMPOUND) { InvService result = s.findNestedService(name); if (result != null) return result; } } return null; }
java
{ "resource": "" }
q174415
Level2Record.getGateSize
test
public int getGateSize(int datatype) { switch (datatype) { case REFLECTIVITY: return ((int) reflect_gate_size); case VELOCITY_HI: case VELOCITY_LOW: case SPECTRUM_WIDTH: return ((int) doppler_gate_size); //high resolution case REFLECTIVITY_HIGH: return ((int) reflectHR_gate_size); case VELOCITY_HIGH: return ((int) velocityHR_gate_size); case SPECTRUM_WIDTH_HIGH: return ((int) spectrumHR_gate_size); case DIFF_REFLECTIVITY_HIGH: return ((int) zdrHR_gate_size); case DIFF_PHASE: return ((int) phiHR_gate_size); case CORRELATION_COEFFICIENT: return ((int) rhoHR_gate_size); } return -1; }
java
{ "resource": "" }
q174416
Level2Record.getGateStart
test
public int getGateStart(int datatype) { switch (datatype) { case REFLECTIVITY: return ((int) reflect_first_gate); case VELOCITY_HI: case VELOCITY_LOW: case SPECTRUM_WIDTH: return ((int) doppler_first_gate); //high resolution case REFLECTIVITY_HIGH: return ((int) reflectHR_first_gate); case VELOCITY_HIGH: return ((int) velocityHR_first_gate); case SPECTRUM_WIDTH_HIGH: return ((int) spectrumHR_first_gate); case DIFF_REFLECTIVITY_HIGH: return ((int) zdrHR_first_gate); case DIFF_PHASE: return ((int) phiHR_first_gate); case CORRELATION_COEFFICIENT: return ((int) rhoHR_first_gate); } return -1; }
java
{ "resource": "" }
q174417
Level2Record.getGateCount
test
public int getGateCount(int datatype) { switch (datatype) { case REFLECTIVITY: return ((int) reflect_gate_count); case VELOCITY_HI: case VELOCITY_LOW: case SPECTRUM_WIDTH: return ((int) doppler_gate_count); // hight resolution case REFLECTIVITY_HIGH: return ((int) reflectHR_gate_count); case VELOCITY_HIGH: return ((int) velocityHR_gate_count); case SPECTRUM_WIDTH_HIGH: return ((int) spectrumHR_gate_count); case DIFF_REFLECTIVITY_HIGH: return ((int) zdrHR_gate_count); case DIFF_PHASE: return ((int) phiHR_gate_count); case CORRELATION_COEFFICIENT: return ((int) rhoHR_gate_count); } return 0; }
java
{ "resource": "" }
q174418
NcMLGWriter.writeXML
test
public void writeXML(NetcdfDataset ncd, OutputStream os, boolean showCoords, String uri) throws IOException { // Output the document, use standard formatter //XMLOutputter fmt = new XMLOutputter(" ", true); //fmt.setLineSeparator("\n"); XMLOutputter fmt = new XMLOutputter( Format.getPrettyFormat()); fmt.output(makeDocument(ncd, showCoords, uri), os); }
java
{ "resource": "" }
q174419
MFlowLayout.preferredLayoutSize
test
public Dimension preferredLayoutSize(Container target) { synchronized (target.getTreeLock()) { Dimension dim = new Dimension(0, 0); for (int i = 0 ; i < target.getComponentCount() ; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = m.getPreferredSize(); // original // dim.height = Math.max(dim.height, d.height); //if (i > 0) { dim.width += hgap; } // dim.width += d.width; // new way Point p = m.getLocation(); dim.width = Math.max(dim.width, p.x+d.width); dim.height = Math.max(dim.height, p.y+d.height); } } Insets insets = target.getInsets(); dim.width += insets.left + insets.right + getHgap()*2; dim.height += insets.top + insets.bottom + getVgap()*2; return dim; } }
java
{ "resource": "" }
q174420
CatalogBuilderHelper.verifyDescendantDataset
test
static CrawlableDataset verifyDescendantDataset( CrawlableDataset ancestorCrDs, String path, CrawlableDatasetFilter filter ) { // Make sure requested path is descendant of ancestor dataset. if ( ! ancestorCrDs.isCollection() ) throw new IllegalArgumentException( "Ancestor dataset <" + ancestorCrDs.getPath() + "> not a collection." ); if ( ! path.startsWith( ancestorCrDs.getPath() ) ) throw new IllegalArgumentException( "Dataset path <" + path + "> not descendant of given dataset <" + ancestorCrDs.getPath() + ">." ); // If path and ancestor are the same, return ancestor. if ( path.length() == ancestorCrDs.getPath().length() ) return ancestorCrDs; // Crawl into the dataset collection through each level of the given path // checking that each level is accepted by the given CrawlableDatasetFilter. String remainingPath = path.substring( ancestorCrDs.getPath().length() ); if ( remainingPath.startsWith( "/" ) ) remainingPath = remainingPath.substring( 1 ); String[] pathSegments = remainingPath.split( "/" ); CrawlableDataset curCrDs = ancestorCrDs; for ( int i = 0; i < pathSegments.length; i++ ) { curCrDs = curCrDs.getDescendant( pathSegments[i]); if ( filter != null ) if ( ! filter.accept( curCrDs ) ) return null; } // Only check complete path for existence since speed of check depends on implementation. if ( ! curCrDs.exists() ) return null; return curCrDs; }
java
{ "resource": "" }
q174421
SimpleCatalogBuilder.generateProxyDsResolverCatalog
test
public InvCatalogImpl generateProxyDsResolverCatalog( CrawlableDataset catalogCrDs, ProxyDatasetHandler pdh ) throws IOException { throw new java.lang.UnsupportedOperationException( "This method not supported by SimpleCatalogBuilder."); }
java
{ "resource": "" }
q174422
CalendarDateUnit.of
test
static public CalendarDateUnit of(String calendarName, String udunitString) { Calendar calt = Calendar.get(calendarName); if (calt == null) calt = Calendar.getDefault(); return new CalendarDateUnit(calt, udunitString); }
java
{ "resource": "" }
q174423
CalendarDateUnit.withCalendar
test
static public CalendarDateUnit withCalendar(Calendar calt, String udunitString) { if (calt == null) calt = Calendar.getDefault(); return new CalendarDateUnit(calt, udunitString); }
java
{ "resource": "" }
q174424
CalendarDateUnit.of
test
static public CalendarDateUnit of(Calendar calt, CalendarPeriod.Field periodField, CalendarDate baseDate) { if (calt == null) calt = Calendar.getDefault(); return new CalendarDateUnit(calt, periodField, baseDate); }
java
{ "resource": "" }
q174425
CalendarDateUnit.makeOffsetFromRefDate
test
public double makeOffsetFromRefDate( CalendarDate date) { if (isCalendarField) { if (date.equals(baseDate)) return 0.0; return date.getDifference(baseDate, periodField); } else { long msecs = date.getDifferenceInMsecs(baseDate); return msecs / period.getValueInMillisecs(); } }
java
{ "resource": "" }
q174426
CalendarDateUnit.makeCalendarDate
test
public CalendarDate makeCalendarDate(double value) { if (isCalendarField) return baseDate.add(CalendarPeriod.of( (int) value, periodField)); // LOOK int vs double else return baseDate.add( value, periodField); }
java
{ "resource": "" }
q174427
UnitDimension.getQuantityDimension
test
public QuantityDimension getQuantityDimension() { Factor[] factors = getFactors(); for (int i = factors.length; --i >= 0; ) { Factor factor = factors[i]; factors[i] = new Factor( ((BaseUnit)factor.getBase()).getBaseQuantity(), factor.getExponent()); } return new QuantityDimension(factors); }
java
{ "resource": "" }
q174428
SigmetIOServiceProvider.isValidFile
test
public boolean isValidFile(ucar.unidata.io.RandomAccessFile raf) { try { raf.order(RandomAccessFile.LITTLE_ENDIAN); // The first struct in the file is the product_hdr, which will have the // standard structure_header, followed by other embedded structures. // Each of these structures also have a structure header. To validate // the file we check for a product_hdr (by looking for type 27 in the // structure_header), then a product_configuration structure (by looking // for type 26 in its structure_header), then checking that that // the product_configuration does indicate a type of RAW data (type 15) raf.seek(0); short[] data = new short[13]; raf.readShort(data, 0, 13); return (data[0] == (short) 27 && data[6] == (short) 26 && data[12] ==(short) 15); } catch (IOException ioe) { System.out.println("In isValidFile(): " + ioe.toString()); return false; } }
java
{ "resource": "" }
q174429
SigmetIOServiceProvider.readStnNames
test
public java.util.Map<String, String> readStnNames(ucar.unidata.io.RandomAccessFile raf) { java.util.Map<String, String> hdrNames = new java.util.HashMap<String, String>(); try { raf.seek(6288); String stnName = raf.readString(16); //System.out.println(" stnName="+stnName.trim()); raf.seek(6306); String stnName_util = raf.readString(16); hdrNames.put("StationName", stnName.trim()); hdrNames.put("StationName_SetupUtility", stnName_util.trim()); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } return hdrNames; }
java
{ "resource": "" }
q174430
SigmetIOServiceProvider.readData1
test
public Array readData1(ucar.nc2.Variable v2, Section section) throws IOException, InvalidRangeException { //doData(raf, ncfile, varList); int[] sh = section.getShape(); Array temp = Array.factory(v2.getDataType(), sh); long pos0 = 0; // Suppose that the data has LayoutRegular LayoutRegular index = new LayoutRegular(pos0, v2.getElementSize(), v2.getShape(), section); if (v2.getShortName().startsWith("time") | v2.getShortName().startsWith("numGates")) { temp = readIntData(index, v2); } else { temp = readFloatData(index, v2); } return temp; }
java
{ "resource": "" }
q174431
SigmetIOServiceProvider.readIntData
test
public Array readIntData(LayoutRegular index, Variable v2) throws IOException { int[] var = (int[]) (v2.read().get1DJavaArray(v2.getDataType())); int[] data = new int[(int) index.getTotalNelems()]; while (index.hasNext()) { Layout.Chunk chunk = index.next(); System.arraycopy(var, (int) chunk.getSrcPos() / 4, data, (int) chunk.getDestElem(), chunk.getNelems()); } return Array.factory(v2.getDataType(), new int[] {(int) index.getTotalNelems()}, data); }
java
{ "resource": "" }
q174432
SigmetIOServiceProvider.readToByteChannel11
test
public long readToByteChannel11(ucar.nc2.Variable v2, Section section, WritableByteChannel channel) throws java.io.IOException, ucar.ma2.InvalidRangeException { Array data = readData(v2, section); float[] ftdata = new float[(int) data.getSize()]; byte[] bytedata = new byte[(int) data.getSize() * 4]; IndexIterator iter = data.getIndexIterator(); int i = 0; ByteBuffer buffer = ByteBuffer.allocateDirect(bytedata.length); while (iter.hasNext()) { ftdata[i] = iter.getFloatNext(); bytedata[i] = new Float(ftdata[i]).byteValue(); buffer.put(bytedata[i]); i++; } buffer = ByteBuffer.wrap(bytedata); // write the bytes to the channel int count = channel.write(buffer); System.out.println("COUNT=" + count); // check if all bytes where written if (buffer.hasRemaining()) { // if not all bytes were written, move the unwritten bytes to the beginning and // set position just after the last unwritten byte buffer.compact(); } else { buffer.clear(); } return (long) count; }
java
{ "resource": "" }
q174433
SigmetIOServiceProvider.calcElev
test
static float calcElev(short angle) { final double maxval = 65536.0; double ang = (double) angle; if (angle < 0) ang = (~angle) + 1; double temp = (ang / maxval) * 360.0; BigDecimal bd = new BigDecimal(temp); BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN); return result.floatValue(); }
java
{ "resource": "" }
q174434
SigmetIOServiceProvider.calcStep
test
static float calcStep(float range_first, float range_last, short num_bins) { float step = (range_last - range_first) / (num_bins - 1); BigDecimal bd = new BigDecimal(step); BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN); return result.floatValue(); }
java
{ "resource": "" }
q174435
SigmetIOServiceProvider.calcAz
test
static float calcAz(short az0, short az1) { // output in deg float azim0 = calcAngle(az0); float azim1 = calcAngle(az1); float d = 0.0f; d = Math.abs(azim0 - azim1); if ((az0 < 0) & (az1 > 0)) { d = Math.abs(360.0f - azim0) + Math.abs(azim1); } double temp = azim0 + d * 0.5; if (temp > 360.0) { temp -= 360.0; } BigDecimal bd = new BigDecimal(temp); BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN); return result.floatValue(); }
java
{ "resource": "" }
q174436
SigmetIOServiceProvider.calcData
test
static float calcData(Map<String, Number> recHdr, short dty, byte data) { short[] coef = {1, 2, 3, 4}; // MultiPRF modes short multiprf = recHdr.get("multiprf").shortValue(); float vNyq = recHdr.get("vNyq").floatValue(); double temp = -999.99; switch (dty) { default: // dty=1,2 -total_power, reflectivity (dBZ) if (data != 0) { temp = (((int) data & 0xFF) - 64) * 0.5; } break; case 3: // dty=3 - mean velocity (m/sec) if (data != 0) { temp = ((((int) data & 0xFF) - 128) / 127.0) * vNyq * coef[multiprf]; } break; case 4: // dty=4 - spectrum width (m/sec) if (data != 0) { double v = ((((int) data & 0xFF) - 128) / 127.0) * vNyq * coef[multiprf]; temp = (((int) data & 0xFF) / 256.0) * v; } break; case 5: // dty=5 - differential reflectivity (dB) if (data != 0) { temp = ((((int) data & 0xFF) - 128) / 16.0); } break; } BigDecimal bd = new BigDecimal(temp); BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN); return result.floatValue(); }
java
{ "resource": "" }
q174437
SigmetIOServiceProvider.calcNyquist
test
static float calcNyquist(int prf, int wave) { double tmp = (prf * wave * 0.01) * 0.25; tmp = tmp * 0.01; //Make it m/sec BigDecimal bd = new BigDecimal(tmp); BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN); return result.floatValue(); }
java
{ "resource": "" }
q174438
VerticalCT.makeVerticalTransform
test
public VerticalTransform makeVerticalTransform(NetcdfDataset ds, Dimension timeDim) { return builder.makeMathTransform(ds, timeDim, this); }
java
{ "resource": "" }
q174439
GridServiceProvider.setDebugFlags
test
static public void setDebugFlags(ucar.nc2.util.DebugFlags debugFlag) { debugOpen = debugFlag.isSet("Grid/open"); debugMissing = debugFlag.isSet("Grid/missing"); debugMissingDetails = debugFlag.isSet("Grid/missingDetails"); debugProj = debugFlag.isSet("Grid/projection"); debugVert = debugFlag.isSet("Grid/vertical"); debugTiming = debugFlag.isSet("Grid/timing"); }
java
{ "resource": "" }
q174440
GridServiceProvider.setExtendIndex
test
static public void setExtendIndex(boolean b) { indexFileModeOnOpen = b ? IndexExtendMode.extendwrite : IndexExtendMode.readonly; indexFileModeOnSync = b ? IndexExtendMode.extendwrite : IndexExtendMode.readonly; }
java
{ "resource": "" }
q174441
GridServiceProvider.readXY
test
private void readXY(Variable v2, int ensIdx, int timeIdx, int levIdx, Range yRange, Range xRange, IndexIterator ii) throws IOException, InvalidRangeException { GridVariable pv = (GridVariable) v2.getSPobject(); GridHorizCoordSys hsys = pv.getHorizCoordSys(); int nx = hsys.getNx(); GridRecord record = pv.findRecord(ensIdx, timeIdx, levIdx); if (record == null) { Attribute att = v2.findAttribute("missing_value"); float missing_value = (att == null) ? -9999.0f : att.getNumericValue().floatValue(); int xyCount = yRange.length() * xRange.length(); for (int j = 0; j < xyCount; j++) { ii.setFloatNext(missing_value); } return; } // otherwise read it float[] data = _readData(record); if (data == null) { _readData(record); // debug return; } // LOOK can improve with System.copy ?? for (int y : yRange) { for (int x : xRange) { int index = y * nx + x; ii.setFloatNext(data[index]); } } }
java
{ "resource": "" }
q174442
GridServiceProvider.isMissingXY
test
public boolean isMissingXY(Variable v2, int timeIdx, int ensIdx, int levIdx) throws InvalidRangeException { GridVariable pv = (GridVariable) v2.getSPobject(); if ((timeIdx < 0) || (timeIdx >= pv.getNTimes())) { throw new InvalidRangeException("timeIdx=" + timeIdx); } if ((levIdx < 0) || (levIdx >= pv.getVertNlevels())) { throw new InvalidRangeException("levIdx=" + levIdx); } if ((ensIdx < 0) || (ensIdx >= pv.getNEnsembles())) { throw new InvalidRangeException("ensIdx=" + ensIdx); } return (null == pv.findRecord(ensIdx, timeIdx, levIdx)); }
java
{ "resource": "" }
q174443
DtCoverageCS.getLatLonBoundingBox
test
public LatLonRect getLatLonBoundingBox() { if (llbb == null) { if ((getXHorizAxis() instanceof CoordinateAxis2D) && (getYHorizAxis() instanceof CoordinateAxis2D)) { return null; } CoordinateAxis horizXaxis = getXHorizAxis(); CoordinateAxis horizYaxis = getYHorizAxis(); if (isLatLon()) { double startLat = horizYaxis.getMinValue(); double startLon = horizXaxis.getMinValue(); double deltaLat = horizYaxis.getMaxValue() - startLat; double deltaLon = horizXaxis.getMaxValue() - startLon; LatLonPoint llpt = new LatLonPointImpl(startLat, startLon); llbb = new LatLonRect(llpt, deltaLat, deltaLon); } else { ProjectionImpl dataProjection = getProjection(); ProjectionRect bb = getBoundingBox(); if (bb != null) llbb = dataProjection.projToLatLonBB(bb); } } return llbb; /* // look at all 4 corners of the bounding box LatLonPointImpl llpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getLowerLeftPoint(), new LatLonPointImpl()); LatLonPointImpl lrpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getLowerRightPoint(), new LatLonPointImpl()); LatLonPointImpl urpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getUpperRightPoint(), new LatLonPointImpl()); LatLonPointImpl ulpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getUpperLeftPoint(), new LatLonPointImpl()); // Check if grid contains poles. boolean includesNorthPole = false; int[] resultNP; resultNP = findXYindexFromLatLon(90.0, 0, null); if (resultNP[0] != -1 && resultNP[1] != -1) includesNorthPole = true; boolean includesSouthPole = false; int[] resultSP; resultSP = findXYindexFromLatLon(-90.0, 0, null); if (resultSP[0] != -1 && resultSP[1] != -1) includesSouthPole = true; if (includesNorthPole && !includesSouthPole) { llbb = new LatLonRect(llpt, new LatLonPointImpl(90.0, 0.0)); // ??? lon=??? llbb.extend(lrpt); llbb.extend(urpt); llbb.extend(ulpt); // OR //llbb.extend( new LatLonRect( llpt, lrpt )); //llbb.extend( new LatLonRect( lrpt, urpt ) ); //llbb.extend( new LatLonRect( urpt, ulpt ) ); //llbb.extend( new LatLonRect( ulpt, llpt ) ); } else if (includesSouthPole && !includesNorthPole) { llbb = new LatLonRect(llpt, new LatLonPointImpl(-90.0, -180.0)); // ??? lon=??? llbb.extend(lrpt); llbb.extend(urpt); llbb.extend(ulpt); } else { double latMin = Math.min(llpt.getLatitude(), lrpt.getLatitude()); double latMax = Math.max(ulpt.getLatitude(), urpt.getLatitude()); // longitude is a bit tricky as usual double lonMin = getMinOrMaxLon(llpt.getLongitude(), ulpt.getLongitude(), true); double lonMax = getMinOrMaxLon(lrpt.getLongitude(), urpt.getLongitude(), false); llpt.set(latMin, lonMin); urpt.set(latMax, lonMax); llbb = new LatLonRect(llpt, urpt); } } } */ }
java
{ "resource": "" }
q174444
ArraySequenceNested.finish
test
public void finish() { sequenceOffset = new int[nelems]; total = 0; for (int i=0; i<nelems; i++) { sequenceOffset[i] = total; total += sequenceLen[i]; } sdata = new StructureData[nelems]; for (int i=0; i<nelems; i++) sdata[i] = new StructureDataA( this, sequenceOffset[i]); // make the member arrays for (StructureMembers.Member m : members.getMembers()) { int[] mShape = m.getShape(); int[] shape = new int[mShape.length + 1]; shape[0] = total; System.arraycopy(mShape, 0, shape, 1, mShape.length); // LOOK not doing nested structures Array data = Array.factory(m.getDataType(), shape); m.setDataArray(data); } }
java
{ "resource": "" }
q174445
Format.tab
test
public static void tab(StringBuffer sbuff, int tabStop, boolean alwaysOne) { int len = sbuff.length(); if (tabStop > len) { sbuff.setLength(tabStop); for (int i = len; i < tabStop; i++) { sbuff.setCharAt(i, ' '); } } else if (alwaysOne) { sbuff.setLength(len + 1); sbuff.setCharAt(len, ' '); } }
java
{ "resource": "" }
q174446
Format.pad
test
public static String pad(String s, int width, boolean rightJustify) { if (s.length() >= width) { return s; } StringBuilder sbuff = new StringBuilder(width); int need = width - s.length(); sbuff.setLength(need); for (int i = 0; i < need; i++) { sbuff.setCharAt(i, ' '); } if (rightJustify) { sbuff.append(s); } else { sbuff.insert(0, s); } return sbuff.toString(); }
java
{ "resource": "" }
q174447
Format.i
test
public static String i(int v, int width) { return pad(Integer.toString(v), width, true); }
java
{ "resource": "" }
q174448
Format.l
test
public static String l(long v, int width) { return pad(Long.toString(v), width, true); }
java
{ "resource": "" }
q174449
Format.formatByteSize
test
public static String formatByteSize(double size) { String unit = null; if (size > 1.0e15) { unit = "Pbytes"; size *= 1.0e-15; } else if (size > 1.0e12) { unit = "Tbytes"; size *= 1.0e-12; } else if (size > 1.0e9) { unit = "Gbytes"; size *= 1.0e-9; } else if (size > 1.0e6) { unit = "Mbytes"; size *= 1.0e-6; } else if (size > 1.0e3) { unit = "Kbytes"; size *= 1.0e-3; } else { unit = "bytes"; } return Format.d(size, 4) + " " + unit; }
java
{ "resource": "" }
q174450
Format.show
test
private static void show(double d, int sigfig) { System.out.println("Format.d(" + d + "," + sigfig + ") == " + Format.d(d, sigfig)); }
java
{ "resource": "" }
q174451
Format.show2
test
private static void show2(double d, int dec_places) { System.out.println("Format.dfrac(" + d + "," + dec_places + ") == " + Format.dfrac(d, dec_places)); }
java
{ "resource": "" }
q174452
GridDatasetInfo.getShapeString
test
private String getShapeString(int[] shape) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < shape.length; i++) { if (i != 0) buf.append(" "); buf.append(shape[i]); } return buf.toString(); }
java
{ "resource": "" }
q174453
Slice.finish
test
public Slice finish() throws DapException { // Attempt to repair undefined values if(this.first == UNDEFINED) this.first = 0; // default if(this.stride == UNDEFINED) this.stride = 1; // default if(this.stop == UNDEFINED && this.maxsize != UNDEFINED) this.stop = this.maxsize; if(this.stop == UNDEFINED && this.maxsize == UNDEFINED) this.stop = this.first + 1; if(this.maxsize == UNDEFINED && this.stop != UNDEFINED) this.maxsize = this.stop; // else (this.stop != UNDEFINED && this.maxsize != UNDEFINED) assert (this.first != UNDEFINED); assert (this.stride != UNDEFINED); assert (this.stop != UNDEFINED); // sanity checks if(this.first > this.maxsize) throw new DapException("Slice: first index > max size"); if(this.stop > (this.maxsize+1)) throw new DapException("Slice: stop > max size"); if(this.first < 0) throw new DapException("Slice: first index < 0"); if(this.stop < 0) throw new DapException("Slice: stop index < 0"); if(this.stride <= 0) throw new DapException("Slice: stride index <= 0"); if(this.first > this.stop) throw new DapException("Slice: first index > last"); return this; // fluent interface }
java
{ "resource": "" }
q174454
Slice.toConstraintString
test
public String toConstraintString() throws DapException { assert this.first != UNDEFINED && this.stride != UNDEFINED && this.stop != UNDEFINED; if((this.stop - this.first) == 0) { return String.format("[0]"); } else if(this.stride == 1) { if((this.stop - this.first) == 1) return String.format("[%d]", this.first); else return String.format("[%d:%d]", this.first, this.stop - 1); } else return String.format("[%d:%d:%d]", this.first, this.stride, this.stop - 1); }
java
{ "resource": "" }
q174455
Slice.compose
test
static public Slice compose(Slice target, Slice src) throws DapException { long sr_stride = target.getStride() * src.getStride(); long sr_first = MAP(target, src.getFirst()); long lastx = MAP(target, src.getLast()); long sr_last = (target.getLast() < lastx ? target.getLast() : lastx); //min(last(),lastx) return new Slice(sr_first, sr_last + 1, sr_stride, sr_last + 1).finish(); }
java
{ "resource": "" }
q174456
Slice.MAP
test
static long MAP(Slice target, long i) throws DapException { if(i < 0) throw new DapException("Slice.compose: i must be >= 0"); if(i > target.getStop()) throw new DapException("i must be < stop"); return target.getFirst() + i * target.getStride(); }
java
{ "resource": "" }
q174457
DapDump.dumpbytes
test
static public void dumpbytes(ByteBuffer buf0, boolean skipdmr) { int savepos = buf0.position(); int limit0 = buf0.limit(); int skipcount = 0; if(limit0 > MAXLIMIT) limit0 = MAXLIMIT; if(limit0 >= buf0.limit()) limit0 = buf0.limit(); if(skipdmr) { ByteOrder saveorder = buf0.order(); buf0.order(ByteOrder.BIG_ENDIAN); // must read in network order skipcount = buf0.getInt(); //dmr count buf0.order(saveorder); skipcount &= 0xFFFFFF; // mask off the flags to get true count skipcount += 4; // skip the count also } byte[] bytes = new byte[(limit0 + 8) - skipcount]; Arrays.fill(bytes, (byte) 0); buf0.position(savepos + skipcount); buf0.get(bytes, 0, limit0 - skipcount); buf0.position(savepos); System.err.println("order="+buf0.order()); ByteBuffer buf = ByteBuffer.wrap(bytes).order(buf0.order()); dumpbytes(buf); }
java
{ "resource": "" }
q174458
DapDump.dumpbytes
test
static public void dumpbytes(ByteBuffer buf0) { int stop = buf0.limit(); int size = stop + 8; int savepos = buf0.position(); assert savepos == 0; byte[] bytes = new byte[size]; Arrays.fill(bytes, (byte) 0); buf0.get(bytes,0,stop); buf0.position(savepos); ByteBuffer buf = ByteBuffer.wrap(bytes).order(buf0.order()); buf.position(0); buf.limit(size); int i = 0; try { for(i = 0; buf.position() < stop; i++) { savepos = buf.position(); int iv = buf.getInt(); buf.position(savepos); long lv = buf.getLong(); buf.position(savepos); short sv = buf.getShort(); buf.position(savepos); byte b = buf.get(); int ub = ((int)b) & 0x000000FF; long uiv = ((long) iv) & 0xFFFFFFFFL; int usv = ((int) sv) & 0xFFFF; int ib = (int) b; char c = (char) ub; String s = Character.toString(c); if(c == '\r') s = "\\r"; else if(c == '\n') s = "\\n"; else if(c < ' ' || c >= 0x7f) s = "?"; System.err.printf("[%03d] %02x %03d %4d '%s'", i, ub, ub, ib, s); System.err.printf("\t%12d 0x%08x", iv, uiv); System.err.printf("\t%5d\t0x%04x", sv, usv); System.err.println(); System.err.flush(); } } catch (Exception e) { System.err.println("failure:" + e); } finally { System.err.flush(); //new Exception().printStackTrace(System.err); System.err.flush(); } }
java
{ "resource": "" }
q174459
EarthEllipsoid.getType
test
public static EarthEllipsoid getType(String name) { if (name == null) return null; return hash.get(name); }
java
{ "resource": "" }
q174460
EarthEllipsoid.getType
test
public static EarthEllipsoid getType(int epsgId) { Collection<EarthEllipsoid> all = getAll(); for (EarthEllipsoid ellipsoid : all) { if (ellipsoid.epsgId == epsgId) { return ellipsoid; } } return null; }
java
{ "resource": "" }
q174461
NcStreamDataCol.decodeVlenData
test
public Array decodeVlenData(NcStreamProto.DataCol dproto) throws IOException { DataType dataType = NcStream.convertDataType(dproto.getDataType()); ByteBuffer bb = dproto.getPrimdata().asReadOnlyByteBuffer(); ByteOrder bo = dproto.getBigend() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; bb.order(bo); Array alldata = Array.factory(dataType, new int[]{dproto.getNelems()}, bb); // flat array IndexIterator all = alldata.getIndexIterator(); Section section = NcStream.decodeSection(dproto.getSection()); Array[] data = new Array[(int) section.computeSize()]; // divide the primitive data into variable length arrays int count = 0; for (int len : dproto.getVlensList()) { Array primdata = Array.factory(dataType, new int[]{len}); IndexIterator prim = primdata.getIndexIterator(); for (int i=0; i<len; i++) { prim.setObjectNext( all.getObjectNext()); // generic } data[count++] = primdata; } // return Array.makeObjectArray(dataType, data[0].getClass(), section.getShape(), data); return Array.makeVlenArray(section.getShape(), data); }
java
{ "resource": "" }
q174462
NcStreamDataCol.decodeVlenData
test
private Array decodeVlenData(NcStreamProto.DataCol dproto, Section parentSection) throws IOException { DataType dataType = NcStream.convertDataType(dproto.getDataType()); ByteBuffer bb = dproto.getPrimdata().asReadOnlyByteBuffer(); ByteOrder bo = dproto.getBigend() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; bb.order(bo); Array alldata = Array.factory(dataType, new int[]{dproto.getNelems()}, bb); // 1D array IndexIterator all = alldata.getIndexIterator(); int psize = (int) parentSection.computeSize(); Section section = NcStream.decodeSection(dproto.getSection()); Section vsection = section.removeFirst(parentSection); int vsectionSize = (int) vsection.computeSize(); // the # of varlen Arrays at the inner structure // LOOK check for scalar // divide the primitive data into variable length arrays int countInner = 0; Array[] pdata = new Array[psize]; for (int pCount=0; pCount<psize; pCount++) { Array[] vdata = new Array[vsectionSize]; for (int vCount=0; vCount<vsectionSize; vCount++) { int vlen = dproto.getVlens(countInner++); Array primdata = Array.factory(dataType, new int[]{vlen}); IndexIterator prim = primdata.getIndexIterator(); for (int i = 0; i < vlen; i++) { prim.setObjectNext(all.getObjectNext()); // generic } vdata[vCount] = primdata; } pdata[pCount] = Array.makeVlenArray(vsection.getShape(), vdata); } // ArrayObject(parentShape) return Array.makeVlenArray(parentSection.getShape(), pdata); }
java
{ "resource": "" }
q174463
DodsURLExtractor.extract
test
public ArrayList extract(String url) throws IOException { if (debug) System.out.println(" URLextract=" + url); baseURL = new URL(url); InputStream in = baseURL.openStream(); InputStreamReader r = new InputStreamReader(filterTag(in), CDM.UTF8); HTMLEditorKit.ParserCallback callback = new CallerBacker(); urlList = new ArrayList(); wantURLS = true; wantText = false; parser.parse(r, callback, false); return urlList; }
java
{ "resource": "" }
q174464
DodsURLExtractor.getTextContent
test
public String getTextContent(String url) throws IOException { if (debug) System.out.println(" URL.getTextContent=" + url); baseURL = new URL(url); InputStream in = baseURL.openStream(); InputStreamReader r = new InputStreamReader(filterTag(in), CDM.UTF8); HTMLEditorKit.ParserCallback callback = new CallerBacker(); textBuffer = new StringBuffer(3000); wantURLS = false; wantText = true; parser.parse(r, callback, false); return textBuffer.toString(); }
java
{ "resource": "" }
q174465
DodsURLExtractor.filterTag
test
private InputStream filterTag(InputStream in) throws IOException { BufferedReader buffIn = new BufferedReader(new InputStreamReader(in, CDM.UTF8)); ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); String line = buffIn.readLine(); while (line != null) { String lline = line.toLowerCase(); if (lline.contains("<meta ")) // skip meta tags continue; //System.out.println("--"+line); bos.write(line.getBytes(CDM.utf8Charset)); line = buffIn.readLine(); } buffIn.close(); return new ByteArrayInputStream(bos.toByteArray()); }
java
{ "resource": "" }
q174466
AbstractIOServiceProvider.readToByteChannel
test
@Override public long readToByteChannel(ucar.nc2.Variable v2, Section section, WritableByteChannel channel) throws java.io.IOException, ucar.ma2.InvalidRangeException { Array data = readData(v2, section); return IospHelper.copyToByteChannel(data, channel); }
java
{ "resource": "" }
q174467
AttributeContainerHelper.addAll
test
@Override public void addAll(Iterable<Attribute> atts) { for (Attribute att : atts) addAttribute(att); }
java
{ "resource": "" }
q174468
AttributeContainerHelper.removeAttribute
test
@Override public boolean removeAttribute(String attName) { Attribute att = findAttribute(attName); return att != null && atts.remove(att); }
java
{ "resource": "" }
q174469
AttributeContainerHelper.removeAttributeIgnoreCase
test
@Override public boolean removeAttributeIgnoreCase(String attName) { Attribute att = findAttributeIgnoreCase(attName); return att != null && atts.remove(att); }
java
{ "resource": "" }
q174470
CoordinateRuntime.getOffsetsInTimeUnits
test
public List<Double> getOffsetsInTimeUnits() { double start = firstDate.getMillis(); List<Double> result = new ArrayList<>(runtimes.length); for (int idx=0; idx<runtimes.length; idx++) { double runtime = (double) getRuntime(idx); double msecs = (runtime - start); result.add(msecs / timeUnit.getValueInMillisecs()); } return result; }
java
{ "resource": "" }
q174471
ActionCoordinator.addActionSourceListener
test
public void addActionSourceListener( ActionSourceListener l) { if (!eventType.equals(l.getEventTypeName())) throw new IllegalArgumentException("ActionCoordinator: tried to add ActionSourceListener for wrong kind of Action "+ eventType+ " != "+ l.getEventTypeName()); lm.addListener(l); l.addActionValueListener(this); }
java
{ "resource": "" }
q174472
DateUnit.getStandardDate
test
static public Date getStandardDate(String text) { double value; String udunitString; text = text.trim(); StringTokenizer stoker = new StringTokenizer(text); String firstToke = stoker.nextToken(); try { value = Double.parseDouble(firstToke); udunitString = text.substring(firstToke.length()); } catch (NumberFormatException e) { // stupid way to test if it starts with a number value = 0.0; udunitString = text; } DateUnit du; try { du = new DateUnit(udunitString); } catch (Exception e) { return null; } return du.makeDate(value); }
java
{ "resource": "" }
q174473
DateUnit.getStandardOrISO
test
static public Date getStandardOrISO(String text) { Date result = getStandardDate(text); if (result == null) { DateFormatter formatter = new DateFormatter(); result = formatter.getISODate(text); } return result; }
java
{ "resource": "" }
q174474
DateUnit.getDateOrigin
test
public Date getDateOrigin() { if (!(uu instanceof TimeScaleUnit)) return null; TimeScaleUnit tu = (TimeScaleUnit) uu; return tu.getOrigin(); }
java
{ "resource": "" }
q174475
DateUnit.getDate
test
public Date getDate() { double secs = timeUnit.getValueInSeconds(value); return new Date(getDateOrigin().getTime() + (long) (1000 * secs)); }
java
{ "resource": "" }
q174476
DateUnit.makeDate
test
public Date makeDate(double val) { if (Double.isNaN(val)) return null; double secs = timeUnit.getValueInSeconds(val); // return new Date(getDateOrigin().getTime() + (long) (1000 * secs)); }
java
{ "resource": "" }
q174477
DateUnit.makeValue
test
public double makeValue(Date date) { double secs = date.getTime() / 1000.0; double origin_secs = getDateOrigin().getTime() / 1000.0; double diff = secs - origin_secs; try { timeUnit.setValueInSeconds(diff); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return timeUnit.getValue(); }
java
{ "resource": "" }
q174478
DateUnit.makeStandardDateString
test
public String makeStandardDateString(double value) { Date date = makeDate(value); if (date == null) return null; DateFormatter formatter = new DateFormatter(); return formatter.toDateTimeStringISO(date); }
java
{ "resource": "" }
q174479
GridHorizCoordSys.getGridSpacingInKm
test
private double getGridSpacingInKm(String type) { double value = gds.getDouble(type); if (Double.isNaN(value)) return value; String gridUnit = gds.getParam(GridDefRecord.GRID_UNITS); SimpleUnit unit; if (gridUnit == null || gridUnit.length() == 0) { unit = SimpleUnit.meterUnit; } else { unit = SimpleUnit.factory(gridUnit); } if (unit != null && SimpleUnit.isCompatible(unit.getUnitString(), "km")) { value = unit.convertTo(value, SimpleUnit.kmUnit); } return value; }
java
{ "resource": "" }
q174480
GridHorizCoordSys.addDimensionsToNetcdfFile
test
void addDimensionsToNetcdfFile(NetcdfFile ncfile) { if (isLatLon) { ncfile.addDimension(g, new Dimension("lat", gds.getInt(GridDefRecord.NY), true)); ncfile.addDimension(g, new Dimension("lon", gds.getInt(GridDefRecord.NX), true)); } else { ncfile.addDimension(g, new Dimension("y", gds.getInt(GridDefRecord.NY), true)); ncfile.addDimension(g, new Dimension("x", gds.getInt(GridDefRecord.NX), true)); } }
java
{ "resource": "" }
q174481
GridHorizCoordSys.addCoordAxis
test
private double[] addCoordAxis(NetcdfFile ncfile, String name, int n, double start, double incr, String units, String desc, String standard_name, AxisType axis) { // ncfile.addDimension(g, new Dimension(name, n, true)); Variable v = new Variable(ncfile, g, null, name); v.setDataType(DataType.DOUBLE); v.setDimensions(name); // create the data double[] data = new double[n]; for (int i = 0; i < n; i++) { data[i] = start + incr * i; } Array dataArray = Array.factory(DataType.DOUBLE, new int[]{n}, data); v.setCachedData(dataArray, false); v.addAttribute(new Attribute("units", units)); v.addAttribute(new Attribute("long_name", desc)); v.addAttribute(new Attribute("standard_name", standard_name)); v.addAttribute(new Attribute("grid_spacing", incr + " " + units)); v.addAttribute(new Attribute(_Coordinate.AxisType, axis.toString())); ncfile.addVariable(g, v); return data; }
java
{ "resource": "" }
q174482
GridHorizCoordSys.makeProjection
test
private boolean makeProjection(NetcdfFile ncfile, int projType) { switch (projType) { case GridTableLookup.RotatedLatLon: makeRotatedLatLon(ncfile); break; case GridTableLookup.PolarStereographic: makePS(); break; case GridTableLookup.LambertConformal: makeLC(); break; case GridTableLookup.Mercator: makeMercator(); break; case GridTableLookup.Orthographic: //makeSpaceViewOrOthographic(); makeMSGgeostationary(); break; case GridTableLookup.Curvilinear: makeCurvilinearAxis( ncfile); break; default: throw new UnsupportedOperationException("unknown projection = " + gds.getInt(GridDefRecord.GRID_TYPE)); } // dummy coordsys variable Variable v = new Variable(ncfile, g, null, grid_name); v.setDataType(DataType.CHAR); v.setDimensions(""); // scalar char[] data = new char[]{'d'}; Array dataArray = Array.factory(DataType.CHAR, new int[0], data); v.setCachedData(dataArray, false); for (Attribute att : attributes) v.addAttribute(att); // add CF Conventions attributes v.addAttribute(new Attribute(GridCF.EARTH_SHAPE, shape_name)); // LOOK - spherical earth ?? double radius_spherical_earth = gds.getDouble(GridDefRecord.RADIUS_SPHERICAL_EARTH); // have to check both because Grib1 and Grib2 used different names if (Double.isNaN(radius_spherical_earth)) radius_spherical_earth = gds.getDouble("radius_spherical_earth"); if( ! Double.isNaN(radius_spherical_earth) ) { //inconsistent - sometimes in km, sometimes in m. if (radius_spherical_earth < 10000.00) // then its in km radius_spherical_earth *= 1000.0; // convert to meters v.addAttribute(new Attribute(GridCF.EARTH_RADIUS, radius_spherical_earth)); //this attribute needs to be meters } else { // oblate earth double major_axis = gds.getDouble( GridDefRecord.MAJOR_AXIS_EARTH ); if (Double.isNaN( major_axis )) major_axis = gds.getDouble("major_axis_earth"); double minor_axis = gds.getDouble( GridDefRecord.MINOR_AXIS_EARTH ); if (Double.isNaN(minor_axis)) minor_axis = gds.getDouble("minor_axis_earth"); if ( ! Double.isNaN ( major_axis ) && ! Double.isNaN ( minor_axis )) { v.addAttribute(new Attribute(GridCF.SEMI_MAJOR_AXIS, major_axis)); v.addAttribute(new Attribute(GridCF.SEMI_MINOR_AXIS, minor_axis)); } } addGDSparams(v); ncfile.addVariable(g, v); return true; }
java
{ "resource": "" }
q174483
GridHorizCoordSys.addGDSparams
test
private void addGDSparams(Variable v) { // add all the gds parameters List<String> keyList = new ArrayList<>(gds.getKeys()); Collections.sort(keyList); String pre = getGDSprefix(); for (String key : keyList) { String name = pre + "_param_" + key; String vals = gds.getParam(key); try { int vali = Integer.parseInt(vals); if (key.equals(GridDefRecord.VECTOR_COMPONENT_FLAG)) { String cf = GridCF.VectorComponentFlag.of(vali); v.addAttribute(new Attribute(name, cf)); } else { v.addAttribute(new Attribute(name, vali)); } } catch (Exception e) { try { double vald = Double.parseDouble(vals); v.addAttribute(new Attribute(name, vald)); } catch (Exception e2) { v.addAttribute(new Attribute(name, vals)); } } } }
java
{ "resource": "" }
q174484
GridHorizCoordSys.addCoordSystemVariable
test
private void addCoordSystemVariable(NetcdfFile ncfile, String name, String dims) { Variable v = new Variable(ncfile, g, null, name); v.setDataType(DataType.CHAR); v.setDimensions(""); // scalar Array dataArray = Array.factory(DataType.CHAR, new int[0], new char[]{'0'}); v.setCachedData(dataArray, false); v.addAttribute(new Attribute(_Coordinate.Axes, dims)); if (isLatLon()) v.addAttribute(new Attribute(_Coordinate.Transforms, "")); // to make sure its identified as a Coordinate System Variable else v.addAttribute(new Attribute(_Coordinate.Transforms, getGridName())); addGDSparams(v); ncfile.addVariable(g, v); }
java
{ "resource": "" }
q174485
GridHorizCoordSys.makeLC
test
private void makeLC() { // we have to project in order to find the origin proj = new LambertConformal( gds.getDouble(GridDefRecord.LATIN1), gds.getDouble(GridDefRecord.LOV), gds.getDouble(GridDefRecord.LATIN1), gds.getDouble(GridDefRecord.LATIN2)); LatLonPointImpl startLL = new LatLonPointImpl(gds.getDouble(GridDefRecord.LA1), gds.getDouble(GridDefRecord.LO1)); ProjectionPointImpl start = (ProjectionPointImpl) proj.latLonToProj(startLL); startx = start.getX(); starty = start.getY(); if (Double.isNaN(getDxInKm())) { setDxDy(startx, starty, proj); } if (GridServiceProvider.debugProj) { System.out.println("GridHorizCoordSys.makeLC start at latlon " + startLL); double Lo2 = gds.getDouble(GridDefRecord.LO2); double La2 = gds.getDouble(GridDefRecord.LA2); LatLonPointImpl endLL = new LatLonPointImpl(La2, Lo2); System.out.println("GridHorizCoordSys.makeLC end at latlon " + endLL); ProjectionPointImpl endPP = (ProjectionPointImpl) proj.latLonToProj(endLL); System.out.println(" end at proj coord " + endPP); double endx = startx + getNx() * getDxInKm(); double endy = starty + getNy() * getDyInKm(); System.out.println(" should be x=" + endx + " y=" + endy); } attributes.add(new Attribute(GridCF.GRID_MAPPING_NAME, "lambert_conformal_conic")); if (gds.getDouble(GridDefRecord.LATIN1) == gds.getDouble(GridDefRecord.LATIN2)) { attributes.add(new Attribute(GridCF.STANDARD_PARALLEL, gds.getDouble(GridDefRecord.LATIN1))); } else { double[] data = new double[]{gds.getDouble(GridDefRecord.LATIN1), gds.getDouble(GridDefRecord.LATIN2)}; attributes.add(new Attribute(GridCF.STANDARD_PARALLEL, Array.factory(DataType.DOUBLE, new int[]{2}, data))); } //attributes.add(new Attribute("longitude_of_central_meridian", attributes.add(new Attribute(GridCF.LONGITUDE_OF_CENTRAL_MERIDIAN, gds.getDouble(GridDefRecord.LOV))); //attributes.add(new Attribute("latitude_of_projection_origin", attributes.add(new Attribute(GridCF.LATITUDE_OF_PROJECTION_ORIGIN, gds.getDouble(GridDefRecord.LATIN1))); }
java
{ "resource": "" }
q174486
GridHorizCoordSys.makePS
test
private void makePS() { String nproj = gds.getParam(GridDefRecord.NPPROJ); double latOrigin = (nproj == null || nproj.equalsIgnoreCase("true")) ? 90.0 : -90.0; // Why the scale factor?. according to GRIB docs: // "Grid lengths are in units of meters, at the 60 degree latitude circle nearest to the pole" // since the scale factor at 60 degrees = k = 2*k0/(1+sin(60)) [Snyder,Working Manual p157] // then to make scale = 1 at 60 degrees, k0 = (1+sin(60))/2 = .933 double scale; double lad = gds.getDouble(GridDefRecord.LAD); if (Double.isNaN(lad)) { scale = .933; } else { scale = (1.0+Math.sin( Math.toRadians( Math.abs(lad)) ))/2; } proj = new Stereographic(latOrigin, gds.getDouble(GridDefRecord.LOV), scale); // we have to project in order to find the origin ProjectionPointImpl start = (ProjectionPointImpl) proj.latLonToProj( new LatLonPointImpl( gds.getDouble(GridDefRecord.LA1), gds.getDouble(GridDefRecord.LO1))); startx = start.getX(); starty = start.getY(); if (Double.isNaN(getDxInKm())) setDxDy(startx, starty, proj); if (GridServiceProvider.debugProj) { System.out.printf("starting proj coord %s lat/lon %s%n", start, proj.projToLatLon(start)); System.out.println(" should be LA1=" + gds.getDouble(GridDefRecord.LA1) + " l)1=" + gds.getDouble(GridDefRecord.LO1)); } attributes.add(new Attribute(GridCF.GRID_MAPPING_NAME, "polar_stereographic")); //attributes.add(new Attribute("longitude_of_projection_origin", attributes.add(new Attribute(GridCF.LONGITUDE_OF_PROJECTION_ORIGIN, gds.getDouble(GridDefRecord.LOV))); //attributes.add(new Attribute("straight_vertical_longitude_from_pole", attributes.add(new Attribute( GridCF.STRAIGHT_VERTICAL_LONGITUDE_FROM_POLE, gds.getDouble(GridDefRecord.LOV))); //attributes.add(new Attribute("scale_factor_at_projection_origin", attributes.add(new Attribute(GridCF.SCALE_FACTOR_AT_PROJECTION_ORIGIN, scale)); attributes.add(new Attribute(GridCF.LATITUDE_OF_PROJECTION_ORIGIN, latOrigin)); }
java
{ "resource": "" }
q174487
GridHorizCoordSys.makeMercator
test
private void makeMercator() { /** * Construct a Mercator Projection. * @param lon0 longitude of origin (degrees) * @param par standard parallel (degrees). cylinder cuts earth at this latitude. */ double Latin = gds.getDouble(GridDefRecord.LAD); // name depends on Grib version 1 or 2 if (Double.isNaN(Latin)) Latin = gds.getDouble(GridDefRecord.LATIN); double Lo1 = gds.getDouble(GridDefRecord.LO1); //gds.Lo1; double La1 = gds.getDouble(GridDefRecord.LA1); //gds.La1; // put longitude origin at first point - doesnt actually matter proj = new Mercator(Lo1, Latin); // find out where ProjectionPoint startP = proj.latLonToProj( new LatLonPointImpl(La1, Lo1)); startx = startP.getX(); starty = startP.getY(); if (Double.isNaN(getDxInKm())) { setDxDy(startx, starty, proj); } attributes.add(new Attribute(GridCF.GRID_MAPPING_NAME, "mercator")); attributes.add(new Attribute(GridCF.STANDARD_PARALLEL, Latin)); attributes.add(new Attribute(GridCF.LONGITUDE_OF_PROJECTION_ORIGIN, Lo1)); if (GridServiceProvider.debugProj) { double Lo2 = gds.getDouble(GridDefRecord.LO2); if (Lo2 < Lo1) Lo2 += 360; double La2 = gds.getDouble(GridDefRecord.LA2); LatLonPointImpl endLL = new LatLonPointImpl(La2, Lo2); System.out.println("GridHorizCoordSys.makeMercator: end at latlon= " + endLL); ProjectionPointImpl endPP = (ProjectionPointImpl) proj.latLonToProj(endLL); System.out.println(" start at proj coord " + new ProjectionPointImpl(startx, starty)); System.out.println(" end at proj coord " + endPP); double endx = startx + (getNx() - 1) * getDxInKm(); double endy = starty + (getNy() - 1) * getDyInKm(); System.out.println(" should be x=" + endx + " y=" + endy); } }
java
{ "resource": "" }
q174488
GridHorizCoordSys.makeMSGgeostationary
test
private void makeMSGgeostationary() { double Lat0 = gds.getDouble(GridDefRecord.LAP); // sub-satellite point lat double Lon0 = gds.getDouble(GridDefRecord.LOP); // sub-satellite point lon //int nx = gds.getInt(GridDefRecord.NX); int ny = gds.getInt(GridDefRecord.NY); int x_off = gds.getInt(GridDefRecord.XP); // sub-satellite point in grid lengths int y_off = gds.getInt(GridDefRecord.YP); double dx; // = gds.getDouble(GridDefRecord.DX); // apparent diameter of earth in units of grid lengths double dy = gds.getDouble(GridDefRecord.DY); // per Simon Eliot 1/18/2010, there is a bug in Eumetsat grib files, // we need to "correct for ellipsoidal earth" // (Note we should check who the originating center is // "Originating_center" = "EUMETSAT Operation Centre" in the GRIB id (section 1)) // although AFAIK, eumetsat is only one using this projection. if (dy < 2100) { dx = 1207; dy = 1203; } else { dx = 3622; dy = 3610; } // have to check both names because Grib1 and Grib2 used different names double major_axis = gds.getDouble(GridDefRecord.MAJOR_AXIS_EARTH); // m if (Double.isNaN(major_axis)) major_axis = gds.getDouble("major_axis_earth"); double minor_axis = gds.getDouble(GridDefRecord.MINOR_AXIS_EARTH); // m if (Double.isNaN(minor_axis)) minor_axis = gds.getDouble("minor_axis_earth"); // Nr = altitude of camera from center, in units of radius double nr = gds.getDouble(GridDefRecord.NR) * 1e-6; // altitude of the camera from the Earths centre, measured in units of the Earth (equatorial) radius // CFAC = 2^16 / {[2 * arcsine (10^6 / Nr)] / dx } double as = 2 * Math.asin(1.0/nr); double cfac = dx / as; double lfac = dy / as; // use km, so scale by the earth radius double scale_factor = (nr - 1) * major_axis / 1000; // this sets the units of the projection x,y coords in km double scale_x = scale_factor; // LOOK fake neg need scan value double scale_y = -scale_factor; // LOOK fake neg need scan value startx = scale_factor * (1 - x_off) / cfac; starty = scale_factor * (y_off - ny) / lfac; incrx = scale_factor/cfac; incry = scale_factor/lfac; attributes.add(new Attribute(GridCF.GRID_MAPPING_NAME, "MSGnavigation")); attributes.add(new Attribute(GridCF.LONGITUDE_OF_PROJECTION_ORIGIN, Lon0)); attributes.add(new Attribute(GridCF.LATITUDE_OF_PROJECTION_ORIGIN, Lat0)); //attributes.add(new Attribute("semi_major_axis", new Double(major_axis))); //attributes.add(new Attribute("semi_minor_axis", new Double(minor_axis))); attributes.add(new Attribute("height_from_earth_center", nr * major_axis)); attributes.add(new Attribute("scale_x", scale_x)); attributes.add(new Attribute("scale_y", scale_y)); proj = new MSGnavigation(Lat0, Lon0, major_axis, minor_axis, nr * major_axis, scale_x, scale_y); if (GridServiceProvider.debugProj) { double Lo2 = gds.getDouble(GridDefRecord.LO2) + 360.0; double La2 = gds.getDouble(GridDefRecord.LA2); LatLonPointImpl endLL = new LatLonPointImpl(La2, Lo2); System.out.println("GridHorizCoordSys.makeMSGgeostationary end at latlon " + endLL); ProjectionPointImpl endPP =(ProjectionPointImpl) proj.latLonToProj(endLL); System.out.println(" end at proj coord " + endPP); double endx = 1 + getNx(); double endy = 1 + getNy(); System.out.println(" should be x=" + endx + " y=" + endy); } }
java
{ "resource": "" }
q174489
GridHorizCoordSys.setDxDy
test
private void setDxDy(double startx, double starty, ProjectionImpl proj) { double Lo2 = gds.getDouble(GridDefRecord.LO2); double La2 = gds.getDouble(GridDefRecord.LA2); if (Double.isNaN(Lo2) || Double.isNaN(La2)) { return; } LatLonPointImpl endLL = new LatLonPointImpl(La2, Lo2); ProjectionPointImpl end = (ProjectionPointImpl) proj.latLonToProj(endLL); double dx = Math.abs(end.getX() - startx) / (gds.getInt(GridDefRecord.NX) - 1); double dy = Math.abs(end.getY() - starty) / (gds.getInt(GridDefRecord.NY) - 1); gds.addParam(GridDefRecord.DX, String.valueOf(dx)); gds.addParam(GridDefRecord.DY, String.valueOf(dy)); gds.addParam(GridDefRecord.GRID_UNITS, "km"); }
java
{ "resource": "" }
q174490
InvCatalogFactory10.readDataset
test
protected InvDatasetImpl readDataset(InvCatalogImpl catalog, InvDatasetImpl parent, Element dsElem, URI base) { // deal with aliases String name = dsElem.getAttributeValue("name"); String alias = dsElem.getAttributeValue("alias"); if (alias != null) { InvDatasetImpl ds = (InvDatasetImpl) catalog.findDatasetByID(alias); if (ds == null) { factory.appendErr(" ** Parse error: dataset named " + name + " has illegal alias = " + alias + "\n"); return null; } return new InvDatasetImplProxy(name, ds); } InvDatasetImpl dataset = new InvDatasetImpl(parent, name); readDatasetInfo(catalog, dataset, dsElem, base); if (InvCatalogFactory.debugXML) System.out.println(" Dataset added: " + dataset.dump()); return dataset; }
java
{ "resource": "" }
q174491
InvCatalogFactory10.readDatasetScan
test
protected InvDatasetScan readDatasetScan(InvCatalogImpl catalog, InvDatasetImpl parent, Element dsElem, URI base) { InvDatasetScan datasetScan; if (dsElem.getAttributeValue("dirLocation") == null) { if (dsElem.getAttributeValue("location") == null) { logger.error("readDatasetScan(): datasetScan has neither a \"location\" nor a \"dirLocation\" attribute."); datasetScan = null; } else { return readDatasetScanNew(catalog, parent, dsElem, base); } } else { String name = dsElem.getAttributeValue("name"); factory.appendWarning("**Warning: Dataset " + name + " using old form of DatasetScan (dirLocation instead of location)\n"); String path = dsElem.getAttributeValue("path"); String scanDir = expandAliasForPath(dsElem.getAttributeValue("dirLocation")); String filter = dsElem.getAttributeValue("filter"); String addDatasetSizeString = dsElem.getAttributeValue("addDatasetSize"); String addLatest = dsElem.getAttributeValue("addLatest"); String sortOrderIncreasingString = dsElem.getAttributeValue("sortOrderIncreasing"); boolean sortOrderIncreasing = false; if (sortOrderIncreasingString != null) if (sortOrderIncreasingString.equalsIgnoreCase("true")) sortOrderIncreasing = true; boolean addDatasetSize = true; if (addDatasetSizeString != null) if (addDatasetSizeString.equalsIgnoreCase("false")) addDatasetSize = false; if (path != null) { if (path.charAt(0) == '/') path = path.substring(1); int last = path.length() - 1; if (path.charAt(last) == '/') path = path.substring(0, last); } if (scanDir != null) { int last = scanDir.length() - 1; if (scanDir.charAt(last) != '/') scanDir = scanDir + '/'; } Element atcElem = dsElem.getChild("addTimeCoverage", defNS); String dsNameMatchPattern = null; String startTimeSubstitutionPattern = null; String duration = null; if (atcElem != null) { dsNameMatchPattern = atcElem.getAttributeValue("datasetNameMatchPattern"); startTimeSubstitutionPattern = atcElem.getAttributeValue("startTimeSubstitutionPattern"); duration = atcElem.getAttributeValue("duration"); } try { datasetScan = new InvDatasetScan(catalog, parent, name, path, scanDir, filter, addDatasetSize, addLatest, sortOrderIncreasing, dsNameMatchPattern, startTimeSubstitutionPattern, duration); readDatasetInfo(catalog, datasetScan, dsElem, base); if (InvCatalogFactory.debugXML) System.out.println(" Dataset added: " + datasetScan.dump()); } catch (Exception e) { logger.error("Reading DatasetScan", e); datasetScan = null; } } return datasetScan; }
java
{ "resource": "" }
q174492
InvCatalogFactory10.readMetadataContentFromURL
test
public Object readMetadataContentFromURL(InvDataset dataset, java.net.URI uri) throws java.io.IOException { Element elem = readContentFromURL(uri); Object contentObject = readMetadataContent(dataset, elem); if (debugMetadataRead) System.out.println(" convert to " + contentObject.getClass().getName()); return contentObject; }
java
{ "resource": "" }
q174493
McIDASGridRecord.getLevelType1
test
public int getLevelType1() { // TODO: flush this out int gribLevel = getDirBlock()[51]; int levelType = 0; if (!((gribLevel == McIDASUtil.MCMISSING) || (gribLevel == 0))) { levelType = gribLevel; } else { levelType = 1; } return levelType; }
java
{ "resource": "" }
q174494
Nldn.isValidFile
test
public boolean isValidFile(RandomAccessFile raf) throws IOException { raf.seek(0); String test = raf.readString(MAGIC.length()); return test.equals(MAGIC); }
java
{ "resource": "" }
q174495
DummySink.write
test
public void write(byte[] b, int off, int len) throws IOException { count += len; super.write(b, off, len); }
java
{ "resource": "" }
q174496
BaseType.setClearName
test
@Override public void setClearName(String clearname) { super.setClearName(clearname); if(_attr != null) _attr.setClearName(clearname); if(_attrTbl != null) _attrTbl.setClearName(clearname); }
java
{ "resource": "" }
q174497
UnidataPointDatasetHelper.getCoordinateName
test
static public String getCoordinateName(NetcdfDataset ds, AxisType a) { List<Variable> varList = ds.getVariables(); for (Variable v : varList) { if (v instanceof Structure) { List<Variable> vars = ((Structure) v).getVariables(); for (Variable vs : vars) { String axisType = ds.findAttValueIgnoreCase(vs, _Coordinate.AxisType, null); if ((axisType != null) && axisType.equals(a.toString())) return vs.getShortName(); } } else { String axisType = ds.findAttValueIgnoreCase(v, _Coordinate.AxisType, null); if ((axisType != null) && axisType.equals(a.toString())) return v.getShortName(); } } if (a == AxisType.Lat) return findVariableName( ds, "latitude"); if (a == AxisType.Lon) return findVariableName( ds, "longitude"); if (a == AxisType.Time) return findVariableName( ds, "time"); if (a == AxisType.Height) { Variable v = findVariable( ds, "altitude"); if (null == v) v = findVariable( ds, "depth"); if (v != null) return v.getShortName(); } // I think the CF part is done by the CoordSysBuilder adding the _CoordinateAxisType attrinutes. return null; }
java
{ "resource": "" }
q174498
UnidataPointDatasetHelper.getCoordinateName
test
static public String getCoordinateName(NetcdfDataset ds, AxisType a, Dimension dim) { String name = getCoordinateName(ds, a); if (name == null) return null; Variable v = ds.findVariable(name); if (v == null) return null; if (v.isScalar()) return null; if (!v.getDimension(0).equals(dim)) return null; return name; }
java
{ "resource": "" }
q174499
ErrorResponse.buildXML
test
public String buildXML() { StringBuilder response = new StringBuilder(); response.append("<Error"); if(code > 0) response.append(String.format(" httpcode=\"%d\"", code)); response.append(">\n"); if(message != null) response.append("<Message>" + getMessage() + "</Message>\n"); if(context != null) response.append("<Context>" + getContext() + "</Context>\n"); if(otherinfo != null) response.append("<OtherInformation>" + getOtherInfo() + "</OtherInformation>\n"); return response.toString(); }
java
{ "resource": "" }