_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q174600
DirectoryScanner.getDirCatalog
test
public InvCatalog getDirCatalog( File directory, String filterPattern, boolean sortInIncreasingOrder, boolean addDatasetSize ) { return( this.getDirCatalog( directory, filterPattern, sortInIncreasingOrder, null, addDatasetSize, null, null, null) ); }
java
{ "resource": "" }
q174601
SmartArrayInt.findIdx
test
public int findIdx(int want) { if (isConstant) return (want == start) ? 0 : -1; if (isSequential) return want - start; if (isSorted) { return Arrays.binarySearch(raw, want); } // linear search for (int i=0; i<raw.length; i++) if (raw[i] == want) return i; return -1; }
java
{ "resource": "" }
q174602
CatGenConfigMetadataFactory.readMetadataContentFromURL
test
private Object readMetadataContentFromURL( InvDataset dataset, String urlString) throws java.net.MalformedURLException, java.io.IOException { // @todo This isn't used anywhere. Remove? Document doc; try { SAXBuilder builder = new SAXBuilder( true); doc = builder.build( urlString); } catch ( JDOMException e) { log.error( "CatGenConfigMetadataFactory parsing error= \n" + e.getMessage()); throw new java.io.IOException( "CatGenConfigMetadataFactory parsing error= " + e.getMessage()); } if (showParsedXML) { XMLOutputter xmlOut = new XMLOutputter( Format.getPrettyFormat() ); System.out.println ("*** catalog/showParsedXML = \n"+xmlOut.outputString(doc)+"\n*******"); } return( readMetadataContentJdom( dataset, doc.getRootElement())); }
java
{ "resource": "" }
q174603
CatGenConfigMetadataFactory.readMetadataContent
test
public Object readMetadataContent( InvDataset dataset, org.jdom2.Element mdataElement ) { log.debug( "readMetadataContent(): ." ); // convert to JDOM element //Element mdataElement = builder.build( mdataDomElement ); return readMetadataContentJdom( dataset, mdataElement ); }
java
{ "resource": "" }
q174604
CatGenConfigMetadataFactory.addMetadataContent
test
public void addMetadataContent( org.jdom2.Element mdataJdomElement, Object contentObject ) { // convert to JDOM element //Element mdataJdomElement = builder.build( mdataElement ); ArrayList catGenConfigList = (ArrayList) contentObject; Iterator iter = catGenConfigList.iterator(); while ( iter.hasNext()) { CatalogGenConfig cgc = (CatalogGenConfig) iter.next(); mdataJdomElement.addContent( createCatGenConfigElement( cgc)); } }
java
{ "resource": "" }
q174605
CatGenConfigMetadataFactory.validateMetadataContent
test
public boolean validateMetadataContent( Object contentObject, StringBuilder out) { boolean ok = true; ArrayList catGenConfigList = (ArrayList) contentObject; Iterator iter = catGenConfigList.iterator(); while ( iter.hasNext()) { CatalogGenConfig catGenConf = (CatalogGenConfig) iter.next(); ok &= catGenConf.validate( out); } return ok; }
java
{ "resource": "" }
q174606
CatGenConfigMetadataFactory.readCatGenConfigElement
test
private CatalogGenConfig readCatGenConfigElement( InvDataset parentDataset, Element catGenConfElement) { String type = catGenConfElement.getAttributeValue("type"); CatalogGenConfig catGenConf = new CatalogGenConfig( parentDataset, type); // get any datasetSource elements java.util.List list = catGenConfElement.getChildren( "datasetSource", catGenConfElement.getNamespace() ); for (int i=0; i< list.size(); i++) { Element dsSourceElement = (Element) list.get(i); catGenConf.setDatasetSource( readDatasetSourceElement( parentDataset, dsSourceElement)); } // @todo Start only allowing datasetSource elements in catalogGenConfig elements. // // get any datasetNamer elements // list = catGenConfElement.getChildren( "datasetNamer", catGenConfElement.getNamespace() ); // for (int i=0; i< list.size(); i++) // { // Element dsNamerElement = (Element) list.get(i); // // catGenConf.addDatasetNamer( readDatasetNamerElement( parentDataset, // dsNamerElement)); // } return( catGenConf); }
java
{ "resource": "" }
q174607
CatGenConfigMetadataFactory.readDatasetSourceElement
test
private DatasetSource readDatasetSourceElement( InvDataset parentDataset, Element dsSourceElement) { String name = dsSourceElement.getAttributeValue( "name"); String type = dsSourceElement.getAttributeValue( "type"); String structure = dsSourceElement.getAttributeValue( "structure"); String accessPoint = dsSourceElement.getAttributeValue( "accessPoint"); String createCatalogRefs = dsSourceElement.getAttributeValue( "createCatalogRefs"); // get the resultService element Element resultServiceElement = dsSourceElement.getChild( "resultService", dsSourceElement.getNamespace() ); ResultService resultService = readResultServiceElement( parentDataset, resultServiceElement); DatasetSource dsSource = DatasetSource.newDatasetSource( name, DatasetSourceType.getType( type), DatasetSourceStructure.getStructure( structure), accessPoint, resultService); if ( createCatalogRefs != null) { dsSource.setCreateCatalogRefs( Boolean.valueOf( createCatalogRefs).booleanValue()); } // get any datasetNamer elements java.util.List list = dsSourceElement.getChildren( "datasetNamer", dsSourceElement.getNamespace() ); for (int i=0; i< list.size(); i++) { Element dsNamerElement = (Element) list.get(i); dsSource.addDatasetNamer( readDatasetNamerElement( parentDataset, dsNamerElement)); } // get any datasetFilter elements list = dsSourceElement.getChildren( "datasetFilter", dsSourceElement.getNamespace() ); for (int i=0; i< list.size(); i++) { Element dsFilterElement = (Element) list.get(i); dsSource.addDatasetFilter( readDatasetFilterElement( dsSource, dsFilterElement)); } return( dsSource); }
java
{ "resource": "" }
q174608
CatGenConfigMetadataFactory.readDatasetNamerElement
test
private DatasetNamer readDatasetNamerElement( InvDataset parentDataset, Element dsNamerElement) { String name = dsNamerElement.getAttributeValue( "name"); String addLevel = dsNamerElement.getAttributeValue( "addLevel"); String type = dsNamerElement.getAttributeValue( "type"); String matchPattern = dsNamerElement.getAttributeValue( "matchPattern"); String substitutePattern = dsNamerElement.getAttributeValue( "substitutePattern"); String attribContainer = dsNamerElement.getAttributeValue( "attribContainer"); String attribName = dsNamerElement.getAttributeValue( "attribName"); DatasetNamer dsNamer = new DatasetNamer( parentDataset, name, addLevel, type, matchPattern, substitutePattern, attribContainer, attribName); return( dsNamer); }
java
{ "resource": "" }
q174609
CatGenConfigMetadataFactory.readDatasetFilterElement
test
private DatasetFilter readDatasetFilterElement( DatasetSource parentDatasetSource, Element dsFilterElement) { String name = dsFilterElement.getAttributeValue( "name"); String type = dsFilterElement.getAttributeValue( "type"); String matchPattern = dsFilterElement.getAttributeValue( "matchPattern"); DatasetFilter dsFilter = new DatasetFilter( parentDatasetSource, name, DatasetFilter.Type.getType( type), matchPattern); String matchPatternTarget = dsFilterElement.getAttributeValue( "matchPatternTarget"); dsFilter.setMatchPatternTarget( matchPatternTarget); if ( dsFilterElement.getAttributeValue( "applyToCollectionDatasets") != null) { boolean applyToCollectionDatasets = Boolean.valueOf( dsFilterElement.getAttributeValue( "applyToCollectionDatasets")).booleanValue(); dsFilter.setApplyToCollectionDatasets( applyToCollectionDatasets); } if ( dsFilterElement.getAttributeValue( "applyToAtomicDatasets") != null) { boolean applyToAtomicDatasets = Boolean.valueOf( dsFilterElement.getAttributeValue( "applyToAtomicDatasets")).booleanValue(); dsFilter.setApplyToAtomicDatasets( applyToAtomicDatasets); } if ( dsFilterElement.getAttributeValue( "rejectMatchingDatasets") != null) { boolean rejectMatchingDatasets = Boolean.valueOf( dsFilterElement.getAttributeValue( "rejectMatchingDatasets")).booleanValue(); dsFilter.setRejectMatchingDatasets( rejectMatchingDatasets); } return( dsFilter); }
java
{ "resource": "" }
q174610
CatGenConfigMetadataFactory.readResultServiceElement
test
private ResultService readResultServiceElement( InvDataset parentDataset, Element resultServiceElement) { String name = resultServiceElement.getAttributeValue( "name"); String serviceType = resultServiceElement.getAttributeValue( "serviceType"); String base = resultServiceElement.getAttributeValue( "base"); String suffix = resultServiceElement.getAttributeValue( "suffix"); String accessPointHeader = resultServiceElement.getAttributeValue( "accessPointHeader"); return( new ResultService( name, ServiceType.getType( serviceType), base, suffix, accessPointHeader)); }
java
{ "resource": "" }
q174611
CatGenConfigMetadataFactory.createCatGenConfigElement
test
private org.jdom2.Element createCatGenConfigElement( CatalogGenConfig cgc) { // @todo Need to deal with the 0.6 and 1.0 namespaces. Element cgcElem = new Element("catalogGenConfig", CATALOG_GEN_CONFIG_NAMESPACE_0_5); if ( cgc != null) { if ( cgc.getType() != null) { cgcElem.setAttribute( "type", cgc.getType().toString()); } // Add 'datasetSource' element DatasetSource dsSource = cgc.getDatasetSource(); cgcElem.addContent( createDatasetSourceElement( dsSource)); } return( cgcElem); }
java
{ "resource": "" }
q174612
CatGenConfigMetadataFactory.createDatasetSourceElement
test
private org.jdom2.Element createDatasetSourceElement( DatasetSource dsSource) { Element dssElem = new Element("datasetSource", CATALOG_GEN_CONFIG_NAMESPACE_0_5); if ( dsSource != null) { // Add 'name' attribute. if ( dsSource.getName() != null) { dssElem.setAttribute( "name", dsSource.getName()); } // Add 'type' attribute. if ( dsSource.getType() != null) { dssElem.setAttribute( "type", dsSource.getType().toString()); } // Add 'structure' attribute. if ( dsSource.getStructure() != null) { dssElem.setAttribute( "structure", dsSource.getStructure().toString()); } // Add 'accessPoint' attribute. if ( dsSource.getAccessPoint() != null) { dssElem.setAttribute( "accessPoint", dsSource.getAccessPoint()); } // Add 'createCatalogRefs' attribute. dssElem.setAttribute( "createCatalogRefs", Boolean.toString( dsSource.isCreateCatalogRefs())); // Add 'resultService' element ResultService rs = dsSource.getResultService(); dssElem.addContent( createResultServiceElement( rs)); // Add 'datasetNamer' elements java.util.List list = dsSource.getDatasetNamerList(); for ( int j=0; j < list.size(); j++) { DatasetNamer dsNamer = (DatasetNamer) list.get(j); dssElem.addContent( createDatasetNamerElement( dsNamer)); } // Add 'datasetFilter' elements list = dsSource.getDatasetFilterList(); for ( int j=0; j < list.size(); j++) { DatasetFilter dsFilter = (DatasetFilter) list.get(j); dssElem.addContent( createDatasetFilterElement( dsFilter)); } } return( dssElem); }
java
{ "resource": "" }
q174613
CatGenConfigMetadataFactory.createDatasetNamerElement
test
private org.jdom2.Element createDatasetNamerElement( DatasetNamer dsNamer) { Element dsnElem = new Element("datasetNamer", CATALOG_GEN_CONFIG_NAMESPACE_0_5); if ( dsNamer != null) { // Add 'name' attribute. if ( dsNamer.getName() != null) { dsnElem.setAttribute( "name", dsNamer.getName()); } // Add 'addLevel' attribute. dsnElem.setAttribute( "addLevel", Boolean.toString( dsNamer.getAddLevel())); // Add 'type' attribute. if ( dsNamer.getType() != null) { dsnElem.setAttribute( "type", dsNamer.getType().toString()); } // Add 'matchPattern' attribute. if ( dsNamer.getMatchPattern() != null) { dsnElem.setAttribute( "matchPattern", dsNamer.getMatchPattern()); } // Add 'subsitutePattern' attribute. if ( dsNamer.getSubstitutePattern() != null) { dsnElem.setAttribute( "substitutePattern", dsNamer.getSubstitutePattern()); } // Add 'attribContainer' attribute. if ( dsNamer.getAttribContainer() != null) { dsnElem.setAttribute( "attribContainer", dsNamer.getAttribContainer()); } // Add 'attribName' attribute. if ( dsNamer.getAttribName() != null) { dsnElem.setAttribute( "attribName", dsNamer.getAttribName()); } } return( dsnElem); }
java
{ "resource": "" }
q174614
CatGenConfigMetadataFactory.createDatasetFilterElement
test
private org.jdom2.Element createDatasetFilterElement( DatasetFilter dsFilter) { Element dsfElem = new Element("datasetFilter", CATALOG_GEN_CONFIG_NAMESPACE_0_5); if ( dsFilter != null) { // Add 'name' attribute. if ( dsFilter.getName() != null) { dsfElem.setAttribute( "name", dsFilter.getName()); } // Add 'type' attribute. if ( dsFilter.getType() != null) { dsfElem.setAttribute( "type", dsFilter.getType().toString()); } // Add 'matchPattern' attribute. if ( dsFilter.getMatchPattern() != null) { dsfElem.setAttribute( "matchPattern", dsFilter.getMatchPattern()); } // Add 'matchPatternTarget' attribute. if ( dsFilter.getMatchPatternTarget() != null) { dsfElem.setAttribute( "matchPatternTarget", dsFilter.getMatchPatternTarget()); } // Add 'applyToCollectionDatasets' attribute. dsfElem.setAttribute( "applyToCollectionDatasets", String.valueOf( dsFilter.isApplyToCollectionDatasets())); // Add 'applyToAtomicDatasets' attribute. dsfElem.setAttribute( "applyToAtomicDatasets", String.valueOf( dsFilter.isApplyToAtomicDatasets())); // Add 'rejectMatchingDatasets' attribute. dsfElem.setAttribute( "rejectMatchingDatasets", String.valueOf( dsFilter.isRejectMatchingDatasets())); } return( dsfElem); }
java
{ "resource": "" }
q174615
CatGenConfigMetadataFactory.createResultServiceElement
test
private org.jdom2.Element createResultServiceElement( ResultService resultService) { Element rsElem = new Element("resultService", CATALOG_GEN_CONFIG_NAMESPACE_0_5); if ( resultService != null) { // Add 'name' attribute. if ( resultService.getName() != null) { rsElem.setAttribute( "name", resultService.getName()); } // Add 'serviceType' attribute. if ( resultService.getServiceType() != null) { rsElem.setAttribute( "serviceType", resultService.getServiceType().toString()); } // Add 'base' attribute. if ( resultService.getBase() != null) { rsElem.setAttribute( "base", resultService.getBase()); } // Add 'suffix' attribute. if ( resultService.getSuffix() != null) { rsElem.setAttribute( "suffix", resultService.getSuffix()); } // Add 'accessPointHeader' attribute. if ( resultService.getAccessPointHeader() != null) { rsElem.setAttribute( "accessPointHeader", resultService.getAccessPointHeader()); } } return( rsElem); }
java
{ "resource": "" }
q174616
Debug.isSet
test
static public boolean isSet(String flagName) { if (store == null) return false; NamePart np = partit( flagName); if (debug) { try { if ((np.storeName.length() > 0) && !store.nodeExists(np.storeName)) System.out.println("Debug.isSet create node = "+ flagName+" "+np); else if (null == store.node(np.storeName).get( np.keyName, null)) System.out.println("Debug.isSet create flag = "+ flagName+" "+np); } catch (BackingStoreException e) { } } // add it if it doesnt already exist boolean value = store.node(np.storeName).getBoolean( np.keyName, false); store.node(np.storeName).putBoolean( np.keyName, value); return value; }
java
{ "resource": "" }
q174617
Debug.constructMenu
test
static public void constructMenu(JMenu topMenu) { if (debug) System.out.println("Debug.constructMenu "); if (topMenu.getItemCount() > 0) topMenu.removeAll(); try { addToMenu( topMenu, store); // recursive } catch (BackingStoreException e) { } topMenu.revalidate(); }
java
{ "resource": "" }
q174618
Debug.addToMenu
test
static private void addToMenu( JMenu menu, Preferences prefs) throws BackingStoreException { if (debug) System.out.println(" addMenu "+ prefs.name()); String[] keys = prefs.keys(); for (String key : keys) { boolean bval = prefs.getBoolean(key, false); String fullname = prefs.absolutePath() + "/" + key; menu.add(new DebugMenuItem(fullname, key, bval)); // menu leaf if (debug) System.out.println(" leaf= <" + key + "><" + fullname + ">"); } String[] kidName = prefs.childrenNames(); for (String aKidName : kidName) { Preferences pkid = prefs.node(aKidName); JMenu subMenu = new JMenu(pkid.name()); menu.add(subMenu); addToMenu(subMenu, pkid); } }
java
{ "resource": "" }
q174619
GempakParameterTable.addParameters
test
public void addParameters(String tbl) throws IOException { try (InputStream is = getInputStream(tbl)) { if (is == null) { throw new IOException("Unable to open " + tbl); } String content = readContents(is); // LOOK this is silly - should just read one line at a time // List lines = StringUtil.split(content, "\n", false); String[] lines = content.split("\n"); List<String[]> result = new ArrayList<>(); for (String line : lines) { //String line = (String) lines.get(i); String tline = line.trim(); if (tline.length() == 0) { continue; } if (tline.startsWith("!")) { continue; } String[] words = new String[indices.length]; for (int idx = 0; idx < indices.length; idx++) { if (indices[idx] >= tline.length()) { continue; } if (indices[idx] + lengths[idx] > tline.length()) { words[idx] = line.substring(indices[idx]); } else { words[idx] = line.substring(indices[idx], indices[idx] + lengths[idx]); } //if (trimWords) { words[idx] = words[idx].trim(); //} } result.add(words); } for (String[] aResult : result) { GempakParameter p = makeParameter(aResult); if (p != null) { if (p.getName().contains("(")) { templateParamMap.put(p.getName(), p); } else { paramMap.put(p.getName(), p); } } } } }
java
{ "resource": "" }
q174620
GempakParameterTable.makeParameter
test
private GempakParameter makeParameter(String[] words) { int num = 0; String description; if (words[0] != null) { num = (int) Double.parseDouble(words[0]); } if ((words[3] == null) || words[3].equals("")) { // no param name return null; } String name = words[3]; if (name.contains("-")) { int first = name.indexOf("-"); int last = name.lastIndexOf("-"); StringBuilder buf = new StringBuilder(name.substring(0, first)); buf.append("("); for (int i = first; i <= last; i++) { buf.append("\\d"); } buf.append(")"); buf.append(name.substring(last + 1)); name = buf.toString(); } if ((words[1] == null) || words[1].equals("")) { description = words[3]; } else { description = words[1]; } String unit = words[2]; if (unit != null) { unit = unit.replaceAll("\\*\\*", ""); if (unit.equals("-")) { unit = ""; } } int decimalScale; try { decimalScale = Integer.parseInt(words[4].trim()); } catch (NumberFormatException ne) { decimalScale = 0; } return new GempakParameter(num, name, description, unit, decimalScale); }
java
{ "resource": "" }
q174621
GempakParameterTable.getParameter
test
public GempakParameter getParameter(String name) { GempakParameter param = paramMap.get(name); if (param == null) { // try the regex list Set<String> keys = templateParamMap.keySet(); if (!keys.isEmpty()) { for (String key : keys) { Pattern p = Pattern.compile(key); Matcher m = p.matcher(name); if (m.matches()) { //System.out.println("found match " + key + " for " + name); String value = m.group(1); GempakParameter match = templateParamMap.get(key); param = new GempakParameter(match.getNumber(), name, match.getDescription() + " (" + value + " hour)", match.getUnit(), match.getDecimalScale()); paramMap.put(name, param); break; } } } } return param; }
java
{ "resource": "" }
q174622
GempakParameterTable.readContents
test
private String readContents(InputStream is) throws IOException { return new String(readBytes(is), CDM.utf8Charset); }
java
{ "resource": "" }
q174623
GempakParameterTable.readBytes
test
private byte[] readBytes(InputStream is) throws IOException { int totalRead = 0; byte[] content = new byte[1000000]; while (true) { int howMany = is.read(content, totalRead, content.length - totalRead); if (howMany < 0) { break; } if (howMany == 0) { continue; } totalRead += howMany; if (totalRead >= content.length) { byte[] tmp = content; int newLength = ((content.length < 25000000) ? content.length * 2 : content.length + 5000000); content = new byte[newLength]; System.arraycopy(tmp, 0, content, 0, totalRead); } } is.close(); byte[] results = new byte[totalRead]; System.arraycopy(content, 0, results, 0, totalRead); return results; }
java
{ "resource": "" }
q174624
GradsEnsembleDimension.replaceFileTemplate
test
public String replaceFileTemplate(String filespec, int ensIndex) { return filespec.replaceAll(ENS_TEMPLATE_ID, getEnsembleNames().get(ensIndex)); }
java
{ "resource": "" }
q174625
RecordDatasetHelper.setStationInfo
test
public void setStationInfo(String stnIdVName, String stnDescVName) { this.stnIdVName = stnIdVName; this.stnDescVName = stnDescVName; Variable stationVar = ncfile.findVariable(stnIdVName); stationIdType = stationVar.getDataType(); }
java
{ "resource": "" }
q174626
Field.accept
test
protected boolean accept(StringBuffer buff){ if (!validate(buff)) { validate(buff); return false; } if (acceptIfDifferent( getEditValue())) { setStoreValue( validValue); sendEvent(); } return true; }
java
{ "resource": "" }
q174627
Field.showFormatInfo
test
static private void showFormatInfo( JFormattedTextField tf) { JFormattedTextField.AbstractFormatter ff = tf.getFormatter(); System.out.println("AbstractFormatter " + ff.getClass().getName()); if (ff instanceof NumberFormatter) { NumberFormatter nf = (NumberFormatter) ff; Format f = nf.getFormat(); System.out.println(" Format = " + f.getClass().getName()); if (f instanceof NumberFormat) { NumberFormat nfat = (NumberFormat) f; System.out.println(" getMinimumIntegerDigits=" + nfat.getMinimumIntegerDigits()); System.out.println(" getMaximumIntegerDigits=" + nfat.getMaximumIntegerDigits()); System.out.println(" getMinimumFractionDigits=" + nfat.getMinimumFractionDigits()); System.out.println(" getMaximumFractionDigits=" + nfat.getMaximumFractionDigits()); } if (f instanceof DecimalFormat) { DecimalFormat df = (DecimalFormat) f; System.out.println(" Pattern = " + df.toPattern()); } } }
java
{ "resource": "" }
q174628
Grib2SectionBitMap.getBitmap
test
@Nullable public byte[] getBitmap(RandomAccessFile raf) throws IOException { // no bitMap if (bitMapIndicator == 255) return null; // LOOK: bitMapIndicator=254 == previously defined bitmap if (bitMapIndicator == 254) logger.debug("HEY bitMapIndicator=254 previously defined bitmap"); if (bitMapIndicator != 0) { throw new UnsupportedOperationException("Grib2 Bit map section pre-defined (provided by center) = " + bitMapIndicator); } raf.seek(startingPosition); int length = GribNumbers.int4(raf); raf.skipBytes(2); byte[] data = new byte[length - 6]; raf.readFully(data); return data; }
java
{ "resource": "" }
q174629
NCdumpPanel.setNetcdfFile
test
public void setNetcdfFile(NetcdfFile ncf) { this.ncfile = ncf; this.filename = ncf.getLocation(); final GetDataRunnable runner = new GetDataRunnable() { public void run(Object o) throws IOException { final StringWriter sw = new StringWriter(50000); NCdumpW.print(ncfile, command, sw, task); result = sw.toString(); } }; task = new GetDataTask(runner, filename, null); stopButton.startProgressMonitorTask(task); }
java
{ "resource": "" }
q174630
DODSNetcdfFile.setDebugFlags
test
static public void setDebugFlags(ucar.nc2.util.DebugFlags debugFlag) { debugCE = debugFlag.isSet("DODS/constraintExpression"); debugServerCall = debugFlag.isSet("DODS/serverCall"); debugOpenResult = debugFlag.isSet("DODS/debugOpenResult"); debugDataResult = debugFlag.isSet("DODS/debugDataResult"); debugCharArray = debugFlag.isSet("DODS/charArray"); debugConstruct = debugFlag.isSet("DODS/constructNetcdf"); debugPreload = debugFlag.isSet("DODS/preload"); debugTime = debugFlag.isSet("DODS/timeCalls"); showNCfile = debugFlag.isSet("DODS/showNCfile"); debugAttributes = debugFlag.isSet("DODS/attributes"); debugCached = debugFlag.isSet("DODS/cache"); }
java
{ "resource": "" }
q174631
DODSNetcdfFile.parseName
test
NamePieces parseName(String name) { NamePieces pieces = new NamePieces(); int dotpos = name.lastIndexOf('.'); int slashpos = name.lastIndexOf('/'); if (slashpos < 0 && dotpos < 0) { pieces.name = name; } else if (slashpos >= 0 && dotpos < 0) { pieces.prefix = name.substring(0, slashpos); pieces.name = name.substring(slashpos + 1, name.length()); } else if (slashpos < 0 && dotpos >= 0) { pieces.var = name.substring(0, dotpos); pieces.name = name.substring(dotpos + 1, name.length()); } else {//slashpos >= 0 && dotpos >= 0) if (slashpos > dotpos) { pieces.prefix = name.substring(0, slashpos); pieces.name = name.substring(slashpos + 1, name.length()); } else {//slashpos < dotpos) pieces.prefix = name.substring(0, slashpos); pieces.var = name.substring(slashpos + 1, dotpos); pieces.name = name.substring(dotpos + 1, name.length()); } } // fixup if (pieces.prefix != null && pieces.prefix.length() == 0) pieces.prefix = null; if (pieces.var != null && pieces.var.length() == 0) pieces.var = null; if (pieces.name.length() == 0) pieces.name = null; return pieces; }
java
{ "resource": "" }
q174632
DODSNetcdfFile.isGroup
test
private boolean isGroup(DStructure dstruct) { BaseType parent = (BaseType) dstruct.getParent(); if (parent == null) return true; if (parent instanceof DStructure) return isGroup((DStructure) parent); return true; }
java
{ "resource": "" }
q174633
DODSNetcdfFile.getNetcdfStrlenDim
test
Dimension getNetcdfStrlenDim(DODSVariable v) { AttributeTable table = das.getAttributeTableN(v.getFullName()); // LOOK this probably doesnt work for nested variables if (table == null) return null; opendap.dap.Attribute dodsAtt = table.getAttribute("DODS"); if (dodsAtt == null) return null; AttributeTable dodsTable = dodsAtt.getContainerN(); if (dodsTable == null) return null; opendap.dap.Attribute att = dodsTable.getAttribute("strlen"); if (att == null) return null; String strlen = att.getValueAtN(0); opendap.dap.Attribute att2 = dodsTable.getAttribute("dimName"); String dimName = (att2 == null) ? null : att2.getValueAtN(0); if (debugCharArray) System.out.println(v.getFullName() + " has strlen= " + strlen + " dimName= " + dimName); int dimLength; try { dimLength = Integer.parseInt(strlen); } catch (NumberFormatException e) { logger.warn("DODSNetcdfFile " + location + " var = " + v.getFullName() + " error on strlen attribute = " + strlen); return null; } if (dimLength <= 0) return null; // LOOK what about unlimited ?? return new Dimension(dimName, dimLength, dimName != null); }
java
{ "resource": "" }
q174634
DODSNetcdfFile.getSharedDimension
test
Dimension getSharedDimension(Group group, Dimension d) { if (d.getShortName() == null) return d; if (group == null) group = rootGroup; for (Dimension sd : group.getDimensions()) { if (sd.getShortName().equals(d.getShortName()) && sd.getLength() == d.getLength()) return sd; } d.setShared(true); group.addDimension(d); return d; }
java
{ "resource": "" }
q174635
DODSNetcdfFile.constructDimensions
test
List<Dimension> constructDimensions(Group group, opendap.dap.DArray dodsArray) { if (group == null) group = rootGroup; List<Dimension> dims = new ArrayList<Dimension>(); Enumeration enumerate = dodsArray.getDimensions(); while (enumerate.hasMoreElements()) { opendap.dap.DArrayDimension dad = (opendap.dap.DArrayDimension) enumerate.nextElement(); String name = dad.getEncodedName(); if (name != null) name = StringUtil2.unescape(name); Dimension myd; if (name == null) { // if no name, make an anonymous dimension myd = new Dimension(null, dad.getSize(), false); } else { // see if shared if (RC.getUseGroups()) { if (name.indexOf('/') >= 0) {// place dimension in proper group group = group.makeRelativeGroup(this, name, true); // change our name name = name.substring(name.lastIndexOf('/') + 1); } } myd = group.findDimension(name); if (myd == null) { // add as shared myd = new Dimension(name, dad.getSize()); group.addDimension(myd); } else if (myd.getLength() != dad.getSize()) { // make a non-shared dimension myd = new Dimension(name, dad.getSize(), false); } // else use existing, shared dimension } dims.add(myd); // add it to the list } return dims; }
java
{ "resource": "" }
q174636
DODSNetcdfFile.isUnsigned
test
static public boolean isUnsigned(opendap.dap.BaseType dtype) { return (dtype instanceof DByte) || (dtype instanceof DUInt16) || (dtype instanceof DUInt32); }
java
{ "resource": "" }
q174637
DODSNetcdfFile.readDataDDSfromServer
test
DataDDS readDataDDSfromServer(String CE) throws IOException, opendap.dap.DAP2Exception { if (debugServerCall) System.out.println("DODSNetcdfFile.readDataDDSfromServer = <" + CE + ">"); long start = 0; if (debugTime) start = System.currentTimeMillis(); if (!CE.startsWith("?")) CE = "?" + CE; DataDDS data; synchronized (this) { data = dodsConnection.getData(CE, null); } if (debugTime) System.out.println("DODSNetcdfFile.readDataDDSfromServer took = " + (System.currentTimeMillis() - start) / 1000.0); if (debugDataResult) { System.out.println(" dataDDS return:"); data.print(System.out); } return data; }
java
{ "resource": "" }
q174638
Resource.getIcon
test
public static ImageIcon getIcon( String fullIconName, boolean errMsg) { ImageIcon icon = null; java.net.URL iconR = cl.getResource(fullIconName); if (debugIcon) { System.out.println("classLoader "+cl.getClassLoader()); System.out.println(" Resource.getIcon on "+fullIconName+" = "+iconR); } if (iconR != null) icon = new ImageIcon(iconR); if ((icon == null) && errMsg) System.out.println(" ERROR: Resource.getIcon failed on "+fullIconName); else if (debugIcon) System.out.println(" Resource.getIcon ok on "+fullIconName); return icon; }
java
{ "resource": "" }
q174639
Resource.getImage
test
public static Image getImage( String fullImageName) { Image image = null; java.net.URL url = cl.getResource(fullImageName); if (url != null) image = Toolkit.getDefaultToolkit().createImage(url); if (image == null) System.out.println(" ERROR: Resource.getImageResource failed on "+fullImageName); return image; }
java
{ "resource": "" }
q174640
Resource.makeCursor
test
public static Cursor makeCursor( String name) { Image image = getImage(name); if (null == image) return null; Cursor cursor; try { Toolkit tk = Toolkit.getDefaultToolkit(); if (debug) { ImageObserver obs = new ImageObserver() { public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) { return true; } }; System.out.println(" bestCursorSize = "+ tk.getBestCursorSize(image.getWidth(obs), image.getHeight(obs))); System.out.println(" getMaximumCursorColors = "+ tk.getMaximumCursorColors()); } cursor = tk.createCustomCursor(image, new Point(17,17), name); } catch (IndexOutOfBoundsException e) { System.out.println("NavigatedPanel createCustomCursor failed " + e); return null; } return cursor; }
java
{ "resource": "" }
q174641
IospHelper.readDataFill
test
static public Object readDataFill(RandomAccessFile raf, Layout index, DataType dataType, Object fillValue, int byteOrder) throws java.io.IOException { Object arr = (fillValue == null) ? makePrimitiveArray((int) index.getTotalNelems(), dataType) : makePrimitiveArray((int) index.getTotalNelems(), dataType, fillValue); return readData(raf, index, dataType, arr, byteOrder, true); }
java
{ "resource": "" }
q174642
IospHelper.readDataFill
test
static public Object readDataFill(PositioningDataInputStream is, Layout index, DataType dataType, Object fillValue) throws java.io.IOException { Object arr = (fillValue == null) ? makePrimitiveArray((int) index.getTotalNelems(), dataType) : makePrimitiveArray((int) index.getTotalNelems(), dataType, fillValue); return readData(is, index, dataType, arr); }
java
{ "resource": "" }
q174643
IospHelper.readDataFill
test
static public Object readDataFill(LayoutBB layout, DataType dataType, Object fillValue) throws java.io.IOException { long size = layout.getTotalNelems(); if (dataType == DataType.STRUCTURE) size *= layout.getElemSize(); Object arr = (fillValue == null) ? makePrimitiveArray((int) size, dataType) : makePrimitiveArray((int) size, dataType, fillValue); return readData(layout, dataType, arr); }
java
{ "resource": "" }
q174644
IospHelper.makePrimitiveArray
test
static public Object makePrimitiveArray(int size, DataType dataType) { Object arr = null; if ((dataType.getPrimitiveClassType() == byte.class) || (dataType == DataType.CHAR) || (dataType == DataType.OPAQUE) || (dataType == DataType.STRUCTURE)) { arr = new byte[size]; } else if (dataType.getPrimitiveClassType() == short.class) { arr = new short[size]; } else if (dataType.getPrimitiveClassType() == int.class) { arr = new int[size]; } else if (dataType.getPrimitiveClassType() == long.class) { arr = new long[size]; } else if (dataType == DataType.FLOAT) { arr = new float[size]; } else if (dataType == DataType.DOUBLE) { arr = new double[size]; } else if (dataType == DataType.STRING) { arr = new String[size]; } return arr; }
java
{ "resource": "" }
q174645
IospHelper.convertByteToCharUTF
test
static public char[] convertByteToCharUTF(byte[] byteArray) { Charset c = CDM.utf8Charset; CharBuffer output = c.decode(ByteBuffer.wrap(byteArray)); return output.array(); }
java
{ "resource": "" }
q174646
IospHelper.convertCharToByteUTF
test
static public byte[] convertCharToByteUTF(char[] from) { Charset c = CDM.utf8Charset; ByteBuffer output = c.encode(CharBuffer.wrap(from)); return output.array(); }
java
{ "resource": "" }
q174647
IospHelper.convertByteToChar
test
static public char[] convertByteToChar(byte[] byteArray) { int size = byteArray.length; char[] cbuff = new char[size]; for (int i = 0; i < size; i++) cbuff[i] = (char) DataType.unsignedByteToShort(byteArray[i]); // NOTE: not Unicode ! return cbuff; } // convert char array to byte array static public byte[] convertCharToByte(char[] from) { byte[] to = null; if (from != null) { int size = from.length; to = new byte[size]; for (int i = 0; i < size; i++) to[i] = (byte) from[i]; // LOOK wrong, convert back to unsigned byte ??? } return to; }
java
{ "resource": "" }
q174648
IospHelper.readSection
test
static public ucar.ma2.Array readSection(ParsedSectionSpec cer) throws IOException, InvalidRangeException { Variable inner = null; List<Range> totalRanges = new ArrayList<>(); ParsedSectionSpec current = cer; while (current != null) { totalRanges.addAll(current.section.getRanges()); inner = current.v; current = current.child; } assert inner != null; Section total = new Section(totalRanges); Array result = Array.factory(inner.getDataType(), total.getShape()); // must be a Structure Structure outer = (Structure) cer.v; Structure outerSubset = outer.select(cer.child.v.getShortName()); // allows IOSPs to optimize for this case ArrayStructure outerData = (ArrayStructure) outerSubset.read(cer.section); extractSection(cer.child, outerData, result.getIndexIterator()); return result; }
java
{ "resource": "" }
q174649
IospHelper.sectionArrayStructure
test
static private ArrayStructure sectionArrayStructure(ParsedSectionSpec child, ArrayStructure innerData, StructureMembers.Member m) throws IOException, InvalidRangeException { StructureMembers membersw = new StructureMembers(m.getStructureMembers()); // no data arrays get propagated ArrayStructureW result = new ArrayStructureW(membersw, child.section.getShape()); int count = 0; Section.Iterator iter = child.section.getIterator(child.v.getShape()); while (iter.hasNext()) { int recno = iter.next(null); StructureData sd = innerData.getStructureData(recno); result.setStructureData(sd, count++); } return result; }
java
{ "resource": "" }
q174650
CDMArrayStructure.getScalarString
test
public String getScalarString(int recnum, StructureMembers.Member m) { Array data = m.getDataArray(); return (String) data.getObject(recnum).toString(); }
java
{ "resource": "" }
q174651
CDMArrayStructure.getScalarStructure
test
public StructureData getScalarStructure(int index, StructureMembers.Member m) { if(m.getDataType() != DataType.STRUCTURE) throw new ForbiddenConversionException("Atomic field cannot be converted to Structure"); Array ca = memberArray(index, memberIndex(m)); if(ca.getDataType() != DataType.STRUCTURE && ca.getDataType() != DataType.SEQUENCE) throw new ForbiddenConversionException("Attempt to access non-structure member"); CDMArrayStructure as = (CDMArrayStructure) ca; return as.getStructureData(0); }
java
{ "resource": "" }
q174652
CDMArrayStructure.getArray
test
@Override public ucar.ma2.Array getArray(int recno, StructureMembers.Member m) { return (ucar.ma2.Array) memberArray(recno, memberIndex(m)); }
java
{ "resource": "" }
q174653
CDMArrayStructure.computemembers
test
static StructureMembers computemembers(DapVariable var) { DapStructure ds = (DapStructure)var.getBaseType(); StructureMembers sm = new StructureMembers(ds.getShortName()); List<DapVariable> fields = ds.getFields(); for(int i = 0; i < fields.size(); i++) { DapVariable field = fields.get(i); DapType dt = field.getBaseType(); DataType cdmtype = CDMTypeFcns.daptype2cdmtype(dt); StructureMembers.Member m = sm.addMember( field.getShortName(), "", null, cdmtype, CDMUtil.computeEffectiveShape(field.getDimensions())); m.setDataParam(i); // So we can index into various lists // recurse if this field is itself a structure if(dt.getTypeSort().isStructType()) { StructureMembers subsm = computemembers(field); m.setStructureMembers(subsm); } } return sm; }
java
{ "resource": "" }
q174654
GridEnsembleCoord.addDimensionsToNetcdfFile
test
public void addDimensionsToNetcdfFile(NetcdfFile ncfile, Group g) { ncfile.addDimension(g, new Dimension(getName(), getNEnsembles(), true)); }
java
{ "resource": "" }
q174655
CrawlableDatasetFactory.createCrawlableDataset
test
public static CrawlableDataset createCrawlableDataset( String path, String className, Object configObj ) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IllegalArgumentException, NullPointerException // throws CrDsException, IllegalArgumentException { if ( path == null ) throw new NullPointerException( "Given path must not be null."); String tmpClassName = ( className == null ? defaultClassName : className ); // @todo Remove alias until sure how to handle things like ".scour*" being a regular file. // if ( CrawlableDatasetAlias.isAlias( tmpPath) ) // return new CrawlableDatasetAlias( tmpPath, tmpClassName, configObj ); // Get the Class instance for desired CrawlableDataset implementation. Class crDsClass = Class.forName( tmpClassName ); // Check that the Class is a CrawlableDataset. if ( ! CrawlableDataset.class.isAssignableFrom( crDsClass ) ) { throw new IllegalArgumentException( "Requested class <" + className + "> not an implementation of thredds.crawlabledataset.CrawlableDataset."); } // Instantiate the desired CrawlableDataset. Class [] argTypes = { String.class, Object.class }; Object [] args = { path, configObj }; Constructor constructor = crDsClass.getDeclaredConstructor( argTypes ); try { return (CrawlableDataset) constructor.newInstance( args ); } catch ( InvocationTargetException e ) { if ( IOException.class.isAssignableFrom( e.getCause().getClass()) ) throw (IOException) e.getCause(); else throw e; } }
java
{ "resource": "" }
q174656
CrawlableDatasetFactory.normalizePath
test
public static String normalizePath( String path ) { // Replace any occurance of a backslash ("\") with a slash ("/"). // NOTE: Both String and Pattern escape backslash, so need four backslashes to find one. // NOTE: No longer replace multiple backslashes with one slash, which allows for UNC pathnames (Windows LAN addresses). // Was path.replaceAll( "\\\\+", "/"); String newPath = path.replaceAll( "\\\\", "/"); // Remove trailing slashes. while ( newPath.endsWith( "/") && ! newPath.equals("/") ) newPath = newPath.substring( 0, newPath.length() - 1 ); return newPath; }
java
{ "resource": "" }
q174657
Aggregation.addExplicitDataset
test
public void addExplicitDataset(String cacheName, String location, String id, String ncoordS, String coordValueS, String sectionSpec, ucar.nc2.util.cache.FileFactory reader) { Dataset nested = makeDataset(cacheName, location, id, ncoordS, coordValueS, sectionSpec, null, reader); explicitDatasets.add(nested); }
java
{ "resource": "" }
q174658
Aggregation.addDatasetScan
test
public void addDatasetScan(Element crawlableDatasetElement, String dirName, String suffix, String regexpPatternString, String dateFormatMark, Set<NetcdfDataset.Enhance> enhanceMode, String subdirs, String olderThan) { datasetManager.addDirectoryScan(dirName, suffix, regexpPatternString, subdirs, olderThan, enhanceMode); this.dateFormatMark = dateFormatMark; if (dateFormatMark != null) { isDate = true; if (type == Type.joinExisting) type = Type.joinExistingOne; // tricky DateExtractor dateExtractor = new DateExtractorFromName(dateFormatMark, true); datasetManager.setDateExtractor(dateExtractor); } }
java
{ "resource": "" }
q174659
Aggregation.finish
test
public void finish(CancelTask cancelTask) throws IOException { datasetManager.scan(true); // Make the list of Datasets, by scanning if needed. cacheDirty = true; makeDatasets(cancelTask); //ucar.unidata.io.RandomAccessFile.setDebugAccess( true); buildNetcdfDataset(cancelTask); //ucar.unidata.io.RandomAccessFile.setDebugAccess( false); }
java
{ "resource": "" }
q174660
Aggregation.makeDatasets
test
protected void makeDatasets(CancelTask cancelTask) throws IOException { // heres where the results will go datasets = new ArrayList<>(); for (MFile cd : datasetManager.getFilesSorted()) { datasets.add( makeDataset(cd)); } // sort using Aggregation.Dataset as Comparator. // Sort by date if it exists, else filename. Collections.sort(datasets); /* optionally extract the date String dateCoordS = null; if (null != dateFormatMark) { String filename = myf.getName(); // LOOK operates on name, not path Date dateCoord = DateFromString.getDateUsingDemarkatedCount(filename, dateFormatMark, '#'); dateCoordS = formatter.toDateTimeStringISO(dateCoord); if (debugDateParse) System.out.println(" adding " + myf.getPath() + " date= " + dateCoordS); } else { if (debugDateParse) System.out.println(" adding " + myf.getPath()); } String location = myf.getPath(); Aggregation.Dataset ds = makeDataset(location, location, null, null, dateCoordS, null, enhance, null); datasets.add(ds); } // Sort by date if it exists, else filename. Collections.sort(datasets, new Comparator<Aggregation.Dataset>() { public int compare(Aggregation.Dataset ds1, Aggregation.Dataset ds2) { if(ds1.cd == null) return ds1.getLocation().compareTo(ds2.getLocation()) ; if (ds1.cd.dateCoord != null) // LOOK can we generalize return ds1.cd.dateCoord.compareTo(ds2.cd.dateCoord); else return ds1.cd.file.getName().compareTo(ds2.cd.file.getName()); } }); */ // add the explicit datasets - these need to be kept in order // LOOK - should they be before or after scanned? Does it make sense to mix scan and explicit? // AggFmrcSingle sets explicit datasets - the scan is empty for (Aggregation.Dataset dataset : explicitDatasets) { datasets.add(dataset); } // Remove unreadable files (i.e. due to permissions) from the aggregation. // LOOK: Is this logic we should install "upstream", perhaps in MFileCollectionManager? // It would affect other collections than just NcML aggregation in that case. for (Iterator<Dataset> datasetsIter = datasets.iterator(); datasetsIter.hasNext(); ) { Dataset dataset = datasetsIter.next(); Path datasetPath; if (dataset.getMFile() instanceof MFileOS) { datasetPath = ((MFileOS) dataset.getMFile()).getFile().toPath(); } else if (dataset.getMFile() instanceof MFileOS7) { datasetPath = ((MFileOS7) dataset.getMFile()).getNioPath(); } else { continue; } if (!Files.isReadable(datasetPath)) { // File.canRead() is broken on Windows, but the JDK7 methods work. logger.warn("Aggregation member isn't readable (permissions issue?). Skipping: " + datasetPath); datasetsIter.remove(); } } // check for duplicate location Set<String> dset = new HashSet<>( 2 * datasets.size()); for (Aggregation.Dataset dataset : datasets) { if (dset.contains(dataset.cacheLocation)) logger.warn("Duplicate dataset in aggregation = "+dataset.cacheLocation); dset.add(dataset.cacheLocation); } if (datasets.size() == 0) { throw new IllegalStateException("There are no datasets in the aggregation " + datasetManager); } }
java
{ "resource": "" }
q174661
Aggregation.getTypicalDataset
test
protected Dataset getTypicalDataset() throws IOException { List<Dataset> nestedDatasets = getDatasets(); int n = nestedDatasets.size(); if (n == 0) throw new FileNotFoundException("No datasets in this aggregation"); int select; if (typicalDatasetMode == TypicalDataset.LATEST) select = n - 1; else if (typicalDatasetMode == TypicalDataset.PENULTIMATE) select = (n < 2) ? 0 : n - 2; else if (typicalDatasetMode == TypicalDataset.FIRST) select = 0; else { // random is default if (r == null) r = new Random(); select = (n < 2) ? 0 : r.nextInt(n); } return nestedDatasets.get(select); }
java
{ "resource": "" }
q174662
Aggregation.makeDataset
test
protected Dataset makeDataset(String cacheName, String location, String id, String ncoordS, String coordValueS, String sectionSpec, EnumSet<NetcdfDataset.Enhance> enhance, ucar.nc2.util.cache.FileFactory reader) { return new Dataset(cacheName, location, id, enhance, reader); // overridden in OuterDim, tiled }
java
{ "resource": "" }
q174663
DatasetTrackerInMem.putResourceControl
test
void putResourceControl(Dataset ds) { if (logger.isDebugEnabled()) logger.debug("putResourceControl " + ds.getRestrictAccess() + " for " + ds.getName()); resourceControlHash.put(ds.getUrlPath(), ds.getRestrictAccess()); // resourceControl is inherited, but no guarentee that children paths are related, unless its a // DatasetScan or InvDatasetFmrc. So we keep track of all datasets that have a ResourceControl, including children // DatasetScan and InvDatasetFmrc must use a PathMatcher, others can use exact match (hash) /* if (ds instanceof DatasetScan) { DatasetScan scan = (DatasetScan) ds; if (debugResourceControl) System.out.println("putResourceControl " + ds.getRestrictAccess() + " for datasetScan " + scan.getPath()); resourceControlMatcher.put(scan.getPath(), ds.getRestrictAccess()); } else { // dataset if (debugResourceControl) System.out.println("putResourceControl " + ds.getRestrictAccess() + " for dataset " + ds.getUrlPath()); // LOOK: seems like you only need to add if InvAccess.InvService.isReletive // LOOK: seems like we should use resourceControlMatcher to make sure we match .dods, etc for (Access access : ds.getAccess()) { if (access.getService().isRelativeBase()) resourceControlHash.put(access.getUrlPath(), ds.getRestrictAccess()); } } */ hasResourceControl = true; }
java
{ "resource": "" }
q174664
CFLine.addPoint
test
public void addPoint(double x, double y) { Point ptPrev = null; if(points.size() > 0) { ptPrev = points.get(points.size() - 1); } this.points.add(new CFPoint(x, y, ptPrev, null, null)); }
java
{ "resource": "" }
q174665
CFLine.getBBUpper
test
public double[] getBBUpper() { double[] bbUpper = new double[2]; List<Point> ptList = this.getPoints(); if(ptList.isEmpty()) return null; bbUpper[0] = ptList.get(0).getY(); bbUpper[1] = ptList.get(0).getY(); for(Point pt : this.getPoints()) { if(bbUpper[0] < pt.getX()){ bbUpper[0] = pt.getX(); } if(bbUpper[1] < pt.getY()) { bbUpper[1] = pt.getY(); } } // Got maximum points, add some padding. bbUpper[0] += 10; bbUpper[1] += 10; return bbUpper; }
java
{ "resource": "" }
q174666
CFLine.getBBLower
test
public double[] getBBLower() { double[] bbLower = new double[2]; List<Point> ptList = this.getPoints(); if(ptList.isEmpty()) return null; bbLower[0] = ptList.get(0).getY(); bbLower[1] = ptList.get(0).getY(); for(Point pt : this.getPoints()) { if(bbLower[0] > pt.getX()){ bbLower[0] = pt.getX(); } if(bbLower[1] > pt.getY()) { bbLower[1] = pt.getY(); } } // Got minimum points, add some padding. bbLower[0] -= 10; bbLower[1] -= 10; return bbLower; }
java
{ "resource": "" }
q174667
DatasetFilter.validate
test
boolean validate(StringBuilder out) { this.isValid = true; // If log from construction has content, append to validation output msg. if (this.log.length() > 0) { out.append(this.log); } // Validity check: 'name' cannot be null. (Though, 'name' // can be an empty string.) if (this.getName() == null) { isValid = false; out.append(" ** DatasetFilter (4): null value for name is not valid."); } // Check that type is not null. if (this.getType() == null) { isValid = false; out.append(" ** DatasetFilter (5): null value for type is not valid (set with bad string?)."); } // Validity check: 'matchPattern' must be null if 'type' value // is not 'RegExp'. if (this.type == DatasetFilter.Type.REGULAR_EXPRESSION && this.matchPattern == null) { isValid = false; out.append(" ** DatasetFilter (6): null value for matchPattern not valid when type is 'RegExp'."); } if (this.type != DatasetFilter.Type.REGULAR_EXPRESSION && this.type != null && this.matchPattern != null) { isValid = false; out.append(" ** DatasetFilter (7): matchPattern value (" + this.matchPattern + ") must be null if type is not 'RegExp'."); } return (this.isValid); }
java
{ "resource": "" }
q174668
DatasetFilter.match
test
private boolean match(InvDataset dataset) { // Check whether this filter applies to the given dataset. if (this.getParentDatasetSource().isCollection(dataset) && !this.applyToCollectionDatasets) return (false); if ((!this.getParentDatasetSource().isCollection(dataset)) && !this.applyToAtomicDatasets) return (false); // Set the default matchPatternTarget so old versions still work. if (this.matchPatternTarget == null) { if (this.getParentDatasetSource().isCollection(dataset)) { this.setMatchPatternTarget("name"); } else { this.setMatchPatternTarget("urlPath"); } } if (this.type == DatasetFilter.Type.REGULAR_EXPRESSION) { boolean isMatch; if (this.getMatchPatternTarget().equals("name")) { java.util.regex.Matcher matcher = this.regExpPattern.matcher(dataset.getName()); isMatch = matcher.find(); } else if (this.getMatchPatternTarget().equals("urlPath")) { java.util.regex.Matcher matcher = this.regExpPattern.matcher(((InvDatasetImpl) dataset).getUrlPath()); isMatch = matcher.find(); } else { // ToDo deal with any matchPatternTarget (XPath-ish) isMatch = false; } // // Invert the meaning of a match (accept things that don't match). // if ( this.isRejectMatchingDatasets()) // { // // If match, return false. // return( regExpMatch == null ? true : false ); // } // // Don't invert (a match is a match). // else // { // If match, return true. return (isMatch); // } } else { System.err.println("WARNING -- DatasetFilter.accept(): unsupported type" + " <" + this.type.toString() + ">."); return (false); // @todo think about exceptions. //throw new java.lang.Exception( "DatasetFilter.accept():" + // " unsupported type <" + this.type.toString() + ">."); } }
java
{ "resource": "" }
q174669
SortingStationPointFeatureCache.addAll
test
public void addAll(FeatureDatasetPoint fdPoint) throws IOException { try (PointFeatureIterator pointFeatIter = new FlattenedDatasetPointCollection(fdPoint).getPointFeatureIterator()) { while (pointFeatIter.hasNext()) { StationPointFeature pointFeat = (StationPointFeature) pointFeatIter.next(); add(pointFeat); } } }
java
{ "resource": "" }
q174670
CEEvaluator.parseConstraint
test
public void parseConstraint(ReqState rs) throws ParseException, opendap.dap.DAP2Exception, NoSuchVariableException, NoSuchFunctionException, InvalidOperatorException, InvalidParameterException, SBHException, WrongTypeException { parseConstraint(rs.getConstraintExpression(),rs.getRequestURL().toString()); }
java
{ "resource": "" }
q174671
CEEvaluator.evalClauses
test
public boolean evalClauses(Object specialO) throws NoSuchVariableException, DAP2ServerSideException, IOException { boolean result = true; Enumeration ec = getClauses(); while (ec.hasMoreElements() && result == true) { Object o = ec.nextElement(); if (_Debug) { System.out.println("Evaluating clause: " + ec.nextElement()); } result = ((TopLevelClause) o).evaluate(); } // Hack: pop the projections of all DArrayDimensions that // have been pushed. return (result); }
java
{ "resource": "" }
q174672
CEEvaluator.printConstraint
test
public void printConstraint(PrintWriter pw) { Enumeration ec = getClauses(); boolean first = true; while (ec.hasMoreElements()) { Clause cl = (Clause)ec.nextElement(); if(!first) pw.print(" & "); cl.printConstraint(pw); first = false; } pw.flush(); }
java
{ "resource": "" }
q174673
HdfEos.amendFromODL
test
static public boolean amendFromODL(NetcdfFile ncfile, Group eosGroup) throws IOException { String smeta = getStructMetadata(eosGroup); if (smeta == null) { return false; } HdfEos fixer = new HdfEos(); fixer.fixAttributes(ncfile.getRootGroup()); fixer.amendFromODL(ncfile, smeta); return true; }
java
{ "resource": "" }
q174674
HdfEos.setSharedDimensions
test
private void setSharedDimensions(Variable v, List<Element> values, List<Dimension> unknownDims, String location) { if (values.size() == 0) { return; } // remove the "scalar" dumbension Iterator<Element> iter = values.iterator(); while (iter.hasNext()) { Element value = iter.next(); String dimName = value.getText().trim(); if (dimName.equalsIgnoreCase("scalar")) { iter.remove(); } } // gotta have same number of dimensions List<Dimension> oldDims = v.getDimensions(); if (oldDims.size() != values.size()) { log.error("Different number of dimensions for {} {}", v, location); return; } List<Dimension> newDims = new ArrayList<>(); Group group = v.getParentGroup(); for (int i = 0; i < values.size(); i++) { Element value = values.get(i); String dimName = value.getText().trim(); dimName = NetcdfFile.makeValidCdmObjectName(dimName); Dimension dim = group.findDimension(dimName); Dimension oldDim = oldDims.get(i); if (dim == null) { dim = checkUnknownDims(dimName, unknownDims, oldDim, location); } if (dim == null) { log.error("Unknown Dimension= {} for variable = {} {} ", dimName, v.getFullName(), location); return; } if (dim.getLength() != oldDim.getLength()) { log.error("Shared dimension ({}) has different length than data dimension ({}) shared={} org={} for {} {}", dim.getShortName(),oldDim.getShortName(), dim.getLength() , oldDim.getLength() , v,location); return; } newDims.add(dim); } v.setDimensions(newDims); if (showWork) { log.debug(" set shared dimensions for {}", v.getNameAndDimensions()); } }
java
{ "resource": "" }
q174675
HdfEos.checkUnknownDims
test
private Dimension checkUnknownDims(String wantDim, List<Dimension> unknownDims, Dimension oldDim, String location) { for (Dimension dim : unknownDims) { if (dim.getShortName().equals(wantDim)) { int len = oldDim.getLength(); if (len == 0) { dim.setUnlimited(true); // allow zero length dimension !! } dim.setLength(len); // use existing (anon) dimension Group parent = dim.getGroup(); parent.addDimensionIfNotExists(dim); // add to the parent unknownDims.remove(dim); // remove from list LOOK is this ok? log.warn("unknownDim {} length set to {}{}", wantDim, oldDim.getLength(), location); return dim; } } return null; }
java
{ "resource": "" }
q174676
HdfEos.findGroupNested
test
private Group findGroupNested(Group parent, String name) { for (Group g : parent.getGroups()) { if (g.getShortName().equals(name)) { return g; } } for (Group g : parent.getGroups()) { Group result = findGroupNested(g, name); if (result != null) { return result; } } return null; }
java
{ "resource": "" }
q174677
Documentation.readXlinkContent
test
public String readXlinkContent() throws java.io.IOException { if (uri == null) return ""; URL url = uri.toURL(); InputStream is = url.openStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(is.available()); // copy to string byte[] buffer = new byte[1024]; while (true) { int bytesRead = is.read(buffer); if (bytesRead == -1) break; os.write(buffer, 0, bytesRead); } is.close(); return new String(os.toByteArray(), CDM.utf8Charset); }
java
{ "resource": "" }
q174678
InvAccess.getStandardUri
test
public URI getStandardUri() { try { InvCatalog cat = dataset.getParentCatalog(); if (cat == null) return new URI(getUnresolvedUrlName()); return cat.resolveUri(getUnresolvedUrlName()); } catch (java.net.URISyntaxException e) { logger.warn("Error parsing URL= " + getUnresolvedUrlName()); return null; } }
java
{ "resource": "" }
q174679
ProjectionParamPanel.setProjection
test
public void setProjection(ProjectionManager.ProjectionClass pc) { // clear out any fields removeAll(); for (ProjectionManager.ProjectionParam pp : pc.paramList) { // construct the label JPanel thisPanel = new JPanel(); thisPanel.add(new JLabel(pp.name + ": ")); // text input field JTextField tf = new JTextField(); pp.setTextField(tf); tf.setColumns(12); thisPanel.add(tf); add(thisPanel); } revalidate(); }
java
{ "resource": "" }
q174680
LayoutM.addLayoutComponent
test
public void addLayoutComponent(Component comp, Object constraint) { if (debug) System.out.println(name+ " addLayoutComponent= "+ comp.getClass().getName()+" "+comp.hashCode()+" "+constraint); if (!(constraint instanceof Constraint)) throw new IllegalArgumentException( "MySpringLayout must be Constraint"); constraintMap.put( comp, constraint); globalBounds = null; }
java
{ "resource": "" }
q174681
LayoutM.invalidateLayout
test
public void invalidateLayout(Container target){ if (debug) System.out.println(name+" invalidateLayout "); globalBounds = null; // this probably need to be scheduled later ?? // layoutContainer( target); }
java
{ "resource": "" }
q174682
LayoutM.removeLayoutComponent
test
public void removeLayoutComponent(Component comp){ if (debug) System.out.println("removeLayoutComponent"); constraintMap.remove(comp); globalBounds = null; }
java
{ "resource": "" }
q174683
LayoutM.minimumLayoutSize
test
public Dimension minimumLayoutSize(Container parent){ if (debug) System.out.println("minimumLayoutSize"); if (globalBounds == null) layoutContainer(parent); return globalBounds.getSize(); }
java
{ "resource": "" }
q174684
LayoutM.layoutContainer
test
public void layoutContainer(Container target) { synchronized (target.getTreeLock()) { if (debug) System.out.println(name+ " layoutContainer "); // first layout any nested LayoutM components // it seems that generally Swing laysout from outer to inner ??? int n = target.getComponentCount(); for (int i=0 ; i<n ; i++) { Component comp = target.getComponent(i); if (comp instanceof Container) { Container c = (Container) comp; LayoutManager m = c.getLayout(); if (m instanceof LayoutM) m.layoutContainer( c); } } // now layout this container reset( target); globalBounds = new Rectangle(0,0,0,0); while ( !layoutPass( target)) target.setPreferredSize( globalBounds.getSize()); // ?? } }
java
{ "resource": "" }
q174685
RadialCoordSys.isRadialCoordSys
test
public static boolean isRadialCoordSys( Formatter parseInfo, CoordinateSystem cs) { return (cs.getAzimuthAxis() != null) && (cs.getRadialAxis() != null) && (cs.getElevationAxis() != null); }
java
{ "resource": "" }
q174686
RadialCoordSys.getMaximumRadial
test
public double getMaximumRadial() { if (maxRadial == 0.0) { try { Array radialData = getRadialAxisDataCached(); maxRadial = MAMath.getMaximum( radialData); String units = getRadialAxis().getUnitsString(); SimpleUnit radialUnit = SimpleUnit.factory(units); maxRadial = radialUnit.convertTo(maxRadial, SimpleUnit.kmUnit); // convert to km } catch (IOException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } return maxRadial; }
java
{ "resource": "" }
q174687
URLDumpPane.openURL
test
private void openURL(String urlString, Command command) { try { //Open the URLConnection for reading URL u = new URL(urlString); currentConnection = (HttpURLConnection) u.openConnection(); currentConnection.setRequestMethod(command.toString()); // GET or HEAD currentConnection.setAllowUserInteraction(true); clear(); appendLine(command + " request for " + urlString); // request headers Map<String, List<String>> reqs = currentConnection.getRequestProperties(); for (Map.Entry<String, List<String>> ent : reqs.entrySet()) { append(" " + ent.getKey() + ": "); for (String v : ent.getValue()) append(v + " "); appendLine(""); } appendLine(""); appendLine("getFollowRedirects=" + HttpURLConnection.getFollowRedirects()); appendLine("getInstanceFollowRedirects=" + currentConnection.getInstanceFollowRedirects()); appendLine("AllowUserInteraction=" + currentConnection.getAllowUserInteraction()); appendLine(""); int code = currentConnection.getResponseCode(); String response = currentConnection.getResponseMessage(); // response headers appendLine(" HTTP/1.x " + code + " " + response); appendLine(" content-length: " + currentConnection.getContentLength()); appendLine(" content-encoding: " + currentConnection.getContentEncoding()); appendLine(" content-type: " + currentConnection.getContentType()); appendLine("\nHeaders: "); for (int j = 1; true; j++) { String header = currentConnection.getHeaderField(j); String key = currentConnection.getHeaderFieldKey(j); if (header == null || key == null) break; appendLine(" " + key + ": " + header); } appendLine(""); appendLine("contents:"); // read it java.io.InputStream is = currentConnection.getInputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(200000); IO.copy(is, bout); is.close(); append(new String(bout.toByteArray(), CDM.utf8Charset)); appendLine("end contents"); } catch (MalformedURLException e) { append(urlString + " is not a parseable URL"); } catch (IOException e) { e.printStackTrace(); } }
java
{ "resource": "" }
q174688
GEOSTransform.earthToSat
test
public double[] earthToSat(double geographic_lon, double geographic_lat) { geographic_lat = geographic_lat * DEG_TO_RAD; geographic_lon = geographic_lon * DEG_TO_RAD; double geocentric_lat = Math.atan(((r_pol * r_pol) / (r_eq * r_eq)) * Math.tan(geographic_lat)); double r_earth = r_pol / Math.sqrt(1.0 - ((r_eq * r_eq - r_pol * r_pol) / (r_eq * r_eq)) * Math.cos(geocentric_lat) * Math.cos(geocentric_lat)); double r_1 = h - r_earth * Math.cos(geocentric_lat) * Math.cos(geographic_lon - sub_lon); double r_2 = -r_earth * Math.cos(geocentric_lat) * Math.sin(geographic_lon - sub_lon); double r_3 = r_earth * Math.sin(geocentric_lat); if (r_1 > h) { // often two geoid intersect points, use the closer one. return new double[]{Double.NaN, Double.NaN}; } double lamda_sat = Double.NaN; double theta_sat = Double.NaN; if (scan_geom.equals(GEOS)) { // GEOS (eg. SEVIRI, MSG) CGMS 03, 4.4.3.2, Normalized Geostationary Projection lamda_sat = Math.atan(-r_2 / r_1); theta_sat = Math.asin(r_3 / Math.sqrt(r_1 * r_1 + r_2 * r_2 + r_3 * r_3)); } else if (scan_geom.equals(GOES)) { // GOES (eg. GOES-R ABI) lamda_sat = Math.asin(-r_2 / Math.sqrt(r_1 * r_1 + r_2 * r_2 + r_3 * r_3)); theta_sat = Math.atan(r_3 / r_1); } return new double[]{lamda_sat, theta_sat}; }
java
{ "resource": "" }
q174689
GEOSTransform.satToEarth
test
public double[] satToEarth(double x, double y) { if (scan_geom.equals(GOES)) { // convert from GOES to GEOS for transfrom below double[] lambda_theta_geos = GOES_to_GEOS(x, y); x = lambda_theta_geos[0]; y = lambda_theta_geos[1]; } double c1 = (h * Math.cos(x) * Math.cos(y)) * (h * Math.cos(x) * Math.cos(y)); double c2 = (Math.cos(y) * Math.cos(y) + fp * Math.sin(y) * Math.sin(y)) * d; if (c1 < c2) { return new double[]{Double.NaN, Double.NaN}; } double s_d = Math.sqrt(c1 - c2); double s_n = (h * Math.cos(x) * Math.cos(y) - s_d) / (Math.cos(y) * Math.cos(y) + fp * Math.sin(y) * Math.sin(y)); double s_1 = h - s_n * Math.cos(x) * Math.cos(y); double s_2 = s_n * Math.sin(x) * Math.cos(y); double s_3 = -s_n * Math.sin(y); double s_xy = Math.sqrt(s_1 * s_1 + s_2 * s_2); double geographic_lon = Math.atan(s_2 / s_1) + sub_lon; double geographic_lat = Math.atan(-fp * (s_3 / s_xy)); double lonDegrees = RAD_TO_DEG * geographic_lon; double latDegrees = RAD_TO_DEG * geographic_lat; // force output longitude to -180 to 180 range if (lonDegrees < -180.0) lonDegrees += 360.0; if (lonDegrees > 180.0) lonDegrees -= 360.0; return new double[]{lonDegrees, latDegrees}; }
java
{ "resource": "" }
q174690
GEOSTransform.GOES_to_GEOS
test
public double[] GOES_to_GEOS(double lamda_goes, double theta_goes) { double theta_geos = Math.asin(Math.sin(theta_goes) * Math.cos(lamda_goes)); double lamda_geos = Math.atan(Math.tan(lamda_goes) / Math.cos(theta_goes)); return new double[]{lamda_geos, theta_geos}; }
java
{ "resource": "" }
q174691
GEOSTransform.scanGeomToSweepAngleAxis
test
public static String scanGeomToSweepAngleAxis(String scanGeometry) { String sweepAngleAxis = "y"; if (scanGeometry.equals(GOES)) { sweepAngleAxis = "x"; } return sweepAngleAxis; }
java
{ "resource": "" }
q174692
GEOSTransform.sweepAngleAxisToScanGeom
test
public static String sweepAngleAxisToScanGeom(String sweepAngleAxis) { String scanGeom = GOES; if (sweepAngleAxis.equals("y")) { scanGeom = GEOS; } return scanGeom; }
java
{ "resource": "" }
q174693
CoordinateTime2DUnionizer.setRuntimeCoords
test
void setRuntimeCoords(CoordinateRuntime runtimes) { for (int idx=0; idx<runtimes.getSize(); idx++) { CalendarDate cd = runtimes.getRuntimeDate(idx); long runtime = runtimes.getRuntime(idx); CoordinateTimeAbstract time = timeMap.get(runtime); if (time == null) { time = isTimeInterval ? new CoordinateTimeIntv(this.code, this.timeUnit, cd, new ArrayList<>(0), null) : new CoordinateTime(this.code, this.timeUnit, cd, new ArrayList<>(0), null); timeMap.put(runtime, time); } } }
java
{ "resource": "" }
q174694
CFPointObWriter.writePointObsDataset
test
public static void writePointObsDataset(PointObsDataset pobsDataset, String fileOut) throws IOException { // see if we have an altitude String altUnits = null; DataIterator iterOne = pobsDataset.getDataIterator(-1); while (iterOne.hasNext()) { PointObsDatatype pobsData = (PointObsDatatype) iterOne.nextData(); ucar.unidata.geoloc.EarthLocation loc = pobsData.getLocation(); altUnits = Double.isNaN(loc.getAltitude()) ? null : "meters"; break; } List<VariableSimpleIF> vars = pobsDataset.getDataVariables(); List<PointObVar> nvars = new ArrayList<PointObVar>(vars.size()); // put vars in order for (VariableSimpleIF v : vars) { if (v.getDataType().isNumeric()) nvars.add(new PointObVar(v)); } int ndoubles = vars.size(); double[] dvals = new double[ndoubles]; for (VariableSimpleIF v : vars) { if (v.getDataType().isString()) nvars.add(new PointObVar(v)); } String[] svals = new String[vars.size() - ndoubles]; FileOutputStream fos = new FileOutputStream(fileOut); DataOutputStream out = new DataOutputStream(fos); CFPointObWriter writer = new CFPointObWriter(out, pobsDataset.getGlobalAttributes(), altUnits, nvars, -1); DataIterator iter = pobsDataset.getDataIterator(1000 * 1000); while (iter.hasNext()) { PointObsDatatype pobsData = (PointObsDatatype) iter.nextData(); StructureData sdata = pobsData.getData(); int dcount = 0; int scount = 0; for (PointObVar v : nvars) { if (v.getDataType().isNumeric()) { Array data = sdata.getArray(v.getName()); data.resetLocalIterator(); if (data.hasNext()) dvals[dcount++] = data.nextDouble(); } else if (v.getDataType().isString()) { ArrayChar data = (ArrayChar) sdata.getArray(v.getName()); svals[scount++] = data.getString(); } } ucar.unidata.geoloc.EarthLocation loc = pobsData.getLocation(); writer.addPoint(loc.getLatitude(), loc.getLongitude(), loc.getAltitude(), pobsData.getObservationTimeAsDate(), dvals, svals); } writer.finish(); }
java
{ "resource": "" }
q174695
CFPointObWriter.rewritePointFeatureDataset
test
public static boolean rewritePointFeatureDataset(String fileIn, String fileOut, boolean inMemory) throws IOException { System.out.println("Rewrite2 .nc files from " + fileIn + " to " + fileOut + " inMemory= " + inMemory); long start = System.currentTimeMillis(); // do it in memory for speed NetcdfFile ncfile = inMemory ? NetcdfFile.openInMemory(fileIn) : NetcdfFile.open(fileIn); NetcdfDataset ncd = new NetcdfDataset(ncfile); Formatter errlog = new Formatter(); FeatureDataset fd = FeatureDatasetFactoryManager.wrap(FeatureType.ANY_POINT, ncd, null, errlog); if (fd == null) return false; if (fd instanceof FeatureDatasetPoint) { writePointFeatureCollection((FeatureDatasetPoint) fd, fileOut); fd.close(); long took = System.currentTimeMillis() - start; System.out.println(" that took " + (took - start) + " msecs"); return true; } return false; }
java
{ "resource": "" }
q174696
StructureData.getArraySequence
test
public ArraySequence getArraySequence(String memberName) { StructureMembers.Member m = members.findMember(memberName); if (m == null) throw new IllegalArgumentException("illegal member name =" + memberName); return getArraySequence(m); }
java
{ "resource": "" }
q174697
InvDataset.getFullName
test
public String getFullName() { return (parent == null) ? name : (parent.getFullName() == null || parent.getFullName().length() == 0) ? name : parent.getFullName() + "/" + name; }
java
{ "resource": "" }
q174698
InvDataset.getUniqueID
test
public String getUniqueID() { String authority = getAuthority(); if ((authority != null) && (getID() != null)) return authority + ":" + getID(); else if (getID() != null) return getID(); else return null; }
java
{ "resource": "" }
q174699
InvDataset.getAccess
test
public InvAccess getAccess(thredds.catalog.ServiceType type) { for (InvAccess a : getAccess()) { InvService s = a.getService(); if (s.getServiceType() == type) return a; } return null; }
java
{ "resource": "" }