repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
eyp/serfj | src/main/java/net/sf/serfj/serializers/JsonSerializer.java | JsonSerializer.serialize | public String serialize(Object object) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Serializing object to Json");
}
XStream xstream = new XStream(new JettisonMappedXmlDriver());
String json = xstream.toXML(object);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Object serialized well");
}
return json;
} | java | public String serialize(Object object) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Serializing object to Json");
}
XStream xstream = new XStream(new JettisonMappedXmlDriver());
String json = xstream.toXML(object);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Object serialized well");
}
return json;
} | [
"public",
"String",
"serialize",
"(",
"Object",
"object",
")",
"{",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Serializing object to Json\"",
")",
";",
"}",
"XStream",
"xstream",
"=",
"new",
"XStream",
"... | Serializes an object to Json. | [
"Serializes",
"an",
"object",
"to",
"Json",
"."
] | e617592af6f24e59ea58443f2785c44aa2312189 | https://github.com/eyp/serfj/blob/e617592af6f24e59ea58443f2785c44aa2312189/src/main/java/net/sf/serfj/serializers/JsonSerializer.java#L36-L46 | train |
eyp/serfj | src/main/java/net/sf/serfj/serializers/JsonSerializer.java | JsonSerializer.deserialize | public Object deserialize(String jsonObject) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deserializing Json object");
}
XStream xstream = new XStream(new JettisonMappedXmlDriver());
Object obj = xstream.fromXML(jsonObject);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Object deserialized");
}
return obj;
} | java | public Object deserialize(String jsonObject) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deserializing Json object");
}
XStream xstream = new XStream(new JettisonMappedXmlDriver());
Object obj = xstream.fromXML(jsonObject);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Object deserialized");
}
return obj;
} | [
"public",
"Object",
"deserialize",
"(",
"String",
"jsonObject",
")",
"{",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Deserializing Json object\"",
")",
";",
"}",
"XStream",
"xstream",
"=",
"new",
"XStream"... | Deserializes a Json string representation to an object. | [
"Deserializes",
"a",
"Json",
"string",
"representation",
"to",
"an",
"object",
"."
] | e617592af6f24e59ea58443f2785c44aa2312189 | https://github.com/eyp/serfj/blob/e617592af6f24e59ea58443f2785c44aa2312189/src/main/java/net/sf/serfj/serializers/JsonSerializer.java#L51-L61 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/util/Splitter.java | Splitter.filterOutEmptyStrings | private Iterator<String> filterOutEmptyStrings(final Iterator<String> splitted) {
return new Iterator<String>() {
String next = getNext();
@Override
public boolean hasNext() {
return next != null;
}
@Override
public String next() {
if ( !hasNext() ) throw new NoSuchElementException();
String result = next;
next = getNext();
return result;
}
public String getNext() {
while (splitted.hasNext()) {
String value = splitted.next();
if ( value != null && !value.isEmpty() ) {
return value;
}
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} | java | private Iterator<String> filterOutEmptyStrings(final Iterator<String> splitted) {
return new Iterator<String>() {
String next = getNext();
@Override
public boolean hasNext() {
return next != null;
}
@Override
public String next() {
if ( !hasNext() ) throw new NoSuchElementException();
String result = next;
next = getNext();
return result;
}
public String getNext() {
while (splitted.hasNext()) {
String value = splitted.next();
if ( value != null && !value.isEmpty() ) {
return value;
}
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} | [
"private",
"Iterator",
"<",
"String",
">",
"filterOutEmptyStrings",
"(",
"final",
"Iterator",
"<",
"String",
">",
"splitted",
")",
"{",
"return",
"new",
"Iterator",
"<",
"String",
">",
"(",
")",
"{",
"String",
"next",
"=",
"getNext",
"(",
")",
";",
"@",
... | Its easier to understand if the logic for omit empty sequences is a filtering iterator
@param splitted - the results of a splittingIterator
@return iterator with no empty values | [
"Its",
"easier",
"to",
"understand",
"if",
"the",
"logic",
"for",
"omit",
"empty",
"sequences",
"is",
"a",
"filtering",
"iterator"
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/util/Splitter.java#L68-L99 | train |
geomajas/geomajas-project-geometry | jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java | GeometryConverterService.toJts | public static Envelope toJts(Bbox bbox) throws JtsConversionException {
if (bbox == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Envelope(bbox.getX(), bbox.getMaxX(), bbox.getY(), bbox.getMaxY());
} | java | public static Envelope toJts(Bbox bbox) throws JtsConversionException {
if (bbox == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Envelope(bbox.getX(), bbox.getMaxX(), bbox.getY(), bbox.getMaxY());
} | [
"public",
"static",
"Envelope",
"toJts",
"(",
"Bbox",
"bbox",
")",
"throws",
"JtsConversionException",
"{",
"if",
"(",
"bbox",
"==",
"null",
")",
"{",
"throw",
"new",
"JtsConversionException",
"(",
"\"Cannot convert null argument\"",
")",
";",
"}",
"return",
"ne... | Convert a Geomajas bounding box to a JTS envelope.
@param bbox Geomajas bbox
@return JTS Envelope
@throws JtsConversionException conversion failed | [
"Convert",
"a",
"Geomajas",
"bounding",
"box",
"to",
"a",
"JTS",
"envelope",
"."
] | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java#L116-L121 | train |
geomajas/geomajas-project-geometry | jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java | GeometryConverterService.toJts | public static com.vividsolutions.jts.geom.Coordinate toJts(org.geomajas.geometry.Coordinate coordinate)
throws JtsConversionException {
if (coordinate == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new com.vividsolutions.jts.geom.Coordinate(coordinate.getX(), coordinate.getY());
} | java | public static com.vividsolutions.jts.geom.Coordinate toJts(org.geomajas.geometry.Coordinate coordinate)
throws JtsConversionException {
if (coordinate == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new com.vividsolutions.jts.geom.Coordinate(coordinate.getX(), coordinate.getY());
} | [
"public",
"static",
"com",
".",
"vividsolutions",
".",
"jts",
".",
"geom",
".",
"Coordinate",
"toJts",
"(",
"org",
".",
"geomajas",
".",
"geometry",
".",
"Coordinate",
"coordinate",
")",
"throws",
"JtsConversionException",
"{",
"if",
"(",
"coordinate",
"==",
... | Convert a Geomajas coordinate to a JTS coordinate.
@param coordinate Geomajas coordinate
@return JTS coordinate
@throws JtsConversionException | [
"Convert",
"a",
"Geomajas",
"coordinate",
"to",
"a",
"JTS",
"coordinate",
"."
] | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java#L130-L136 | train |
geomajas/geomajas-project-geometry | jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java | GeometryConverterService.fromJts | public static Geometry fromJts(com.vividsolutions.jts.geom.Geometry geometry) throws JtsConversionException {
if (geometry == null) {
throw new JtsConversionException("Cannot convert null argument");
}
int srid = geometry.getSRID();
int precision = -1;
PrecisionModel precisionmodel = geometry.getPrecisionModel();
if (!precisionmodel.isFloating()) {
precision = (int) Math.log10(precisionmodel.getScale());
}
String geometryType = getGeometryType(geometry);
Geometry dto = new Geometry(geometryType, srid, precision);
if (geometry.isEmpty()) {
// nothing to do
} else if (geometry instanceof Point) {
dto.setCoordinates(convertCoordinates(geometry));
} else if (geometry instanceof LinearRing) {
dto.setCoordinates(convertCoordinates(geometry));
} else if (geometry instanceof LineString) {
dto.setCoordinates(convertCoordinates(geometry));
} else if (geometry instanceof Polygon) {
Polygon polygon = (Polygon) geometry;
Geometry[] geometries = new Geometry[polygon.getNumInteriorRing() + 1];
for (int i = 0; i < geometries.length; i++) {
if (i == 0) {
geometries[i] = fromJts(polygon.getExteriorRing());
} else {
geometries[i] = fromJts(polygon.getInteriorRingN(i - 1));
}
}
dto.setGeometries(geometries);
} else if (geometry instanceof MultiPoint) {
dto.setGeometries(convertGeometries(geometry));
} else if (geometry instanceof MultiLineString) {
dto.setGeometries(convertGeometries(geometry));
} else if (geometry instanceof MultiPolygon) {
dto.setGeometries(convertGeometries(geometry));
} else {
throw new JtsConversionException("Cannot convert geometry: Unsupported type.");
}
return dto;
} | java | public static Geometry fromJts(com.vividsolutions.jts.geom.Geometry geometry) throws JtsConversionException {
if (geometry == null) {
throw new JtsConversionException("Cannot convert null argument");
}
int srid = geometry.getSRID();
int precision = -1;
PrecisionModel precisionmodel = geometry.getPrecisionModel();
if (!precisionmodel.isFloating()) {
precision = (int) Math.log10(precisionmodel.getScale());
}
String geometryType = getGeometryType(geometry);
Geometry dto = new Geometry(geometryType, srid, precision);
if (geometry.isEmpty()) {
// nothing to do
} else if (geometry instanceof Point) {
dto.setCoordinates(convertCoordinates(geometry));
} else if (geometry instanceof LinearRing) {
dto.setCoordinates(convertCoordinates(geometry));
} else if (geometry instanceof LineString) {
dto.setCoordinates(convertCoordinates(geometry));
} else if (geometry instanceof Polygon) {
Polygon polygon = (Polygon) geometry;
Geometry[] geometries = new Geometry[polygon.getNumInteriorRing() + 1];
for (int i = 0; i < geometries.length; i++) {
if (i == 0) {
geometries[i] = fromJts(polygon.getExteriorRing());
} else {
geometries[i] = fromJts(polygon.getInteriorRingN(i - 1));
}
}
dto.setGeometries(geometries);
} else if (geometry instanceof MultiPoint) {
dto.setGeometries(convertGeometries(geometry));
} else if (geometry instanceof MultiLineString) {
dto.setGeometries(convertGeometries(geometry));
} else if (geometry instanceof MultiPolygon) {
dto.setGeometries(convertGeometries(geometry));
} else {
throw new JtsConversionException("Cannot convert geometry: Unsupported type.");
}
return dto;
} | [
"public",
"static",
"Geometry",
"fromJts",
"(",
"com",
".",
"vividsolutions",
".",
"jts",
".",
"geom",
".",
"Geometry",
"geometry",
")",
"throws",
"JtsConversionException",
"{",
"if",
"(",
"geometry",
"==",
"null",
")",
"{",
"throw",
"new",
"JtsConversionExcep... | Convert a JTS geometry to a Geomajas geometry.
@param geometry JTS geometry
@return Geomajas geometry
@throws JtsConversionException conversion failed | [
"Convert",
"a",
"JTS",
"geometry",
"to",
"a",
"Geomajas",
"geometry",
"."
] | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java#L144-L185 | train |
geomajas/geomajas-project-geometry | jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java | GeometryConverterService.fromJts | public static Bbox fromJts(Envelope envelope) throws JtsConversionException {
if (envelope == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Bbox(envelope.getMinX(), envelope.getMinY(), envelope.getWidth(), envelope.getHeight());
} | java | public static Bbox fromJts(Envelope envelope) throws JtsConversionException {
if (envelope == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Bbox(envelope.getMinX(), envelope.getMinY(), envelope.getWidth(), envelope.getHeight());
} | [
"public",
"static",
"Bbox",
"fromJts",
"(",
"Envelope",
"envelope",
")",
"throws",
"JtsConversionException",
"{",
"if",
"(",
"envelope",
"==",
"null",
")",
"{",
"throw",
"new",
"JtsConversionException",
"(",
"\"Cannot convert null argument\"",
")",
";",
"}",
"retu... | Convert a JTS envelope to a Geomajas bounding box.
@param envelope JTS envelope
@return Geomajas bbox
@throws JtsConversionException conversion failed | [
"Convert",
"a",
"JTS",
"envelope",
"to",
"a",
"Geomajas",
"bounding",
"box",
"."
] | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java#L194-L199 | train |
geomajas/geomajas-project-geometry | jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java | GeometryConverterService.fromJts | public static Coordinate fromJts(com.vividsolutions.jts.geom.Coordinate coordinate) throws JtsConversionException {
if (coordinate == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Coordinate(coordinate.x, coordinate.y);
} | java | public static Coordinate fromJts(com.vividsolutions.jts.geom.Coordinate coordinate) throws JtsConversionException {
if (coordinate == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Coordinate(coordinate.x, coordinate.y);
} | [
"public",
"static",
"Coordinate",
"fromJts",
"(",
"com",
".",
"vividsolutions",
".",
"jts",
".",
"geom",
".",
"Coordinate",
"coordinate",
")",
"throws",
"JtsConversionException",
"{",
"if",
"(",
"coordinate",
"==",
"null",
")",
"{",
"throw",
"new",
"JtsConvers... | Convert a GTS coordinate to a Geomajas coordinate.
@param coordinate jTS coordinate
@return Geomajas coordinate
@throws JtsConversionException conversion failed | [
"Convert",
"a",
"GTS",
"coordinate",
"to",
"a",
"Geomajas",
"coordinate",
"."
] | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java#L208-L213 | train |
Teddy-Zhu/SilentGo | framework/src/main/java/com/silentgo/servlet/oreilly/multipart/FilePart.java | FilePart.writeTo | public long writeTo(File fileOrDirectory) throws IOException {
long written = 0;
OutputStream fileOut = null;
try {
// Only do something if this part contains a file
if (fileName != null) {
// Check if user supplied directory
File file;
if (fileOrDirectory.isDirectory()) {
// Write it to that dir the user supplied,
// with the filename it arrived with
file = new File(fileOrDirectory, fileName);
}
else {
// Write it to the file the user supplied,
// ignoring the filename it arrived with
file = fileOrDirectory;
}
if (policy != null) {
file = policy.rename(file);
fileName = file.getName();
}
fileOut = new BufferedOutputStream(new FileOutputStream(file));
written = write(fileOut);
}
}
finally {
if (fileOut != null) fileOut.close();
}
return written;
} | java | public long writeTo(File fileOrDirectory) throws IOException {
long written = 0;
OutputStream fileOut = null;
try {
// Only do something if this part contains a file
if (fileName != null) {
// Check if user supplied directory
File file;
if (fileOrDirectory.isDirectory()) {
// Write it to that dir the user supplied,
// with the filename it arrived with
file = new File(fileOrDirectory, fileName);
}
else {
// Write it to the file the user supplied,
// ignoring the filename it arrived with
file = fileOrDirectory;
}
if (policy != null) {
file = policy.rename(file);
fileName = file.getName();
}
fileOut = new BufferedOutputStream(new FileOutputStream(file));
written = write(fileOut);
}
}
finally {
if (fileOut != null) fileOut.close();
}
return written;
} | [
"public",
"long",
"writeTo",
"(",
"File",
"fileOrDirectory",
")",
"throws",
"IOException",
"{",
"long",
"written",
"=",
"0",
";",
"OutputStream",
"fileOut",
"=",
"null",
";",
"try",
"{",
"// Only do something if this part contains a file",
"if",
"(",
"fileName",
"... | Write this file part to a file or directory. If the user
supplied a file, we write it to that file, and if they supplied
a directory, we write it to that directory with the filename
that accompanied it. If this part doesn't contain a file this
method does nothing.
@return number of bytes written
@exception IOException if an input or output exception has occurred. | [
"Write",
"this",
"file",
"part",
"to",
"a",
"file",
"or",
"directory",
".",
"If",
"the",
"user",
"supplied",
"a",
"file",
"we",
"write",
"it",
"to",
"that",
"file",
"and",
"if",
"they",
"supplied",
"a",
"directory",
"we",
"write",
"it",
"to",
"that",
... | 27f58b0cafe56b2eb9fc6993efa9ca2b529661e1 | https://github.com/Teddy-Zhu/SilentGo/blob/27f58b0cafe56b2eb9fc6993efa9ca2b529661e1/framework/src/main/java/com/silentgo/servlet/oreilly/multipart/FilePart.java#L143-L174 | train |
Teddy-Zhu/SilentGo | framework/src/main/java/com/silentgo/servlet/oreilly/multipart/FilePart.java | FilePart.writeTo | public long writeTo(OutputStream out) throws IOException {
long size=0;
// Only do something if this part contains a file
if (fileName != null) {
// Write it out
size = write( out );
}
return size;
} | java | public long writeTo(OutputStream out) throws IOException {
long size=0;
// Only do something if this part contains a file
if (fileName != null) {
// Write it out
size = write( out );
}
return size;
} | [
"public",
"long",
"writeTo",
"(",
"OutputStream",
"out",
")",
"throws",
"IOException",
"{",
"long",
"size",
"=",
"0",
";",
"// Only do something if this part contains a file",
"if",
"(",
"fileName",
"!=",
"null",
")",
"{",
"// Write it out",
"size",
"=",
"write",
... | Write this file part to the given output stream. If this part doesn't
contain a file this method does nothing.
@return number of bytes written.
@exception IOException if an input or output exception has occurred. | [
"Write",
"this",
"file",
"part",
"to",
"the",
"given",
"output",
"stream",
".",
"If",
"this",
"part",
"doesn",
"t",
"contain",
"a",
"file",
"this",
"method",
"does",
"nothing",
"."
] | 27f58b0cafe56b2eb9fc6993efa9ca2b529661e1 | https://github.com/Teddy-Zhu/SilentGo/blob/27f58b0cafe56b2eb9fc6993efa9ca2b529661e1/framework/src/main/java/com/silentgo/servlet/oreilly/multipart/FilePart.java#L183-L191 | train |
Teddy-Zhu/SilentGo | framework/src/main/java/com/silentgo/servlet/oreilly/multipart/FilePart.java | FilePart.write | long write(OutputStream out) throws IOException {
// decode macbinary if this was sent
if (contentType.equals("application/x-macbinary")) {
out = new MacBinaryDecoderOutputStream(out);
}
long size=0;
int read;
byte[] buf = new byte[8 * 1024];
while((read = partInput.read(buf)) != -1) {
out.write(buf, 0, read);
size += read;
}
return size;
} | java | long write(OutputStream out) throws IOException {
// decode macbinary if this was sent
if (contentType.equals("application/x-macbinary")) {
out = new MacBinaryDecoderOutputStream(out);
}
long size=0;
int read;
byte[] buf = new byte[8 * 1024];
while((read = partInput.read(buf)) != -1) {
out.write(buf, 0, read);
size += read;
}
return size;
} | [
"long",
"write",
"(",
"OutputStream",
"out",
")",
"throws",
"IOException",
"{",
"// decode macbinary if this was sent",
"if",
"(",
"contentType",
".",
"equals",
"(",
"\"application/x-macbinary\"",
")",
")",
"{",
"out",
"=",
"new",
"MacBinaryDecoderOutputStream",
"(",
... | Internal method to write this file part; doesn't check to see
if it has contents first.
@return number of bytes written.
@exception IOException if an input or output exception has occurred. | [
"Internal",
"method",
"to",
"write",
"this",
"file",
"part",
";",
"doesn",
"t",
"check",
"to",
"see",
"if",
"it",
"has",
"contents",
"first",
"."
] | 27f58b0cafe56b2eb9fc6993efa9ca2b529661e1 | https://github.com/Teddy-Zhu/SilentGo/blob/27f58b0cafe56b2eb9fc6993efa9ca2b529661e1/framework/src/main/java/com/silentgo/servlet/oreilly/multipart/FilePart.java#L200-L213 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/XmlReader.java | XmlReader.readAllFromResource | public static Xml readAllFromResource(String resourceName) {
InputStream is = XmlReader.class.getResourceAsStream(resourceName);
XmlReader reader = new XmlReader(is);
Xml xml = reader.read("node()");
reader.close();
return xml;
} | java | public static Xml readAllFromResource(String resourceName) {
InputStream is = XmlReader.class.getResourceAsStream(resourceName);
XmlReader reader = new XmlReader(is);
Xml xml = reader.read("node()");
reader.close();
return xml;
} | [
"public",
"static",
"Xml",
"readAllFromResource",
"(",
"String",
"resourceName",
")",
"{",
"InputStream",
"is",
"=",
"XmlReader",
".",
"class",
".",
"getResourceAsStream",
"(",
"resourceName",
")",
";",
"XmlReader",
"reader",
"=",
"new",
"XmlReader",
"(",
"is",
... | Read all XML content from a resource location
@param resourceName resource name
@return {@code Xml} object | [
"Read",
"all",
"XML",
"content",
"from",
"a",
"resource",
"location"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/XmlReader.java#L58-L64 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/XmlReader.java | XmlReader.init | private void init(InputStream inputStream) {
this.inputStream = inputStream;
currentPath = new LinkedList<Node>();
nodeQueue = new LinkedList<XmlNode>();
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty("javax.xml.stream.isCoalescing", true);
factory.setProperty("javax.xml.stream.isReplacingEntityReferences", true);
try {
reader = factory.createXMLStreamReader(inputStream);
} catch (XMLStreamException e) {
throw new XmlReaderException(e);
}
} | java | private void init(InputStream inputStream) {
this.inputStream = inputStream;
currentPath = new LinkedList<Node>();
nodeQueue = new LinkedList<XmlNode>();
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty("javax.xml.stream.isCoalescing", true);
factory.setProperty("javax.xml.stream.isReplacingEntityReferences", true);
try {
reader = factory.createXMLStreamReader(inputStream);
} catch (XMLStreamException e) {
throw new XmlReaderException(e);
}
} | [
"private",
"void",
"init",
"(",
"InputStream",
"inputStream",
")",
"{",
"this",
".",
"inputStream",
"=",
"inputStream",
";",
"currentPath",
"=",
"new",
"LinkedList",
"<",
"Node",
">",
"(",
")",
";",
"nodeQueue",
"=",
"new",
"LinkedList",
"<",
"XmlNode",
">... | Initialize XML reader for processing
@param inputStream input stream | [
"Initialize",
"XML",
"reader",
"for",
"processing"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/XmlReader.java#L78-L90 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/XmlReader.java | XmlReader.find | public boolean find(String xmlPathQuery) {
XmlPath xmlPath = XmlPathParser.parse(xmlPathQuery);
XmlNode node;
while((node = pullXmlNode()) != null) {
if(node instanceof XmlStartElement) {
XmlStartElement startElement = (XmlStartElement) node;
Element element = new Element(startElement.getLocalName());
element.addAttributes(startElement.getAttributes());
currentPath.addLast(element);
if(xmlPath.matches(currentPath)) {
nodeQueue.push(node);
currentPath.removeLast();
return true;
}
} else if(node instanceof XmlEndElement) {
if(currentPath.getLast() instanceof Content) {
currentPath.removeLast();
}
currentPath.removeLast();
} else if(node instanceof XmlContent) {
XmlContent content = (XmlContent) node;
if(currentPath.getLast() instanceof Content) {
currentPath.removeLast();
}
currentPath.addLast(new Content(content.getText()));
} else {
throw new XmlReaderException("Unknown XmlNode type: " + node);
}
}
return false;
} | java | public boolean find(String xmlPathQuery) {
XmlPath xmlPath = XmlPathParser.parse(xmlPathQuery);
XmlNode node;
while((node = pullXmlNode()) != null) {
if(node instanceof XmlStartElement) {
XmlStartElement startElement = (XmlStartElement) node;
Element element = new Element(startElement.getLocalName());
element.addAttributes(startElement.getAttributes());
currentPath.addLast(element);
if(xmlPath.matches(currentPath)) {
nodeQueue.push(node);
currentPath.removeLast();
return true;
}
} else if(node instanceof XmlEndElement) {
if(currentPath.getLast() instanceof Content) {
currentPath.removeLast();
}
currentPath.removeLast();
} else if(node instanceof XmlContent) {
XmlContent content = (XmlContent) node;
if(currentPath.getLast() instanceof Content) {
currentPath.removeLast();
}
currentPath.addLast(new Content(content.getText()));
} else {
throw new XmlReaderException("Unknown XmlNode type: " + node);
}
}
return false;
} | [
"public",
"boolean",
"find",
"(",
"String",
"xmlPathQuery",
")",
"{",
"XmlPath",
"xmlPath",
"=",
"XmlPathParser",
".",
"parse",
"(",
"xmlPathQuery",
")",
";",
"XmlNode",
"node",
";",
"while",
"(",
"(",
"node",
"=",
"pullXmlNode",
"(",
")",
")",
"!=",
"nu... | Find position in input stream that matches XML path query
@param xmlPathQuery XML path query
@return {@code boolean} true if found | [
"Find",
"position",
"in",
"input",
"stream",
"that",
"matches",
"XML",
"path",
"query"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/XmlReader.java#L97-L128 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/XmlReader.java | XmlReader.pullXmlNode | private XmlNode pullXmlNode() {
// read from queue
if(! nodeQueue.isEmpty()) {
return nodeQueue.poll();
}
// read from stream
try {
while(reader.hasNext()) {
int event = reader.next();
switch(event) {
case XMLStreamConstants.START_ELEMENT:
return new XmlStartElement(reader.getLocalName(), getAttributes(reader));
case XMLStreamConstants.CHARACTERS:
// capture XML?
String text = filterWhitespace(reader.getText());
if(text.length() > 0) {
return new XmlContent(text);
}
break;
case XMLStreamConstants.END_ELEMENT:
return new XmlEndElement(reader.getLocalName());
default:
// do nothing
}
}
} catch (XMLStreamException e) {
throw new XmlReaderException(e);
}
// nothing to return
return null;
} | java | private XmlNode pullXmlNode() {
// read from queue
if(! nodeQueue.isEmpty()) {
return nodeQueue.poll();
}
// read from stream
try {
while(reader.hasNext()) {
int event = reader.next();
switch(event) {
case XMLStreamConstants.START_ELEMENT:
return new XmlStartElement(reader.getLocalName(), getAttributes(reader));
case XMLStreamConstants.CHARACTERS:
// capture XML?
String text = filterWhitespace(reader.getText());
if(text.length() > 0) {
return new XmlContent(text);
}
break;
case XMLStreamConstants.END_ELEMENT:
return new XmlEndElement(reader.getLocalName());
default:
// do nothing
}
}
} catch (XMLStreamException e) {
throw new XmlReaderException(e);
}
// nothing to return
return null;
} | [
"private",
"XmlNode",
"pullXmlNode",
"(",
")",
"{",
"// read from queue",
"if",
"(",
"!",
"nodeQueue",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"nodeQueue",
".",
"poll",
"(",
")",
";",
"}",
"// read from stream",
"try",
"{",
"while",
"(",
"reader",
... | Pull an XML node object from the input stream
@return {@code XmlNode} | [
"Pull",
"an",
"XML",
"node",
"object",
"from",
"the",
"input",
"stream"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/XmlReader.java#L213-L244 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/XmlReader.java | XmlReader.filterWhitespace | private String filterWhitespace(String text) {
text = text.replace("\n", " ");
text = text.replaceAll(" {2,}", " ");
text = XmlEscape.escape(text);
return text.trim();
} | java | private String filterWhitespace(String text) {
text = text.replace("\n", " ");
text = text.replaceAll(" {2,}", " ");
text = XmlEscape.escape(text);
return text.trim();
} | [
"private",
"String",
"filterWhitespace",
"(",
"String",
"text",
")",
"{",
"text",
"=",
"text",
".",
"replace",
"(",
"\"\\n\"",
",",
"\" \"",
")",
";",
"text",
"=",
"text",
".",
"replaceAll",
"(",
"\" {2,}\"",
",",
"\" \"",
")",
";",
"text",
"=",
"XmlEs... | This method filters out white space characters
@param text original text
@return {@code String} filtered text | [
"This",
"method",
"filters",
"out",
"white",
"space",
"characters"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/XmlReader.java#L251-L256 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/XmlReader.java | XmlReader.getAttributes | private List<Attribute> getAttributes(XMLStreamReader reader) {
List<Attribute> list = new ArrayList<Attribute>();
for(int i=0; i<reader.getAttributeCount(); i++) {
list.add(new Attribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i)));
}
return list;
} | java | private List<Attribute> getAttributes(XMLStreamReader reader) {
List<Attribute> list = new ArrayList<Attribute>();
for(int i=0; i<reader.getAttributeCount(); i++) {
list.add(new Attribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i)));
}
return list;
} | [
"private",
"List",
"<",
"Attribute",
">",
"getAttributes",
"(",
"XMLStreamReader",
"reader",
")",
"{",
"List",
"<",
"Attribute",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"Attribute",
">",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"... | Extract XML element attributes form XML input stream
@param reader XML reader
@return {@code List} of {@code Attribute} items | [
"Extract",
"XML",
"element",
"attributes",
"form",
"XML",
"input",
"stream"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/XmlReader.java#L277-L283 | train |
Teddy-Zhu/SilentGo | utils/src/main/java/com/silentgo/utils/asm/ClassUtils.java | ClassUtils.isOverridable | private static boolean isOverridable(Method method, Class<?> targetClass) {
if (Modifier.isPrivate(method.getModifiers())) {
return false;
}
if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
return true;
}
return (targetClass == null ||
getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass)));
} | java | private static boolean isOverridable(Method method, Class<?> targetClass) {
if (Modifier.isPrivate(method.getModifiers())) {
return false;
}
if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
return true;
}
return (targetClass == null ||
getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass)));
} | [
"private",
"static",
"boolean",
"isOverridable",
"(",
"Method",
"method",
",",
"Class",
"<",
"?",
">",
"targetClass",
")",
"{",
"if",
"(",
"Modifier",
".",
"isPrivate",
"(",
"method",
".",
"getModifiers",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
... | Determine whether the given method is overridable in the given target class.
@param method the method to check
@param targetClass the target class to check against | [
"Determine",
"whether",
"the",
"given",
"method",
"is",
"overridable",
"in",
"the",
"given",
"target",
"class",
"."
] | 27f58b0cafe56b2eb9fc6993efa9ca2b529661e1 | https://github.com/Teddy-Zhu/SilentGo/blob/27f58b0cafe56b2eb9fc6993efa9ca2b529661e1/utils/src/main/java/com/silentgo/utils/asm/ClassUtils.java#L837-L846 | train |
99soft/lifegycle | src/main/java/org/nnsoft/guice/lifegycle/Disposer.java | Disposer.register | <I> void register( Method disposeMethod, I injectee )
{
disposables.add( new Disposable( disposeMethod, injectee ) );
} | java | <I> void register( Method disposeMethod, I injectee )
{
disposables.add( new Disposable( disposeMethod, injectee ) );
} | [
"<",
"I",
">",
"void",
"register",
"(",
"Method",
"disposeMethod",
",",
"I",
"injectee",
")",
"{",
"disposables",
".",
"add",
"(",
"new",
"Disposable",
"(",
"disposeMethod",
",",
"injectee",
")",
")",
";",
"}"
] | Register an injectee and its related method to release resources.
@param disposeMethod the method to be invoked to release resources
@param injectee the target injectee has to release the resources | [
"Register",
"an",
"injectee",
"and",
"its",
"related",
"method",
"to",
"release",
"resources",
"."
] | 0adde20bcf32e90fe995bb493630b77fa6ce6361 | https://github.com/99soft/lifegycle/blob/0adde20bcf32e90fe995bb493630b77fa6ce6361/src/main/java/org/nnsoft/guice/lifegycle/Disposer.java#L42-L45 | train |
Teddy-Zhu/SilentGo | framework/src/main/java/com/silentgo/core/route/support/paramdispatcher/PathParamDispatch.java | PathParamDispatch.dispatch | @Override
public void dispatch(ParameterResolveFactory parameterResolveFactory, ActionParam param, Route route, Object[] args) {
if (!route.isRegex()) return;
Matcher matcher = route.getMatcher();
String[] pathParameters = new String[matcher.groupCount()];
for (int i = 1, len = matcher.groupCount(); i <= len; i++) {
pathParameters[i - 1] = matcher.group(i);
}
Map<String, String> path = new HashMap<>();
route.getRegexRoute().getNames().forEach(name -> CollectionKit.MapAdd(path, name, matcher.group(name)));
param.getRequest().setPathNamedParameters(path);
param.getRequest().setPathParameters(pathParameters);
} | java | @Override
public void dispatch(ParameterResolveFactory parameterResolveFactory, ActionParam param, Route route, Object[] args) {
if (!route.isRegex()) return;
Matcher matcher = route.getMatcher();
String[] pathParameters = new String[matcher.groupCount()];
for (int i = 1, len = matcher.groupCount(); i <= len; i++) {
pathParameters[i - 1] = matcher.group(i);
}
Map<String, String> path = new HashMap<>();
route.getRegexRoute().getNames().forEach(name -> CollectionKit.MapAdd(path, name, matcher.group(name)));
param.getRequest().setPathNamedParameters(path);
param.getRequest().setPathParameters(pathParameters);
} | [
"@",
"Override",
"public",
"void",
"dispatch",
"(",
"ParameterResolveFactory",
"parameterResolveFactory",
",",
"ActionParam",
"param",
",",
"Route",
"route",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"if",
"(",
"!",
"route",
".",
"isRegex",
"(",
")",
")",
... | prepare to resolve path parameters
@param parameterResolveFactory
@param param
@param route
@param args | [
"prepare",
"to",
"resolve",
"path",
"parameters"
] | 27f58b0cafe56b2eb9fc6993efa9ca2b529661e1 | https://github.com/Teddy-Zhu/SilentGo/blob/27f58b0cafe56b2eb9fc6993efa9ca2b529661e1/framework/src/main/java/com/silentgo/core/route/support/paramdispatcher/PathParamDispatch.java#L37-L50 | train |
btaz/data-util | src/main/java/com/btaz/util/files/FileTracker.java | FileTracker.createDir | public File createDir(File dir) throws DataUtilException {
if(dir == null) {
throw new DataUtilException("Dir parameter can not be a null value");
}
if(dir.exists()) {
throw new DataUtilException("Directory already exists: " + dir.getAbsolutePath());
}
if(! dir.mkdir()) {
throw new DataUtilException("The result of File.mkDir() was false. Failed to create directory. : "
+ dir.getAbsolutePath());
}
trackedFiles.add(dir);
return dir;
} | java | public File createDir(File dir) throws DataUtilException {
if(dir == null) {
throw new DataUtilException("Dir parameter can not be a null value");
}
if(dir.exists()) {
throw new DataUtilException("Directory already exists: " + dir.getAbsolutePath());
}
if(! dir.mkdir()) {
throw new DataUtilException("The result of File.mkDir() was false. Failed to create directory. : "
+ dir.getAbsolutePath());
}
trackedFiles.add(dir);
return dir;
} | [
"public",
"File",
"createDir",
"(",
"File",
"dir",
")",
"throws",
"DataUtilException",
"{",
"if",
"(",
"dir",
"==",
"null",
")",
"{",
"throw",
"new",
"DataUtilException",
"(",
"\"Dir parameter can not be a null value\"",
")",
";",
"}",
"if",
"(",
"dir",
".",
... | Create and add a new directory
@param dir new directory
@return file new directory | [
"Create",
"and",
"add",
"a",
"new",
"directory"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/files/FileTracker.java#L107-L120 | train |
btaz/data-util | src/main/java/com/btaz/util/files/FileTracker.java | FileTracker.deleteAll | public void deleteAll() {
if(trackedFiles.size() == 0) {
return;
}
ArrayList<File> files = new ArrayList<File>(trackedFiles);
Collections.sort(files, filePathComparator);
for(File file : files) {
if(file.exists()) {
if(!file.delete()) {
throw new DataUtilException("Couldn't delete a tracked "
+ (file.isFile()? "file":"directory" + ": ") + file.getAbsolutePath());
}
}
}
trackedFiles.clear();
} | java | public void deleteAll() {
if(trackedFiles.size() == 0) {
return;
}
ArrayList<File> files = new ArrayList<File>(trackedFiles);
Collections.sort(files, filePathComparator);
for(File file : files) {
if(file.exists()) {
if(!file.delete()) {
throw new DataUtilException("Couldn't delete a tracked "
+ (file.isFile()? "file":"directory" + ": ") + file.getAbsolutePath());
}
}
}
trackedFiles.clear();
} | [
"public",
"void",
"deleteAll",
"(",
")",
"{",
"if",
"(",
"trackedFiles",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"ArrayList",
"<",
"File",
">",
"files",
"=",
"new",
"ArrayList",
"<",
"File",
">",
"(",
"trackedFiles",
")",
";... | Delete all tracked files | [
"Delete",
"all",
"tracked",
"files"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/files/FileTracker.java#L141-L159 | train |
fcrepo4-labs/fcrepo4-client | fcrepo-client-impl/src/main/java/org/fcrepo/client/impl/FedoraResourceImpl.java | FedoraResourceImpl.removeTombstone | public void removeTombstone(final String path) throws FedoraException {
final HttpDelete delete = httpHelper.createDeleteMethod(path + "/fcr:tombstone");
try {
final HttpResponse response = httpHelper.execute( delete );
final StatusLine status = response.getStatusLine();
final String uri = delete.getURI().toString();
if ( status.getStatusCode() == SC_NO_CONTENT) {
LOGGER.debug("triples updated successfully for resource {}", uri);
} else if ( status.getStatusCode() == SC_NOT_FOUND) {
LOGGER.error("resource {} does not exist, cannot update", uri);
throw new NotFoundException("resource " + uri + " does not exist, cannot update");
} else {
LOGGER.error("error updating resource {}: {} {}", uri, status.getStatusCode(),
status.getReasonPhrase());
throw new FedoraException("error updating resource " + uri + ": " + status.getStatusCode() + " " +
status.getReasonPhrase());
}
} catch (final FedoraException e) {
throw e;
} catch (final Exception e) {
LOGGER.error("Error executing request", e);
throw new FedoraException(e);
} finally {
delete.releaseConnection();
}
} | java | public void removeTombstone(final String path) throws FedoraException {
final HttpDelete delete = httpHelper.createDeleteMethod(path + "/fcr:tombstone");
try {
final HttpResponse response = httpHelper.execute( delete );
final StatusLine status = response.getStatusLine();
final String uri = delete.getURI().toString();
if ( status.getStatusCode() == SC_NO_CONTENT) {
LOGGER.debug("triples updated successfully for resource {}", uri);
} else if ( status.getStatusCode() == SC_NOT_FOUND) {
LOGGER.error("resource {} does not exist, cannot update", uri);
throw new NotFoundException("resource " + uri + " does not exist, cannot update");
} else {
LOGGER.error("error updating resource {}: {} {}", uri, status.getStatusCode(),
status.getReasonPhrase());
throw new FedoraException("error updating resource " + uri + ": " + status.getStatusCode() + " " +
status.getReasonPhrase());
}
} catch (final FedoraException e) {
throw e;
} catch (final Exception e) {
LOGGER.error("Error executing request", e);
throw new FedoraException(e);
} finally {
delete.releaseConnection();
}
} | [
"public",
"void",
"removeTombstone",
"(",
"final",
"String",
"path",
")",
"throws",
"FedoraException",
"{",
"final",
"HttpDelete",
"delete",
"=",
"httpHelper",
".",
"createDeleteMethod",
"(",
"path",
"+",
"\"/fcr:tombstone\"",
")",
";",
"try",
"{",
"final",
"Htt... | Remove tombstone located at given path | [
"Remove",
"tombstone",
"located",
"at",
"given",
"path"
] | 21eaf27200c5b2542095f6ebb9dd8ec865b95bbd | https://github.com/fcrepo4-labs/fcrepo4-client/blob/21eaf27200c5b2542095f6ebb9dd8ec865b95bbd/fcrepo-client-impl/src/main/java/org/fcrepo/client/impl/FedoraResourceImpl.java#L186-L213 | train |
fcrepo4-labs/fcrepo4-client | fcrepo-client-impl/src/main/java/org/fcrepo/client/impl/FedoraResourceImpl.java | FedoraResourceImpl.getPropertyValues | protected Collection<String> getPropertyValues(final Property property) {
final ExtendedIterator<Triple> iterator = graph.find(Node.ANY,
property.asNode(),
Node.ANY);
final Set<String> set = new HashSet<>();
while (iterator.hasNext()) {
final Node object = iterator.next().getObject();
if (object.isLiteral()) {
set.add(object.getLiteralValue().toString());
} else if (object.isURI()) {
set.add(object.getURI().toString());
} else {
set.add(object.toString());
}
}
return set;
} | java | protected Collection<String> getPropertyValues(final Property property) {
final ExtendedIterator<Triple> iterator = graph.find(Node.ANY,
property.asNode(),
Node.ANY);
final Set<String> set = new HashSet<>();
while (iterator.hasNext()) {
final Node object = iterator.next().getObject();
if (object.isLiteral()) {
set.add(object.getLiteralValue().toString());
} else if (object.isURI()) {
set.add(object.getURI().toString());
} else {
set.add(object.toString());
}
}
return set;
} | [
"protected",
"Collection",
"<",
"String",
">",
"getPropertyValues",
"(",
"final",
"Property",
"property",
")",
"{",
"final",
"ExtendedIterator",
"<",
"Triple",
">",
"iterator",
"=",
"graph",
".",
"find",
"(",
"Node",
".",
"ANY",
",",
"property",
".",
"asNode... | Return all the values of a property
@param property The Property to get values for
@return Collection of values | [
"Return",
"all",
"the",
"values",
"of",
"a",
"property"
] | 21eaf27200c5b2542095f6ebb9dd8ec865b95bbd | https://github.com/fcrepo4-labs/fcrepo4-client/blob/21eaf27200c5b2542095f6ebb9dd8ec865b95bbd/fcrepo-client-impl/src/main/java/org/fcrepo/client/impl/FedoraResourceImpl.java#L479-L495 | train |
AdeptInternet/auth-java | saml/src/main/java/org/adeptnet/auth/saml/SAMLUtils.java | SAMLUtils.generateRequestId | public static String generateRequestId() {
/* compute a random 256-bit string and hex-encode it */
final SecureRandom sr = new SecureRandom();
final byte[] bytes = new byte[32];
sr.nextBytes(bytes);
return hexEncode(bytes);
} | java | public static String generateRequestId() {
/* compute a random 256-bit string and hex-encode it */
final SecureRandom sr = new SecureRandom();
final byte[] bytes = new byte[32];
sr.nextBytes(bytes);
return hexEncode(bytes);
} | [
"public",
"static",
"String",
"generateRequestId",
"(",
")",
"{",
"/* compute a random 256-bit string and hex-encode it */",
"final",
"SecureRandom",
"sr",
"=",
"new",
"SecureRandom",
"(",
")",
";",
"final",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"32"... | Generate a request ID suitable for passing to
SAMLClient.createAuthnRequest. | [
"Generate",
"a",
"request",
"ID",
"suitable",
"for",
"passing",
"to",
"SAMLClient",
".",
"createAuthnRequest",
"."
] | 644116ed1f50bf899b9cecc5e3682bac7abf7007 | https://github.com/AdeptInternet/auth-java/blob/644116ed1f50bf899b9cecc5e3682bac7abf7007/saml/src/main/java/org/adeptnet/auth/saml/SAMLUtils.java#L37-L43 | train |
TechShroom/lettar | src/main/java/com/techshroom/lettar/mime/MimeType.java | MimeType.isAssignableTo | public final boolean isAssignableTo(MimeType mimeType) {
if (mimeType.getPrimaryType().equals("*")) {
// matches all
return true;
}
if (!mimeType.getPrimaryType().equalsIgnoreCase(getPrimaryType())) {
return false;
}
String mtSec = mimeType.getSecondaryType();
return mtSec.equals("*") || mtSec.equalsIgnoreCase(getSecondaryType());
} | java | public final boolean isAssignableTo(MimeType mimeType) {
if (mimeType.getPrimaryType().equals("*")) {
// matches all
return true;
}
if (!mimeType.getPrimaryType().equalsIgnoreCase(getPrimaryType())) {
return false;
}
String mtSec = mimeType.getSecondaryType();
return mtSec.equals("*") || mtSec.equalsIgnoreCase(getSecondaryType());
} | [
"public",
"final",
"boolean",
"isAssignableTo",
"(",
"MimeType",
"mimeType",
")",
"{",
"if",
"(",
"mimeType",
".",
"getPrimaryType",
"(",
")",
".",
"equals",
"(",
"\"*\"",
")",
")",
"{",
"// matches all",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"mime... | Checks if this MIME type is a subtype of the provided MIME type.
@param mimeType
- the MIME type to check against
@return {@code true} if this MIME type is a subtype of the provided MIME
type | [
"Checks",
"if",
"this",
"MIME",
"type",
"is",
"a",
"subtype",
"of",
"the",
"provided",
"MIME",
"type",
"."
] | 97a38d1ff7f7dd5f7ff98bafd633e074791a6947 | https://github.com/TechShroom/lettar/blob/97a38d1ff7f7dd5f7ff98bafd633e074791a6947/src/main/java/com/techshroom/lettar/mime/MimeType.java#L86-L96 | train |
j-a-w-r/jawr-tools | jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/spring/SpringControllerBundleProcessor.java | SpringControllerBundleProcessor.initJawrSpringServlets | @SuppressWarnings("rawtypes")
public List<ServletDefinition> initJawrSpringServlets(ServletContext servletContext) throws ServletException{
List<ServletDefinition> jawrServletDefinitions = new ArrayList<ServletDefinition>();
ContextLoader contextLoader = new ContextLoader();
WebApplicationContext applicationCtx = contextLoader.initWebApplicationContext(servletContext);
Map<?, ?> jawrControllersMap = applicationCtx.getBeansOfType(JawrSpringController.class);
Iterator<?> entrySetIterator = jawrControllersMap.entrySet().iterator();
while(entrySetIterator.hasNext()){
JawrSpringController jawrController = (JawrSpringController) ((Map.Entry) entrySetIterator.next()).getValue();
Map<String, Object> initParams = new HashMap<String, Object>();
initParams.putAll(jawrController.getInitParams());
ServletConfig servletConfig = new MockServletConfig(SPRING_DISPATCHER_SERVLET,servletContext, initParams);
MockJawrSpringServlet servlet = new MockJawrSpringServlet(jawrController, servletConfig);
ServletDefinition servletDefinition = new ServletDefinition(servlet, servletConfig) ;
jawrServletDefinitions.add(servletDefinition);
}
contextLoader.closeWebApplicationContext(servletContext);
return jawrServletDefinitions;
} | java | @SuppressWarnings("rawtypes")
public List<ServletDefinition> initJawrSpringServlets(ServletContext servletContext) throws ServletException{
List<ServletDefinition> jawrServletDefinitions = new ArrayList<ServletDefinition>();
ContextLoader contextLoader = new ContextLoader();
WebApplicationContext applicationCtx = contextLoader.initWebApplicationContext(servletContext);
Map<?, ?> jawrControllersMap = applicationCtx.getBeansOfType(JawrSpringController.class);
Iterator<?> entrySetIterator = jawrControllersMap.entrySet().iterator();
while(entrySetIterator.hasNext()){
JawrSpringController jawrController = (JawrSpringController) ((Map.Entry) entrySetIterator.next()).getValue();
Map<String, Object> initParams = new HashMap<String, Object>();
initParams.putAll(jawrController.getInitParams());
ServletConfig servletConfig = new MockServletConfig(SPRING_DISPATCHER_SERVLET,servletContext, initParams);
MockJawrSpringServlet servlet = new MockJawrSpringServlet(jawrController, servletConfig);
ServletDefinition servletDefinition = new ServletDefinition(servlet, servletConfig) ;
jawrServletDefinitions.add(servletDefinition);
}
contextLoader.closeWebApplicationContext(servletContext);
return jawrServletDefinitions;
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"List",
"<",
"ServletDefinition",
">",
"initJawrSpringServlets",
"(",
"ServletContext",
"servletContext",
")",
"throws",
"ServletException",
"{",
"List",
"<",
"ServletDefinition",
">",
"jawrServletDefinitions",
... | Initialize the servlets which will handle the request to the JawrSpringController
@param servletContext the servlet context
@return the list of servlet definition for the JawrSpringControllers
@throws ServletException if a servlet exception occurs | [
"Initialize",
"the",
"servlets",
"which",
"will",
"handle",
"the",
"request",
"to",
"the",
"JawrSpringController"
] | ebae989e55b53fd7dca4450ed9294c6f64309041 | https://github.com/j-a-w-r/jawr-tools/blob/ebae989e55b53fd7dca4450ed9294c6f64309041/jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/spring/SpringControllerBundleProcessor.java#L51-L73 | train |
fcrepo4-labs/fcrepo4-client | fcrepo-client-impl/src/main/java/org/fcrepo/client/utils/RDFSinkFilter.java | RDFSinkFilter.filterTriples | public static Graph filterTriples (
final Iterator<Triple> triples,
final Node... properties) {
final Graph filteredGraph = new RandomOrderGraph(RandomOrderGraph.createDefaultGraph());
final Sink<Triple> graphOutput = new SinkTriplesToGraph(true, filteredGraph);
final RDFSinkFilter rdfFilter = new RDFSinkFilter(graphOutput, properties);
rdfFilter.start();
while (triples.hasNext()) {
final Triple triple = triples.next();
rdfFilter.triple(triple);
}
rdfFilter.finish();
return filteredGraph;
} | java | public static Graph filterTriples (
final Iterator<Triple> triples,
final Node... properties) {
final Graph filteredGraph = new RandomOrderGraph(RandomOrderGraph.createDefaultGraph());
final Sink<Triple> graphOutput = new SinkTriplesToGraph(true, filteredGraph);
final RDFSinkFilter rdfFilter = new RDFSinkFilter(graphOutput, properties);
rdfFilter.start();
while (triples.hasNext()) {
final Triple triple = triples.next();
rdfFilter.triple(triple);
}
rdfFilter.finish();
return filteredGraph;
} | [
"public",
"static",
"Graph",
"filterTriples",
"(",
"final",
"Iterator",
"<",
"Triple",
">",
"triples",
",",
"final",
"Node",
"...",
"properties",
")",
"{",
"final",
"Graph",
"filteredGraph",
"=",
"new",
"RandomOrderGraph",
"(",
"RandomOrderGraph",
".",
"createDe... | Filter the triples
@param triples Iterator of triples
@param properties Properties to include
@return Graph containing the fitlered triples | [
"Filter",
"the",
"triples"
] | 21eaf27200c5b2542095f6ebb9dd8ec865b95bbd | https://github.com/fcrepo4-labs/fcrepo4-client/blob/21eaf27200c5b2542095f6ebb9dd8ec865b95bbd/fcrepo-client-impl/src/main/java/org/fcrepo/client/utils/RDFSinkFilter.java#L68-L81 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/model/TypesImpl.java | TypesImpl.directSupertypes | @Override
public List<? extends TypeMirror> directSupertypes(TypeMirror t)
{
switch (t.getKind())
{
case DECLARED:
DeclaredType dt = (DeclaredType) t;
TypeElement te = (TypeElement) dt.asElement();
List<TypeMirror> list = new ArrayList<>();
TypeElement superclass = (TypeElement) asElement(te.getSuperclass());
if (superclass != null)
{
list.add(0, superclass.asType());
}
list.addAll(te.getInterfaces());
return list;
case EXECUTABLE:
case PACKAGE:
throw new IllegalArgumentException(t.getKind().name());
default:
throw new UnsupportedOperationException(t.getKind().name()+" not supported yet");
}
} | java | @Override
public List<? extends TypeMirror> directSupertypes(TypeMirror t)
{
switch (t.getKind())
{
case DECLARED:
DeclaredType dt = (DeclaredType) t;
TypeElement te = (TypeElement) dt.asElement();
List<TypeMirror> list = new ArrayList<>();
TypeElement superclass = (TypeElement) asElement(te.getSuperclass());
if (superclass != null)
{
list.add(0, superclass.asType());
}
list.addAll(te.getInterfaces());
return list;
case EXECUTABLE:
case PACKAGE:
throw new IllegalArgumentException(t.getKind().name());
default:
throw new UnsupportedOperationException(t.getKind().name()+" not supported yet");
}
} | [
"@",
"Override",
"public",
"List",
"<",
"?",
"extends",
"TypeMirror",
">",
"directSupertypes",
"(",
"TypeMirror",
"t",
")",
"{",
"switch",
"(",
"t",
".",
"getKind",
"(",
")",
")",
"{",
"case",
"DECLARED",
":",
"DeclaredType",
"dt",
"=",
"(",
"DeclaredTyp... | The direct superclass is the class from whose implementation the
implementation of the current class is derived.
@param t
@return | [
"The",
"direct",
"superclass",
"is",
"the",
"class",
"from",
"whose",
"implementation",
"the",
"implementation",
"of",
"the",
"current",
"class",
"is",
"derived",
"."
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/model/TypesImpl.java#L322-L344 | train |
pierre/ning-service-skeleton | core/src/main/java/com/ning/jetty/core/modules/ServerModule.java | ServerModule.getJacksonProvider | protected Provider<ObjectMapper> getJacksonProvider()
{
return new Provider<ObjectMapper>()
{
@Override
public ObjectMapper get()
{
final ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
};
} | java | protected Provider<ObjectMapper> getJacksonProvider()
{
return new Provider<ObjectMapper>()
{
@Override
public ObjectMapper get()
{
final ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
};
} | [
"protected",
"Provider",
"<",
"ObjectMapper",
">",
"getJacksonProvider",
"(",
")",
"{",
"return",
"new",
"Provider",
"<",
"ObjectMapper",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ObjectMapper",
"get",
"(",
")",
"{",
"final",
"ObjectMapper",
"mapper",
... | Override this method to provide your own Jackson provider.
@return ObjectMapper provider for Jackson | [
"Override",
"this",
"method",
"to",
"provide",
"your",
"own",
"Jackson",
"provider",
"."
] | 766369c8c975d262ede212e81d89b65c589090b7 | https://github.com/pierre/ning-service-skeleton/blob/766369c8c975d262ede212e81d89b65c589090b7/core/src/main/java/com/ning/jetty/core/modules/ServerModule.java#L63-L76 | train |
pierre/ning-service-skeleton | core/src/main/java/com/ning/jetty/core/listeners/SetupServer.java | SetupServer.injector | public Injector injector(final ServletContextEvent event)
{
return (Injector) event.getServletContext().getAttribute(Injector.class.getName());
} | java | public Injector injector(final ServletContextEvent event)
{
return (Injector) event.getServletContext().getAttribute(Injector.class.getName());
} | [
"public",
"Injector",
"injector",
"(",
"final",
"ServletContextEvent",
"event",
")",
"{",
"return",
"(",
"Injector",
")",
"event",
".",
"getServletContext",
"(",
")",
".",
"getAttribute",
"(",
"Injector",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"... | This method can be called by classes extending SetupServer to retrieve
the actual injector. This requires some inside knowledge on where it is
stored, but the actual key is not visible outside the guice packages. | [
"This",
"method",
"can",
"be",
"called",
"by",
"classes",
"extending",
"SetupServer",
"to",
"retrieve",
"the",
"actual",
"injector",
".",
"This",
"requires",
"some",
"inside",
"knowledge",
"on",
"where",
"it",
"is",
"stored",
"but",
"the",
"actual",
"key",
"... | 766369c8c975d262ede212e81d89b65c589090b7 | https://github.com/pierre/ning-service-skeleton/blob/766369c8c975d262ede212e81d89b65c589090b7/core/src/main/java/com/ning/jetty/core/listeners/SetupServer.java#L102-L105 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/RDFDatabaseWriter.java | RDFDatabaseWriter.writeParent | private void writeParent(Account account, XmlStreamWriter writer)
throws Exception {
// Sequence block
writer.writeStartElement("RDF:Seq");
writer.writeAttribute("RDF:about", account.getId());
for (Account child : account.getChildren()) {
logger.fine(" Write-RDF:li: " + child.getId());
writer.writeStartElement("RDF:li");
writer.writeAttribute("RDF:resource", child.getId());
writer.writeEndElement();
}
writer.writeEndElement();
// Descriptions of all elements including the parent
writeDescription(account, writer);
for (Account child : account.getChildren()) {
logger.fine("Write-RDF:Desc: " + child.getName());
writeDescription(child, writer);
}
// Recurse into the children
for (Account child : account.getChildren()) {
if (child.getChildren().size() > 0) {
writeParent(child, writer);
}
}
} | java | private void writeParent(Account account, XmlStreamWriter writer)
throws Exception {
// Sequence block
writer.writeStartElement("RDF:Seq");
writer.writeAttribute("RDF:about", account.getId());
for (Account child : account.getChildren()) {
logger.fine(" Write-RDF:li: " + child.getId());
writer.writeStartElement("RDF:li");
writer.writeAttribute("RDF:resource", child.getId());
writer.writeEndElement();
}
writer.writeEndElement();
// Descriptions of all elements including the parent
writeDescription(account, writer);
for (Account child : account.getChildren()) {
logger.fine("Write-RDF:Desc: " + child.getName());
writeDescription(child, writer);
}
// Recurse into the children
for (Account child : account.getChildren()) {
if (child.getChildren().size() > 0) {
writeParent(child, writer);
}
}
} | [
"private",
"void",
"writeParent",
"(",
"Account",
"account",
",",
"XmlStreamWriter",
"writer",
")",
"throws",
"Exception",
"{",
"// Sequence block\r",
"writer",
".",
"writeStartElement",
"(",
"\"RDF:Seq\"",
")",
";",
"writer",
".",
"writeAttribute",
"(",
"\"RDF:abou... | Writes a parent node to the stream, recursing into any children.
@param account The parent account to write.
@param writer The XML stream to write to.
@throws Exception on who the hell knows. | [
"Writes",
"a",
"parent",
"node",
"to",
"the",
"stream",
"recursing",
"into",
"any",
"children",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/RDFDatabaseWriter.java#L194-L220 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/RDFDatabaseWriter.java | RDFDatabaseWriter.writeFFGlobalSettings | private void writeFFGlobalSettings(Database db, XmlStreamWriter writer)
throws Exception {
writer.writeStartElement("RDF:Description");
writer.writeAttribute("RDF:about", RDFDatabaseReader.FF_GLOBAL_SETTINGS_URI);
for (String key : db.getGlobalSettings().keySet()) {
writer.writeAttribute(key, db.getGlobalSettings().get(key));
}
writer.writeEndElement();
} | java | private void writeFFGlobalSettings(Database db, XmlStreamWriter writer)
throws Exception {
writer.writeStartElement("RDF:Description");
writer.writeAttribute("RDF:about", RDFDatabaseReader.FF_GLOBAL_SETTINGS_URI);
for (String key : db.getGlobalSettings().keySet()) {
writer.writeAttribute(key, db.getGlobalSettings().get(key));
}
writer.writeEndElement();
} | [
"private",
"void",
"writeFFGlobalSettings",
"(",
"Database",
"db",
",",
"XmlStreamWriter",
"writer",
")",
"throws",
"Exception",
"{",
"writer",
".",
"writeStartElement",
"(",
"\"RDF:Description\"",
")",
";",
"writer",
".",
"writeAttribute",
"(",
"\"RDF:about\"",
","... | Writes the firefox settings back.
@param db The database with the settings to write.
@param writer The XML stream to write to.
@throws Exception ... probably never. | [
"Writes",
"the",
"firefox",
"settings",
"back",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/RDFDatabaseWriter.java#L229-L240 | train |
geomajas/geomajas-project-geometry | core/src/main/java/org/geomajas/geometry/service/MathService.java | MathService.intersectsLineSegment | public static boolean intersectsLineSegment(Coordinate a, Coordinate b, Coordinate c, Coordinate d) {
// check single-point segment: these never intersect
if ((a.getX() == b.getX() && a.getY() == b.getY()) || (c.getX() == d.getX() && c.getY() == d.getY())) {
return false;
}
double c1 = cross(a, c, a, b);
double c2 = cross(a, b, c, d);
if (c1 == 0 && c2 == 0) {
// colinear, only intersecting if overlapping (touch is ok)
double xmin = Math.min(a.getX(), b.getX());
double ymin = Math.min(a.getY(), b.getY());
double xmax = Math.max(a.getX(), b.getX());
double ymax = Math.max(a.getY(), b.getY());
// check first point of last segment in bounding box of first segment
if (c.getX() > xmin && c.getX() < xmax && c.getY() > ymin && c.getY() < ymax) {
return true;
// check last point of last segment in bounding box of first segment
} else if (d.getX() > xmin && d.getX() < xmax && d.getY() > ymin && d.getY() < ymax) {
return true;
// check same segment
} else {
return c.getX() >= xmin && c.getX() <= xmax && c.getY() >= ymin && c.getY() <= ymax & d.getX() >= xmin
&& d.getX() <= xmax && d.getY() >= ymin && d.getY() <= ymax;
}
}
if (c2 == 0) {
// segments are parallel but not colinear
return false;
}
// not parallel, classical test
double u = c1 / c2;
double t = cross(a, c, c, d) / c2;
return (t > 0) && (t < 1) && (u > 0) && (u < 1);
} | java | public static boolean intersectsLineSegment(Coordinate a, Coordinate b, Coordinate c, Coordinate d) {
// check single-point segment: these never intersect
if ((a.getX() == b.getX() && a.getY() == b.getY()) || (c.getX() == d.getX() && c.getY() == d.getY())) {
return false;
}
double c1 = cross(a, c, a, b);
double c2 = cross(a, b, c, d);
if (c1 == 0 && c2 == 0) {
// colinear, only intersecting if overlapping (touch is ok)
double xmin = Math.min(a.getX(), b.getX());
double ymin = Math.min(a.getY(), b.getY());
double xmax = Math.max(a.getX(), b.getX());
double ymax = Math.max(a.getY(), b.getY());
// check first point of last segment in bounding box of first segment
if (c.getX() > xmin && c.getX() < xmax && c.getY() > ymin && c.getY() < ymax) {
return true;
// check last point of last segment in bounding box of first segment
} else if (d.getX() > xmin && d.getX() < xmax && d.getY() > ymin && d.getY() < ymax) {
return true;
// check same segment
} else {
return c.getX() >= xmin && c.getX() <= xmax && c.getY() >= ymin && c.getY() <= ymax & d.getX() >= xmin
&& d.getX() <= xmax && d.getY() >= ymin && d.getY() <= ymax;
}
}
if (c2 == 0) {
// segments are parallel but not colinear
return false;
}
// not parallel, classical test
double u = c1 / c2;
double t = cross(a, c, c, d) / c2;
return (t > 0) && (t < 1) && (u > 0) && (u < 1);
} | [
"public",
"static",
"boolean",
"intersectsLineSegment",
"(",
"Coordinate",
"a",
",",
"Coordinate",
"b",
",",
"Coordinate",
"c",
",",
"Coordinate",
"d",
")",
"{",
"// check single-point segment: these never intersect",
"if",
"(",
"(",
"a",
".",
"getX",
"(",
")",
... | Calculates whether or not 2 line-segments intersect. The definition we use is that line segments intersect if
they either cross or overlap. If they touch in 1 end point, they do not intersect. This definition is most useful
for checking polygon validity, as touching rings in 1 point are allowed, but crossing or overlapping not.
@param a First coordinate of the first line-segment.
@param b Second coordinate of the first line-segment.
@param c First coordinate of the second line-segment.
@param d Second coordinate of the second line-segment.
@return Returns true or false. | [
"Calculates",
"whether",
"or",
"not",
"2",
"line",
"-",
"segments",
"intersect",
".",
"The",
"definition",
"we",
"use",
"is",
"that",
"line",
"segments",
"intersect",
"if",
"they",
"either",
"cross",
"or",
"overlap",
".",
"If",
"they",
"touch",
"in",
"1",
... | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/core/src/main/java/org/geomajas/geometry/service/MathService.java#L41-L74 | train |
geomajas/geomajas-project-geometry | core/src/main/java/org/geomajas/geometry/service/MathService.java | MathService.cross | private static double cross(Coordinate a1, Coordinate a2, Coordinate b1, Coordinate b2) {
return (a2.getX() - a1.getX()) * (b2.getY() - b1.getY()) - (a2.getY() - a1.getY()) * (b2.getX() - b1.getX());
} | java | private static double cross(Coordinate a1, Coordinate a2, Coordinate b1, Coordinate b2) {
return (a2.getX() - a1.getX()) * (b2.getY() - b1.getY()) - (a2.getY() - a1.getY()) * (b2.getX() - b1.getX());
} | [
"private",
"static",
"double",
"cross",
"(",
"Coordinate",
"a1",
",",
"Coordinate",
"a2",
",",
"Coordinate",
"b1",
",",
"Coordinate",
"b2",
")",
"{",
"return",
"(",
"a2",
".",
"getX",
"(",
")",
"-",
"a1",
".",
"getX",
"(",
")",
")",
"*",
"(",
"b2",... | cross-product of 2 vectors | [
"cross",
"-",
"product",
"of",
"2",
"vectors"
] | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/core/src/main/java/org/geomajas/geometry/service/MathService.java#L77-L79 | train |
geomajas/geomajas-project-geometry | core/src/main/java/org/geomajas/geometry/service/MathService.java | MathService.distance | public static double distance(Coordinate c1, Coordinate c2) {
double a = c1.getX() - c2.getX();
double b = c1.getY() - c2.getY();
return Math.sqrt(a * a + b * b);
} | java | public static double distance(Coordinate c1, Coordinate c2) {
double a = c1.getX() - c2.getX();
double b = c1.getY() - c2.getY();
return Math.sqrt(a * a + b * b);
} | [
"public",
"static",
"double",
"distance",
"(",
"Coordinate",
"c1",
",",
"Coordinate",
"c2",
")",
"{",
"double",
"a",
"=",
"c1",
".",
"getX",
"(",
")",
"-",
"c2",
".",
"getX",
"(",
")",
";",
"double",
"b",
"=",
"c1",
".",
"getY",
"(",
")",
"-",
... | Distance between 2 points.
@param c1 First coordinate
@param c2 Second coordinate
@return distance between given points | [
"Distance",
"between",
"2",
"points",
"."
] | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/core/src/main/java/org/geomajas/geometry/service/MathService.java#L154-L158 | train |
geomajas/geomajas-project-geometry | core/src/main/java/org/geomajas/geometry/service/MathService.java | MathService.distance | public static double distance(Coordinate c1, Coordinate c2, Coordinate c) {
return distance(nearest(c1, c2, c), c);
} | java | public static double distance(Coordinate c1, Coordinate c2, Coordinate c) {
return distance(nearest(c1, c2, c), c);
} | [
"public",
"static",
"double",
"distance",
"(",
"Coordinate",
"c1",
",",
"Coordinate",
"c2",
",",
"Coordinate",
"c",
")",
"{",
"return",
"distance",
"(",
"nearest",
"(",
"c1",
",",
"c2",
",",
"c",
")",
",",
"c",
")",
";",
"}"
] | Distance between a point and a line segment. This method looks at the line segment c1-c2, it does not regard it
as a line. This means that the distance to c is calculated to a point between c1 and c2.
@param c1 First coordinate of the line segment.
@param c2 Second coordinate of the line segment.
@param c Coordinate to calculate distance to line from.
@return distance between point and line segment | [
"Distance",
"between",
"a",
"point",
"and",
"a",
"line",
"segment",
".",
"This",
"method",
"looks",
"at",
"the",
"line",
"segment",
"c1",
"-",
"c2",
"it",
"does",
"not",
"regard",
"it",
"as",
"a",
"line",
".",
"This",
"means",
"that",
"the",
"distance"... | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/core/src/main/java/org/geomajas/geometry/service/MathService.java#L169-L171 | train |
geomajas/geomajas-project-geometry | core/src/main/java/org/geomajas/geometry/service/MathService.java | MathService.nearest | public static Coordinate nearest(Coordinate c1, Coordinate c2, Coordinate c) {
double len = distance(c1, c2);
double u = (c.getX() - c1.getX()) * (c2.getX() - c1.getX()) + (c.getY() - c1.getY()) * (c2.getY() - c1.getY());
u = u / (len * len);
if (u < 0.00001 || u > 1) {
// Shortest point not within LineSegment, so take closest end-point.
double len1 = distance(c, c1);
double len2 = distance(c, c2);
if (len1 < len2) {
return c1;
}
return c2;
} else {
// Intersecting point is on the line, use the formula: P = P1 + u (P2 - P1)
double x1 = c1.getX() + u * (c2.getX() - c1.getX());
double y1 = c1.getY() + u * (c2.getY() - c1.getY());
return new Coordinate(x1, y1);
}
} | java | public static Coordinate nearest(Coordinate c1, Coordinate c2, Coordinate c) {
double len = distance(c1, c2);
double u = (c.getX() - c1.getX()) * (c2.getX() - c1.getX()) + (c.getY() - c1.getY()) * (c2.getY() - c1.getY());
u = u / (len * len);
if (u < 0.00001 || u > 1) {
// Shortest point not within LineSegment, so take closest end-point.
double len1 = distance(c, c1);
double len2 = distance(c, c2);
if (len1 < len2) {
return c1;
}
return c2;
} else {
// Intersecting point is on the line, use the formula: P = P1 + u (P2 - P1)
double x1 = c1.getX() + u * (c2.getX() - c1.getX());
double y1 = c1.getY() + u * (c2.getY() - c1.getY());
return new Coordinate(x1, y1);
}
} | [
"public",
"static",
"Coordinate",
"nearest",
"(",
"Coordinate",
"c1",
",",
"Coordinate",
"c2",
",",
"Coordinate",
"c",
")",
"{",
"double",
"len",
"=",
"distance",
"(",
"c1",
",",
"c2",
")",
";",
"double",
"u",
"=",
"(",
"c",
".",
"getX",
"(",
")",
... | Calculate which point on a line segment is nearest to the given coordinate. Will be perpendicular or one of the
end-points.
@param c1 First coordinate of the line segment.
@param c2 Second coordinate of the line segment.
@param c The coordinate to search the nearest point for.
@return The point on the line segment nearest to the given coordinate. | [
"Calculate",
"which",
"point",
"on",
"a",
"line",
"segment",
"is",
"nearest",
"to",
"the",
"given",
"coordinate",
".",
"Will",
"be",
"perpendicular",
"or",
"one",
"of",
"the",
"end",
"-",
"points",
"."
] | 09a214fede69c9c01e41630828c4abbb551a557d | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/core/src/main/java/org/geomajas/geometry/service/MathService.java#L182-L202 | train |
osglworks/java-http | src/main/java/org/osgl/http/HttpConfig.java | HttpConfig.isXForwardedAllowed | public static boolean isXForwardedAllowed(String remoteAddr) {
return isXForwardedAllowed() && (S.eq("all", xForwardedAllowed) || xForwardedAllowed.contains(remoteAddr));
} | java | public static boolean isXForwardedAllowed(String remoteAddr) {
return isXForwardedAllowed() && (S.eq("all", xForwardedAllowed) || xForwardedAllowed.contains(remoteAddr));
} | [
"public",
"static",
"boolean",
"isXForwardedAllowed",
"(",
"String",
"remoteAddr",
")",
"{",
"return",
"isXForwardedAllowed",
"(",
")",
"&&",
"(",
"S",
".",
"eq",
"(",
"\"all\"",
",",
"xForwardedAllowed",
")",
"||",
"xForwardedAllowed",
".",
"contains",
"(",
"... | Does the remote address is allowed for x-forwarded header
@param remoteAddr the remote address
@return is the remote address allowed for x-forwarded header | [
"Does",
"the",
"remote",
"address",
"is",
"allowed",
"for",
"x",
"-",
"forwarded",
"header"
] | c75a1beb12bb6ad085539e681ae9539b9875c1e5 | https://github.com/osglworks/java-http/blob/c75a1beb12bb6ad085539e681ae9539b9875c1e5/src/main/java/org/osgl/http/HttpConfig.java#L127-L129 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Account.java | Account.createId | public static String createId(Account acc)
throws Exception {
return Account.createId(acc.getName() + acc.getDesc() + (new Random()).nextLong() + Runtime.getRuntime().freeMemory());
} | java | public static String createId(Account acc)
throws Exception {
return Account.createId(acc.getName() + acc.getDesc() + (new Random()).nextLong() + Runtime.getRuntime().freeMemory());
} | [
"public",
"static",
"String",
"createId",
"(",
"Account",
"acc",
")",
"throws",
"Exception",
"{",
"return",
"Account",
".",
"createId",
"(",
"acc",
".",
"getName",
"(",
")",
"+",
"acc",
".",
"getDesc",
"(",
")",
"+",
"(",
"new",
"Random",
"(",
")",
"... | Creates and _returns_ an ID from data in an account.
@param acc The account to base the data off.
@return The new ID.
@throws Exception on error. | [
"Creates",
"and",
"_returns_",
"an",
"ID",
"from",
"data",
"in",
"an",
"account",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Account.java#L229-L232 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Account.java | Account.getChild | public Account getChild(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= children.size())
throw new IndexOutOfBoundsException("Illegal child index, " + index);
return children.get(index);
} | java | public Account getChild(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= children.size())
throw new IndexOutOfBoundsException("Illegal child index, " + index);
return children.get(index);
} | [
"public",
"Account",
"getChild",
"(",
"int",
"index",
")",
"throws",
"IndexOutOfBoundsException",
"{",
"if",
"(",
"index",
"<",
"0",
"||",
"index",
">=",
"children",
".",
"size",
"(",
")",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Illegal child... | Gets a specifically indexed child.
@param index The index of the child to get.
@return The child at the index.
@throws IndexOutOfBoundsException upon invalid index. | [
"Gets",
"a",
"specifically",
"indexed",
"child",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Account.java#L617-L621 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Account.java | Account.hasChild | public boolean hasChild(Account account) {
for (Account child : children) {
if (child.equals(account))
return true;
}
return false;
} | java | public boolean hasChild(Account account) {
for (Account child : children) {
if (child.equals(account))
return true;
}
return false;
} | [
"public",
"boolean",
"hasChild",
"(",
"Account",
"account",
")",
"{",
"for",
"(",
"Account",
"child",
":",
"children",
")",
"{",
"if",
"(",
"child",
".",
"equals",
"(",
"account",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Tests if an account is a direct child of this account.
@param account check if the passed in account is a child of 'this' account
@return true if given account is a child of 'this' account | [
"Tests",
"if",
"an",
"account",
"is",
"a",
"direct",
"child",
"of",
"this",
"account",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Account.java#L633-L639 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Account.java | Account.compareTo | public int compareTo(Account o) {
if (this.isFolder() && !o.isFolder())
return -1;
else if (!this.isFolder() && o.isFolder())
return 1;
// First ignore case, if they equate, use case.
int result = name.compareToIgnoreCase(o.name);
if (result == 0)
return name.compareTo(o.name);
else
return result;
} | java | public int compareTo(Account o) {
if (this.isFolder() && !o.isFolder())
return -1;
else if (!this.isFolder() && o.isFolder())
return 1;
// First ignore case, if they equate, use case.
int result = name.compareToIgnoreCase(o.name);
if (result == 0)
return name.compareTo(o.name);
else
return result;
} | [
"public",
"int",
"compareTo",
"(",
"Account",
"o",
")",
"{",
"if",
"(",
"this",
".",
"isFolder",
"(",
")",
"&&",
"!",
"o",
".",
"isFolder",
"(",
")",
")",
"return",
"-",
"1",
";",
"else",
"if",
"(",
"!",
"this",
".",
"isFolder",
"(",
")",
"&&",... | Implements the Comparable<Account> interface, this is based first on if the
account is a folder or not. This is so that during sorting, all folders are
first in the list. Finally, it is based on the name.
@param o The other account to compare to.
@return this.name.compareTo(otherAccount.name); | [
"Implements",
"the",
"Comparable<",
";",
"Account>",
";",
"interface",
"this",
"is",
"based",
"first",
"on",
"if",
"the",
"account",
"is",
"a",
"folder",
"or",
"not",
".",
"This",
"is",
"so",
"that",
"during",
"sorting",
"all",
"folders",
"are",
"first... | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Account.java#L649-L661 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Account.java | Account.setPatterns | @SuppressWarnings("UnusedDeclaration")
public void setPatterns(Iterable<AccountPatternData> patterns) {
this.patterns.clear();
for (AccountPatternData data : patterns) {
this.patterns.add(new AccountPatternData(data));
}
} | java | @SuppressWarnings("UnusedDeclaration")
public void setPatterns(Iterable<AccountPatternData> patterns) {
this.patterns.clear();
for (AccountPatternData data : patterns) {
this.patterns.add(new AccountPatternData(data));
}
} | [
"@",
"SuppressWarnings",
"(",
"\"UnusedDeclaration\"",
")",
"public",
"void",
"setPatterns",
"(",
"Iterable",
"<",
"AccountPatternData",
">",
"patterns",
")",
"{",
"this",
".",
"patterns",
".",
"clear",
"(",
")",
";",
"for",
"(",
"AccountPatternData",
"data",
... | This will make a deep clone of the passed in Iterable.
This will also replace any patterns already set.
@param patterns the patterns to set | [
"This",
"will",
"make",
"a",
"deep",
"clone",
"of",
"the",
"passed",
"in",
"Iterable",
".",
"This",
"will",
"also",
"replace",
"any",
"patterns",
"already",
"set",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Account.java#L697-L703 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/diff/FileReport.java | FileReport.close | public void close() throws DiffException {
try {
if(writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
throw new DiffException("Failed to close report file", e);
}
} | java | public void close() throws DiffException {
try {
if(writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
throw new DiffException("Failed to close report file", e);
}
} | [
"public",
"void",
"close",
"(",
")",
"throws",
"DiffException",
"{",
"try",
"{",
"if",
"(",
"writer",
"!=",
"null",
")",
"{",
"writer",
".",
"flush",
"(",
")",
";",
"writer",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
... | Close the file report instance and it's underlying writer
@throws DiffException | [
"Close",
"the",
"file",
"report",
"instance",
"and",
"it",
"s",
"underlying",
"writer"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/diff/FileReport.java#L59-L68 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Database.java | Database.swapAccounts | public void swapAccounts(Database other) {
Account otherRoot = other.rootAccount;
other.rootAccount = rootAccount;
rootAccount = otherRoot;
boolean otherDirty = other.dirty;
other.dirty = dirty;
dirty = otherDirty;
HashMap<String, String> otherGlobalSettings = other.globalSettings;
other.globalSettings = globalSettings;
globalSettings = otherGlobalSettings;
} | java | public void swapAccounts(Database other) {
Account otherRoot = other.rootAccount;
other.rootAccount = rootAccount;
rootAccount = otherRoot;
boolean otherDirty = other.dirty;
other.dirty = dirty;
dirty = otherDirty;
HashMap<String, String> otherGlobalSettings = other.globalSettings;
other.globalSettings = globalSettings;
globalSettings = otherGlobalSettings;
} | [
"public",
"void",
"swapAccounts",
"(",
"Database",
"other",
")",
"{",
"Account",
"otherRoot",
"=",
"other",
".",
"rootAccount",
";",
"other",
".",
"rootAccount",
"=",
"rootAccount",
";",
"rootAccount",
"=",
"otherRoot",
";",
"boolean",
"otherDirty",
"=",
"othe... | Is is so that the after an database is loaded, we can reuse this object
This does not swap listeners.
@param other - the other database to swap with | [
"Is",
"is",
"so",
"that",
"the",
"after",
"an",
"database",
"is",
"loaded",
"we",
"can",
"reuse",
"this",
"object",
"This",
"does",
"not",
"swap",
"listeners",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L66-L76 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Database.java | Database.addAccount | public void addAccount(Account parent, Account child)
throws Exception {
// Check to see if the account physically already exists - there is something funny with
// some Firefox RDF exports where an RDF:li node gets duplicated multiple times.
for (Account dup : parent.getChildren()) {
if (dup == child) {
logger.warning("Duplicate RDF:li=" + child.getId() + " detected. Dropping duplicate");
return;
}
}
int iterationCount = 0;
final int maxIteration = 0x100000; // if we can't find a hash in 1 million iterations, something is wrong
while (findAccountById(child.getId()) != null && (iterationCount++ < maxIteration)) {
logger.warning("ID collision detected on '" + child.getId() + "', attempting to regenerate ID. iteration=" + iterationCount);
child.setId(Account.createId(child));
}
if (iterationCount >= maxIteration) {
throw new Exception("Could not genererate a unique ID in " + iterationCount + " iterations, this is really rare. I know it's lame, but change the description and try again.");
}
// add to new parent
parent.getChildren().add(child);
sendAccountAdded(parent, child);
setDirty(true);
} | java | public void addAccount(Account parent, Account child)
throws Exception {
// Check to see if the account physically already exists - there is something funny with
// some Firefox RDF exports where an RDF:li node gets duplicated multiple times.
for (Account dup : parent.getChildren()) {
if (dup == child) {
logger.warning("Duplicate RDF:li=" + child.getId() + " detected. Dropping duplicate");
return;
}
}
int iterationCount = 0;
final int maxIteration = 0x100000; // if we can't find a hash in 1 million iterations, something is wrong
while (findAccountById(child.getId()) != null && (iterationCount++ < maxIteration)) {
logger.warning("ID collision detected on '" + child.getId() + "', attempting to regenerate ID. iteration=" + iterationCount);
child.setId(Account.createId(child));
}
if (iterationCount >= maxIteration) {
throw new Exception("Could not genererate a unique ID in " + iterationCount + " iterations, this is really rare. I know it's lame, but change the description and try again.");
}
// add to new parent
parent.getChildren().add(child);
sendAccountAdded(parent, child);
setDirty(true);
} | [
"public",
"void",
"addAccount",
"(",
"Account",
"parent",
",",
"Account",
"child",
")",
"throws",
"Exception",
"{",
"// Check to see if the account physically already exists - there is something funny with",
"// some Firefox RDF exports where an RDF:li node gets duplicated multiple times... | Adds an account to a parent. This will first check to see if the account
already has a parent and if so remove it from that parent before adding it
to the new parent.
@param parent The parent to add the child under.
@param child The child to add.
@throws Exception On error. | [
"Adds",
"an",
"account",
"to",
"a",
"parent",
".",
"This",
"will",
"first",
"check",
"to",
"see",
"if",
"the",
"account",
"already",
"has",
"a",
"parent",
"and",
"if",
"so",
"remove",
"it",
"from",
"that",
"parent",
"before",
"adding",
"it",
"to",
"the... | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L87-L113 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Database.java | Database.removeAccount | public void removeAccount(Account accountToDelete) {
// Thou shalt not delete root
if (accountToDelete.getId().equals(rootAccount.getId()))
return;
Account parent = findParent(accountToDelete);
if (parent != null) {
removeAccount(parent, accountToDelete);
setDirty(true);
}
} | java | public void removeAccount(Account accountToDelete) {
// Thou shalt not delete root
if (accountToDelete.getId().equals(rootAccount.getId()))
return;
Account parent = findParent(accountToDelete);
if (parent != null) {
removeAccount(parent, accountToDelete);
setDirty(true);
}
} | [
"public",
"void",
"removeAccount",
"(",
"Account",
"accountToDelete",
")",
"{",
"// Thou shalt not delete root",
"if",
"(",
"accountToDelete",
".",
"getId",
"(",
")",
".",
"equals",
"(",
"rootAccount",
".",
"getId",
"(",
")",
")",
")",
"return",
";",
"Account"... | Removes an account from a parent account.
@param accountToDelete Duh. | [
"Removes",
"an",
"account",
"from",
"a",
"parent",
"account",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L133-L143 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Database.java | Database.removeAccount | private void removeAccount(Account parent, Account child) {
parent.getChildren().remove(child);
sendAccountRemoved(parent, child);
} | java | private void removeAccount(Account parent, Account child) {
parent.getChildren().remove(child);
sendAccountRemoved(parent, child);
} | [
"private",
"void",
"removeAccount",
"(",
"Account",
"parent",
",",
"Account",
"child",
")",
"{",
"parent",
".",
"getChildren",
"(",
")",
".",
"remove",
"(",
"child",
")",
";",
"sendAccountRemoved",
"(",
"parent",
",",
"child",
")",
";",
"}"
] | Internal routine to remove a child from a parent.
Notifies the listeners of the removal
@param parent - The parent to remove the child from
@param child - The child to remove from parent | [
"Internal",
"routine",
"to",
"remove",
"a",
"child",
"from",
"a",
"parent",
".",
"Notifies",
"the",
"listeners",
"of",
"the",
"removal"
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L152-L155 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Database.java | Database.setGlobalSetting | public void setGlobalSetting(String name, String value) {
String oldValue;
// Avoid redundant setting
if (globalSettings.containsKey(name)) {
oldValue = globalSettings.get(name);
if (value.compareTo(oldValue) == 0)
return;
}
globalSettings.put(name, value);
setDirty(true);
} | java | public void setGlobalSetting(String name, String value) {
String oldValue;
// Avoid redundant setting
if (globalSettings.containsKey(name)) {
oldValue = globalSettings.get(name);
if (value.compareTo(oldValue) == 0)
return;
}
globalSettings.put(name, value);
setDirty(true);
} | [
"public",
"void",
"setGlobalSetting",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"String",
"oldValue",
";",
"// Avoid redundant setting",
"if",
"(",
"globalSettings",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"oldValue",
"=",
"globalSettings"... | Sets a firefox global setting. This allows any name and should be avoided. It
is used by the RDF reader.
@param name The name of the setting.
@param value The value. | [
"Sets",
"a",
"firefox",
"global",
"setting",
".",
"This",
"allows",
"any",
"name",
"and",
"should",
"be",
"avoided",
".",
"It",
"is",
"used",
"by",
"the",
"RDF",
"reader",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L170-L181 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Database.java | Database.getGlobalSetting | public String getGlobalSetting(GlobalSettingKey key) {
if (globalSettings.containsKey(key.toString()))
return globalSettings.get(key.toString());
return key.getDefault();
} | java | public String getGlobalSetting(GlobalSettingKey key) {
if (globalSettings.containsKey(key.toString()))
return globalSettings.get(key.toString());
return key.getDefault();
} | [
"public",
"String",
"getGlobalSetting",
"(",
"GlobalSettingKey",
"key",
")",
"{",
"if",
"(",
"globalSettings",
".",
"containsKey",
"(",
"key",
".",
"toString",
"(",
")",
")",
")",
"return",
"globalSettings",
".",
"get",
"(",
"key",
".",
"toString",
"(",
")... | The preferred way of getting a global setting value.
@param key The key to obtain.
@return the setting obtained | [
"The",
"preferred",
"way",
"of",
"getting",
"a",
"global",
"setting",
"value",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L208-L212 | train |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Database.java | Database.printDatabase | private void printDatabase(Account acc, int level, PrintStream stream) {
String buf = "";
for (int i = 0; i < level; i++)
buf += " ";
buf += "+";
buf += acc.getName() + "[" + acc.getUrl() + "] (" + acc.getPatterns().size() + " patterns)";
stream.println(buf);
for (Account account : acc.getChildren())
printDatabase(account, level + 2, stream);
}
public List<Account> findPathToAccountById(String id) {
LinkedList<Account> result = getRootInLinkedList();
findAccountById(result, id);
// reverse the list, so that its,<root> -> parent -> ... -> Found Account
List<Account> retValue = new ArrayList<Account>(result.size());
Iterator<Account> iter = result.descendingIterator();
while (iter.hasNext()) retValue.add(iter.next());
return retValue;
}
public List<Account> getAllAccounts() {
Set<Account> acc = new HashSet<Account>();
getAllAccounts(getRootAccount(), acc);
List<Account> sorted = new ArrayList<Account>(acc);
Collections.sort(sorted, new Comparator<Account>() {
@Override
public int compare(Account o1, Account o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
});
return sorted;
}
private void getAllAccounts(Account base, Collection<Account> into) {
for (Account c : base.getChildren()) {
if ( c.hasChildren() ) {
getAllAccounts(c, into);
} else {
into.add(c);
}
}
}
/**
* Locates an account, given an id.
*
* @param id The account id (unique hash).
* @return The account if found, else null.
*/
public Account findAccountById(String id) {
return findAccountById(getRootInLinkedList(), id);
}
/**
* Internal function to recurse through accounts looking for an id.
*
* @param stack The path to the current parent
* @param id The id to look for.
* @return The Account if found, else null.
*/
private Account findAccountById(LinkedList<Account> stack, String id) {
final Account parent = stack.peek();
if (parent == null) {
if ( ! stack.isEmpty() ) stack.pop();
return null;
}
for (Account child : parent.getChildren()) {
if (child.getId().equals(id)) {
stack.push(child);
return child;
}
if (child.getChildren().size() > 0) {
stack.push(child);
Account foundAccount = findAccountById(stack, id);
if (foundAccount != null)
return foundAccount;
}
}
stack.pop();
return null;
}
private LinkedList<Account> getRootInLinkedList() {
LinkedList<Account> stack = new LinkedList<Account>();
stack.add(rootAccount);
return stack;
}
/**
* Searches the database for any account with a matching URL.
*
* @param url The regex to search with.
* @return The account if found, else null.
*/
public Account findAccountByUrl(String url) {
return findAccountByUrl(rootAccount, url);
}
/**
* Internal function to aid in searching. This will find the first account in the tree starting at parent
* that matches the url given.
*
* @param parent - The parent to start searching with.
* @param url - Url to search for
* @return the matching account (maybe the parent), or Null if no matching account was found.
*/
private Account findAccountByUrl(Account parent, String url) {
// First search the parent
if (AccountPatternMatcher.matchUrl(parent, url) && !parent.isRoot())
return parent;
for (Account child : parent.getChildren()) {
Account foundAccount = findAccountByUrl(child, url);
if (foundAccount != null)
return foundAccount;
}
return null;
} | java | private void printDatabase(Account acc, int level, PrintStream stream) {
String buf = "";
for (int i = 0; i < level; i++)
buf += " ";
buf += "+";
buf += acc.getName() + "[" + acc.getUrl() + "] (" + acc.getPatterns().size() + " patterns)";
stream.println(buf);
for (Account account : acc.getChildren())
printDatabase(account, level + 2, stream);
}
public List<Account> findPathToAccountById(String id) {
LinkedList<Account> result = getRootInLinkedList();
findAccountById(result, id);
// reverse the list, so that its,<root> -> parent -> ... -> Found Account
List<Account> retValue = new ArrayList<Account>(result.size());
Iterator<Account> iter = result.descendingIterator();
while (iter.hasNext()) retValue.add(iter.next());
return retValue;
}
public List<Account> getAllAccounts() {
Set<Account> acc = new HashSet<Account>();
getAllAccounts(getRootAccount(), acc);
List<Account> sorted = new ArrayList<Account>(acc);
Collections.sort(sorted, new Comparator<Account>() {
@Override
public int compare(Account o1, Account o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
});
return sorted;
}
private void getAllAccounts(Account base, Collection<Account> into) {
for (Account c : base.getChildren()) {
if ( c.hasChildren() ) {
getAllAccounts(c, into);
} else {
into.add(c);
}
}
}
/**
* Locates an account, given an id.
*
* @param id The account id (unique hash).
* @return The account if found, else null.
*/
public Account findAccountById(String id) {
return findAccountById(getRootInLinkedList(), id);
}
/**
* Internal function to recurse through accounts looking for an id.
*
* @param stack The path to the current parent
* @param id The id to look for.
* @return The Account if found, else null.
*/
private Account findAccountById(LinkedList<Account> stack, String id) {
final Account parent = stack.peek();
if (parent == null) {
if ( ! stack.isEmpty() ) stack.pop();
return null;
}
for (Account child : parent.getChildren()) {
if (child.getId().equals(id)) {
stack.push(child);
return child;
}
if (child.getChildren().size() > 0) {
stack.push(child);
Account foundAccount = findAccountById(stack, id);
if (foundAccount != null)
return foundAccount;
}
}
stack.pop();
return null;
}
private LinkedList<Account> getRootInLinkedList() {
LinkedList<Account> stack = new LinkedList<Account>();
stack.add(rootAccount);
return stack;
}
/**
* Searches the database for any account with a matching URL.
*
* @param url The regex to search with.
* @return The account if found, else null.
*/
public Account findAccountByUrl(String url) {
return findAccountByUrl(rootAccount, url);
}
/**
* Internal function to aid in searching. This will find the first account in the tree starting at parent
* that matches the url given.
*
* @param parent - The parent to start searching with.
* @param url - Url to search for
* @return the matching account (maybe the parent), or Null if no matching account was found.
*/
private Account findAccountByUrl(Account parent, String url) {
// First search the parent
if (AccountPatternMatcher.matchUrl(parent, url) && !parent.isRoot())
return parent;
for (Account child : parent.getChildren()) {
Account foundAccount = findAccountByUrl(child, url);
if (foundAccount != null)
return foundAccount;
}
return null;
} | [
"private",
"void",
"printDatabase",
"(",
"Account",
"acc",
",",
"int",
"level",
",",
"PrintStream",
"stream",
")",
"{",
"String",
"buf",
"=",
"\"\"",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"level",
";",
"i",
"++",
")",
"buf",
"+=",
... | Gooey recursiveness. | [
"Gooey",
"recursiveness",
"."
] | 18c22fca7dd9a47f08161425b85a5bd257afbb2b | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L302-L424 | train |
jcuda/jcurand | JCurandJava/src/main/java/jcuda/jcurand/JCurand.java | JCurand.checkResult | private static int checkResult(int result)
{
if (exceptionsEnabled && result != curandStatus.CURAND_STATUS_SUCCESS)
{
throw new CudaException(curandStatus.stringFor(result));
}
return result;
} | java | private static int checkResult(int result)
{
if (exceptionsEnabled && result != curandStatus.CURAND_STATUS_SUCCESS)
{
throw new CudaException(curandStatus.stringFor(result));
}
return result;
} | [
"private",
"static",
"int",
"checkResult",
"(",
"int",
"result",
")",
"{",
"if",
"(",
"exceptionsEnabled",
"&&",
"result",
"!=",
"curandStatus",
".",
"CURAND_STATUS_SUCCESS",
")",
"{",
"throw",
"new",
"CudaException",
"(",
"curandStatus",
".",
"stringFor",
"(",
... | If the given result is not curandStatus.CURAND_STATUS_SUCCESS
and exceptions have been enabled, this method will throw a
CudaException with an error message that corresponds to the
given result code. Otherwise, the given result is simply
returned.
@param result The result to check
@return The result that was given as the parameter
@throws CudaException If exceptions have been enabled and
the given result code is not curandStatus.CURAND_STATUS_SUCCESS | [
"If",
"the",
"given",
"result",
"is",
"not",
"curandStatus",
".",
"CURAND_STATUS_SUCCESS",
"and",
"exceptions",
"have",
"been",
"enabled",
"this",
"method",
"will",
"throw",
"a",
"CudaException",
"with",
"an",
"error",
"message",
"that",
"corresponds",
"to",
"th... | 0f463d2bb72cd93b3988f7ce148cdb6069ba4fd9 | https://github.com/jcuda/jcurand/blob/0f463d2bb72cd93b3988f7ce148cdb6069ba4fd9/JCurandJava/src/main/java/jcuda/jcurand/JCurand.java#L129-L136 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.nameArgument | public final void nameArgument(String name, int index)
{
VariableElement lv = getLocalVariable(index);
if (lv instanceof UpdateableElement)
{
UpdateableElement ue = (UpdateableElement) lv;
ue.setSimpleName(El.getName(name));
}
else
{
throw new IllegalArgumentException("local variable at index "+index+" cannot be named");
}
} | java | public final void nameArgument(String name, int index)
{
VariableElement lv = getLocalVariable(index);
if (lv instanceof UpdateableElement)
{
UpdateableElement ue = (UpdateableElement) lv;
ue.setSimpleName(El.getName(name));
}
else
{
throw new IllegalArgumentException("local variable at index "+index+" cannot be named");
}
} | [
"public",
"final",
"void",
"nameArgument",
"(",
"String",
"name",
",",
"int",
"index",
")",
"{",
"VariableElement",
"lv",
"=",
"getLocalVariable",
"(",
"index",
")",
";",
"if",
"(",
"lv",
"instanceof",
"UpdateableElement",
")",
"{",
"UpdateableElement",
"ue",
... | Names an argument
@param name Argument name
@param index First argument is 1, this = 0 | [
"Names",
"an",
"argument"
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L178-L190 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.getLocalVariable | public VariableElement getLocalVariable(int index)
{
int idx = 0;
for (VariableElement lv : localVariables)
{
if (idx == index)
{
return lv;
}
if (Typ.isCategory2(lv.asType()))
{
idx += 2;
}
else
{
idx++;
}
}
throw new IllegalArgumentException("local variable at index "+index+" not found");
} | java | public VariableElement getLocalVariable(int index)
{
int idx = 0;
for (VariableElement lv : localVariables)
{
if (idx == index)
{
return lv;
}
if (Typ.isCategory2(lv.asType()))
{
idx += 2;
}
else
{
idx++;
}
}
throw new IllegalArgumentException("local variable at index "+index+" not found");
} | [
"public",
"VariableElement",
"getLocalVariable",
"(",
"int",
"index",
")",
"{",
"int",
"idx",
"=",
"0",
";",
"for",
"(",
"VariableElement",
"lv",
":",
"localVariables",
")",
"{",
"if",
"(",
"idx",
"==",
"index",
")",
"{",
"return",
"lv",
";",
"}",
"if"... | Returns local variable at index. Note! long and double take two positions.
@param index
@return | [
"Returns",
"local",
"variable",
"at",
"index",
".",
"Note!",
"long",
"and",
"double",
"take",
"two",
"positions",
"."
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L196-L215 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.getLocalName | public String getLocalName(int index)
{
VariableElement lv = getLocalVariable(index);
return lv.getSimpleName().toString();
} | java | public String getLocalName(int index)
{
VariableElement lv = getLocalVariable(index);
return lv.getSimpleName().toString();
} | [
"public",
"String",
"getLocalName",
"(",
"int",
"index",
")",
"{",
"VariableElement",
"lv",
"=",
"getLocalVariable",
"(",
"index",
")",
";",
"return",
"lv",
".",
"getSimpleName",
"(",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Returns the name of local variable at index
@param index
@return | [
"Returns",
"the",
"name",
"of",
"local",
"variable",
"at",
"index"
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L260-L264 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.getLocalType | public TypeMirror getLocalType(String name)
{
VariableElement lv = getLocalVariable(name);
return lv.asType();
} | java | public TypeMirror getLocalType(String name)
{
VariableElement lv = getLocalVariable(name);
return lv.asType();
} | [
"public",
"TypeMirror",
"getLocalType",
"(",
"String",
"name",
")",
"{",
"VariableElement",
"lv",
"=",
"getLocalVariable",
"(",
"name",
")",
";",
"return",
"lv",
".",
"asType",
"(",
")",
";",
"}"
] | returns the type of local variable named name.
@param name
@return | [
"returns",
"the",
"type",
"of",
"local",
"variable",
"named",
"name",
"."
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L280-L284 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.getLocalDescription | public String getLocalDescription(int index)
{
StringWriter sw = new StringWriter();
El.printElements(sw, getLocalVariable(index));
return sw.toString();
} | java | public String getLocalDescription(int index)
{
StringWriter sw = new StringWriter();
El.printElements(sw, getLocalVariable(index));
return sw.toString();
} | [
"public",
"String",
"getLocalDescription",
"(",
"int",
"index",
")",
"{",
"StringWriter",
"sw",
"=",
"new",
"StringWriter",
"(",
")",
";",
"El",
".",
"printElements",
"(",
"sw",
",",
"getLocalVariable",
"(",
"index",
")",
")",
";",
"return",
"sw",
".",
"... | return a descriptive text about local variable named name.
@param index
@return | [
"return",
"a",
"descriptive",
"text",
"about",
"local",
"variable",
"named",
"name",
"."
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L307-L312 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.loadDefault | public void loadDefault(TypeMirror type) throws IOException
{
if (type.getKind() != TypeKind.VOID)
{
if (Typ.isPrimitive(type))
{
tconst(type, 0);
}
else
{
aconst_null();
}
}
} | java | public void loadDefault(TypeMirror type) throws IOException
{
if (type.getKind() != TypeKind.VOID)
{
if (Typ.isPrimitive(type))
{
tconst(type, 0);
}
else
{
aconst_null();
}
}
} | [
"public",
"void",
"loadDefault",
"(",
"TypeMirror",
"type",
")",
"throws",
"IOException",
"{",
"if",
"(",
"type",
".",
"getKind",
"(",
")",
"!=",
"TypeKind",
".",
"VOID",
")",
"{",
"if",
"(",
"Typ",
".",
"isPrimitive",
"(",
"type",
")",
")",
"{",
"tc... | Load default value to stack depending on type
@param type
@throws IOException | [
"Load",
"default",
"value",
"to",
"stack",
"depending",
"on",
"type"
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L385-L398 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.startSubroutine | public void startSubroutine(String target) throws IOException
{
if (subroutine != null)
{
throw new IllegalStateException("subroutine "+subroutine+" not ended when "+target+ "started");
}
subroutine = target;
if (!hasLocalVariable(SUBROUTINERETURNADDRESSNAME))
{
addVariable(SUBROUTINERETURNADDRESSNAME, Typ.ReturnAddress);
}
fixAddress(target);
tstore(SUBROUTINERETURNADDRESSNAME);
} | java | public void startSubroutine(String target) throws IOException
{
if (subroutine != null)
{
throw new IllegalStateException("subroutine "+subroutine+" not ended when "+target+ "started");
}
subroutine = target;
if (!hasLocalVariable(SUBROUTINERETURNADDRESSNAME))
{
addVariable(SUBROUTINERETURNADDRESSNAME, Typ.ReturnAddress);
}
fixAddress(target);
tstore(SUBROUTINERETURNADDRESSNAME);
} | [
"public",
"void",
"startSubroutine",
"(",
"String",
"target",
")",
"throws",
"IOException",
"{",
"if",
"(",
"subroutine",
"!=",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"subroutine \"",
"+",
"subroutine",
"+",
"\" not ended when \"",
"+",
... | Compiles the subroutine start. Use endSubroutine to end that subroutine.
@param target
@throws IOException | [
"Compiles",
"the",
"subroutine",
"start",
".",
"Use",
"endSubroutine",
"to",
"end",
"that",
"subroutine",
"."
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L404-L417 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.typeForCount | public TypeMirror typeForCount(int count)
{
if (count <= Byte.MAX_VALUE)
{
return Typ.Byte;
}
if (count <= Short.MAX_VALUE)
{
return Typ.Short;
}
if (count <= Integer.MAX_VALUE)
{
return Typ.Int;
}
return Typ.Long;
} | java | public TypeMirror typeForCount(int count)
{
if (count <= Byte.MAX_VALUE)
{
return Typ.Byte;
}
if (count <= Short.MAX_VALUE)
{
return Typ.Short;
}
if (count <= Integer.MAX_VALUE)
{
return Typ.Int;
}
return Typ.Long;
} | [
"public",
"TypeMirror",
"typeForCount",
"(",
"int",
"count",
")",
"{",
"if",
"(",
"count",
"<=",
"Byte",
".",
"MAX_VALUE",
")",
"{",
"return",
"Typ",
".",
"Byte",
";",
"}",
"if",
"(",
"count",
"<=",
"Short",
".",
"MAX_VALUE",
")",
"{",
"return",
"Typ... | Return a integral class able to support count values
@param count
@return | [
"Return",
"a",
"integral",
"class",
"able",
"to",
"support",
"count",
"values"
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L506-L521 | train |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.fixAddress | @Override
public void fixAddress(String name) throws IOException
{
super.fixAddress(name);
if (debugMethod != null)
{
int position = position();
tload("this");
ldc(position);
ldc(name);
invokevirtual(debugMethod);
}
} | java | @Override
public void fixAddress(String name) throws IOException
{
super.fixAddress(name);
if (debugMethod != null)
{
int position = position();
tload("this");
ldc(position);
ldc(name);
invokevirtual(debugMethod);
}
} | [
"@",
"Override",
"public",
"void",
"fixAddress",
"(",
"String",
"name",
")",
"throws",
"IOException",
"{",
"super",
".",
"fixAddress",
"(",
"name",
")",
";",
"if",
"(",
"debugMethod",
"!=",
"null",
")",
"{",
"int",
"position",
"=",
"position",
"(",
")",
... | Labels a current position
@param name
@throws IOException | [
"Labels",
"a",
"current",
"position"
] | 4e84e313018d487f1a8cca3952d71bc21e77d16b | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L686-L698 | train |
Teddy-Zhu/SilentGo | framework/src/main/java/com/silentgo/core/route/support/RouteFactory.java | RouteFactory.matchRoute | public Route matchRoute(String url) {
if (hashRoute.containsKey(url)) {
return new Route(hashRoute.get(url).get(0), null);
}
for (RegexRoute route : regexRoute) {
Matcher matcher = route.getPattern().matcher(url);
if (matcher.matches()) {
return new Route(route, matcher);
}
}
return null;
} | java | public Route matchRoute(String url) {
if (hashRoute.containsKey(url)) {
return new Route(hashRoute.get(url).get(0), null);
}
for (RegexRoute route : regexRoute) {
Matcher matcher = route.getPattern().matcher(url);
if (matcher.matches()) {
return new Route(route, matcher);
}
}
return null;
} | [
"public",
"Route",
"matchRoute",
"(",
"String",
"url",
")",
"{",
"if",
"(",
"hashRoute",
".",
"containsKey",
"(",
"url",
")",
")",
"{",
"return",
"new",
"Route",
"(",
"hashRoute",
".",
"get",
"(",
"url",
")",
".",
"get",
"(",
"0",
")",
",",
"null",... | simple match route
@param url
@return
@deprecated | [
"simple",
"match",
"route"
] | 27f58b0cafe56b2eb9fc6993efa9ca2b529661e1 | https://github.com/Teddy-Zhu/SilentGo/blob/27f58b0cafe56b2eb9fc6993efa9ca2b529661e1/framework/src/main/java/com/silentgo/core/route/support/RouteFactory.java#L62-L74 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/model/Element.java | Element.addAttributes | public void addAttributes(List<Attribute> attributes) {
for(Attribute attribute : attributes) {
addAttribute(attribute.getName(), attribute.getValue());
}
} | java | public void addAttributes(List<Attribute> attributes) {
for(Attribute attribute : attributes) {
addAttribute(attribute.getName(), attribute.getValue());
}
} | [
"public",
"void",
"addAttributes",
"(",
"List",
"<",
"Attribute",
">",
"attributes",
")",
"{",
"for",
"(",
"Attribute",
"attribute",
":",
"attributes",
")",
"{",
"addAttribute",
"(",
"attribute",
".",
"getName",
"(",
")",
",",
"attribute",
".",
"getValue",
... | Add element attributes
@param attributes list of {@code Attribute} items | [
"Add",
"element",
"attributes"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/model/Element.java#L93-L97 | train |
btaz/data-util | src/main/java/com/btaz/util/xml/model/Element.java | Element.addAttribute | public void addAttribute(String attributeName, String attributeValue) throws XmlModelException {
String name = attributeName.trim();
String value = attributeValue.trim();
if(attributesMap.containsKey(name)) {
throw new XmlModelException("Duplicate attribute: " + name);
}
attributeNames.add(name);
attributesMap.put(name, new Attribute(name, value));
} | java | public void addAttribute(String attributeName, String attributeValue) throws XmlModelException {
String name = attributeName.trim();
String value = attributeValue.trim();
if(attributesMap.containsKey(name)) {
throw new XmlModelException("Duplicate attribute: " + name);
}
attributeNames.add(name);
attributesMap.put(name, new Attribute(name, value));
} | [
"public",
"void",
"addAttribute",
"(",
"String",
"attributeName",
",",
"String",
"attributeValue",
")",
"throws",
"XmlModelException",
"{",
"String",
"name",
"=",
"attributeName",
".",
"trim",
"(",
")",
";",
"String",
"value",
"=",
"attributeValue",
".",
"trim",... | Add a new element attribute
@param attributeName attribute name
@param attributeValue attribute value
@throws XmlModelException XML model exception | [
"Add",
"a",
"new",
"element",
"attribute"
] | f01de64854c456a88a31ffbe8bac6d605151b496 | https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/xml/model/Element.java#L105-L113 | train |
aehrc/ontology-core | ontology-model/src/main/java/au/csiro/ontology/snomed/refset/rf2/ModuleDependencyRefset.java | ModuleDependencyRefset.tc | private static void tc(Map<M, Set<M>> index) {
final Map<String, Object[]> warnings = new HashMap<>();
for (Entry<M, Set<M>> entry: index.entrySet()) {
final M src = entry.getKey();
final Set<M> dependents = entry.getValue();
final Queue<M> queue = new LinkedList<M>(dependents);
while (!queue.isEmpty()) {
final M key = queue.poll();
if (!index.containsKey(key)) {
continue;
}
for (M addition: index.get(key)) {
if (!dependents.contains(addition)) {
dependents.add(addition);
queue.add(addition);
warnings.put(src + "|" + addition + "|" + key, new Object[] {src, addition, key});
}
}
}
}
for (final Object[] args: warnings.values()) {
StructuredLog.ImpliedTransitiveDependency.warn(log, args);
}
} | java | private static void tc(Map<M, Set<M>> index) {
final Map<String, Object[]> warnings = new HashMap<>();
for (Entry<M, Set<M>> entry: index.entrySet()) {
final M src = entry.getKey();
final Set<M> dependents = entry.getValue();
final Queue<M> queue = new LinkedList<M>(dependents);
while (!queue.isEmpty()) {
final M key = queue.poll();
if (!index.containsKey(key)) {
continue;
}
for (M addition: index.get(key)) {
if (!dependents.contains(addition)) {
dependents.add(addition);
queue.add(addition);
warnings.put(src + "|" + addition + "|" + key, new Object[] {src, addition, key});
}
}
}
}
for (final Object[] args: warnings.values()) {
StructuredLog.ImpliedTransitiveDependency.warn(log, args);
}
} | [
"private",
"static",
"void",
"tc",
"(",
"Map",
"<",
"M",
",",
"Set",
"<",
"M",
">",
">",
"index",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Object",
"[",
"]",
">",
"warnings",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"for",
"(",
"Entry"... | Compute the transitive closure of the dependencies
@param index | [
"Compute",
"the",
"transitive",
"closure",
"of",
"the",
"dependencies"
] | 446aa691119f2bbcb8d184566084b8da7a07a44e | https://github.com/aehrc/ontology-core/blob/446aa691119f2bbcb8d184566084b8da7a07a44e/ontology-model/src/main/java/au/csiro/ontology/snomed/refset/rf2/ModuleDependencyRefset.java#L185-L212 | train |
99soft/lifegycle | src/main/java/org/nnsoft/guice/lifegycle/AbstractMethodTypeListener.java | AbstractMethodTypeListener.hear | private <I> void hear( Class<? super I> type, TypeEncounter<I> encounter )
{
if ( type == null || type.getPackage().getName().startsWith( JAVA_PACKAGE ) )
{
return;
}
for ( Method method : type.getDeclaredMethods() )
{
if ( method.isAnnotationPresent( annotationType ) )
{
if ( method.getParameterTypes().length != 0 )
{
encounter.addError( "Annotated methods with @%s must not accept any argument, found %s",
annotationType.getName(), method );
}
hear( method, encounter );
}
}
hear( type.getSuperclass(), encounter );
} | java | private <I> void hear( Class<? super I> type, TypeEncounter<I> encounter )
{
if ( type == null || type.getPackage().getName().startsWith( JAVA_PACKAGE ) )
{
return;
}
for ( Method method : type.getDeclaredMethods() )
{
if ( method.isAnnotationPresent( annotationType ) )
{
if ( method.getParameterTypes().length != 0 )
{
encounter.addError( "Annotated methods with @%s must not accept any argument, found %s",
annotationType.getName(), method );
}
hear( method, encounter );
}
}
hear( type.getSuperclass(), encounter );
} | [
"private",
"<",
"I",
">",
"void",
"hear",
"(",
"Class",
"<",
"?",
"super",
"I",
">",
"type",
",",
"TypeEncounter",
"<",
"I",
">",
"encounter",
")",
"{",
"if",
"(",
"type",
"==",
"null",
"||",
"type",
".",
"getPackage",
"(",
")",
".",
"getName",
"... | Allows traverse the input type hierarchy.
@param type encountered by Guice.
@param encounter the injection context. | [
"Allows",
"traverse",
"the",
"input",
"type",
"hierarchy",
"."
] | 0adde20bcf32e90fe995bb493630b77fa6ce6361 | https://github.com/99soft/lifegycle/blob/0adde20bcf32e90fe995bb493630b77fa6ce6361/src/main/java/org/nnsoft/guice/lifegycle/AbstractMethodTypeListener.java#L67-L89 | train |
brianwhu/xillium | data/src/main/java/org/xillium/data/persistence/xml/ResultSetStreamer.java | ResultSetStreamer.require | public ResultSetStreamer require(String column, Assertion assertion) {
if (_requires == Collections.EMPTY_MAP) _requires = new HashMap<String, Assertion>();
_requires.put(column, assertion);
return this;
} | java | public ResultSetStreamer require(String column, Assertion assertion) {
if (_requires == Collections.EMPTY_MAP) _requires = new HashMap<String, Assertion>();
_requires.put(column, assertion);
return this;
} | [
"public",
"ResultSetStreamer",
"require",
"(",
"String",
"column",
",",
"Assertion",
"assertion",
")",
"{",
"if",
"(",
"_requires",
"==",
"Collections",
".",
"EMPTY_MAP",
")",
"_requires",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Assertion",
">",
"(",
")"... | Requires a data column to satisfy an assertion. | [
"Requires",
"a",
"data",
"column",
"to",
"satisfy",
"an",
"assertion",
"."
] | e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799 | https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/data/src/main/java/org/xillium/data/persistence/xml/ResultSetStreamer.java#L71-L75 | train |
brianwhu/xillium | data/src/main/java/org/xillium/data/persistence/xml/ResultSetStreamer.java | ResultSetStreamer.exclude | public ResultSetStreamer exclude(String column, Assertion assertion) {
if (_excludes == Collections.EMPTY_MAP) _excludes = new HashMap<String, Assertion>();
_excludes.put(column, assertion);
return this;
} | java | public ResultSetStreamer exclude(String column, Assertion assertion) {
if (_excludes == Collections.EMPTY_MAP) _excludes = new HashMap<String, Assertion>();
_excludes.put(column, assertion);
return this;
} | [
"public",
"ResultSetStreamer",
"exclude",
"(",
"String",
"column",
",",
"Assertion",
"assertion",
")",
"{",
"if",
"(",
"_excludes",
"==",
"Collections",
".",
"EMPTY_MAP",
")",
"_excludes",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Assertion",
">",
"(",
")"... | Excludes rows whose data columns satisfy an assertion. | [
"Excludes",
"rows",
"whose",
"data",
"columns",
"satisfy",
"an",
"assertion",
"."
] | e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799 | https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/data/src/main/java/org/xillium/data/persistence/xml/ResultSetStreamer.java#L80-L84 | train |
seedstack/shed | src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java | ExecutablePredicates.executableIsSynthetic | public static <T extends Executable> Predicate<T> executableIsSynthetic() {
return candidate -> candidate != null && candidate.isSynthetic();
} | java | public static <T extends Executable> Predicate<T> executableIsSynthetic() {
return candidate -> candidate != null && candidate.isSynthetic();
} | [
"public",
"static",
"<",
"T",
"extends",
"Executable",
">",
"Predicate",
"<",
"T",
">",
"executableIsSynthetic",
"(",
")",
"{",
"return",
"candidate",
"->",
"candidate",
"!=",
"null",
"&&",
"candidate",
".",
"isSynthetic",
"(",
")",
";",
"}"
] | Checks if a candidate executable is synthetic.
@return the predicate. | [
"Checks",
"if",
"a",
"candidate",
"executable",
"is",
"synthetic",
"."
] | 49ecb25aa3777539ab0f29f89abaae5ee93b572e | https://github.com/seedstack/shed/blob/49ecb25aa3777539ab0f29f89abaae5ee93b572e/src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java#L25-L27 | train |
seedstack/shed | src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java | ExecutablePredicates.executableBelongsToClass | public static <T extends Executable> Predicate<T> executableBelongsToClass(Class<?> reference) {
return candidate -> candidate != null && reference.equals(candidate.getDeclaringClass());
} | java | public static <T extends Executable> Predicate<T> executableBelongsToClass(Class<?> reference) {
return candidate -> candidate != null && reference.equals(candidate.getDeclaringClass());
} | [
"public",
"static",
"<",
"T",
"extends",
"Executable",
">",
"Predicate",
"<",
"T",
">",
"executableBelongsToClass",
"(",
"Class",
"<",
"?",
">",
"reference",
")",
"{",
"return",
"candidate",
"->",
"candidate",
"!=",
"null",
"&&",
"reference",
".",
"equals",
... | Checks if a candidate executable does belong to the specified class.
@param reference the class to check against.
@return the predicate. | [
"Checks",
"if",
"a",
"candidate",
"executable",
"does",
"belong",
"to",
"the",
"specified",
"class",
"."
] | 49ecb25aa3777539ab0f29f89abaae5ee93b572e | https://github.com/seedstack/shed/blob/49ecb25aa3777539ab0f29f89abaae5ee93b572e/src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java#L35-L37 | train |
seedstack/shed | src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java | ExecutablePredicates.executableBelongsToClassAssignableTo | public static <T extends Executable> Predicate<T> executableBelongsToClassAssignableTo(Class<?> reference) {
return candidate -> candidate != null && reference.isAssignableFrom(candidate.getDeclaringClass());
} | java | public static <T extends Executable> Predicate<T> executableBelongsToClassAssignableTo(Class<?> reference) {
return candidate -> candidate != null && reference.isAssignableFrom(candidate.getDeclaringClass());
} | [
"public",
"static",
"<",
"T",
"extends",
"Executable",
">",
"Predicate",
"<",
"T",
">",
"executableBelongsToClassAssignableTo",
"(",
"Class",
"<",
"?",
">",
"reference",
")",
"{",
"return",
"candidate",
"->",
"candidate",
"!=",
"null",
"&&",
"reference",
".",
... | Checks if a candidate executable does belong to a class assignable as the specified class.
@param reference the class to check against.
@return the predicate. | [
"Checks",
"if",
"a",
"candidate",
"executable",
"does",
"belong",
"to",
"a",
"class",
"assignable",
"as",
"the",
"specified",
"class",
"."
] | 49ecb25aa3777539ab0f29f89abaae5ee93b572e | https://github.com/seedstack/shed/blob/49ecb25aa3777539ab0f29f89abaae5ee93b572e/src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java#L45-L47 | train |
seedstack/shed | src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java | ExecutablePredicates.executableIsEquivalentTo | public static <T extends Executable> Predicate<T> executableIsEquivalentTo(T reference) {
Predicate<T> predicate = candidate -> candidate != null
&& candidate.getName().equals(reference.getName())
&& executableHasSameParameterTypesAs(reference).test(candidate);
if (reference instanceof Method) {
predicate.and(candidate -> candidate instanceof Method && ((Method) candidate).getReturnType()
.equals(((Method) reference).getReturnType()));
}
return predicate;
} | java | public static <T extends Executable> Predicate<T> executableIsEquivalentTo(T reference) {
Predicate<T> predicate = candidate -> candidate != null
&& candidate.getName().equals(reference.getName())
&& executableHasSameParameterTypesAs(reference).test(candidate);
if (reference instanceof Method) {
predicate.and(candidate -> candidate instanceof Method && ((Method) candidate).getReturnType()
.equals(((Method) reference).getReturnType()));
}
return predicate;
} | [
"public",
"static",
"<",
"T",
"extends",
"Executable",
">",
"Predicate",
"<",
"T",
">",
"executableIsEquivalentTo",
"(",
"T",
"reference",
")",
"{",
"Predicate",
"<",
"T",
">",
"predicate",
"=",
"candidate",
"->",
"candidate",
"!=",
"null",
"&&",
"candidate"... | Checks if a candidate executable is equivalent to the specified reference executable.
@param reference the executable to check equivalency against.
@return the predicate. | [
"Checks",
"if",
"a",
"candidate",
"executable",
"is",
"equivalent",
"to",
"the",
"specified",
"reference",
"executable",
"."
] | 49ecb25aa3777539ab0f29f89abaae5ee93b572e | https://github.com/seedstack/shed/blob/49ecb25aa3777539ab0f29f89abaae5ee93b572e/src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java#L55-L64 | train |
seedstack/shed | src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java | ExecutablePredicates.executableHasSameParameterTypesAs | public static <T extends Executable> Predicate<T> executableHasSameParameterTypesAs(T reference) {
return candidate -> {
if (candidate == null) {
return false;
}
Class<?>[] candidateParameterTypes = candidate.getParameterTypes();
Class<?>[] referenceParameterTypes = reference.getParameterTypes();
if (candidateParameterTypes.length != referenceParameterTypes.length) {
return false;
}
for (int i = 0; i < candidateParameterTypes.length; i++) {
if (!candidateParameterTypes[i].equals(referenceParameterTypes[i])) {
return false;
}
}
return true;
};
} | java | public static <T extends Executable> Predicate<T> executableHasSameParameterTypesAs(T reference) {
return candidate -> {
if (candidate == null) {
return false;
}
Class<?>[] candidateParameterTypes = candidate.getParameterTypes();
Class<?>[] referenceParameterTypes = reference.getParameterTypes();
if (candidateParameterTypes.length != referenceParameterTypes.length) {
return false;
}
for (int i = 0; i < candidateParameterTypes.length; i++) {
if (!candidateParameterTypes[i].equals(referenceParameterTypes[i])) {
return false;
}
}
return true;
};
} | [
"public",
"static",
"<",
"T",
"extends",
"Executable",
">",
"Predicate",
"<",
"T",
">",
"executableHasSameParameterTypesAs",
"(",
"T",
"reference",
")",
"{",
"return",
"candidate",
"->",
"{",
"if",
"(",
"candidate",
"==",
"null",
")",
"{",
"return",
"false",... | Checks if a candidate executable has the same parameter type as the specified reference
executable.
@param reference the executable to check parameters against.
@return the predicate. | [
"Checks",
"if",
"a",
"candidate",
"executable",
"has",
"the",
"same",
"parameter",
"type",
"as",
"the",
"specified",
"reference",
"executable",
"."
] | 49ecb25aa3777539ab0f29f89abaae5ee93b572e | https://github.com/seedstack/shed/blob/49ecb25aa3777539ab0f29f89abaae5ee93b572e/src/main/java/org/seedstack/shed/reflect/ExecutablePredicates.java#L73-L90 | train |
theHilikus/JRoboCom | jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/robot/Robot.java | Robot.run | @Override
public void run() {
try {
try {
turnsControl.waitTurns(1, "Robot starting"); // block at the beginning so that all
// robots start at the
// same time
} catch (BankInterruptedException exc) {
log.trace("[run] Interrupted before starting");
}
assert getData().isEnabled() : "Robot is disabled";
mainLoop();
log.debug("[run] Robot terminated gracefully");
} catch (Exception | Error all) {
log.error("[run] Problem running robot " + this, all);
die("Execution Error -- " + all);
}
} | java | @Override
public void run() {
try {
try {
turnsControl.waitTurns(1, "Robot starting"); // block at the beginning so that all
// robots start at the
// same time
} catch (BankInterruptedException exc) {
log.trace("[run] Interrupted before starting");
}
assert getData().isEnabled() : "Robot is disabled";
mainLoop();
log.debug("[run] Robot terminated gracefully");
} catch (Exception | Error all) {
log.error("[run] Problem running robot " + this, all);
die("Execution Error -- " + all);
}
} | [
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"try",
"{",
"turnsControl",
".",
"waitTurns",
"(",
"1",
",",
"\"Robot starting\"",
")",
";",
"// block at the beginning so that all",
"// robots start at the",
"// same time",
"}",
"catch",
"(",
... | The main loop of the robot | [
"The",
"main",
"loop",
"of",
"the",
"robot"
] | 0e31c1ecf1006e35f68c229ff66c37640effffac | https://github.com/theHilikus/JRoboCom/blob/0e31c1ecf1006e35f68c229ff66c37640effffac/jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/robot/Robot.java#L201-L221 | train |
theHilikus/JRoboCom | jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/robot/Robot.java | Robot.die | @Override
public void die(String reason) {
log.info("[die] Robot {} died with reason: {}", serialNumber, reason);
if (alive) { // if not alive it means it was killed at creation
alive = false;
interrupted = true; // to speed up death
world.remove(Robot.this);
}
} | java | @Override
public void die(String reason) {
log.info("[die] Robot {} died with reason: {}", serialNumber, reason);
if (alive) { // if not alive it means it was killed at creation
alive = false;
interrupted = true; // to speed up death
world.remove(Robot.this);
}
} | [
"@",
"Override",
"public",
"void",
"die",
"(",
"String",
"reason",
")",
"{",
"log",
".",
"info",
"(",
"\"[die] Robot {} died with reason: {}\"",
",",
"serialNumber",
",",
"reason",
")",
";",
"if",
"(",
"alive",
")",
"{",
"// if not alive it means it was killed at ... | Kills the robot and removes it from the board
@param reason user-friendly explanation for the death | [
"Kills",
"the",
"robot",
"and",
"removes",
"it",
"from",
"the",
"board"
] | 0e31c1ecf1006e35f68c229ff66c37640effffac | https://github.com/theHilikus/JRoboCom/blob/0e31c1ecf1006e35f68c229ff66c37640effffac/jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/robot/Robot.java#L295-L304 | train |
pierre/serialization | hadoop/src/main/java/com/ning/metrics/serialization/hadoop/SmileInputFormat.java | SmileInputFormat.listStatus | protected List<FileStatus> listStatus(JobContext job) throws IOException
{
List<FileStatus> result = new ArrayList<FileStatus>();
Path[] dirs = getInputPaths(job);
if (dirs.length == 0) {
throw new IOException("No input paths specified in job");
}
// Get tokens for all the required FileSystems..
TokenCache.obtainTokensForNamenodes(job.getCredentials(), dirs, job.getConfiguration());
List<IOException> errors = new ArrayList<IOException>();
for (Path p : dirs) {
FileSystem fs = p.getFileSystem(job.getConfiguration());
final SmilePathFilter filter = new SmilePathFilter();
FileStatus[] matches = fs.globStatus(p, filter);
if (matches == null) {
errors.add(new IOException("Input path does not exist: " + p));
}
else if (matches.length == 0) {
errors.add(new IOException("Input Pattern " + p + " matches 0 files"));
}
else {
for (FileStatus globStat : matches) {
if (globStat.isDir()) {
Collections.addAll(result, fs.listStatus(globStat.getPath(), filter));
}
else {
result.add(globStat);
}
}
}
}
if (!errors.isEmpty()) {
throw new InvalidInputException(errors);
}
return result;
} | java | protected List<FileStatus> listStatus(JobContext job) throws IOException
{
List<FileStatus> result = new ArrayList<FileStatus>();
Path[] dirs = getInputPaths(job);
if (dirs.length == 0) {
throw new IOException("No input paths specified in job");
}
// Get tokens for all the required FileSystems..
TokenCache.obtainTokensForNamenodes(job.getCredentials(), dirs, job.getConfiguration());
List<IOException> errors = new ArrayList<IOException>();
for (Path p : dirs) {
FileSystem fs = p.getFileSystem(job.getConfiguration());
final SmilePathFilter filter = new SmilePathFilter();
FileStatus[] matches = fs.globStatus(p, filter);
if (matches == null) {
errors.add(new IOException("Input path does not exist: " + p));
}
else if (matches.length == 0) {
errors.add(new IOException("Input Pattern " + p + " matches 0 files"));
}
else {
for (FileStatus globStat : matches) {
if (globStat.isDir()) {
Collections.addAll(result, fs.listStatus(globStat.getPath(), filter));
}
else {
result.add(globStat);
}
}
}
}
if (!errors.isEmpty()) {
throw new InvalidInputException(errors);
}
return result;
} | [
"protected",
"List",
"<",
"FileStatus",
">",
"listStatus",
"(",
"JobContext",
"job",
")",
"throws",
"IOException",
"{",
"List",
"<",
"FileStatus",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"FileStatus",
">",
"(",
")",
";",
"Path",
"[",
"]",
"dirs",
"=... | List input directories.
@param job the job to list input paths for
@return array of FileStatus objects
@throws IOException if zero items. | [
"List",
"input",
"directories",
"."
] | b15b7c749ba78bfe94dce8fc22f31b30b2e6830b | https://github.com/pierre/serialization/blob/b15b7c749ba78bfe94dce8fc22f31b30b2e6830b/hadoop/src/main/java/com/ning/metrics/serialization/hadoop/SmileInputFormat.java#L66-L105 | train |
incodehq-legacy/incode-module-document | dom/src/main/java/org/incode/module/document/dom/impl/applicability/AttachmentAdvisorAbstract.java | AttachmentAdvisorAbstract.checkInputClass | protected void checkInputClass(final Object domainObject) {
final Class<?> actualInputType = domainObject.getClass();
if(!(expectedInputType.isAssignableFrom(actualInputType))) {
throw new IllegalArgumentException("The input document is required to be of type: " + expectedInputType.getName());
}
} | java | protected void checkInputClass(final Object domainObject) {
final Class<?> actualInputType = domainObject.getClass();
if(!(expectedInputType.isAssignableFrom(actualInputType))) {
throw new IllegalArgumentException("The input document is required to be of type: " + expectedInputType.getName());
}
} | [
"protected",
"void",
"checkInputClass",
"(",
"final",
"Object",
"domainObject",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"actualInputType",
"=",
"domainObject",
".",
"getClass",
"(",
")",
";",
"if",
"(",
"!",
"(",
"expectedInputType",
".",
"isAssignableFrom"... | Optional hook; default implementation checks that the input type is of the correct type. | [
"Optional",
"hook",
";",
"default",
"implementation",
"checks",
"that",
"the",
"input",
"type",
"is",
"of",
"the",
"correct",
"type",
"."
] | c62f064e96d6e6007f7fd6a4bc06e03b78b1816c | https://github.com/incodehq-legacy/incode-module-document/blob/c62f064e96d6e6007f7fd6a4bc06e03b78b1816c/dom/src/main/java/org/incode/module/document/dom/impl/applicability/AttachmentAdvisorAbstract.java#L49-L54 | train |
syphr42/libmythtv-java | api/src/main/java/org/syphr/mythtv/api/commons/AbstractCachedConnection.java | AbstractCachedConnection.setTimeout | public void setTimeout(long timeout, TimeUnit unit)
{
this.timeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
} | java | public void setTimeout(long timeout, TimeUnit unit)
{
this.timeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
} | [
"public",
"void",
"setTimeout",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"{",
"this",
".",
"timeout",
"=",
"TimeUnit",
".",
"MILLISECONDS",
".",
"convert",
"(",
"timeout",
",",
"unit",
")",
";",
"}"
] | Change the idle timeout.
@param timeout
the timeout value
@param unit
the timeout units | [
"Change",
"the",
"idle",
"timeout",
"."
] | cc7a2012fbd4a4ba2562dda6b2614fb0548526ea | https://github.com/syphr42/libmythtv-java/blob/cc7a2012fbd4a4ba2562dda6b2614fb0548526ea/api/src/main/java/org/syphr/mythtv/api/commons/AbstractCachedConnection.java#L122-L125 | train |
taimos/spring-cxf-daemon | src/main/java/de/taimos/springcxfdaemon/websocket/ClientSocketAdapter.java | ClientSocketAdapter.sendObjectToSocket | public final void sendObjectToSocket(Object o) {
Session sess = this.getSession();
if (sess != null) {
String json;
try {
json = this.mapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
ClientSocketAdapter.LOGGER.error("Failed to serialize object", e);
return;
}
sess.getRemote().sendString(json, new WriteCallback() {
@Override
public void writeSuccess() {
ClientSocketAdapter.LOGGER.info("Send data to socket");
}
@Override
public void writeFailed(Throwable x) {
ClientSocketAdapter.LOGGER.error("Error sending message to socket", x);
}
});
}
} | java | public final void sendObjectToSocket(Object o) {
Session sess = this.getSession();
if (sess != null) {
String json;
try {
json = this.mapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
ClientSocketAdapter.LOGGER.error("Failed to serialize object", e);
return;
}
sess.getRemote().sendString(json, new WriteCallback() {
@Override
public void writeSuccess() {
ClientSocketAdapter.LOGGER.info("Send data to socket");
}
@Override
public void writeFailed(Throwable x) {
ClientSocketAdapter.LOGGER.error("Error sending message to socket", x);
}
});
}
} | [
"public",
"final",
"void",
"sendObjectToSocket",
"(",
"Object",
"o",
")",
"{",
"Session",
"sess",
"=",
"this",
".",
"getSession",
"(",
")",
";",
"if",
"(",
"sess",
"!=",
"null",
")",
"{",
"String",
"json",
";",
"try",
"{",
"json",
"=",
"this",
".",
... | send the given object to the server using JSON serialization
@param o the object to send to the server | [
"send",
"the",
"given",
"object",
"to",
"the",
"server",
"using",
"JSON",
"serialization"
] | a2f2158043ab7339ac08d9acfc3fe61d5a34b43a | https://github.com/taimos/spring-cxf-daemon/blob/a2f2158043ab7339ac08d9acfc3fe61d5a34b43a/src/main/java/de/taimos/springcxfdaemon/websocket/ClientSocketAdapter.java#L65-L88 | train |
taimos/spring-cxf-daemon | src/main/java/de/taimos/springcxfdaemon/websocket/ClientSocketAdapter.java | ClientSocketAdapter.readMessage | protected final <T> T readMessage(String message, Class<T> clazz) {
if ((message == null) || message.isEmpty()) {
ClientSocketAdapter.LOGGER.info("Got empty session data");
return null;
}
try {
return this.mapper.readValue(message, clazz);
} catch (IOException e1) {
ClientSocketAdapter.LOGGER.info("Got invalid session data", e1);
return null;
}
} | java | protected final <T> T readMessage(String message, Class<T> clazz) {
if ((message == null) || message.isEmpty()) {
ClientSocketAdapter.LOGGER.info("Got empty session data");
return null;
}
try {
return this.mapper.readValue(message, clazz);
} catch (IOException e1) {
ClientSocketAdapter.LOGGER.info("Got invalid session data", e1);
return null;
}
} | [
"protected",
"final",
"<",
"T",
">",
"T",
"readMessage",
"(",
"String",
"message",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"if",
"(",
"(",
"message",
"==",
"null",
")",
"||",
"message",
".",
"isEmpty",
"(",
")",
")",
"{",
"ClientSocketAdapter... | reads the received string into the given class by parsing JSON
@param <T> the expected type
@param message the JSON string
@param clazz the target class of type T
@return the parsed object or null if parsing was not possible or message is null | [
"reads",
"the",
"received",
"string",
"into",
"the",
"given",
"class",
"by",
"parsing",
"JSON"
] | a2f2158043ab7339ac08d9acfc3fe61d5a34b43a | https://github.com/taimos/spring-cxf-daemon/blob/a2f2158043ab7339ac08d9acfc3fe61d5a34b43a/src/main/java/de/taimos/springcxfdaemon/websocket/ClientSocketAdapter.java#L98-L109 | train |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/util/BaseFileManager.java | BaseFileManager.makeByteBuffer | public ByteBuffer makeByteBuffer(InputStream in)
throws IOException {
int limit = in.available();
if (limit < 1024) limit = 1024;
ByteBuffer result = byteBufferCache.get(limit);
int position = 0;
while (in.available() != 0) {
if (position >= limit)
// expand buffer
result = ByteBuffer.
allocate(limit <<= 1).
put((ByteBuffer)result.flip());
int count = in.read(result.array(),
position,
limit - position);
if (count < 0) break;
result.position(position += count);
}
return (ByteBuffer)result.flip();
} | java | public ByteBuffer makeByteBuffer(InputStream in)
throws IOException {
int limit = in.available();
if (limit < 1024) limit = 1024;
ByteBuffer result = byteBufferCache.get(limit);
int position = 0;
while (in.available() != 0) {
if (position >= limit)
// expand buffer
result = ByteBuffer.
allocate(limit <<= 1).
put((ByteBuffer)result.flip());
int count = in.read(result.array(),
position,
limit - position);
if (count < 0) break;
result.position(position += count);
}
return (ByteBuffer)result.flip();
} | [
"public",
"ByteBuffer",
"makeByteBuffer",
"(",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"int",
"limit",
"=",
"in",
".",
"available",
"(",
")",
";",
"if",
"(",
"limit",
"<",
"1024",
")",
"limit",
"=",
"1024",
";",
"ByteBuffer",
"result",
"=... | Make a byte buffer from an input stream. | [
"Make",
"a",
"byte",
"buffer",
"from",
"an",
"input",
"stream",
"."
] | 8812d28c20f4de070a0dd6de1b45602431379834 | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/util/BaseFileManager.java#L290-L309 | train |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/provider/newrelic/BrowserApplicationCache.java | BrowserApplicationCache.add | public void add(Collection<BrowserApplication> browserApplications)
{
for(BrowserApplication browserApplication : browserApplications)
this.browserApplications.put(browserApplication.getId(), browserApplication);
} | java | public void add(Collection<BrowserApplication> browserApplications)
{
for(BrowserApplication browserApplication : browserApplications)
this.browserApplications.put(browserApplication.getId(), browserApplication);
} | [
"public",
"void",
"add",
"(",
"Collection",
"<",
"BrowserApplication",
">",
"browserApplications",
")",
"{",
"for",
"(",
"BrowserApplication",
"browserApplication",
":",
"browserApplications",
")",
"this",
".",
"browserApplications",
".",
"put",
"(",
"browserApplicati... | Adds the browser application list to the browser applications for the account.
@param browserApplications The browser applications to add | [
"Adds",
"the",
"browser",
"application",
"list",
"to",
"the",
"browser",
"applications",
"for",
"the",
"account",
"."
] | c48904f7e8d029fd45357811ec38a735e261e3fd | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/provider/newrelic/BrowserApplicationCache.java#L55-L59 | train |
brianwhu/xillium | base/src/main/java/org/xillium/base/util/Objects.java | Objects.getProperty | public static Object getProperty(Object object, String name) throws NoSuchFieldException {
try {
Matcher matcher = ARRAY_INDEX.matcher(name);
if (matcher.matches()) {
object = getProperty(object, matcher.group(1));
if (object.getClass().isArray()) {
return Array.get(object, Integer.parseInt(matcher.group(2)));
} else {
return ((List)object).get(Integer.parseInt(matcher.group(2)));
}
} else {
int dot = name.lastIndexOf('.');
if (dot > 0) {
object = getProperty(object, name.substring(0, dot));
name = name.substring(dot + 1);
}
return Beans.getKnownField(object.getClass(), name).get(object);
}
} catch (NoSuchFieldException x) {
throw x;
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage() + ": " + name, x);
}
} | java | public static Object getProperty(Object object, String name) throws NoSuchFieldException {
try {
Matcher matcher = ARRAY_INDEX.matcher(name);
if (matcher.matches()) {
object = getProperty(object, matcher.group(1));
if (object.getClass().isArray()) {
return Array.get(object, Integer.parseInt(matcher.group(2)));
} else {
return ((List)object).get(Integer.parseInt(matcher.group(2)));
}
} else {
int dot = name.lastIndexOf('.');
if (dot > 0) {
object = getProperty(object, name.substring(0, dot));
name = name.substring(dot + 1);
}
return Beans.getKnownField(object.getClass(), name).get(object);
}
} catch (NoSuchFieldException x) {
throw x;
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage() + ": " + name, x);
}
} | [
"public",
"static",
"Object",
"getProperty",
"(",
"Object",
"object",
",",
"String",
"name",
")",
"throws",
"NoSuchFieldException",
"{",
"try",
"{",
"Matcher",
"matcher",
"=",
"ARRAY_INDEX",
".",
"matcher",
"(",
"name",
")",
";",
"if",
"(",
"matcher",
".",
... | Reports a property.
@param object the target object
@param name a dot-separated path to the property
@return the property value
@throws NoSuchFieldException if the property is not found | [
"Reports",
"a",
"property",
"."
] | e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799 | https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/util/Objects.java#L26-L49 | train |
brianwhu/xillium | base/src/main/java/org/xillium/base/util/Objects.java | Objects.setProperty | @SuppressWarnings("unchecked")
public static void setProperty(Object object, String name, String text) throws NoSuchFieldException {
try {
// need to get to the field for any typeinfo annotation, so here we go ...
int length = name.lastIndexOf('.');
if (length > 0) {
object = getProperty(object, name.substring(0, length));
name = name.substring(length + 1);
}
length = name.length();
Matcher matcher = ARRAY_INDEX.matcher(name);
for (Matcher m = matcher; m.matches(); m = ARRAY_INDEX.matcher(name)) {
name = m.group(1);
}
Field field = Beans.getKnownField(object.getClass(), name);
if (name.length() != length) {
int index = Integer.parseInt(matcher.group(2));
object = getProperty(object, matcher.group(1));
if (object.getClass().isArray()) {
Array.set(object, index, new ValueOf(object.getClass().getComponentType(), field.getAnnotation(typeinfo.class)).invoke(text));
} else {
((List)object).set(index, new ValueOf(field.getAnnotation(typeinfo.class).value()[0]).invoke(text));
}
} else {
field.set(object, new ValueOf(field.getType(), field.getAnnotation(typeinfo.class)).invoke(text));
}
} catch (NoSuchFieldException x) {
throw x;
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage() + ": " + name, x);
}
} | java | @SuppressWarnings("unchecked")
public static void setProperty(Object object, String name, String text) throws NoSuchFieldException {
try {
// need to get to the field for any typeinfo annotation, so here we go ...
int length = name.lastIndexOf('.');
if (length > 0) {
object = getProperty(object, name.substring(0, length));
name = name.substring(length + 1);
}
length = name.length();
Matcher matcher = ARRAY_INDEX.matcher(name);
for (Matcher m = matcher; m.matches(); m = ARRAY_INDEX.matcher(name)) {
name = m.group(1);
}
Field field = Beans.getKnownField(object.getClass(), name);
if (name.length() != length) {
int index = Integer.parseInt(matcher.group(2));
object = getProperty(object, matcher.group(1));
if (object.getClass().isArray()) {
Array.set(object, index, new ValueOf(object.getClass().getComponentType(), field.getAnnotation(typeinfo.class)).invoke(text));
} else {
((List)object).set(index, new ValueOf(field.getAnnotation(typeinfo.class).value()[0]).invoke(text));
}
} else {
field.set(object, new ValueOf(field.getType(), field.getAnnotation(typeinfo.class)).invoke(text));
}
} catch (NoSuchFieldException x) {
throw x;
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage() + ": " + name, x);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"void",
"setProperty",
"(",
"Object",
"object",
",",
"String",
"name",
",",
"String",
"text",
")",
"throws",
"NoSuchFieldException",
"{",
"try",
"{",
"// need to get to the field for any typeinfo ... | Updates a property.
@param object the target object
@param name a dot-separated path to the property
@param text a String representation of the new value
@throws NoSuchFieldException if the property is not found
@throws IllegalArgumentException if the value expression is invalid or can't be assigned to the property | [
"Updates",
"a",
"property",
"."
] | e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799 | https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/util/Objects.java#L60-L93 | train |
brianwhu/xillium | base/src/main/java/org/xillium/base/util/Objects.java | Objects.concat | @SafeVarargs
public static <T> T[] concat(T[] first, T[]... rest) {
int length = first.length;
for (T[] array : rest) {
length += array.length;
}
T[] result = Arrays.copyOf(first, length);
int offset = first.length;
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
} | java | @SafeVarargs
public static <T> T[] concat(T[] first, T[]... rest) {
int length = first.length;
for (T[] array : rest) {
length += array.length;
}
T[] result = Arrays.copyOf(first, length);
int offset = first.length;
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
} | [
"@",
"SafeVarargs",
"public",
"static",
"<",
"T",
">",
"T",
"[",
"]",
"concat",
"(",
"T",
"[",
"]",
"first",
",",
"T",
"[",
"]",
"...",
"rest",
")",
"{",
"int",
"length",
"=",
"first",
".",
"length",
";",
"for",
"(",
"T",
"[",
"]",
"array",
"... | Concatenates several reference arrays.
@param <T> the type of the elements in the array
@param first the first array
@param rest the rest of the arrays
@return a single array containing all elements in all arrays | [
"Concatenates",
"several",
"reference",
"arrays",
"."
] | e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799 | https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/util/Objects.java#L103-L116 | train |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java | GeneratedDi18nDaoImpl.queryByBaseBundle | public Iterable<Di18n> queryByBaseBundle(java.lang.String baseBundle) {
return queryByField(null, Di18nMapper.Field.BASEBUNDLE.getFieldName(), baseBundle);
} | java | public Iterable<Di18n> queryByBaseBundle(java.lang.String baseBundle) {
return queryByField(null, Di18nMapper.Field.BASEBUNDLE.getFieldName(), baseBundle);
} | [
"public",
"Iterable",
"<",
"Di18n",
">",
"queryByBaseBundle",
"(",
"java",
".",
"lang",
".",
"String",
"baseBundle",
")",
"{",
"return",
"queryByField",
"(",
"null",
",",
"Di18nMapper",
".",
"Field",
".",
"BASEBUNDLE",
".",
"getFieldName",
"(",
")",
",",
"... | query-by method for field baseBundle
@param baseBundle the specified attribute
@return an Iterable of Di18ns for the specified baseBundle | [
"query",
"-",
"by",
"method",
"for",
"field",
"baseBundle"
] | eb8ba8e6794a96ea0dd9744cada4f9ad9618f114 | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java#L43-L45 | train |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java | GeneratedDi18nDaoImpl.queryByKey | public Iterable<Di18n> queryByKey(java.lang.String key) {
return queryByField(null, Di18nMapper.Field.KEY.getFieldName(), key);
} | java | public Iterable<Di18n> queryByKey(java.lang.String key) {
return queryByField(null, Di18nMapper.Field.KEY.getFieldName(), key);
} | [
"public",
"Iterable",
"<",
"Di18n",
">",
"queryByKey",
"(",
"java",
".",
"lang",
".",
"String",
"key",
")",
"{",
"return",
"queryByField",
"(",
"null",
",",
"Di18nMapper",
".",
"Field",
".",
"KEY",
".",
"getFieldName",
"(",
")",
",",
"key",
")",
";",
... | query-by method for field key
@param key the specified attribute
@return an Iterable of Di18ns for the specified key | [
"query",
"-",
"by",
"method",
"for",
"field",
"key"
] | eb8ba8e6794a96ea0dd9744cada4f9ad9618f114 | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java#L70-L72 | train |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java | GeneratedDi18nDaoImpl.queryByLocale | public Iterable<Di18n> queryByLocale(java.lang.String locale) {
return queryByField(null, Di18nMapper.Field.LOCALE.getFieldName(), locale);
} | java | public Iterable<Di18n> queryByLocale(java.lang.String locale) {
return queryByField(null, Di18nMapper.Field.LOCALE.getFieldName(), locale);
} | [
"public",
"Iterable",
"<",
"Di18n",
">",
"queryByLocale",
"(",
"java",
".",
"lang",
".",
"String",
"locale",
")",
"{",
"return",
"queryByField",
"(",
"null",
",",
"Di18nMapper",
".",
"Field",
".",
"LOCALE",
".",
"getFieldName",
"(",
")",
",",
"locale",
"... | query-by method for field locale
@param locale the specified attribute
@return an Iterable of Di18ns for the specified locale | [
"query",
"-",
"by",
"method",
"for",
"field",
"locale"
] | eb8ba8e6794a96ea0dd9744cada4f9ad9618f114 | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java#L79-L81 | train |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java | GeneratedDi18nDaoImpl.queryByLocalizedMessage | public Iterable<Di18n> queryByLocalizedMessage(java.lang.String localizedMessage) {
return queryByField(null, Di18nMapper.Field.LOCALIZEDMESSAGE.getFieldName(), localizedMessage);
} | java | public Iterable<Di18n> queryByLocalizedMessage(java.lang.String localizedMessage) {
return queryByField(null, Di18nMapper.Field.LOCALIZEDMESSAGE.getFieldName(), localizedMessage);
} | [
"public",
"Iterable",
"<",
"Di18n",
">",
"queryByLocalizedMessage",
"(",
"java",
".",
"lang",
".",
"String",
"localizedMessage",
")",
"{",
"return",
"queryByField",
"(",
"null",
",",
"Di18nMapper",
".",
"Field",
".",
"LOCALIZEDMESSAGE",
".",
"getFieldName",
"(",... | query-by method for field localizedMessage
@param localizedMessage the specified attribute
@return an Iterable of Di18ns for the specified localizedMessage | [
"query",
"-",
"by",
"method",
"for",
"field",
"localizedMessage"
] | eb8ba8e6794a96ea0dd9744cada4f9ad9618f114 | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java#L88-L90 | train |
arakelian/more-commons | src/main/java/com/arakelian/core/utils/MoreStringUtils.java | MoreStringUtils.maskExcept | public static String maskExcept(final String s, final int unmaskedLength, final char maskChar) {
if (s == null) {
return null;
}
final boolean maskLeading = unmaskedLength > 0;
final int length = s.length();
final int maskedLength = Math.max(0, length - Math.abs(unmaskedLength));
if (maskedLength > 0) {
final String mask = StringUtils.repeat(maskChar, maskedLength);
if (maskLeading) {
return StringUtils.overlay(s, mask, 0, maskedLength);
}
return StringUtils.overlay(s, mask, length - maskedLength, length);
}
return s;
} | java | public static String maskExcept(final String s, final int unmaskedLength, final char maskChar) {
if (s == null) {
return null;
}
final boolean maskLeading = unmaskedLength > 0;
final int length = s.length();
final int maskedLength = Math.max(0, length - Math.abs(unmaskedLength));
if (maskedLength > 0) {
final String mask = StringUtils.repeat(maskChar, maskedLength);
if (maskLeading) {
return StringUtils.overlay(s, mask, 0, maskedLength);
}
return StringUtils.overlay(s, mask, length - maskedLength, length);
}
return s;
} | [
"public",
"static",
"String",
"maskExcept",
"(",
"final",
"String",
"s",
",",
"final",
"int",
"unmaskedLength",
",",
"final",
"char",
"maskChar",
")",
"{",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"boolean",
"maskLeadi... | Returns a masked string, leaving only the given number of characters unmasked.
@param s
string that requires masking
@param unmaskedLength
number of characters to leave unmasked; if positive, the unmasked characters are
at the end of the string, otherwise the unmasked characters are at the start of
the string.
@param maskChar
character to be used for masking
@return a masked string | [
"Returns",
"a",
"masked",
"string",
"leaving",
"only",
"the",
"given",
"number",
"of",
"characters",
"unmasked",
"."
] | 83c607044f64a7f6c005a67866c0ef7cb68d6e29 | https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/MoreStringUtils.java#L179-L194 | train |
arakelian/more-commons | src/main/java/com/arakelian/core/utils/MoreStringUtils.java | MoreStringUtils.replaceNonPrintableControlCharacters | public static String replaceNonPrintableControlCharacters(final String value) {
if (value == null || value.length() == 0) {
return value;
}
boolean changing = false;
for (int i = 0, length = value.length(); i < length; i++) {
final char ch = value.charAt(i);
if (ch < 32 && ch != '\n' && ch != '\r' && ch != '\t') {
changing = true;
break;
}
}
if (!changing) {
return value;
}
final StringBuilder buf = new StringBuilder(value);
for (int i = 0, length = buf.length(); i < length; i++) {
final char ch = buf.charAt(i);
if (ch < 32 && ch != '\n' && ch != '\r' && ch != '\t') {
buf.setCharAt(i, ' ');
}
}
// return cleaned string
return buf.toString();
} | java | public static String replaceNonPrintableControlCharacters(final String value) {
if (value == null || value.length() == 0) {
return value;
}
boolean changing = false;
for (int i = 0, length = value.length(); i < length; i++) {
final char ch = value.charAt(i);
if (ch < 32 && ch != '\n' && ch != '\r' && ch != '\t') {
changing = true;
break;
}
}
if (!changing) {
return value;
}
final StringBuilder buf = new StringBuilder(value);
for (int i = 0, length = buf.length(); i < length; i++) {
final char ch = buf.charAt(i);
if (ch < 32 && ch != '\n' && ch != '\r' && ch != '\t') {
buf.setCharAt(i, ' ');
}
}
// return cleaned string
return buf.toString();
} | [
"public",
"static",
"String",
"replaceNonPrintableControlCharacters",
"(",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
"||",
"value",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"value",
";",
"}",
"boolean",
"changin... | Returns a string where non-printable control characters are replaced by whitespace.
@param value
string which may contain non-printable characters
@return a string where non-printable control characters are replaced by whitespace. | [
"Returns",
"a",
"string",
"where",
"non",
"-",
"printable",
"control",
"characters",
"are",
"replaced",
"by",
"whitespace",
"."
] | 83c607044f64a7f6c005a67866c0ef7cb68d6e29 | https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/MoreStringUtils.java#L349-L377 | train |
arakelian/more-commons | src/main/java/com/arakelian/core/utils/MoreStringUtils.java | MoreStringUtils.shortUuid | public static String shortUuid() {
// source: java.util.UUID.randomUUID()
final byte[] randomBytes = new byte[16];
UUID_GENERATOR.nextBytes(randomBytes);
randomBytes[6] = (byte) (randomBytes[6] & 0x0f); // clear version
randomBytes[6] = (byte) (randomBytes[6] | 0x40); // set to version 4
randomBytes[8] = (byte) (randomBytes[8] & 0x3f); // clear variant
randomBytes[8] = (byte) (randomBytes[8] | 0x80); // set to IETF variant
// all base 64 encoding schemes use A-Z, a-z, and 0-9 for the first 62 characters. for the
// last 2 characters, we use hyphen and underscore, which are URL safe
return BaseEncoding.base64Url().omitPadding().encode(randomBytes);
} | java | public static String shortUuid() {
// source: java.util.UUID.randomUUID()
final byte[] randomBytes = new byte[16];
UUID_GENERATOR.nextBytes(randomBytes);
randomBytes[6] = (byte) (randomBytes[6] & 0x0f); // clear version
randomBytes[6] = (byte) (randomBytes[6] | 0x40); // set to version 4
randomBytes[8] = (byte) (randomBytes[8] & 0x3f); // clear variant
randomBytes[8] = (byte) (randomBytes[8] | 0x80); // set to IETF variant
// all base 64 encoding schemes use A-Z, a-z, and 0-9 for the first 62 characters. for the
// last 2 characters, we use hyphen and underscore, which are URL safe
return BaseEncoding.base64Url().omitPadding().encode(randomBytes);
} | [
"public",
"static",
"String",
"shortUuid",
"(",
")",
"{",
"// source: java.util.UUID.randomUUID()",
"final",
"byte",
"[",
"]",
"randomBytes",
"=",
"new",
"byte",
"[",
"16",
"]",
";",
"UUID_GENERATOR",
".",
"nextBytes",
"(",
"randomBytes",
")",
";",
"randomBytes"... | Returns a short UUID which is encoding use base 64 characters instead of hexadecimal. This
saves 10 bytes per UUID.
@return short UUID which is encoding use base 64 characters instead of hexadecimal | [
"Returns",
"a",
"short",
"UUID",
"which",
"is",
"encoding",
"use",
"base",
"64",
"characters",
"instead",
"of",
"hexadecimal",
".",
"This",
"saves",
"10",
"bytes",
"per",
"UUID",
"."
] | 83c607044f64a7f6c005a67866c0ef7cb68d6e29 | https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/MoreStringUtils.java#L385-L397 | train |
arakelian/more-commons | src/main/java/com/arakelian/core/utils/MoreStringUtils.java | MoreStringUtils.splitToList | public static List<String> splitToList(final String value) {
if (!StringUtils.isEmpty(value)) {
return COMMA_SPLITTER.splitToList(value);
}
return Collections.<String> emptyList();
} | java | public static List<String> splitToList(final String value) {
if (!StringUtils.isEmpty(value)) {
return COMMA_SPLITTER.splitToList(value);
}
return Collections.<String> emptyList();
} | [
"public",
"static",
"List",
"<",
"String",
">",
"splitToList",
"(",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"value",
")",
")",
"{",
"return",
"COMMA_SPLITTER",
".",
"splitToList",
"(",
"value",
")",
";",
... | Parses a comma-separated string and returns a list of String values.
@param value
comma-separated string
@return list of String values | [
"Parses",
"a",
"comma",
"-",
"separated",
"string",
"and",
"returns",
"a",
"list",
"of",
"String",
"values",
"."
] | 83c607044f64a7f6c005a67866c0ef7cb68d6e29 | https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/MoreStringUtils.java#L417-L422 | train |
arakelian/more-commons | src/main/java/com/arakelian/core/utils/MoreStringUtils.java | MoreStringUtils.trimWhitespace | public static String trimWhitespace(final String s) {
if (s == null || s.length() == 0) {
return s;
}
final int length = s.length();
int end = length;
int start = 0;
while (start < end && Character.isWhitespace(s.charAt(start))) {
start++;
}
while (start < end && Character.isWhitespace(s.charAt(end - 1))) {
end--;
}
return start > 0 || end < length ? s.substring(start, end) : s;
} | java | public static String trimWhitespace(final String s) {
if (s == null || s.length() == 0) {
return s;
}
final int length = s.length();
int end = length;
int start = 0;
while (start < end && Character.isWhitespace(s.charAt(start))) {
start++;
}
while (start < end && Character.isWhitespace(s.charAt(end - 1))) {
end--;
}
return start > 0 || end < length ? s.substring(start, end) : s;
} | [
"public",
"static",
"String",
"trimWhitespace",
"(",
"final",
"String",
"s",
")",
"{",
"if",
"(",
"s",
"==",
"null",
"||",
"s",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"s",
";",
"}",
"final",
"int",
"length",
"=",
"s",
".",
"lengt... | Strip leading and trailing whitespace from a String.
Spring's version of StringUtils.trimWhitespace needlessly creates a StringBuilder when
whitespace characters are not present, and java.lang.String.trim() removes non-printable
characters in a non-unicode safe way.
@param s
string to be trimmed
@return input string with leading and trailing whitespace removed. | [
"Strip",
"leading",
"and",
"trailing",
"whitespace",
"from",
"a",
"String",
"."
] | 83c607044f64a7f6c005a67866c0ef7cb68d6e29 | https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/MoreStringUtils.java#L484-L499 | train |
arakelian/more-commons | src/main/java/com/arakelian/core/utils/MoreStringUtils.java | MoreStringUtils.trimWhitespaceToNull | public static String trimWhitespaceToNull(final String s) {
final String result = trimWhitespace(s);
return StringUtils.isEmpty(result) ? null : s;
} | java | public static String trimWhitespaceToNull(final String s) {
final String result = trimWhitespace(s);
return StringUtils.isEmpty(result) ? null : s;
} | [
"public",
"static",
"String",
"trimWhitespaceToNull",
"(",
"final",
"String",
"s",
")",
"{",
"final",
"String",
"result",
"=",
"trimWhitespace",
"(",
"s",
")",
";",
"return",
"StringUtils",
".",
"isEmpty",
"(",
"result",
")",
"?",
"null",
":",
"s",
";",
... | Strip leading and trailing whitespace from a String. If the resulting string is empty, this
method returns null.
@param s
string to be trimmed
@return input string with leading and trailing whitespace removed. | [
"Strip",
"leading",
"and",
"trailing",
"whitespace",
"from",
"a",
"String",
".",
"If",
"the",
"resulting",
"string",
"is",
"empty",
"this",
"method",
"returns",
"null",
"."
] | 83c607044f64a7f6c005a67866c0ef7cb68d6e29 | https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/MoreStringUtils.java#L509-L512 | train |
SixDimensions/Component-Bindings-Provider | impl/src/main/java/com/sixdimensions/wcm/cq/component/bindings/impl/ComponentBindingsProviderCache.java | ComponentBindingsProviderCache.getReferences | public List<ServiceReference> getReferences(String resourceType) {
List<ServiceReference> references = new ArrayList<ServiceReference>();
if (containsKey(resourceType)) {
references.addAll(get(resourceType));
Collections.sort(references, new Comparator<ServiceReference>() {
@Override
public int compare(ServiceReference r0, ServiceReference r1) {
Integer p0 = OsgiUtil.toInteger(
r0.getProperty(ComponentBindingsProvider.PRIORITY),
0);
Integer p1 = OsgiUtil.toInteger(
r1.getProperty(ComponentBindingsProvider.PRIORITY),
0);
return -1 * p0.compareTo(p1);
}
});
}
return references;
} | java | public List<ServiceReference> getReferences(String resourceType) {
List<ServiceReference> references = new ArrayList<ServiceReference>();
if (containsKey(resourceType)) {
references.addAll(get(resourceType));
Collections.sort(references, new Comparator<ServiceReference>() {
@Override
public int compare(ServiceReference r0, ServiceReference r1) {
Integer p0 = OsgiUtil.toInteger(
r0.getProperty(ComponentBindingsProvider.PRIORITY),
0);
Integer p1 = OsgiUtil.toInteger(
r1.getProperty(ComponentBindingsProvider.PRIORITY),
0);
return -1 * p0.compareTo(p1);
}
});
}
return references;
} | [
"public",
"List",
"<",
"ServiceReference",
">",
"getReferences",
"(",
"String",
"resourceType",
")",
"{",
"List",
"<",
"ServiceReference",
">",
"references",
"=",
"new",
"ArrayList",
"<",
"ServiceReference",
">",
"(",
")",
";",
"if",
"(",
"containsKey",
"(",
... | Gets the ComponentBindingProvider references for the specified resource
type.
@param resourceType
the resource type for which to retrieve the references
@return the references for the resource type | [
"Gets",
"the",
"ComponentBindingProvider",
"references",
"for",
"the",
"specified",
"resource",
"type",
"."
] | 1d4da2f8c274d32edcd0a2593bec1255b8340b5b | https://github.com/SixDimensions/Component-Bindings-Provider/blob/1d4da2f8c274d32edcd0a2593bec1255b8340b5b/impl/src/main/java/com/sixdimensions/wcm/cq/component/bindings/impl/ComponentBindingsProviderCache.java#L61-L80 | train |
SixDimensions/Component-Bindings-Provider | impl/src/main/java/com/sixdimensions/wcm/cq/component/bindings/impl/ComponentBindingsProviderCache.java | ComponentBindingsProviderCache.registerComponentBindingsProvider | public void registerComponentBindingsProvider(ServiceReference reference) {
log.info("registerComponentBindingsProvider");
log.info("Registering Component Bindings Provider {} - {}",
new Object[] { reference.getProperty(Constants.SERVICE_ID),
reference.getProperty(Constants.SERVICE_PID) });
String[] resourceTypes = OsgiUtil.toStringArray(reference
.getProperty(ComponentBindingsProvider.RESOURCE_TYPE_PROP),
new String[0]);
for (String resourceType : resourceTypes) {
if (!this.containsKey(resourceType)) {
put(resourceType, new HashSet<ServiceReference>());
}
log.debug("Adding to resource type {}", resourceType);
get(resourceType).add(reference);
}
} | java | public void registerComponentBindingsProvider(ServiceReference reference) {
log.info("registerComponentBindingsProvider");
log.info("Registering Component Bindings Provider {} - {}",
new Object[] { reference.getProperty(Constants.SERVICE_ID),
reference.getProperty(Constants.SERVICE_PID) });
String[] resourceTypes = OsgiUtil.toStringArray(reference
.getProperty(ComponentBindingsProvider.RESOURCE_TYPE_PROP),
new String[0]);
for (String resourceType : resourceTypes) {
if (!this.containsKey(resourceType)) {
put(resourceType, new HashSet<ServiceReference>());
}
log.debug("Adding to resource type {}", resourceType);
get(resourceType).add(reference);
}
} | [
"public",
"void",
"registerComponentBindingsProvider",
"(",
"ServiceReference",
"reference",
")",
"{",
"log",
".",
"info",
"(",
"\"registerComponentBindingsProvider\"",
")",
";",
"log",
".",
"info",
"(",
"\"Registering Component Bindings Provider {} - {}\"",
",",
"new",
"... | Registers the ComponentBindingsProvider specified by the
ServiceReference.
@param reference
the reference to the ComponentBindingsProvider service | [
"Registers",
"the",
"ComponentBindingsProvider",
"specified",
"by",
"the",
"ServiceReference",
"."
] | 1d4da2f8c274d32edcd0a2593bec1255b8340b5b | https://github.com/SixDimensions/Component-Bindings-Provider/blob/1d4da2f8c274d32edcd0a2593bec1255b8340b5b/impl/src/main/java/com/sixdimensions/wcm/cq/component/bindings/impl/ComponentBindingsProviderCache.java#L89-L104 | train |
SixDimensions/Component-Bindings-Provider | impl/src/main/java/com/sixdimensions/wcm/cq/component/bindings/impl/ComponentBindingsProviderCache.java | ComponentBindingsProviderCache.unregisterComponentBindingsProvider | public void unregisterComponentBindingsProvider(ServiceReference reference) {
log.info("unregisterComponentBindingsProvider");
String[] resourceTypes = OsgiUtil.toStringArray(reference
.getProperty(ComponentBindingsProvider.RESOURCE_TYPE_PROP),
new String[0]);
for (String resourceType : resourceTypes) {
if (!this.containsKey(resourceType)) {
continue;
}
get(resourceType).remove(reference);
}
} | java | public void unregisterComponentBindingsProvider(ServiceReference reference) {
log.info("unregisterComponentBindingsProvider");
String[] resourceTypes = OsgiUtil.toStringArray(reference
.getProperty(ComponentBindingsProvider.RESOURCE_TYPE_PROP),
new String[0]);
for (String resourceType : resourceTypes) {
if (!this.containsKey(resourceType)) {
continue;
}
get(resourceType).remove(reference);
}
} | [
"public",
"void",
"unregisterComponentBindingsProvider",
"(",
"ServiceReference",
"reference",
")",
"{",
"log",
".",
"info",
"(",
"\"unregisterComponentBindingsProvider\"",
")",
";",
"String",
"[",
"]",
"resourceTypes",
"=",
"OsgiUtil",
".",
"toStringArray",
"(",
"ref... | UnRegisters the ComponentBindingsProvider specified by the
ServiceReference.
@param reference
the reference to the ComponentBindingsProvider service | [
"UnRegisters",
"the",
"ComponentBindingsProvider",
"specified",
"by",
"the",
"ServiceReference",
"."
] | 1d4da2f8c274d32edcd0a2593bec1255b8340b5b | https://github.com/SixDimensions/Component-Bindings-Provider/blob/1d4da2f8c274d32edcd0a2593bec1255b8340b5b/impl/src/main/java/com/sixdimensions/wcm/cq/component/bindings/impl/ComponentBindingsProviderCache.java#L113-L124 | train |
devnull-tools/trugger | src/main/java/tools/devnull/trugger/util/factory/ComponentFactory.java | ComponentFactory.toCreate | public ComponentFactory<T, E> toCreate(BiFunction<Constructor, Object[], Object>
createFunction) {
return new ComponentFactory<>(this.annotationType, this.classElement, this.contextConsumer, createFunction);
} | java | public ComponentFactory<T, E> toCreate(BiFunction<Constructor, Object[], Object>
createFunction) {
return new ComponentFactory<>(this.annotationType, this.classElement, this.contextConsumer, createFunction);
} | [
"public",
"ComponentFactory",
"<",
"T",
",",
"E",
">",
"toCreate",
"(",
"BiFunction",
"<",
"Constructor",
",",
"Object",
"[",
"]",
",",
"Object",
">",
"createFunction",
")",
"{",
"return",
"new",
"ComponentFactory",
"<>",
"(",
"this",
".",
"annotationType",
... | Sets the function used to create the objects.
@param createFunction the function to use
@return a new ComponentFactory | [
"Sets",
"the",
"function",
"used",
"to",
"create",
"the",
"objects",
"."
] | 614d5f0b30daf82fc251a46fb436d0fc5e787627 | https://github.com/devnull-tools/trugger/blob/614d5f0b30daf82fc251a46fb436d0fc5e787627/src/main/java/tools/devnull/trugger/util/factory/ComponentFactory.java#L119-L122 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.