_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q175900 | Attribute.appendValue | test | public void appendValue(String value, boolean check)
throws NoSuchAttributeException, AttributeBadValueException
{
checkVectorUsage();
if(check)
value = forceValue(type, value);
((Vector) attr).addElement(value);
} | java | {
"resource": ""
} |
q175901 | Attribute.dispatchCheckValue | test | private static void dispatchCheckValue(int type, String value)
throws AttributeBadValueException
{
switch (type) {
case BYTE:
if(!checkByte(value))
throw new AttributeBadValueException("`" + value + "' is not a Byte value.");
break;
case INT16:
if(!checkShort(value))
throw new AttributeBadValueException("`" + value + "' is not an Int16 value.");
break;
case UINT16:
if(!checkUShort(value))
throw new AttributeBadValueException("`" + value + "' is not an UInt16 value.");
break;
case INT32:
if(!checkInt(value))
throw new AttributeBadValueException("`" + value + "' is not an Int32 value.");
break;
case UINT32:
if(!checkUInt(value))
throw new AttributeBadValueException("`" + value + "' is not an UInt32 value.");
break;
case FLOAT32:
if(!checkFloat(value))
throw new AttributeBadValueException("`" + value + "' is not a Float32 value.");
break;
case FLOAT64:
if(!checkDouble(value))
throw new AttributeBadValueException("`" + value + "' is not a Float64 value.");
break;
// case BOOLEAN:
// if(!checkBoolean(value))
// throw new AttributeBadValueException("`" + value + "' is not a Boolean value.");
// break;
default:
// Assume UNKNOWN, CONTAINER, STRING, and URL are okay.
}
} | java | {
"resource": ""
} |
q175902 | Attribute.forceValue | test | private static String forceValue(int type, String value)
throws AttributeBadValueException
{
try {
dispatchCheckValue(type, value);
} catch (AttributeBadValueException abe) {
if(type == BYTE) {// Try again: allow e.g. negative byte values
short val = Short.parseShort(value);
if(val > 255 && val < -128)
throw new AttributeBadValueException("Cannot convert to byte: " + value);
value = Integer.toString((val&0xFF));
}
}
return value;
} | java | {
"resource": ""
} |
q175903 | Attribute.checkByte | test | private static final boolean checkByte(String s)
throws AttributeBadValueException
{
try {
// Byte.parseByte() can't be used because values > 127 are allowed
short val = Short.parseShort(s);
if(DebugValueChecking) {
log.debug("Attribute.checkByte() - string: '" + s + "' value: " + val);
}
if(val > 0xFF || val < 0)
return false;
else
return true;
} catch (NumberFormatException e) {
throw new AttributeBadValueException("`" + s + "' is not a Byte value.");
}
} | java | {
"resource": ""
} |
q175904 | Attribute.checkShort | test | private static final boolean checkShort(String s)
{
try {
short val = Short.parseShort(s);
if(DebugValueChecking) {
DAPNode.log.debug("Attribute.checkShort() - string: '" + s + "' value: " + val);
}
return true;
} catch (NumberFormatException e) {
return false;
}
} | java | {
"resource": ""
} |
q175905 | Attribute.checkInt | test | private static final boolean checkInt(String s)
{
try {
//Coverity[FB.DLS_DEAD_LOCAL_STORE]
int val = Integer.parseInt(s);
if(DebugValueChecking) {
DAPNode.log.debug("Attribute.checkInt() - string: '" + s + "' value: " + val);
}
return true;
} catch (NumberFormatException e) {
return false;
}
} | java | {
"resource": ""
} |
q175906 | Attribute.checkUInt | test | private static final boolean checkUInt(String s)
{
// Note: Because there is no Unsigned class in Java, use Long instead.
try {
long val = Long.parseLong(s);
if(DebugValueChecking) {
DAPNode.log.debug("Attribute.checkUInt() - string: '" + s + "' value: " + val);
}
if(val > 0xFFFFFFFFL)
return false;
else
return true;
} catch (NumberFormatException e) {
return false;
}
} | java | {
"resource": ""
} |
q175907 | Attribute.checkFloat | test | private static final boolean checkFloat(String s)
{
try {
//Coverity[FB.DLS_DEAD_LOCAL_STORE]=
float val = Float.parseFloat(s);
if(DebugValueChecking) {
DAPNode.log.debug("Attribute.checkFloat() - string: '" + s + "' value: " + val);
}
return true;
} catch (NumberFormatException e) {
if(s.equalsIgnoreCase("nan") || s.equalsIgnoreCase("inf"))
return true;
return false;
}
} | java | {
"resource": ""
} |
q175908 | Attribute.checkDouble | test | private static final boolean checkDouble(String s)
{
try {
//Coverity[FB.DLS_DEAD_LOCAL_STORE]
double val = Double.parseDouble(s);
if(DebugValueChecking) {
DAPNode.log.debug("Attribute.checkDouble() - string: '" + s + "' value: " + val);
}
return true;
} catch (NumberFormatException e) {
if(s.equalsIgnoreCase("nan") || s.equalsIgnoreCase("inf"))
return true;
return false;
}
} | java | {
"resource": ""
} |
q175909 | EnhanceScaleMissingUnsignedImpl.getAttributeDataType | test | private DataType getAttributeDataType(Attribute attribute) {
DataType dataType = attribute.getDataType();
if (signedness == Signedness.UNSIGNED) {
// If variable is unsigned, make its integral attributes unsigned too.
dataType = dataType.withSignedness(signedness);
}
return dataType;
} | java | {
"resource": ""
} |
q175910 | Godiva3Viewer.isViewable | test | @Override
public boolean isViewable(Dataset ds) {
Access access = ds.getAccess(ServiceType.WMS);
return access != null && (ThreddsConfig.getBoolean("WMS.allow", false));
} | java | {
"resource": ""
} |
q175911 | StringValidateEncodeUtils.validBooleanString | test | @SuppressWarnings({"SimplifiableIfStatement"})
public static boolean validBooleanString(String boolString) {
if (boolString == null)
return false;
Matcher m = VALID_CHARACTERS_FOR_BOOLEAN_STRING_PATTERN.matcher(boolString);
if (!m.matches())
return false;
return boolString.equalsIgnoreCase("true")
|| boolString.equalsIgnoreCase("false");
} | java | {
"resource": ""
} |
q175912 | StringValidateEncodeUtils.validAlphanumericString | test | public static boolean validAlphanumericString(String alphNumString) {
if (alphNumString == null)
return false;
Matcher m = VALID_CHARACTERS_FOR_ALPHANUMERIC_STRING_PATTERN.matcher(alphNumString);
return m.matches();
} | java | {
"resource": ""
} |
q175913 | StringValidateEncodeUtils.validAlphanumericStringConstrainedSet | test | public static boolean validAlphanumericStringConstrainedSet(String alphNumString,
String[] constrainedSet,
boolean ignoreCase) {
if (alphNumString == null || constrainedSet == null || constrainedSet.length == 0)
return false;
Matcher m = VALID_CHARACTERS_FOR_ALPHANUMERIC_STRING_PATTERN.matcher(alphNumString);
if (!m.matches())
return false;
for (String s : constrainedSet) {
if (ignoreCase ? alphNumString.equalsIgnoreCase(s) : alphNumString.equals(s))
return true;
}
return false;
} | java | {
"resource": ""
} |
q175914 | StringValidateEncodeUtils.descendOnlyFilePath | test | @SuppressWarnings({"UnnecessaryContinue"})
public static boolean descendOnlyFilePath(String path) {
String[] pathSegments = path.split("/");
//String[] newPathSegments = new String[pathSegments.length];
int i = 0;
for (int indxOrigSegs = 0; indxOrigSegs < pathSegments.length; indxOrigSegs++) {
String s = pathSegments[indxOrigSegs];
if (s.equals("."))
continue;
else if (s.equals("..")) {
if (i == 0)
return false;
i--;
} else {
//newPathSegments[i] = s;
i++;
}
}
return true;
} | java | {
"resource": ""
} |
q175915 | StringValidateEncodeUtils.unicodeCodePoint2PercentHexString | test | public static String unicodeCodePoint2PercentHexString(int codePoint, String charsetName) {
if (!Character.isDefined(codePoint))
throw new IllegalArgumentException(String.format("Given code point [U+%1$04X - %1$d] not assigned to an abstract character.", codePoint));
if (Character.getType(codePoint) == Character.SURROGATE)
throw new IllegalArgumentException(String.format("Given code point [U+%1$04X - %1$d] is an unencodable (by itself) surrogate character.", codePoint));
Charset charset = Charset.availableCharsets().get(charsetName);
if (charset == null)
throw new IllegalArgumentException(String.format("Unsupported charset [%s].", charsetName));
char[] chars = Character.toChars(codePoint);
ByteBuffer byteBuffer = null;
try {
byteBuffer = charset.newEncoder().encode(CharBuffer.wrap(chars));
} catch (CharacterCodingException e) {
String message = String.format("Given code point [U+%1$04X - %1$d] cannot be encode in given charset [%2$s].", codePoint, charsetName);
throw new IllegalArgumentException(message, e);
}
byteBuffer.rewind();
StringBuilder encodedString = new StringBuilder();
for (int i = 0; i < byteBuffer.limit(); i++) {
String asHex = Integer.toHexString(byteBuffer.get() & 0xFF);
encodedString.append("%").append(asHex.length() == 1 ? "0" : "").append(asHex);
}
return encodedString.toString();
} | java | {
"resource": ""
} |
q175916 | GridDefRecord.getParam | test | public final String getParam(String key) {
String value = paramStr.get(key);
if(value == null) { // check the dbl and int tables
Double result = paramDbl.get(key);
if (result != null) {
value = result.toString();
} else {
Integer intResult = paramInt.get(key);
if (intResult != null) {
value = intResult.toString();
}
}
// save it back off to the string table for next time
if (value != null) {
paramStr.put(key, value);
}
}
if (debug && value == null) {
System.out.println( key +" value not found");
}
return value;
} | java | {
"resource": ""
} |
q175917 | GridDefRecord.compare | test | public static boolean compare( GridDefRecord local, GridDefRecord other ) {
java.util.Set<String> keys = local.getKeys();
java.util.Set<String> okeys = other.getKeys();
if( keys.size() != okeys.size() )
return false;
for( String key : keys ) {
if( key.equals(WIND_FLAG) || key.equals(RESOLUTION) || key.equals(VECTOR_COMPONENT_FLAG)
|| key.equals(GDS_KEY))
continue;
String val = local.getParam( key );
String oval = other.getParam( key ); //
if( val.matches( "^[0-9]+\\.[0-9]*")) {
//double
double d = local.getDouble( key );
double od = other.getDouble( key );
if( ! Misc.nearlyEquals(d, od) )
return false;
} else if( val.matches( "^[0-9]+")) {
// int
if( !val.equals( oval ))
return false;
} else {
// String
if( !val.equals( oval ))
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q175918 | MessageBroker.process | test | public void process(InputStream is) throws IOException {
int pos = -1;
Buffer b = null;
while (true) {
b = (pos < 0) ? readBuffer(is) : readBuffer(is, b, pos);
pos = process(b, is);
if (b.done) break;
}
} | java | {
"resource": ""
} |
q175919 | MessageBroker.process | test | private int process(Buffer b, InputStream is) throws IOException {
int start = 0;
while (start < b.have) {
int matchPos = matcher.indexOf(b.buff, start, b.have - start);
// didnt find "BUFR" match
if (matchPos < 0) {
if (start == 0) // discard all but last 3 bytes
return b.have - 3;
else
return start; // indicates part of the buffer thats not processed
}
// do we have the length already read ??
if (matchPos + 6 >= b.have) {
return start; // this will save the end of the buffer and read more in.
}
// read BUFR message length
int b1 = (b.buff[matchPos + 4] & 0xff);
int b2 = (b.buff[matchPos + 5] & 0xff);
int b3 = (b.buff[matchPos + 6] & 0xff);
int messLen = b1 << 16 | b2 << 8 | b3;
// System.out.println("match at=" + matchPos + " len= " + messLen);
// create a task for this message
//int headerLen = matchPos - start;
MessageTask task = new MessageTask(messLen);
task.header = extractHeader(start, matchPos, b);
// copy message bytes into it
int last = matchPos + messLen;
if (last > b.have) {
task.have = b.have - matchPos;
System.arraycopy(b.buff, matchPos, task.mess, 0, task.have);
// read the rest of the message
if (!readBuffer(is, task.mess, task.have, task.len - task.have)) {
System.out.println("Failed to read remaining BUFR message");
break;
}
} else {
task.have = task.len;
System.arraycopy(b.buff, matchPos, task.mess, 0, task.have);
}
boolean ok = true;
// check on ending
for (int i = task.len - 4; i < task.len; i++) {
int bb = task.mess[i];
if (bb != 55) {
//System.out.println("Missing End of BUFR message at pos=" + i + " " + bb);
ok = false;
bad_msgs++;
}
}
try {
if (ok) messQ.put(task);
total_msgs++;
//System.out.println(" added message " + task.id + " start=" + matchPos + " end= " + (matchPos + messLen));
} catch (InterruptedException e) {
System.out.println(" interrupted queue put - assume process exit");
break;
}
start = matchPos + messLen + 1;
}
return -1;
} | java | {
"resource": ""
} |
q175920 | Ceparse.removeQuotes | test | String removeQuotes(String s)
{
if (s.startsWith("\"") && s.endsWith("\""))
return s.substring(1, s.length() - 1);
else
return s;
} | java | {
"resource": ""
} |
q175921 | Ceparse.markStackedVariables | test | void markStackedVariables(Stack s)
{
// Reverse the stack.
Stack bts = new Stack();
// LogStream.err.println("Variables to be marked:");
while (!s.empty()) {
// LogStream.err.println(((BaseType)s.peek()).getName());
bts.push(s.pop());
}
// For each but the last stack element, set the projection.
// setProject(true, false) for a ctor type sets the projection for
// the ctor itself but *does not* set the projection for all its
// children. Thus, if a user wants the variable S.X, and S contains Y
// and Z too, S's projection will be set (so serialize will descend
// into S) but X, Y and Z's projection remain clear. In this example,
// X's projection is set by the code that follows the while loop.
// 1/28/2000 jhrg
while (bts.size() > 1) {
ServerMethods ct = (ServerMethods) bts.pop();
ct.setProject(true, false);
}
// For the last element, project the entire variable.
ServerMethods bt = (ServerMethods) bts.pop();
bt.setProject(true, true);
} | java | {
"resource": ""
} |
q175922 | NcmlEditor.writeNcml | test | boolean writeNcml(String location) {
boolean err = false;
closeOpenFiles();
try {
final String result;
ds = openDataset(location, addCoords, null);
if (ds == null) {
editor.setText("Failed to open <" + location + ">");
}
else {
final NcMLWriter ncmlWriter = new NcMLWriter();
final Element netcdfElem = ncmlWriter.makeNetcdfElement(ds, null);
result = ncmlWriter.writeToString(netcdfElem);
editor.setText(result);
editor.setCaretPosition(0);
}
}
catch (Exception e) {
final StringWriter sw = new StringWriter(10000);
e.printStackTrace();
e.printStackTrace(new PrintWriter(sw));
editor.setText(sw.toString());
err = true;
}
return !err;
} | java | {
"resource": ""
} |
q175923 | TdsConfigMapper.getValueFromThreddsConfig | test | private static String getValueFromThreddsConfig(String key, String alternateKey, String defaultValue) {
String value = ThreddsConfig.get(key, null);
if (value == null && alternateKey != null)
value = ThreddsConfig.get(alternateKey, null);
if (value == null)
value = defaultValue;
return value;
} | java | {
"resource": ""
} |
q175924 | EnumTypedef.writeCDL | test | public String writeCDL(boolean strict) {
Formatter out = new Formatter();
writeCDL(out, new Indent(2), strict);
return out.toString();
} | java | {
"resource": ""
} |
q175925 | StationCollectionStream.createStationHelper | test | @Override
protected StationHelper createStationHelper() throws IOException {
// read in all the stations with the "stations" query
StationHelper stationHelper = new StationHelper();
try (InputStream in = CdmRemote.sendQuery(null, uri, "req=stations")) {
PointStream.MessageType mtype = PointStream.readMagic(in);
if (mtype != PointStream.MessageType.StationList) {
throw new RuntimeException("Station Request: bad response");
}
int len = NcStream.readVInt(in);
byte[] b = new byte[len];
NcStream.readFully(in, b);
PointStreamProto.StationList stationsp = PointStreamProto.StationList.parseFrom(b);
for (ucar.nc2.ft.point.remote.PointStreamProto.Station sp : stationsp.getStationsList()) {
// Station s = new StationImpl(sp.getId(), sp.getDesc(), sp.getWmoId(), sp.getLat(), sp.getLon(), sp.getAlt());
stationHelper.addStation(new StationFeatureStream(null, null)); // LOOK WRONG
}
return stationHelper;
}
} | java | {
"resource": ""
} |
q175926 | ResultService.validate | test | protected 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);
}
// Check that 'accessPointHeader' attribute is not null.
if ( this.getAccessPointHeader() == null)
{
this.isValid = false;
out.append( " ** ResultService (1): a null 'accessPointHeader' is invalid.");
}
return( this.isValid);
} | java | {
"resource": ""
} |
q175927 | Cinrad2Record.getAzimuth | test | public float getAzimuth() {
if (message_type != 1) return -1.0f;
if(Cinrad2IOServiceProvider.isSC)
return 360.0f * azimuth_ang / 65536.0f;
else if(Cinrad2IOServiceProvider.isCC)
return 360.0f * azimuth_ang / 512.0f;
else if(Cinrad2IOServiceProvider.isCC20)
return azimuth_ang * 0.01f;
return 180.0f * azimuth_ang / 32768.0f;
} | java | {
"resource": ""
} |
q175928 | Cinrad2Record.getElevation | test | public float getElevation() {
if (message_type != 1) return -1.0f;
if(Cinrad2IOServiceProvider.isSC)
return 120.0f * elevation_ang / 65536.0f;
else if(Cinrad2IOServiceProvider.isCC)
return elevation_ang * 0.01f;
else if(Cinrad2IOServiceProvider.isCC20)
return elevation_ang * 0.01f;
return 180.0f * elevation_ang / 32768.0f;
} | java | {
"resource": ""
} |
q175929 | DoradeSWIB.getLatitudes | test | public float[] getLatitudes() {
if (myASIBs == null)
return null;
float[] lats = new float[nRays];
for (int i = 0; i < nRays; i++)
lats[i] = myASIBs[i].getLatitude();
return lats;
} | java | {
"resource": ""
} |
q175930 | DoradeSWIB.getLongitudes | test | public float[] getLongitudes() {
if (myASIBs == null)
return null;
float[] lons = new float[nRays];
for (int i = 0; i < nRays; i++)
lons[i] = myASIBs[i].getLongitude();
return lons;
} | java | {
"resource": ""
} |
q175931 | DoradeSWIB.getAltitudes | test | public float[] getAltitudes() {
if (myASIBs == null)
return null;
float[] alts = new float[nRays];
for (int i = 0; i < nRays; i++)
alts[i] = myASIBs[i].getAltitude();
return alts;
} | java | {
"resource": ""
} |
q175932 | DoradeSWIB.getAzimuths | test | public float[] getAzimuths() {
if (azimuths == null) {
azimuths = new float[nRays];
for (int r = 0; r < nRays; r++) {
azimuths[r] = myRYIBs[r].getAzimuth();
}
}
return azimuths;
} | java | {
"resource": ""
} |
q175933 | DoradeSWIB.getElevations | test | public float[] getElevations() {
if (elevations == null) {
elevations = new float[nRays];
for (int r = 0; r < nRays; r++) {
elevations[r] = myRYIBs[r].getElevation();
}
}
return elevations;
} | java | {
"resource": ""
} |
q175934 | Structure.select | test | public Structure select( List<String> memberNames) {
Structure result = (Structure) copy();
List<Variable> members = new ArrayList<>();
for (String name : memberNames) {
Variable m = findVariable(name);
if (null != m) members.add(m);
}
result.setMemberVariables(members);
result.isSubset = true;
return result;
} | java | {
"resource": ""
} |
q175935 | Structure.select | test | public Structure select( String varName) {
List<String> memberNames = new ArrayList<>(1);
memberNames.add(varName);
return select(memberNames);
} | java | {
"resource": ""
} |
q175936 | Structure.addMemberVariable | test | public Variable addMemberVariable( Variable v) {
if (isImmutable()) throw new IllegalStateException("Cant modify");
members.add( v);
memberHash.put( v.getShortName(), v);
v.setParentStructure( this);
return v;
} | java | {
"resource": ""
} |
q175937 | Structure.setMemberVariables | test | public void setMemberVariables( List<Variable> vars) {
if (isImmutable()) throw new IllegalStateException("Cant modify");
members = new ArrayList<>();
memberHash = new HashMap<>(2*vars.size());
for (Variable v : vars) {
addMemberVariable(v);
}
} | java | {
"resource": ""
} |
q175938 | Structure.setParentGroup | test | @Override
public void setParentGroup(Group group) {
if (isImmutable())
throw new IllegalStateException("Cant modify");
super.setParentGroup(group);
if(members != null)
{
for (Variable v : members) {
v.setParentGroup(group);
}
}
} | java | {
"resource": ""
} |
q175939 | Structure.calcElementSize | test | public void calcElementSize() {
int total = 0;
for (Variable v : members) {
total += v.getElementSize() * v.getSize();
}
elementSize = total;
} | java | {
"resource": ""
} |
q175940 | Structure.readStructure | test | public StructureData readStructure(int index) throws IOException, ucar.ma2.InvalidRangeException {
Section section = null; // works for scalars i think
if (getRank() == 1) {
section = new Section().appendRange(index,index);
} else if (getRank() > 1) {
Index ii = Index.factory(shape); // convert to nD index
ii.setCurrentCounter(index);
int[] origin = ii.getCurrentCounter();
section = new Section();
for (int anOrigin : origin)
section.appendRange(anOrigin, anOrigin);
}
Array dataArray = read(section);
ArrayStructure data = (ArrayStructure) dataArray;
return data.getStructureData(0);
} | java | {
"resource": ""
} |
q175941 | Structure.readStructure | test | public ArrayStructure readStructure(int start, int count) throws IOException, ucar.ma2.InvalidRangeException {
if (getRank() != 1) throw new java.lang.UnsupportedOperationException("not a vector structure");
int[] origin = new int[] {start};
int[] shape = new int[] {count};
if (NetcdfFile.debugStructureIterator)
System.out.println("readStructure "+start+" "+count);
return (ArrayStructure) read(origin, shape);
} | java | {
"resource": ""
} |
q175942 | Structure.getStructureIterator | test | public StructureDataIterator getStructureIterator(int bufferSize) throws java.io.IOException {
return (getRank() < 2) ? new Structure.IteratorRank1(bufferSize) : new Structure.Iterator(bufferSize);
} | java | {
"resource": ""
} |
q175943 | TableA.getDataCategory | test | static public String getDataCategory(int cat) {
if (tableA == null) init();
String result = tableA.get(cat);
return result != null ? result : "Unknown category=" + cat;
} | java | {
"resource": ""
} |
q175944 | ProjectionImpl.getClassName | test | public String getClassName() {
String className = getClass().getName();
int index = className.lastIndexOf(".");
if (index >= 0) {
className = className.substring(index + 1);
}
return className;
} | java | {
"resource": ""
} |
q175945 | ProjectionImpl.addParameter | test | protected void addParameter(String name, String value) {
atts.add(new Parameter(name, value));
} | java | {
"resource": ""
} |
q175946 | ProjectionImpl.getHeader | test | public static String getHeader() {
StringBuilder headerB = new StringBuilder(60);
headerB.append("Name");
Format.tab(headerB, 20, true);
headerB.append("Class");
Format.tab(headerB, 40, true);
headerB.append("Parameters");
return headerB.toString();
} | java | {
"resource": ""
} |
q175947 | ProjectionImpl.latLonToProjBB2 | test | ProjectionRect latLonToProjBB2(LatLonRect latlonRect) {
double minx, maxx, miny, maxy;
LatLonPointImpl llpt = latlonRect.getLowerLeftPoint();
LatLonPointImpl urpt = latlonRect.getUpperRightPoint();
LatLonPointImpl lrpt = latlonRect.getLowerRightPoint();
LatLonPointImpl ulpt = latlonRect.getUpperLeftPoint();
if (isLatLon()) {
minx = getMinOrMaxLon(llpt.getLongitude(), ulpt.getLongitude(), true);
miny = Math.min(llpt.getLatitude(), lrpt.getLatitude());
maxx = getMinOrMaxLon(urpt.getLongitude(), lrpt.getLongitude(), false);
maxy = Math.min(ulpt.getLatitude(), urpt.getLatitude());
} else {
ProjectionPoint ll = latLonToProj(llpt, new ProjectionPointImpl());
ProjectionPoint ur = latLonToProj(urpt, new ProjectionPointImpl());
ProjectionPoint lr = latLonToProj(lrpt, new ProjectionPointImpl());
ProjectionPoint ul = latLonToProj(ulpt, new ProjectionPointImpl());
minx = Math.min(ll.getX(), ul.getX());
miny = Math.min(ll.getY(), lr.getY());
maxx = Math.max(ur.getX(), lr.getX());
maxy = Math.max(ul.getY(), ur.getY());
}
return new ProjectionRect(minx, miny, maxx, maxy);
} | java | {
"resource": ""
} |
q175948 | CF1Convention.getVersion | test | public static int getVersion(String hasConvName) {
int result = extractVersion(hasConvName);
if (result >= 0) return result;
List<String> names = breakupConventionNames(hasConvName);
for (String name : names) {
result = extractVersion(name);
if (result >= 0) return result;
}
return -1;
} | java | {
"resource": ""
} |
q175949 | CF1Convention.getZisPositive | test | public static String getZisPositive(String zaxisName, String vertCoordUnits) {
if (vertCoordUnits == null) return CF.POSITIVE_UP;
if (vertCoordUnits.isEmpty()) return CF.POSITIVE_UP;
if (SimpleUnit.isCompatible("millibar", vertCoordUnits))
return CF.POSITIVE_DOWN;
if (SimpleUnit.isCompatible("m", vertCoordUnits))
return CF.POSITIVE_UP;
// dunno - make it up
return CF.POSITIVE_UP;
} | java | {
"resource": ""
} |
q175950 | ImageFactoryRandom.delete | test | public boolean delete() {
if (nextFile == null) return false;
fileList.remove( nextFile);
File f = new File("C:/tmp/deleted/"+nextFile.getName());
return nextFile.renameTo(f);
} | java | {
"resource": ""
} |
q175951 | CoverageRenderer.setColorScaleParams | test | private void setColorScaleParams() {
if (dataMinMaxType == ColorScale.MinMaxType.hold && !isNewField)
return;
isNewField = false;
GeoReferencedArray dataArr = readHSlice(wantLevel, wantTime, wantEnsemble, wantRunTime);
//else
// dataArr = makeVSlice(stridedGrid, wantSlice, wantTime, wantEnsemble, wantRunTime);
if (dataArr != null) {
MAMath.MinMax minmax = MAMath.getMinMaxSkipMissingData(dataArr.getData(), dataState.grid);
colorScale.setMinMax(minmax.min, minmax.max);
colorScale.setGeoGrid(dataState.grid);
}
} | java | {
"resource": ""
} |
q175952 | CoverageRenderer.renderPlanView | test | public void renderPlanView(java.awt.Graphics2D g, AffineTransform dFromN) {
if ((dataState.grid == null) || (colorScale == null) || (drawProjection == null))
return;
if (!drawGrid && !drawContours)
return;
// no anitaliasing
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
dataH = readHSlice(wantLevel, wantTime, wantEnsemble, wantRunTime);
if (dataH == null)
return;
setColorScaleParams();
if (drawGrid)
drawGridHoriz(g, dataH);
//if (drawContours)
// drawContours(g, dataH.transpose(0, 1), dFromN);
if (drawGridLines)
drawGridLines(g, dataH);
if (drawBB)
drawGridBB(g, this.dataState.coverageDataset.getLatlonBoundingBox());
} | java | {
"resource": ""
} |
q175953 | H5Group.isChildOf | test | boolean isChildOf(H5Group that) {
if (parent == null) return false;
if (parent == that) return true;
return parent.isChildOf(that);
} | java | {
"resource": ""
} |
q175954 | MessageType.getType | test | public static MessageType getType(String name) {
if (name == null) return null;
return hash.get(name);
} | java | {
"resource": ""
} |
q175955 | TableAligner.installInAllColumns | test | public static void installInAllColumns(JTable table, int alignment) {
// We don't want to set up completely new cell renderers: rather, we want to use the existing ones but just
// change their alignment.
for (int colViewIndex = 0; colViewIndex < table.getColumnCount(); ++colViewIndex) {
installInOneColumn(table, colViewIndex, alignment);
}
} | java | {
"resource": ""
} |
q175956 | CoinbaseBuilder.withApiKey | test | public CoinbaseBuilder withApiKey(String api_key, String api_secret) {
this.api_key = api_key;
this.api_secret = api_secret;
return this;
} | java | {
"resource": ""
} |
q175957 | Label.of | test | public static Label of(String value) {
return new Label(value, false, false, false, false, null, null);
} | java | {
"resource": ""
} |
q175958 | Label.lines | test | public static Label lines(Justification just, String... lines) {
final String sep = just == LEFT ? "\\l" : just == RIGHT ? "\\r" : "\n";
final String value = Stream.of(lines).map(line -> line + sep).collect(joining());
return new Label(value, false, false, false, false, null, null);
} | java | {
"resource": ""
} |
q175959 | Label.html | test | public static Label html(String value) {
return new Label(value, true, false, false, false, null, null);
} | java | {
"resource": ""
} |
q175960 | CoreSocketFactory.connect | test | public Socket connect(Properties props, String socketPathFormat) throws IOException {
// Gather parameters
final String csqlInstanceName = props.getProperty(CLOUD_SQL_INSTANCE_PROPERTY);
final List<String> ipTypes = listIpTypes(props.getProperty("ipTypes", DEFAULT_IP_TYPES));
final boolean forceUnixSocket = System.getenv("CLOUD_SQL_FORCE_UNIX_SOCKET") != null;
// Validate parameters
Preconditions.checkArgument(
csqlInstanceName != null,
"cloudSqlInstance property not set. Please specify this property in the JDBC URL or the "
+ "connection Properties with value in form \"project:region:instance\"");
// GAE Standard runtimes provide a connection path at "/cloudsql/<CONNECTION_NAME>"
if (forceUnixSocket || runningOnGaeStandard()) {
logger.info(
String.format(
"Connecting to Cloud SQL instance [%s] via unix socket.", csqlInstanceName));
UnixSocketAddress socketAddress =
new UnixSocketAddress(new File(String.format(socketPathFormat, csqlInstanceName)));
return UnixSocketChannel.open(socketAddress).socket();
}
logger.info(
String.format("Connecting to Cloud SQL instance [%s] via SSL socket.", csqlInstanceName));
return getInstance().createSslSocket(csqlInstanceName, ipTypes);
} | java | {
"resource": ""
} |
q175961 | CoreSocketFactory.listIpTypes | test | private static List<String> listIpTypes(String cloudSqlIpTypes) {
String[] rawTypes = cloudSqlIpTypes.split(",");
ArrayList<String> result = new ArrayList<>(rawTypes.length);
for (int i = 0; i < rawTypes.length; i++) {
if (rawTypes[i].trim().equalsIgnoreCase("PUBLIC")) {
result.add(i, "PRIMARY");
} else {
result.add(i, rawTypes[i].trim().toUpperCase());
}
}
return result;
} | java | {
"resource": ""
} |
q175962 | SocketFactory.connect | test | public <T extends Closeable> T connect(
String host, int portNumber, Properties props, int loginTimeout) throws IOException {
@SuppressWarnings("unchecked")
T socket =
(T)
CoreSocketFactory.getInstance()
.connect(props, CoreSocketFactory.MYSQL_SOCKET_FILE_FORMAT);
return socket;
} | java | {
"resource": ""
} |
q175963 | FluentLoggerFactory.purgeLogger | test | protected synchronized void purgeLogger(FluentLogger logger) {
Iterator<Entry<FluentLogger, String>> it = loggers.entrySet().iterator();
while (it.hasNext()) {
if (it.next().getKey() == logger) {
it.remove();
return;
}
}
} | java | {
"resource": ""
} |
q175964 | InMemoryJavaCompiler.compileAll | test | public Map<String, Class<?>> compileAll() throws Exception {
if (sourceCodes.size() == 0) {
throw new CompilationException("No source code to compile");
}
Collection<SourceCode> compilationUnits = sourceCodes.values();
CompiledCode[] code;
code = new CompiledCode[compilationUnits.size()];
Iterator<SourceCode> iter = compilationUnits.iterator();
for (int i = 0; i < code.length; i++) {
code[i] = new CompiledCode(iter.next().getClassName());
}
DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(null, null, null), classLoader);
JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, collector, options, null, compilationUnits);
boolean result = task.call();
if (!result || collector.getDiagnostics().size() > 0) {
StringBuffer exceptionMsg = new StringBuffer();
exceptionMsg.append("Unable to compile the source");
boolean hasWarnings = false;
boolean hasErrors = false;
for (Diagnostic<? extends JavaFileObject> d : collector.getDiagnostics()) {
switch (d.getKind()) {
case NOTE:
case MANDATORY_WARNING:
case WARNING:
hasWarnings = true;
break;
case OTHER:
case ERROR:
default:
hasErrors = true;
break;
}
exceptionMsg.append("\n").append("[kind=").append(d.getKind());
exceptionMsg.append(", ").append("line=").append(d.getLineNumber());
exceptionMsg.append(", ").append("message=").append(d.getMessage(Locale.US)).append("]");
}
if (hasWarnings && !ignoreWarnings || hasErrors) {
throw new CompilationException(exceptionMsg.toString());
}
}
Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
for (String className : sourceCodes.keySet()) {
classes.put(className, classLoader.loadClass(className));
}
return classes;
} | java | {
"resource": ""
} |
q175965 | InMemoryJavaCompiler.compile | test | public Class<?> compile(String className, String sourceCode) throws Exception {
return addSource(className, sourceCode).compileAll().get(className);
} | java | {
"resource": ""
} |
q175966 | InMemoryJavaCompiler.addSource | test | public InMemoryJavaCompiler addSource(String className, String sourceCode) throws Exception {
sourceCodes.put(className, new SourceCode(className, sourceCode));
return this;
} | java | {
"resource": ""
} |
q175967 | GifHeaderParser.readGraphicControlExt | test | private void readGraphicControlExt() {
// Block size.
read();
// Packed fields.
int packed = read();
// Disposal method.
header.currentFrame.dispose = (packed & 0x1c) >> 2;
if (header.currentFrame.dispose == 0) {
// Elect to keep old image if discretionary.
header.currentFrame.dispose = 1;
}
header.currentFrame.transparency = (packed & 1) != 0;
// Delay in milliseconds.
int delayInHundredthsOfASecond = readShort();
// TODO: consider allowing -1 to indicate show forever.
if (delayInHundredthsOfASecond < MIN_FRAME_DELAY) {
delayInHundredthsOfASecond = DEFAULT_FRAME_DELAY;
}
header.currentFrame.delay = delayInHundredthsOfASecond * 10;
// Transparent color index
header.currentFrame.transIndex = read();
// Block terminator
read();
} | java | {
"resource": ""
} |
q175968 | GifDecoder.getNextFrame | test | synchronized Bitmap getNextFrame() {
if (header.frameCount <= 0 || framePointer < 0) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "unable to decode frame, frameCount=" + header.frameCount + " framePointer="
+ framePointer);
}
status = STATUS_FORMAT_ERROR;
}
if (status == STATUS_FORMAT_ERROR || status == STATUS_OPEN_ERROR) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Unable to decode frame, status=" + status);
}
return null;
}
status = STATUS_OK;
GifFrame currentFrame = header.frames.get(framePointer);
GifFrame previousFrame = null;
int previousIndex = framePointer - 1;
if (previousIndex >= 0) {
previousFrame = header.frames.get(previousIndex);
}
// Set the appropriate color table.
act = currentFrame.lct != null ? currentFrame.lct : header.gct;
if (act == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "No Valid Color Table for frame #" + framePointer);
}
// No color table defined.
status = STATUS_FORMAT_ERROR;
return null;
}
// Reset the transparent pixel in the color table
if (currentFrame.transparency) {
// Prepare local copy of color table ("pct = act"), see #1068
System.arraycopy(act, 0, pct, 0, act.length);
// Forget about act reference from shared header object, use copied version
act = pct;
// Set transparent color if specified.
act[currentFrame.transIndex] = 0;
}
// Transfer pixel data to image.
return setPixels(currentFrame, previousFrame);
} | java | {
"resource": ""
} |
q175969 | PersonLoginViewModel.selectablePersonsProperty | test | public SelectableStringList selectablePersonsProperty() {
if (selectablePersons == null) {
selectablePersons = new SelectableItemList<>(
FXCollections.observableArrayList(repository.getPersons()),
person -> person.getFirstName() + " " + person.getLastName());
}
return selectablePersons;
} | java | {
"resource": ""
} |
q175970 | ListTransformation.initListEvents | test | private void initListEvents() {
this.listChangeListener = new ListChangeListener<SourceType>() {
@Override
public void onChanged(
Change<? extends SourceType> listEvent) {
// We have to stage delete events, because if we process them
// separately, there will be unwanted ChangeEvents on the
// targetList
List<TargetType> deleteStaging = new ArrayList<>();
while (listEvent.next()) {
if (listEvent.wasUpdated()) {
processUpdateEvent(listEvent);
} else if (listEvent.wasReplaced()) {
processReplaceEvent(listEvent, deleteStaging);
} else if (listEvent.wasAdded()) {
processAddEvent(listEvent);
} else if (listEvent.wasRemoved()) {
processRemoveEvent(listEvent, deleteStaging);
}
}
// Process the staged elements
processStagingLists(deleteStaging);
}
};
modelListProperty().addListener(
new WeakListChangeListener<>(listChangeListener));
} | java | {
"resource": ""
} |
q175971 | Repository.getPersonById | test | public Person getPersonById(final int id) {
for (Person person : persons) {
if (id == person.getId()) {
return person;
}
}
return null;
} | java | {
"resource": ""
} |
q175972 | CompositeValidationStatus.addMessage | test | void addMessage(Validator validator, List<? extends ValidationMessage> messages) {
if(messages.isEmpty()) {
return;
}
final int validatorHash = System.identityHashCode(validator);
if(!validatorToMessagesMap.containsKey(validatorHash)){
validatorToMessagesMap.put(validatorHash, new ArrayList<>());
}
final List<Integer> messageHashesOfThisValidator = validatorToMessagesMap.get(validatorHash);
// add the hashCodes of the messages to the internal map
messages.stream()
.map(System::identityHashCode)
.forEach(messageHashesOfThisValidator::add);
// add the actual messages to the message list so that they are accessible by the user.
getMessagesInternal().addAll(messages);
} | java | {
"resource": ""
} |
q175973 | PersonWelcomeViewModel.setPersonId | test | public void setPersonId(int personId) {
person = repository.getPersonById(personId);
StringBinding salutationBinding
= Bindings.when(person.genderProperty().isEqualTo(Gender.NOT_SPECIFIED))
.then("Herr/Frau/* ")
.otherwise(
Bindings.when(person.genderProperty().isEqualTo(Gender.MALE))
.then("Herr ").otherwise("Frau "));
welcomeString.unbind();
welcomeString.bind(Bindings.concat("Willkommen ", salutationBinding,
person.firstNameProperty(), " ",
person.lastNameProperty()));
} | java | {
"resource": ""
} |
q175974 | ViewLoaderReflectionUtils.createAndInjectViewModel | test | @SuppressWarnings("unchecked")
public static <V extends View<? extends VM>, VM extends ViewModel> void createAndInjectViewModel(final V view,
Consumer<ViewModel> newVmConsumer) {
final Class<?> viewModelType = TypeResolver.resolveRawArgument(View.class, view.getClass());
if (viewModelType == ViewModel.class) {
// if no viewModel can be created, we have to check if the user has
// tried to inject a ViewModel
final List<Field> viewModelFields = ViewLoaderReflectionUtils.getViewModelFields(view.getClass());
if (!viewModelFields.isEmpty()) {
throw new RuntimeException("The given view of type <" + view.getClass()
+ "> has no generic viewModel type declared but tries to inject a viewModel.");
}
return;
}
if (viewModelType == TypeResolver.Unknown.class) {
return;
}
final Optional<Field> fieldOptional = getViewModelField(view.getClass(), viewModelType);
if (fieldOptional.isPresent()) {
Field field = fieldOptional.get();
ReflectionUtils.accessMember(field, () -> {
Object existingViewModel = field.get(view);
if (existingViewModel == null) {
final Object newViewModel = DependencyInjector.getInstance().getInstanceOf(viewModelType);
field.set(view, newViewModel);
newVmConsumer.accept((ViewModel) newViewModel);
}
}, "Can't inject ViewModel of type <" + viewModelType + "> into the view <" + view + ">");
}
} | java | {
"resource": ""
} |
q175975 | ViewLoaderReflectionUtils.createViewModel | test | @SuppressWarnings("unchecked")
public static <ViewType extends View<? extends ViewModelType>, ViewModelType extends ViewModel> ViewModelType createViewModel(
ViewType view) {
final Class<?> viewModelType = TypeResolver.resolveRawArgument(View.class, view.getClass());
if (viewModelType == ViewModel.class) {
return null;
}
if (TypeResolver.Unknown.class == viewModelType) {
return null;
}
return (ViewModelType) DependencyInjector.getInstance().getInstanceOf(viewModelType);
} | java | {
"resource": ""
} |
q175976 | DataFxCountrySelector.loadCountries | test | void loadCountries() {
InputStream iso3166Resource = this.getClass().getResourceAsStream(ISO_3166_LOCATION);
if (iso3166Resource == null) {
throw new IllegalStateException("Can't find the list of countries! Expected location was:"
+ ISO_3166_LOCATION);
}
XmlConverter<Country> countryConverter = new XmlConverter<>("iso_3166_entry", Country.class);
try {
DataReader<Country> dataSource = new InputStreamSource<>( iso3166Resource, countryConverter );
ListDataProvider<Country> listDataProvider = new ListDataProvider<>(dataSource);
listDataProvider.setResultObservableList(countries);
Worker<ObservableList<Country>> worker = listDataProvider.retrieve();
// when the countries are loaded we start the loading of the subdivisions.
worker.stateProperty().addListener(obs -> {
if (worker.getState() == Worker.State.SUCCEEDED) {
loadSubdivisions();
}
});
} catch (IOException e) {
LOG.error("A problem was detected while loading the XML file with the available countries.", e);
}
} | java | {
"resource": ""
} |
q175977 | DataFxCountrySelector.loadSubdivisions | test | void loadSubdivisions() {
InputStream iso3166_2Resource = this.getClass().getResourceAsStream(ISO_3166_2_LOCATION);
if (iso3166_2Resource == null) {
throw new IllegalStateException("Can't find the list of subdivisions! Expected location was:"
+ ISO_3166_2_LOCATION);
}
XmlConverter<ISO3166_2_CountryEntity> converter = new XmlConverter<>("iso_3166_country",
ISO3166_2_CountryEntity.class);
ObservableList<ISO3166_2_CountryEntity> subdivisionsEntities = FXCollections.observableArrayList();
try {
DataReader<ISO3166_2_CountryEntity> dataSource =
new InputStreamSource<>( iso3166_2Resource, converter );
ListDataProvider<ISO3166_2_CountryEntity> listDataProvider = new ListDataProvider<>(dataSource);
listDataProvider.setResultObservableList(subdivisionsEntities);
Worker<ObservableList<ISO3166_2_CountryEntity>> worker = listDataProvider.retrieve();
worker.stateProperty().addListener(obs -> {
if (worker.getState() == Worker.State.SUCCEEDED) {
subdivisionsEntities.forEach(entity -> {
if (entity.subsets != null && !entity.subsets.isEmpty()) {
Country country = findCountryByCode(entity.code);
if (!countryCodeSubdivisionMap.containsKey(country)) {
countryCodeSubdivisionMap.put(country, new ArrayList<>());
}
List<Subdivision> subdivisionList = countryCodeSubdivisionMap.get(country);
entity.subsets.forEach(subset -> {
subset.entryList.forEach(entry -> {
subdivisionList.add(new Subdivision(entry.name, entry.code, country));
});
});
String subdivisionName = entity.subsets.stream()
.map(subset -> subset.subdivisionType)
.collect(Collectors.joining("/"));
countryCodeSubdivisionNameMap.put(country, subdivisionName);
}
});
inProgress.set(false);
}
});
} catch (IOException e) {
LOG.error("A problem was detected while loading the XML file with the available subdivisions.", e);
}
} | java | {
"resource": ""
} |
q175978 | ModelWrapper.field | test | public StringProperty field(StringGetter<M> getter, StringSetter<M> setter) {
return add(new BeanPropertyField<>(this::propertyWasChanged, getter, setter, SimpleStringProperty::new));
} | java | {
"resource": ""
} |
q175979 | ModelWrapper.immutableField | test | public StringProperty immutableField(StringGetter<M> getter, StringImmutableSetter<M> immutableSetter){
return addImmutable(new ImmutableBeanPropertyField<>(this::propertyWasChanged, getter, immutableSetter, SimpleStringProperty::new));
} | java | {
"resource": ""
} |
q175980 | FluentViewLoader.javaView | test | public static <ViewType extends JavaView<? extends ViewModelType>, ViewModelType extends ViewModel> JavaViewStep<ViewType, ViewModelType> javaView(
Class<? extends ViewType> viewType) {
return new JavaViewStep<>(viewType);
} | java | {
"resource": ""
} |
q175981 | FluentViewLoader.fxmlView | test | public static <ViewType extends FxmlView<? extends ViewModelType>, ViewModelType extends ViewModel> FxmlViewStep<ViewType, ViewModelType> fxmlView(
Class<? extends ViewType> viewType) {
return new FxmlViewStep<>(viewType);
} | java | {
"resource": ""
} |
q175982 | ListenerManager.clearMap | test | private <T, U> void clearMap(Map<T, Set<U>> map, BiConsumer<T, U> consumer) {
for (T observable : map.keySet()) {
for (U listener : map.get(observable)) {
consumer.accept(observable, listener);
}
}
map.clear();
} | java | {
"resource": ""
} |
q175983 | SelectableItemList.createIndexEvents | test | private void createIndexEvents() {
selectionModel
.selectedIndexProperty()
.addListener((bean, oldVal, newVal) -> {
int index = newVal.intValue();
ListType item = index == -1 ? null : modelListProperty()
.get(index);
selectedItem.set(item);
});
selectedItem.addListener((observable, oldVal, newVal) -> {
// Item null
if (newVal == null) {
selectionModel.select(-1);
selectedItem.set(null);
} else {
int index = modelListProperty().get().indexOf(newVal);
// Item not found
if (index != -1) {
selectionModel.select(index);
} else {
// If item not found - Rollback
selectedItem.set(oldVal);
}
}
});
} | java | {
"resource": ""
} |
q175984 | ReflectionUtils.accessMember | test | public static <T> T accessMember(final AccessibleObject member, final Callable<T> callable, String errorMessage) {
if (callable == null) {
return null;
}
return AccessController.doPrivileged((PrivilegedAction<T>) () -> {
boolean wasAccessible = member.isAccessible();
try {
member.setAccessible(true);
return callable.call();
} catch (Exception exception) {
throw new IllegalStateException(errorMessage, exception);
} finally {
member.setAccessible(wasAccessible);
}
});
} | java | {
"resource": ""
} |
q175985 | FxmlViewLoader.loadFxmlViewTuple | test | public <ViewType extends View<? extends ViewModelType>, ViewModelType extends ViewModel> ViewTuple<ViewType, ViewModelType> loadFxmlViewTuple(
Class<? extends ViewType> viewType, ResourceBundle resourceBundle, ViewType codeBehind, Object root,
ViewModelType viewModel, Context context, Collection<Scope> providedScopes,
List<BuilderFactory> builderFactories) {
final String pathToFXML = createFxmlPath(viewType);
return loadFxmlViewTuple(viewType, pathToFXML, resourceBundle, codeBehind, root, viewModel, context, providedScopes, builderFactories);
} | java | {
"resource": ""
} |
q175986 | FxmlViewLoader.createFxmlPath | test | private String createFxmlPath(Class<?> viewType) {
final StringBuilder pathBuilder = new StringBuilder();
final FxmlPath pathAnnotation = viewType.getDeclaredAnnotation(FxmlPath.class); //Get annotation from view
final String fxmlPath = Optional.ofNullable(pathAnnotation)
.map(FxmlPath::value)
.map(String::trim)
.orElse("");
if (fxmlPath.isEmpty()) {
pathBuilder.append("/");
if (viewType.getPackage() != null) {
pathBuilder.append(viewType.getPackage().getName().replaceAll("\\.", "/"));
pathBuilder.append("/");
}
pathBuilder.append(viewType.getSimpleName());
pathBuilder.append(".fxml");
} else {
pathBuilder.append(fxmlPath);
}
return pathBuilder.toString();
} | java | {
"resource": ""
} |
q175987 | StyleDao.queryForRow | test | public StyleRow queryForRow(StyleMappingRow styleMappingRow) {
StyleRow styleRow = null;
AttributesRow attributesRow = queryForIdRow(styleMappingRow
.getRelatedId());
if (attributesRow != null) {
styleRow = getRow(attributesRow);
}
return styleRow;
} | java | {
"resource": ""
} |
q175988 | CoverageDataPng.getPixelValue | test | public int getPixelValue(byte[] imageBytes, int x, int y) {
PngReaderInt reader = new PngReaderInt(new ByteArrayInputStream(imageBytes));
validateImageType(reader);
ImageLineInt row = (ImageLineInt) reader.readRow(y);
int pixelValue = row.getScanline()[x];
reader.close();
return pixelValue;
} | java | {
"resource": ""
} |
q175989 | CoverageDataPng.getPixelValues | test | public int[] getPixelValues(byte[] imageBytes) {
PngReaderInt reader = new PngReaderInt(new ByteArrayInputStream(imageBytes));
validateImageType(reader);
int[] pixels = new int[reader.imgInfo.cols * reader.imgInfo.rows];
int rowNumber = 0;
while (reader.hasMoreRows()) {
ImageLineInt row = reader.readRowInt();
int[] rowValues = row.getScanline();
System.arraycopy(rowValues, 0, pixels, rowNumber * reader.imgInfo.cols, rowValues.length);
rowNumber++;
}
reader.close();
return pixels;
} | java | {
"resource": ""
} |
q175990 | CoverageDataPng.validateImageType | test | public static void validateImageType(PngReader reader) {
if (reader == null) {
throw new GeoPackageException("The image is null");
}
if (reader.imgInfo.channels != 1 || reader.imgInfo.bitDepth != 16) {
throw new GeoPackageException(
"The coverage data tile is expected to be a single channel 16 bit unsigned short, channels: "
+ reader.imgInfo.channels + ", bits: " + reader.imgInfo.bitDepth);
}
} | java | {
"resource": ""
} |
q175991 | CoverageDataPng.createImage | test | public CoverageDataPngImage createImage(int tileWidth, int tileHeight) {
ImageInfo imageInfo = new ImageInfo(tileWidth, tileHeight, 16, false, true, false);
CoverageDataPngImage image = new CoverageDataPngImage(imageInfo);
return image;
} | java | {
"resource": ""
} |
q175992 | TileRow.setTileData | test | public void setTileData(Bitmap bitmap, CompressFormat format, int quality)
throws IOException {
byte[] tileData = BitmapConverter.toBytes(bitmap, format, quality);
setTileData(tileData);
} | java | {
"resource": ""
} |
q175993 | GeoPackageConnection.rawQuery | test | public Cursor rawQuery(String sql, String[] args) {
return db.rawQuery(sql, args);
} | java | {
"resource": ""
} |
q175994 | GeoPackageConnection.wrapQuery | test | public CursorResult wrapQuery(String sql,
String[] selectionArgs) {
return new CursorResult(rawQuery(sql, selectionArgs));
} | java | {
"resource": ""
} |
q175995 | UserConnection.query | test | public TResult query(TResult previousResult) {
UserQuery query = previousResult.getQuery();
TResult result = query(query);
return result;
} | java | {
"resource": ""
} |
q175996 | UserConnection.query | test | public TResult query(UserQuery query) {
Cursor cursor = null;
String[] selectionArgs = query.getSelectionArgs();
String sql = query.getSql();
if (sql != null) {
cursor = database.rawQuery(sql, selectionArgs);
} else {
String table = query.getTable();
String[] columns = query.getColumns();
String selection = query.getSelection();
String groupBy = query.getGroupBy();
String having = query.getHaving();
String orderBy = query.getOrderBy();
String[] columnsAs = query.getColumnsAs();
String limit = query.getLimit();
if (columnsAs != null && limit != null) {
cursor = database.query(table, columns, columnsAs, selection, selectionArgs, groupBy, having, orderBy, limit);
} else if (columnsAs != null) {
cursor = database.query(table, columns, columnsAs, selection, selectionArgs, groupBy, having, orderBy);
} else if (limit != null) {
cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
} else {
cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
}
}
TResult result = handleCursor(cursor, query);
return result;
} | java | {
"resource": ""
} |
q175997 | UserConnection.handleCursor | test | private TResult handleCursor(Cursor cursor, UserQuery query) {
TResult result = convertCursor(cursor);
result.setQuery(query);
if (table != null) {
result.setTable(table);
}
return result;
} | java | {
"resource": ""
} |
q175998 | FeatureTableIndex.getFeatureRow | test | public FeatureRow getFeatureRow(GeometryIndex geometryIndex) {
long geomId = geometryIndex.getGeomId();
// Get the row or lock for reading
FeatureRow row = featureRowSync.getRowOrLock(geomId);
if (row == null) {
// Query for the row and set in the sync
try {
row = featureDao.queryForIdRow(geomId);
} finally {
featureRowSync.setRow(geomId, row);
}
}
return row;
} | java | {
"resource": ""
} |
q175999 | GeoPackageCursorFactory.registerTable | test | public void registerTable(String tableName,
GeoPackageCursorWrapper cursorWrapper) {
// Remove an existing cursor wrapper
tableCursors.remove(tableName);
// Add the wrapper
tableCursors.put(tableName, cursorWrapper);
String quotedTableName = CoreSQLUtils.quoteWrap(tableName);
tableCursors.put(quotedTableName, cursorWrapper);
// The Android android.database.sqlite.SQLiteDatabase findEditTable method
// finds the new cursor edit table name based upon the first space or comma.
// Fix (hopefully temporary) to wrap with the expected cursor type
int spacePosition = tableName.indexOf(' ');
if (spacePosition > 0) {
tableCursors.put(tableName.substring(0, spacePosition), cursorWrapper);
tableCursors.put(quotedTableName.substring(0, quotedTableName.indexOf(' ')), cursorWrapper);
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.