_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q174900
SI.du
test
private static Unit du(final String name, final String symbol, final Unit definition) throws NameException { return definition.clone(UnitName.newUnitName(name, null, symbol)); }
java
{ "resource": "" }
q174901
SI.baseUnitDB
test
private static UnitDBImpl baseUnitDB() throws NameException, UnitExistsException, NoSuchUnitException { final UnitDBImpl db = new UnitDBImpl(9, 9); db.addUnit(AMPERE); db.addUnit(CANDELA); db.addUnit(KELVIN); db.addUnit(KILOGRAM); db.addUnit(METER); db.addUnit(MOLE); db.addUnit(SECOND); db.addUnit(RADIAN); db.addUnit(STERADIAN); db.addAlias("metre", "meter"); return db; }
java
{ "resource": "" }
q174902
SI.derivedUnitDB
test
private static UnitDBImpl derivedUnitDB() throws NameException, UnitExistsException, NoSuchUnitException { final UnitDBImpl db = new UnitDBImpl(42, 43); db.addUnit(HERTZ); db.addUnit(NEWTON); db.addUnit(PASCAL); db.addUnit(JOULE); db.addUnit(WATT); db.addUnit(COULOMB); db.addUnit(VOLT); db.addUnit(FARAD); db.addUnit(OHM); db.addUnit(SIEMENS); db.addUnit(WEBER); db.addUnit(TESLA); db.addUnit(HENRY); db.addUnit(DEGREE_CELSIUS); db.addUnit(LUMEN); db.addUnit(LUX); db.addUnit(BECQUEREL); db.addUnit(GRAY); db.addUnit(SIEVERT); db.addUnit(MINUTE); db.addUnit(HOUR); db.addUnit(DAY); db.addUnit(ARC_DEGREE); db.addUnit(ARC_MINUTE); db.addUnit(ARC_SECOND); db.addUnit(LITER); db.addUnit(METRIC_TON); db.addUnit(NAUTICAL_MILE); db.addUnit(KNOT); db.addUnit(ANGSTROM); db.addUnit(ARE); db.addUnit(HECTARE); db.addUnit(BARN); db.addUnit(BAR); db.addUnit(GAL); db.addUnit(CURIE); db.addUnit(ROENTGEN); db.addUnit(RAD); db.addUnit(REM); db.addAlias("litre", "liter", "l"); db.addAlias("tonne", "metric ton"); db.addSymbol("tne", "tonne"); return db; }
java
{ "resource": "" }
q174903
SI.instance
test
public static synchronized SI instance() throws UnitSystemException { if (si == null) { try { si = new SI(); } catch (final UnitException e) { throw new UnitSystemException("Couldn't initialize class SI", e); } } return si; }
java
{ "resource": "" }
q174904
CoordAxisHelper.findCoordElement
test
int findCoordElement(double[] target, boolean bounded) { switch (axis.getSpacing()) { case regularInterval: // can use midpoint return findCoordElementRegular((target[0]+target[1])/2, bounded); case contiguousInterval: // can use midpoint return findCoordElementContiguous((target[0]+target[1])/2, bounded); case discontiguousInterval: // cant use midpoint return findCoordElementDiscontiguousInterval(target, bounded); } throw new IllegalStateException("unknown spacing" + axis.getSpacing()); }
java
{ "resource": "" }
q174905
CoordAxisHelper.findClosest
test
private int findClosest(double target) { double minDiff = Double.MAX_VALUE; double useValue = Double.MIN_VALUE; int idxFound = -1; for (int i = 0; i < axis.getNcoords(); i++) { double coord = axis.getCoordMidpoint(i); double diff = Math.abs(coord - target); if (diff < minDiff || (diff == minDiff && coord > useValue)) { minDiff = diff; idxFound = i; useValue = coord; } } return idxFound; }
java
{ "resource": "" }
q174906
CoordAxisHelper.subsetValues
test
private Optional<CoverageCoordAxisBuilder> subsetValues(double minValue, double maxValue, int stride) { if (axis.getSpacing() == CoverageCoordAxis.Spacing.discontiguousInterval) return subsetValuesDiscontinuous(minValue, maxValue, stride); double lower = axis.isAscending() ? Math.min(minValue, maxValue) : Math.max(minValue, maxValue); double upper = axis.isAscending() ? Math.max(minValue, maxValue) : Math.min(minValue, maxValue); int minIndex = findCoordElement(lower, false); int maxIndex = findCoordElement(upper, false); if (minIndex >= axis.getNcoords()) return Optional.empty(String.format("no points in subset: lower %f > end %f", lower, axis.getEndValue())); if (maxIndex < 0) return Optional.empty(String.format("no points in subset: upper %f < start %f", upper, axis.getStartValue())); if (minIndex < 0) minIndex = 0; if (maxIndex >= axis.getNcoords()) maxIndex = axis.getNcoords() - 1; int count = maxIndex - minIndex + 1; if (count <= 0) throw new IllegalArgumentException("no points in subset"); try { return Optional.of(subsetByIndex(new Range(minIndex, maxIndex, stride))); } catch (InvalidRangeException e) { return Optional.empty(e.getMessage()); } }
java
{ "resource": "" }
q174907
DataFactory.openFeatureDataset
test
@Nonnull public DataFactory.Result openFeatureDataset(Dataset Dataset, ucar.nc2.util.CancelTask task) throws IOException { return openFeatureDataset(null, Dataset, task, new Result()); }
java
{ "resource": "" }
q174908
DataFactory.openFeatureDataset
test
public DataFactory.Result openFeatureDataset(Access access, ucar.nc2.util.CancelTask task) throws IOException { Dataset ds = access.getDataset(); DataFactory.Result result = new Result(); if (ds.getFeatureType() == null) { result.errLog.format("InvDatasert must specify a FeatureType%n"); result.fatalError = true; return result; } return openFeatureDataset(ds.getFeatureType(), access, task, result); }
java
{ "resource": "" }
q174909
DataFactory.annotate
test
public static void annotate(Dataset ds, NetcdfDataset ncDataset) { ncDataset.setTitle(ds.getName()); ncDataset.setId(ds.getId()); // add properties as global attributes for (Property p : ds.getProperties()) { String name = p.getName(); if (null == ncDataset.findGlobalAttribute(name)) { ncDataset.addAttribute(null, new Attribute(name, p.getValue())); } } /* ThreddsMetadata.GeospatialCoverage geoCoverage = ds.getGeospatialCoverage(); if (geoCoverage != null) { if ( null != geoCoverage.getNorthSouthRange()) { ncDataset.addAttribute(null, new Attribute("geospatial_lat_min", new Double(geoCoverage.getLatSouth()))); ncDataset.addAttribute(null, new Attribute("geospatial_lat_max", new Double(geoCoverage.getLatNorth()))); } if ( null != geoCoverage.getEastWestRange()) { ncDataset.addAttribute(null, new Attribute("geospatial_lon_min", new Double(geoCoverage.getLonWest()))); ncDataset.addAttribute(null, new Attribute("geospatial_lon_max", new Double(geoCoverage.getLonEast()))); } if ( null != geoCoverage.getUpDownRange()) { ncDataset.addAttribute(null, new Attribute("geospatial_vertical_min", new Double(geoCoverage.getHeightStart()))); ncDataset.addAttribute(null, new Attribute("geospatial_vertical_max", new Double(geoCoverage.getHeightStart() + geoCoverage.getHeightExtent()))); } } DateRange timeCoverage = ds.getTimeCoverage(); if (timeCoverage != null) { ncDataset.addAttribute(null, new Attribute("time_coverage_start", timeCoverage.getStart().toDateTimeStringISO())); ncDataset.addAttribute(null, new Attribute("time_coverage_end", timeCoverage.getEnd().toDateTimeStringISO())); } */ ncDataset.finish(); }
java
{ "resource": "" }
q174910
Grib1Record.readData
test
public static float[] readData(RandomAccessFile raf, long startPos) throws IOException { raf.seek(startPos); Grib1Record gr = new Grib1Record(raf); return gr.readData(raf); }
java
{ "resource": "" }
q174911
XURI.assemble
test
public String assemble(EnumSet<Parts> parts) { StringBuilder uri = new StringBuilder(); // Note that format and base may be same, so case it out int useformat = (parts.contains(Parts.FORMAT) ? 1 : 0); int usebase = (parts.contains(Parts.BASE) ? 2 : 0); switch (useformat + usebase) { case 0 + 0: // neither break; case 1 + 0: // FORMAT only uri.append(this.formatprotocol + ":"); break; case 2 + 0: // BASE only uri.append(this.baseprotocol + ":"); break; case 2 + 1: // both uri.append(this.formatprotocol + ":"); if(!this.baseprotocol.equals(this.formatprotocol)) uri.append(this.formatprotocol + ":"); break; } uri.append(this.baseprotocol.equals("file") ? "/" : "//"); if(userinfo != null && parts.contains(Parts.PWD)) uri.append(this.userinfo + ":"); if(this.host != null && parts.contains(Parts.HOST)) uri.append(this.host); if(this.path != null && parts.contains(Parts.PATH)) uri.append(this.path); if(this.query != null && parts.contains(Parts.QUERY)) uri.append("?" + this.query); if(this.frag != null && parts.contains(Parts.FRAG)) uri.append("#" + this.frag); return uri.toString(); }
java
{ "resource": "" }
q174912
XURI.canonical
test
static public String canonical(String s) { if(s != null) { s = s.trim(); if(s.length() == 0) s = null; } return s; }
java
{ "resource": "" }
q174913
WRFConvention.normalize
test
private String normalize(String units) { switch (units) { case "fraction": units = ""; break; case "dimensionless": units = ""; break; case "NA": units = ""; break; case "-": units = ""; break; default: units = StringUtil2.substitute(units, "**", "^"); units = StringUtil2.remove(units, '}'); units = StringUtil2.remove(units, '{'); break; } return units; }
java
{ "resource": "" }
q174914
Nc4DMRCompiler.compile
test
public DapDataset compile() throws DapException { // create and fill the root group buildrootgroup(this.ncid); if(this.dmr != null) dmr.finish(); return this.dmr; }
java
{ "resource": "" }
q174915
InvMetadata.finish
test
public void finish() { if (init) return; init = true; if (xlinkHref == null) return; xlinkHref = xlinkHref.trim(); try { this.xlinkUri = dataset.getParentCatalog().resolveUri(xlinkHref); } catch (java.net.URISyntaxException e) { log.append(" ** Error: Bad URL in metadata href = ").append(xlinkHref).append("\n"); return; } // open and read the referenced catalog XML try { if (converter == null) { log.append(" **InvMetadata on = (").append(this).append("): has no converter\n"); return; } contentObject = converter.readMetadataContentFromURL(dataset, xlinkUri); if (isThreddsMetadata) tm = (ThreddsMetadata) contentObject; } catch (java.io.IOException e) { log.append(" **InvMetadata on = (").append(xlinkUri).append("): Exception (").append(e.getMessage()).append(")\n"); // e.printStackTrace(); } }
java
{ "resource": "" }
q174916
SortedTable.get
test
public synchronized Object get(Object key) { int index = keys.indexOf(key); if (index != -1) return elements.elementAt(index); else return null; }
java
{ "resource": "" }
q174917
SortedTable.put
test
public synchronized Object put(Object key, Object value) throws NullPointerException { if (key == null || value == null) throw new NullPointerException(); int index = keys.indexOf(key); if (index != -1) { Object prev = elements.elementAt(index); elements.setElementAt(value, index); return prev; } else { keys.addElement(key); elements.addElement(value); return null; } }
java
{ "resource": "" }
q174918
GradsTimeStruct.getDate
test
public Date getDate() { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); // MONTH is zero based calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); }
java
{ "resource": "" }
q174919
DMRPrinter.printXMLAttributes
test
void printXMLAttributes(DapNode node, CEConstraint ce, int flags) throws IOException { if((flags & PERLINE) != 0) printer.indent(2); // Print name first, if non-null and !NONAME // Note that the short name needs to use // entity escaping (which is done by printXMLattribute), // but backslash escaping is not required. String name = node.getShortName(); if(name != null && (flags & NONAME) == 0) { name = node.getShortName(); printXMLAttribute("name", name, flags); } switch (node.getSort()) { case DATASET: DapDataset dataset = (DapDataset) node; printXMLAttribute("dapVersion", dataset.getDapVersion(), flags); printXMLAttribute("dmrVersion", dataset.getDMRVersion(), flags); // boilerplate printXMLAttribute("xmlns", "http://xml.opendap.org/ns/DAP/4.0#", flags); printXMLAttribute("xmlns:dap", "http://xml.opendap.org/ns/DAP/4.0#", flags); break; case DIMENSION: DapDimension orig = (DapDimension) node; if(orig.isShared()) {//not Anonymous // name will have already been printed // Now, we need to get the size as defined by the constraint DapDimension actual = this.ce.getRedefDim(orig); if(actual == null) actual = orig; long size = actual.getSize(); printXMLAttribute("size", Long.toString(size), flags); } break; case ENUMERATION: printXMLAttribute("basetype", ((DapEnumeration) node).getBaseType().getTypeName(), flags); break; case VARIABLE: DapVariable var = (DapVariable) node; DapType basetype = var.getBaseType(); if(basetype.isEnumType()) { printXMLAttribute("enum", basetype.getTypeName(), flags); } break; case ATTRIBUTE: DapAttribute attr = (DapAttribute) node; basetype = attr.getBaseType(); printXMLAttribute("type", basetype.getTypeName(), flags); if(attr.getBaseType().isEnumType()) { printXMLAttribute("enum", basetype.getTypeName(), flags); } break; default: break; // node either has no attributes or name only } //switch if(!this.testing) printReserved(node); if((flags & PERLINE) != 0) { printer.outdent(2); } }
java
{ "resource": "" }
q174920
DMRPrinter.printXMLAttribute
test
protected void printXMLAttribute(String name, String value, int flags) throws DapException { if(name == null) return; if((flags & NONNIL) == 0 && (value == null || value.length() == 0)) return; if((flags & PERLINE) != 0) { printer.eol(); printer.margin(); } printer.print(" " + name + "="); printer.print("\""); if(value != null) { // add xml entity escaping if((flags & XMLESCAPED) == 0) value = Escape.entityEscape(value, "\""); printer.print(value); } printer.print("\""); }
java
{ "resource": "" }
q174921
DMRPrinter.isSpecial
test
static boolean isSpecial(DapAttribute attr) { if(attr.getParent().getSort() == DapSort.DATASET) { for(String s : GROUPSPECIAL) { if(s.equals(attr.getShortName())) return true; } } else if(attr.getParent().getSort() == DapSort.VARIABLE) { for(String s : VARSPECIAL) { if(s.equals(attr.getShortName())) return true; } } return false; }
java
{ "resource": "" }
q174922
DMRPrinter.printDimrefs
test
void printDimrefs(DapVariable var) throws DapException { if(var.getRank() == 0) return; List<DapDimension> dimset = this.ce.getConstrainedDimensions(var); if(dimset == null) throw new DapException("Unknown variable: " + var); assert var.getRank() == dimset.size(); for(int i = 0; i < var.getRank(); i++) { DapDimension dim = dimset.get(i); printer.marginPrint("<Dim"); if(dim.isShared()) { String fqn = dim.getFQN(); assert (fqn != null) : "Illegal Dimension reference"; fqn = fqnXMLEscape(fqn); printXMLAttribute("name", fqn, XMLESCAPED); } else { long size = dim.getSize();// the size for printing purposes printXMLAttribute("size", Long.toString(size), NILFLAGS); } printer.println("/>"); } }
java
{ "resource": "" }
q174923
AreaReader.isValidFile
test
public static boolean isValidFile(RandomAccessFile raf) { String fileName = raf.getLocation(); AreaFile af = null; try { af = new AreaFile(fileName); // LOOK opening again not ok for isValidFile return true; } catch (AreaFileException e) { return false; // barfola } finally { if (af != null) af.close(); // LOOK need to look at this code } }
java
{ "resource": "" }
q174924
AreaReader.setAreaDirectoryAttributes
test
private void setAreaDirectoryAttributes(Variable v) { if ((dirBlock == null) || (ad == null)) { return; } for (int i = 1; i < 14; i++) { if (i == 7) { continue; } v.addAttribute(new Attribute(getADDescription(i), dirBlock[i])); } }
java
{ "resource": "" }
q174925
AreaReader.setNavBlockAttributes
test
private void setNavBlockAttributes(Variable v) { if ((navBlock == null) || (ad == null)) { return; } v.addAttribute( new Attribute( "navigation_type", McIDASUtil.intBitsToString(navBlock[0]))); }
java
{ "resource": "" }
q174926
AreaReader.getCalType
test
private int getCalType(String calName) { int calTypeOut = Calibrator.CAL_NONE; if (calName.trim().equals("ALB")) { calTypeOut = Calibrator.CAL_ALB; } else if (calName.trim().equals("BRIT")) { calTypeOut = Calibrator.CAL_BRIT; } else if (calName.trim().equals("RAD")) { calTypeOut = Calibrator.CAL_RAD; } else if (calName.trim().equals("RAW")) { calTypeOut = Calibrator.CAL_RAW; } else if (calName.trim().equals("TEMP")) { calTypeOut = Calibrator.CAL_TEMP; } return calTypeOut; }
java
{ "resource": "" }
q174927
AreaReader.setCalTypeAttributes
test
private void setCalTypeAttributes(Variable image, int calType) { String longName = "image values"; //String unit = ""; switch (calType) { case Calibrator.CAL_ALB: longName = "albedo"; //unit = "%"; break; case Calibrator.CAL_BRIT: longName = "brightness values"; break; case Calibrator.CAL_TEMP: longName = "temperature"; //unit = "K"; break; case Calibrator.CAL_RAD: longName = "pixel radiance values"; //unit = "mW/m2/sr/cm-1"; break; case Calibrator.CAL_RAW: longName = "raw image values"; break; default: break; } image.addAttribute(new Attribute("long_name", longName)); if (calUnit != null) { image.addAttribute(new Attribute(CDM.UNITS, calUnit)); } if (calScale != 1.f) { image.addAttribute(new Attribute("scale_factor", calScale)); } }
java
{ "resource": "" }
q174928
CoordSysEvaluator.findCoords
test
static public void findCoords(TableConfig nt, NetcdfDataset ds, Predicate p) { nt.lat = findCoordShortNameByType(ds, AxisType.Lat, p); nt.lon = findCoordShortNameByType(ds, AxisType.Lon, p); nt.time = findCoordShortNameByType(ds, AxisType.Time, p); nt.elev = findCoordShortNameByType(ds, AxisType.Height, p); if (nt.elev == null) nt.elev = findCoordShortNameByType(ds, AxisType.Pressure, p); }
java
{ "resource": "" }
q174929
CoordSysEvaluator.findCoordNameByType
test
static public String findCoordNameByType(NetcdfDataset ds, AxisType atype) { CoordinateAxis coordAxis = findCoordByType(ds, atype); return coordAxis == null ? null : coordAxis.getFullName(); }
java
{ "resource": "" }
q174930
CoordSysEvaluator.findCoordByType
test
static public CoordinateAxis findCoordByType(NetcdfDataset ds, AxisType atype) { return findCoordByType(ds, atype, null); }
java
{ "resource": "" }
q174931
CoordSysEvaluator.findCoordByType
test
static public CoordinateAxis findCoordByType(NetcdfDataset ds, AxisType atype, Predicate p) { // try the "best" coordinate system CoordinateSystem use = findBestCoordinateSystem(ds); if (use == null) return null; CoordinateAxis result = findCoordByType(use.getCoordinateAxes(), atype, p); if (result != null) return result; // try all the axes return findCoordByType(ds.getCoordinateAxes(), atype, p); }
java
{ "resource": "" }
q174932
CoordSysEvaluator.findDimensionByType
test
static public Dimension findDimensionByType(NetcdfDataset ds, AxisType atype) { CoordinateAxis axis = findCoordByType(ds, atype); if (axis == null) return null; if (axis.isScalar()) return null; return axis.getDimension(0); }
java
{ "resource": "" }
q174933
CoordSysEvaluator.findBestCoordinateSystem
test
static private CoordinateSystem findBestCoordinateSystem(NetcdfDataset ds) { // find coordinate system with highest rank (largest number of axes) CoordinateSystem use = null; for (CoordinateSystem cs : ds.getCoordinateSystems()) { if (use == null) use = cs; else if (cs.getCoordinateAxes().size() > use.getCoordinateAxes().size()) use = cs; } return use; }
java
{ "resource": "" }
q174934
CoordsSet.findDependent
test
private CoverageCoordAxis1D findDependent( CoverageCoordAxis independentAxis, AxisType axisType) { for (CoverageCoordAxis axis : axes) { if (axis.getDependenceType() == CoverageCoordAxis.DependenceType.dependent) { for (String axisName : axis.dependsOn) { if (axisName.equalsIgnoreCase(independentAxis.getName()) && axis.getAxisType() == axisType) return (CoverageCoordAxis1D) axis; } } } return null; }
java
{ "resource": "" }
q174935
DSequence.getVariable
test
public BaseType getVariable(int row, String name) throws NoSuchVariableException { int dotIndex = name.indexOf('.'); if (dotIndex != -1) { // name contains "." String aggregate = name.substring(0, dotIndex); String field = name.substring(dotIndex + 1); BaseType aggRef = getVariable(aggregate); if (aggRef instanceof DConstructor) return ((DConstructor) aggRef).getVariable(field); // recurse else ; // fall through to throw statement } else { Vector selectedRow = (Vector) allValues.elementAt(row); for (Enumeration e = selectedRow.elements(); e.hasMoreElements();) { BaseType v = (BaseType) e.nextElement(); if (v.getEncodedName().equals(name)) return v; } } throw new NoSuchVariableException("DSequence: getVariable()"); }
java
{ "resource": "" }
q174936
DSequence.oldDeserialize
test
private void oldDeserialize(DataInputStream source, ServerVersion sv, StatusUI statusUI) throws IOException, DataReadException { try { for (; ;) { deserializeSingle(source, sv, statusUI); } } catch (EOFException e) { } }
java
{ "resource": "" }
q174937
DSequence.readMarker
test
private byte readMarker(DataInputStream source) throws IOException { byte marker = source.readByte(); // pad out to a multiple of four bytes byte unused; for (int i = 0; i < 3; i++) unused = source.readByte(); return marker; }
java
{ "resource": "" }
q174938
DSequence.writeMarker
test
protected void writeMarker(DataOutputStream sink, byte marker) throws IOException { //for(int i=0; i<4; i++) sink.writeByte(marker); sink.writeByte((byte) 0); sink.writeByte((byte) 0); sink.writeByte((byte) 0); }
java
{ "resource": "" }
q174939
SaxEventHandler.fatalError
test
@Override public void fatalError(SAXParseException e) throws SAXException { throw new SAXParseException( String.format("Sax fatal error: %s; %s%n", e, report(this.locator)), this.locator); }
java
{ "resource": "" }
q174940
MultipleAxisChart.createDataset
test
private static TimeSeries createDataset(String name, double base, RegularTimePeriod start, int count) { TimeSeries series = new TimeSeries(name, start.getClass()); RegularTimePeriod period = start; double value = base; for (int i = 0; i < count; i++) { series.add(period, value); period = period.next(); value = value * (1 + (Math.random() - 0.495) / 10.0); } return series; }
java
{ "resource": "" }
q174941
MultipleAxisChart.main
test
public static void main(String[] args) { TimeSeries dataset1 = createDataset("Series 1", 100.0, new Minute(), 200); MultipleAxisChart demo = new MultipleAxisChart( "Multiple Axis Demo 1", "Time of Day", "Primary Range Axis", dataset1); /* AXIS 2 NumberAxis axis2 = new NumberAxis("Range Axis 2"); axis2.setFixedDimension(10.0); axis2.setAutoRangeIncludesZero(false); plot.setRangeAxis(1, axis2); plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_LEFT); / plot.setDataset(1, dataset2); plot.mapDatasetToRangeAxis(1, 1); XYItemRenderer renderer2 = new StandardXYItemRenderer(); plot.setRenderer(1, renderer2); */ TimeSeries dataset2 = createDataset("Series 2", 1000.0, new Minute(), 170); demo.addSeries("Range Axis 2", dataset2); /* // AXIS 3 NumberAxis axis3 = new NumberAxis("Range Axis 3"); plot.setRangeAxis(2, axis3); XYDataset dataset3 = createDataset("Series 3", 10000.0, new Minute(), 170); plot.setDataset(2, dataset3); plot.mapDatasetToRangeAxis(2, 2); XYItemRenderer renderer3 = new StandardXYItemRenderer(); plot.setRenderer(2, renderer3); */ TimeSeries dataset3 = createDataset("Series 3", 10000.0, new Minute(), 170); demo.addSeries("Range Axis 3", dataset3); /* AXIS 4 NumberAxis axis4 = new NumberAxis("Range Axis 4"); plot.setRangeAxis(3, axis4); XYDataset dataset4 = createDataset("Series 4", 25.0, new Minute(), 200); plot.setDataset(3, dataset4); plot.mapDatasetToRangeAxis(3, 3); XYItemRenderer renderer4 = new StandardXYItemRenderer(); plot.setRenderer(3, renderer4); */ TimeSeries dataset4 = createDataset("Series 4", 25.0, new Minute(), 200); demo.addSeries("Range Axis 4", dataset4); demo.finish(new java.awt.Dimension(600, 270)); JFrame frame = new JFrame("Demovabulous "); frame.getContentPane().add(demo, BorderLayout.CENTER); frame.setSize(640, 480); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
java
{ "resource": "" }
q174942
StructureDataA.getJavaArrayString
test
public String[] getJavaArrayString(StructureMembers.Member m) { if (m.getDataType() == DataType.STRING) { Array data = getArray(m); int n = m.getSize(); String[] result = new String[n]; for (int i = 0; i < result.length; i++) result[i] = (String) data.getObject(i); return result; } else if (m.getDataType() == DataType.CHAR) { ArrayChar data = (ArrayChar) getArray(m); ArrayChar.StringIterator iter = data.getStringIterator(); String[] result = new String[iter.getNumElems()]; int count = 0; while (iter.hasNext()) result[count++] = iter.next(); return result; } throw new IllegalArgumentException("getJavaArrayString: not String DataType :" + m.getDataType()); }
java
{ "resource": "" }
q174943
DoradeVOLD.getParamList
test
public DoradePARM[] getParamList() { int paramCount = 0; for (int i = 0; i < nSensors; i++) paramCount += myRADDs[i].getNParams(); DoradePARM[] list = new DoradePARM[paramCount]; int next = 0; for (int i = 0; i < nSensors; i++) { int nParams = myRADDs[i].getNParams(); System.arraycopy(myRADDs[i].getParamList(), 0, list, next, nParams); next += nParams; } return list; }
java
{ "resource": "" }
q174944
StationRegionDateChooser.setStations
test
public void setStations(java.util.List stns) { stnRender.setStations(stns); redraw(true); }
java
{ "resource": "" }
q174945
StationRegionDateChooser.setSelectedStation
test
public void setSelectedStation(String id) { stnRender.setSelectedStation(id); selectedStation = stnRender.getSelectedStation(); assert selectedStation != null; np.setLatLonCenterMapArea(selectedStation.getLatitude(), selectedStation.getLongitude()); redraw(); }
java
{ "resource": "" }
q174946
StationRegionDateChooser.redraw
test
protected void redraw() { long tstart = System.currentTimeMillis(); java.awt.Graphics2D gNP = np.getBufferedImageGraphics(); if (gNP == null) // panel not drawn on screen yet return; // clear it gNP.setBackground(np.getBackgroundColor()); java.awt.Rectangle r = gNP.getClipBounds(); gNP.clearRect(r.x, r.y, r.width, r.height); if (regionSelect && geoSelectionMode) { if (geoSelection != null) drawBB(gNP, geoSelection, Color.cyan); if (geoBounds != null) drawBB(gNP, geoBounds, null); // System.out.println("GeoRegionChooser.redraw geoBounds= "+geoBounds); if (geoSelection != null) { // gNP.setColor( Color.orange); Navigation navigate = np.getNavigation(); double handleSize = RubberbandRectangleHandles.handleSizePixels / navigate.getPixPerWorld(); Rectangle2D rect = new Rectangle2D.Double(geoSelection.getX(), geoSelection.getY(), geoSelection.getWidth(), geoSelection.getHeight()); RubberbandRectangleHandles.drawHandledRect(gNP, rect, handleSize); if (debug) System.out.println("GeoRegionChooser.drawHandledRect=" + handleSize + " = " + geoSelection); } } for (int i = 0; i < renderers.size(); i++) { ucar.nc2.ui.util.Renderer rend = (Renderer) renderers.get(i); rend.draw(gNP, atI); } gNP.dispose(); if (debug) { long tend = System.currentTimeMillis(); System.out.println("StationRegionDateChooser draw time = " + (tend - tstart) / 1000.0 + " secs"); } // copy buffer to the screen np.repaint(); }
java
{ "resource": "" }
q174947
ProjectionRect.readObject
test
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { double x = s.readDouble(); double y = s.readDouble(); double w = s.readDouble(); double h = s.readDouble(); setRect(x, y, w, h); }
java
{ "resource": "" }
q174948
ProjectionRect.writeObject
test
private void writeObject(ObjectOutputStream s) throws IOException { s.writeDouble(getX()); s.writeDouble(getY()); s.writeDouble(getWidth()); s.writeDouble(getHeight()); }
java
{ "resource": "" }
q174949
UnitDBImpl.add
test
public void add(final UnitDBImpl that) throws UnitExistsException { unitSet.addAll(that.unitSet); nameMap.putAll(that.nameMap); symbolMap.putAll(that.symbolMap); }
java
{ "resource": "" }
q174950
UnitDBImpl.addUnit
test
public void addUnit(final Unit unit) throws UnitExistsException, NameException { if (unit.getName() == null) { throw new NameException("Unit name can't be null"); } addByName(unit.getName(), unit); addByName(unit.getPlural(), unit); addBySymbol(unit.getSymbol(), unit); unitSet.add(unit); }
java
{ "resource": "" }
q174951
UnitDBImpl.addSymbol
test
public final void addSymbol(final String symbol, final String name) throws NoSuchUnitException, UnitExistsException { addAlias(null, name, symbol, null); }
java
{ "resource": "" }
q174952
UnitDBImpl.get
test
public Unit get(final String id) { Unit unit = getBySymbol(id); if (unit == null) { unit = getByName(id); } return unit; }
java
{ "resource": "" }
q174953
UnitDBImpl.addByName
test
private final void addByName(final String name, final Unit newUnit) throws UnitExistsException { if (name != null) { addUnique(nameMap, canonicalize(name), newUnit); } }
java
{ "resource": "" }
q174954
UnitDBImpl.addBySymbol
test
private final void addBySymbol(final String symbol, final Unit newUnit) throws UnitExistsException { if (symbol != null) { addUnique(symbolMap, symbol, newUnit); } }
java
{ "resource": "" }
q174955
UnitDBImpl.addUnique
test
private static final void addUnique(final Map<String, Unit> map, final String key, final Unit newUnit) throws UnitExistsException { final Unit oldUnit = map.put(key, newUnit); if (oldUnit != null && !oldUnit.equals(newUnit)) { throw new UnitExistsException(oldUnit, newUnit); } }
java
{ "resource": "" }
q174956
PLAF.addToMenu
test
public void addToMenu(final JMenu menu) { final UIManager.LookAndFeelInfo[] plafInfo = UIManager.getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo aPlafInfo : plafInfo) { addToMenu(aPlafInfo.getName(), aPlafInfo.getClassName(), menu); } final LookAndFeel current = UIManager.getLookAndFeel(); System.out.printf("current L&F=%s%n", current.getName()); }
java
{ "resource": "" }
q174957
Grib2RecordScanner.findRecordByDrspos
test
@Nullable public static Grib2Record findRecordByDrspos(RandomAccessFile raf, long drsPos) throws IOException { long pos = Math.max(0, drsPos- (20*1000)); // go back 20K Grib2RecordScanner scan = new Grib2RecordScanner(raf, pos); while (scan.hasNext()) { ucar.nc2.grib.grib2.Grib2Record gr = scan.next(); Grib2SectionDataRepresentation drs = gr.getDataRepresentationSection(); if (drsPos == drs.getStartingPosition()) return gr; if (raf.getFilePointer() > drsPos) break; // missed it. } return null; }
java
{ "resource": "" }
q174958
NcSDStructure.read
test
public boolean read(String datasetName, Object specialO) throws NoSuchVariableException, IOException { // read the scalar structure into memory StructureData sdata = ncVar.readStructure(); setData( sdata); return(false); }
java
{ "resource": "" }
q174959
NcSDStructure.serialize
test
public void serialize(String dataset,DataOutputStream sink,CEEvaluator ce,Object specialO) throws NoSuchVariableException, DAP2ServerSideException, IOException { if (org == null) { super.serialize(dataset, sink, ce, specialO); return; } // use the projection info in the original java.util.Enumeration vars = org.getVariables(); // run through each structure member StructureMembers sm = sdata.getStructureMembers(); int count = 0; while (vars.hasMoreElements()) { HasNetcdfVariable sm_org = (HasNetcdfVariable) vars.nextElement(); boolean isProjected = ((ServerMethods) sm_org).isProject(); if (isProjected) { StructureMembers.Member m = sm.getMember(count); sm_org.serialize( sink, sdata, m); } count++; } }
java
{ "resource": "" }
q174960
DoradePARM.getParamValues
test
public float[] getParamValues(DoradeRDAT rdat,float[] workingArray) throws DescriptorException { if (! paramName.equals(rdat.getParamName())) throw new DescriptorException("parameter name mismatch"); byte[] paramData = rdat.getRawData(); int nCells = myRADD.getNCells(); float[] values; if(workingArray!=null && workingArray.length == nCells) { values = workingArray; } else { values = new float[nCells]; } short[] svalues = null; if (myRADD.getCompressionScheme() == DoradeRADD.COMPRESSION_HRD) { if (binaryFormat != DoradePARM.FORMAT_16BIT_INT) { throw new DescriptorException("Cannot unpack " + "compressed data with binary format " + binaryFormat); } svalues = uncompressHRD(paramData, nCells); } for (int cell = 0; cell < nCells; cell++) { switch (binaryFormat) { case DoradePARM.FORMAT_8BIT_INT: byte bval = paramData[cell]; values[cell] = (bval == badDataFlag) ? BAD_VALUE : (bval - bias) / scale; break; case DoradePARM.FORMAT_16BIT_INT: short sval = (svalues != null) ? svalues[cell] : grabShort(paramData, 2 * cell); values[cell] = (sval == badDataFlag) ? BAD_VALUE : (sval - bias) / scale; break; case DoradePARM.FORMAT_32BIT_INT: int ival = grabInt(paramData, 4 * cell); values[cell] = (ival == badDataFlag) ? BAD_VALUE : (ival - bias) / scale; break; case DoradePARM.FORMAT_32BIT_FLOAT: float fval = grabFloat(paramData, 4 * cell); values[cell] = (fval == badDataFlag) ? BAD_VALUE : (fval - bias) / scale; break; case DoradePARM.FORMAT_16BIT_FLOAT: throw new DescriptorException("can't unpack 16-bit " + "float data yet"); default: throw new DescriptorException("bad binary format (" + binaryFormat + ")"); } } return values; }
java
{ "resource": "" }
q174961
VerticalPerspectiveView.constructCopy
test
@Override public ProjectionImpl constructCopy() { ProjectionImpl result = new VerticalPerspectiveView(getOriginLat(), getOriginLon(), R, getHeight(), false_east, false_north); result.setDefaultMapArea(defaultMapArea); result.setName(name); return result; }
java
{ "resource": "" }
q174962
ThreddsDataFactory.openFeatureDataset
test
public ThreddsDataFactory.Result openFeatureDataset(InvDataset invDataset, ucar.nc2.util.CancelTask task) throws IOException { return openFeatureDataset(null, invDataset, task, new Result()); }
java
{ "resource": "" }
q174963
ThreddsDataFactory.openFeatureDataset
test
public ThreddsDataFactory.Result openFeatureDataset(InvAccess access, ucar.nc2.util.CancelTask task) throws IOException { InvDataset invDataset = access.getDataset(); ThreddsDataFactory.Result result = new Result(); if (invDataset.getDataType() == null) { result.errLog.format("InvDatasert must specify a FeatureType%n"); result.fatalError = true; return result; } return openFeatureDataset(invDataset.getDataType(), access, task, result); }
java
{ "resource": "" }
q174964
ThreddsDataFactory.openDataset
test
public NetcdfDataset openDataset(InvDataset invDataset, boolean acquire, ucar.nc2.util.CancelTask task, Formatter log) throws IOException { Result result = new Result(); NetcdfDataset ncd = openDataset(invDataset, acquire, task, result); if (log != null) log.format("%s", result.errLog); return (result.fatalError) ? null : ncd; }
java
{ "resource": "" }
q174965
ThreddsDataFactory.annotate
test
public static void annotate(InvDataset ds, NetcdfDataset ncDataset) { ncDataset.setTitle(ds.getName()); ncDataset.setId(ds.getID()); // add properties as global attributes for (InvProperty p : ds.getProperties()) { String name = p.getName(); if (null == ncDataset.findGlobalAttribute(name)) { ncDataset.addAttribute(null, new Attribute(name, p.getValue())); } } /* ThreddsMetadata.GeospatialCoverage geoCoverage = ds.getGeospatialCoverage(); if (geoCoverage != null) { if ( null != geoCoverage.getNorthSouthRange()) { ncDataset.addAttribute(null, new Attribute("geospatial_lat_min", new Double(geoCoverage.getLatSouth()))); ncDataset.addAttribute(null, new Attribute("geospatial_lat_max", new Double(geoCoverage.getLatNorth()))); } if ( null != geoCoverage.getEastWestRange()) { ncDataset.addAttribute(null, new Attribute("geospatial_lon_min", new Double(geoCoverage.getLonWest()))); ncDataset.addAttribute(null, new Attribute("geospatial_lon_max", new Double(geoCoverage.getLonEast()))); } if ( null != geoCoverage.getUpDownRange()) { ncDataset.addAttribute(null, new Attribute("geospatial_vertical_min", new Double(geoCoverage.getHeightStart()))); ncDataset.addAttribute(null, new Attribute("geospatial_vertical_max", new Double(geoCoverage.getHeightStart() + geoCoverage.getHeightExtent()))); } } DateRange timeCoverage = ds.getTimeCoverage(); if (timeCoverage != null) { ncDataset.addAttribute(null, new Attribute("time_coverage_start", timeCoverage.getStart().toDateTimeStringISO())); ncDataset.addAttribute(null, new Attribute("time_coverage_end", timeCoverage.getEnd().toDateTimeStringISO())); } */ ncDataset.finish(); }
java
{ "resource": "" }
q174966
Property.removeDups
test
public static List<Property> removeDups(List<Property> org) { List<Property> result = new ArrayList<>(org.size()); for (Property p : org) if (!result.contains(p)) // O(n**2) result.add(p); return result; }
java
{ "resource": "" }
q174967
VariableIndexPartitioned.addPartition
test
void addPartition(int partno, int groupno, int varno, int ndups, int nrecords, int nmissing, GribCollectionMutable.VariableIndex vi) { if (partList == null) partList = new ArrayList<>(nparts); partList.add(new PartitionForVariable2D(partno, groupno, varno)); this.ndups += ndups; this.nrecords += nrecords; this.nmissing += nmissing; }
java
{ "resource": "" }
q174968
Partition.makeGribCollection
test
@Nullable public GribCollectionMutable makeGribCollection() { GribCollectionMutable result = GribCdmIndex.openMutableGCFromIndex(dcm.getIndexFilename(GribCdmIndex.NCX_SUFFIX), config, false, true, logger); if (result == null) { logger.error("Failed on openMutableGCFromIndex {}", dcm.getIndexFilename(GribCdmIndex.NCX_SUFFIX)); return null; } lastModified = result.lastModified; fileSize = result.fileSize; if (result.masterRuntime != null) partitionDate = result.masterRuntime.getFirstDate(); return result; }
java
{ "resource": "" }
q174969
RegExpAndDurationTimeCoverageEnhancer.getInstanceToMatchOnDatasetName
test
public static RegExpAndDurationTimeCoverageEnhancer getInstanceToMatchOnDatasetName( String matchPattern, String substitutionPattern, String duration ) { return new RegExpAndDurationTimeCoverageEnhancer( matchPattern, substitutionPattern, duration, MatchTarget.DATASET_NAME ); }
java
{ "resource": "" }
q174970
RegExpAndDurationTimeCoverageEnhancer.getInstanceToMatchOnDatasetPath
test
public static RegExpAndDurationTimeCoverageEnhancer getInstanceToMatchOnDatasetPath( String matchPattern, String substitutionPattern, String duration ) { return new RegExpAndDurationTimeCoverageEnhancer( matchPattern, substitutionPattern, duration, MatchTarget.DATASET_PATH ); }
java
{ "resource": "" }
q174971
DqcFactory.writeXML
test
public boolean writeXML(QueryCapability dqc, String filename) { try { BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(filename)); writeXML(dqc, os); os.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
java
{ "resource": "" }
q174972
H4iosp.readStructureData
test
private ucar.ma2.ArrayStructure readStructureData(ucar.nc2.Structure s, Section section) throws java.io.IOException, InvalidRangeException { H4header.Vinfo vinfo = (H4header.Vinfo) s.getSPobject(); vinfo.setLayoutInfo(); // make sure needed info is present int recsize = vinfo.elemSize; // create the ArrayStructure StructureMembers members = s.makeStructureMembers(); for (StructureMembers.Member m : members.getMembers()) { Variable v2 = s.findVariable(m.getName()); H4header.Minfo minfo = (H4header.Minfo) v2.getSPobject(); m.setDataParam(minfo.offset); } members.setStructureSize(recsize); ArrayStructureBB structureArray = new ArrayStructureBB(members, section.getShape()); // LOOK subset // loop over records byte[] result = structureArray.getByteBuffer().array(); /*if (vinfo.isChunked) { InputStream is = getChunkedInputStream(vinfo); PositioningDataInputStream dataSource = new PositioningDataInputStream(is); Layout layout = new LayoutRegular(vinfo.start, recsize, s.getShape(), section); IospHelper.readData(dataSource, layout, DataType.STRUCTURE, result); */ if (!vinfo.isLinked && !vinfo.isCompressed) { Layout layout = new LayoutRegular(vinfo.start, recsize, s.getShape(), section); IospHelper.readData(raf, layout, DataType.STRUCTURE, result, -1, true); /* option 1 } else if (vinfo.isLinked && !vinfo.isCompressed) { Layout layout = new LayoutSegmented(vinfo.segPos, vinfo.segSize, recsize, s.getShape(), section); IospHelper.readData(raf, layout, DataType.STRUCTURE, result, -1); */ // option 2 } else if (vinfo.isLinked && !vinfo.isCompressed) { InputStream is = new LinkedInputStream(vinfo); PositioningDataInputStream dataSource = new PositioningDataInputStream(is); Layout layout = new LayoutRegular(0, recsize, s.getShape(), section); IospHelper.readData(dataSource, layout, DataType.STRUCTURE, result); } else if (!vinfo.isLinked && vinfo.isCompressed) { InputStream is = getCompressedInputStream(vinfo); PositioningDataInputStream dataSource = new PositioningDataInputStream(is); Layout layout = new LayoutRegular(0, recsize, s.getShape(), section); IospHelper.readData(dataSource, layout, DataType.STRUCTURE, result); } else if (vinfo.isLinked && vinfo.isCompressed) { InputStream is = getLinkedCompressedInputStream(vinfo); PositioningDataInputStream dataSource = new PositioningDataInputStream(is); Layout layout = new LayoutRegular(0, recsize, s.getShape(), section); IospHelper.readData(dataSource, layout, DataType.STRUCTURE, result); } else { throw new IllegalStateException(); } return structureArray; }
java
{ "resource": "" }
q174973
PicturePane.setPicture
test
public void setPicture( URL filenameURL, String legendParam, double rotation ) { legend = legendParam; centerWhenScaled = true; sclPic.setScaleSize(getSize()); sclPic.stopLoadingExcept( filenameURL ); sclPic.loadAndScalePictureInThread( filenameURL, Thread.MAX_PRIORITY, rotation ); }
java
{ "resource": "" }
q174974
PicturePane.setBufferedImage
test
public void setBufferedImage( BufferedImage img, String statusMessage ) { legend = statusMessage; centerWhenScaled = true; Dimension dim = getSize(); sclPic.setScaleSize(dim); SourcePicture source = new SourcePicture(); source.setSourceBufferedImage( img, statusMessage ); sclPic.setSourcePicture( source); if (!scaleToFit) sclPic.setScaleFactor(1.0); sclPic.scalePicture(); repaint(); }
java
{ "resource": "" }
q174975
PicturePane.zoomToFit
test
public void zoomToFit() { //Tools.log("zoomToFit invoked"); sclPic.setScaleSize( getSize() ); // prevent useless rescale events when the picture is not ready if ( sclPic.getStatusCode() == sclPic.LOADED || sclPic.getStatusCode() == sclPic.READY ) { sclPic.createScaledPictureInThread( Thread.MAX_PRIORITY ); } }
java
{ "resource": "" }
q174976
PicturePane.paintComponent
test
public void paintComponent(Graphics g) { int WindowWidth = getSize().width; int WindowHeight = getSize().height; Tools.log ("paintComponent called"); if (Dragging == false) { //otherwise it's already a move Cursor setCursor(new Cursor(Cursor.WAIT_CURSOR)); } if ( sclPic.getScaledPicture() != null ) { Graphics2D g2d = (Graphics2D)g; int X_Offset = (int) ((double) (WindowWidth / 2) - (focusPoint.x * sclPic.getScaleFactor())); int Y_Offset = (int) ((double) (WindowHeight / 2) - (focusPoint.y * sclPic.getScaleFactor())); // clear damaged component area Rectangle clipBounds = g2d.getClipBounds(); g2d.setColor(Color.black); // getBackground()); g2d.fillRect(clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height); g2d.drawRenderedImage(sclPic.getScaledPicture(), AffineTransform.getTranslateInstance( X_Offset, Y_Offset)); //g2d.drawImage(sclPic.getScaledPicture(), null, 0, 0); if (showInfo) { g2d.setColor(Color.white); g2d.drawString(legend, infoPoint.x, infoPoint.y); g2d.drawString("Size: " + Integer.toString(sclPic.getOriginalWidth()) + " x " + Integer.toString(sclPic.getOriginalHeight()) + " Offset: " + X_Offset + " x " + Y_Offset + " Mid: " + Integer.toString(focusPoint.x) + " x " + Integer.toString(focusPoint.y) + " Scale: " + twoDecimalFormatter.format(sclPic.getScaleFactor()), infoPoint.x, infoPoint.y + lineSpacing); /* g2d.drawString("File: " + sclPic.getFilename() , infoPoint.x , infoPoint.y + (2 * lineSpacing) ); g2d.drawString("Loaded in: " + twoDecimalFormatter.format( sclPic.getSourcePicture().loadTime / 1000F ) + " Seconds" , infoPoint.x , infoPoint.y + (3 * lineSpacing) ); g2d.drawString("Free memory: " + Long.toString( Runtime.getRuntime().freeMemory( )/1024/1024, 0 ) + " MB" , infoPoint.x , infoPoint.y + (4 * lineSpacing) ); */ } } else { // paint a black square g.setClip(0, 0, WindowWidth, WindowHeight); g.setColor(Color.black); g.fillRect(0,0,WindowWidth,WindowHeight); } if (Dragging == false) { //otherwise a move Cursor and should remain setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }
java
{ "resource": "" }
q174977
GempakUtil.TG_FTOI
test
public static int[] TG_FTOI(int[] iftime, int start) { int[] intdtf = new int[3]; // If there is no forecast information, the string is stored as // date and time. if (iftime[start] < 100000000) { intdtf[0] = iftime[start]; intdtf[1] = iftime[start + 1]; intdtf[2] = 0; // Otherwise, decode date/time and forecast info from the // two integers. } else { // The first word contains MMDDYYHHMM. This must be turned // into YYMMDD and HHMM. intdtf[0] = iftime[start] / 10000; intdtf[1] = iftime[start] - intdtf[0] * 10000; int mmdd = intdtf[0] / 100; int iyyy = intdtf[0] - mmdd * 100; intdtf[0] = iyyy * 10000 + mmdd; // The forecast time remains the same. intdtf[2] = iftime[start + 1]; } return intdtf; }
java
{ "resource": "" }
q174978
GempakUtil.TG_ITOC
test
public static String TG_ITOC(int[] intdtf) { String gdattim = ""; //Check for the blank time which may be found. if ((intdtf[0] == 0) && (intdtf[1] == 0) && (intdtf[2] == 0)) { return gdattim; } // Put the date and time into the character time. gdattim = TI_CDTM(intdtf[0], intdtf[1]); // Decode the forecast information if there is any. if (intdtf[2] != 0) { String[] timeType = TG_CFTM(intdtf[2]); String ftype = timeType[0]; String ftime = timeType[1]; // Combine two parts into string. gdattim = gdattim.substring(0, 11) + ftype + ftime; } return gdattim; }
java
{ "resource": "" }
q174979
GempakUtil.TI_ITOC
test
public static String TI_ITOC(int[] idtarr) { String dattim; String date, time; // Put array values into variables. int iyear = idtarr[0]; int imonth = idtarr[1]; int iday = idtarr[2]; int ihour = idtarr[3]; int iminut = idtarr[4]; // Check for leap year. //int ndays = TI_DAYM(iyear, imonth); iyear = iyear % 100; // Check that each of these values is valid. /* TODO: Check these IF ( iyear .lt. 0 ) iret = -7 IF ( ( imonth .lt. 1 ) .or. ( imonth .gt. 12 ) ) iret = -8 IF ( ( iday .lt. 1 ) .or. ( iday .gt. ndays ) ) + iret = -9 IF ( ( ihour .lt. 0 ) .or. ( ihour .gt. 24 ) ) iret = -10 IF ( ( iminut .lt. 0 ) .or. ( iminut .gt. 60 ) ) iret = -11 IF ( iret .ne. 0 ) RETURN */ // Get the date and time. int idate = iyear * 10000 + imonth * 100 + iday; int itime = ihour * 100 + iminut; // Convert date and time to character strings. // Fill in blanks with zeroes. date = StringUtil2.padZero(idate, 6); time = StringUtil2.padZero(itime, 4); dattim = date + "/" + time; return dattim; }
java
{ "resource": "" }
q174980
GempakUtil.TI_DAYM
test
public static int TI_DAYM(int iyear, int imon) { int iday = 0; if ((imon > 0) && (imon < 13)) { // Pick the number of days for the given month. iday = month[imon - 1]; if ((imon == 2) && LEAP(iyear)) { iday = iday + 1; } } return iday; }
java
{ "resource": "" }
q174981
GempakUtil.LV_CCRD
test
public static String LV_CCRD(int ivcord) { //Translate known vertical coordinates or look for parameter name. String vcoord = ""; //Check for numeric vertical coordinates. if ((ivcord >= 0) && (ivcord < vertCoords.length)) { vcoord = vertCoords[ivcord]; } else if (ivcord > 100) { // Check for character name as vertical coordinate. Check that // each character is an alphanumeric character. vcoord = ST_ITOC(ivcord); /* Check for bad values DO i = 1, 4 v = vcoord (i:i) IF ( ( ( v .lt. 'A' ) .or. ( v .gt. 'Z' ) ) .and. + ( ( v .lt. '0' ) .or. ( v .gt. '9' ) ) ) THEN ier = -1 END IF END DO END IF */ } return vcoord; }
java
{ "resource": "" }
q174982
GempakUtil.swp4
test
public static int[] swp4(int[] values, int startIndex, int number) { for (int i = startIndex; i < startIndex + number; i++) { values[i] = Integer.reverseBytes(values[i]); } return values; }
java
{ "resource": "" }
q174983
GempakUtil.getGridPackingName
test
public static String getGridPackingName(int pktyp) { String packingType = "UNKNOWN"; switch (pktyp) { case GempakConstants.MDGNON : packingType = "MDGNON"; break; case GempakConstants.MDGGRB : packingType = "MDGGRB"; break; case GempakConstants.MDGNMC : packingType = "MDGNMC"; break; case GempakConstants.MDGDIF : packingType = "MDGDIF"; break; case GempakConstants.MDGDEC : packingType = "MDGDEC"; break; case GempakConstants.MDGRB2 : packingType = "MDGRB2"; break; default : break; } return packingType; }
java
{ "resource": "" }
q174984
GempakUtil.getDataType
test
public static String getDataType(int typrt) { String dataType = "" + typrt; switch (typrt) { case GempakConstants.MDREAL : dataType = "MDREAL"; break; case GempakConstants.MDINTG : dataType = "MDINTG"; break; case GempakConstants.MDCHAR : dataType = "MDCHAR"; break; case GempakConstants.MDRPCK : dataType = "MDRPCK"; break; case GempakConstants.MDGRID : dataType = "MDGRID"; break; default : break; } return dataType; }
java
{ "resource": "" }
q174985
DataDDS.readData
test
public void readData(InputStream is, StatusUI statusUI) throws IOException, EOFException, DAP2Exception { /* ByteArrayOutputStream bout = new ByteArrayOutputStream(50 * 1000); copy(is, bout); LogStream.dbg.printf(" readData size=%d %n",bout.size()); LogStream.dbg.logflush(); ByteArrayInputStream bufferedIS = new ByteArrayInputStream( bout.toByteArray()); */ //statusUI = new Counter(); // Buffer the input stream for better performance BufferedInputStream bufferedIS = new BufferedInputStream(is); // Use a DataInputStream for deserialize DataInputStream dataIS = new DataInputStream(bufferedIS); for (Enumeration e = getVariables(); e.hasMoreElements();) { if (statusUI != null && statusUI.userCancelled()) throw new DataReadException("User cancelled"); ClientIO bt = (ClientIO) e.nextElement(); /* if (true) { BaseType btt = (BaseType) bt; System.out.printf("Deserializing: %s (%s) %n", btt.getEncodedName(), ((BaseType) bt).getTypeName()); } */ bt.deserialize(dataIS, ver, statusUI); } //LogStream.out.printf("Deserializing: total size = %s %n", counter); // notify GUI of finished download if (statusUI != null) statusUI.finished(); }
java
{ "resource": "" }
q174986
DataDDS.externalize
test
public final void externalize(OutputStream os, boolean compress, boolean headers) throws IOException { // First, print headers if (headers) { PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,Util.UTF8)); pw.println("HTTP/1.0 200 OK"); pw.println("XDAP: " + ServerVersion.DAP2_PROTOCOL_VERSION); pw.println("XDODS-Server: DODS/" + ServerVersion.DAP2_PROTOCOL_VERSION); pw.println("Content-type: application/octet-stream"); pw.println("Content-Description: dods-data"); if (compress) { pw.println("Content-Encoding: deflate"); } pw.println(); pw.flush(); } // Buffer the output stream for better performance OutputStream bufferedOS; if (compress) { // need a BufferedOutputStream - 3X performance - LOOK: why ?? bufferedOS = new BufferedOutputStream(new DeflaterOutputStream(os)); } else { bufferedOS = new BufferedOutputStream(os); } // Redefine PrintWriter here, so the DDS is also compressed if necessary PrintWriter pw = new PrintWriter(new OutputStreamWriter(bufferedOS,Util.UTF8)); print(pw); // pw.println("Data:"); // JCARON CHANGED pw.flush(); bufferedOS.write("\nData:\n".getBytes(CDM.utf8Charset)); // JCARON CHANGED bufferedOS.flush(); // Use a DataOutputStream for serialize DataOutputStream dataOS = new DataOutputStream(bufferedOS); for (Enumeration e = getVariables(); e.hasMoreElements();) { ClientIO bt = (ClientIO) e.nextElement(); bt.externalize(dataOS); } // Note: for DeflaterOutputStream, flush() is not sufficient to flush // all buffered data dataOS.close(); }
java
{ "resource": "" }
q174987
TagEnum.getTag
test
public static TagEnum getTag(short code) { TagEnum te = hash.get(code); if (te == null) te = new TagEnum("UNKNOWN", "UNKNOWN", code); return te; }
java
{ "resource": "" }
q174988
ImageDatasetFactory.getNextImage
test
public BufferedImage getNextImage(boolean forward) { if (grid != null) { if (forward) { this.time++; if (this.time >= this.ntimes) this.time = 0; } else { this.time--; if (this.time < 0) this.time = this.ntimes-1; } Array data; try { data = grid.readDataSlice( this.time, 0, -1, -1); return ImageArrayAdapter.makeGrayscaleImage( data, grid); } catch (IOException e) { e.printStackTrace(); return null; } } if (currentFile == null) return null; if (currentDir == null) { currentDirFileNo = 0; currentDir = currentFile.getParentFile(); currentDirFileList = new ArrayList<>(); addToList( currentDir, currentDirFileList); //Arrays.asList(currentDir.listFiles()); //Collections.sort(currentDirFileList); for (int i = 0; i < currentDirFileList.size(); i++) { File file = currentDirFileList.get(i); if (file.equals(currentFile)) currentDirFileNo = i; } } if (forward) { currentDirFileNo++; if (currentDirFileNo >= currentDirFileList.size()) currentDirFileNo = 0; } else { currentDirFileNo--; if (currentDirFileNo < 0) currentDirFileNo = currentDirFileList.size()-1; } File nextFile = currentDirFileList.get(currentDirFileNo); try { System.out.println("Open image "+nextFile); return javax.imageio.ImageIO.read(nextFile); } catch (IOException e) { System.out.println("Failed to open image "+nextFile); return getNextImage( forward); } }
java
{ "resource": "" }
q174989
LibTypeFcns.size
test
static public int size(DapType type) { switch (type.getTypeSort()) { case Char: // remember serial size is 1, not 2. case UInt8: case Int8: return 1; case Int16: case UInt16: return 2; case Int32: case UInt32: case Float32: return 4; case Int64: case UInt64: case Float64: return 8; case Enum: return size(((DapEnumeration)type).getBaseType()); default: break; } return 0; }
java
{ "resource": "" }
q174990
FixedYearVariableMonthChronology.sumArray
test
private static int sumArray(int[] arr) { if (arr == null) throw new NullPointerException("null array"); if (arr.length == 0) throw new IllegalArgumentException("Zero-length array"); int sum = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] <= 0) { throw new IllegalArgumentException("All array values must be > 0"); } sum += arr[i]; } return sum; }
java
{ "resource": "" }
q174991
SpatialGrid.setGrid
test
public void setGrid( Rectangle2D bbox, double width, double height) { offsetX = bbox.getX(); offsetY = bbox.getY(); // number of grid cells countX = Math.min( nx, (int) (bbox.getWidth() / (scaleOverlap * width))); countY = Math.min( ny, (int) (bbox.getHeight() / (scaleOverlap * height))); gridWidth = bbox.getWidth() / countX; gridHeight = bbox.getHeight() / countY; if (debug) System.out.println("SpatialGrid size "+ gridWidth+" "+ gridHeight+" = "+countX+" by "+countY+ " scaleOverlap= "+ scaleOverlap); }
java
{ "resource": "" }
q174992
SpatialGrid.setOverlap
test
public void setOverlap(int overlap) { // overlap limited to [0, 50%] double dover = Math.max( 0.0, Math.min(.01*overlap, .50)); scaleOverlap = 1.0 - dover; }
java
{ "resource": "" }
q174993
SpatialGrid.clear
test
public void clear() { for (int y=0; y<countY; y++) for (int x=0; x<countX; x++) gridArray[y][x].used = false; }
java
{ "resource": "" }
q174994
SpatialGrid.markIfClear
test
public boolean markIfClear (Rectangle2D rect, Object o) { double centerX = rect.getX() + rect.getWidth()/2; double centerY = rect.getY() + rect.getHeight()/2; int indexX = (int) ((centerX-offsetX)/gridWidth); int indexY = (int) ((centerY-offsetY)/gridHeight); if (debugMark) System.out.println("markIfClear "+ rect+ " "+indexX+" "+indexY); if ((indexX < 0) || (indexX >= countX) || (indexY < 0) || (indexY >= countY)) // outside box return false; GridCell gwant = gridArray[indexY][indexX]; if (gwant.used) // already taken return false; if (null != findIntersection(rect)) return false; // its ok to use gwant.used = true; gwant.objectBB = rect; gwant.o = o; return true; }
java
{ "resource": "" }
q174995
SpatialGrid.findIntersection
test
public Object findIntersection (Rectangle2D rect) { double centerX = rect.getX() + rect.getWidth()/2; double centerY = rect.getY() + rect.getHeight()/2; int indexX = (int) ((centerX-offsetX)/gridWidth); int indexY = (int) ((centerY-offsetY)/gridHeight); // outside box if ((indexX < 0) || (indexX >= countX) || (indexY < 0) || (indexY >= countY)) return null; // check the surrounding points for (int y=Math.max(0,indexY-1); y<=Math.min(countY-1,indexY+1); y++) { for (int x=Math.max(0,indexX-1); x<=Math.min(countX-1,indexX+1); x++) { GridCell gtest = gridArray[y][x]; if (!gtest.used) continue; if (intersectsOverlap( rect, gtest.objectBB)) // hits an adjacent rectangle return gtest.o; } } return null; }
java
{ "resource": "" }
q174996
SpatialGrid.findIntersection
test
public Object findIntersection (Point2D p) { int indexX = (int) ((p.getX()-offsetX)/gridWidth); int indexY = (int) ((p.getY()-offsetY)/gridHeight); // outside box if ((indexX < 0) || (indexX >= countX) || (indexY < 0) || (indexY >= countY)) return null; // check the surrounding points for (int y=Math.max(0,indexY-1); y<=Math.min(countY-1,indexY+1); y++) { for (int x=Math.max(0,indexX-1); x<=Math.min(countX-1,indexX+1); x++) { GridCell gtest = gridArray[y][x]; if (!gtest.used) continue; if (gtest.objectBB.contains( p.getX(), p.getY())) return gtest.o; } } return null; }
java
{ "resource": "" }
q174997
SpatialGrid.findClosest
test
public Object findClosest(Point2D pt) { Object o = null; int indexX = (int) ((pt.getX()-offsetX)/gridWidth); int indexY = (int) ((pt.getY()-offsetY)/gridHeight); if (debugClosest) System.out.println("findClosest "+ pt+ " "+indexX+" "+indexY); if ((indexX < 0) || (indexX >= countX) || (indexY < 0) || (indexY >= countY)) // outside box return null; GridCell gwant = gridArray[indexY][indexX]; if (gwant.used) // that was easy return gwant.o; // check the surrounding points along perimeter of increasing diameter for (int p=1; p<Math.max(countX-1, countY-1); p++) if (null != (o = findClosestAlongPerimeter(pt, indexX, indexY, p))) return o; return null; // nothing found }
java
{ "resource": "" }
q174998
SpatialGrid.distanceSq
test
private double distanceSq( Point2D pt, int indexX, int indexY) { if ((indexX < 0) || (indexX >= countX) || (indexY < 0) || (indexY >= countY)) // outside bounding box return MAX_DOUBLE; GridCell gtest = gridArray[indexY][indexX]; if (!gtest.used) // nothing in this cell return MAX_DOUBLE; // get distance from center of cell Rectangle2D rect = gtest.objectBB; double dx = rect.getX()+rect.getWidth()/2 - pt.getX(); double dy = rect.getY()+rect.getHeight()/2 - pt.getY(); return (dx*dx + dy*dy); }
java
{ "resource": "" }
q174999
BaseUnit.getOrCreate
test
public static synchronized BaseUnit getOrCreate(final UnitName id, final BaseQuantity baseQuantity) throws NameException, UnitExistsException { BaseUnit baseUnit; final BaseUnit nameUnit = nameMap.get(id); final BaseUnit quantityUnit = quantityMap.get(baseQuantity); if (nameUnit != null || quantityUnit != null) { baseUnit = nameUnit != null ? nameUnit : quantityUnit; if ((nameUnit != null && !baseQuantity.equals(nameUnit .getBaseQuantity())) || (quantityUnit != null && !id.equals(quantityUnit .getUnitName()))) { throw new UnitExistsException( "Attempt to incompatibly redefine base unit \"" + baseUnit + '"'); } } else { baseUnit = new BaseUnit(id, baseQuantity); quantityMap.put(baseQuantity, baseUnit); nameMap.put(id, baseUnit); } return baseUnit; }
java
{ "resource": "" }