repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerValue.java
DerValue.getUTCTime
public Date getUTCTime() throws IOException { """ Returns a Date if the DerValue is UtcTime. @return the Date held in this DER value """ if (tag != tag_UtcTime) { throw new IOException("DerValue.getUTCTime, not a UtcTime: " + tag); } return buffer.getUTCTime(data.available()); }
java
public Date getUTCTime() throws IOException { if (tag != tag_UtcTime) { throw new IOException("DerValue.getUTCTime, not a UtcTime: " + tag); } return buffer.getUTCTime(data.available()); }
[ "public", "Date", "getUTCTime", "(", ")", "throws", "IOException", "{", "if", "(", "tag", "!=", "tag_UtcTime", ")", "{", "throw", "new", "IOException", "(", "\"DerValue.getUTCTime, not a UtcTime: \"", "+", "tag", ")", ";", "}", "return", "buffer", ".", "getUTCTime", "(", "data", ".", "available", "(", ")", ")", ";", "}" ]
Returns a Date if the DerValue is UtcTime. @return the Date held in this DER value
[ "Returns", "a", "Date", "if", "the", "DerValue", "is", "UtcTime", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerValue.java#L741-L746
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.lighten
public static Expression lighten(Generator generator, FunctionCall input) { """ Increases the lightness of the given color by N percent. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation """ Color color = input.getExpectedColorParam(0); int increase = input.getExpectedIntParam(1); return changeLighteness(color, increase); }
java
public static Expression lighten(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int increase = input.getExpectedIntParam(1); return changeLighteness(color, increase); }
[ "public", "static", "Expression", "lighten", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "Color", "color", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "int", "increase", "=", "input", ".", "getExpectedIntParam", "(", "1", ")", ";", "return", "changeLighteness", "(", "color", ",", "increase", ")", ";", "}" ]
Increases the lightness of the given color by N percent. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Increases", "the", "lightness", "of", "the", "given", "color", "by", "N", "percent", "." ]
train
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L93-L97
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/NumberInRange.java
NumberInRange.isInRange
@ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static boolean isInRange(@Nonnull final Number number, @Nonnull final BigInteger min, @Nonnull final BigInteger max) { """ Test if a number is in an arbitrary range. @param number a number @param min lower boundary of the range @param max upper boundary of the range @return true if the given number is within the range """ Check.notNull(number, "number"); Check.notNull(min, "min"); Check.notNull(max, "max"); BigInteger bigInteger = null; if (number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) { bigInteger = BigInteger.valueOf(number.longValue()); } else if (number instanceof Float || number instanceof Double) { bigInteger = new BigDecimal(number.doubleValue()).toBigInteger(); } else if (number instanceof BigInteger) { bigInteger = (BigInteger) number; } else if (number instanceof BigDecimal) { bigInteger = ((BigDecimal) number).toBigInteger(); } else { throw new IllegalNumberArgumentException("Return value is no known subclass of 'java.lang.Number': " + number.getClass().getName()); } return max.compareTo(bigInteger) >= 0 && min.compareTo(bigInteger) <= 0; }
java
@ArgumentsChecked @Throws(IllegalNullArgumentException.class) public static boolean isInRange(@Nonnull final Number number, @Nonnull final BigInteger min, @Nonnull final BigInteger max) { Check.notNull(number, "number"); Check.notNull(min, "min"); Check.notNull(max, "max"); BigInteger bigInteger = null; if (number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) { bigInteger = BigInteger.valueOf(number.longValue()); } else if (number instanceof Float || number instanceof Double) { bigInteger = new BigDecimal(number.doubleValue()).toBigInteger(); } else if (number instanceof BigInteger) { bigInteger = (BigInteger) number; } else if (number instanceof BigDecimal) { bigInteger = ((BigDecimal) number).toBigInteger(); } else { throw new IllegalNumberArgumentException("Return value is no known subclass of 'java.lang.Number': " + number.getClass().getName()); } return max.compareTo(bigInteger) >= 0 && min.compareTo(bigInteger) <= 0; }
[ "@", "ArgumentsChecked", "@", "Throws", "(", "IllegalNullArgumentException", ".", "class", ")", "public", "static", "boolean", "isInRange", "(", "@", "Nonnull", "final", "Number", "number", ",", "@", "Nonnull", "final", "BigInteger", "min", ",", "@", "Nonnull", "final", "BigInteger", "max", ")", "{", "Check", ".", "notNull", "(", "number", ",", "\"number\"", ")", ";", "Check", ".", "notNull", "(", "min", ",", "\"min\"", ")", ";", "Check", ".", "notNull", "(", "max", ",", "\"max\"", ")", ";", "BigInteger", "bigInteger", "=", "null", ";", "if", "(", "number", "instanceof", "Byte", "||", "number", "instanceof", "Short", "||", "number", "instanceof", "Integer", "||", "number", "instanceof", "Long", ")", "{", "bigInteger", "=", "BigInteger", ".", "valueOf", "(", "number", ".", "longValue", "(", ")", ")", ";", "}", "else", "if", "(", "number", "instanceof", "Float", "||", "number", "instanceof", "Double", ")", "{", "bigInteger", "=", "new", "BigDecimal", "(", "number", ".", "doubleValue", "(", ")", ")", ".", "toBigInteger", "(", ")", ";", "}", "else", "if", "(", "number", "instanceof", "BigInteger", ")", "{", "bigInteger", "=", "(", "BigInteger", ")", "number", ";", "}", "else", "if", "(", "number", "instanceof", "BigDecimal", ")", "{", "bigInteger", "=", "(", "(", "BigDecimal", ")", "number", ")", ".", "toBigInteger", "(", ")", ";", "}", "else", "{", "throw", "new", "IllegalNumberArgumentException", "(", "\"Return value is no known subclass of 'java.lang.Number': \"", "+", "number", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "return", "max", ".", "compareTo", "(", "bigInteger", ")", ">=", "0", "&&", "min", ".", "compareTo", "(", "bigInteger", ")", "<=", "0", ";", "}" ]
Test if a number is in an arbitrary range. @param number a number @param min lower boundary of the range @param max upper boundary of the range @return true if the given number is within the range
[ "Test", "if", "a", "number", "is", "in", "an", "arbitrary", "range", "." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/NumberInRange.java#L285-L306
openengsb/openengsb
components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/EngineeringObjectEnhancer.java
EngineeringObjectEnhancer.mergeEngineeringObjectWithReferencedModel
private void mergeEngineeringObjectWithReferencedModel(Field field, EngineeringObjectModelWrapper model) { """ Merges the given EngineeringObject with the referenced model which is defined in the given field. """ AdvancedModelWrapper result = performMerge(loadReferencedModel(model, field), model); if (result != null) { model = result.toEngineeringObject(); } }
java
private void mergeEngineeringObjectWithReferencedModel(Field field, EngineeringObjectModelWrapper model) { AdvancedModelWrapper result = performMerge(loadReferencedModel(model, field), model); if (result != null) { model = result.toEngineeringObject(); } }
[ "private", "void", "mergeEngineeringObjectWithReferencedModel", "(", "Field", "field", ",", "EngineeringObjectModelWrapper", "model", ")", "{", "AdvancedModelWrapper", "result", "=", "performMerge", "(", "loadReferencedModel", "(", "model", ",", "field", ")", ",", "model", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "model", "=", "result", ".", "toEngineeringObject", "(", ")", ";", "}", "}" ]
Merges the given EngineeringObject with the referenced model which is defined in the given field.
[ "Merges", "the", "given", "EngineeringObject", "with", "the", "referenced", "model", "which", "is", "defined", "in", "the", "given", "field", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/EngineeringObjectEnhancer.java#L288-L293
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java
MultiViewOps.errorsHomographySymm
public static void errorsHomographySymm(List<AssociatedPair> observations , DMatrixRMaj H , @Nullable DMatrixRMaj H_inv , GrowQueue_F64 storage ) { """ <p>Computes symmetric Euclidean error for each observation and puts it into the storage. If the homography projects the point into the plane at infinity (z=0) then it is skipped</p> error[i] = (H*x1 - x2')**2 + (inv(H)*x2 - x1')**2<br> @param observations (Input) observations @param H (Input) Homography @param H_inv (Input) Inverse of homography. if null it will be computed internally @param storage (Output) storage for found errors """ storage.reset(); if( H_inv == null ) H_inv = new DMatrixRMaj(3,3); CommonOps_DDRM.invert(H,H_inv); Point3D_F64 tmp = new Point3D_F64(); for (int i = 0; i < observations.size(); i++) { AssociatedPair p = observations.get(i); double dx,dy; double error = 0; GeometryMath_F64.mult(H,p.p1,tmp); if( Math.abs(tmp.z) <= UtilEjml.EPS ) continue; dx = p.p2.x - tmp.x/tmp.z; dy = p.p2.y - tmp.y/tmp.z; error += dx*dx + dy*dy; GeometryMath_F64.mult(H_inv,p.p2,tmp); if( Math.abs(tmp.z) <= UtilEjml.EPS ) continue; dx = p.p1.x - tmp.x/tmp.z; dy = p.p1.y - tmp.y/tmp.z; error += dx*dx + dy*dy; storage.add(error); } }
java
public static void errorsHomographySymm(List<AssociatedPair> observations , DMatrixRMaj H , @Nullable DMatrixRMaj H_inv , GrowQueue_F64 storage ) { storage.reset(); if( H_inv == null ) H_inv = new DMatrixRMaj(3,3); CommonOps_DDRM.invert(H,H_inv); Point3D_F64 tmp = new Point3D_F64(); for (int i = 0; i < observations.size(); i++) { AssociatedPair p = observations.get(i); double dx,dy; double error = 0; GeometryMath_F64.mult(H,p.p1,tmp); if( Math.abs(tmp.z) <= UtilEjml.EPS ) continue; dx = p.p2.x - tmp.x/tmp.z; dy = p.p2.y - tmp.y/tmp.z; error += dx*dx + dy*dy; GeometryMath_F64.mult(H_inv,p.p2,tmp); if( Math.abs(tmp.z) <= UtilEjml.EPS ) continue; dx = p.p1.x - tmp.x/tmp.z; dy = p.p1.y - tmp.y/tmp.z; error += dx*dx + dy*dy; storage.add(error); } }
[ "public", "static", "void", "errorsHomographySymm", "(", "List", "<", "AssociatedPair", ">", "observations", ",", "DMatrixRMaj", "H", ",", "@", "Nullable", "DMatrixRMaj", "H_inv", ",", "GrowQueue_F64", "storage", ")", "{", "storage", ".", "reset", "(", ")", ";", "if", "(", "H_inv", "==", "null", ")", "H_inv", "=", "new", "DMatrixRMaj", "(", "3", ",", "3", ")", ";", "CommonOps_DDRM", ".", "invert", "(", "H", ",", "H_inv", ")", ";", "Point3D_F64", "tmp", "=", "new", "Point3D_F64", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "observations", ".", "size", "(", ")", ";", "i", "++", ")", "{", "AssociatedPair", "p", "=", "observations", ".", "get", "(", "i", ")", ";", "double", "dx", ",", "dy", ";", "double", "error", "=", "0", ";", "GeometryMath_F64", ".", "mult", "(", "H", ",", "p", ".", "p1", ",", "tmp", ")", ";", "if", "(", "Math", ".", "abs", "(", "tmp", ".", "z", ")", "<=", "UtilEjml", ".", "EPS", ")", "continue", ";", "dx", "=", "p", ".", "p2", ".", "x", "-", "tmp", ".", "x", "/", "tmp", ".", "z", ";", "dy", "=", "p", ".", "p2", ".", "y", "-", "tmp", ".", "y", "/", "tmp", ".", "z", ";", "error", "+=", "dx", "*", "dx", "+", "dy", "*", "dy", ";", "GeometryMath_F64", ".", "mult", "(", "H_inv", ",", "p", ".", "p2", ",", "tmp", ")", ";", "if", "(", "Math", ".", "abs", "(", "tmp", ".", "z", ")", "<=", "UtilEjml", ".", "EPS", ")", "continue", ";", "dx", "=", "p", ".", "p1", ".", "x", "-", "tmp", ".", "x", "/", "tmp", ".", "z", ";", "dy", "=", "p", ".", "p1", ".", "y", "-", "tmp", ".", "y", "/", "tmp", ".", "z", ";", "error", "+=", "dx", "*", "dx", "+", "dy", "*", "dy", ";", "storage", ".", "add", "(", "error", ")", ";", "}", "}" ]
<p>Computes symmetric Euclidean error for each observation and puts it into the storage. If the homography projects the point into the plane at infinity (z=0) then it is skipped</p> error[i] = (H*x1 - x2')**2 + (inv(H)*x2 - x1')**2<br> @param observations (Input) observations @param H (Input) Homography @param H_inv (Input) Inverse of homography. if null it will be computed internally @param storage (Output) storage for found errors
[ "<p", ">", "Computes", "symmetric", "Euclidean", "error", "for", "each", "observation", "and", "puts", "it", "into", "the", "storage", ".", "If", "the", "homography", "projects", "the", "point", "into", "the", "plane", "at", "infinity", "(", "z", "=", "0", ")", "then", "it", "is", "skipped<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L1182-L1216
nguyenq/tess4j
src/main/java/net/sourceforge/tess4j/util/ImageIOHelper.java
ImageIOHelper.getImageByteBuffer
public static ByteBuffer getImageByteBuffer(RenderedImage image) { """ Gets pixel data of an <code>RenderedImage</code> object. @param image an <code>RenderedImage</code> object @return a byte buffer of pixel data """ ColorModel cm = image.getColorModel(); WritableRaster wr = image.getData().createCompatibleWritableRaster(image.getWidth(), image.getHeight()); image.copyData(wr); BufferedImage bi = new BufferedImage(cm, wr, cm.isAlphaPremultiplied(), null); return convertImageData(bi); }
java
public static ByteBuffer getImageByteBuffer(RenderedImage image) { ColorModel cm = image.getColorModel(); WritableRaster wr = image.getData().createCompatibleWritableRaster(image.getWidth(), image.getHeight()); image.copyData(wr); BufferedImage bi = new BufferedImage(cm, wr, cm.isAlphaPremultiplied(), null); return convertImageData(bi); }
[ "public", "static", "ByteBuffer", "getImageByteBuffer", "(", "RenderedImage", "image", ")", "{", "ColorModel", "cm", "=", "image", ".", "getColorModel", "(", ")", ";", "WritableRaster", "wr", "=", "image", ".", "getData", "(", ")", ".", "createCompatibleWritableRaster", "(", "image", ".", "getWidth", "(", ")", ",", "image", ".", "getHeight", "(", ")", ")", ";", "image", ".", "copyData", "(", "wr", ")", ";", "BufferedImage", "bi", "=", "new", "BufferedImage", "(", "cm", ",", "wr", ",", "cm", ".", "isAlphaPremultiplied", "(", ")", ",", "null", ")", ";", "return", "convertImageData", "(", "bi", ")", ";", "}" ]
Gets pixel data of an <code>RenderedImage</code> object. @param image an <code>RenderedImage</code> object @return a byte buffer of pixel data
[ "Gets", "pixel", "data", "of", "an", "<code", ">", "RenderedImage<", "/", "code", ">", "object", "." ]
train
https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/util/ImageIOHelper.java#L269-L275
jhunters/jprotobuf
v3/src/main/java/com/baidu/bjf/remoting/protobuf/MapFieldLite.java
MapFieldLite.calculateHashCodeForMap
static <K, V> int calculateHashCodeForMap(Map<K, V> a) { """ Calculates the hash code for a {@link Map}. We don't use the default hash code method of {@link Map} because for byte arrays and protobuf enums it use {@link Object#hashCode()}. @param <K> the key type @param <V> the value type @param a the a @return the int """ int result = 0; for (Map.Entry<K, V> entry : a.entrySet()) { result += calculateHashCodeForObject(entry.getKey()) ^ calculateHashCodeForObject(entry.getValue()); } return result; }
java
static <K, V> int calculateHashCodeForMap(Map<K, V> a) { int result = 0; for (Map.Entry<K, V> entry : a.entrySet()) { result += calculateHashCodeForObject(entry.getKey()) ^ calculateHashCodeForObject(entry.getValue()); } return result; }
[ "static", "<", "K", ",", "V", ">", "int", "calculateHashCodeForMap", "(", "Map", "<", "K", ",", "V", ">", "a", ")", "{", "int", "result", "=", "0", ";", "for", "(", "Map", ".", "Entry", "<", "K", ",", "V", ">", "entry", ":", "a", ".", "entrySet", "(", ")", ")", "{", "result", "+=", "calculateHashCodeForObject", "(", "entry", ".", "getKey", "(", ")", ")", "^", "calculateHashCodeForObject", "(", "entry", ".", "getValue", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Calculates the hash code for a {@link Map}. We don't use the default hash code method of {@link Map} because for byte arrays and protobuf enums it use {@link Object#hashCode()}. @param <K> the key type @param <V> the value type @param a the a @return the int
[ "Calculates", "the", "hash", "code", "for", "a", "{", "@link", "Map", "}", ".", "We", "don", "t", "use", "the", "default", "hash", "code", "method", "of", "{", "@link", "Map", "}", "because", "for", "byte", "arrays", "and", "protobuf", "enums", "it", "use", "{", "@link", "Object#hashCode", "()", "}", "." ]
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/v3/src/main/java/com/baidu/bjf/remoting/protobuf/MapFieldLite.java#L224-L230
detro/browsermob-proxy-client
src/main/java/com/github/detro/browsermobproxyclient/BMPCProxy.java
BMPCProxy.harToFile
public static void harToFile(JsonObject har, String destinationDir, String destinationFile) { """ Utility to store HAR to file. @param har JsonObject containing HAR data @param destinationDir Path to destination Directory @param destinationFile Path to destination File """ // Prepare HAR destination directory File harDestinationDir = new File(destinationDir); if (!harDestinationDir.exists()) harDestinationDir.mkdirs(); // Store HAR to disk PrintWriter harDestinationFileWriter = null; try { // Prepare Writer harDestinationFileWriter = new PrintWriter( destinationDir + File.separator + destinationFile); // Store HAR if any, otherwise empty file if (null != har) { harDestinationFileWriter.print(har.toString()); } else { harDestinationFileWriter.print(""); } } catch (FileNotFoundException e) { throw new BMPCUnableToSaveHarToFileException(e); } finally { if (null != harDestinationFileWriter) { harDestinationFileWriter.flush(); harDestinationFileWriter.close(); } } }
java
public static void harToFile(JsonObject har, String destinationDir, String destinationFile) { // Prepare HAR destination directory File harDestinationDir = new File(destinationDir); if (!harDestinationDir.exists()) harDestinationDir.mkdirs(); // Store HAR to disk PrintWriter harDestinationFileWriter = null; try { // Prepare Writer harDestinationFileWriter = new PrintWriter( destinationDir + File.separator + destinationFile); // Store HAR if any, otherwise empty file if (null != har) { harDestinationFileWriter.print(har.toString()); } else { harDestinationFileWriter.print(""); } } catch (FileNotFoundException e) { throw new BMPCUnableToSaveHarToFileException(e); } finally { if (null != harDestinationFileWriter) { harDestinationFileWriter.flush(); harDestinationFileWriter.close(); } } }
[ "public", "static", "void", "harToFile", "(", "JsonObject", "har", ",", "String", "destinationDir", ",", "String", "destinationFile", ")", "{", "// Prepare HAR destination directory", "File", "harDestinationDir", "=", "new", "File", "(", "destinationDir", ")", ";", "if", "(", "!", "harDestinationDir", ".", "exists", "(", ")", ")", "harDestinationDir", ".", "mkdirs", "(", ")", ";", "// Store HAR to disk", "PrintWriter", "harDestinationFileWriter", "=", "null", ";", "try", "{", "// Prepare Writer", "harDestinationFileWriter", "=", "new", "PrintWriter", "(", "destinationDir", "+", "File", ".", "separator", "+", "destinationFile", ")", ";", "// Store HAR if any, otherwise empty file", "if", "(", "null", "!=", "har", ")", "{", "harDestinationFileWriter", ".", "print", "(", "har", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "harDestinationFileWriter", ".", "print", "(", "\"\"", ")", ";", "}", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "throw", "new", "BMPCUnableToSaveHarToFileException", "(", "e", ")", ";", "}", "finally", "{", "if", "(", "null", "!=", "harDestinationFileWriter", ")", "{", "harDestinationFileWriter", ".", "flush", "(", ")", ";", "harDestinationFileWriter", ".", "close", "(", ")", ";", "}", "}", "}" ]
Utility to store HAR to file. @param har JsonObject containing HAR data @param destinationDir Path to destination Directory @param destinationFile Path to destination File
[ "Utility", "to", "store", "HAR", "to", "file", "." ]
train
https://github.com/detro/browsermob-proxy-client/blob/da03deff8211b7e1153e36100c5ba60acd470a4f/src/main/java/com/github/detro/browsermobproxyclient/BMPCProxy.java#L403-L429
bennidi/mbassador
src/main/java/net/engio/mbassy/common/ReflectionUtils.java
ReflectionUtils.getAnnotation
private static <A extends Annotation> A getAnnotation( AnnotatedElement from, Class<A> annotationType, Set<AnnotatedElement> visited) { """ Searches for an Annotation of the given type on the class. Supports meta annotations. @param from AnnotatedElement (class, method...) @param annotationType Annotation class to look for. @param <A> Class of annotation type @return Annotation instance or null """ if( visited.contains(from) ) return null; visited.add(from); A ann = from.getAnnotation( annotationType ); if( ann != null) return ann; for ( Annotation metaAnn : from.getAnnotations() ) { ann = getAnnotation(metaAnn.annotationType(), annotationType, visited); if ( ann != null ) { return ann; } } return null; }
java
private static <A extends Annotation> A getAnnotation( AnnotatedElement from, Class<A> annotationType, Set<AnnotatedElement> visited) { if( visited.contains(from) ) return null; visited.add(from); A ann = from.getAnnotation( annotationType ); if( ann != null) return ann; for ( Annotation metaAnn : from.getAnnotations() ) { ann = getAnnotation(metaAnn.annotationType(), annotationType, visited); if ( ann != null ) { return ann; } } return null; }
[ "private", "static", "<", "A", "extends", "Annotation", ">", "A", "getAnnotation", "(", "AnnotatedElement", "from", ",", "Class", "<", "A", ">", "annotationType", ",", "Set", "<", "AnnotatedElement", ">", "visited", ")", "{", "if", "(", "visited", ".", "contains", "(", "from", ")", ")", "return", "null", ";", "visited", ".", "add", "(", "from", ")", ";", "A", "ann", "=", "from", ".", "getAnnotation", "(", "annotationType", ")", ";", "if", "(", "ann", "!=", "null", ")", "return", "ann", ";", "for", "(", "Annotation", "metaAnn", ":", "from", ".", "getAnnotations", "(", ")", ")", "{", "ann", "=", "getAnnotation", "(", "metaAnn", ".", "annotationType", "(", ")", ",", "annotationType", ",", "visited", ")", ";", "if", "(", "ann", "!=", "null", ")", "{", "return", "ann", ";", "}", "}", "return", "null", ";", "}" ]
Searches for an Annotation of the given type on the class. Supports meta annotations. @param from AnnotatedElement (class, method...) @param annotationType Annotation class to look for. @param <A> Class of annotation type @return Annotation instance or null
[ "Searches", "for", "an", "Annotation", "of", "the", "given", "type", "on", "the", "class", ".", "Supports", "meta", "annotations", "." ]
train
https://github.com/bennidi/mbassador/blob/60c153fb72868fc31e535852cf0c420022d26c2b/src/main/java/net/engio/mbassy/common/ReflectionUtils.java#L126-L138
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Matchers.expressionStatement
public static Matcher<StatementTree> expressionStatement(final Matcher<ExpressionTree> matcher) { """ Matches an {@link ExpressionStatementTree} based on its {@link ExpressionTree}. """ return new Matcher<StatementTree>() { @Override public boolean matches(StatementTree statementTree, VisitorState state) { return statementTree instanceof ExpressionStatementTree && matcher.matches(((ExpressionStatementTree) statementTree).getExpression(), state); } }; }
java
public static Matcher<StatementTree> expressionStatement(final Matcher<ExpressionTree> matcher) { return new Matcher<StatementTree>() { @Override public boolean matches(StatementTree statementTree, VisitorState state) { return statementTree instanceof ExpressionStatementTree && matcher.matches(((ExpressionStatementTree) statementTree).getExpression(), state); } }; }
[ "public", "static", "Matcher", "<", "StatementTree", ">", "expressionStatement", "(", "final", "Matcher", "<", "ExpressionTree", ">", "matcher", ")", "{", "return", "new", "Matcher", "<", "StatementTree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "StatementTree", "statementTree", ",", "VisitorState", "state", ")", "{", "return", "statementTree", "instanceof", "ExpressionStatementTree", "&&", "matcher", ".", "matches", "(", "(", "(", "ExpressionStatementTree", ")", "statementTree", ")", ".", "getExpression", "(", ")", ",", "state", ")", ";", "}", "}", ";", "}" ]
Matches an {@link ExpressionStatementTree} based on its {@link ExpressionTree}.
[ "Matches", "an", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L1226-L1234
EdwardRaff/JSAT
JSAT/src/jsat/regression/RANSAC.java
RANSAC.setMaxPointError
public void setMaxPointError(double maxPointError) { """ Each data point not in the initial training set will be tested against. If a data points error is sufficiently small, it will be added to the set of inliers. @param maxPointError the new maximum error a data point may have to be considered an inlier. """ if(maxPointError < 0 || Double.isInfinite(maxPointError) || Double.isNaN(maxPointError)) throw new ArithmeticException("The error must be a positive value, not " + maxPointError ); this.maxPointError = maxPointError; }
java
public void setMaxPointError(double maxPointError) { if(maxPointError < 0 || Double.isInfinite(maxPointError) || Double.isNaN(maxPointError)) throw new ArithmeticException("The error must be a positive value, not " + maxPointError ); this.maxPointError = maxPointError; }
[ "public", "void", "setMaxPointError", "(", "double", "maxPointError", ")", "{", "if", "(", "maxPointError", "<", "0", "||", "Double", ".", "isInfinite", "(", "maxPointError", ")", "||", "Double", ".", "isNaN", "(", "maxPointError", ")", ")", "throw", "new", "ArithmeticException", "(", "\"The error must be a positive value, not \"", "+", "maxPointError", ")", ";", "this", ".", "maxPointError", "=", "maxPointError", ";", "}" ]
Each data point not in the initial training set will be tested against. If a data points error is sufficiently small, it will be added to the set of inliers. @param maxPointError the new maximum error a data point may have to be considered an inlier.
[ "Each", "data", "point", "not", "in", "the", "initial", "training", "set", "will", "be", "tested", "against", ".", "If", "a", "data", "points", "error", "is", "sufficiently", "small", "it", "will", "be", "added", "to", "the", "set", "of", "inliers", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/regression/RANSAC.java#L258-L263
xmlunit/xmlunit
xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/Transform.java
Transform.setParameter
public void setParameter(String name, Object value) { """ Add a parameter for the transformation @param name @param value @see Transformer#setParameter(java.lang.String, java.lang.Object) """ parameters.put(name, value); transformation.addParameter(name, value); }
java
public void setParameter(String name, Object value) { parameters.put(name, value); transformation.addParameter(name, value); }
[ "public", "void", "setParameter", "(", "String", "name", ",", "Object", "value", ")", "{", "parameters", ".", "put", "(", "name", ",", "value", ")", ";", "transformation", ".", "addParameter", "(", "name", ",", "value", ")", ";", "}" ]
Add a parameter for the transformation @param name @param value @see Transformer#setParameter(java.lang.String, java.lang.Object)
[ "Add", "a", "parameter", "for", "the", "transformation" ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/Transform.java#L257-L260
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/executiongraph/ExecutionGroupVertex.java
ExecutionGroupVertex.calculateConnectionID
int calculateConnectionID(int currentConnectionID, final Set<ExecutionGroupVertex> alreadyVisited) { """ Recursive method to calculate the connection IDs of the {@link ExecutionGraph}. @param currentConnectionID the current connection ID @param alreadyVisited the set of already visited group vertices @return maximum assigned connectionID """ if (!alreadyVisited.add(this)) { return currentConnectionID; } for (final ExecutionGroupEdge backwardLink : this.backwardLinks) { backwardLink.setConnectionID(currentConnectionID); ++currentConnectionID; currentConnectionID = backwardLink.getSourceVertex() .calculateConnectionID(currentConnectionID, alreadyVisited); } return currentConnectionID; }
java
int calculateConnectionID(int currentConnectionID, final Set<ExecutionGroupVertex> alreadyVisited) { if (!alreadyVisited.add(this)) { return currentConnectionID; } for (final ExecutionGroupEdge backwardLink : this.backwardLinks) { backwardLink.setConnectionID(currentConnectionID); ++currentConnectionID; currentConnectionID = backwardLink.getSourceVertex() .calculateConnectionID(currentConnectionID, alreadyVisited); } return currentConnectionID; }
[ "int", "calculateConnectionID", "(", "int", "currentConnectionID", ",", "final", "Set", "<", "ExecutionGroupVertex", ">", "alreadyVisited", ")", "{", "if", "(", "!", "alreadyVisited", ".", "add", "(", "this", ")", ")", "{", "return", "currentConnectionID", ";", "}", "for", "(", "final", "ExecutionGroupEdge", "backwardLink", ":", "this", ".", "backwardLinks", ")", "{", "backwardLink", ".", "setConnectionID", "(", "currentConnectionID", ")", ";", "++", "currentConnectionID", ";", "currentConnectionID", "=", "backwardLink", ".", "getSourceVertex", "(", ")", ".", "calculateConnectionID", "(", "currentConnectionID", ",", "alreadyVisited", ")", ";", "}", "return", "currentConnectionID", ";", "}" ]
Recursive method to calculate the connection IDs of the {@link ExecutionGraph}. @param currentConnectionID the current connection ID @param alreadyVisited the set of already visited group vertices @return maximum assigned connectionID
[ "Recursive", "method", "to", "calculate", "the", "connection", "IDs", "of", "the", "{", "@link", "ExecutionGraph", "}", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/executiongraph/ExecutionGroupVertex.java#L919-L936
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/ChaincodeCollectionConfiguration.java
ChaincodeCollectionConfiguration.fromFile
private static ChaincodeCollectionConfiguration fromFile(File configFile, boolean isJson) throws InvalidArgumentException, IOException, ChaincodeCollectionConfigurationException { """ Loads a ChaincodeCollectionConfiguration object from a Json or Yaml file """ // Sanity check if (configFile == null) { throw new InvalidArgumentException("configFile must be specified"); } if (logger.isTraceEnabled()) { logger.trace(format("ChaincodeCollectionConfiguration.fromFile: %s isJson = %b", configFile.getAbsolutePath(), isJson)); } // Json file try (InputStream stream = new FileInputStream(configFile)) { return isJson ? fromJsonStream(stream) : fromYamlStream(stream); } }
java
private static ChaincodeCollectionConfiguration fromFile(File configFile, boolean isJson) throws InvalidArgumentException, IOException, ChaincodeCollectionConfigurationException { // Sanity check if (configFile == null) { throw new InvalidArgumentException("configFile must be specified"); } if (logger.isTraceEnabled()) { logger.trace(format("ChaincodeCollectionConfiguration.fromFile: %s isJson = %b", configFile.getAbsolutePath(), isJson)); } // Json file try (InputStream stream = new FileInputStream(configFile)) { return isJson ? fromJsonStream(stream) : fromYamlStream(stream); } }
[ "private", "static", "ChaincodeCollectionConfiguration", "fromFile", "(", "File", "configFile", ",", "boolean", "isJson", ")", "throws", "InvalidArgumentException", ",", "IOException", ",", "ChaincodeCollectionConfigurationException", "{", "// Sanity check", "if", "(", "configFile", "==", "null", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"configFile must be specified\"", ")", ";", "}", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "logger", ".", "trace", "(", "format", "(", "\"ChaincodeCollectionConfiguration.fromFile: %s isJson = %b\"", ",", "configFile", ".", "getAbsolutePath", "(", ")", ",", "isJson", ")", ")", ";", "}", "// Json file", "try", "(", "InputStream", "stream", "=", "new", "FileInputStream", "(", "configFile", ")", ")", "{", "return", "isJson", "?", "fromJsonStream", "(", "stream", ")", ":", "fromYamlStream", "(", "stream", ")", ";", "}", "}" ]
Loads a ChaincodeCollectionConfiguration object from a Json or Yaml file
[ "Loads", "a", "ChaincodeCollectionConfiguration", "object", "from", "a", "Json", "or", "Yaml", "file" ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/ChaincodeCollectionConfiguration.java#L193-L209
gallandarakhneorg/afc
core/maths/mathgen/src/main/java/org/arakhne/afc/math/MathUtil.java
MathUtil.clampCyclic
@Pure public static double clampCyclic(double value, double min, double max) { """ Clamp the given value to fit between the min and max values according to a cyclic heuristic. If the given value is not between the minimum and maximum values, the replied value is modulo the min-max range. @param value the value to clamp. @param min the minimum value inclusive. @param max the maximum value exclusive. @return the clamped value """ assert min <= max : AssertMessages.lowerEqualParameters(1, min, 2, max); if (Double.isNaN(max) || Double.isNaN(min) || Double.isNaN(max)) { return Double.NaN; } if (value < min) { final double perimeter = max - min; final double nvalue = min - value; double rest = perimeter - (nvalue % perimeter); if (rest >= perimeter) { rest -= perimeter; } return min + rest; } else if (value >= max) { final double perimeter = max - min; final double nvalue = value - max; final double rest = nvalue % perimeter; return min + rest; } return value; }
java
@Pure public static double clampCyclic(double value, double min, double max) { assert min <= max : AssertMessages.lowerEqualParameters(1, min, 2, max); if (Double.isNaN(max) || Double.isNaN(min) || Double.isNaN(max)) { return Double.NaN; } if (value < min) { final double perimeter = max - min; final double nvalue = min - value; double rest = perimeter - (nvalue % perimeter); if (rest >= perimeter) { rest -= perimeter; } return min + rest; } else if (value >= max) { final double perimeter = max - min; final double nvalue = value - max; final double rest = nvalue % perimeter; return min + rest; } return value; }
[ "@", "Pure", "public", "static", "double", "clampCyclic", "(", "double", "value", ",", "double", "min", ",", "double", "max", ")", "{", "assert", "min", "<=", "max", ":", "AssertMessages", ".", "lowerEqualParameters", "(", "1", ",", "min", ",", "2", ",", "max", ")", ";", "if", "(", "Double", ".", "isNaN", "(", "max", ")", "||", "Double", ".", "isNaN", "(", "min", ")", "||", "Double", ".", "isNaN", "(", "max", ")", ")", "{", "return", "Double", ".", "NaN", ";", "}", "if", "(", "value", "<", "min", ")", "{", "final", "double", "perimeter", "=", "max", "-", "min", ";", "final", "double", "nvalue", "=", "min", "-", "value", ";", "double", "rest", "=", "perimeter", "-", "(", "nvalue", "%", "perimeter", ")", ";", "if", "(", "rest", ">=", "perimeter", ")", "{", "rest", "-=", "perimeter", ";", "}", "return", "min", "+", "rest", ";", "}", "else", "if", "(", "value", ">=", "max", ")", "{", "final", "double", "perimeter", "=", "max", "-", "min", ";", "final", "double", "nvalue", "=", "value", "-", "max", ";", "final", "double", "rest", "=", "nvalue", "%", "perimeter", ";", "return", "min", "+", "rest", ";", "}", "return", "value", ";", "}" ]
Clamp the given value to fit between the min and max values according to a cyclic heuristic. If the given value is not between the minimum and maximum values, the replied value is modulo the min-max range. @param value the value to clamp. @param min the minimum value inclusive. @param max the maximum value exclusive. @return the clamped value
[ "Clamp", "the", "given", "value", "to", "fit", "between", "the", "min", "and", "max", "values", "according", "to", "a", "cyclic", "heuristic", ".", "If", "the", "given", "value", "is", "not", "between", "the", "minimum", "and", "maximum", "values", "the", "replied", "value", "is", "modulo", "the", "min", "-", "max", "range", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgen/src/main/java/org/arakhne/afc/math/MathUtil.java#L428-L449
aspectran/aspectran
core/src/main/java/com/aspectran/core/util/MethodUtils.java
MethodUtils.invokeGetter
public static Object invokeGetter(Object object, String getterName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { """ Gets an Object property from a bean. @param object the bean @param getterName the property name or getter method name @param args use this arguments @return the property value (as an Object) @throws NoSuchMethodException the no such method exception @throws IllegalAccessException the illegal access exception @throws InvocationTargetException the invocation target exception """ int index = getterName.indexOf('.'); if (index > 0) { String getterName2 = getterName.substring(0, index); Object o = invokeGetter(object, getterName2); return invokeGetter(o, getterName.substring(index + 1), args); } else { if (!getterName.startsWith("get") && !getterName.startsWith("is")) { getterName = "get" + getterName.substring(0, 1).toUpperCase(Locale.US) + getterName.substring(1); } return invokeMethod(object, getterName, args); } }
java
public static Object invokeGetter(Object object, String getterName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { int index = getterName.indexOf('.'); if (index > 0) { String getterName2 = getterName.substring(0, index); Object o = invokeGetter(object, getterName2); return invokeGetter(o, getterName.substring(index + 1), args); } else { if (!getterName.startsWith("get") && !getterName.startsWith("is")) { getterName = "get" + getterName.substring(0, 1).toUpperCase(Locale.US) + getterName.substring(1); } return invokeMethod(object, getterName, args); } }
[ "public", "static", "Object", "invokeGetter", "(", "Object", "object", ",", "String", "getterName", ",", "Object", "[", "]", "args", ")", "throws", "NoSuchMethodException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "int", "index", "=", "getterName", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "index", ">", "0", ")", "{", "String", "getterName2", "=", "getterName", ".", "substring", "(", "0", ",", "index", ")", ";", "Object", "o", "=", "invokeGetter", "(", "object", ",", "getterName2", ")", ";", "return", "invokeGetter", "(", "o", ",", "getterName", ".", "substring", "(", "index", "+", "1", ")", ",", "args", ")", ";", "}", "else", "{", "if", "(", "!", "getterName", ".", "startsWith", "(", "\"get\"", ")", "&&", "!", "getterName", ".", "startsWith", "(", "\"is\"", ")", ")", "{", "getterName", "=", "\"get\"", "+", "getterName", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", "Locale", ".", "US", ")", "+", "getterName", ".", "substring", "(", "1", ")", ";", "}", "return", "invokeMethod", "(", "object", ",", "getterName", ",", "args", ")", ";", "}", "}" ]
Gets an Object property from a bean. @param object the bean @param getterName the property name or getter method name @param args use this arguments @return the property value (as an Object) @throws NoSuchMethodException the no such method exception @throws IllegalAccessException the illegal access exception @throws InvocationTargetException the invocation target exception
[ "Gets", "an", "Object", "property", "from", "a", "bean", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/MethodUtils.java#L127-L140
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ConcurrentLinkedQueue.java
ConcurrentLinkedQueue.updateHead
final void updateHead(Node<E> h, Node<E> p) { """ Tries to CAS head to p. If successful, repoint old head to itself as sentinel for succ(), below. """ // assert h != null && p != null && (h == p || h.item == null); if (h != p && casHead(h, p)) lazySetNext(h, sentinel()); }
java
final void updateHead(Node<E> h, Node<E> p) { // assert h != null && p != null && (h == p || h.item == null); if (h != p && casHead(h, p)) lazySetNext(h, sentinel()); }
[ "final", "void", "updateHead", "(", "Node", "<", "E", ">", "h", ",", "Node", "<", "E", ">", "p", ")", "{", "// assert h != null && p != null && (h == p || h.item == null);", "if", "(", "h", "!=", "p", "&&", "casHead", "(", "h", ",", "p", ")", ")", "lazySetNext", "(", "h", ",", "sentinel", "(", ")", ")", ";", "}" ]
Tries to CAS head to p. If successful, repoint old head to itself as sentinel for succ(), below.
[ "Tries", "to", "CAS", "head", "to", "p", ".", "If", "successful", "repoint", "old", "head", "to", "itself", "as", "sentinel", "for", "succ", "()", "below", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ConcurrentLinkedQueue.java#L287-L291
i-net-software/jlessc
src/com/inet/lib/less/Operation.java
Operation.unitFactor
static double unitFactor( String leftUnit, String rightUnit, boolean fail ) { """ Calculate the factor between 2 units. @param leftUnit left unit @param rightUnit right unit @param fail true, should be fail if units incompatible; false, return 1 is incompatible @return the factor between the 2 units. @throws LessException if unit are incompatible and fail is true """ if( leftUnit.length() == 0 || rightUnit.length() == 0 || leftUnit.equals( rightUnit ) ) { return 1; } HashMap<String, Double> leftGroup = UNIT_CONVERSIONS.get( leftUnit ); if( leftGroup != null ) { HashMap<String, Double> rightGroup = UNIT_CONVERSIONS.get( rightUnit ); if( leftGroup == rightGroup ) { return leftGroup.get( leftUnit ) / leftGroup.get( rightUnit ); } } if( fail ) { throw new LessException( "Incompatible types" ); } return 1; }
java
static double unitFactor( String leftUnit, String rightUnit, boolean fail ) { if( leftUnit.length() == 0 || rightUnit.length() == 0 || leftUnit.equals( rightUnit ) ) { return 1; } HashMap<String, Double> leftGroup = UNIT_CONVERSIONS.get( leftUnit ); if( leftGroup != null ) { HashMap<String, Double> rightGroup = UNIT_CONVERSIONS.get( rightUnit ); if( leftGroup == rightGroup ) { return leftGroup.get( leftUnit ) / leftGroup.get( rightUnit ); } } if( fail ) { throw new LessException( "Incompatible types" ); } return 1; }
[ "static", "double", "unitFactor", "(", "String", "leftUnit", ",", "String", "rightUnit", ",", "boolean", "fail", ")", "{", "if", "(", "leftUnit", ".", "length", "(", ")", "==", "0", "||", "rightUnit", ".", "length", "(", ")", "==", "0", "||", "leftUnit", ".", "equals", "(", "rightUnit", ")", ")", "{", "return", "1", ";", "}", "HashMap", "<", "String", ",", "Double", ">", "leftGroup", "=", "UNIT_CONVERSIONS", ".", "get", "(", "leftUnit", ")", ";", "if", "(", "leftGroup", "!=", "null", ")", "{", "HashMap", "<", "String", ",", "Double", ">", "rightGroup", "=", "UNIT_CONVERSIONS", ".", "get", "(", "rightUnit", ")", ";", "if", "(", "leftGroup", "==", "rightGroup", ")", "{", "return", "leftGroup", ".", "get", "(", "leftUnit", ")", "/", "leftGroup", ".", "get", "(", "rightUnit", ")", ";", "}", "}", "if", "(", "fail", ")", "{", "throw", "new", "LessException", "(", "\"Incompatible types\"", ")", ";", "}", "return", "1", ";", "}" ]
Calculate the factor between 2 units. @param leftUnit left unit @param rightUnit right unit @param fail true, should be fail if units incompatible; false, return 1 is incompatible @return the factor between the 2 units. @throws LessException if unit are incompatible and fail is true
[ "Calculate", "the", "factor", "between", "2", "units", "." ]
train
https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/Operation.java#L299-L314
RestComm/Restcomm-Connect
restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/rcmlserver/resolver/RcmlserverResolver.java
RcmlserverResolver.getInstance
public static RcmlserverResolver getInstance(String rvdOrigin, String apiPath, boolean reinit) { """ not really a clean singleton pattern but a way to init once and use many. Only the first time this method is called the parameters are used in the initialization """ if (singleton == null || reinit) { singleton = new RcmlserverResolver(rvdOrigin, apiPath); } return singleton; }
java
public static RcmlserverResolver getInstance(String rvdOrigin, String apiPath, boolean reinit) { if (singleton == null || reinit) { singleton = new RcmlserverResolver(rvdOrigin, apiPath); } return singleton; }
[ "public", "static", "RcmlserverResolver", "getInstance", "(", "String", "rvdOrigin", ",", "String", "apiPath", ",", "boolean", "reinit", ")", "{", "if", "(", "singleton", "==", "null", "||", "reinit", ")", "{", "singleton", "=", "new", "RcmlserverResolver", "(", "rvdOrigin", ",", "apiPath", ")", ";", "}", "return", "singleton", ";", "}" ]
not really a clean singleton pattern but a way to init once and use many. Only the first time this method is called the parameters are used in the initialization
[ "not", "really", "a", "clean", "singleton", "pattern", "but", "a", "way", "to", "init", "once", "and", "use", "many", ".", "Only", "the", "first", "time", "this", "method", "is", "called", "the", "parameters", "are", "used", "in", "the", "initialization" ]
train
https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/rcmlserver/resolver/RcmlserverResolver.java#L52-L57
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/OutputLayerUtil.java
OutputLayerUtil.validateOutputLayerConfiguration
public static void validateOutputLayerConfiguration(String layerName, long nOut, boolean isLossLayer, IActivation activation, ILossFunction lossFunction) { """ Validate the output layer (or loss layer) configuration, to detect invalid consfiugrations. A DL4JInvalidConfigException will be thrown for invalid configurations (like softmax + nOut=1).<br> <p> If the specified layer is not an output layer, this is a no-op @param layerName Name of the layer @param nOut Number of outputs for the layer @param isLossLayer Should be true for loss layers (no params), false for output layers @param activation Activation function @param lossFunction Loss function """ //nOut = 1 + softmax if(!isLossLayer && nOut == 1 && activation instanceof ActivationSoftmax){ //May not have valid nOut for LossLayer throw new DL4JInvalidConfigException("Invalid output layer configuration for layer \"" + layerName + "\": Softmax + nOut=1 networks " + "are not supported. Softmax cannot be used with nOut=1 as the output will always be exactly 1.0 " + "regardless of the input. " + COMMON_MSG); } //loss function required probability, but activation is outside 0-1 range if(lossFunctionExpectsProbability(lossFunction) && activationExceedsZeroOneRange(activation, isLossLayer)){ throw new DL4JInvalidConfigException("Invalid output layer configuration for layer \"" + layerName + "\": loss function " + lossFunction + " expects activations to be in the range 0 to 1 (probabilities) but activation function " + activation + " does not bound values to this 0 to 1 range. This indicates a likely invalid network configuration. " + COMMON_MSG); } //Common mistake: softmax + xent if(activation instanceof ActivationSoftmax && lossFunction instanceof LossBinaryXENT){ throw new DL4JInvalidConfigException("Invalid output layer configuration for layer \"" + layerName + "\": softmax activation function in combination " + "with LossBinaryXENT (binary cross entropy loss function). For multi-class classification, use softmax + " + "MCXENT (multi-class cross entropy); for binary multi-label classification, use sigmoid + XENT. " + COMMON_MSG); } //Common mistake: sigmoid + mcxent if(activation instanceof ActivationSigmoid && lossFunction instanceof LossMCXENT){ throw new DL4JInvalidConfigException("Invalid output layer configuration for layer \"" + layerName + "\": sigmoid activation function in combination " + "with LossMCXENT (multi-class cross entropy loss function). For multi-class classification, use softmax + " + "MCXENT (multi-class cross entropy); for binary multi-label classification, use sigmoid + XENT. " + COMMON_MSG); } }
java
public static void validateOutputLayerConfiguration(String layerName, long nOut, boolean isLossLayer, IActivation activation, ILossFunction lossFunction){ //nOut = 1 + softmax if(!isLossLayer && nOut == 1 && activation instanceof ActivationSoftmax){ //May not have valid nOut for LossLayer throw new DL4JInvalidConfigException("Invalid output layer configuration for layer \"" + layerName + "\": Softmax + nOut=1 networks " + "are not supported. Softmax cannot be used with nOut=1 as the output will always be exactly 1.0 " + "regardless of the input. " + COMMON_MSG); } //loss function required probability, but activation is outside 0-1 range if(lossFunctionExpectsProbability(lossFunction) && activationExceedsZeroOneRange(activation, isLossLayer)){ throw new DL4JInvalidConfigException("Invalid output layer configuration for layer \"" + layerName + "\": loss function " + lossFunction + " expects activations to be in the range 0 to 1 (probabilities) but activation function " + activation + " does not bound values to this 0 to 1 range. This indicates a likely invalid network configuration. " + COMMON_MSG); } //Common mistake: softmax + xent if(activation instanceof ActivationSoftmax && lossFunction instanceof LossBinaryXENT){ throw new DL4JInvalidConfigException("Invalid output layer configuration for layer \"" + layerName + "\": softmax activation function in combination " + "with LossBinaryXENT (binary cross entropy loss function). For multi-class classification, use softmax + " + "MCXENT (multi-class cross entropy); for binary multi-label classification, use sigmoid + XENT. " + COMMON_MSG); } //Common mistake: sigmoid + mcxent if(activation instanceof ActivationSigmoid && lossFunction instanceof LossMCXENT){ throw new DL4JInvalidConfigException("Invalid output layer configuration for layer \"" + layerName + "\": sigmoid activation function in combination " + "with LossMCXENT (multi-class cross entropy loss function). For multi-class classification, use softmax + " + "MCXENT (multi-class cross entropy); for binary multi-label classification, use sigmoid + XENT. " + COMMON_MSG); } }
[ "public", "static", "void", "validateOutputLayerConfiguration", "(", "String", "layerName", ",", "long", "nOut", ",", "boolean", "isLossLayer", ",", "IActivation", "activation", ",", "ILossFunction", "lossFunction", ")", "{", "//nOut = 1 + softmax", "if", "(", "!", "isLossLayer", "&&", "nOut", "==", "1", "&&", "activation", "instanceof", "ActivationSoftmax", ")", "{", "//May not have valid nOut for LossLayer", "throw", "new", "DL4JInvalidConfigException", "(", "\"Invalid output layer configuration for layer \\\"\"", "+", "layerName", "+", "\"\\\": Softmax + nOut=1 networks \"", "+", "\"are not supported. Softmax cannot be used with nOut=1 as the output will always be exactly 1.0 \"", "+", "\"regardless of the input. \"", "+", "COMMON_MSG", ")", ";", "}", "//loss function required probability, but activation is outside 0-1 range", "if", "(", "lossFunctionExpectsProbability", "(", "lossFunction", ")", "&&", "activationExceedsZeroOneRange", "(", "activation", ",", "isLossLayer", ")", ")", "{", "throw", "new", "DL4JInvalidConfigException", "(", "\"Invalid output layer configuration for layer \\\"\"", "+", "layerName", "+", "\"\\\": loss function \"", "+", "lossFunction", "+", "\" expects activations to be in the range 0 to 1 (probabilities) but activation function \"", "+", "activation", "+", "\" does not bound values to this 0 to 1 range. This indicates a likely invalid network configuration. \"", "+", "COMMON_MSG", ")", ";", "}", "//Common mistake: softmax + xent", "if", "(", "activation", "instanceof", "ActivationSoftmax", "&&", "lossFunction", "instanceof", "LossBinaryXENT", ")", "{", "throw", "new", "DL4JInvalidConfigException", "(", "\"Invalid output layer configuration for layer \\\"\"", "+", "layerName", "+", "\"\\\": softmax activation function in combination \"", "+", "\"with LossBinaryXENT (binary cross entropy loss function). For multi-class classification, use softmax + \"", "+", "\"MCXENT (multi-class cross entropy); for binary multi-label classification, use sigmoid + XENT. \"", "+", "COMMON_MSG", ")", ";", "}", "//Common mistake: sigmoid + mcxent", "if", "(", "activation", "instanceof", "ActivationSigmoid", "&&", "lossFunction", "instanceof", "LossMCXENT", ")", "{", "throw", "new", "DL4JInvalidConfigException", "(", "\"Invalid output layer configuration for layer \\\"\"", "+", "layerName", "+", "\"\\\": sigmoid activation function in combination \"", "+", "\"with LossMCXENT (multi-class cross entropy loss function). For multi-class classification, use softmax + \"", "+", "\"MCXENT (multi-class cross entropy); for binary multi-label classification, use sigmoid + XENT. \"", "+", "COMMON_MSG", ")", ";", "}", "}" ]
Validate the output layer (or loss layer) configuration, to detect invalid consfiugrations. A DL4JInvalidConfigException will be thrown for invalid configurations (like softmax + nOut=1).<br> <p> If the specified layer is not an output layer, this is a no-op @param layerName Name of the layer @param nOut Number of outputs for the layer @param isLossLayer Should be true for loss layers (no params), false for output layers @param activation Activation function @param lossFunction Loss function
[ "Validate", "the", "output", "layer", "(", "or", "loss", "layer", ")", "configuration", "to", "detect", "invalid", "consfiugrations", ".", "A", "DL4JInvalidConfigException", "will", "be", "thrown", "for", "invalid", "configurations", "(", "like", "softmax", "+", "nOut", "=", "1", ")", ".", "<br", ">", "<p", ">", "If", "the", "specified", "layer", "is", "not", "an", "output", "layer", "this", "is", "a", "no", "-", "op" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/OutputLayerUtil.java#L117-L145
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsPatternPanelMonthlyController.java
CmsPatternPanelMonthlyController.setPatternScheme
public void setPatternScheme(final boolean isByWeekDay, final boolean fireChange) { """ Set the pattern scheme to either "by weekday" or "by day of month". @param isByWeekDay flag, indicating if the pattern "by weekday" should be set. @param fireChange flag, indicating if a value change event should be fired. """ if (isByWeekDay ^ (null != m_model.getWeekDay())) { removeExceptionsOnChange(new Command() { public void execute() { if (isByWeekDay) { m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth()); m_model.setWeekDay(getPatternDefaultValues().getWeekDay()); } else { m_model.clearWeekDays(); m_model.clearWeeksOfMonth(); m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth()); } m_model.setInterval(getPatternDefaultValues().getInterval()); if (fireChange) { onValueChange(); } } }); } }
java
public void setPatternScheme(final boolean isByWeekDay, final boolean fireChange) { if (isByWeekDay ^ (null != m_model.getWeekDay())) { removeExceptionsOnChange(new Command() { public void execute() { if (isByWeekDay) { m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth()); m_model.setWeekDay(getPatternDefaultValues().getWeekDay()); } else { m_model.clearWeekDays(); m_model.clearWeeksOfMonth(); m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth()); } m_model.setInterval(getPatternDefaultValues().getInterval()); if (fireChange) { onValueChange(); } } }); } }
[ "public", "void", "setPatternScheme", "(", "final", "boolean", "isByWeekDay", ",", "final", "boolean", "fireChange", ")", "{", "if", "(", "isByWeekDay", "^", "(", "null", "!=", "m_model", ".", "getWeekDay", "(", ")", ")", ")", "{", "removeExceptionsOnChange", "(", "new", "Command", "(", ")", "{", "public", "void", "execute", "(", ")", "{", "if", "(", "isByWeekDay", ")", "{", "m_model", ".", "setWeekOfMonth", "(", "getPatternDefaultValues", "(", ")", ".", "getWeekOfMonth", "(", ")", ")", ";", "m_model", ".", "setWeekDay", "(", "getPatternDefaultValues", "(", ")", ".", "getWeekDay", "(", ")", ")", ";", "}", "else", "{", "m_model", ".", "clearWeekDays", "(", ")", ";", "m_model", ".", "clearWeeksOfMonth", "(", ")", ";", "m_model", ".", "setDayOfMonth", "(", "getPatternDefaultValues", "(", ")", ".", "getDayOfMonth", "(", ")", ")", ";", "}", "m_model", ".", "setInterval", "(", "getPatternDefaultValues", "(", ")", ".", "getInterval", "(", ")", ")", ";", "if", "(", "fireChange", ")", "{", "onValueChange", "(", ")", ";", "}", "}", "}", ")", ";", "}", "}" ]
Set the pattern scheme to either "by weekday" or "by day of month". @param isByWeekDay flag, indicating if the pattern "by weekday" should be set. @param fireChange flag, indicating if a value change event should be fired.
[ "Set", "the", "pattern", "scheme", "to", "either", "by", "weekday", "or", "by", "day", "of", "month", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsPatternPanelMonthlyController.java#L65-L88
jboss/jboss-servlet-api_spec
src/main/java/javax/servlet/http/HttpServletResponseWrapper.java
HttpServletResponseWrapper.setStatus
@Deprecated @Override public void setStatus(int sc, String sm) { """ The default behavior of this method is to call setStatus(int sc, String sm) on the wrapped response object. @deprecated As of version 2.1, due to ambiguous meaning of the message parameter. To set a status code use {@link #setStatus(int)}, to send an error with a description use {@link #sendError(int, String)} """ this._getHttpServletResponse().setStatus(sc, sm); }
java
@Deprecated @Override public void setStatus(int sc, String sm) { this._getHttpServletResponse().setStatus(sc, sm); }
[ "@", "Deprecated", "@", "Override", "public", "void", "setStatus", "(", "int", "sc", ",", "String", "sm", ")", "{", "this", ".", "_getHttpServletResponse", "(", ")", ".", "setStatus", "(", "sc", ",", "sm", ")", ";", "}" ]
The default behavior of this method is to call setStatus(int sc, String sm) on the wrapped response object. @deprecated As of version 2.1, due to ambiguous meaning of the message parameter. To set a status code use {@link #setStatus(int)}, to send an error with a description use {@link #sendError(int, String)}
[ "The", "default", "behavior", "of", "this", "method", "is", "to", "call", "setStatus", "(", "int", "sc", "String", "sm", ")", "on", "the", "wrapped", "response", "object", "." ]
train
https://github.com/jboss/jboss-servlet-api_spec/blob/5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2/src/main/java/javax/servlet/http/HttpServletResponseWrapper.java#L257-L261
geomajas/geomajas-project-graphics
graphics/src/main/java/org/geomajas/graphics/client/widget/SliderBar.java
SliderBar.startSliding
private void startSliding(boolean highlight, boolean fireEvent) { """ Start sliding the knob. @param highlight true to change the style @param fireEvent true to fire the event """ if (highlight) { DOM.setElementProperty(lineElement, "className", SLIDER_LINE + " " + SLIDER_LINE_SLIDING); DOM.setElementProperty(knobImage.getElement(), "className", SLIDER_KNOB + " " + SLIDER_KNOB_SLIDING); } }
java
private void startSliding(boolean highlight, boolean fireEvent) { if (highlight) { DOM.setElementProperty(lineElement, "className", SLIDER_LINE + " " + SLIDER_LINE_SLIDING); DOM.setElementProperty(knobImage.getElement(), "className", SLIDER_KNOB + " " + SLIDER_KNOB_SLIDING); } }
[ "private", "void", "startSliding", "(", "boolean", "highlight", ",", "boolean", "fireEvent", ")", "{", "if", "(", "highlight", ")", "{", "DOM", ".", "setElementProperty", "(", "lineElement", ",", "\"className\"", ",", "SLIDER_LINE", "+", "\" \"", "+", "SLIDER_LINE_SLIDING", ")", ";", "DOM", ".", "setElementProperty", "(", "knobImage", ".", "getElement", "(", ")", ",", "\"className\"", ",", "SLIDER_KNOB", "+", "\" \"", "+", "SLIDER_KNOB_SLIDING", ")", ";", "}", "}" ]
Start sliding the knob. @param highlight true to change the style @param fireEvent true to fire the event
[ "Start", "sliding", "the", "knob", "." ]
train
https://github.com/geomajas/geomajas-project-graphics/blob/1104196640e0ba455b8a619e774352a8e1e319ba/graphics/src/main/java/org/geomajas/graphics/client/widget/SliderBar.java#L928-L935
telegram-s/telegram-mt
src/main/java/org/telegram/mtproto/MTProto.java
MTProto.sendRpcMessage
public int sendRpcMessage(TLMethod request, long timeout, boolean highPriority) { """ Sending rpc request @param request request @param timeout timeout of request @param highPriority is hight priority request @return request id """ int id = scheduller.postMessage(request, true, timeout, highPriority); Logger.d(TAG, "sendMessage #" + id + " " + request.toString() + " with timeout " + timeout + " ms"); return id; }
java
public int sendRpcMessage(TLMethod request, long timeout, boolean highPriority) { int id = scheduller.postMessage(request, true, timeout, highPriority); Logger.d(TAG, "sendMessage #" + id + " " + request.toString() + " with timeout " + timeout + " ms"); return id; }
[ "public", "int", "sendRpcMessage", "(", "TLMethod", "request", ",", "long", "timeout", ",", "boolean", "highPriority", ")", "{", "int", "id", "=", "scheduller", ".", "postMessage", "(", "request", ",", "true", ",", "timeout", ",", "highPriority", ")", ";", "Logger", ".", "d", "(", "TAG", ",", "\"sendMessage #\"", "+", "id", "+", "\" \"", "+", "request", ".", "toString", "(", ")", "+", "\" with timeout \"", "+", "timeout", "+", "\" ms\"", ")", ";", "return", "id", ";", "}" ]
Sending rpc request @param request request @param timeout timeout of request @param highPriority is hight priority request @return request id
[ "Sending", "rpc", "request" ]
train
https://github.com/telegram-s/telegram-mt/blob/57e3f635a6508705081eba9396ae24db050bc943/src/main/java/org/telegram/mtproto/MTProto.java#L264-L268
deephacks/confit
api-runtime/src/main/java/org/deephacks/confit/query/ConfigQueryBuilder.java
ConfigQueryBuilder.lessThan
public static <A extends Comparable<A>> Restriction lessThan(String property, A value) { """ Query which asserts that a property is less than (but not equal to) a value. @param property field to query @param value value to query for @return restriction to be added to {@link ConfigQuery}. """ return new LessThan(property, value); }
java
public static <A extends Comparable<A>> Restriction lessThan(String property, A value) { return new LessThan(property, value); }
[ "public", "static", "<", "A", "extends", "Comparable", "<", "A", ">", ">", "Restriction", "lessThan", "(", "String", "property", ",", "A", "value", ")", "{", "return", "new", "LessThan", "(", "property", ",", "value", ")", ";", "}" ]
Query which asserts that a property is less than (but not equal to) a value. @param property field to query @param value value to query for @return restriction to be added to {@link ConfigQuery}.
[ "Query", "which", "asserts", "that", "a", "property", "is", "less", "than", "(", "but", "not", "equal", "to", ")", "a", "value", "." ]
train
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-runtime/src/main/java/org/deephacks/confit/query/ConfigQueryBuilder.java#L69-L72
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/CheckedExceptionsFactory.java
CheckedExceptionsFactory.newCloneNotSupportedException
public static CloneNotSupportedException newCloneNotSupportedException(String message, Object... args) { """ Constructs and initializes a new {@link CloneNotSupportedException} with the given {@link String message} formatted with the given {@link Object[] arguments}. @param message {@link String} describing the {@link CloneNotSupportedException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link CloneNotSupportedException} with the given {@link String message}. @see #newCloneNotSupportedException(Throwable, String, Object...) @see java.lang.CloneNotSupportedException """ return newCloneNotSupportedException(null, message, args); }
java
public static CloneNotSupportedException newCloneNotSupportedException(String message, Object... args) { return newCloneNotSupportedException(null, message, args); }
[ "public", "static", "CloneNotSupportedException", "newCloneNotSupportedException", "(", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "newCloneNotSupportedException", "(", "null", ",", "message", ",", "args", ")", ";", "}" ]
Constructs and initializes a new {@link CloneNotSupportedException} with the given {@link String message} formatted with the given {@link Object[] arguments}. @param message {@link String} describing the {@link CloneNotSupportedException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link CloneNotSupportedException} with the given {@link String message}. @see #newCloneNotSupportedException(Throwable, String, Object...) @see java.lang.CloneNotSupportedException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "CloneNotSupportedException", "}", "with", "the", "given", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object", "[]", "arguments", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/CheckedExceptionsFactory.java#L45-L47
nohana/Amalgam
amalgam/src/main/java/com/amalgam/graphics/BitmapUtils.java
BitmapUtils.storeOnApplicationPrivateDir
public static boolean storeOnApplicationPrivateDir(Context context, Bitmap bitmap, String filename, Bitmap.CompressFormat format, int quality) { """ Store the bitmap on the application private directory path. @param context the context. @param bitmap to store. @param filename file name. @param format bitmap format. @param quality the quality of the compressed bitmap. @return the compressed bitmap file. """ OutputStream out = null; try { out = new BufferedOutputStream(context.openFileOutput(filename, Context.MODE_PRIVATE)); return bitmap.compress(format, quality, out); } catch (FileNotFoundException e) { Log.e(TAG, "no such file for saving bitmap: ", e); return false; } finally { CloseableUtils.close(out); } }
java
public static boolean storeOnApplicationPrivateDir(Context context, Bitmap bitmap, String filename, Bitmap.CompressFormat format, int quality) { OutputStream out = null; try { out = new BufferedOutputStream(context.openFileOutput(filename, Context.MODE_PRIVATE)); return bitmap.compress(format, quality, out); } catch (FileNotFoundException e) { Log.e(TAG, "no such file for saving bitmap: ", e); return false; } finally { CloseableUtils.close(out); } }
[ "public", "static", "boolean", "storeOnApplicationPrivateDir", "(", "Context", "context", ",", "Bitmap", "bitmap", ",", "String", "filename", ",", "Bitmap", ".", "CompressFormat", "format", ",", "int", "quality", ")", "{", "OutputStream", "out", "=", "null", ";", "try", "{", "out", "=", "new", "BufferedOutputStream", "(", "context", ".", "openFileOutput", "(", "filename", ",", "Context", ".", "MODE_PRIVATE", ")", ")", ";", "return", "bitmap", ".", "compress", "(", "format", ",", "quality", ",", "out", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"no such file for saving bitmap: \"", ",", "e", ")", ";", "return", "false", ";", "}", "finally", "{", "CloseableUtils", ".", "close", "(", "out", ")", ";", "}", "}" ]
Store the bitmap on the application private directory path. @param context the context. @param bitmap to store. @param filename file name. @param format bitmap format. @param quality the quality of the compressed bitmap. @return the compressed bitmap file.
[ "Store", "the", "bitmap", "on", "the", "application", "private", "directory", "path", "." ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/graphics/BitmapUtils.java#L269-L280
apache/groovy
src/main/groovy/groovy/lang/MetaClassImpl.java
MetaClassImpl.chooseMethod
protected Object chooseMethod(String methodName, Object methodOrList, Class[] arguments) { """ Chooses the correct method to use from a list of methods which match by name. @param methodOrList the possible methods to choose from @param arguments the arguments """ Object method = chooseMethodInternal(methodName, methodOrList, arguments); if (method instanceof GeneratedMetaMethod.Proxy) return ((GeneratedMetaMethod.Proxy)method).proxy (); return method; }
java
protected Object chooseMethod(String methodName, Object methodOrList, Class[] arguments) { Object method = chooseMethodInternal(methodName, methodOrList, arguments); if (method instanceof GeneratedMetaMethod.Proxy) return ((GeneratedMetaMethod.Proxy)method).proxy (); return method; }
[ "protected", "Object", "chooseMethod", "(", "String", "methodName", ",", "Object", "methodOrList", ",", "Class", "[", "]", "arguments", ")", "{", "Object", "method", "=", "chooseMethodInternal", "(", "methodName", ",", "methodOrList", ",", "arguments", ")", ";", "if", "(", "method", "instanceof", "GeneratedMetaMethod", ".", "Proxy", ")", "return", "(", "(", "GeneratedMetaMethod", ".", "Proxy", ")", "method", ")", ".", "proxy", "(", ")", ";", "return", "method", ";", "}" ]
Chooses the correct method to use from a list of methods which match by name. @param methodOrList the possible methods to choose from @param arguments the arguments
[ "Chooses", "the", "correct", "method", "to", "use", "from", "a", "list", "of", "methods", "which", "match", "by", "name", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/lang/MetaClassImpl.java#L3248-L3253
jtmelton/appsensor
analysis-engines/appsensor-analysis-rules/src/main/java/org/owasp/appsensor/analysis/AggregateEventAnalysisEngine.java
AggregateEventAnalysisEngine.isThresholdViolated
public boolean isThresholdViolated(Queue<Event> queue, Event tailEvent, Threshold threshold) { """ Determines whether a queue of {@link Event}s crosses a {@link Threshold} in the correct amount of time. @param queue a queue of {@link Event}s @param tailEvent the {@link Event} at the tail of the queue @param threshold the {@link Threshold} to evaluate @return boolean evaluation of the {@link Threshold} """ Interval queueInterval = null; if (queue.size() >= threshold.getCount()) { queueInterval = getQueueInterval(queue, tailEvent); if (queueInterval.toMillis() <= threshold.getInterval().toMillis()) { return true; } } return false; }
java
public boolean isThresholdViolated(Queue<Event> queue, Event tailEvent, Threshold threshold) { Interval queueInterval = null; if (queue.size() >= threshold.getCount()) { queueInterval = getQueueInterval(queue, tailEvent); if (queueInterval.toMillis() <= threshold.getInterval().toMillis()) { return true; } } return false; }
[ "public", "boolean", "isThresholdViolated", "(", "Queue", "<", "Event", ">", "queue", ",", "Event", "tailEvent", ",", "Threshold", "threshold", ")", "{", "Interval", "queueInterval", "=", "null", ";", "if", "(", "queue", ".", "size", "(", ")", ">=", "threshold", ".", "getCount", "(", ")", ")", "{", "queueInterval", "=", "getQueueInterval", "(", "queue", ",", "tailEvent", ")", ";", "if", "(", "queueInterval", ".", "toMillis", "(", ")", "<=", "threshold", ".", "getInterval", "(", ")", ".", "toMillis", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determines whether a queue of {@link Event}s crosses a {@link Threshold} in the correct amount of time. @param queue a queue of {@link Event}s @param tailEvent the {@link Event} at the tail of the queue @param threshold the {@link Threshold} to evaluate @return boolean evaluation of the {@link Threshold}
[ "Determines", "whether", "a", "queue", "of", "{", "@link", "Event", "}", "s", "crosses", "a", "{", "@link", "Threshold", "}", "in", "the", "correct", "amount", "of", "time", "." ]
train
https://github.com/jtmelton/appsensor/blob/c3b4e9ada50fdee974e0d618ec4bdfabc2163798/analysis-engines/appsensor-analysis-rules/src/main/java/org/owasp/appsensor/analysis/AggregateEventAnalysisEngine.java#L219-L231
apache/flink
flink-mesos/src/main/java/org/apache/flink/mesos/entrypoint/MesosEntrypointUtils.java
MesosEntrypointUtils.loadConfiguration
public static Configuration loadConfiguration(Configuration dynamicProperties, Logger log) { """ Loads the global configuration, adds the given dynamic properties configuration, and sets the temp directory paths. @param dynamicProperties dynamic properties to integrate @param log logger instance @return the loaded and adapted global configuration """ Configuration configuration = GlobalConfiguration.loadConfigurationWithDynamicProperties(dynamicProperties); // read the environment variables final Map<String, String> envs = System.getenv(); final String tmpDirs = envs.get(MesosConfigKeys.ENV_FLINK_TMP_DIR); BootstrapTools.updateTmpDirectoriesInConfiguration(configuration, tmpDirs); return configuration; }
java
public static Configuration loadConfiguration(Configuration dynamicProperties, Logger log) { Configuration configuration = GlobalConfiguration.loadConfigurationWithDynamicProperties(dynamicProperties); // read the environment variables final Map<String, String> envs = System.getenv(); final String tmpDirs = envs.get(MesosConfigKeys.ENV_FLINK_TMP_DIR); BootstrapTools.updateTmpDirectoriesInConfiguration(configuration, tmpDirs); return configuration; }
[ "public", "static", "Configuration", "loadConfiguration", "(", "Configuration", "dynamicProperties", ",", "Logger", "log", ")", "{", "Configuration", "configuration", "=", "GlobalConfiguration", ".", "loadConfigurationWithDynamicProperties", "(", "dynamicProperties", ")", ";", "// read the environment variables", "final", "Map", "<", "String", ",", "String", ">", "envs", "=", "System", ".", "getenv", "(", ")", ";", "final", "String", "tmpDirs", "=", "envs", ".", "get", "(", "MesosConfigKeys", ".", "ENV_FLINK_TMP_DIR", ")", ";", "BootstrapTools", ".", "updateTmpDirectoriesInConfiguration", "(", "configuration", ",", "tmpDirs", ")", ";", "return", "configuration", ";", "}" ]
Loads the global configuration, adds the given dynamic properties configuration, and sets the temp directory paths. @param dynamicProperties dynamic properties to integrate @param log logger instance @return the loaded and adapted global configuration
[ "Loads", "the", "global", "configuration", "adds", "the", "given", "dynamic", "properties", "configuration", "and", "sets", "the", "temp", "directory", "paths", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-mesos/src/main/java/org/apache/flink/mesos/entrypoint/MesosEntrypointUtils.java#L169-L180
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatProvider.java
ChatProvider.createTellMessage
protected UserMessage createTellMessage (BodyObject source, String message) { """ Used to create a {@link UserMessage} for the supplied sender. """ return UserMessage.create(source.getVisibleName(), message); }
java
protected UserMessage createTellMessage (BodyObject source, String message) { return UserMessage.create(source.getVisibleName(), message); }
[ "protected", "UserMessage", "createTellMessage", "(", "BodyObject", "source", ",", "String", "message", ")", "{", "return", "UserMessage", ".", "create", "(", "source", ".", "getVisibleName", "(", ")", ",", "message", ")", ";", "}" ]
Used to create a {@link UserMessage} for the supplied sender.
[ "Used", "to", "create", "a", "{" ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatProvider.java#L272-L275
motown-io/motown
ocpp/websocket-json/src/main/java/io/motown/ocpp/websocketjson/OcppJsonService.java
OcppJsonService.changeConfiguration
public void changeConfiguration(ChargingStationId chargingStationId, ConfigurationItem configurationItem, CorrelationToken correlationToken) { """ Send a request to a charging station to change a configuration item. @param chargingStationId the charging station's id. @param configurationItem the configuration item to change. @param correlationToken the token to correlate commands and events that belong together. """ Changeconfiguration changeConfigurationRequest = new Changeconfiguration(); changeConfigurationRequest.setKey(configurationItem.getKey()); changeConfigurationRequest.setValue(configurationItem.getValue()); responseHandlers.put(correlationToken.getToken(), new ChangeConfigurationResponseHandler(configurationItem, correlationToken)); WampMessage wampMessage = new WampMessage(WampMessage.CALL, correlationToken.getToken(), MessageProcUri.CHANGE_CONFIGURATION, changeConfigurationRequest); sendWampMessage(wampMessage, chargingStationId); }
java
public void changeConfiguration(ChargingStationId chargingStationId, ConfigurationItem configurationItem, CorrelationToken correlationToken) { Changeconfiguration changeConfigurationRequest = new Changeconfiguration(); changeConfigurationRequest.setKey(configurationItem.getKey()); changeConfigurationRequest.setValue(configurationItem.getValue()); responseHandlers.put(correlationToken.getToken(), new ChangeConfigurationResponseHandler(configurationItem, correlationToken)); WampMessage wampMessage = new WampMessage(WampMessage.CALL, correlationToken.getToken(), MessageProcUri.CHANGE_CONFIGURATION, changeConfigurationRequest); sendWampMessage(wampMessage, chargingStationId); }
[ "public", "void", "changeConfiguration", "(", "ChargingStationId", "chargingStationId", ",", "ConfigurationItem", "configurationItem", ",", "CorrelationToken", "correlationToken", ")", "{", "Changeconfiguration", "changeConfigurationRequest", "=", "new", "Changeconfiguration", "(", ")", ";", "changeConfigurationRequest", ".", "setKey", "(", "configurationItem", ".", "getKey", "(", ")", ")", ";", "changeConfigurationRequest", ".", "setValue", "(", "configurationItem", ".", "getValue", "(", ")", ")", ";", "responseHandlers", ".", "put", "(", "correlationToken", ".", "getToken", "(", ")", ",", "new", "ChangeConfigurationResponseHandler", "(", "configurationItem", ",", "correlationToken", ")", ")", ";", "WampMessage", "wampMessage", "=", "new", "WampMessage", "(", "WampMessage", ".", "CALL", ",", "correlationToken", ".", "getToken", "(", ")", ",", "MessageProcUri", ".", "CHANGE_CONFIGURATION", ",", "changeConfigurationRequest", ")", ";", "sendWampMessage", "(", "wampMessage", ",", "chargingStationId", ")", ";", "}" ]
Send a request to a charging station to change a configuration item. @param chargingStationId the charging station's id. @param configurationItem the configuration item to change. @param correlationToken the token to correlate commands and events that belong together.
[ "Send", "a", "request", "to", "a", "charging", "station", "to", "change", "a", "configuration", "item", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/websocket-json/src/main/java/io/motown/ocpp/websocketjson/OcppJsonService.java#L111-L120
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/MethodAnnotation.java
MethodAnnotation.fromVisitedMethod
public static MethodAnnotation fromVisitedMethod(PreorderVisitor visitor) { """ Factory method to create a MethodAnnotation from the method the given visitor is currently visiting. @param visitor the BetterVisitor currently visiting the method """ String className = visitor.getDottedClassName(); MethodAnnotation result = new MethodAnnotation(className, visitor.getMethodName(), visitor.getMethodSig(), visitor .getMethod().isStatic()); // Try to find the source lines for the method SourceLineAnnotation srcLines = SourceLineAnnotation.fromVisitedMethod(visitor); result.setSourceLines(srcLines); return result; }
java
public static MethodAnnotation fromVisitedMethod(PreorderVisitor visitor) { String className = visitor.getDottedClassName(); MethodAnnotation result = new MethodAnnotation(className, visitor.getMethodName(), visitor.getMethodSig(), visitor .getMethod().isStatic()); // Try to find the source lines for the method SourceLineAnnotation srcLines = SourceLineAnnotation.fromVisitedMethod(visitor); result.setSourceLines(srcLines); return result; }
[ "public", "static", "MethodAnnotation", "fromVisitedMethod", "(", "PreorderVisitor", "visitor", ")", "{", "String", "className", "=", "visitor", ".", "getDottedClassName", "(", ")", ";", "MethodAnnotation", "result", "=", "new", "MethodAnnotation", "(", "className", ",", "visitor", ".", "getMethodName", "(", ")", ",", "visitor", ".", "getMethodSig", "(", ")", ",", "visitor", ".", "getMethod", "(", ")", ".", "isStatic", "(", ")", ")", ";", "// Try to find the source lines for the method", "SourceLineAnnotation", "srcLines", "=", "SourceLineAnnotation", ".", "fromVisitedMethod", "(", "visitor", ")", ";", "result", ".", "setSourceLines", "(", "srcLines", ")", ";", "return", "result", ";", "}" ]
Factory method to create a MethodAnnotation from the method the given visitor is currently visiting. @param visitor the BetterVisitor currently visiting the method
[ "Factory", "method", "to", "create", "a", "MethodAnnotation", "from", "the", "method", "the", "given", "visitor", "is", "currently", "visiting", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/MethodAnnotation.java#L124-L134
facebookarchive/hadoop-20
src/tools/org/apache/hadoop/tools/DistCp.java
DistCp.getCopier
public static DistCopier getCopier(final Configuration conf, final Arguments args) throws IOException { """ Return a DistCopier object for copying the files. If a MapReduce job is needed, a DistCopier instance will be initialized and returned. If no MapReduce job is needed (for empty directories), all the other work will be done in this function, and NULL will be returned. If caller sees NULL returned, the copying has succeeded. @param conf @param args @return @throws IOException """ DistCopier dc = new DistCopier(conf, args); dc.setupJob(); if (dc.getJobConf() != null) { return dc; } else { return null; } }
java
public static DistCopier getCopier(final Configuration conf, final Arguments args) throws IOException { DistCopier dc = new DistCopier(conf, args); dc.setupJob(); if (dc.getJobConf() != null) { return dc; } else { return null; } }
[ "public", "static", "DistCopier", "getCopier", "(", "final", "Configuration", "conf", ",", "final", "Arguments", "args", ")", "throws", "IOException", "{", "DistCopier", "dc", "=", "new", "DistCopier", "(", "conf", ",", "args", ")", ";", "dc", ".", "setupJob", "(", ")", ";", "if", "(", "dc", ".", "getJobConf", "(", ")", "!=", "null", ")", "{", "return", "dc", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Return a DistCopier object for copying the files. If a MapReduce job is needed, a DistCopier instance will be initialized and returned. If no MapReduce job is needed (for empty directories), all the other work will be done in this function, and NULL will be returned. If caller sees NULL returned, the copying has succeeded. @param conf @param args @return @throws IOException
[ "Return", "a", "DistCopier", "object", "for", "copying", "the", "files", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/tools/org/apache/hadoop/tools/DistCp.java#L1525-L1534
astrapi69/mystic-crypt
crypt-core/src/main/java/de/alpharogroup/crypto/pw/PasswordEncryptor.java
PasswordEncryptor.hashAndHexPassword
public String hashAndHexPassword(final String password, final String salt) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException { """ Hash and hex password with the given salt. @param password the password @param salt the salt @return the generated {@link String} object @throws NoSuchAlgorithmException is thrown if instantiation of the MessageDigest object fails. @throws UnsupportedEncodingException is thrown by get the byte array of the private key String object fails. @throws NoSuchPaddingException is thrown if instantiation of the cypher object fails. @throws InvalidKeyException the invalid key exception is thrown if initialization of the cypher object fails. @throws BadPaddingException is thrown if {@link Cipher#doFinal(byte[])} fails. @throws IllegalBlockSizeException is thrown if {@link Cipher#doFinal(byte[])} fails. @throws InvalidAlgorithmParameterException is thrown if initialization of the cypher object fails. @throws InvalidKeySpecException is thrown if generation of the SecretKey object fails. """ return hashAndHexPassword(password, salt, DEFAULT_ALGORITHM, DEFAULT_CHARSET); }
java
public String hashAndHexPassword(final String password, final String salt) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException { return hashAndHexPassword(password, salt, DEFAULT_ALGORITHM, DEFAULT_CHARSET); }
[ "public", "String", "hashAndHexPassword", "(", "final", "String", "password", ",", "final", "String", "salt", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeyException", ",", "UnsupportedEncodingException", ",", "NoSuchPaddingException", ",", "IllegalBlockSizeException", ",", "BadPaddingException", ",", "InvalidKeySpecException", ",", "InvalidAlgorithmParameterException", "{", "return", "hashAndHexPassword", "(", "password", ",", "salt", ",", "DEFAULT_ALGORITHM", ",", "DEFAULT_CHARSET", ")", ";", "}" ]
Hash and hex password with the given salt. @param password the password @param salt the salt @return the generated {@link String} object @throws NoSuchAlgorithmException is thrown if instantiation of the MessageDigest object fails. @throws UnsupportedEncodingException is thrown by get the byte array of the private key String object fails. @throws NoSuchPaddingException is thrown if instantiation of the cypher object fails. @throws InvalidKeyException the invalid key exception is thrown if initialization of the cypher object fails. @throws BadPaddingException is thrown if {@link Cipher#doFinal(byte[])} fails. @throws IllegalBlockSizeException is thrown if {@link Cipher#doFinal(byte[])} fails. @throws InvalidAlgorithmParameterException is thrown if initialization of the cypher object fails. @throws InvalidKeySpecException is thrown if generation of the SecretKey object fails.
[ "Hash", "and", "hex", "password", "with", "the", "given", "salt", "." ]
train
https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-core/src/main/java/de/alpharogroup/crypto/pw/PasswordEncryptor.java#L148-L154
dwdyer/watchmaker
examples/src/java/main/org/uncommons/watchmaker/examples/monalisa/PolygonImageEvaluator.java
PolygonImageEvaluator.getFitness
public double getFitness(List<ColouredPolygon> candidate, List<? extends List<ColouredPolygon>> population) { """ Render the polygons as an image and then do a pixel-by-pixel comparison against the target image. The fitness score is the total error. A lower score means a closer match. @param candidate The image to evaluate. @param population Not used. @return A number indicating how close the candidate image is to the target image (lower is better). """ // Use one renderer per thread because they are not thread safe. Renderer<List<ColouredPolygon>, BufferedImage> renderer = threadLocalRenderer.get(); if (renderer == null) { renderer = new PolygonImageRenderer(new Dimension(width, height), false, transform); threadLocalRenderer.set(renderer); } BufferedImage candidateImage = renderer.render(candidate); Raster candidateImageData = candidateImage.getData(); int[] candidatePixelValues = new int[targetPixels.length]; candidatePixelValues = (int[]) candidateImageData.getDataElements(0, 0, candidateImageData.getWidth(), candidateImageData.getHeight(), candidatePixelValues); double fitness = 0; for (int i = 0; i < targetPixels.length; i++) { fitness += comparePixels(targetPixels[i], candidatePixelValues[i]); } return fitness; }
java
public double getFitness(List<ColouredPolygon> candidate, List<? extends List<ColouredPolygon>> population) { // Use one renderer per thread because they are not thread safe. Renderer<List<ColouredPolygon>, BufferedImage> renderer = threadLocalRenderer.get(); if (renderer == null) { renderer = new PolygonImageRenderer(new Dimension(width, height), false, transform); threadLocalRenderer.set(renderer); } BufferedImage candidateImage = renderer.render(candidate); Raster candidateImageData = candidateImage.getData(); int[] candidatePixelValues = new int[targetPixels.length]; candidatePixelValues = (int[]) candidateImageData.getDataElements(0, 0, candidateImageData.getWidth(), candidateImageData.getHeight(), candidatePixelValues); double fitness = 0; for (int i = 0; i < targetPixels.length; i++) { fitness += comparePixels(targetPixels[i], candidatePixelValues[i]); } return fitness; }
[ "public", "double", "getFitness", "(", "List", "<", "ColouredPolygon", ">", "candidate", ",", "List", "<", "?", "extends", "List", "<", "ColouredPolygon", ">", ">", "population", ")", "{", "// Use one renderer per thread because they are not thread safe.", "Renderer", "<", "List", "<", "ColouredPolygon", ">", ",", "BufferedImage", ">", "renderer", "=", "threadLocalRenderer", ".", "get", "(", ")", ";", "if", "(", "renderer", "==", "null", ")", "{", "renderer", "=", "new", "PolygonImageRenderer", "(", "new", "Dimension", "(", "width", ",", "height", ")", ",", "false", ",", "transform", ")", ";", "threadLocalRenderer", ".", "set", "(", "renderer", ")", ";", "}", "BufferedImage", "candidateImage", "=", "renderer", ".", "render", "(", "candidate", ")", ";", "Raster", "candidateImageData", "=", "candidateImage", ".", "getData", "(", ")", ";", "int", "[", "]", "candidatePixelValues", "=", "new", "int", "[", "targetPixels", ".", "length", "]", ";", "candidatePixelValues", "=", "(", "int", "[", "]", ")", "candidateImageData", ".", "getDataElements", "(", "0", ",", "0", ",", "candidateImageData", ".", "getWidth", "(", ")", ",", "candidateImageData", ".", "getHeight", "(", ")", ",", "candidatePixelValues", ")", ";", "double", "fitness", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "targetPixels", ".", "length", ";", "i", "++", ")", "{", "fitness", "+=", "comparePixels", "(", "targetPixels", "[", "i", "]", ",", "candidatePixelValues", "[", "i", "]", ")", ";", "}", "return", "fitness", ";", "}" ]
Render the polygons as an image and then do a pixel-by-pixel comparison against the target image. The fitness score is the total error. A lower score means a closer match. @param candidate The image to evaluate. @param population Not used. @return A number indicating how close the candidate image is to the target image (lower is better).
[ "Render", "the", "polygons", "as", "an", "image", "and", "then", "do", "a", "pixel", "-", "by", "-", "pixel", "comparison", "against", "the", "target", "image", ".", "The", "fitness", "score", "is", "the", "total", "error", ".", "A", "lower", "score", "means", "a", "closer", "match", "." ]
train
https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/examples/src/java/main/org/uncommons/watchmaker/examples/monalisa/PolygonImageEvaluator.java#L113-L142
samskivert/samskivert
src/main/java/com/samskivert/util/CollectionUtil.java
CollectionUtil.maxList
public static <T> List<T> maxList (Iterable<T> iterable, Comparator<? super T> comp) { """ Return a List containing all the elements of the specified Iterable that compare as being equal to the maximum element. @throws NoSuchElementException if the Iterable is empty. """ Iterator<T> itr = iterable.iterator(); T max = itr.next(); List<T> maxes = new ArrayList<T>(); maxes.add(max); if (itr.hasNext()) { do { T elem = itr.next(); int cmp = comp.compare(max, elem); if (cmp <= 0) { if (cmp < 0) { max = elem; maxes.clear(); } maxes.add(elem); } } while (itr.hasNext()); } else if (0 != comp.compare(max, max)) { // The main point of this test is to compare the sole element to something, // in case it turns out to be incompatible with the Comparator for some reason. // In that case, we don't even get to this IAE, we've probably already bombed out // with an NPE or CCE. For example, the Comparable version could be called with // a sole element of null. (Collections.max() gets this wrong.) throw new IllegalArgumentException(); } return maxes; }
java
public static <T> List<T> maxList (Iterable<T> iterable, Comparator<? super T> comp) { Iterator<T> itr = iterable.iterator(); T max = itr.next(); List<T> maxes = new ArrayList<T>(); maxes.add(max); if (itr.hasNext()) { do { T elem = itr.next(); int cmp = comp.compare(max, elem); if (cmp <= 0) { if (cmp < 0) { max = elem; maxes.clear(); } maxes.add(elem); } } while (itr.hasNext()); } else if (0 != comp.compare(max, max)) { // The main point of this test is to compare the sole element to something, // in case it turns out to be incompatible with the Comparator for some reason. // In that case, we don't even get to this IAE, we've probably already bombed out // with an NPE or CCE. For example, the Comparable version could be called with // a sole element of null. (Collections.max() gets this wrong.) throw new IllegalArgumentException(); } return maxes; }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "maxList", "(", "Iterable", "<", "T", ">", "iterable", ",", "Comparator", "<", "?", "super", "T", ">", "comp", ")", "{", "Iterator", "<", "T", ">", "itr", "=", "iterable", ".", "iterator", "(", ")", ";", "T", "max", "=", "itr", ".", "next", "(", ")", ";", "List", "<", "T", ">", "maxes", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "maxes", ".", "add", "(", "max", ")", ";", "if", "(", "itr", ".", "hasNext", "(", ")", ")", "{", "do", "{", "T", "elem", "=", "itr", ".", "next", "(", ")", ";", "int", "cmp", "=", "comp", ".", "compare", "(", "max", ",", "elem", ")", ";", "if", "(", "cmp", "<=", "0", ")", "{", "if", "(", "cmp", "<", "0", ")", "{", "max", "=", "elem", ";", "maxes", ".", "clear", "(", ")", ";", "}", "maxes", ".", "add", "(", "elem", ")", ";", "}", "}", "while", "(", "itr", ".", "hasNext", "(", ")", ")", ";", "}", "else", "if", "(", "0", "!=", "comp", ".", "compare", "(", "max", ",", "max", ")", ")", "{", "// The main point of this test is to compare the sole element to something,", "// in case it turns out to be incompatible with the Comparator for some reason.", "// In that case, we don't even get to this IAE, we've probably already bombed out", "// with an NPE or CCE. For example, the Comparable version could be called with", "// a sole element of null. (Collections.max() gets this wrong.)", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "return", "maxes", ";", "}" ]
Return a List containing all the elements of the specified Iterable that compare as being equal to the maximum element. @throws NoSuchElementException if the Iterable is empty.
[ "Return", "a", "List", "containing", "all", "the", "elements", "of", "the", "specified", "Iterable", "that", "compare", "as", "being", "equal", "to", "the", "maximum", "element", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/CollectionUtil.java#L138-L166
carewebframework/carewebframework-core
org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/domain/DomainFactoryRegistry.java
DomainFactoryRegistry.fetchObject
public static <T> T fetchObject(Class<T> clazz, String id) { """ Fetches an object, identified by its unique id, from the underlying data store. @param <T> Class of domain object. @param clazz Class of object to create. @param id Unique id of the object. @return The requested object. """ return getFactory(clazz).fetchObject(clazz, id); }
java
public static <T> T fetchObject(Class<T> clazz, String id) { return getFactory(clazz).fetchObject(clazz, id); }
[ "public", "static", "<", "T", ">", "T", "fetchObject", "(", "Class", "<", "T", ">", "clazz", ",", "String", "id", ")", "{", "return", "getFactory", "(", "clazz", ")", ".", "fetchObject", "(", "clazz", ",", "id", ")", ";", "}" ]
Fetches an object, identified by its unique id, from the underlying data store. @param <T> Class of domain object. @param clazz Class of object to create. @param id Unique id of the object. @return The requested object.
[ "Fetches", "an", "object", "identified", "by", "its", "unique", "id", "from", "the", "underlying", "data", "store", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/domain/DomainFactoryRegistry.java#L64-L66
james-hu/jabb-core
src/main/java/net/sf/jabb/util/col/MapLister.java
MapLister.listToString
public static String listToString(Map<?, ?> map) { """ Print the content of the Map in a newly created String, entries are sorted by key, formatted as "key\t= value\n".<br> 把Map里的内容列在String里,Map里的每个entry占一行,按key排序, 每行的格式为“key\t= value\n”。 @param map The Map object for which the content need to be listed.<br> 需要列出内容的Map对象 @return A String that holds formated content of the Map.<br> 含有格式化过的Map内容的String """ if (map == null){ return "null"; } TreeMap<?, ?> tm = new TreeMap<Object, Object>(map); StringBuilder sb = new StringBuilder(); for (Map.Entry<?, ?> item: tm.entrySet()){ Object k = item.getKey(); Object v = item.getValue(); sb.append(k == null ? "null" : k.toString()); sb.append("\t= "); sb.append(v == null ? "null" : v.toString()); sb.append('\n'); } return sb.toString(); }
java
public static String listToString(Map<?, ?> map){ if (map == null){ return "null"; } TreeMap<?, ?> tm = new TreeMap<Object, Object>(map); StringBuilder sb = new StringBuilder(); for (Map.Entry<?, ?> item: tm.entrySet()){ Object k = item.getKey(); Object v = item.getValue(); sb.append(k == null ? "null" : k.toString()); sb.append("\t= "); sb.append(v == null ? "null" : v.toString()); sb.append('\n'); } return sb.toString(); }
[ "public", "static", "String", "listToString", "(", "Map", "<", "?", ",", "?", ">", "map", ")", "{", "if", "(", "map", "==", "null", ")", "{", "return", "\"null\"", ";", "}", "TreeMap", "<", "?", ",", "?", ">", "tm", "=", "new", "TreeMap", "<", "Object", ",", "Object", ">", "(", "map", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "?", ",", "?", ">", "item", ":", "tm", ".", "entrySet", "(", ")", ")", "{", "Object", "k", "=", "item", ".", "getKey", "(", ")", ";", "Object", "v", "=", "item", ".", "getValue", "(", ")", ";", "sb", ".", "append", "(", "k", "==", "null", "?", "\"null\"", ":", "k", ".", "toString", "(", ")", ")", ";", "sb", ".", "append", "(", "\"\\t= \"", ")", ";", "sb", ".", "append", "(", "v", "==", "null", "?", "\"null\"", ":", "v", ".", "toString", "(", ")", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Print the content of the Map in a newly created String, entries are sorted by key, formatted as "key\t= value\n".<br> 把Map里的内容列在String里,Map里的每个entry占一行,按key排序, 每行的格式为“key\t= value\n”。 @param map The Map object for which the content need to be listed.<br> 需要列出内容的Map对象 @return A String that holds formated content of the Map.<br> 含有格式化过的Map内容的String
[ "Print", "the", "content", "of", "the", "Map", "in", "a", "newly", "created", "String", "entries", "are", "sorted", "by", "key", "formatted", "as", "key", "\\", "t", "=", "value", "\\", "n", ".", "<br", ">", "把Map里的内容列在String里,Map里的每个entry占一行,按key排序,", "每行的格式为“key", "\\", "t", "=", "value", "\\", "n”。" ]
train
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/col/MapLister.java#L41-L56
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/validation/CsvExceptionConverter.java
CsvExceptionConverter.convertAndFormat
public List<String> convertAndFormat(final SuperCsvException exception, final BeanMapping<?> beanMapping) { """ 例外をエラーオブジェクトに変換し、さらに、エラーオブジェジェクトをメッセージにフォーマットする。 @param exception 変換するSuperCsvの例外。 @param beanMapping Beanの定義情報 @return フォーマットされたメッセージ。 @throws NullPointerException {@literal exception or beanMapping is null.} """ return convert(exception, beanMapping).stream() .map(error -> error.format(messageResolver, messageInterpolator)) .collect(Collectors.toList()); }
java
public List<String> convertAndFormat(final SuperCsvException exception, final BeanMapping<?> beanMapping) { return convert(exception, beanMapping).stream() .map(error -> error.format(messageResolver, messageInterpolator)) .collect(Collectors.toList()); }
[ "public", "List", "<", "String", ">", "convertAndFormat", "(", "final", "SuperCsvException", "exception", ",", "final", "BeanMapping", "<", "?", ">", "beanMapping", ")", "{", "return", "convert", "(", "exception", ",", "beanMapping", ")", ".", "stream", "(", ")", ".", "map", "(", "error", "->", "error", ".", "format", "(", "messageResolver", ",", "messageInterpolator", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
例外をエラーオブジェクトに変換し、さらに、エラーオブジェジェクトをメッセージにフォーマットする。 @param exception 変換するSuperCsvの例外。 @param beanMapping Beanの定義情報 @return フォーマットされたメッセージ。 @throws NullPointerException {@literal exception or beanMapping is null.}
[ "例外をエラーオブジェクトに変換し、さらに、エラーオブジェジェクトをメッセージにフォーマットする。" ]
train
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/validation/CsvExceptionConverter.java#L53-L58
apache/groovy
src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java
InvokerHelper.setProperty2
public static void setProperty2(Object newValue, Object object, String property) { """ This is so we don't have to reorder the stack when we call this method. At some point a better name might be in order. """ setProperty(object, property, newValue); }
java
public static void setProperty2(Object newValue, Object object, String property) { setProperty(object, property, newValue); }
[ "public", "static", "void", "setProperty2", "(", "Object", "newValue", ",", "Object", "object", ",", "String", "property", ")", "{", "setProperty", "(", "object", ",", "property", ",", "newValue", ")", ";", "}" ]
This is so we don't have to reorder the stack when we call this method. At some point a better name might be in order.
[ "This", "is", "so", "we", "don", "t", "have", "to", "reorder", "the", "stack", "when", "we", "call", "this", "method", ".", "At", "some", "point", "a", "better", "name", "might", "be", "in", "order", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java#L227-L229
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java
ParseUtils.unexpectedAttribute
public static XMLStreamException unexpectedAttribute(final XMLExtendedStreamReader reader, final int index) { """ Get an exception reporting an unexpected XML attribute. @param reader the stream reader @param index the attribute index @return the exception """ final XMLStreamException ex = ControllerLogger.ROOT_LOGGER.unexpectedAttribute(reader.getAttributeName(index), reader.getLocation()); return new XMLStreamValidationException(ex.getMessage(), ValidationError.from(ex, ErrorType.UNEXPECTED_ATTRIBUTE) .element(reader.getName()) .attribute(reader.getAttributeName(index)), ex); }
java
public static XMLStreamException unexpectedAttribute(final XMLExtendedStreamReader reader, final int index) { final XMLStreamException ex = ControllerLogger.ROOT_LOGGER.unexpectedAttribute(reader.getAttributeName(index), reader.getLocation()); return new XMLStreamValidationException(ex.getMessage(), ValidationError.from(ex, ErrorType.UNEXPECTED_ATTRIBUTE) .element(reader.getName()) .attribute(reader.getAttributeName(index)), ex); }
[ "public", "static", "XMLStreamException", "unexpectedAttribute", "(", "final", "XMLExtendedStreamReader", "reader", ",", "final", "int", "index", ")", "{", "final", "XMLStreamException", "ex", "=", "ControllerLogger", ".", "ROOT_LOGGER", ".", "unexpectedAttribute", "(", "reader", ".", "getAttributeName", "(", "index", ")", ",", "reader", ".", "getLocation", "(", ")", ")", ";", "return", "new", "XMLStreamValidationException", "(", "ex", ".", "getMessage", "(", ")", ",", "ValidationError", ".", "from", "(", "ex", ",", "ErrorType", ".", "UNEXPECTED_ATTRIBUTE", ")", ".", "element", "(", "reader", ".", "getName", "(", ")", ")", ".", "attribute", "(", "reader", ".", "getAttributeName", "(", "index", ")", ")", ",", "ex", ")", ";", "}" ]
Get an exception reporting an unexpected XML attribute. @param reader the stream reader @param index the attribute index @return the exception
[ "Get", "an", "exception", "reporting", "an", "unexpected", "XML", "attribute", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java#L134-L142
raphw/byte-buddy
byte-buddy-maven-plugin/src/main/java/net/bytebuddy/build/maven/ClassLoaderResolver.java
ClassLoaderResolver.doResolve
private ClassLoader doResolve(MavenCoordinate mavenCoordinate) throws MojoExecutionException, MojoFailureException { """ Resolves a Maven coordinate to a class loader that can load all of the coordinates classes. @param mavenCoordinate The Maven coordinate to resolve. @return A class loader that references all of the class loader's dependencies and which is a child of this class's class loader. @throws MojoExecutionException If the user configuration results in an error. @throws MojoFailureException If the plugin application raises an error. """ List<URL> urls = new ArrayList<URL>(); log.info("Resolving transformer dependency: " + mavenCoordinate); try { DependencyNode root = repositorySystem.collectDependencies(repositorySystemSession, new CollectRequest(new Dependency(mavenCoordinate.asArtifact(), "runtime"), remoteRepositories)).getRoot(); repositorySystem.resolveDependencies(repositorySystemSession, new DependencyRequest().setRoot(root)); PreorderNodeListGenerator preorderNodeListGenerator = new PreorderNodeListGenerator(); root.accept(preorderNodeListGenerator); for (Artifact artifact : preorderNodeListGenerator.getArtifacts(false)) { urls.add(artifact.getFile().toURI().toURL()); } } catch (DependencyCollectionException exception) { throw new MojoExecutionException("Could not collect dependencies for " + mavenCoordinate, exception); } catch (DependencyResolutionException exception) { throw new MojoExecutionException("Could not resolve dependencies for " + mavenCoordinate, exception); } catch (MalformedURLException exception) { throw new MojoFailureException("Could not resolve file as URL for " + mavenCoordinate, exception); } return new URLClassLoader(urls.toArray(new URL[0]), ByteBuddy.class.getClassLoader()); }
java
private ClassLoader doResolve(MavenCoordinate mavenCoordinate) throws MojoExecutionException, MojoFailureException { List<URL> urls = new ArrayList<URL>(); log.info("Resolving transformer dependency: " + mavenCoordinate); try { DependencyNode root = repositorySystem.collectDependencies(repositorySystemSession, new CollectRequest(new Dependency(mavenCoordinate.asArtifact(), "runtime"), remoteRepositories)).getRoot(); repositorySystem.resolveDependencies(repositorySystemSession, new DependencyRequest().setRoot(root)); PreorderNodeListGenerator preorderNodeListGenerator = new PreorderNodeListGenerator(); root.accept(preorderNodeListGenerator); for (Artifact artifact : preorderNodeListGenerator.getArtifacts(false)) { urls.add(artifact.getFile().toURI().toURL()); } } catch (DependencyCollectionException exception) { throw new MojoExecutionException("Could not collect dependencies for " + mavenCoordinate, exception); } catch (DependencyResolutionException exception) { throw new MojoExecutionException("Could not resolve dependencies for " + mavenCoordinate, exception); } catch (MalformedURLException exception) { throw new MojoFailureException("Could not resolve file as URL for " + mavenCoordinate, exception); } return new URLClassLoader(urls.toArray(new URL[0]), ByteBuddy.class.getClassLoader()); }
[ "private", "ClassLoader", "doResolve", "(", "MavenCoordinate", "mavenCoordinate", ")", "throws", "MojoExecutionException", ",", "MojoFailureException", "{", "List", "<", "URL", ">", "urls", "=", "new", "ArrayList", "<", "URL", ">", "(", ")", ";", "log", ".", "info", "(", "\"Resolving transformer dependency: \"", "+", "mavenCoordinate", ")", ";", "try", "{", "DependencyNode", "root", "=", "repositorySystem", ".", "collectDependencies", "(", "repositorySystemSession", ",", "new", "CollectRequest", "(", "new", "Dependency", "(", "mavenCoordinate", ".", "asArtifact", "(", ")", ",", "\"runtime\"", ")", ",", "remoteRepositories", ")", ")", ".", "getRoot", "(", ")", ";", "repositorySystem", ".", "resolveDependencies", "(", "repositorySystemSession", ",", "new", "DependencyRequest", "(", ")", ".", "setRoot", "(", "root", ")", ")", ";", "PreorderNodeListGenerator", "preorderNodeListGenerator", "=", "new", "PreorderNodeListGenerator", "(", ")", ";", "root", ".", "accept", "(", "preorderNodeListGenerator", ")", ";", "for", "(", "Artifact", "artifact", ":", "preorderNodeListGenerator", ".", "getArtifacts", "(", "false", ")", ")", "{", "urls", ".", "add", "(", "artifact", ".", "getFile", "(", ")", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ")", ";", "}", "}", "catch", "(", "DependencyCollectionException", "exception", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Could not collect dependencies for \"", "+", "mavenCoordinate", ",", "exception", ")", ";", "}", "catch", "(", "DependencyResolutionException", "exception", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Could not resolve dependencies for \"", "+", "mavenCoordinate", ",", "exception", ")", ";", "}", "catch", "(", "MalformedURLException", "exception", ")", "{", "throw", "new", "MojoFailureException", "(", "\"Could not resolve file as URL for \"", "+", "mavenCoordinate", ",", "exception", ")", ";", "}", "return", "new", "URLClassLoader", "(", "urls", ".", "toArray", "(", "new", "URL", "[", "0", "]", ")", ",", "ByteBuddy", ".", "class", ".", "getClassLoader", "(", ")", ")", ";", "}" ]
Resolves a Maven coordinate to a class loader that can load all of the coordinates classes. @param mavenCoordinate The Maven coordinate to resolve. @return A class loader that references all of the class loader's dependencies and which is a child of this class's class loader. @throws MojoExecutionException If the user configuration results in an error. @throws MojoFailureException If the plugin application raises an error.
[ "Resolves", "a", "Maven", "coordinate", "to", "a", "class", "loader", "that", "can", "load", "all", "of", "the", "coordinates", "classes", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-maven-plugin/src/main/java/net/bytebuddy/build/maven/ClassLoaderResolver.java#L117-L136
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java
SDMath.zeroFraction
public SDVariable zeroFraction(String name, SDVariable input) { """ Full array zero fraction array reduction operation, optionally along specified dimensions: out = (count(x == 0) / length(x)) @param name Name of the output variable @param input Input variable @return Reduced array of rank 0 (scalar) """ validateNumerical("zeroFraction", input); SDVariable res = f().zeroFraction(input); return updateVariableNameAndReference(res, name); }
java
public SDVariable zeroFraction(String name, SDVariable input) { validateNumerical("zeroFraction", input); SDVariable res = f().zeroFraction(input); return updateVariableNameAndReference(res, name); }
[ "public", "SDVariable", "zeroFraction", "(", "String", "name", ",", "SDVariable", "input", ")", "{", "validateNumerical", "(", "\"zeroFraction\"", ",", "input", ")", ";", "SDVariable", "res", "=", "f", "(", ")", ".", "zeroFraction", "(", "input", ")", ";", "return", "updateVariableNameAndReference", "(", "res", ",", "name", ")", ";", "}" ]
Full array zero fraction array reduction operation, optionally along specified dimensions: out = (count(x == 0) / length(x)) @param name Name of the output variable @param input Input variable @return Reduced array of rank 0 (scalar)
[ "Full", "array", "zero", "fraction", "array", "reduction", "operation", "optionally", "along", "specified", "dimensions", ":", "out", "=", "(", "count", "(", "x", "==", "0", ")", "/", "length", "(", "x", "))" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java#L2406-L2410
xetorthio/jedis
src/main/java/redis/clients/jedis/BinaryJedis.java
BinaryJedis.incrByFloat
@Override public Double incrByFloat(final byte[] key, final double increment) { """ INCRBYFLOAT work just like {@link #incrBy(byte[], long)} INCRBY} but increments by floats instead of integers. <p> INCRBYFLOAT commands are limited to double precision floating point values. <p> Note: this is actually a string operation, that is, in Redis there are not "double" types. Simply the string stored at the key is parsed as a base double precision floating point value, incremented, and then converted back as a string. There is no DECRYBYFLOAT but providing a negative value will work as expected. <p> Time complexity: O(1) @see #incr(byte[]) @see #decr(byte[]) @see #decrBy(byte[], long) @param key the key to increment @param increment the value to increment by @return Integer reply, this commands will reply with the new value of key after the increment. """ checkIsInMultiOrPipeline(); client.incrByFloat(key, increment); String dval = client.getBulkReply(); return (dval != null ? new Double(dval) : null); }
java
@Override public Double incrByFloat(final byte[] key, final double increment) { checkIsInMultiOrPipeline(); client.incrByFloat(key, increment); String dval = client.getBulkReply(); return (dval != null ? new Double(dval) : null); }
[ "@", "Override", "public", "Double", "incrByFloat", "(", "final", "byte", "[", "]", "key", ",", "final", "double", "increment", ")", "{", "checkIsInMultiOrPipeline", "(", ")", ";", "client", ".", "incrByFloat", "(", "key", ",", "increment", ")", ";", "String", "dval", "=", "client", ".", "getBulkReply", "(", ")", ";", "return", "(", "dval", "!=", "null", "?", "new", "Double", "(", "dval", ")", ":", "null", ")", ";", "}" ]
INCRBYFLOAT work just like {@link #incrBy(byte[], long)} INCRBY} but increments by floats instead of integers. <p> INCRBYFLOAT commands are limited to double precision floating point values. <p> Note: this is actually a string operation, that is, in Redis there are not "double" types. Simply the string stored at the key is parsed as a base double precision floating point value, incremented, and then converted back as a string. There is no DECRYBYFLOAT but providing a negative value will work as expected. <p> Time complexity: O(1) @see #incr(byte[]) @see #decr(byte[]) @see #decrBy(byte[], long) @param key the key to increment @param increment the value to increment by @return Integer reply, this commands will reply with the new value of key after the increment.
[ "INCRBYFLOAT", "work", "just", "like", "{" ]
train
https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/BinaryJedis.java#L807-L813
Azure/azure-sdk-for-java
kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java
ClustersInner.startAsync
public Observable<Void> startAsync(String resourceGroupName, String clusterName) { """ Starts a Kusto cluster. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return startWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> startAsync(String resourceGroupName, String clusterName) { return startWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "startAsync", "(", "String", "resourceGroupName", ",", "String", "clusterName", ")", "{", "return", "startWithServiceResponseAsync", "(", "resourceGroupName", ",", "clusterName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Starts a Kusto cluster. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Starts", "a", "Kusto", "cluster", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java#L907-L914
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/security/auth/authorizer/DRPCAuthorizerBase.java
DRPCAuthorizerBase.permit
@Override public boolean permit(ReqContext context, String operation, Map params) { """ Authorizes request from to the DRPC server. @param context the client request context @param operation the operation requested by the DRPC server @param params a Map with any key-value entries of use to the authorization implementation """ if ("execute".equals(operation)) { return permitClientRequest(context, operation, params); } else if ("failRequest".equals(operation) || "fetchRequest".equals(operation) || "result".equals(operation)) { return permitInvocationRequest(context, operation, params); } // Deny unsupported operations. LOG.warn("Denying unsupported operation \"" + operation + "\" from " + context.remoteAddress()); return false; }
java
@Override public boolean permit(ReqContext context, String operation, Map params) { if ("execute".equals(operation)) { return permitClientRequest(context, operation, params); } else if ("failRequest".equals(operation) || "fetchRequest".equals(operation) || "result".equals(operation)) { return permitInvocationRequest(context, operation, params); } // Deny unsupported operations. LOG.warn("Denying unsupported operation \"" + operation + "\" from " + context.remoteAddress()); return false; }
[ "@", "Override", "public", "boolean", "permit", "(", "ReqContext", "context", ",", "String", "operation", ",", "Map", "params", ")", "{", "if", "(", "\"execute\"", ".", "equals", "(", "operation", ")", ")", "{", "return", "permitClientRequest", "(", "context", ",", "operation", ",", "params", ")", ";", "}", "else", "if", "(", "\"failRequest\"", ".", "equals", "(", "operation", ")", "||", "\"fetchRequest\"", ".", "equals", "(", "operation", ")", "||", "\"result\"", ".", "equals", "(", "operation", ")", ")", "{", "return", "permitInvocationRequest", "(", "context", ",", "operation", ",", "params", ")", ";", "}", "// Deny unsupported operations.", "LOG", ".", "warn", "(", "\"Denying unsupported operation \\\"\"", "+", "operation", "+", "\"\\\" from \"", "+", "context", ".", "remoteAddress", "(", ")", ")", ";", "return", "false", ";", "}" ]
Authorizes request from to the DRPC server. @param context the client request context @param operation the operation requested by the DRPC server @param params a Map with any key-value entries of use to the authorization implementation
[ "Authorizes", "request", "from", "to", "the", "DRPC", "server", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/security/auth/authorizer/DRPCAuthorizerBase.java#L50-L60
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/registry/OperationTransformerRegistry.java
OperationTransformerRegistry.resolveOperationTransformer
public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) { """ Resolve an operation transformer entry. @param address the address @param operationName the operation name @param placeholderResolver a placeholder resolver used to resolve children of a placeholder registration @return the transformer entry """ final Iterator<PathElement> iterator = address.iterator(); final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver); if(entry != null) { return entry; } // Default is forward unchanged return FORWARD; }
java
public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) { final Iterator<PathElement> iterator = address.iterator(); final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver); if(entry != null) { return entry; } // Default is forward unchanged return FORWARD; }
[ "public", "OperationTransformerEntry", "resolveOperationTransformer", "(", "final", "PathAddress", "address", ",", "final", "String", "operationName", ",", "PlaceholderResolver", "placeholderResolver", ")", "{", "final", "Iterator", "<", "PathElement", ">", "iterator", "=", "address", ".", "iterator", "(", ")", ";", "final", "OperationTransformerEntry", "entry", "=", "resolveOperationTransformer", "(", "iterator", ",", "operationName", ",", "placeholderResolver", ")", ";", "if", "(", "entry", "!=", "null", ")", "{", "return", "entry", ";", "}", "// Default is forward unchanged", "return", "FORWARD", ";", "}" ]
Resolve an operation transformer entry. @param address the address @param operationName the operation name @param placeholderResolver a placeholder resolver used to resolve children of a placeholder registration @return the transformer entry
[ "Resolve", "an", "operation", "transformer", "entry", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/registry/OperationTransformerRegistry.java#L107-L115
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/JMapper.java
JMapper.getDestination
public D getDestination(D destination,final S source,final MappingType mtDestination,final MappingType mtSource) { """ This Method returns the destination given in input enriched with data contained in source given in input<br> with this setting: <table summary = ""> <tr> <td><code>NullPointerControl</code></td><td><code>ALL</code></td> </tr><tr> <td><code>MappingType</code> of Destination</td><td>mtDestination</td> </tr><tr> <td><code>MappingType</code> of Source</td><td>mtSource</td> </tr> </table> @param destination instance to enrich @param source instance that contains the data @param mtDestination type of mapping of destination instance @param mtSource type of mapping of source instance @return destination enriched @see NullPointerControl @see MappingType """ return getDestination(destination,source,NullPointerControl.ALL,mtDestination,mtSource); }
java
public D getDestination(D destination,final S source,final MappingType mtDestination,final MappingType mtSource){ return getDestination(destination,source,NullPointerControl.ALL,mtDestination,mtSource); }
[ "public", "D", "getDestination", "(", "D", "destination", ",", "final", "S", "source", ",", "final", "MappingType", "mtDestination", ",", "final", "MappingType", "mtSource", ")", "{", "return", "getDestination", "(", "destination", ",", "source", ",", "NullPointerControl", ".", "ALL", ",", "mtDestination", ",", "mtSource", ")", ";", "}" ]
This Method returns the destination given in input enriched with data contained in source given in input<br> with this setting: <table summary = ""> <tr> <td><code>NullPointerControl</code></td><td><code>ALL</code></td> </tr><tr> <td><code>MappingType</code> of Destination</td><td>mtDestination</td> </tr><tr> <td><code>MappingType</code> of Source</td><td>mtSource</td> </tr> </table> @param destination instance to enrich @param source instance that contains the data @param mtDestination type of mapping of destination instance @param mtSource type of mapping of source instance @return destination enriched @see NullPointerControl @see MappingType
[ "This", "Method", "returns", "the", "destination", "given", "in", "input", "enriched", "with", "data", "contained", "in", "source", "given", "in", "input<br", ">", "with", "this", "setting", ":", "<table", "summary", "=", ">", "<tr", ">", "<td", ">", "<code", ">", "NullPointerControl<", "/", "code", ">", "<", "/", "td", ">", "<td", ">", "<code", ">", "ALL<", "/", "code", ">", "<", "/", "td", ">", "<", "/", "tr", ">", "<tr", ">", "<td", ">", "<code", ">", "MappingType<", "/", "code", ">", "of", "Destination<", "/", "td", ">", "<td", ">", "mtDestination<", "/", "td", ">", "<", "/", "tr", ">", "<tr", ">", "<td", ">", "<code", ">", "MappingType<", "/", "code", ">", "of", "Source<", "/", "td", ">", "<td", ">", "mtSource<", "/", "td", ">", "<", "/", "tr", ">", "<", "/", "table", ">" ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/JMapper.java#L264-L266
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/lss/LssClient.java
LssClient.getSessionStatistics
public GetSessionStatisticsResponse getSessionStatistics(GetSessionStatisticsRequest request) { """ Returns the session statistics. @param request the request @return the response """ checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS, LIVE_SESSION, request.getSessionId()); if (request.getStartDate() != null) { internalRequest.addParameter("startDate", request.getStartDate()); } if (request.getEndDate() != null) { internalRequest.addParameter("endDate", request.getEndDate()); } if (request.getAggregate() != null) { internalRequest.addParameter("aggregate", request.getAggregate().toString()); } return invokeHttpClient(internalRequest, GetSessionStatisticsResponse.class); }
java
public GetSessionStatisticsResponse getSessionStatistics(GetSessionStatisticsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS, LIVE_SESSION, request.getSessionId()); if (request.getStartDate() != null) { internalRequest.addParameter("startDate", request.getStartDate()); } if (request.getEndDate() != null) { internalRequest.addParameter("endDate", request.getEndDate()); } if (request.getAggregate() != null) { internalRequest.addParameter("aggregate", request.getAggregate().toString()); } return invokeHttpClient(internalRequest, GetSessionStatisticsResponse.class); }
[ "public", "GetSessionStatisticsResponse", "getSessionStatistics", "(", "GetSessionStatisticsRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"The parameter request should NOT be null.\"", ")", ";", "checkStringNotEmpty", "(", "request", ".", "getSessionId", "(", ")", ",", "\"The parameter sessionId should NOT be null or empty string.\"", ")", ";", "InternalRequest", "internalRequest", "=", "createRequest", "(", "HttpMethodName", ".", "GET", ",", "request", ",", "STATISTICS", ",", "LIVE_SESSION", ",", "request", ".", "getSessionId", "(", ")", ")", ";", "if", "(", "request", ".", "getStartDate", "(", ")", "!=", "null", ")", "{", "internalRequest", ".", "addParameter", "(", "\"startDate\"", ",", "request", ".", "getStartDate", "(", ")", ")", ";", "}", "if", "(", "request", ".", "getEndDate", "(", ")", "!=", "null", ")", "{", "internalRequest", ".", "addParameter", "(", "\"endDate\"", ",", "request", ".", "getEndDate", "(", ")", ")", ";", "}", "if", "(", "request", ".", "getAggregate", "(", ")", "!=", "null", ")", "{", "internalRequest", ".", "addParameter", "(", "\"aggregate\"", ",", "request", ".", "getAggregate", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "return", "invokeHttpClient", "(", "internalRequest", ",", "GetSessionStatisticsResponse", ".", "class", ")", ";", "}" ]
Returns the session statistics. @param request the request @return the response
[ "Returns", "the", "session", "statistics", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L1335-L1350
mbenson/therian
core/src/main/java/therian/TherianContext.java
TherianContext.evalSuccess
public final synchronized boolean evalSuccess(Operation<?> operation, Hint... hints) { """ Convenience method to perform an operation, discarding its result, and report whether it succeeded. @param operation @param hints @return whether {@code operation} was supported and successful @throws NullPointerException on {@code null} input @throws OperationException potentially, via {@link Operation#getResult()} """ final boolean dummyRoot = stack.isEmpty(); if (dummyRoot) { // add a root frame to preserve our cache "around" the supports/eval lifecycle, bypassing #push(): stack.push(Frame.ROOT); } try { if (supports(operation, hints)) { eval(operation, hints); return operation.isSuccessful(); } } finally { if (dummyRoot) { pop(Frame.ROOT); } } return false; }
java
public final synchronized boolean evalSuccess(Operation<?> operation, Hint... hints) { final boolean dummyRoot = stack.isEmpty(); if (dummyRoot) { // add a root frame to preserve our cache "around" the supports/eval lifecycle, bypassing #push(): stack.push(Frame.ROOT); } try { if (supports(operation, hints)) { eval(operation, hints); return operation.isSuccessful(); } } finally { if (dummyRoot) { pop(Frame.ROOT); } } return false; }
[ "public", "final", "synchronized", "boolean", "evalSuccess", "(", "Operation", "<", "?", ">", "operation", ",", "Hint", "...", "hints", ")", "{", "final", "boolean", "dummyRoot", "=", "stack", ".", "isEmpty", "(", ")", ";", "if", "(", "dummyRoot", ")", "{", "// add a root frame to preserve our cache \"around\" the supports/eval lifecycle, bypassing #push():", "stack", ".", "push", "(", "Frame", ".", "ROOT", ")", ";", "}", "try", "{", "if", "(", "supports", "(", "operation", ",", "hints", ")", ")", "{", "eval", "(", "operation", ",", "hints", ")", ";", "return", "operation", ".", "isSuccessful", "(", ")", ";", "}", "}", "finally", "{", "if", "(", "dummyRoot", ")", "{", "pop", "(", "Frame", ".", "ROOT", ")", ";", "}", "}", "return", "false", ";", "}" ]
Convenience method to perform an operation, discarding its result, and report whether it succeeded. @param operation @param hints @return whether {@code operation} was supported and successful @throws NullPointerException on {@code null} input @throws OperationException potentially, via {@link Operation#getResult()}
[ "Convenience", "method", "to", "perform", "an", "operation", "discarding", "its", "result", "and", "report", "whether", "it", "succeeded", "." ]
train
https://github.com/mbenson/therian/blob/0653505f73e2a6f5b0abc394ea6d83af03408254/core/src/main/java/therian/TherianContext.java#L429-L446
sebastiangraf/treetank
interfacemodules/jax-rx/src/main/java/org/treetank/service/jaxrx/implementation/DatabaseRepresentation.java
DatabaseRepresentation.deleteResource
public void deleteResource(final String resourceName) throws WebApplicationException { """ This method is responsible to delete an existing database. @param resourceName The name of the database. @throws WebApplicationException The exception occurred. """ synchronized (resourceName) { try { mDatabase.truncateResource(new SessionConfiguration(resourceName, null)); } catch (TTException e) { throw new WebApplicationException(e); } } }
java
public void deleteResource(final String resourceName) throws WebApplicationException { synchronized (resourceName) { try { mDatabase.truncateResource(new SessionConfiguration(resourceName, null)); } catch (TTException e) { throw new WebApplicationException(e); } } }
[ "public", "void", "deleteResource", "(", "final", "String", "resourceName", ")", "throws", "WebApplicationException", "{", "synchronized", "(", "resourceName", ")", "{", "try", "{", "mDatabase", ".", "truncateResource", "(", "new", "SessionConfiguration", "(", "resourceName", ",", "null", ")", ")", ";", "}", "catch", "(", "TTException", "e", ")", "{", "throw", "new", "WebApplicationException", "(", "e", ")", ";", "}", "}", "}" ]
This method is responsible to delete an existing database. @param resourceName The name of the database. @throws WebApplicationException The exception occurred.
[ "This", "method", "is", "responsible", "to", "delete", "an", "existing", "database", "." ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/jax-rx/src/main/java/org/treetank/service/jaxrx/implementation/DatabaseRepresentation.java#L276-L284
carewebframework/carewebframework-core
org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/xml/XMLViewer.java
XMLViewer.showXML
public static Window showXML(Document document, BaseUIComponent parent) { """ Show the dialog, loading the specified document. @param document The XML document. @param parent If specified, show viewer in embedded mode. Otherwise, show as modal dialog. @return The dialog. """ Map<String, Object> args = Collections.singletonMap("document", document); boolean modal = parent == null; Window dialog = PopupDialog.show(XMLConstants.VIEW_DIALOG, args, modal, modal, modal, null); if (parent != null) { dialog.setParent(parent); } return dialog; }
java
public static Window showXML(Document document, BaseUIComponent parent) { Map<String, Object> args = Collections.singletonMap("document", document); boolean modal = parent == null; Window dialog = PopupDialog.show(XMLConstants.VIEW_DIALOG, args, modal, modal, modal, null); if (parent != null) { dialog.setParent(parent); } return dialog; }
[ "public", "static", "Window", "showXML", "(", "Document", "document", ",", "BaseUIComponent", "parent", ")", "{", "Map", "<", "String", ",", "Object", ">", "args", "=", "Collections", ".", "singletonMap", "(", "\"document\"", ",", "document", ")", ";", "boolean", "modal", "=", "parent", "==", "null", ";", "Window", "dialog", "=", "PopupDialog", ".", "show", "(", "XMLConstants", ".", "VIEW_DIALOG", ",", "args", ",", "modal", ",", "modal", ",", "modal", ",", "null", ")", ";", "if", "(", "parent", "!=", "null", ")", "{", "dialog", ".", "setParent", "(", "parent", ")", ";", "}", "return", "dialog", ";", "}" ]
Show the dialog, loading the specified document. @param document The XML document. @param parent If specified, show viewer in embedded mode. Otherwise, show as modal dialog. @return The dialog.
[ "Show", "the", "dialog", "loading", "the", "specified", "document", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/xml/XMLViewer.java#L59-L69
OpenLiberty/open-liberty
dev/com.ibm.tx.core/src/com/ibm/tx/ltc/impl/LTCUOWCallback.java
LTCUOWCallback.contextChange
@Override public void contextChange(int typeOfChange, UOWScope scope) throws IllegalStateException { """ /* Notification from UserTransaction or UserActivitySession interface implementations that the state of a bean-managed UOW has changed. As a result of this bean-managed UOW change we may have to change the LTC that's on the thread. """ if (tc.isEntryEnabled()) Tr.entry(tc, "contextChange", new Object[] { typeOfChange, scope, this }); try { // Determine the Tx change type and process. Ensure we do what // we need to do as close to the context switch as possible switch (typeOfChange) { case PRE_BEGIN: uowPreBegin(); break; case POST_BEGIN: uowPostBegin(scope); break; case PRE_END: uowPreEnd(scope); break; case POST_END: uowPostEnd(); break; default: if (tc.isDebugEnabled()) Tr.debug(tc, "Unknown typeOfChange: " + typeOfChange); } } catch (IllegalStateException ise) { if (tc.isEntryEnabled()) Tr.exit(tc, "contextChange", ise); throw ise; } if (tc.isEntryEnabled()) Tr.exit(tc, "contextChange"); }
java
@Override public void contextChange(int typeOfChange, UOWScope scope) throws IllegalStateException { if (tc.isEntryEnabled()) Tr.entry(tc, "contextChange", new Object[] { typeOfChange, scope, this }); try { // Determine the Tx change type and process. Ensure we do what // we need to do as close to the context switch as possible switch (typeOfChange) { case PRE_BEGIN: uowPreBegin(); break; case POST_BEGIN: uowPostBegin(scope); break; case PRE_END: uowPreEnd(scope); break; case POST_END: uowPostEnd(); break; default: if (tc.isDebugEnabled()) Tr.debug(tc, "Unknown typeOfChange: " + typeOfChange); } } catch (IllegalStateException ise) { if (tc.isEntryEnabled()) Tr.exit(tc, "contextChange", ise); throw ise; } if (tc.isEntryEnabled()) Tr.exit(tc, "contextChange"); }
[ "@", "Override", "public", "void", "contextChange", "(", "int", "typeOfChange", ",", "UOWScope", "scope", ")", "throws", "IllegalStateException", "{", "if", "(", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "entry", "(", "tc", ",", "\"contextChange\"", ",", "new", "Object", "[", "]", "{", "typeOfChange", ",", "scope", ",", "this", "}", ")", ";", "try", "{", "// Determine the Tx change type and process. Ensure we do what", "// we need to do as close to the context switch as possible", "switch", "(", "typeOfChange", ")", "{", "case", "PRE_BEGIN", ":", "uowPreBegin", "(", ")", ";", "break", ";", "case", "POST_BEGIN", ":", "uowPostBegin", "(", "scope", ")", ";", "break", ";", "case", "PRE_END", ":", "uowPreEnd", "(", "scope", ")", ";", "break", ";", "case", "POST_END", ":", "uowPostEnd", "(", ")", ";", "break", ";", "default", ":", "if", "(", "tc", ".", "isDebugEnabled", "(", ")", ")", "Tr", ".", "debug", "(", "tc", ",", "\"Unknown typeOfChange: \"", "+", "typeOfChange", ")", ";", "}", "}", "catch", "(", "IllegalStateException", "ise", ")", "{", "if", "(", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "exit", "(", "tc", ",", "\"contextChange\"", ",", "ise", ")", ";", "throw", "ise", ";", "}", "if", "(", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "exit", "(", "tc", ",", "\"contextChange\"", ")", ";", "}" ]
/* Notification from UserTransaction or UserActivitySession interface implementations that the state of a bean-managed UOW has changed. As a result of this bean-managed UOW change we may have to change the LTC that's on the thread.
[ "/", "*", "Notification", "from", "UserTransaction", "or", "UserActivitySession", "interface", "implementations", "that", "the", "state", "of", "a", "bean", "-", "managed", "UOW", "has", "changed", ".", "As", "a", "result", "of", "this", "bean", "-", "managed", "UOW", "change", "we", "may", "have", "to", "change", "the", "LTC", "that", "s", "on", "the", "thread", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.tx.core/src/com/ibm/tx/ltc/impl/LTCUOWCallback.java#L73-L106
liferay/com-liferay-commerce
commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPDefinitionSpecificationOptionValueWrapper.java
CPDefinitionSpecificationOptionValueWrapper.setValue
@Override public void setValue(String value, java.util.Locale locale) { """ Sets the localized value of this cp definition specification option value in the language. @param value the localized value of this cp definition specification option value @param locale the locale of the language """ _cpDefinitionSpecificationOptionValue.setValue(value, locale); }
java
@Override public void setValue(String value, java.util.Locale locale) { _cpDefinitionSpecificationOptionValue.setValue(value, locale); }
[ "@", "Override", "public", "void", "setValue", "(", "String", "value", ",", "java", ".", "util", ".", "Locale", "locale", ")", "{", "_cpDefinitionSpecificationOptionValue", ".", "setValue", "(", "value", ",", "locale", ")", ";", "}" ]
Sets the localized value of this cp definition specification option value in the language. @param value the localized value of this cp definition specification option value @param locale the locale of the language
[ "Sets", "the", "localized", "value", "of", "this", "cp", "definition", "specification", "option", "value", "in", "the", "language", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPDefinitionSpecificationOptionValueWrapper.java#L685-L688
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/EventUtil.java
EventUtil.initEventHandlerInstance
public static synchronized void initEventHandlerInstance(int maxEntries, int flushPeriodMs) { """ Initializes the common eventHandler instance for all sessions/threads @param maxEntries - maximum number of buffered events before flush @param flushPeriodMs - period of time between asynchronous buffer flushes """ if (eventHandler.get() == null) { eventHandler.set(new EventHandler(maxEntries, flushPeriodMs)); } //eventHandler.startFlusher(); }
java
public static synchronized void initEventHandlerInstance(int maxEntries, int flushPeriodMs) { if (eventHandler.get() == null) { eventHandler.set(new EventHandler(maxEntries, flushPeriodMs)); } //eventHandler.startFlusher(); }
[ "public", "static", "synchronized", "void", "initEventHandlerInstance", "(", "int", "maxEntries", ",", "int", "flushPeriodMs", ")", "{", "if", "(", "eventHandler", ".", "get", "(", ")", "==", "null", ")", "{", "eventHandler", ".", "set", "(", "new", "EventHandler", "(", "maxEntries", ",", "flushPeriodMs", ")", ")", ";", "}", "//eventHandler.startFlusher();", "}" ]
Initializes the common eventHandler instance for all sessions/threads @param maxEntries - maximum number of buffered events before flush @param flushPeriodMs - period of time between asynchronous buffer flushes
[ "Initializes", "the", "common", "eventHandler", "instance", "for", "all", "sessions", "/", "threads" ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/EventUtil.java#L43-L51
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java
CommerceAvailabilityEstimatePersistenceImpl.findAll
@Override public List<CommerceAvailabilityEstimate> findAll(int start, int end) { """ Returns a range of all the commerce availability estimates. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceAvailabilityEstimateModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce availability estimates @param end the upper bound of the range of commerce availability estimates (not inclusive) @return the range of commerce availability estimates """ return findAll(start, end, null); }
java
@Override public List<CommerceAvailabilityEstimate> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceAvailabilityEstimate", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce availability estimates. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceAvailabilityEstimateModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce availability estimates @param end the upper bound of the range of commerce availability estimates (not inclusive) @return the range of commerce availability estimates
[ "Returns", "a", "range", "of", "all", "the", "commerce", "availability", "estimates", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java#L2694-L2697
nmorel/gwt-jackson
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/RebindConfiguration.java
RebindConfiguration.isTypeSupportedForDeserialization
public boolean isTypeSupportedForDeserialization( TreeLogger logger, JClassType classType ) { """ <p>isTypeSupportedForDeserialization</p> @param logger a {@link com.google.gwt.core.ext.TreeLogger} object. @param classType a {@link com.google.gwt.core.ext.typeinfo.JClassType} object. @return a boolean. """ return allSupportedDeserializationClass.contains( classType ) || additionalSupportedTypes.isIncluded( logger, classType.getQualifiedSourceName() ); }
java
public boolean isTypeSupportedForDeserialization( TreeLogger logger, JClassType classType ) { return allSupportedDeserializationClass.contains( classType ) || additionalSupportedTypes.isIncluded( logger, classType.getQualifiedSourceName() ); }
[ "public", "boolean", "isTypeSupportedForDeserialization", "(", "TreeLogger", "logger", ",", "JClassType", "classType", ")", "{", "return", "allSupportedDeserializationClass", ".", "contains", "(", "classType", ")", "||", "additionalSupportedTypes", ".", "isIncluded", "(", "logger", ",", "classType", ".", "getQualifiedSourceName", "(", ")", ")", ";", "}" ]
<p>isTypeSupportedForDeserialization</p> @param logger a {@link com.google.gwt.core.ext.TreeLogger} object. @param classType a {@link com.google.gwt.core.ext.typeinfo.JClassType} object. @return a boolean.
[ "<p", ">", "isTypeSupportedForDeserialization<", "/", "p", ">" ]
train
https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/RebindConfiguration.java#L624-L627
symphonyoss/messageml-utils
src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java
Element.buildElement
private void buildElement(MessageMLParser context, org.w3c.dom.Element element) throws InvalidInputException, ProcessingException { """ Build a MessageML element based on the provided DOM element and descend into its children. """ Element child = context.createElement(element, this); child.buildAll(context, element); child.validate(); addChild(child); }
java
private void buildElement(MessageMLParser context, org.w3c.dom.Element element) throws InvalidInputException, ProcessingException { Element child = context.createElement(element, this); child.buildAll(context, element); child.validate(); addChild(child); }
[ "private", "void", "buildElement", "(", "MessageMLParser", "context", ",", "org", ".", "w3c", ".", "dom", ".", "Element", "element", ")", "throws", "InvalidInputException", ",", "ProcessingException", "{", "Element", "child", "=", "context", ".", "createElement", "(", "element", ",", "this", ")", ";", "child", ".", "buildAll", "(", "context", ",", "element", ")", ";", "child", ".", "validate", "(", ")", ";", "addChild", "(", "child", ")", ";", "}" ]
Build a MessageML element based on the provided DOM element and descend into its children.
[ "Build", "a", "MessageML", "element", "based", "on", "the", "provided", "DOM", "element", "and", "descend", "into", "its", "children", "." ]
train
https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L136-L142
groupon/monsoon
history/src/main/java/com/groupon/lex/metrics/history/v1/xdr/ToXdr.java
ToXdr.tags_index
private int tags_index(dictionary_delta dict_delta, Tags tags) { """ Lookup the index for the argument, or if it isn't present, create one. """ final BiMap<Tags, Integer> dict = from_.getTagDict().inverse(); final Integer resolved = dict.get(tags); if (resolved != null) return resolved; final int allocated = allocate_index_(dict); dict.put(tags, allocated); // Create new pdd for serialization. tag_dictionary_delta tdd = new tag_dictionary_delta(); tdd.id = allocated; tdd.value = new tags(); tdd.value.elems = tags.stream() .map(entry -> { tag_elem elem = new tag_elem(); elem.key = entry.getKey(); elem.value = metric_value_(dict_delta, entry.getValue()); return elem; }) .toArray(tag_elem[]::new); // Append new entry to array. dict_delta.tdd = Stream.concat(Arrays.stream(dict_delta.tdd), Stream.of(tdd)) .toArray(tag_dictionary_delta[]::new); LOG.log(Level.FINE, "dict_delta.tdd: {0} items (added {1})", new Object[]{dict_delta.tdd.length, tags}); return allocated; }
java
private int tags_index(dictionary_delta dict_delta, Tags tags) { final BiMap<Tags, Integer> dict = from_.getTagDict().inverse(); final Integer resolved = dict.get(tags); if (resolved != null) return resolved; final int allocated = allocate_index_(dict); dict.put(tags, allocated); // Create new pdd for serialization. tag_dictionary_delta tdd = new tag_dictionary_delta(); tdd.id = allocated; tdd.value = new tags(); tdd.value.elems = tags.stream() .map(entry -> { tag_elem elem = new tag_elem(); elem.key = entry.getKey(); elem.value = metric_value_(dict_delta, entry.getValue()); return elem; }) .toArray(tag_elem[]::new); // Append new entry to array. dict_delta.tdd = Stream.concat(Arrays.stream(dict_delta.tdd), Stream.of(tdd)) .toArray(tag_dictionary_delta[]::new); LOG.log(Level.FINE, "dict_delta.tdd: {0} items (added {1})", new Object[]{dict_delta.tdd.length, tags}); return allocated; }
[ "private", "int", "tags_index", "(", "dictionary_delta", "dict_delta", ",", "Tags", "tags", ")", "{", "final", "BiMap", "<", "Tags", ",", "Integer", ">", "dict", "=", "from_", ".", "getTagDict", "(", ")", ".", "inverse", "(", ")", ";", "final", "Integer", "resolved", "=", "dict", ".", "get", "(", "tags", ")", ";", "if", "(", "resolved", "!=", "null", ")", "return", "resolved", ";", "final", "int", "allocated", "=", "allocate_index_", "(", "dict", ")", ";", "dict", ".", "put", "(", "tags", ",", "allocated", ")", ";", "// Create new pdd for serialization.", "tag_dictionary_delta", "tdd", "=", "new", "tag_dictionary_delta", "(", ")", ";", "tdd", ".", "id", "=", "allocated", ";", "tdd", ".", "value", "=", "new", "tags", "(", ")", ";", "tdd", ".", "value", ".", "elems", "=", "tags", ".", "stream", "(", ")", ".", "map", "(", "entry", "->", "{", "tag_elem", "elem", "=", "new", "tag_elem", "(", ")", ";", "elem", ".", "key", "=", "entry", ".", "getKey", "(", ")", ";", "elem", ".", "value", "=", "metric_value_", "(", "dict_delta", ",", "entry", ".", "getValue", "(", ")", ")", ";", "return", "elem", ";", "}", ")", ".", "toArray", "(", "tag_elem", "[", "]", "::", "new", ")", ";", "// Append new entry to array.", "dict_delta", ".", "tdd", "=", "Stream", ".", "concat", "(", "Arrays", ".", "stream", "(", "dict_delta", ".", "tdd", ")", ",", "Stream", ".", "of", "(", "tdd", ")", ")", ".", "toArray", "(", "tag_dictionary_delta", "[", "]", "::", "new", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"dict_delta.tdd: {0} items (added {1})\"", ",", "new", "Object", "[", "]", "{", "dict_delta", ".", "tdd", ".", "length", ",", "tags", "}", ")", ";", "return", "allocated", ";", "}" ]
Lookup the index for the argument, or if it isn't present, create one.
[ "Lookup", "the", "index", "for", "the", "argument", "or", "if", "it", "isn", "t", "present", "create", "one", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/history/src/main/java/com/groupon/lex/metrics/history/v1/xdr/ToXdr.java#L156-L182
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/slim/MapFixture.java
MapFixture.copyValuesFromTo
public void copyValuesFromTo(Map<String, Object> otherMap, Map<String, Object> map) { """ Adds all values in the supplied map to the current values. @param otherMap to obtain values from. @param map map to store value in. """ getMapHelper().copyValuesFromTo(otherMap, map); }
java
public void copyValuesFromTo(Map<String, Object> otherMap, Map<String, Object> map) { getMapHelper().copyValuesFromTo(otherMap, map); }
[ "public", "void", "copyValuesFromTo", "(", "Map", "<", "String", ",", "Object", ">", "otherMap", ",", "Map", "<", "String", ",", "Object", ">", "map", ")", "{", "getMapHelper", "(", ")", ".", "copyValuesFromTo", "(", "otherMap", ",", "map", ")", ";", "}" ]
Adds all values in the supplied map to the current values. @param otherMap to obtain values from. @param map map to store value in.
[ "Adds", "all", "values", "in", "the", "supplied", "map", "to", "the", "current", "values", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/MapFixture.java#L104-L106
Netflix/Hystrix
hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/AopUtils.java
AopUtils.getDeclaredMethod
public static Method getDeclaredMethod(Class<?> type, String methodName, Class<?>... parameterTypes) { """ Gets declared method from specified type by mame and parameters types. @param type the type @param methodName the name of the method @param parameterTypes the parameter array @return a {@link Method} object or null if method doesn't exist """ Method method = null; try { method = type.getDeclaredMethod(methodName, parameterTypes); if(method.isBridge()){ method = MethodProvider.getInstance().unbride(method, type); } } catch (NoSuchMethodException e) { Class<?> superclass = type.getSuperclass(); if (superclass != null) { method = getDeclaredMethod(superclass, methodName, parameterTypes); } } catch (ClassNotFoundException e) { Throwables.propagate(e); } catch (IOException e) { Throwables.propagate(e); } return method; }
java
public static Method getDeclaredMethod(Class<?> type, String methodName, Class<?>... parameterTypes) { Method method = null; try { method = type.getDeclaredMethod(methodName, parameterTypes); if(method.isBridge()){ method = MethodProvider.getInstance().unbride(method, type); } } catch (NoSuchMethodException e) { Class<?> superclass = type.getSuperclass(); if (superclass != null) { method = getDeclaredMethod(superclass, methodName, parameterTypes); } } catch (ClassNotFoundException e) { Throwables.propagate(e); } catch (IOException e) { Throwables.propagate(e); } return method; }
[ "public", "static", "Method", "getDeclaredMethod", "(", "Class", "<", "?", ">", "type", ",", "String", "methodName", ",", "Class", "<", "?", ">", "...", "parameterTypes", ")", "{", "Method", "method", "=", "null", ";", "try", "{", "method", "=", "type", ".", "getDeclaredMethod", "(", "methodName", ",", "parameterTypes", ")", ";", "if", "(", "method", ".", "isBridge", "(", ")", ")", "{", "method", "=", "MethodProvider", ".", "getInstance", "(", ")", ".", "unbride", "(", "method", ",", "type", ")", ";", "}", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "Class", "<", "?", ">", "superclass", "=", "type", ".", "getSuperclass", "(", ")", ";", "if", "(", "superclass", "!=", "null", ")", "{", "method", "=", "getDeclaredMethod", "(", "superclass", ",", "methodName", ",", "parameterTypes", ")", ";", "}", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "return", "method", ";", "}" ]
Gets declared method from specified type by mame and parameters types. @param type the type @param methodName the name of the method @param parameterTypes the parameter array @return a {@link Method} object or null if method doesn't exist
[ "Gets", "declared", "method", "from", "specified", "type", "by", "mame", "and", "parameters", "types", "." ]
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/AopUtils.java#L89-L107
operasoftware/operaprestodriver
src/com/opera/core/systems/OperaProfile.java
OperaProfile.getPreferenceFile
private static File getPreferenceFile(final File directory) { """ Opera preference files can be named either <code>opera.ini</code> or <code>operaprefs.ini</code> depending on the product. This method will look in the specified directory for either of the files and return the one that exists. <code>operaprefs.ini</code> has priority. @param directory the directory to look for a preference file @return a preference file """ List<File> candidates = ImmutableList.of( new File(directory, "operaprefs.ini"), new File(directory, "opera.ini")); for (File candidate : candidates) { if (candidate.exists()) { return candidate; } } return candidates.get(0); }
java
private static File getPreferenceFile(final File directory) { List<File> candidates = ImmutableList.of( new File(directory, "operaprefs.ini"), new File(directory, "opera.ini")); for (File candidate : candidates) { if (candidate.exists()) { return candidate; } } return candidates.get(0); }
[ "private", "static", "File", "getPreferenceFile", "(", "final", "File", "directory", ")", "{", "List", "<", "File", ">", "candidates", "=", "ImmutableList", ".", "of", "(", "new", "File", "(", "directory", ",", "\"operaprefs.ini\"", ")", ",", "new", "File", "(", "directory", ",", "\"opera.ini\"", ")", ")", ";", "for", "(", "File", "candidate", ":", "candidates", ")", "{", "if", "(", "candidate", ".", "exists", "(", ")", ")", "{", "return", "candidate", ";", "}", "}", "return", "candidates", ".", "get", "(", "0", ")", ";", "}" ]
Opera preference files can be named either <code>opera.ini</code> or <code>operaprefs.ini</code> depending on the product. This method will look in the specified directory for either of the files and return the one that exists. <code>operaprefs.ini</code> has priority. @param directory the directory to look for a preference file @return a preference file
[ "Opera", "preference", "files", "can", "be", "named", "either", "<code", ">", "opera", ".", "ini<", "/", "code", ">", "or", "<code", ">", "operaprefs", ".", "ini<", "/", "code", ">", "depending", "on", "the", "product", ".", "This", "method", "will", "look", "in", "the", "specified", "directory", "for", "either", "of", "the", "files", "and", "return", "the", "one", "that", "exists", ".", "<code", ">", "operaprefs", ".", "ini<", "/", "code", ">", "has", "priority", "." ]
train
https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/OperaProfile.java#L221-L233
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/TransientNodeData.java
TransientNodeData.createNodeData
public static TransientNodeData createNodeData(NodeData parent, InternalQName name, InternalQName primaryTypeName, InternalQName[] mixinTypesName, String identifier, AccessControlList acl) { """ Factory method @param parent NodeData @param name InternalQName @param primaryTypeName InternalQName @param mixinTypesName InternalQName[] @param identifier String @param acl AccessControlList @return """ TransientNodeData nodeData = null; QPath path = QPath.makeChildPath(parent.getQPath(), name); nodeData = new TransientNodeData(path, identifier, -1, primaryTypeName, mixinTypesName, 0, parent.getIdentifier(), acl); return nodeData; }
java
public static TransientNodeData createNodeData(NodeData parent, InternalQName name, InternalQName primaryTypeName, InternalQName[] mixinTypesName, String identifier, AccessControlList acl) { TransientNodeData nodeData = null; QPath path = QPath.makeChildPath(parent.getQPath(), name); nodeData = new TransientNodeData(path, identifier, -1, primaryTypeName, mixinTypesName, 0, parent.getIdentifier(), acl); return nodeData; }
[ "public", "static", "TransientNodeData", "createNodeData", "(", "NodeData", "parent", ",", "InternalQName", "name", ",", "InternalQName", "primaryTypeName", ",", "InternalQName", "[", "]", "mixinTypesName", ",", "String", "identifier", ",", "AccessControlList", "acl", ")", "{", "TransientNodeData", "nodeData", "=", "null", ";", "QPath", "path", "=", "QPath", ".", "makeChildPath", "(", "parent", ".", "getQPath", "(", ")", ",", "name", ")", ";", "nodeData", "=", "new", "TransientNodeData", "(", "path", ",", "identifier", ",", "-", "1", ",", "primaryTypeName", ",", "mixinTypesName", ",", "0", ",", "parent", ".", "getIdentifier", "(", ")", ",", "acl", ")", ";", "return", "nodeData", ";", "}" ]
Factory method @param parent NodeData @param name InternalQName @param primaryTypeName InternalQName @param mixinTypesName InternalQName[] @param identifier String @param acl AccessControlList @return
[ "Factory", "method" ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/TransientNodeData.java#L274-L282
hypercube1024/firefly
firefly/src/main/java/com/firefly/codec/http2/decode/HttpParser.java
HttpParser.complianceViolation
protected boolean complianceViolation(HttpComplianceSection violation, String reason) { """ Check RFC compliance violation @param violation The compliance section violation @param reason The reason for the violation @return True if the current compliance level is set so as to Not allow this violation """ if (_compliances.contains(violation)) return true; if (reason == null) reason = violation.description; if (_complianceHandler != null) _complianceHandler.onComplianceViolation(_compliance, violation, reason); return false; }
java
protected boolean complianceViolation(HttpComplianceSection violation, String reason) { if (_compliances.contains(violation)) return true; if (reason == null) reason = violation.description; if (_complianceHandler != null) _complianceHandler.onComplianceViolation(_compliance, violation, reason); return false; }
[ "protected", "boolean", "complianceViolation", "(", "HttpComplianceSection", "violation", ",", "String", "reason", ")", "{", "if", "(", "_compliances", ".", "contains", "(", "violation", ")", ")", "return", "true", ";", "if", "(", "reason", "==", "null", ")", "reason", "=", "violation", ".", "description", ";", "if", "(", "_complianceHandler", "!=", "null", ")", "_complianceHandler", ".", "onComplianceViolation", "(", "_compliance", ",", "violation", ",", "reason", ")", ";", "return", "false", ";", "}" ]
Check RFC compliance violation @param violation The compliance section violation @param reason The reason for the violation @return True if the current compliance level is set so as to Not allow this violation
[ "Check", "RFC", "compliance", "violation" ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/http2/decode/HttpParser.java#L304-L313
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.getAllContinentPOIID
public void getAllContinentPOIID(int continentID, int floorID, int regionID, int mapID, Callback<List<Integer>> callback) throws NullPointerException { """ For more info on continents API go <a href="https://wiki.guildwars2.com/wiki/API:2/continents">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions @param continentID {@link Continent#id} @param floorID {@link ContinentFloor#id} @param regionID {@link ContinentRegion#id} @param mapID {@link ContinentMap#id} @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws NullPointerException if given {@link Callback} is empty @see ContinentMap.PoI continents map PoI info """ gw2API.getAllContinentPOIIDs(Integer.toString(continentID), Integer.toString(floorID), Integer.toString(regionID), Integer.toString(mapID)).enqueue(callback); }
java
public void getAllContinentPOIID(int continentID, int floorID, int regionID, int mapID, Callback<List<Integer>> callback) throws NullPointerException { gw2API.getAllContinentPOIIDs(Integer.toString(continentID), Integer.toString(floorID), Integer.toString(regionID), Integer.toString(mapID)).enqueue(callback); }
[ "public", "void", "getAllContinentPOIID", "(", "int", "continentID", ",", "int", "floorID", ",", "int", "regionID", ",", "int", "mapID", ",", "Callback", "<", "List", "<", "Integer", ">", ">", "callback", ")", "throws", "NullPointerException", "{", "gw2API", ".", "getAllContinentPOIIDs", "(", "Integer", ".", "toString", "(", "continentID", ")", ",", "Integer", ".", "toString", "(", "floorID", ")", ",", "Integer", ".", "toString", "(", "regionID", ")", ",", "Integer", ".", "toString", "(", "mapID", ")", ")", ".", "enqueue", "(", "callback", ")", ";", "}" ]
For more info on continents API go <a href="https://wiki.guildwars2.com/wiki/API:2/continents">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions @param continentID {@link Continent#id} @param floorID {@link ContinentFloor#id} @param regionID {@link ContinentRegion#id} @param mapID {@link ContinentMap#id} @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws NullPointerException if given {@link Callback} is empty @see ContinentMap.PoI continents map PoI info
[ "For", "more", "info", "on", "continents", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "continents", ">", "here<", "/", "a", ">", "<br", "/", ">", "Give", "user", "the", "access", "to", "{", "@link", "Callback#onResponse", "(", "Call", "Response", ")", "}", "and", "{", "@link", "Callback#onFailure", "(", "Call", "Throwable", ")", "}", "methods", "for", "custom", "interactions" ]
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1177-L1179
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/StringUtil.java
StringUtil.indexOf
public static int indexOf(String input, char ch, int offset) { """ Like a String.indexOf but without MIN_SUPPLEMENTARY_CODE_POINT handling @param input to check the indexOf on @param ch character to find the index of @param offset offset to start the reading from @return index of the character, or -1 if not found """ for (int i = offset; i < input.length(); i++) { if (input.charAt(i) == ch) { return i; } } return -1; }
java
public static int indexOf(String input, char ch, int offset) { for (int i = offset; i < input.length(); i++) { if (input.charAt(i) == ch) { return i; } } return -1; }
[ "public", "static", "int", "indexOf", "(", "String", "input", ",", "char", "ch", ",", "int", "offset", ")", "{", "for", "(", "int", "i", "=", "offset", ";", "i", "<", "input", ".", "length", "(", ")", ";", "i", "++", ")", "{", "if", "(", "input", ".", "charAt", "(", "i", ")", "==", "ch", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
Like a String.indexOf but without MIN_SUPPLEMENTARY_CODE_POINT handling @param input to check the indexOf on @param ch character to find the index of @param offset offset to start the reading from @return index of the character, or -1 if not found
[ "Like", "a", "String", ".", "indexOf", "but", "without", "MIN_SUPPLEMENTARY_CODE_POINT", "handling" ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/StringUtil.java#L210-L217
web3j/web3j
crypto/src/main/java/org/web3j/crypto/Sign.java
Sign.decompressKey
private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { """ Decompress a compressed public key (x co-ord and low-bit of y-coord). """ X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); compEnc[0] = (byte)(yBit ? 0x03 : 0x02); return CURVE.getCurve().decodePoint(compEnc); }
java
private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); compEnc[0] = (byte)(yBit ? 0x03 : 0x02); return CURVE.getCurve().decodePoint(compEnc); }
[ "private", "static", "ECPoint", "decompressKey", "(", "BigInteger", "xBN", ",", "boolean", "yBit", ")", "{", "X9IntegerConverter", "x9", "=", "new", "X9IntegerConverter", "(", ")", ";", "byte", "[", "]", "compEnc", "=", "x9", ".", "integerToBytes", "(", "xBN", ",", "1", "+", "x9", ".", "getByteLength", "(", "CURVE", ".", "getCurve", "(", ")", ")", ")", ";", "compEnc", "[", "0", "]", "=", "(", "byte", ")", "(", "yBit", "?", "0x03", ":", "0x02", ")", ";", "return", "CURVE", ".", "getCurve", "(", ")", ".", "decodePoint", "(", "compEnc", ")", ";", "}" ]
Decompress a compressed public key (x co-ord and low-bit of y-coord).
[ "Decompress", "a", "compressed", "public", "key", "(", "x", "co", "-", "ord", "and", "low", "-", "bit", "of", "y", "-", "coord", ")", "." ]
train
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/Sign.java#L173-L178
roboconf/roboconf-platform
core/roboconf-target-iaas-azure/src/main/java/net/roboconf/target/azure/internal/AzureIaasHandler.java
AzureIaasHandler.buildProperties
static AzureProperties buildProperties( Map<String,String> targetProperties ) throws TargetException { """ Validates the received properties and builds a Java bean from them. @param targetProperties the target properties @return a non-null bean @throws TargetException if properties are invalid """ String[] properties = { AzureConstants.AZURE_SUBSCRIPTION_ID, AzureConstants.AZURE_KEY_STORE_FILE, AzureConstants.AZURE_KEY_STORE_PASSWORD, AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE, AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE, AzureConstants.AZURE_LOCATION, AzureConstants.AZURE_VM_SIZE, AzureConstants.AZURE_VM_TEMPLATE }; for( String property : properties ) { if( Utils.isEmptyOrWhitespaces( targetProperties.get( property ))) throw new TargetException( "The value for " + property + " cannot be null or empty." ); } // Create a bean AzureProperties azureProperties = new AzureProperties(); String s = targetProperties.get( AzureConstants.AZURE_SUBSCRIPTION_ID ); azureProperties.setSubscriptionId( s.trim()); s = targetProperties.get( AzureConstants.AZURE_KEY_STORE_FILE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_KEY_STORE_PASSWORD ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_LOCATION ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_VM_SIZE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_VM_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); return azureProperties; }
java
static AzureProperties buildProperties( Map<String,String> targetProperties ) throws TargetException { String[] properties = { AzureConstants.AZURE_SUBSCRIPTION_ID, AzureConstants.AZURE_KEY_STORE_FILE, AzureConstants.AZURE_KEY_STORE_PASSWORD, AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE, AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE, AzureConstants.AZURE_LOCATION, AzureConstants.AZURE_VM_SIZE, AzureConstants.AZURE_VM_TEMPLATE }; for( String property : properties ) { if( Utils.isEmptyOrWhitespaces( targetProperties.get( property ))) throw new TargetException( "The value for " + property + " cannot be null or empty." ); } // Create a bean AzureProperties azureProperties = new AzureProperties(); String s = targetProperties.get( AzureConstants.AZURE_SUBSCRIPTION_ID ); azureProperties.setSubscriptionId( s.trim()); s = targetProperties.get( AzureConstants.AZURE_KEY_STORE_FILE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_KEY_STORE_PASSWORD ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_LOCATION ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_VM_SIZE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_VM_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); return azureProperties; }
[ "static", "AzureProperties", "buildProperties", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ")", "throws", "TargetException", "{", "String", "[", "]", "properties", "=", "{", "AzureConstants", ".", "AZURE_SUBSCRIPTION_ID", ",", "AzureConstants", ".", "AZURE_KEY_STORE_FILE", ",", "AzureConstants", ".", "AZURE_KEY_STORE_PASSWORD", ",", "AzureConstants", ".", "AZURE_CREATE_CLOUD_SERVICE_TEMPLATE", ",", "AzureConstants", ".", "AZURE_CREATE_DEPLOYMENT_TEMPLATE", ",", "AzureConstants", ".", "AZURE_LOCATION", ",", "AzureConstants", ".", "AZURE_VM_SIZE", ",", "AzureConstants", ".", "AZURE_VM_TEMPLATE", "}", ";", "for", "(", "String", "property", ":", "properties", ")", "{", "if", "(", "Utils", ".", "isEmptyOrWhitespaces", "(", "targetProperties", ".", "get", "(", "property", ")", ")", ")", "throw", "new", "TargetException", "(", "\"The value for \"", "+", "property", "+", "\" cannot be null or empty.\"", ")", ";", "}", "// Create a bean", "AzureProperties", "azureProperties", "=", "new", "AzureProperties", "(", ")", ";", "String", "s", "=", "targetProperties", ".", "get", "(", "AzureConstants", ".", "AZURE_SUBSCRIPTION_ID", ")", ";", "azureProperties", ".", "setSubscriptionId", "(", "s", ".", "trim", "(", ")", ")", ";", "s", "=", "targetProperties", ".", "get", "(", "AzureConstants", ".", "AZURE_KEY_STORE_FILE", ")", ";", "azureProperties", ".", "setKeyStoreFile", "(", "s", ".", "trim", "(", ")", ")", ";", "s", "=", "targetProperties", ".", "get", "(", "AzureConstants", ".", "AZURE_KEY_STORE_PASSWORD", ")", ";", "azureProperties", ".", "setKeyStoreFile", "(", "s", ".", "trim", "(", ")", ")", ";", "s", "=", "targetProperties", ".", "get", "(", "AzureConstants", ".", "AZURE_CREATE_CLOUD_SERVICE_TEMPLATE", ")", ";", "azureProperties", ".", "setKeyStoreFile", "(", "s", ".", "trim", "(", ")", ")", ";", "s", "=", "targetProperties", ".", "get", "(", "AzureConstants", ".", "AZURE_CREATE_DEPLOYMENT_TEMPLATE", ")", ";", "azureProperties", ".", "setKeyStoreFile", "(", "s", ".", "trim", "(", ")", ")", ";", "s", "=", "targetProperties", ".", "get", "(", "AzureConstants", ".", "AZURE_LOCATION", ")", ";", "azureProperties", ".", "setKeyStoreFile", "(", "s", ".", "trim", "(", ")", ")", ";", "s", "=", "targetProperties", ".", "get", "(", "AzureConstants", ".", "AZURE_VM_SIZE", ")", ";", "azureProperties", ".", "setKeyStoreFile", "(", "s", ".", "trim", "(", ")", ")", ";", "s", "=", "targetProperties", ".", "get", "(", "AzureConstants", ".", "AZURE_VM_TEMPLATE", ")", ";", "azureProperties", ".", "setKeyStoreFile", "(", "s", ".", "trim", "(", ")", ")", ";", "return", "azureProperties", ";", "}" ]
Validates the received properties and builds a Java bean from them. @param targetProperties the target properties @return a non-null bean @throws TargetException if properties are invalid
[ "Validates", "the", "received", "properties", "and", "builds", "a", "Java", "bean", "from", "them", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-azure/src/main/java/net/roboconf/target/azure/internal/AzureIaasHandler.java#L253-L299
wisdom-framework/wisdom
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/node/NPM.java
NPM.configureRegistry
public static void configureRegistry(NodeManager node, Log log, String npmRegistryUrl) { """ Configures the NPM registry location. @param node the node manager @param log the logger @param npmRegistryUrl the registry url """ try { node.factory().getNpmRunner(node.proxy()).execute("config set registry " + npmRegistryUrl); } catch (TaskRunnerException e) { log.error("Error during the configuration of NPM registry with the url " + npmRegistryUrl + " - check log", e); } }
java
public static void configureRegistry(NodeManager node, Log log, String npmRegistryUrl) { try { node.factory().getNpmRunner(node.proxy()).execute("config set registry " + npmRegistryUrl); } catch (TaskRunnerException e) { log.error("Error during the configuration of NPM registry with the url " + npmRegistryUrl + " - check log", e); } }
[ "public", "static", "void", "configureRegistry", "(", "NodeManager", "node", ",", "Log", "log", ",", "String", "npmRegistryUrl", ")", "{", "try", "{", "node", ".", "factory", "(", ")", ".", "getNpmRunner", "(", "node", ".", "proxy", "(", ")", ")", ".", "execute", "(", "\"config set registry \"", "+", "npmRegistryUrl", ")", ";", "}", "catch", "(", "TaskRunnerException", "e", ")", "{", "log", ".", "error", "(", "\"Error during the configuration of NPM registry with the url \"", "+", "npmRegistryUrl", "+", "\" - check log\"", ",", "e", ")", ";", "}", "}" ]
Configures the NPM registry location. @param node the node manager @param log the logger @param npmRegistryUrl the registry url
[ "Configures", "the", "NPM", "registry", "location", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/node/NPM.java#L415-L421
Whiley/WhileyCompiler
src/main/java/wyil/util/AbstractTypedVisitor.java
AbstractTypedVisitor.selectLambda
public Type.Callable selectLambda(Type target, Expr expr, Environment environment) { """ <p> Given an arbitrary target type, filter out the target lambda types. For example, consider the following method: </p> <pre> type fun_t is function(int)->(int) method f(int x): fun_t|null xs = &(int y -> y+1) ... </pre> <p> When type checking the expression <code>&(int y -> y+1)</code> the flow type checker will attempt to determine an <i>expected</i> lambda type. In order to then determine the appropriate expected type for the lambda body <code>y+1</code> it filters <code>fun_t|null</code> down to just <code>fun_t</code>. </p> @param target Target type for this value @param expr Source expression for this value @author David J. Pearce """ Type.Callable type = asType(expr.getType(), Type.Callable.class); // Construct the default case for matching against any Type.Callable anyType = new Type.Function(type.getParameters(), TUPLE_ANY); // Create the filter itself AbstractTypeFilter<Type.Callable> filter = new AbstractTypeFilter<>(Type.Callable.class, anyType); // return selectCandidate(filter.apply(target), type, environment); }
java
public Type.Callable selectLambda(Type target, Expr expr, Environment environment) { Type.Callable type = asType(expr.getType(), Type.Callable.class); // Construct the default case for matching against any Type.Callable anyType = new Type.Function(type.getParameters(), TUPLE_ANY); // Create the filter itself AbstractTypeFilter<Type.Callable> filter = new AbstractTypeFilter<>(Type.Callable.class, anyType); // return selectCandidate(filter.apply(target), type, environment); }
[ "public", "Type", ".", "Callable", "selectLambda", "(", "Type", "target", ",", "Expr", "expr", ",", "Environment", "environment", ")", "{", "Type", ".", "Callable", "type", "=", "asType", "(", "expr", ".", "getType", "(", ")", ",", "Type", ".", "Callable", ".", "class", ")", ";", "// Construct the default case for matching against any", "Type", ".", "Callable", "anyType", "=", "new", "Type", ".", "Function", "(", "type", ".", "getParameters", "(", ")", ",", "TUPLE_ANY", ")", ";", "// Create the filter itself", "AbstractTypeFilter", "<", "Type", ".", "Callable", ">", "filter", "=", "new", "AbstractTypeFilter", "<>", "(", "Type", ".", "Callable", ".", "class", ",", "anyType", ")", ";", "//", "return", "selectCandidate", "(", "filter", ".", "apply", "(", "target", ")", ",", "type", ",", "environment", ")", ";", "}" ]
<p> Given an arbitrary target type, filter out the target lambda types. For example, consider the following method: </p> <pre> type fun_t is function(int)->(int) method f(int x): fun_t|null xs = &(int y -> y+1) ... </pre> <p> When type checking the expression <code>&(int y -> y+1)</code> the flow type checker will attempt to determine an <i>expected</i> lambda type. In order to then determine the appropriate expected type for the lambda body <code>y+1</code> it filters <code>fun_t|null</code> down to just <code>fun_t</code>. </p> @param target Target type for this value @param expr Source expression for this value @author David J. Pearce
[ "<p", ">", "Given", "an", "arbitrary", "target", "type", "filter", "out", "the", "target", "lambda", "types", ".", "For", "example", "consider", "the", "following", "method", ":", "<", "/", "p", ">" ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/util/AbstractTypedVisitor.java#L1208-L1216
haraldk/TwelveMonkeys
imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageReaderBase.java
ImageReaderBase.fakeSubsampling
protected static Image fakeSubsampling(Image pImage, ImageReadParam pParam) { """ Utility method for getting the subsampled image. The subsampling is defined by the {@link javax.imageio.IIOParam#setSourceSubsampling(int, int, int, int)} method. <p/> NOTE: This method does not take the subsampling offsets into consideration. <p/> Note: If it is possible for the reader to subsample directly, such a method should be used instead, for efficiency. @param pImage the image to subsample @param pParam the param optionally specifying subsampling @return an {@code Image} containing the subsampled image, or the original image, if no subsampling was specified, or {@code pParam} was {@code null} """ return IIOUtil.fakeSubsampling(pImage, pParam); }
java
protected static Image fakeSubsampling(Image pImage, ImageReadParam pParam) { return IIOUtil.fakeSubsampling(pImage, pParam); }
[ "protected", "static", "Image", "fakeSubsampling", "(", "Image", "pImage", ",", "ImageReadParam", "pParam", ")", "{", "return", "IIOUtil", ".", "fakeSubsampling", "(", "pImage", ",", "pParam", ")", ";", "}" ]
Utility method for getting the subsampled image. The subsampling is defined by the {@link javax.imageio.IIOParam#setSourceSubsampling(int, int, int, int)} method. <p/> NOTE: This method does not take the subsampling offsets into consideration. <p/> Note: If it is possible for the reader to subsample directly, such a method should be used instead, for efficiency. @param pImage the image to subsample @param pParam the param optionally specifying subsampling @return an {@code Image} containing the subsampled image, or the original image, if no subsampling was specified, or {@code pParam} was {@code null}
[ "Utility", "method", "for", "getting", "the", "subsampled", "image", ".", "The", "subsampling", "is", "defined", "by", "the", "{", "@link", "javax", ".", "imageio", ".", "IIOParam#setSourceSubsampling", "(", "int", "int", "int", "int", ")", "}", "method", ".", "<p", "/", ">", "NOTE", ":", "This", "method", "does", "not", "take", "the", "subsampling", "offsets", "into", "consideration", ".", "<p", "/", ">", "Note", ":", "If", "it", "is", "possible", "for", "the", "reader", "to", "subsample", "directly", "such", "a", "method", "should", "be", "used", "instead", "for", "efficiency", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageReaderBase.java#L359-L361
vincentk/joptimizer
src/main/java/com/joptimizer/util/ColtUtils.java
ColtUtils.diagonalMatrixMult
public static final DoubleMatrix2D diagonalMatrixMult(final DoubleMatrix1D diagonalU, DoubleMatrix2D A, final DoubleMatrix1D diagonalV) { """ Return diagonalU.A.diagonalV with diagonalU and diagonalV diagonal. @param diagonalU diagonal matrix U, in the form of a vector of its diagonal elements @param diagonalV diagonal matrix V, in the form of a vector of its diagonal elements @return U.A.V """ int r = A.rows(); int c = A.columns(); final DoubleMatrix2D ret; if (A instanceof SparseDoubleMatrix2D) { ret = DoubleFactory2D.sparse.make(r, c); A.forEachNonZero(new IntIntDoubleFunction() { @Override public double apply(int i, int j, double aij) { ret.setQuick(i, j, aij * diagonalU.getQuick(i) * diagonalV.getQuick(j)); return aij; } }); } else { ret = DoubleFactory2D.dense.make(r, c); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { ret.setQuick(i, j, A.getQuick(i, j) * diagonalU.getQuick(i) * diagonalV.getQuick(j)); } } } return ret; }
java
public static final DoubleMatrix2D diagonalMatrixMult(final DoubleMatrix1D diagonalU, DoubleMatrix2D A, final DoubleMatrix1D diagonalV){ int r = A.rows(); int c = A.columns(); final DoubleMatrix2D ret; if (A instanceof SparseDoubleMatrix2D) { ret = DoubleFactory2D.sparse.make(r, c); A.forEachNonZero(new IntIntDoubleFunction() { @Override public double apply(int i, int j, double aij) { ret.setQuick(i, j, aij * diagonalU.getQuick(i) * diagonalV.getQuick(j)); return aij; } }); } else { ret = DoubleFactory2D.dense.make(r, c); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { ret.setQuick(i, j, A.getQuick(i, j) * diagonalU.getQuick(i) * diagonalV.getQuick(j)); } } } return ret; }
[ "public", "static", "final", "DoubleMatrix2D", "diagonalMatrixMult", "(", "final", "DoubleMatrix1D", "diagonalU", ",", "DoubleMatrix2D", "A", ",", "final", "DoubleMatrix1D", "diagonalV", ")", "{", "int", "r", "=", "A", ".", "rows", "(", ")", ";", "int", "c", "=", "A", ".", "columns", "(", ")", ";", "final", "DoubleMatrix2D", "ret", ";", "if", "(", "A", "instanceof", "SparseDoubleMatrix2D", ")", "{", "ret", "=", "DoubleFactory2D", ".", "sparse", ".", "make", "(", "r", ",", "c", ")", ";", "A", ".", "forEachNonZero", "(", "new", "IntIntDoubleFunction", "(", ")", "{", "@", "Override", "public", "double", "apply", "(", "int", "i", ",", "int", "j", ",", "double", "aij", ")", "{", "ret", ".", "setQuick", "(", "i", ",", "j", ",", "aij", "*", "diagonalU", ".", "getQuick", "(", "i", ")", "*", "diagonalV", ".", "getQuick", "(", "j", ")", ")", ";", "return", "aij", ";", "}", "}", ")", ";", "}", "else", "{", "ret", "=", "DoubleFactory2D", ".", "dense", ".", "make", "(", "r", ",", "c", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "r", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "c", ";", "j", "++", ")", "{", "ret", ".", "setQuick", "(", "i", ",", "j", ",", "A", ".", "getQuick", "(", "i", ",", "j", ")", "*", "diagonalU", ".", "getQuick", "(", "i", ")", "*", "diagonalV", ".", "getQuick", "(", "j", ")", ")", ";", "}", "}", "}", "return", "ret", ";", "}" ]
Return diagonalU.A.diagonalV with diagonalU and diagonalV diagonal. @param diagonalU diagonal matrix U, in the form of a vector of its diagonal elements @param diagonalV diagonal matrix V, in the form of a vector of its diagonal elements @return U.A.V
[ "Return", "diagonalU", ".", "A", ".", "diagonalV", "with", "diagonalU", "and", "diagonalV", "diagonal", "." ]
train
https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/util/ColtUtils.java#L122-L145
mbenson/therian
core/src/main/java/therian/TherianContext.java
TherianContext.evalIfSupported
public final synchronized <RESULT, OPERATION extends Operation<RESULT>> RESULT evalIfSupported(OPERATION operation, RESULT defaultValue, Hint... hints) { """ Evaluates {@code operation} if supported; otherwise returns {@code defaultValue}. @param operation @param defaultValue @param hints @return RESULT or {@code defaultValue} @throws NullPointerException on {@code null} input @throws OperationException potentially, via {@link Operation#getResult()} """ return evalSuccess(operation, hints) ? operation.getResult() : defaultValue; }
java
public final synchronized <RESULT, OPERATION extends Operation<RESULT>> RESULT evalIfSupported(OPERATION operation, RESULT defaultValue, Hint... hints) { return evalSuccess(operation, hints) ? operation.getResult() : defaultValue; }
[ "public", "final", "synchronized", "<", "RESULT", ",", "OPERATION", "extends", "Operation", "<", "RESULT", ">", ">", "RESULT", "evalIfSupported", "(", "OPERATION", "operation", ",", "RESULT", "defaultValue", ",", "Hint", "...", "hints", ")", "{", "return", "evalSuccess", "(", "operation", ",", "hints", ")", "?", "operation", ".", "getResult", "(", ")", ":", "defaultValue", ";", "}" ]
Evaluates {@code operation} if supported; otherwise returns {@code defaultValue}. @param operation @param defaultValue @param hints @return RESULT or {@code defaultValue} @throws NullPointerException on {@code null} input @throws OperationException potentially, via {@link Operation#getResult()}
[ "Evaluates", "{", "@code", "operation", "}", "if", "supported", ";", "otherwise", "returns", "{", "@code", "defaultValue", "}", "." ]
train
https://github.com/mbenson/therian/blob/0653505f73e2a6f5b0abc394ea6d83af03408254/core/src/main/java/therian/TherianContext.java#L394-L397
TNG/ArchUnit
archunit/src/main/java/com/tngtech/archunit/core/importer/Location.java
Location.encodeIllegalCharacters
private String encodeIllegalCharacters(String relativeURI) { """ hand form-encodes all characters, even '/' which we do not want. """ try { return new URI(null, null, relativeURI, null).toString(); } catch (URISyntaxException e) { throw new LocationException(e); } }
java
private String encodeIllegalCharacters(String relativeURI) { try { return new URI(null, null, relativeURI, null).toString(); } catch (URISyntaxException e) { throw new LocationException(e); } }
[ "private", "String", "encodeIllegalCharacters", "(", "String", "relativeURI", ")", "{", "try", "{", "return", "new", "URI", "(", "null", ",", "null", ",", "relativeURI", ",", "null", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "LocationException", "(", "e", ")", ";", "}", "}" ]
hand form-encodes all characters, even '/' which we do not want.
[ "hand", "form", "-", "encodes", "all", "characters", "even", "/", "which", "we", "do", "not", "want", "." ]
train
https://github.com/TNG/ArchUnit/blob/024c5d2502e91de6cb586b86c7084dbd12f3ef37/archunit/src/main/java/com/tngtech/archunit/core/importer/Location.java#L122-L128
pebble/pebble-android-sdk
PebbleKit/PebbleKit/src/main/java/com/getpebble/android/kit/PebbleKit.java
PebbleKit.registerReceivedDataHandler
public static BroadcastReceiver registerReceivedDataHandler(final Context context, final PebbleDataReceiver receiver) { """ A convenience function to assist in programatically registering a broadcast receiver for the 'RECEIVE' intent. To avoid leaking memory, activities registering BroadcastReceivers <em>must</em> unregister them in the Activity's {@link android.app.Activity#onPause()} method. @param context The context in which to register the BroadcastReceiver. @param receiver The receiver to be registered. @return The registered receiver. @see Constants#INTENT_APP_RECEIVE """ return registerBroadcastReceiverInternal(context, INTENT_APP_RECEIVE, receiver); }
java
public static BroadcastReceiver registerReceivedDataHandler(final Context context, final PebbleDataReceiver receiver) { return registerBroadcastReceiverInternal(context, INTENT_APP_RECEIVE, receiver); }
[ "public", "static", "BroadcastReceiver", "registerReceivedDataHandler", "(", "final", "Context", "context", ",", "final", "PebbleDataReceiver", "receiver", ")", "{", "return", "registerBroadcastReceiverInternal", "(", "context", ",", "INTENT_APP_RECEIVE", ",", "receiver", ")", ";", "}" ]
A convenience function to assist in programatically registering a broadcast receiver for the 'RECEIVE' intent. To avoid leaking memory, activities registering BroadcastReceivers <em>must</em> unregister them in the Activity's {@link android.app.Activity#onPause()} method. @param context The context in which to register the BroadcastReceiver. @param receiver The receiver to be registered. @return The registered receiver. @see Constants#INTENT_APP_RECEIVE
[ "A", "convenience", "function", "to", "assist", "in", "programatically", "registering", "a", "broadcast", "receiver", "for", "the", "RECEIVE", "intent", "." ]
train
https://github.com/pebble/pebble-android-sdk/blob/ddfc53ecf3950deebb62a1f205aa21fbe9bce45d/PebbleKit/PebbleKit/src/main/java/com/getpebble/android/kit/PebbleKit.java#L426-L429
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/webhook/WebhookMessage.java
WebhookMessage.files
public static WebhookMessage files(String name1, Object data1, Object... attachments) { """ forcing first pair as we expect at least one entry (Effective Java 3rd. Edition - Item 53) """ Checks.notBlank(name1, "Name"); Checks.notNull(data1, "Data"); Checks.notNull(attachments, "Attachments"); Checks.check(attachments.length % 2 == 0, "Must provide even number of varargs arguments"); int fileAmount = 1 + attachments.length / 2; Checks.check(fileAmount <= WebhookMessageBuilder.MAX_FILES, "Cannot add more than %d files to a message", WebhookMessageBuilder.MAX_FILES); MessageAttachment[] files = new MessageAttachment[fileAmount]; files[0] = convertAttachment(name1, data1); for (int i = 0, j = 1; i < attachments.length; j++, i += 2) { Object name = attachments[i]; Object data = attachments[i+1]; if (!(name instanceof String)) throw new IllegalArgumentException("Provided arguments must be pairs for (String, Data). Expected String and found " + (name == null ? null : name.getClass().getName())); files[j] = convertAttachment((String) name, data); } return new WebhookMessage(null, null, null, null, false, files); }
java
public static WebhookMessage files(String name1, Object data1, Object... attachments) { Checks.notBlank(name1, "Name"); Checks.notNull(data1, "Data"); Checks.notNull(attachments, "Attachments"); Checks.check(attachments.length % 2 == 0, "Must provide even number of varargs arguments"); int fileAmount = 1 + attachments.length / 2; Checks.check(fileAmount <= WebhookMessageBuilder.MAX_FILES, "Cannot add more than %d files to a message", WebhookMessageBuilder.MAX_FILES); MessageAttachment[] files = new MessageAttachment[fileAmount]; files[0] = convertAttachment(name1, data1); for (int i = 0, j = 1; i < attachments.length; j++, i += 2) { Object name = attachments[i]; Object data = attachments[i+1]; if (!(name instanceof String)) throw new IllegalArgumentException("Provided arguments must be pairs for (String, Data). Expected String and found " + (name == null ? null : name.getClass().getName())); files[j] = convertAttachment((String) name, data); } return new WebhookMessage(null, null, null, null, false, files); }
[ "public", "static", "WebhookMessage", "files", "(", "String", "name1", ",", "Object", "data1", ",", "Object", "...", "attachments", ")", "{", "Checks", ".", "notBlank", "(", "name1", ",", "\"Name\"", ")", ";", "Checks", ".", "notNull", "(", "data1", ",", "\"Data\"", ")", ";", "Checks", ".", "notNull", "(", "attachments", ",", "\"Attachments\"", ")", ";", "Checks", ".", "check", "(", "attachments", ".", "length", "%", "2", "==", "0", ",", "\"Must provide even number of varargs arguments\"", ")", ";", "int", "fileAmount", "=", "1", "+", "attachments", ".", "length", "/", "2", ";", "Checks", ".", "check", "(", "fileAmount", "<=", "WebhookMessageBuilder", ".", "MAX_FILES", ",", "\"Cannot add more than %d files to a message\"", ",", "WebhookMessageBuilder", ".", "MAX_FILES", ")", ";", "MessageAttachment", "[", "]", "files", "=", "new", "MessageAttachment", "[", "fileAmount", "]", ";", "files", "[", "0", "]", "=", "convertAttachment", "(", "name1", ",", "data1", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "1", ";", "i", "<", "attachments", ".", "length", ";", "j", "++", ",", "i", "+=", "2", ")", "{", "Object", "name", "=", "attachments", "[", "i", "]", ";", "Object", "data", "=", "attachments", "[", "i", "+", "1", "]", ";", "if", "(", "!", "(", "name", "instanceof", "String", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Provided arguments must be pairs for (String, Data). Expected String and found \"", "+", "(", "name", "==", "null", "?", "null", ":", "name", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ")", ";", "files", "[", "j", "]", "=", "convertAttachment", "(", "(", "String", ")", "name", ",", "data", ")", ";", "}", "return", "new", "WebhookMessage", "(", "null", ",", "null", ",", "null", ",", "null", ",", "false", ",", "files", ")", ";", "}" ]
forcing first pair as we expect at least one entry (Effective Java 3rd. Edition - Item 53)
[ "forcing", "first", "pair", "as", "we", "expect", "at", "least", "one", "entry", "(", "Effective", "Java", "3rd", ".", "Edition", "-", "Item", "53", ")" ]
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/webhook/WebhookMessage.java#L186-L205
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/crdt/CRDTReplicationMigrationService.java
CRDTReplicationMigrationService.setReplicatedVectorClocks
void setReplicatedVectorClocks(String serviceName, String memberUUID, Map<String, VectorClock> vectorClocks) { """ Sets the replicated vector clocks for the given {@code serviceName} and {@code memberUUID}. The vector clock map contains mappings from CRDT name to the last successfully replicated CRDT state version. All CRDTs in this map should be of the same type. @param serviceName the service name @param memberUUID the target member UUID @param vectorClocks the vector clocks to set @see CRDTReplicationAwareService """ replicationVectorClocks.setReplicatedVectorClocks(serviceName, memberUUID, vectorClocks); }
java
void setReplicatedVectorClocks(String serviceName, String memberUUID, Map<String, VectorClock> vectorClocks) { replicationVectorClocks.setReplicatedVectorClocks(serviceName, memberUUID, vectorClocks); }
[ "void", "setReplicatedVectorClocks", "(", "String", "serviceName", ",", "String", "memberUUID", ",", "Map", "<", "String", ",", "VectorClock", ">", "vectorClocks", ")", "{", "replicationVectorClocks", ".", "setReplicatedVectorClocks", "(", "serviceName", ",", "memberUUID", ",", "vectorClocks", ")", ";", "}" ]
Sets the replicated vector clocks for the given {@code serviceName} and {@code memberUUID}. The vector clock map contains mappings from CRDT name to the last successfully replicated CRDT state version. All CRDTs in this map should be of the same type. @param serviceName the service name @param memberUUID the target member UUID @param vectorClocks the vector clocks to set @see CRDTReplicationAwareService
[ "Sets", "the", "replicated", "vector", "clocks", "for", "the", "given", "{", "@code", "serviceName", "}", "and", "{", "@code", "memberUUID", "}", ".", "The", "vector", "clock", "map", "contains", "mappings", "from", "CRDT", "name", "to", "the", "last", "successfully", "replicated", "CRDT", "state", "version", ".", "All", "CRDTs", "in", "this", "map", "should", "be", "of", "the", "same", "type", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/crdt/CRDTReplicationMigrationService.java#L228-L230
lucee/Lucee
core/src/main/java/lucee/commons/lang/ClassUtil.java
ClassUtil.getSourcePathForClass
public static String getSourcePathForClass(String className, String defaultValue) { """ tries to load the class and returns the path that it was loaded from @param className - the name of the class to check @param defaultValue - a value to return in case the source could not be determined @return """ try { return getSourcePathForClass(ClassUtil.loadClass(className), defaultValue); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } return defaultValue; }
java
public static String getSourcePathForClass(String className, String defaultValue) { try { return getSourcePathForClass(ClassUtil.loadClass(className), defaultValue); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } return defaultValue; }
[ "public", "static", "String", "getSourcePathForClass", "(", "String", "className", ",", "String", "defaultValue", ")", "{", "try", "{", "return", "getSourcePathForClass", "(", "ClassUtil", ".", "loadClass", "(", "className", ")", ",", "defaultValue", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "ExceptionUtil", ".", "rethrowIfNecessary", "(", "t", ")", ";", "}", "return", "defaultValue", ";", "}" ]
tries to load the class and returns the path that it was loaded from @param className - the name of the class to check @param defaultValue - a value to return in case the source could not be determined @return
[ "tries", "to", "load", "the", "class", "and", "returns", "the", "path", "that", "it", "was", "loaded", "from" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/ClassUtil.java#L749-L760
wisdom-framework/wisdom
core/wisdom-api/src/main/java/org/wisdom/api/router/RouteBuilder.java
RouteBuilder.to
public Route to(Controller controller, Method method) { """ Sets the targeted action method of the resulting route. @param controller the controller object, must not be {@literal null}. @param method the method name, must not be {@literal null}. @return the current route builder """ Preconditions.checkNotNull(controller); Preconditions.checkNotNull(method); this.controller = controller; this.controllerMethod = method; if (!method.getReturnType().isAssignableFrom(Result.class)) { throw new IllegalArgumentException(ERROR_CTRL + method + ERROR_IN + controller .getClass() + "`, or the method does not return a " + Result.class.getName() + " object"); } return _build(); }
java
public Route to(Controller controller, Method method) { Preconditions.checkNotNull(controller); Preconditions.checkNotNull(method); this.controller = controller; this.controllerMethod = method; if (!method.getReturnType().isAssignableFrom(Result.class)) { throw new IllegalArgumentException(ERROR_CTRL + method + ERROR_IN + controller .getClass() + "`, or the method does not return a " + Result.class.getName() + " object"); } return _build(); }
[ "public", "Route", "to", "(", "Controller", "controller", ",", "Method", "method", ")", "{", "Preconditions", ".", "checkNotNull", "(", "controller", ")", ";", "Preconditions", ".", "checkNotNull", "(", "method", ")", ";", "this", ".", "controller", "=", "controller", ";", "this", ".", "controllerMethod", "=", "method", ";", "if", "(", "!", "method", ".", "getReturnType", "(", ")", ".", "isAssignableFrom", "(", "Result", ".", "class", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "ERROR_CTRL", "+", "method", "+", "ERROR_IN", "+", "controller", ".", "getClass", "(", ")", "+", "\"`, or the method does not return a \"", "+", "Result", ".", "class", ".", "getName", "(", ")", "+", "\" object\"", ")", ";", "}", "return", "_build", "(", ")", ";", "}" ]
Sets the targeted action method of the resulting route. @param controller the controller object, must not be {@literal null}. @param method the method name, must not be {@literal null}. @return the current route builder
[ "Sets", "the", "targeted", "action", "method", "of", "the", "resulting", "route", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-api/src/main/java/org/wisdom/api/router/RouteBuilder.java#L105-L115
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/FileUtils.java
FileUtils.toDocument
public static Document toDocument(final String aFilePath, final String aPattern, final boolean aDeepConversion) throws FileNotFoundException, ParserConfigurationException { """ Returns an XML Document representing the file structure found at the supplied file system path. Files included in the representation will match the supplied regular expression pattern. This method doesn't descend through the directory structure. @param aFilePath The directory from which the structural representation should be built @param aPattern A regular expression pattern which files included in the Document should match @param aDeepConversion Whether the conversion should descend through subdirectories @return An XML Document representation of the directory structure @throws FileNotFoundException If the supplied directory isn't found @throws ParserConfigurationException If the default XML parser for the JRE isn't configured correctly """ final Element element = toElement(aFilePath, aPattern, aDeepConversion); final Document document = element.getOwnerDocument(); document.appendChild(element); return document; }
java
public static Document toDocument(final String aFilePath, final String aPattern, final boolean aDeepConversion) throws FileNotFoundException, ParserConfigurationException { final Element element = toElement(aFilePath, aPattern, aDeepConversion); final Document document = element.getOwnerDocument(); document.appendChild(element); return document; }
[ "public", "static", "Document", "toDocument", "(", "final", "String", "aFilePath", ",", "final", "String", "aPattern", ",", "final", "boolean", "aDeepConversion", ")", "throws", "FileNotFoundException", ",", "ParserConfigurationException", "{", "final", "Element", "element", "=", "toElement", "(", "aFilePath", ",", "aPattern", ",", "aDeepConversion", ")", ";", "final", "Document", "document", "=", "element", ".", "getOwnerDocument", "(", ")", ";", "document", ".", "appendChild", "(", "element", ")", ";", "return", "document", ";", "}" ]
Returns an XML Document representing the file structure found at the supplied file system path. Files included in the representation will match the supplied regular expression pattern. This method doesn't descend through the directory structure. @param aFilePath The directory from which the structural representation should be built @param aPattern A regular expression pattern which files included in the Document should match @param aDeepConversion Whether the conversion should descend through subdirectories @return An XML Document representation of the directory structure @throws FileNotFoundException If the supplied directory isn't found @throws ParserConfigurationException If the default XML parser for the JRE isn't configured correctly
[ "Returns", "an", "XML", "Document", "representing", "the", "file", "structure", "found", "at", "the", "supplied", "file", "system", "path", ".", "Files", "included", "in", "the", "representation", "will", "match", "the", "supplied", "regular", "expression", "pattern", ".", "This", "method", "doesn", "t", "descend", "through", "the", "directory", "structure", "." ]
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/FileUtils.java#L310-L317
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/util/TimeIntervalFormatUtil.java
TimeIntervalFormatUtil.checkValidInterval
public static boolean checkValidInterval(int interval, TimeUnit unit) { """ 切替インターバルの値が閾値内に収まっているかの確認を行う。<br> <br> 切替インターバル {@literal 1<= interval <= 100} <br> 切替単位 MillSecond、Second、Minute、Hourのいずれか<br> @param interval 切替インターバル @param unit 切替単位 @return 切替インターバルの値が閾値内に収まっているか """ if (0 >= interval || INTERVAL_MAX < interval) { return false; } switch (unit) { case HOURS: break; case MINUTES: break; case SECONDS: break; case MILLISECONDS: break; default: return false; } return true; }
java
public static boolean checkValidInterval(int interval, TimeUnit unit) { if (0 >= interval || INTERVAL_MAX < interval) { return false; } switch (unit) { case HOURS: break; case MINUTES: break; case SECONDS: break; case MILLISECONDS: break; default: return false; } return true; }
[ "public", "static", "boolean", "checkValidInterval", "(", "int", "interval", ",", "TimeUnit", "unit", ")", "{", "if", "(", "0", ">=", "interval", "||", "INTERVAL_MAX", "<", "interval", ")", "{", "return", "false", ";", "}", "switch", "(", "unit", ")", "{", "case", "HOURS", ":", "break", ";", "case", "MINUTES", ":", "break", ";", "case", "SECONDS", ":", "break", ";", "case", "MILLISECONDS", ":", "break", ";", "default", ":", "return", "false", ";", "}", "return", "true", ";", "}" ]
切替インターバルの値が閾値内に収まっているかの確認を行う。<br> <br> 切替インターバル {@literal 1<= interval <= 100} <br> 切替単位 MillSecond、Second、Minute、Hourのいずれか<br> @param interval 切替インターバル @param unit 切替単位 @return 切替インターバルの値が閾値内に収まっているか
[ "切替インターバルの値が閾値内に収まっているかの確認を行う。<br", ">", "<br", ">", "切替インターバル", "{", "@literal", "1<", "=", "interval", "<", "=", "100", "}", "<br", ">", "切替単位", "MillSecond、Second、Minute、Hourのいずれか<br", ">" ]
train
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/util/TimeIntervalFormatUtil.java#L47-L69
VoltDB/voltdb
src/frontend/org/voltdb/jni/ExecutionEngineJNI.java
ExecutionEngineJNI.coreLoadCatalog
@Override protected void coreLoadCatalog(long timestamp, final byte[] catalogBytes) throws EEException { """ Provide a serialized catalog and initialize version 0 of the engine's catalog. """ LOG.trace("Loading Application Catalog..."); int errorCode = 0; errorCode = nativeLoadCatalog(pointer, timestamp, catalogBytes); checkErrorCode(errorCode); //LOG.info("Loaded Catalog."); }
java
@Override protected void coreLoadCatalog(long timestamp, final byte[] catalogBytes) throws EEException { LOG.trace("Loading Application Catalog..."); int errorCode = 0; errorCode = nativeLoadCatalog(pointer, timestamp, catalogBytes); checkErrorCode(errorCode); //LOG.info("Loaded Catalog."); }
[ "@", "Override", "protected", "void", "coreLoadCatalog", "(", "long", "timestamp", ",", "final", "byte", "[", "]", "catalogBytes", ")", "throws", "EEException", "{", "LOG", ".", "trace", "(", "\"Loading Application Catalog...\"", ")", ";", "int", "errorCode", "=", "0", ";", "errorCode", "=", "nativeLoadCatalog", "(", "pointer", ",", "timestamp", ",", "catalogBytes", ")", ";", "checkErrorCode", "(", "errorCode", ")", ";", "//LOG.info(\"Loaded Catalog.\");", "}" ]
Provide a serialized catalog and initialize version 0 of the engine's catalog.
[ "Provide", "a", "serialized", "catalog", "and", "initialize", "version", "0", "of", "the", "engine", "s", "catalog", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jni/ExecutionEngineJNI.java#L335-L342
kubernetes-client/java
util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java
SharedInformerFactory.sharedIndexInformerFor
public synchronized <ApiType, ApiListType> SharedIndexInformer<ApiType> sharedIndexInformerFor( Function<CallGeneratorParams, Call> callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass) { """ Shared index informer for shared index informer. @param <ApiType> the type parameter @param <ApiListType> the type parameter @param callGenerator the call generator @param apiTypeClass the api type class @param apiListTypeClass the api list type class @return the shared index informer """ return sharedIndexInformerFor(callGenerator, apiTypeClass, apiListTypeClass, 0); }
java
public synchronized <ApiType, ApiListType> SharedIndexInformer<ApiType> sharedIndexInformerFor( Function<CallGeneratorParams, Call> callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass) { return sharedIndexInformerFor(callGenerator, apiTypeClass, apiListTypeClass, 0); }
[ "public", "synchronized", "<", "ApiType", ",", "ApiListType", ">", "SharedIndexInformer", "<", "ApiType", ">", "sharedIndexInformerFor", "(", "Function", "<", "CallGeneratorParams", ",", "Call", ">", "callGenerator", ",", "Class", "<", "ApiType", ">", "apiTypeClass", ",", "Class", "<", "ApiListType", ">", "apiListTypeClass", ")", "{", "return", "sharedIndexInformerFor", "(", "callGenerator", ",", "apiTypeClass", ",", "apiListTypeClass", ",", "0", ")", ";", "}" ]
Shared index informer for shared index informer. @param <ApiType> the type parameter @param <ApiListType> the type parameter @param callGenerator the call generator @param apiTypeClass the api type class @param apiListTypeClass the api list type class @return the shared index informer
[ "Shared", "index", "informer", "for", "shared", "index", "informer", "." ]
train
https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java#L53-L58
Hygieia/Hygieia
collectors/artifact/artifactory/src/main/java/com/capitalone/dashboard/collector/DefaultArtifactoryClient.java
DefaultArtifactoryClient.joinUrl
private String joinUrl(String url, String... paths) { """ join a base url to another path or paths - this will handle trailing or non-trailing /'s """ StringBuilder result = new StringBuilder(url); for (String path : paths) { if (path != null) { String p = path.replaceFirst("^(\\/)+", ""); if (result.lastIndexOf("/") != result.length() - 1) { result.append('/'); } result.append(p); } } return result.toString(); }
java
private String joinUrl(String url, String... paths) { StringBuilder result = new StringBuilder(url); for (String path : paths) { if (path != null) { String p = path.replaceFirst("^(\\/)+", ""); if (result.lastIndexOf("/") != result.length() - 1) { result.append('/'); } result.append(p); } } return result.toString(); }
[ "private", "String", "joinUrl", "(", "String", "url", ",", "String", "...", "paths", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", "url", ")", ";", "for", "(", "String", "path", ":", "paths", ")", "{", "if", "(", "path", "!=", "null", ")", "{", "String", "p", "=", "path", ".", "replaceFirst", "(", "\"^(\\\\/)+\"", ",", "\"\"", ")", ";", "if", "(", "result", ".", "lastIndexOf", "(", "\"/\"", ")", "!=", "result", ".", "length", "(", ")", "-", "1", ")", "{", "result", ".", "append", "(", "'", "'", ")", ";", "}", "result", ".", "append", "(", "p", ")", ";", "}", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
join a base url to another path or paths - this will handle trailing or non-trailing /'s
[ "join", "a", "base", "url", "to", "another", "path", "or", "paths", "-", "this", "will", "handle", "trailing", "or", "non", "-", "trailing", "/", "s" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/artifact/artifactory/src/main/java/com/capitalone/dashboard/collector/DefaultArtifactoryClient.java#L413-L425
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/mime/MimeTypeParser.java
MimeTypeParser.safeParseMimeType
@Nullable public static MimeType safeParseMimeType (@Nullable final String sMimeType, @Nonnull final EMimeQuoting eQuotingAlgorithm) { """ Try to convert the string representation of a MIME type to an object. The default quoting algorithm {@link CMimeType#DEFAULT_QUOTING} is used to un-quote strings. Compared to {@link #parseMimeType(String, EMimeQuoting)} this method swallows all {@link MimeTypeParserException} and simply returns <code>null</code>. @param sMimeType The string representation to be converted. May be <code>null</code>. @param eQuotingAlgorithm The quoting algorithm to be used to un-quote parameter values. May not be <code>null</code>. @return <code>null</code> if the parsed string is empty or not a valid mime type. """ try { return parseMimeType (sMimeType, eQuotingAlgorithm); } catch (final MimeTypeParserException ex) { return null; } }
java
@Nullable public static MimeType safeParseMimeType (@Nullable final String sMimeType, @Nonnull final EMimeQuoting eQuotingAlgorithm) { try { return parseMimeType (sMimeType, eQuotingAlgorithm); } catch (final MimeTypeParserException ex) { return null; } }
[ "@", "Nullable", "public", "static", "MimeType", "safeParseMimeType", "(", "@", "Nullable", "final", "String", "sMimeType", ",", "@", "Nonnull", "final", "EMimeQuoting", "eQuotingAlgorithm", ")", "{", "try", "{", "return", "parseMimeType", "(", "sMimeType", ",", "eQuotingAlgorithm", ")", ";", "}", "catch", "(", "final", "MimeTypeParserException", "ex", ")", "{", "return", "null", ";", "}", "}" ]
Try to convert the string representation of a MIME type to an object. The default quoting algorithm {@link CMimeType#DEFAULT_QUOTING} is used to un-quote strings. Compared to {@link #parseMimeType(String, EMimeQuoting)} this method swallows all {@link MimeTypeParserException} and simply returns <code>null</code>. @param sMimeType The string representation to be converted. May be <code>null</code>. @param eQuotingAlgorithm The quoting algorithm to be used to un-quote parameter values. May not be <code>null</code>. @return <code>null</code> if the parsed string is empty or not a valid mime type.
[ "Try", "to", "convert", "the", "string", "representation", "of", "a", "MIME", "type", "to", "an", "object", ".", "The", "default", "quoting", "algorithm", "{", "@link", "CMimeType#DEFAULT_QUOTING", "}", "is", "used", "to", "un", "-", "quote", "strings", ".", "Compared", "to", "{", "@link", "#parseMimeType", "(", "String", "EMimeQuoting", ")", "}", "this", "method", "swallows", "all", "{", "@link", "MimeTypeParserException", "}", "and", "simply", "returns", "<code", ">", "null<", "/", "code", ">", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/mime/MimeTypeParser.java#L418-L430
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/EffectSize.java
EffectSize.getCohenD
public static <V> double getCohenD(final int baselineN, final double baselineMean, final double baselineStd, final int testN, final double testMean, final double testStd) { """ Original Cohen's d formulation, as in Cohen (1988), Statistical power analysis for the behavioral sciences. @param <V> type of the keys of each map. @param baselineN number of samples of baseline method. @param baselineMean mean of baseline method. @param baselineStd standard deviation of baseline method. @param testN number of samples of test method. @param testMean mean of test method. @param testStd standard deviation of test method. @return Cohen's d without least squares estimation. """ double pooledStd = Math.sqrt(((testN - 1) * Math.pow(testStd, 2) + (baselineN - 1) * Math.pow(baselineStd, 2)) / (baselineN + testN)); double d = Math.abs(testMean - baselineMean) / pooledStd; return d; }
java
public static <V> double getCohenD(final int baselineN, final double baselineMean, final double baselineStd, final int testN, final double testMean, final double testStd) { double pooledStd = Math.sqrt(((testN - 1) * Math.pow(testStd, 2) + (baselineN - 1) * Math.pow(baselineStd, 2)) / (baselineN + testN)); double d = Math.abs(testMean - baselineMean) / pooledStd; return d; }
[ "public", "static", "<", "V", ">", "double", "getCohenD", "(", "final", "int", "baselineN", ",", "final", "double", "baselineMean", ",", "final", "double", "baselineStd", ",", "final", "int", "testN", ",", "final", "double", "testMean", ",", "final", "double", "testStd", ")", "{", "double", "pooledStd", "=", "Math", ".", "sqrt", "(", "(", "(", "testN", "-", "1", ")", "*", "Math", ".", "pow", "(", "testStd", ",", "2", ")", "+", "(", "baselineN", "-", "1", ")", "*", "Math", ".", "pow", "(", "baselineStd", ",", "2", ")", ")", "/", "(", "baselineN", "+", "testN", ")", ")", ";", "double", "d", "=", "Math", ".", "abs", "(", "testMean", "-", "baselineMean", ")", "/", "pooledStd", ";", "return", "d", ";", "}" ]
Original Cohen's d formulation, as in Cohen (1988), Statistical power analysis for the behavioral sciences. @param <V> type of the keys of each map. @param baselineN number of samples of baseline method. @param baselineMean mean of baseline method. @param baselineStd standard deviation of baseline method. @param testN number of samples of test method. @param testMean mean of test method. @param testStd standard deviation of test method. @return Cohen's d without least squares estimation.
[ "Original", "Cohen", "s", "d", "formulation", "as", "in", "Cohen", "(", "1988", ")", "Statistical", "power", "analysis", "for", "the", "behavioral", "sciences", "." ]
train
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/EffectSize.java#L122-L127
Sciss/abc4j
abc/src/main/java/abc/ui/swing/ScoreTemplate.java
ScoreTemplate.setTextStyle
public void setTextStyle(byte[] fields, int style) { """ Sets the font style of several fields @param fields array of {@link ScoreElements} constants @param style style from Font class : {@link Font#PLAIN}, {@link Font#BOLD}, {@link Font#ITALIC} or Font.BOLD+Font.ITALIC """ for (byte field : fields) { getFieldInfos(field).m_fontStyle = style; } notifyListeners(); }
java
public void setTextStyle(byte[] fields, int style) { for (byte field : fields) { getFieldInfos(field).m_fontStyle = style; } notifyListeners(); }
[ "public", "void", "setTextStyle", "(", "byte", "[", "]", "fields", ",", "int", "style", ")", "{", "for", "(", "byte", "field", ":", "fields", ")", "{", "getFieldInfos", "(", "field", ")", ".", "m_fontStyle", "=", "style", ";", "}", "notifyListeners", "(", ")", ";", "}" ]
Sets the font style of several fields @param fields array of {@link ScoreElements} constants @param style style from Font class : {@link Font#PLAIN}, {@link Font#BOLD}, {@link Font#ITALIC} or Font.BOLD+Font.ITALIC
[ "Sets", "the", "font", "style", "of", "several", "fields" ]
train
https://github.com/Sciss/abc4j/blob/117b405642c84a7bfca4e3e13668838258b90ca7/abc/src/main/java/abc/ui/swing/ScoreTemplate.java#L1013-L1018
bbossgroups/bboss-elasticsearch
bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/BucketPath.java
BucketPath.getEscapeMapping
@Deprecated public static Map<String, String> getEscapeMapping(String in, Map<String, String> headers) { """ Instead of replacing escape sequences in a string, this method returns a mapping of an attribute name to the value based on the escape sequence found in the argument string. """ return getEscapeMapping(in, headers, false, 0, 0); }
java
@Deprecated public static Map<String, String> getEscapeMapping(String in, Map<String, String> headers) { return getEscapeMapping(in, headers, false, 0, 0); }
[ "@", "Deprecated", "public", "static", "Map", "<", "String", ",", "String", ">", "getEscapeMapping", "(", "String", "in", ",", "Map", "<", "String", ",", "String", ">", "headers", ")", "{", "return", "getEscapeMapping", "(", "in", ",", "headers", ",", "false", ",", "0", ",", "0", ")", ";", "}" ]
Instead of replacing escape sequences in a string, this method returns a mapping of an attribute name to the value based on the escape sequence found in the argument string.
[ "Instead", "of", "replacing", "escape", "sequences", "in", "a", "string", "this", "method", "returns", "a", "mapping", "of", "an", "attribute", "name", "to", "the", "value", "based", "on", "the", "escape", "sequence", "found", "in", "the", "argument", "string", "." ]
train
https://github.com/bbossgroups/bboss-elasticsearch/blob/31717c8aa2c4c880987be53aeeb8a0cf5183c3a7/bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/BucketPath.java#L487-L491
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/util/LightWeightGSet.java
LightWeightGSet.shardIterator
@Override public Iterator<E> shardIterator(int shardId, int numShards) { """ Get iterator over a part of the blocks map. @param shardId index of the starting bucket @param numShards next bucket is obtained by index+=numShards """ if (shardId >= entries.length) { return null; } if (shardId >= numShards) { throw new IllegalArgumentException( "Shard id must be less than total shards, shardId: " + shardId + ", numShards: " + numShards); } return new SetIterator(shardId, numShards); }
java
@Override public Iterator<E> shardIterator(int shardId, int numShards) { if (shardId >= entries.length) { return null; } if (shardId >= numShards) { throw new IllegalArgumentException( "Shard id must be less than total shards, shardId: " + shardId + ", numShards: " + numShards); } return new SetIterator(shardId, numShards); }
[ "@", "Override", "public", "Iterator", "<", "E", ">", "shardIterator", "(", "int", "shardId", ",", "int", "numShards", ")", "{", "if", "(", "shardId", ">=", "entries", ".", "length", ")", "{", "return", "null", ";", "}", "if", "(", "shardId", ">=", "numShards", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Shard id must be less than total shards, shardId: \"", "+", "shardId", "+", "\", numShards: \"", "+", "numShards", ")", ";", "}", "return", "new", "SetIterator", "(", "shardId", ",", "numShards", ")", ";", "}" ]
Get iterator over a part of the blocks map. @param shardId index of the starting bucket @param numShards next bucket is obtained by index+=numShards
[ "Get", "iterator", "over", "a", "part", "of", "the", "blocks", "map", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/util/LightWeightGSet.java#L223-L234
lessthanoptimal/BoofCV
integration/boofcv-openkinect/src/main/java/boofcv/openkinect/UtilOpenKinect.java
UtilOpenKinect.bufferDepthToU16
public static void bufferDepthToU16( ByteBuffer input , GrayU16 output ) { """ Converts data in a ByteBuffer into a 16bit depth image @param input Input buffer @param output Output depth image """ int indexIn = 0; for( int y = 0; y < output.height; y++ ) { int indexOut = output.startIndex + y*output.stride; for( int x = 0; x < output.width; x++ , indexOut++ ) { output.data[indexOut] = (short)((input.get(indexIn++) & 0xFF) | ((input.get(indexIn++) & 0xFF) << 8 )); } } }
java
public static void bufferDepthToU16( ByteBuffer input , GrayU16 output ) { int indexIn = 0; for( int y = 0; y < output.height; y++ ) { int indexOut = output.startIndex + y*output.stride; for( int x = 0; x < output.width; x++ , indexOut++ ) { output.data[indexOut] = (short)((input.get(indexIn++) & 0xFF) | ((input.get(indexIn++) & 0xFF) << 8 )); } } }
[ "public", "static", "void", "bufferDepthToU16", "(", "ByteBuffer", "input", ",", "GrayU16", "output", ")", "{", "int", "indexIn", "=", "0", ";", "for", "(", "int", "y", "=", "0", ";", "y", "<", "output", ".", "height", ";", "y", "++", ")", "{", "int", "indexOut", "=", "output", ".", "startIndex", "+", "y", "*", "output", ".", "stride", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "output", ".", "width", ";", "x", "++", ",", "indexOut", "++", ")", "{", "output", ".", "data", "[", "indexOut", "]", "=", "(", "short", ")", "(", "(", "input", ".", "get", "(", "indexIn", "++", ")", "&", "0xFF", ")", "|", "(", "(", "input", ".", "get", "(", "indexIn", "++", ")", "&", "0xFF", ")", "<<", "8", ")", ")", ";", "}", "}", "}" ]
Converts data in a ByteBuffer into a 16bit depth image @param input Input buffer @param output Output depth image
[ "Converts", "data", "in", "a", "ByteBuffer", "into", "a", "16bit", "depth", "image" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-openkinect/src/main/java/boofcv/openkinect/UtilOpenKinect.java#L65-L73
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/lang/EnumHelper.java
EnumHelper.getFromIDCaseInsensitiveOrNull
@Nullable public static <ENUMTYPE extends Enum <ENUMTYPE> & IHasID <String>> ENUMTYPE getFromIDCaseInsensitiveOrNull (@Nonnull final Class <ENUMTYPE> aClass, @Nullable final String sID) { """ Get the enum value with the passed string ID case insensitive @param <ENUMTYPE> The enum type @param aClass The enum class @param sID The ID to search @return <code>null</code> if no enum item with the given ID is present. """ return getFromIDCaseInsensitiveOrDefault (aClass, sID, null); }
java
@Nullable public static <ENUMTYPE extends Enum <ENUMTYPE> & IHasID <String>> ENUMTYPE getFromIDCaseInsensitiveOrNull (@Nonnull final Class <ENUMTYPE> aClass, @Nullable final String sID) { return getFromIDCaseInsensitiveOrDefault (aClass, sID, null); }
[ "@", "Nullable", "public", "static", "<", "ENUMTYPE", "extends", "Enum", "<", "ENUMTYPE", ">", "&", "IHasID", "<", "String", ">", ">", "ENUMTYPE", "getFromIDCaseInsensitiveOrNull", "(", "@", "Nonnull", "final", "Class", "<", "ENUMTYPE", ">", "aClass", ",", "@", "Nullable", "final", "String", "sID", ")", "{", "return", "getFromIDCaseInsensitiveOrDefault", "(", "aClass", ",", "sID", ",", "null", ")", ";", "}" ]
Get the enum value with the passed string ID case insensitive @param <ENUMTYPE> The enum type @param aClass The enum class @param sID The ID to search @return <code>null</code> if no enum item with the given ID is present.
[ "Get", "the", "enum", "value", "with", "the", "passed", "string", "ID", "case", "insensitive" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/EnumHelper.java#L172-L177
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.archiveEquals
public static boolean archiveEquals(File f1, File f2) { """ Compares two ZIP files and returns <code>true</code> if they contain same entries. <p> First the two files are compared byte-by-byte. If a difference is found the corresponding entries of both ZIP files are compared. Thus if same contents is packed differently the two archives may still be the same. </p> <p> Two archives are considered the same if <ol> <li>they contain same number of entries,</li> <li>for each entry in the first archive there exists an entry with the same in the second archive</li> <li>for each entry in the first archive and the entry with the same name in the second archive <ol> <li>both are either directories or files,</li> <li>both have the same size,</li> <li>both have the same CRC,</li> <li>both have the same contents (compared byte-by-byte).</li> </ol> </li> </ol> @param f1 first ZIP file. @param f2 second ZIP file. @return <code>true</code> if the two ZIP files contain same entries, <code>false</code> if a difference was found or an error occurred during the comparison. """ try { // Check the files byte-by-byte if (FileUtils.contentEquals(f1, f2)) { return true; } log.debug("Comparing archives '{}' and '{}'...", f1, f2); long start = System.currentTimeMillis(); boolean result = archiveEqualsInternal(f1, f2); long time = System.currentTimeMillis() - start; if (time > 0) { log.debug("Archives compared in " + time + " ms."); } return result; } catch (Exception e) { log.debug("Could not compare '" + f1 + "' and '" + f2 + "':", e); return false; } }
java
public static boolean archiveEquals(File f1, File f2) { try { // Check the files byte-by-byte if (FileUtils.contentEquals(f1, f2)) { return true; } log.debug("Comparing archives '{}' and '{}'...", f1, f2); long start = System.currentTimeMillis(); boolean result = archiveEqualsInternal(f1, f2); long time = System.currentTimeMillis() - start; if (time > 0) { log.debug("Archives compared in " + time + " ms."); } return result; } catch (Exception e) { log.debug("Could not compare '" + f1 + "' and '" + f2 + "':", e); return false; } }
[ "public", "static", "boolean", "archiveEquals", "(", "File", "f1", ",", "File", "f2", ")", "{", "try", "{", "// Check the files byte-by-byte", "if", "(", "FileUtils", ".", "contentEquals", "(", "f1", ",", "f2", ")", ")", "{", "return", "true", ";", "}", "log", ".", "debug", "(", "\"Comparing archives '{}' and '{}'...\"", ",", "f1", ",", "f2", ")", ";", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "boolean", "result", "=", "archiveEqualsInternal", "(", "f1", ",", "f2", ")", ";", "long", "time", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ";", "if", "(", "time", ">", "0", ")", "{", "log", ".", "debug", "(", "\"Archives compared in \"", "+", "time", "+", "\" ms.\"", ")", ";", "}", "return", "result", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "debug", "(", "\"Could not compare '\"", "+", "f1", "+", "\"' and '\"", "+", "f2", "+", "\"':\"", ",", "e", ")", ";", "return", "false", ";", "}", "}" ]
Compares two ZIP files and returns <code>true</code> if they contain same entries. <p> First the two files are compared byte-by-byte. If a difference is found the corresponding entries of both ZIP files are compared. Thus if same contents is packed differently the two archives may still be the same. </p> <p> Two archives are considered the same if <ol> <li>they contain same number of entries,</li> <li>for each entry in the first archive there exists an entry with the same in the second archive</li> <li>for each entry in the first archive and the entry with the same name in the second archive <ol> <li>both are either directories or files,</li> <li>both have the same size,</li> <li>both have the same CRC,</li> <li>both have the same contents (compared byte-by-byte).</li> </ol> </li> </ol> @param f1 first ZIP file. @param f2 second ZIP file. @return <code>true</code> if the two ZIP files contain same entries, <code>false</code> if a difference was found or an error occurred during the comparison.
[ "Compares", "two", "ZIP", "files", "and", "returns", "<code", ">", "true<", "/", "code", ">", "if", "they", "contain", "same", "entries", ".", "<p", ">", "First", "the", "two", "files", "are", "compared", "byte", "-", "by", "-", "byte", ".", "If", "a", "difference", "is", "found", "the", "corresponding", "entries", "of", "both", "ZIP", "files", "are", "compared", ".", "Thus", "if", "same", "contents", "is", "packed", "differently", "the", "two", "archives", "may", "still", "be", "the", "same", ".", "<", "/", "p", ">", "<p", ">", "Two", "archives", "are", "considered", "the", "same", "if", "<ol", ">", "<li", ">", "they", "contain", "same", "number", "of", "entries", "<", "/", "li", ">", "<li", ">", "for", "each", "entry", "in", "the", "first", "archive", "there", "exists", "an", "entry", "with", "the", "same", "in", "the", "second", "archive<", "/", "li", ">", "<li", ">", "for", "each", "entry", "in", "the", "first", "archive", "and", "the", "entry", "with", "the", "same", "name", "in", "the", "second", "archive", "<ol", ">", "<li", ">", "both", "are", "either", "directories", "or", "files", "<", "/", "li", ">", "<li", ">", "both", "have", "the", "same", "size", "<", "/", "li", ">", "<li", ">", "both", "have", "the", "same", "CRC", "<", "/", "li", ">", "<li", ">", "both", "have", "the", "same", "contents", "(", "compared", "byte", "-", "by", "-", "byte", ")", ".", "<", "/", "li", ">", "<", "/", "ol", ">", "<", "/", "li", ">", "<", "/", "ol", ">" ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L3048-L3069
app55/app55-java
src/support/java/com/googlecode/openbeans/Encoder.java
Encoder.setPersistenceDelegate
public void setPersistenceDelegate(Class<?> type, PersistenceDelegate delegate) { """ Register the <code>PersistenceDelegate</code> of the specified type. @param type @param delegate """ if (type == null || delegate == null) { throw new NullPointerException(); } delegates.put(type, delegate); }
java
public void setPersistenceDelegate(Class<?> type, PersistenceDelegate delegate) { if (type == null || delegate == null) { throw new NullPointerException(); } delegates.put(type, delegate); }
[ "public", "void", "setPersistenceDelegate", "(", "Class", "<", "?", ">", "type", ",", "PersistenceDelegate", "delegate", ")", "{", "if", "(", "type", "==", "null", "||", "delegate", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "delegates", ".", "put", "(", "type", ",", "delegate", ")", ";", "}" ]
Register the <code>PersistenceDelegate</code> of the specified type. @param type @param delegate
[ "Register", "the", "<code", ">", "PersistenceDelegate<", "/", "code", ">", "of", "the", "specified", "type", "." ]
train
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/Encoder.java#L296-L303
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Collectors.java
Collectors.averagingDouble
@NotNull public static <T> Collector<T, ?, Double> averagingDouble(@NotNull final ToDoubleFunction<? super T> mapper) { """ Returns a {@code Collector} that calculates average of double-valued input elements. @param <T> the type of the input elements @param mapper the mapping function which extracts value from element to calculate result @return a {@code Collector} @since 1.1.3 """ return new CollectorsImpl<T, double[], Double>( DOUBLE_2ELEMENTS_ARRAY_SUPPLIER, new BiConsumer<double[], T>() { @Override public void accept(double[] t, T u) { t[0]++; // count t[1] += mapper.applyAsDouble(u); // sum } }, new Function<double[], Double>() { @NotNull @Override public Double apply(double[] t) { if (t[0] == 0) return 0d; return t[1] / t[0]; } } ); }
java
@NotNull public static <T> Collector<T, ?, Double> averagingDouble(@NotNull final ToDoubleFunction<? super T> mapper) { return new CollectorsImpl<T, double[], Double>( DOUBLE_2ELEMENTS_ARRAY_SUPPLIER, new BiConsumer<double[], T>() { @Override public void accept(double[] t, T u) { t[0]++; // count t[1] += mapper.applyAsDouble(u); // sum } }, new Function<double[], Double>() { @NotNull @Override public Double apply(double[] t) { if (t[0] == 0) return 0d; return t[1] / t[0]; } } ); }
[ "@", "NotNull", "public", "static", "<", "T", ">", "Collector", "<", "T", ",", "?", ",", "Double", ">", "averagingDouble", "(", "@", "NotNull", "final", "ToDoubleFunction", "<", "?", "super", "T", ">", "mapper", ")", "{", "return", "new", "CollectorsImpl", "<", "T", ",", "double", "[", "]", ",", "Double", ">", "(", "DOUBLE_2ELEMENTS_ARRAY_SUPPLIER", ",", "new", "BiConsumer", "<", "double", "[", "]", ",", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "double", "[", "]", "t", ",", "T", "u", ")", "{", "t", "[", "0", "]", "++", ";", "// count", "t", "[", "1", "]", "+=", "mapper", ".", "applyAsDouble", "(", "u", ")", ";", "// sum", "}", "}", ",", "new", "Function", "<", "double", "[", "]", ",", "Double", ">", "(", ")", "{", "@", "NotNull", "@", "Override", "public", "Double", "apply", "(", "double", "[", "]", "t", ")", "{", "if", "(", "t", "[", "0", "]", "==", "0", ")", "return", "0d", ";", "return", "t", "[", "1", "]", "/", "t", "[", "0", "]", ";", "}", "}", ")", ";", "}" ]
Returns a {@code Collector} that calculates average of double-valued input elements. @param <T> the type of the input elements @param mapper the mapping function which extracts value from element to calculate result @return a {@code Collector} @since 1.1.3
[ "Returns", "a", "{", "@code", "Collector", "}", "that", "calculates", "average", "of", "double", "-", "valued", "input", "elements", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L544-L567
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/cursor/FilteredCursor.java
FilteredCursor.applyFilter
public static <S extends Storable> Cursor<S> applyFilter(Cursor<S> cursor, Class<S> type, String filter, Object... filterValues) { """ Returns a Cursor that is filtered by the given filter expression and values. @param cursor cursor to wrap @param type type of storable @param filter filter to apply @param filterValues values for filter @return wrapped cursor which filters results @throws IllegalStateException if any values are not specified @throws IllegalArgumentException if any argument is null @since 1.2 """ Filter<S> f = Filter.filterFor(type, filter).bind(); FilterValues<S> fv = f.initialFilterValues().withValues(filterValues); return applyFilter(f, fv, cursor); }
java
public static <S extends Storable> Cursor<S> applyFilter(Cursor<S> cursor, Class<S> type, String filter, Object... filterValues) { Filter<S> f = Filter.filterFor(type, filter).bind(); FilterValues<S> fv = f.initialFilterValues().withValues(filterValues); return applyFilter(f, fv, cursor); }
[ "public", "static", "<", "S", "extends", "Storable", ">", "Cursor", "<", "S", ">", "applyFilter", "(", "Cursor", "<", "S", ">", "cursor", ",", "Class", "<", "S", ">", "type", ",", "String", "filter", ",", "Object", "...", "filterValues", ")", "{", "Filter", "<", "S", ">", "f", "=", "Filter", ".", "filterFor", "(", "type", ",", "filter", ")", ".", "bind", "(", ")", ";", "FilterValues", "<", "S", ">", "fv", "=", "f", ".", "initialFilterValues", "(", ")", ".", "withValues", "(", "filterValues", ")", ";", "return", "applyFilter", "(", "f", ",", "fv", ",", "cursor", ")", ";", "}" ]
Returns a Cursor that is filtered by the given filter expression and values. @param cursor cursor to wrap @param type type of storable @param filter filter to apply @param filterValues values for filter @return wrapped cursor which filters results @throws IllegalStateException if any values are not specified @throws IllegalArgumentException if any argument is null @since 1.2
[ "Returns", "a", "Cursor", "that", "is", "filtered", "by", "the", "given", "filter", "expression", "and", "values", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/cursor/FilteredCursor.java#L49-L57
netty/netty-tcnative
openssl-dynamic/src/main/java/io/netty/internal/tcnative/Library.java
Library.initialize
public static boolean initialize(String libraryName, String engine) throws Exception { """ Setup native library. This is the first method that must be called! @param libraryName the name of the library to load @param engine Support for external a Crypto Device ("engine"), usually @return {@code true} if initialization was successful @throws Exception if an error happens during initialization """ if (_instance == null) { _instance = libraryName == null ? new Library() : new Library(libraryName); if (aprMajorVersion() < 1) { throw new UnsatisfiedLinkError("Unsupported APR Version (" + aprVersionString() + ")"); } if (!aprHasThreads()) { throw new UnsatisfiedLinkError("Missing APR_HAS_THREADS"); } } return initialize0() && SSL.initialize(engine) == 0; }
java
public static boolean initialize(String libraryName, String engine) throws Exception { if (_instance == null) { _instance = libraryName == null ? new Library() : new Library(libraryName); if (aprMajorVersion() < 1) { throw new UnsatisfiedLinkError("Unsupported APR Version (" + aprVersionString() + ")"); } if (!aprHasThreads()) { throw new UnsatisfiedLinkError("Missing APR_HAS_THREADS"); } } return initialize0() && SSL.initialize(engine) == 0; }
[ "public", "static", "boolean", "initialize", "(", "String", "libraryName", ",", "String", "engine", ")", "throws", "Exception", "{", "if", "(", "_instance", "==", "null", ")", "{", "_instance", "=", "libraryName", "==", "null", "?", "new", "Library", "(", ")", ":", "new", "Library", "(", "libraryName", ")", ";", "if", "(", "aprMajorVersion", "(", ")", "<", "1", ")", "{", "throw", "new", "UnsatisfiedLinkError", "(", "\"Unsupported APR Version (\"", "+", "aprVersionString", "(", ")", "+", "\")\"", ")", ";", "}", "if", "(", "!", "aprHasThreads", "(", ")", ")", "{", "throw", "new", "UnsatisfiedLinkError", "(", "\"Missing APR_HAS_THREADS\"", ")", ";", "}", "}", "return", "initialize0", "(", ")", "&&", "SSL", ".", "initialize", "(", "engine", ")", "==", "0", ";", "}" ]
Setup native library. This is the first method that must be called! @param libraryName the name of the library to load @param engine Support for external a Crypto Device ("engine"), usually @return {@code true} if initialization was successful @throws Exception if an error happens during initialization
[ "Setup", "native", "library", ".", "This", "is", "the", "first", "method", "that", "must", "be", "called!" ]
train
https://github.com/netty/netty-tcnative/blob/4a5d7330c6c36cff2bebbb465571cab1cf7a4063/openssl-dynamic/src/main/java/io/netty/internal/tcnative/Library.java#L145-L159
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/StandardDiskConfiguration.java
StandardDiskConfiguration.of
public static StandardDiskConfiguration of(DiskTypeId diskType, long sizeGb) { """ Returns a {@code StandardDiskConfiguration} object given the disk type and size in GB. """ return newBuilder().setDiskType(diskType).setSizeGb(sizeGb).build(); }
java
public static StandardDiskConfiguration of(DiskTypeId diskType, long sizeGb) { return newBuilder().setDiskType(diskType).setSizeGb(sizeGb).build(); }
[ "public", "static", "StandardDiskConfiguration", "of", "(", "DiskTypeId", "diskType", ",", "long", "sizeGb", ")", "{", "return", "newBuilder", "(", ")", ".", "setDiskType", "(", "diskType", ")", ".", "setSizeGb", "(", "sizeGb", ")", ".", "build", "(", ")", ";", "}" ]
Returns a {@code StandardDiskConfiguration} object given the disk type and size in GB.
[ "Returns", "a", "{" ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/StandardDiskConfiguration.java#L108-L110
JOML-CI/JOML
src/org/joml/Intersectiond.java
Intersectiond.intersectRaySphere
public static boolean intersectRaySphere(Vector3dc origin, Vector3dc dir, Vector3dc center, double radiusSquared, Vector2d result) { """ Test whether the ray with the given <code>origin</code> and normalized direction <code>dir</code> intersects the sphere with the given <code>center</code> and square radius <code>radiusSquared</code>, and store the values of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> for both points (near and far) of intersections into the given <code>result</code> vector. <p> This method returns <code>true</code> for a ray whose origin lies inside the sphere. <p> Reference: <a href="http://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-sphere-intersection">http://www.scratchapixel.com/</a> @param origin the ray's origin @param dir the ray's normalized direction @param center the sphere's center @param radiusSquared the sphere radius squared @param result a vector that will contain the values of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> for both points (near, far) of intersections with the sphere @return <code>true</code> if the ray intersects the sphere; <code>false</code> otherwise """ return intersectRaySphere(origin.x(), origin.y(), origin.z(), dir.x(), dir.y(), dir.z(), center.x(), center.y(), center.z(), radiusSquared, result); }
java
public static boolean intersectRaySphere(Vector3dc origin, Vector3dc dir, Vector3dc center, double radiusSquared, Vector2d result) { return intersectRaySphere(origin.x(), origin.y(), origin.z(), dir.x(), dir.y(), dir.z(), center.x(), center.y(), center.z(), radiusSquared, result); }
[ "public", "static", "boolean", "intersectRaySphere", "(", "Vector3dc", "origin", ",", "Vector3dc", "dir", ",", "Vector3dc", "center", ",", "double", "radiusSquared", ",", "Vector2d", "result", ")", "{", "return", "intersectRaySphere", "(", "origin", ".", "x", "(", ")", ",", "origin", ".", "y", "(", ")", ",", "origin", ".", "z", "(", ")", ",", "dir", ".", "x", "(", ")", ",", "dir", ".", "y", "(", ")", ",", "dir", ".", "z", "(", ")", ",", "center", ".", "x", "(", ")", ",", "center", ".", "y", "(", ")", ",", "center", ".", "z", "(", ")", ",", "radiusSquared", ",", "result", ")", ";", "}" ]
Test whether the ray with the given <code>origin</code> and normalized direction <code>dir</code> intersects the sphere with the given <code>center</code> and square radius <code>radiusSquared</code>, and store the values of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> for both points (near and far) of intersections into the given <code>result</code> vector. <p> This method returns <code>true</code> for a ray whose origin lies inside the sphere. <p> Reference: <a href="http://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-sphere-intersection">http://www.scratchapixel.com/</a> @param origin the ray's origin @param dir the ray's normalized direction @param center the sphere's center @param radiusSquared the sphere radius squared @param result a vector that will contain the values of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> for both points (near, far) of intersections with the sphere @return <code>true</code> if the ray intersects the sphere; <code>false</code> otherwise
[ "Test", "whether", "the", "ray", "with", "the", "given", "<code", ">", "origin<", "/", "code", ">", "and", "normalized", "direction", "<code", ">", "dir<", "/", "code", ">", "intersects", "the", "sphere", "with", "the", "given", "<code", ">", "center<", "/", "code", ">", "and", "square", "radius", "<code", ">", "radiusSquared<", "/", "code", ">", "and", "store", "the", "values", "of", "the", "parameter", "<i", ">", "t<", "/", "i", ">", "in", "the", "ray", "equation", "<i", ">", "p", "(", "t", ")", "=", "origin", "+", "t", "*", "dir<", "/", "i", ">", "for", "both", "points", "(", "near", "and", "far", ")", "of", "intersections", "into", "the", "given", "<code", ">", "result<", "/", "code", ">", "vector", ".", "<p", ">", "This", "method", "returns", "<code", ">", "true<", "/", "code", ">", "for", "a", "ray", "whose", "origin", "lies", "inside", "the", "sphere", ".", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "www", ".", "scratchapixel", ".", "com", "/", "lessons", "/", "3d", "-", "basic", "-", "rendering", "/", "minimal", "-", "ray", "-", "tracer", "-", "rendering", "-", "simple", "-", "shapes", "/", "ray", "-", "sphere", "-", "intersection", ">", "http", ":", "//", "www", ".", "scratchapixel", ".", "com", "/", "<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectiond.java#L2112-L2114
square/wire
wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoParser.java
ProtoParser.readExtensions
private ExtensionsElement readExtensions(Location location, String documentation) { """ Reads extensions like "extensions 101;" or "extensions 101 to max;". """ int start = reader.readInt(); // Range start. int end = start; if (reader.peekChar() != ';') { if (!"to".equals(reader.readWord())) throw reader.unexpected("expected ';' or 'to'"); String s = reader.readWord(); // Range end. if (s.equals("max")) { end = Util.MAX_TAG_VALUE; } else { end = Integer.parseInt(s); } } reader.require(';'); return new ExtensionsElement(location, documentation, start, end); }
java
private ExtensionsElement readExtensions(Location location, String documentation) { int start = reader.readInt(); // Range start. int end = start; if (reader.peekChar() != ';') { if (!"to".equals(reader.readWord())) throw reader.unexpected("expected ';' or 'to'"); String s = reader.readWord(); // Range end. if (s.equals("max")) { end = Util.MAX_TAG_VALUE; } else { end = Integer.parseInt(s); } } reader.require(';'); return new ExtensionsElement(location, documentation, start, end); }
[ "private", "ExtensionsElement", "readExtensions", "(", "Location", "location", ",", "String", "documentation", ")", "{", "int", "start", "=", "reader", ".", "readInt", "(", ")", ";", "// Range start.", "int", "end", "=", "start", ";", "if", "(", "reader", ".", "peekChar", "(", ")", "!=", "'", "'", ")", "{", "if", "(", "!", "\"to\"", ".", "equals", "(", "reader", ".", "readWord", "(", ")", ")", ")", "throw", "reader", ".", "unexpected", "(", "\"expected ';' or 'to'\"", ")", ";", "String", "s", "=", "reader", ".", "readWord", "(", ")", ";", "// Range end.", "if", "(", "s", ".", "equals", "(", "\"max\"", ")", ")", "{", "end", "=", "Util", ".", "MAX_TAG_VALUE", ";", "}", "else", "{", "end", "=", "Integer", ".", "parseInt", "(", "s", ")", ";", "}", "}", "reader", ".", "require", "(", "'", "'", ")", ";", "return", "new", "ExtensionsElement", "(", "location", ",", "documentation", ",", "start", ",", "end", ")", ";", "}" ]
Reads extensions like "extensions 101;" or "extensions 101 to max;".
[ "Reads", "extensions", "like", "extensions", "101", ";", "or", "extensions", "101", "to", "max", ";", "." ]
train
https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoParser.java#L471-L485