_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q174500
ErrorResponse.buildException
test
public DapException buildException() { String XML = buildXML(); DapException dapex = new DapException(XML).setCode(code); return dapex; }
java
{ "resource": "" }
q174501
AWIPSConvention.breakupLevels
test
private List<Dimension> breakupLevels(NetcdfDataset ds, Variable levelVar) throws IOException { if (debugBreakup) parseInfo.format("breakupLevels = %s%n", levelVar.getShortName()); List<Dimension> dimList = new ArrayList<>(); ArrayChar levelVarData; try { levelVarData = (ArrayChar) levelVar.read(); } catch (IOException ioe) { return dimList; } List<String> values = null; String currentUnits = null; ArrayChar.StringIterator iter = levelVarData.getStringIterator(); while (iter.hasNext()) { String s = iter.next(); if (debugBreakup) parseInfo.format(" %s%n", s); StringTokenizer stoke = new StringTokenizer(s); /* problem with blank string: char pvvLevels(levels_35=35, charsPerLevel=10); "MB 1000 ", "MB 975 ", "MB 950 ", "MB 925 ", "MB 900 ", "MB 875 ", "MB 850 ", "MB 825 ", "MB 800 ", "MB 775 ", "MB 750 ", "MB 725 ", "MB 700 ", "MB 675 ", "MB 650 ", "MB 625 ", "MB 600 ", "MB 575 ", "MB 550 ", "MB 525 ", "MB 500 ", "MB 450 ", "MB 400 ", "MB 350 ", "MB 300 ", "MB 250 ", "MB 200 ", "MB 150 ", "MB 100 ", "BL 0 30 ", "BL 60 90 ", "BL 90 120 ", "BL 120 150", "BL 150 180", "" */ if (!stoke.hasMoreTokens()) continue; // skip it // first token is the unit String units = stoke.nextToken().trim(); if (!units.equals(currentUnits)) { if (values != null) dimList.add(makeZCoordAxis(ds, values, currentUnits)); values = new ArrayList<>(); currentUnits = units; } // next token is the value if (stoke.hasMoreTokens()) values.add(stoke.nextToken()); else values.add("0"); } if (values != null) dimList.add(makeZCoordAxis(ds, values, currentUnits)); if (debugBreakup) parseInfo.format(" done breakup%n"); return dimList; }
java
{ "resource": "" }
q174502
AWIPSConvention.makeZCoordAxis
test
private Dimension makeZCoordAxis(NetcdfDataset ds, List<String> values, String units) throws IOException { int len = values.size(); String name = makeZCoordName(units); if (len > 1) name = name + Integer.toString(len); else name = name + values.get(0); StringUtil2.replace(name, ' ', "-"); Dimension dim; if (null != (dim = ds.getRootGroup().findDimension(name))) { if (dim.getLength() == len) { // check against actual values Variable coord = ds.getRootGroup().findVariable(name); Array coordData = coord.read(); Array newData = Array.makeArray(coord.getDataType(), values); if (MAMath.nearlyEquals(coordData, newData)) { if (debugBreakup) parseInfo.format(" use existing coord %s%n", dim); return dim; } } } String orgName = name; int count = 1; while (ds.getRootGroup().findDimension(name) != null) { name = orgName + "-" + count; count++; } // create new one dim = new Dimension(name, len); ds.addDimension(null, dim); if (debugBreakup) parseInfo.format(" make Dimension = %s length = %d%n", name, len); // if (len < 2) return dim; // skip 1D if (debugBreakup) { parseInfo.format(" make ZCoordAxis = = %s length = %d%n", name, len); } CoordinateAxis v = new CoordinateAxis1D(ds, null, name, DataType.DOUBLE, name, makeUnitsName(units), makeLongName(name)); String positive = getZisPositive(ds, v); if (null != positive) v.addAttribute(new Attribute(_Coordinate.ZisPositive, positive)); v.setValues(values); ds.addCoordinateAxis(v); parseInfo.format("Created Z Coordinate Axis = "); v.getNameAndDimensions(parseInfo, true, false); parseInfo.format("%n"); return dim; }
java
{ "resource": "" }
q174503
AWIPSConvention.createNewVariables
test
private void createNewVariables(NetcdfDataset ds, Variable ncVar, List<Dimension> newDims, Dimension levelDim) throws InvalidRangeException { List<Dimension> dims = ncVar.getDimensions(); int newDimIndex = dims.indexOf(levelDim); //String shapeS = ncVar.getShapeS(); int[] origin = new int[ncVar.getRank()]; int[] shape = ncVar.getShape(); int count = 0; for (Dimension dim : newDims) { String name = ncVar.getShortName() + "-" + dim.getShortName(); origin[newDimIndex] = count; shape[newDimIndex] = dim.getLength(); Variable varNew = ncVar.section(new Section(origin, shape)); varNew.setName(name); varNew.setDimension(newDimIndex, dim); // synthesize long name String long_name = ds.findAttValueIgnoreCase(ncVar, CDM.LONG_NAME, ncVar.getShortName()); long_name = long_name + "-" + dim.getShortName(); ds.addVariableAttribute(varNew, new Attribute(CDM.LONG_NAME, long_name)); ds.addVariable(null, varNew); parseInfo.format("Created New Variable as section = "); varNew.getNameAndDimensions(parseInfo, true, false); parseInfo.format("%n"); count += dim.getLength(); } }
java
{ "resource": "" }
q174504
AWIPSConvention.makeTimeCoordAxisFromReference
test
private CoordinateAxis makeTimeCoordAxisFromReference(NetcdfDataset ds, Variable timeVar, Array vals) { Variable refVar = ds.findVariable("reftime"); if (refVar == null) return null; double refValue; try { Array refArray = refVar.read(); refValue = refArray.getDouble(refArray.getIndex()); // get the first value } catch (IOException ioe) { return null; } if (refValue == N3iosp.NC_FILL_DOUBLE) return null; // construct the values array - make it a double to be safe Array dvals = Array.factory(DataType.DOUBLE, vals.getShape()); IndexIterator diter = dvals.getIndexIterator(); IndexIterator iiter = vals.getIndexIterator(); while (iiter.hasNext()) diter.setDoubleNext(iiter.getDoubleNext() + refValue); // add reftime to each of the values String units = ds.findAttValueIgnoreCase(refVar, CDM.UNITS, "seconds since 1970-1-1 00:00:00"); units = normalize(units); String desc = "synthesized time coordinate from reftime, valtimeMINUSreftime"; CoordinateAxis1D timeCoord = new CoordinateAxis1D(ds, null, "timeCoord", DataType.DOUBLE, "record", units, desc); timeCoord.setCachedData(dvals, true); parseInfo.format("Created Time Coordinate Axis From Reference = "); timeCoord.getNameAndDimensions(parseInfo, true, false); parseInfo.format("%n"); return timeCoord; }
java
{ "resource": "" }
q174505
GribToNetcdfWriter.bitShave
test
public static float bitShave(float value, int bitMask) { if (Float.isNaN(value)) return value; // ?? int bits = Float.floatToRawIntBits(value); int shave = bits & bitMask; return Float.intBitsToFloat(shave); }
java
{ "resource": "" }
q174506
GribToNetcdfWriter.main
test
public static void main(String[] args) { String fileIn = (args.length > 0) ? args[0] : "Q:/cdmUnitTest/formats/grib2/LMPEF_CLM_050518_1200.grb"; String fileOut = (args.length > 1) ? args[1] : "C:/tmp/ds.mint.bi"; try (GribToNetcdfWriter writer = new GribToNetcdfWriter(fileIn, fileOut)) { writer.write(); } catch (IOException e) { e.printStackTrace(); } }
java
{ "resource": "" }
q174507
NetcdfDataset.wrap
test
static public NetcdfDataset wrap(NetcdfFile ncfile, Set<Enhance> mode) throws IOException { if (ncfile instanceof NetcdfDataset) { NetcdfDataset ncd = (NetcdfDataset) ncfile; if (!ncd.enhanceNeeded(mode)) return (NetcdfDataset) ncfile; } // enhancement requires wrappping, to not modify underlying dataset, eg if cached // perhaps need a method variant that allows the ncfile to be modified return new NetcdfDataset(ncfile, mode); }
java
{ "resource": "" }
q174508
NetcdfDataset.openFile
test
public static NetcdfFile openFile(String location, ucar.nc2.util.CancelTask cancelTask) throws IOException { DatasetUrl durl = DatasetUrl.findDatasetUrl(location); return openOrAcquireFile(null, null, null, durl, -1, cancelTask, null); }
java
{ "resource": "" }
q174509
NetcdfDataset.clearCoordinateSystems
test
public void clearCoordinateSystems() { coordSys = new ArrayList<>(); coordAxes = new ArrayList<>(); coordTransforms = new ArrayList<>(); for (Variable v : getVariables()) { VariableEnhanced ve = (VariableEnhanced) v; ve.clearCoordinateSystems(); // ?? } enhanceMode.remove(Enhance.CoordSystems); }
java
{ "resource": "" }
q174510
NetcdfDataset.findCoordinateAxis
test
public CoordinateAxis findCoordinateAxis(AxisType type) { if (type == null) return null; for (CoordinateAxis v : coordAxes) { if (type == v.getAxisType()) return v; } return null; }
java
{ "resource": "" }
q174511
NetcdfDataset.findCoordinateAxis
test
public CoordinateAxis findCoordinateAxis(String fullName) { if (fullName == null) return null; for (CoordinateAxis v : coordAxes) { if (fullName.equals(v.getFullName())) return v; } return null; }
java
{ "resource": "" }
q174512
NetcdfDataset.findCoordinateSystem
test
public CoordinateSystem findCoordinateSystem(String name) { if (name == null) return null; for (CoordinateSystem v : coordSys) { if (name.equals(v.getName())) return v; } return null; }
java
{ "resource": "" }
q174513
NetcdfDataset.findCoordinateTransform
test
public CoordinateTransform findCoordinateTransform(String name) { if (name == null) return null; for (CoordinateTransform v : coordTransforms) { if (name.equals(v.getName())) return v; } return null; }
java
{ "resource": "" }
q174514
NetcdfDataset.enhanceNeeded
test
public boolean enhanceNeeded(Set<Enhance> want) throws IOException { if (want == null) return false; for (Enhance mode : want) { if (!this.enhanceMode.contains(mode)) return true; } return false; }
java
{ "resource": "" }
q174515
NetcdfDataset.setValues
test
public void setValues(Variable v, int npts, double start, double incr) { if (npts != v.getSize()) throw new IllegalArgumentException("bad npts = " + npts + " should be " + v.getSize()); Array data = Array.makeArray(v.getDataType(), npts, start, incr); if (v.getRank() != 1) data = data.reshape(v.getShape()); v.setCachedData(data, true); }
java
{ "resource": "" }
q174516
NetcdfDataset.setValues
test
public void setValues(Variable v, List<String> values) throws IllegalArgumentException { Array data = Array.makeArray(v.getDataType(), values); if (data.getSize() != v.getSize()) throw new IllegalArgumentException("Incorrect number of values specified for the Variable " + v.getFullName() + " needed= " + v.getSize() + " given=" + data.getSize()); if (v.getRank() != 1) // dont have to reshape for rank 1 data = data.reshape(v.getShape()); v.setCachedData(data, true); }
java
{ "resource": "" }
q174517
NetcdfDataset.makeArray
test
static public Array makeArray(DataType dtype, List<String> stringValues) throws NumberFormatException { return Array.makeArray(dtype, stringValues); }
java
{ "resource": "" }
q174518
Index.index
test
public long index() { long offset = 0; for(int i = 0; i < this.indices.length; i++) { offset *= this.dimsizes[i]; offset += this.indices[i]; } return offset; }
java
{ "resource": "" }
q174519
MFileOS7.getExistingFile
test
static public MFileOS7 getExistingFile(String filename) throws IOException { if (filename == null) return null; Path path = Paths.get(filename); if (Files.exists(path)) return new MFileOS7(path); return null; }
java
{ "resource": "" }
q174520
EsriShapefile.getFeatures
test
public List<EsriFeature> getFeatures(Rectangle2D bBox) { if (bBox == null) return features; List<EsriFeature> list = new ArrayList<>(); for (EsriFeature gf : features) { if (gf.getBounds2D().intersects(bBox)) list.add(gf); } return list; }
java
{ "resource": "" }
q174521
EsriShapefile.discretize
test
private void discretize(double[] d, int n) { if (coarseness == 0.0) return; for (int i = 0; i < n; i++) { d[i] = (Math.rint(resolution * d[i]) / resolution); } }
java
{ "resource": "" }
q174522
ThreddsMetadata.add
test
public void add(ThreddsMetadata tmd, boolean includeInherited) { creators.addAll(tmd.getCreators()); contributors.addAll(tmd.getContributors()); dates.addAll(tmd.getDates()); docs.addAll(tmd.getDocumentation()); keywords.addAll(tmd.getKeywords()); projects.addAll(tmd.getProjects()); properties.addAll(tmd.getProperties()); publishers.addAll(tmd.getPublishers()); variables.addAll(tmd.getVariables()); if (includeInherited) metadata.addAll(tmd.getMetadata()); else { for (InvMetadata mdata : tmd.getMetadata() ) { if (!mdata.isInherited()) metadata.add(mdata); } } // LOOK! should be copies ??!! if (gc == null) gc = tmd.getGeospatialCoverage(); if (timeCoverage == null) timeCoverage = tmd.getTimeCoverage(); if (serviceName == null) serviceName = tmd.getServiceName(); if (dataType == null) dataType = tmd.getDataType(); if (dataSize == 0.0) dataSize = tmd.getDataSize(); if (dataFormat == null) dataFormat = tmd.getDataFormatType(); if (authorityName == null) authorityName = tmd.getAuthority(); if (variableMapLink == null) variableMapLink = tmd.getVariableMap(); }
java
{ "resource": "" }
q174523
ThreddsMetadata.addDocumentation
test
public void addDocumentation(String type, String content) { if (content == null) { removeDocumentation(type); return; } content = content.trim(); for (InvDocumentation doc : getDocumentation()) { String dtype = doc.getType(); if ((dtype != null) && dtype.equalsIgnoreCase(type)) { doc.setInlineContent(content); return; } } if (content.length() > 0) addDocumentation(new InvDocumentation(null, null, null, type, content)); }
java
{ "resource": "" }
q174524
ThreddsMetadata.removeDocumentation
test
public void removeDocumentation(String type) { Iterator iter = docs.iterator(); while (iter.hasNext()) { InvDocumentation doc = (InvDocumentation) iter.next(); String dtype = doc.getType(); if ((dtype != null) && dtype.equalsIgnoreCase(type)) iter.remove(); } }
java
{ "resource": "" }
q174525
LayoutSegmented.getMaxBytes
test
private int getMaxBytes(long start) { int segno = 0; while (start >= segMax[segno]) segno++; return (int) (segMax[segno] - start); }
java
{ "resource": "" }
q174526
NsslRadarMosaicConvention.isMine
test
public static boolean isMine(NetcdfFile ncfile) { String cs = ncfile.findAttValueIgnoreCase(null, CDM.CONVENTIONS, null); if (cs != null) return false; String s = ncfile.findAttValueIgnoreCase(null, "DataType", null); if ((s == null) || !(s.equalsIgnoreCase("LatLonGrid") || s.equalsIgnoreCase("LatLonHeightGrid"))) return false; if ((null == ncfile.findGlobalAttribute("Latitude")) || (null == ncfile.findGlobalAttribute("Longitude")) || (null == ncfile.findGlobalAttribute("LatGridSpacing")) || (null == ncfile.findGlobalAttribute("LonGridSpacing")) || (null == ncfile.findGlobalAttribute("Time"))) return false; return !(null == ncfile.findDimension("Lat") || null == ncfile.findDimension("Lon")); }
java
{ "resource": "" }
q174527
CollectionManagerCatalog.getDataset
test
@Override public void getDataset(Dataset ds, Object context) { if (ds.hasAccess()) { DataFactory tdataFactory = new DataFactory(); Access access = tdataFactory.chooseDatasetAccess(ds.getAccess()); if (access == null) throw new IllegalStateException(); MFileRemote mfile = new MFileRemote(access); if (mfile.getPath().endsWith(".xml")) return; // eliminate latest.xml LOOK kludge-o-rama mfiles.add(mfile); if (debug) System.out.format("add %s %n", mfile.getPath()); } }
java
{ "resource": "" }
q174528
CoordSysBuilder.breakupConventionNames
test
static public List<String> breakupConventionNames(String convAttValue) { List<String> names = new ArrayList<>(); if ((convAttValue.indexOf(',') > 0) || (convAttValue.indexOf(';') > 0)) { StringTokenizer stoke = new StringTokenizer(convAttValue, ",;"); while (stoke.hasMoreTokens()) { String name = stoke.nextToken(); names.add(name.trim()); } } else if ((convAttValue.indexOf('/') > 0)) { StringTokenizer stoke = new StringTokenizer(convAttValue, "/"); while (stoke.hasMoreTokens()) { String name = stoke.nextToken(); names.add(name.trim()); } } else { StringTokenizer stoke = new StringTokenizer(convAttValue, " "); while (stoke.hasMoreTokens()) { String name = stoke.nextToken(); names.add(name.trim()); } } return names; }
java
{ "resource": "" }
q174529
CoordSysBuilder.buildConventionAttribute
test
static public String buildConventionAttribute(String mainConv, String... convAtts) { List<String> result = new ArrayList<>(); result.add(mainConv); for (String convs : convAtts) { if (convs == null) continue; List<String> ss = breakupConventionNames(convs); // may be a list for (String s : ss) { if (matchConvention(s) == null) // only add extra ones, not ones that compete with mainConv result.add(s); } } // now form comma separated result boolean start = true; Formatter f = new Formatter(); for (String s : result) { if (start) f.format("%s", s); else f.format(", %s", s); start = false; } return f.toString(); }
java
{ "resource": "" }
q174530
CoordSysBuilder.buildCoordinateSystems
test
@Override public void buildCoordinateSystems(NetcdfDataset ncDataset) { // put status info into parseInfo that can be shown to someone trying to debug this process parseInfo.format("Parsing with Convention = %s%n", conventionName); // Bookkeeping info for each variable is kept in the VarProcess inner class addVariables(ncDataset, ncDataset.getVariables(), varList); // identify which variables are coordinate axes findCoordinateAxes(ncDataset); // identify which variables are used to describe coordinate system findCoordinateSystems(ncDataset); // identify which variables are used to describe coordinate transforms findCoordinateTransforms(ncDataset); // turn Variables into CoordinateAxis objects makeCoordinateAxes(ncDataset); // make Coordinate Systems for all Coordinate Systems Variables makeCoordinateSystems(ncDataset); // assign explicit CoordinateSystem objects to variables assignCoordinateSystemsExplicit(ncDataset); // assign implicit CoordinateSystem objects to variables makeCoordinateSystemsImplicit(ncDataset); // optionally assign implicit CoordinateSystem objects to variables that dont have one yet if (useMaximalCoordSys) makeCoordinateSystemsMaximal(ncDataset); // make Coordinate Transforms makeCoordinateTransforms(ncDataset); // assign Coordinate Transforms assignCoordinateTransforms(ncDataset); if (debug) System.out.println("parseInfo = \n" + parseInfo.toString()); }
java
{ "resource": "" }
q174531
CoordSysBuilder.findCoordinateAxes
test
protected void findCoordinateAxes(NetcdfDataset ncDataset) { for (VarProcess vp : varList) { if (vp.coordAxes != null) findCoordinateAxes(vp, vp.coordAxes); if (vp.coordinates != null) findCoordinateAxes(vp, vp.coordinates); } }
java
{ "resource": "" }
q174532
CoordSysBuilder.findCoordinateSystems
test
protected void findCoordinateSystems(NetcdfDataset ncDataset) { for (VarProcess vp : varList) { if (vp.coordSys != null) { StringTokenizer stoker = new StringTokenizer(vp.coordSys); while (stoker.hasMoreTokens()) { String vname = stoker.nextToken(); VarProcess ap = findVarProcess(vname, vp); if (ap != null) { if (!ap.isCoordinateSystem) parseInfo.format(" CoordinateSystem = %s added; referenced from var= %s%n", vname, vp.v.getFullName()); ap.isCoordinateSystem = true; } else { parseInfo.format("***Cant find coordSystem %s referenced from var= %s%n", vname, vp.v.getFullName()); userAdvice.format("***Cant find coordSystem %s referenced from var= %s%n", vname, vp.v.getFullName()); } } } } }
java
{ "resource": "" }
q174533
CoordSysBuilder.makeCoordinateSystems
test
protected void makeCoordinateSystems(NetcdfDataset ncDataset) { for (VarProcess vp : varList) { if (vp.isCoordinateSystem) { vp.makeCoordinateSystem(); } } }
java
{ "resource": "" }
q174534
CoordSysBuilder.makeCoordinateSystemsMaximal
test
protected void makeCoordinateSystemsMaximal(NetcdfDataset ncDataset) { boolean requireCompleteCoordSys = !ncDataset.getEnhanceMode().contains(NetcdfDataset.Enhance.IncompleteCoordSystems); for (VarProcess vp : varList) { VariableEnhanced ve = (VariableEnhanced) vp.v; if (vp.hasCoordinateSystem() || !vp.isData()) continue; // look through all axes that fit List<CoordinateAxis> axisList = new ArrayList<>(); List<CoordinateAxis> axes = ncDataset.getCoordinateAxes(); for (CoordinateAxis axis : axes) { if (isCoordinateAxisForVariable(axis, ve)) axisList.add(axis); } if (axisList.size() < 2) continue; String csName = CoordinateSystem.makeName(axisList); CoordinateSystem cs = ncDataset.findCoordinateSystem(csName); boolean okToBuild = false; // do coordinate systems need to be complete? // default enhance mode is yes, they must be complete if (requireCompleteCoordSys) { if (cs != null) { // only build if coordinate system is complete okToBuild = cs.isComplete(ve); } } else { // coordinate system can be incomplete, so we're ok to build if we find something okToBuild = true; } if (cs != null && okToBuild) { ve.addCoordinateSystem(cs); parseInfo.format(" assigned maximal CoordSystem '%s' for var= %s%n", cs.getName(), ve.getFullName()); } else { CoordinateSystem csnew = new CoordinateSystem(ncDataset, axisList, null); // again, do coordinate systems need to be complete? // default enhance mode is yes, they must be complete if (requireCompleteCoordSys) { // only build if new coordinate system is complete okToBuild = csnew.isComplete(ve); } if (okToBuild) { csnew.setImplicit(true); ve.addCoordinateSystem(csnew); ncDataset.addCoordinateSystem(csnew); parseInfo.format(" created maximal CoordSystem '%s' for var= %s%n", csnew.getName(), ve.getFullName()); } } } }
java
{ "resource": "" }
q174535
CoordSysBuilder.isCoordinateAxisForVariable
test
protected boolean isCoordinateAxisForVariable(Variable axis, VariableEnhanced v) { List<Dimension> varDims = v.getDimensionsAll(); List<Dimension> axisDims = axis.getDimensionsAll(); // a CHAR variable must really be a STRING, so leave out the last (string length) dimension int checkDims = axisDims.size(); if (axis.getDataType() == DataType.CHAR) checkDims--; for (int i = 0; i < checkDims; i++) { Dimension axisDim = axisDims.get(i); if (!varDims.contains(axisDim)) { return false; } } return true; }
java
{ "resource": "" }
q174536
CoordSysBuilder.addCoordinateVariable
test
protected void addCoordinateVariable(Dimension dim, VarProcess vp) { List<VarProcess> list = coordVarMap.get(dim); if (list == null) { list = new ArrayList<>(); coordVarMap.put(dim, list); } if (!list.contains(vp)) list.add(vp); }
java
{ "resource": "" }
q174537
InvCatalogImpl.subset
test
public void subset(InvDataset ds) { InvDatasetImpl dataset = (InvDatasetImpl) ds; // Make all inherited metadata local. dataset.transferMetadata(dataset, true); topDataset = dataset; datasets.clear(); // throw away the rest datasets.add(topDataset); // parent lookups need to be local //InvService service = dataset.getServiceDefault(); //if (service != null) LOOK // dataset.serviceName = service.getName(); dataset.dataType = dataset.getDataType(); // all properties need to be local // LOOK dataset.setPropertiesLocal( new ArrayList(dataset.getProperties())); // next part requires this before it dataset.setCatalog(this); dataset.parent = null; // any referenced services need to be local List<InvService> services = new ArrayList<InvService>(dataset.getServicesLocal()); findServices(services, dataset); dataset.setServicesLocal(services); finish(); }
java
{ "resource": "" }
q174538
InvCatalogImpl.filter
test
public void filter(DatasetFilter filter) { mark(filter, topDataset); delete(topDataset); this.filter = filter; }
java
{ "resource": "" }
q174539
InvCatalogImpl.mark
test
private boolean mark(DatasetFilter filter, InvDatasetImpl ds) { if (ds instanceof InvCatalogRef) { InvCatalogRef catRef = (InvCatalogRef) ds; if (!catRef.isRead()) return false; } // recurse into nested datasets first boolean allMarked = true; for (InvDataset nested : ds.getDatasets()) { allMarked &= mark(filter, (InvDatasetImpl) nested); } if (!allMarked) return false; if (filter.accept(ds) >= 0) return false; // mark for deletion ds.setMark(true); if (debugFilter) System.out.println(" mark " + ds.getName()); return true; }
java
{ "resource": "" }
q174540
InvCatalogImpl.delete
test
private void delete(InvDatasetImpl ds) { if (ds instanceof InvCatalogRef) { InvCatalogRef catRef = (InvCatalogRef) ds; if (!catRef.isRead()) return; } Iterator iter = ds.getDatasets().iterator(); while (iter.hasNext()) { InvDatasetImpl nested = (InvDatasetImpl) iter.next(); if (nested.getMark()) { iter.remove(); if (debugFilter) System.out.println(" remove " + nested.getName()); } else delete(nested); } }
java
{ "resource": "" }
q174541
LoadCommon.initOnce
test
public void initOnce(HttpServletRequest req) throws SendError { if(once) return; once = true; log.info(getClass().getName() + " GET initialization"); if(this.tdsContext == null) throw new SendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot find TDS Context"); // Get server host + port name StringBuilder buf = new StringBuilder(); buf.append(req.getServerName()); int port = req.getServerPort(); if(port > 0) { buf.append(":"); buf.append(port); } this.server = buf.toString(); // Obtain servlet path info String tmp = HTTPUtil.canonicalpath(req.getContextPath()); this.threddsname = HTTPUtil.nullify(HTTPUtil.relpath(tmp)); tmp = HTTPUtil.canonicalpath(req.getServletPath()); this.requestname = HTTPUtil.nullify(HTTPUtil.relpath(tmp)); if(this.threddsname == null) this.threddsname = DEFAULTSERVLETNAME; // Get the upload dir File updir = tdsContext.getUploadDir(); if(updir == null) { log.warn("No tds.upload.dir specified"); this.uploaddir = null; } else this.uploaddir = HTTPUtil.canonicalpath(updir.getAbsolutePath()); // Get the download dir File downdir = tdsContext.getDownloadDir(); if(downdir == null) { log.warn("No tds.download.dir specified"); this.downloaddir = null; } else this.downloaddir = HTTPUtil.canonicalpath(downdir.getAbsolutePath()); }
java
{ "resource": "" }
q174542
Counters.count
test
public boolean count(String name, Comparable value) { Counter counter = map.get(name); if (counter == null) { counter = add(name); } return counter.count(value); }
java
{ "resource": "" }
q174543
StandardPrefixDB.add
test
private void add(final String name, final String symbol, final double definition) throws PrefixExistsException { addName(name, definition); addSymbol(symbol, definition); }
java
{ "resource": "" }
q174544
TableRowAbstract.compare
test
public int compare( TableRow other, int col) { String s1 = getValueAt(col).toString(); String s2 = other.getValueAt(col).toString(); int ret = s1.compareToIgnoreCase( s2); // break ties if (ret == 0) return compareTie( other, col); return ret; }
java
{ "resource": "" }
q174545
TableRowAbstract.compareBoolean
test
protected int compareBoolean(TableRow other, int col, boolean b1, boolean b2) { // break ties if (b1 == b2) return compareTie( other, col); return b1 ? 1 : -1; }
java
{ "resource": "" }
q174546
Dap4ParserImpl.getGroupScope
test
DapGroup getGroupScope() throws DapException { DapGroup gscope = (DapGroup) searchScope(DapSort.GROUP, DapSort.DATASET); if(gscope == null) throw new DapException("Undefined Group Scope"); return gscope; }
java
{ "resource": "" }
q174547
Dap4ParserImpl.passReserved
test
void passReserved(XMLAttributeMap map, DapNode node) throws ParseException { try { DapAttribute attr = null; for(Map.Entry<String, SaxEvent> entry : map.entrySet()) { SaxEvent event = entry.getValue(); String key = entry.getKey(); String value = event.value; if(isReserved(key)) node.addXMLAttribute(key,value); } } catch (DapException de) { throw new ParseException(de); } }
java
{ "resource": "" }
q174548
TimeParamsValidator.hasValidDateRange
test
private boolean hasValidDateRange(String time_start, String time_end, String time_duration) { // no range if ((null == time_start) && (null == time_end) && (null == time_duration)) return false; if ((null != time_start) && (null != time_end)) return true; if ((null != time_start) && (null != time_duration)) return true; if ((null != time_end) && (null != time_duration)) return true; // misformed range // errs.append("Must have 2 of 3 parameters: time_start, time_end, time_duration\n"); return false; }
java
{ "resource": "" }
q174549
SliceIterator.hasNext
test
@Override public boolean hasNext() { switch (state) { case INITIAL: return (slice.getFirst() < slice.getStop()); case STARTED: return (this.index < slice.getLast()); case DONE: } return false; }
java
{ "resource": "" }
q174550
DSPRegistry.register
test
synchronized public void register(String className, boolean last) throws DapException { try { Class<? extends DSP> klass = (Class<? extends DSP>) loader.loadClass(className); register(klass, last); } catch (ClassNotFoundException e) { throw new DapException(e); } }
java
{ "resource": "" }
q174551
DSPRegistry.register
test
synchronized public void register(Class<? extends DSP> klass, boolean last) { // is this already defined? if(registered(klass)) return; if(last) registry.add(new Registration(klass)); else registry.add(0, new Registration(klass)); }
java
{ "resource": "" }
q174552
DSPRegistry.registered
test
synchronized public boolean registered(Class<? extends DSP> klass) { for(Registration r : registry) { if(r.dspclass == klass) return true; } return false; }
java
{ "resource": "" }
q174553
DSPRegistry.unregister
test
synchronized public void unregister(Class<? extends DSP> klass) { for(int i = 0; i < registry.size(); i++) { if(registry.get(i).dspclass == klass) { registry.remove(i); break; } } }
java
{ "resource": "" }
q174554
Grib2Tables.factory
test
public static Grib2Tables factory(int center, int subCenter, int masterVersion, int localVersion, int genProcessId) { Grib2TablesId id = new Grib2TablesId(center, subCenter, masterVersion, localVersion, genProcessId); Grib2Tables cust = tables.get(id); if (cust != null) return cust; // note that we match on id, so same Grib2Customizer may be mapped to multiple id's (eg match on -1) Grib2TableConfig config = Grib2TableConfig.matchTable(id); cust = build(config); tables.put(id, cust); return cust; }
java
{ "resource": "" }
q174555
Grib2Tables.getForecastTimeIntervalSizeInHours
test
public double getForecastTimeIntervalSizeInHours(Grib2Pds pds) { Grib2Pds.PdsInterval pdsIntv = (Grib2Pds.PdsInterval) pds; int timeUnitOrg = pds.getTimeUnit(); // calculate total "range" in units of timeUnit int range = 0; for (Grib2Pds.TimeInterval ti : pdsIntv.getTimeIntervals()) { if (ti.timeRangeUnit == 255) continue; if ((ti.timeRangeUnit != timeUnitOrg) || (ti.timeIncrementUnit != timeUnitOrg && ti.timeIncrementUnit != 255 && ti.timeIncrement != 0)) { logger.warn("TimeInterval(2) has different units timeUnit org=" + timeUnitOrg + " TimeInterval=" + ti.timeIncrementUnit); throw new RuntimeException("TimeInterval(2) has different units"); } range += ti.timeRangeLength; if (ti.timeIncrementUnit != 255) range += ti.timeIncrement; } // now convert that range to units of the requested period. CalendarPeriod timeUnitPeriod = Grib2Utils.getCalendarPeriod(convertTimeUnit(timeUnitOrg)); if (timeUnitPeriod == null) return GribNumbers.UNDEFINEDD; if (timeUnitPeriod.equals(CalendarPeriod.Hour)) return range; double fac; if (timeUnitPeriod.getField() == CalendarPeriod.Field.Month) { fac = 30.0 * 24.0; // nominal hours in a month } else if (timeUnitPeriod.getField() == CalendarPeriod.Field.Year) { fac = 365.0 * 24.0; // nominal hours in a year } else { fac = CalendarPeriod.Hour.getConvertFactor(timeUnitPeriod); } return fac * range; }
java
{ "resource": "" }
q174556
Grib2Tables.getForecastTimeIntervalOffset
test
@Nullable public int[] getForecastTimeIntervalOffset(Grib2Record gr) { TimeCoordIntvDateValue tinvd = getForecastTimeInterval(gr); if (tinvd == null) return null; Grib2Pds pds = gr.getPDS(); int unit = convertTimeUnit(pds.getTimeUnit()); TimeCoordIntvValue tinv = tinvd.convertReferenceDate(gr.getReferenceDate(), Grib2Utils.getCalendarPeriod(unit)); if (tinv == null) return null; int[] result = new int[2]; result[0] = tinv.getBounds1(); result[1] = tinv.getBounds2(); return result; }
java
{ "resource": "" }
q174557
Grib2Tables.getVertUnit
test
@Override public VertCoordType getVertUnit(int code) { // VertCoordType(int code, String desc, String abbrev, String units, String datum, boolean isPositiveUp, boolean isLayer) switch (code) { case 11: case 12: return new VertCoordType(code, "m", null, true); case 20: return new VertCoordType(code, "K", null, false); case 100: return new VertCoordType(code, "Pa", null, false); case 102: return new VertCoordType(code, "m", "mean sea level", true); case 103: return new VertCoordType(code, "m", "ground", true); case 104: case 105: return new VertCoordType(code, "sigma", null, false); // positive? case 106: return new VertCoordType(code, "m", "land surface", false); case 107: return new VertCoordType(code, "K", null, true); // positive? case 108: return new VertCoordType(code, "Pa", "ground", true); case 109: return new VertCoordType(code, "K m2 kg-1 s-1", null, true); // positive? case 114: return new VertCoordType(code, "numeric", null, false); case 117: return new VertCoordType(code, "m", null, true); case 119: return new VertCoordType(code, "Pa", null, false); // ?? case 160: return new VertCoordType(code, "m", "sea level", false); case 161: return new VertCoordType(code, "m", "water surface", false); // LOOK NCEP specific case 235: return new VertCoordType(code, "0.1 C", null, true); case 237: return new VertCoordType(code, "m", null, true); case 238: return new VertCoordType(code, "m", null, true); default: return new VertCoordType(code, null, null, true); } }
java
{ "resource": "" }
q174558
DapDataset.finish
test
public void finish() { if(this.finished) return; if(this.ce == null) this.visiblenodes = nodelist; else { this.visiblenodes = new ArrayList<DapNode>(nodelist.size()); for(int i = 0; i < nodelist.size(); i++) { DapNode node = nodelist.get(i); if(ce.references(node)) visiblenodes.add(node); } } this.topvariables = new ArrayList<DapVariable>(); this.allvariables = new ArrayList<DapVariable>(); this.allgroups = new ArrayList<DapGroup>(); this.allenums = new ArrayList<DapEnumeration>(); this.allcompounds = new ArrayList<DapStructure>(); this.alldimensions = new ArrayList<DapDimension>(); finishR(this); }
java
{ "resource": "" }
q174559
DapDataset.sort
test
public void sort() { List<DapNode> sorted = new ArrayList<DapNode>(); sortR(this, sorted); // Assign indices for(int i = 0; i < sorted.size(); i++) { sorted.get(i).setIndex(i); } this.nodelist = sorted; }
java
{ "resource": "" }
q174560
PartitionCollectionImmutable.getRaf
test
RandomAccessFile getRaf(int partno, int fileno) throws IOException { Partition part = getPartition(partno); try (GribCollectionImmutable gc = part.getGribCollection()) { return gc.getDataRaf(fileno); } }
java
{ "resource": "" }
q174561
Evaluator.findVariableWithAttribute
test
static public VarAtt findVariableWithAttribute(NetcdfDataset ds, String attName) { for (Variable v : ds.getVariables()) { Attribute att = v.findAttributeIgnoreCase(attName); if (att != null) return new VarAtt(v, att); } // descend into structures for (Variable v : ds.getVariables()) { if (v instanceof Structure) { Structure s = (Structure) v; for (Variable vs : s.getVariables()) { Attribute att = vs.findAttributeIgnoreCase(attName); if (att != null) return new VarAtt(vs, att); } } } return null; }
java
{ "resource": "" }
q174562
Evaluator.findVariableWithAttributeValue
test
static public Variable findVariableWithAttributeValue(NetcdfDataset ds, String attName, String attValue) { for (Variable v : ds.getVariables()) { String haveValue = ds.findAttValueIgnoreCase(v, attName, null); if ((haveValue != null) && haveValue.equals(attValue)) return v; } // descend into structures for (Variable v : ds.getVariables()) { if (v instanceof Structure) { Variable vn = findVariableWithAttributeValue((Structure) v, attName, attValue); if (null != vn) return vn; } } return null; }
java
{ "resource": "" }
q174563
Evaluator.findNameOfVariableWithAttributeValue
test
static public String findNameOfVariableWithAttributeValue(NetcdfDataset ds, String attName, String attValue) { Variable v = findVariableWithAttributeValue(ds, attName, attValue); return (v == null) ? null : v.getShortName(); }
java
{ "resource": "" }
q174564
Evaluator.findVariableWithAttributeValue
test
static public Variable findVariableWithAttributeValue(Structure struct, String attName, String attValue) { for (Variable v : struct.getVariables()) { Attribute att = v.findAttributeIgnoreCase(attName); if ((att != null) && att.getStringValue().equals(attValue)) return v; } return null; }
java
{ "resource": "" }
q174565
Evaluator.findNestedStructure
test
static public Structure findNestedStructure(Structure s) { for (Variable v : s.getVariables()) { if ((v instanceof Structure)) return (Structure) v; } return null; }
java
{ "resource": "" }
q174566
Evaluator.hasNetcdf3RecordStructure
test
static public boolean hasNetcdf3RecordStructure(NetcdfDataset ds) { Variable v = ds.findVariable("record"); return (v != null) && (v.getDataType() == DataType.STRUCTURE); }
java
{ "resource": "" }
q174567
Evaluator.getLiteral
test
static public String getLiteral(NetcdfDataset ds, String key, Formatter errlog) { if (key.startsWith(":")) { String val = ds.findAttValueIgnoreCase(null, key.substring(1), null); if ((val == null) && (errlog != null)) errlog.format(" Cant find global attribute %s%n", key); return val; } return key; }
java
{ "resource": "" }
q174568
Evaluator.getFeatureType
test
static public FeatureType getFeatureType(NetcdfDataset ds, String key, Formatter errlog) { FeatureType ft = null; String fts = getLiteral(ds, key, errlog); if (fts != null) { ft = FeatureType.valueOf(fts.toUpperCase()); if ((ft == null) && (errlog != null)) errlog.format(" Cant find Feature type %s from %s%n", fts, key); } return ft; }
java
{ "resource": "" }
q174569
Evaluator.getVariableName
test
static public String getVariableName(NetcdfDataset ds, String key, Formatter errlog) { Variable v = null; String vs = getLiteral(ds, key, errlog); if (vs != null) { v = ds.findVariable(vs); if ((v == null) && (errlog != null)) errlog.format(" Cant find Variable %s from %s%n", vs, key); } return v == null ? null : v.getShortName(); }
java
{ "resource": "" }
q174570
CoordinateAxis2D.getCoordValue
test
public double getCoordValue(int j, int i) { if (coords == null) doRead(); return coords.get(j, i); }
java
{ "resource": "" }
q174571
CoordinateAxis2D.connectLon
test
static private double connectLon(double connect, double val) { if (Double.isNaN(connect)) return val; if (Double.isNaN(val)) return val; double diff = val - connect; if (Math.abs(diff) < MAX_JUMP) return val; // common case fast // we have to add or subtract 360 double result = diff > 0 ? val - 360 : val + 360; double diff2 = connect - result; if ((Math.abs(diff2)) < Math.abs(diff)) val = result; return val; }
java
{ "resource": "" }
q174572
CoordinateAxis2D.getCoordValues
test
public double[] getCoordValues() { if (coords == null) doRead(); if (!isNumeric()) throw new UnsupportedOperationException("CoordinateAxis2D.getCoordValues() on non-numeric"); return (double[]) coords.get1DJavaArray(DataType.DOUBLE); }
java
{ "resource": "" }
q174573
CoordinateAxis2D.section
test
public CoordinateAxis2D section(Range r1, Range r2) throws InvalidRangeException { List<Range> section = new ArrayList<>(); section.add(r1); section.add(r2); return (CoordinateAxis2D) section(section); }
java
{ "resource": "" }
q174574
CoordinateAxis2D.findClosest
test
private int findClosest(ArrayDouble.D2 boundsForRun , double target) { double minDiff = Double.MAX_VALUE; int idxFound = -1; int n = boundsForRun.getShape()[0]; for (int i = 0; i < n; i++) { double midpoint = (boundsForRun.get(i,0) + boundsForRun.get(i,1))/2.0; double diff = Math.abs(midpoint - target); if (diff < minDiff) { minDiff = diff; idxFound = i; } } return idxFound; }
java
{ "resource": "" }
q174575
CDMNode.getName
test
@Deprecated public String getName() { switch (sort) { case ATTRIBUTE: case DIMENSION: case ENUMERATION: // for these cases, getName is getShortName return getShortName(); case VARIABLE: // Atomic case SEQUENCE: case STRUCTURE: case GROUP: // for these cases, getName is getFullName return getFullName(); default: break; } return getShortName(); // default }
java
{ "resource": "" }
q174576
PopupMenu.addAction
test
public void addAction( String menuName, Action act) { act.putValue( Action.NAME, menuName); super.add(act); }
java
{ "resource": "" }
q174577
PathMatcher.match
test
public Match match( String path) { SortedMap<String, Match> tail = treeMap.tailMap( path); if (tail.isEmpty()) return null; String after = tail.firstKey(); //System.out.println(" "+path+"; after="+afterPath); if (path.startsWith( after)) // common case return treeMap.get( after); // have to check more, until no common starting chars for (String key : tail.keySet()) { if (path.startsWith(key)) return treeMap.get(key); // terminate when there's no match at all. if (StringUtil2.match(path, key) == 0) break; } return null; }
java
{ "resource": "" }
q174578
ProjectionManager.main
test
public static void main(String[] args) { ProjectionManager d = new ProjectionManager(null, null); d.setVisible(); }
java
{ "resource": "" }
q174579
KMPMatch.indexOf
test
public int indexOf(byte[] data, int start, int max) { int j = 0; if (data.length == 0) return -1; if (start + max > data.length) System.out.println("HEY KMPMatch"); for (int i = start; i < start + max; i++) { while (j > 0 && match[j] != data[i]) j = failure[j - 1]; if (match[j] == data[i]) j++; if (j == match.length) return i - match.length + 1; } return -1; }
java
{ "resource": "" }
q174580
PictureCache.add
test
public static synchronized void add( URL url, SourcePicture sp ) { Tools.log("PictureCache.add: " + url.toString() ); if ( sp.getSourceBufferedImage() == null ) { Tools.log ("PictureCache.add: invoked with a null picture! Not cached!"); return; } if ( ( maxCache < 1 ) ) { Tools.log("PictureCache.add: cache is diabled. Not adding picture."); return; } if ( isInCache( url ) ) { Tools.log( "Picture " + url.toString() + " is already in the cache. Not adding again."); return; } if ( pictureCache.size() >= maxCache ) removeLeastPopular(); if ( pictureCache.size() < maxCache ) pictureCache.put( url.toString(), sp ); //reportCache(); }
java
{ "resource": "" }
q174581
PictureCache.reportCache
test
public static synchronized void reportCache() { Tools.log(" PictureCache.reportCache: cache contains: " + Integer.toString( pictureCache.size() ) + " max: " + Integer.toString( maxCache ) ); //Tools.freeMem(); Enumeration e = pictureCache.keys(); while ( e.hasMoreElements() ) { Tools.log(" Cache contains: " + ((String) e.nextElement()) ); } Tools.log(" End of cache contents"); }
java
{ "resource": "" }
q174582
PictureCache.stopBackgroundLoading
test
public static void stopBackgroundLoading() { Enumeration e = cacheLoadsInProgress.elements(); while ( e.hasMoreElements() ) { ((SourcePicture) e.nextElement()).stopLoading(); } }
java
{ "resource": "" }
q174583
PictureCache.stopBackgroundLoadingExcept
test
public static boolean stopBackgroundLoadingExcept( URL exemptionURL ) { SourcePicture sp; String exemptionURLString = exemptionURL.toString(); Enumeration e = cacheLoadsInProgress.elements(); boolean inProgress = false; while ( e.hasMoreElements() ) { sp = ((SourcePicture) e.nextElement()); if ( ! sp.getUrlString().equals( exemptionURLString ) ) sp.stopLoading(); else { Tools.log( "PictureCache.stopBackgroundLoading: picture was already loading"); inProgress = true; } } return inProgress; }
java
{ "resource": "" }
q174584
HTTPFactory.Get
test
static public HTTPMethod Get(HTTPSession session, String legalurl) throws HTTPException { return makemethod(HTTPSession.Methods.Get, session, legalurl); }
java
{ "resource": "" }
q174585
HTTPFactory.makemethod
test
static protected HTTPMethod makemethod(HTTPSession.Methods m, HTTPSession session, String url) throws HTTPException { HTTPMethod meth = null; if(MOCKMETHODCLASS == null) { // do the normal case meth = new HTTPMethod(m, session, url); } else {//(MOCKMETHODCLASS != null) java.lang.Class methodcl = MOCKMETHODCLASS; Constructor<HTTPMethod> cons = null; try { cons = methodcl.getConstructor(HTTPSession.Methods.class, HTTPSession.class, String.class); } catch (Exception e) { throw new HTTPException("HTTPFactory: no proper HTTPMethod constructor available", e); } try { meth = cons.newInstance(m, session, url); } catch (Exception e) { throw new HTTPException("HTTPFactory: HTTPMethod constructor failed", e); } } return meth; }
java
{ "resource": "" }
q174586
RandomValue.nextFloat
test
public Object nextFloat(DapType basetype) throws DapException { TypeSort atomtype = basetype.getTypeSort(); switch (atomtype) { case Float32: return new float[]{random.nextFloat()}; case Float64: return new double[]{random.nextDouble()}; default: break; } throw new DapException("Unexpected type: " + basetype); }
java
{ "resource": "" }
q174587
RandomValue.nextCount
test
public int nextCount(int max) throws DapException { int min = 1; if(max < min || min < 1) throw new DapException("bad range"); int range = (max + 1) - min; // min..max+1 -> 0..(max+1)-min int n = random.nextInt(range); // 0..(max+1)-min n = n + min; // min..(max+1) if(DEBUG) System.err.println("RandomValue.nextCount: " + n); return n; }
java
{ "resource": "" }
q174588
DapNetcdfFile.readData
test
@Override protected Array readData(Variable cdmvar, Section section) throws IOException, InvalidRangeException { // The section is applied wrt to the DataDMR, so it // takes into account any constraint used in forming the dataDMR. // We use the Section to produce a view of the underlying variable array. assert this.dsp != null; Array result = arraymap.get(cdmvar); if(result == null) throw new IOException("No data for variable: " + cdmvar.getFullName()); if(section != null) { if(cdmvar.getRank() != section.getRank()) throw new InvalidRangeException(String.format("Section rank != %s rank", cdmvar.getFullName())); List<Range> ranges = section.getRanges(); // Case out the possibilities if(CDMUtil.hasVLEN(ranges)) { ranges = ranges.subList(0, ranges.size() - 1);// may produce empty list } if(ranges.size() > 0 && !CDMUtil.isWhole(ranges, cdmvar)) result = result.sectionNoReduce(ranges); } return result; }
java
{ "resource": "" }
q174589
RadarServerConfig.getProvider
test
private static FileSystemProvider getProvider(URI uri) throws IOException { if(fsproviders.containsKey(uri.getScheme())) { return fsproviders.get(uri.getScheme()); } else { FileSystem fs; try { fs = FileSystems.newFileSystem(uri, new HashMap<String, Object>(), Thread.currentThread().getContextClassLoader()); } catch (FileSystemAlreadyExistsException e) { fs = FileSystems.getFileSystem(uri); } fsproviders.put(uri.getScheme(), fs.provider()); return fs.provider(); } }
java
{ "resource": "" }
q174590
NexradStationDB.readStationTable
test
private static void readStationTable() throws IOException { stationTableHash = new HashMap<String,Station>(); ClassLoader cl = Level2VolumeScan.class.getClassLoader(); InputStream is = cl.getResourceAsStream("resources/nj22/tables/nexrad.tbl"); List<TableParser.Record> recs = TableParser.readTable(is, "3,15,46, 54,60d,67d,73d", 50000); for (TableParser.Record record : recs) { Station s = new Station(); s.id = "K" + record.get(0); s.name = record.get(2) + " " + record.get(3); s.lat = (Double) record.get(4) * .01; s.lon = (Double) record.get(5) * .01; s.elev = (Double) record.get(6); stationTableHash.put(s.id, s); if (showStations) System.out.println(" station= " + s); } }
java
{ "resource": "" }
q174591
CoordinateBuilderImpl.getIndex
test
@Override public int getIndex(T gr) { Integer result = valMap.get( extract(gr)); return (result == null) ? 0 : result; }
java
{ "resource": "" }
q174592
TypedDatasetImpl.removeDataVariable
test
protected void removeDataVariable( String varName) { Iterator iter = dataVariables.iterator(); while (iter.hasNext()) { VariableSimpleIF v = (VariableSimpleIF) iter.next(); if (v.getShortName().equals( varName) ) iter.remove(); } }
java
{ "resource": "" }
q174593
MetarParseReport.cloud_hgt2_meters
test
private String cloud_hgt2_meters(String height) { if (height.equals("999")) { return "30000"; } else { // $meters = 30 * $height ; return Integer.toString(30 * Integer.parseInt(height)); } }
java
{ "resource": "" }
q174594
ProxyReader2D.reallyRead
test
@Override public Array reallyRead(Variable mainv, Section section, CancelTask cancelTask) throws IOException, InvalidRangeException { FmrcInvLite.Gridset.Grid gridLite = (FmrcInvLite.Gridset.Grid) mainv.getSPobject(); // read the original type - if its been promoted to a new type, the conversion happens after this read DataType dtype = (mainv instanceof VariableDS) ? ((VariableDS) mainv).getOriginalDataType() : mainv.getDataType(); Array allData = Array.factory(dtype, section.getShape()); int destPos = 0; // assumes the first two dimensions are runtime and time: LOOK: ensemble ?? List<Range> ranges = section.getRanges(); Range runRange = ranges.get(0); Range timeRange = ranges.get(1); List<Range> innerSection = ranges.subList(2, ranges.size()); // keep track of open file - must be local variable for thread safety HashMap<String, NetcdfDataset> openFilesRead = new HashMap<>(); try { // iterate over the desired runs for (int runIdx : runRange) { //Date runDate = vstate.runTimes.get(runIdx); // iterate over the desired forecast times for (int timeIdx : timeRange) { Array result = null; // find the inventory for this grid, runtime, and hour TimeInventory.Instance timeInv = gridLite.getInstance(runIdx, timeIdx); if (timeInv != null) { if (debugRead) System.out.printf("HIT %d %d ", runIdx, timeIdx); result = read(timeInv, gridLite.name, innerSection, openFilesRead); // may return null result = MAMath.convert(result, dtype); // just in case it need to be converted } // missing data if (result == null) { int[] shape = new Section(innerSection).getShape(); result = ((VariableDS) mainv).getMissingDataArray(shape); // fill with missing values if (debugRead) System.out.printf("MISS %d %d ", runIdx, timeIdx); } if (debugRead) System.out.printf("%d %d reallyRead %s %d bytes start at %d total size is %d%n", runIdx, timeIdx, mainv.getFullName(), result.getSize(), destPos, allData.getSize()); Array.arraycopy(result, 0, allData, destPos, (int) result.getSize()); destPos += result.getSize(); } } return allData; } finally { // close any files used during this operation closeAll(openFilesRead); } }
java
{ "resource": "" }
q174595
ColorScale.setNumColors
test
public void setNumColors(int n) { if (n != ncolors) { colors = new Color[n]; int prevn = Math.min(ncolors, n); System.arraycopy(useColors, 0, colors, 0, prevn); for (int i = ncolors; i < n; i++) colors[i] = Color.white; useColors = colors; ncolors = n; edge = new double[ ncolors]; hist = new int[ ncolors + 1]; } }
java
{ "resource": "" }
q174596
ScaledPanel.calcTransform
test
private AffineTransform calcTransform(Rectangle2D screen, Bounds world) { // scale to limiting dimension double xs = screen.getWidth() / (world.getRight() - world.getLeft()); double ys = screen.getHeight() / (world.getLower() - world.getUpper()); AffineTransform cat = new AffineTransform(); cat.setToScale(xs, ys); cat.translate(-world.getLeft(), -world.getUpper()); if (debugTransform) { System.out.println("TPanel calcTransform = "); System.out.println(" screen = " + screen); System.out.println(" world = " + world); System.out.println(" transform = " + cat.getScaleX() + " " + cat.getShearX() + " " + cat.getTranslateX()); System.out.println(" " + cat.getShearY() + " " + cat.getScaleY() + " " + cat.getTranslateY()); Point2D src = new Point2D.Double(world.getLeft(), world.getUpper()); Point2D dst = new Point2D.Double(0.0, 0.0); System.out.println(" upper left pt = " + src); System.out.println(" transform = " + cat.transform(src, dst)); src = new Point2D.Double(world.getRight(), world.getLower()); System.out.println(" lower right pt = " + src); System.out.println(" transform = " + cat.transform(src, dst)); } return cat; }
java
{ "resource": "" }
q174597
HTTPAuthUtil.uriToAuthScope
test
static AuthScope uriToAuthScope(URI uri) { assert (uri != null); return new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, uri.getScheme()); }
java
{ "resource": "" }
q174598
GridIndex.finish
test
public void finish() { if (gcs.size() == 1) return; if (gcs.size() == 2) { List hcs = getHorizCoordSys(); GridDefRecord.compare((GridDefRecord) hcs.get(0), (GridDefRecord) hcs.get(1)); } }
java
{ "resource": "" }
q174599
Factor.isReciprocalOf
test
public boolean isReciprocalOf(final Factor that) { return getBase().equals(that.getBase()) && getExponent() == -that.getExponent(); }
java
{ "resource": "" }