repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/KeyedStream.java
KeyedStream.maxBy
public SingleOutputStreamOperator<T> maxBy(String field, boolean first) { return aggregate(new ComparableAggregator<>(field, getType(), AggregationFunction.AggregationType.MAXBY, first, getExecutionConfig())); }
java
public SingleOutputStreamOperator<T> maxBy(String field, boolean first) { return aggregate(new ComparableAggregator<>(field, getType(), AggregationFunction.AggregationType.MAXBY, first, getExecutionConfig())); }
[ "public", "SingleOutputStreamOperator", "<", "T", ">", "maxBy", "(", "String", "field", ",", "boolean", "first", ")", "{", "return", "aggregate", "(", "new", "ComparableAggregator", "<>", "(", "field", ",", "getType", "(", ")", ",", "AggregationFunction", ".",...
Applies an aggregation that gives the current maximum element of the data stream by the given field expression by the given key. An independent aggregate is kept per key. A field expression is either the name of a public field or a getter method with parentheses of the {@link DataStream}'s underlying type. A dot can be used to drill down into objects, as in {@code "field1.fieldxy" }. @param field In case of a POJO, Scala case class, or Tuple type, the name of the (public) field on which to perform the aggregation. Additionally, a dot can be used to drill down into nested objects, as in {@code "field1.fieldxy" }. Furthermore "*" can be specified in case of a basic type (which is considered as having only one field). @param first If True then in case of field equality the first object will be returned @return The transformed DataStream.
[ "Applies", "an", "aggregation", "that", "gives", "the", "current", "maximum", "element", "of", "the", "data", "stream", "by", "the", "given", "field", "expression", "by", "the", "given", "key", ".", "An", "independent", "aggregate", "is", "kept", "per", "key...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/KeyedStream.java#L874-L877
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java
CommonOps_DDRM.elementPower
public static void elementPower(DMatrixD1 A , double b, DMatrixD1 C ) { if( A.numRows != C.numRows || A.numCols != C.numCols ) { throw new MatrixDimensionException("All matrices must be the same shape"); } int size = A.getNumElements(); for( int i = 0; i < size; i++ ) { C.data[i] = Math.pow(A.data[i], b); } }
java
public static void elementPower(DMatrixD1 A , double b, DMatrixD1 C ) { if( A.numRows != C.numRows || A.numCols != C.numCols ) { throw new MatrixDimensionException("All matrices must be the same shape"); } int size = A.getNumElements(); for( int i = 0; i < size; i++ ) { C.data[i] = Math.pow(A.data[i], b); } }
[ "public", "static", "void", "elementPower", "(", "DMatrixD1", "A", ",", "double", "b", ",", "DMatrixD1", "C", ")", "{", "if", "(", "A", ".", "numRows", "!=", "C", ".", "numRows", "||", "A", ".", "numCols", "!=", "C", ".", "numCols", ")", "{", "thro...
<p> Element-wise power operation <br> c<sub>ij</sub> = a<sub>ij</sub> ^ b <p> @param A left side @param b right scalar @param C output (modified)
[ "<p", ">", "Element", "-", "wise", "power", "operation", "<br", ">", "c<sub", ">", "ij<", "/", "sub", ">", "=", "a<sub", ">", "ij<", "/", "sub", ">", "^", "b", "<p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L1686-L1696
apache/flink
flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/Graph.java
Graph.fromTuple2DataSet
public static <K> Graph<K, NullValue, NullValue> fromTuple2DataSet(DataSet<Tuple2<K, K>> edges, ExecutionEnvironment context) { DataSet<Edge<K, NullValue>> edgeDataSet = edges .map(new Tuple2ToEdgeMap<>()) .name("To Edge"); return fromDataSet(edgeDataSet, context); }
java
public static <K> Graph<K, NullValue, NullValue> fromTuple2DataSet(DataSet<Tuple2<K, K>> edges, ExecutionEnvironment context) { DataSet<Edge<K, NullValue>> edgeDataSet = edges .map(new Tuple2ToEdgeMap<>()) .name("To Edge"); return fromDataSet(edgeDataSet, context); }
[ "public", "static", "<", "K", ">", "Graph", "<", "K", ",", "NullValue", ",", "NullValue", ">", "fromTuple2DataSet", "(", "DataSet", "<", "Tuple2", "<", "K", ",", "K", ">", ">", "edges", ",", "ExecutionEnvironment", "context", ")", "{", "DataSet", "<", ...
Creates a graph from a DataSet of Tuple2 objects for edges. Each Tuple2 will become one Edge, where the source ID will be the first field of the Tuple2 and the target ID will be the second field of the Tuple2. <p>Edge value types and Vertex values types will be set to NullValue. @param edges a DataSet of Tuple2. @param context the flink execution environment. @return the newly created graph.
[ "Creates", "a", "graph", "from", "a", "DataSet", "of", "Tuple2", "objects", "for", "edges", ".", "Each", "Tuple2", "will", "become", "one", "Edge", "where", "the", "source", "ID", "will", "be", "the", "first", "field", "of", "the", "Tuple2", "and", "the"...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/Graph.java#L342-L350
jaxio/celerio
celerio-engine/src/main/java/com/jaxio/celerio/template/ContentWriter.java
ContentWriter.getFullPathForLog
private String getFullPathForLog(OutputResult or, String targetFilename) { if (or.sameDirectory()) { return targetFilename; } else { return or.getGeneratedSource().getFullPath(targetFilename); } }
java
private String getFullPathForLog(OutputResult or, String targetFilename) { if (or.sameDirectory()) { return targetFilename; } else { return or.getGeneratedSource().getFullPath(targetFilename); } }
[ "private", "String", "getFullPathForLog", "(", "OutputResult", "or", ",", "String", "targetFilename", ")", "{", "if", "(", "or", ".", "sameDirectory", "(", ")", ")", "{", "return", "targetFilename", ";", "}", "else", "{", "return", "or", ".", "getGeneratedSo...
Use it only to display proper path in log @param targetFilename
[ "Use", "it", "only", "to", "display", "proper", "path", "in", "log" ]
train
https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/template/ContentWriter.java#L109-L115
JoeKerouac/utils
src/main/java/com/joe/utils/img/ImgUtil.java
ImgUtil.changeAlpha
public static void changeAlpha(String oldPath, String newPath, byte alpha) throws IOException { changeAlpha(new FileInputStream(oldPath), new FileOutputStream(newPath), alpha); }
java
public static void changeAlpha(String oldPath, String newPath, byte alpha) throws IOException { changeAlpha(new FileInputStream(oldPath), new FileOutputStream(newPath), alpha); }
[ "public", "static", "void", "changeAlpha", "(", "String", "oldPath", ",", "String", "newPath", ",", "byte", "alpha", ")", "throws", "IOException", "{", "changeAlpha", "(", "new", "FileInputStream", "(", "oldPath", ")", ",", "new", "FileOutputStream", "(", "new...
更改图片alpha值 @param oldPath 图片本地路径 @param newPath 更改alpha值后的图片保存路径 @param alpha 要设置的alpha值 @throws IOException IOException
[ "更改图片alpha值" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/img/ImgUtil.java#L29-L31
CloudSlang/cs-actions
cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java
DateTimeUtils.getDateFormatter
public static DateTimeFormatter getDateFormatter(String format, String lang, String country) { if (StringUtils.isNotBlank(format)) { DateTimeFormatter dateFormat = DateTimeFormat.forPattern(format); if (StringUtils.isNotBlank(lang)) { return dateFormat.withLocale(DateTimeUtils.getLocaleByCountry(lang, country)); } return dateFormat; } return formatWithDefault(lang, country); }
java
public static DateTimeFormatter getDateFormatter(String format, String lang, String country) { if (StringUtils.isNotBlank(format)) { DateTimeFormatter dateFormat = DateTimeFormat.forPattern(format); if (StringUtils.isNotBlank(lang)) { return dateFormat.withLocale(DateTimeUtils.getLocaleByCountry(lang, country)); } return dateFormat; } return formatWithDefault(lang, country); }
[ "public", "static", "DateTimeFormatter", "getDateFormatter", "(", "String", "format", ",", "String", "lang", ",", "String", "country", ")", "{", "if", "(", "StringUtils", ".", "isNotBlank", "(", "format", ")", ")", "{", "DateTimeFormatter", "dateFormat", "=", ...
Generates a DateTimeFormatter using a custom pattern with the default locale or a new one according to what language and country are provided as params. @param format the pattern @param lang the language @param country the country @return the DateTimeFormatter generated
[ "Generates", "a", "DateTimeFormatter", "using", "a", "custom", "pattern", "with", "the", "default", "locale", "or", "a", "new", "one", "according", "to", "what", "language", "and", "country", "are", "provided", "as", "params", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L101-L110
JakeWharton/NineOldAndroids
sample/src/com/jakewharton/nineoldandroids/sample/pathanimation/PathPoint.java
PathPoint.curveTo
public static PathPoint curveTo(float c0X, float c0Y, float c1X, float c1Y, float x, float y) { return new PathPoint(c0X, c0Y, c1X, c1Y, x, y); }
java
public static PathPoint curveTo(float c0X, float c0Y, float c1X, float c1Y, float x, float y) { return new PathPoint(c0X, c0Y, c1X, c1Y, x, y); }
[ "public", "static", "PathPoint", "curveTo", "(", "float", "c0X", ",", "float", "c0Y", ",", "float", "c1X", ",", "float", "c1Y", ",", "float", "x", ",", "float", "y", ")", "{", "return", "new", "PathPoint", "(", "c0X", ",", "c0Y", ",", "c1X", ",", "...
Constructs and returns a PathPoint object that describes a cubic B�zier curve to the given xy location with the control points at c0 and c1.
[ "Constructs", "and", "returns", "a", "PathPoint", "object", "that", "describes", "a", "cubic", "B�zier", "curve", "to", "the", "given", "xy", "location", "with", "the", "control", "points", "at", "c0", "and", "c1", "." ]
train
https://github.com/JakeWharton/NineOldAndroids/blob/d582f0ec8e79013e9fa96c07986160b52e662e63/sample/src/com/jakewharton/nineoldandroids/sample/pathanimation/PathPoint.java#L90-L92
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/JsCodeBuilder.java
JsCodeBuilder.pushOutputVar
public JsCodeBuilder pushOutputVar(String outputVarName) { currOutputVar = id(outputVarName); outputVars.push(new OutputVar(currOutputVar, false)); currOutputVarIsInited = false; return this; }
java
public JsCodeBuilder pushOutputVar(String outputVarName) { currOutputVar = id(outputVarName); outputVars.push(new OutputVar(currOutputVar, false)); currOutputVarIsInited = false; return this; }
[ "public", "JsCodeBuilder", "pushOutputVar", "(", "String", "outputVarName", ")", "{", "currOutputVar", "=", "id", "(", "outputVarName", ")", ";", "outputVars", ".", "push", "(", "new", "OutputVar", "(", "currOutputVar", ",", "false", ")", ")", ";", "currOutput...
Pushes on a new current output variable. @param outputVarName The new output variable name.
[ "Pushes", "on", "a", "new", "current", "output", "variable", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsCodeBuilder.java#L220-L225
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java
SlaveMain.redirectStreams
@SuppressForbidden("legitimate sysstreams.") private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) { final PrintStream origSysOut = System.out; final PrintStream origSysErr = System.err; // Set warnings stream to System.err. warnings = System.err; AccessController.doPrivileged(new PrivilegedAction<Void>() { @SuppressForbidden("legitimate PrintStream with default charset.") @Override public Void run() { System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() { @Override public void write(byte[] b, int off, int len) throws IOException { if (multiplexStdStreams) { origSysOut.write(b, off, len); } serializer.serialize(new AppendStdOutEvent(b, off, len)); if (flushFrequently) serializer.flush(); } }))); System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() { @Override public void write(byte[] b, int off, int len) throws IOException { if (multiplexStdStreams) { origSysErr.write(b, off, len); } serializer.serialize(new AppendStdErrEvent(b, off, len)); if (flushFrequently) serializer.flush(); } }))); return null; } }); }
java
@SuppressForbidden("legitimate sysstreams.") private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) { final PrintStream origSysOut = System.out; final PrintStream origSysErr = System.err; // Set warnings stream to System.err. warnings = System.err; AccessController.doPrivileged(new PrivilegedAction<Void>() { @SuppressForbidden("legitimate PrintStream with default charset.") @Override public Void run() { System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() { @Override public void write(byte[] b, int off, int len) throws IOException { if (multiplexStdStreams) { origSysOut.write(b, off, len); } serializer.serialize(new AppendStdOutEvent(b, off, len)); if (flushFrequently) serializer.flush(); } }))); System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() { @Override public void write(byte[] b, int off, int len) throws IOException { if (multiplexStdStreams) { origSysErr.write(b, off, len); } serializer.serialize(new AppendStdErrEvent(b, off, len)); if (flushFrequently) serializer.flush(); } }))); return null; } }); }
[ "@", "SuppressForbidden", "(", "\"legitimate sysstreams.\"", ")", "private", "static", "void", "redirectStreams", "(", "final", "Serializer", "serializer", ",", "final", "boolean", "flushFrequently", ")", "{", "final", "PrintStream", "origSysOut", "=", "System", ".", ...
Redirect standard streams so that the output can be passed to listeners.
[ "Redirect", "standard", "streams", "so", "that", "the", "output", "can", "be", "passed", "to", "listeners", "." ]
train
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java#L470-L505
unbescape/unbescape
src/main/java/org/unbescape/uri/UriEscape.java
UriEscape.unescapeUriQueryParam
public static void unescapeUriQueryParam(final String text, final Writer writer, final String encoding) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (encoding == null) { throw new IllegalArgumentException("Argument 'encoding' cannot be null"); } UriEscapeUtil.unescape(new InternalStringReader(text), writer, UriEscapeUtil.UriEscapeType.QUERY_PARAM, encoding); }
java
public static void unescapeUriQueryParam(final String text, final Writer writer, final String encoding) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (encoding == null) { throw new IllegalArgumentException("Argument 'encoding' cannot be null"); } UriEscapeUtil.unescape(new InternalStringReader(text), writer, UriEscapeUtil.UriEscapeType.QUERY_PARAM, encoding); }
[ "public", "static", "void", "unescapeUriQueryParam", "(", "final", "String", "text", ",", "final", "Writer", "writer", ",", "final", "String", "encoding", ")", "throws", "IOException", "{", "if", "(", "writer", "==", "null", ")", "{", "throw", "new", "Illega...
<p> Perform am URI query parameter (name or value) <strong>unescape</strong> operation on a <tt>String</tt> input, writing results to a <tt>Writer</tt>. </p> <p> This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input, even for those characters that do not need to be percent-encoded in this context (unreserved characters can be percent-encoded even if/when this is not required, though it is not generally considered a good practice). </p> <p> This method will use specified <tt>encoding</tt> in order to determine the characters specified in the percent-encoded byte sequences. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be unescaped. @param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @param encoding the encoding to be used for unescaping. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "am", "URI", "query", "parameter", "(", "name", "or", "value", ")", "<strong", ">", "unescape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "String<", "/", "tt", ">", "input", "writing", "results", "to", "a", "<tt", ...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L1987-L2000
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java
DevicesInner.downloadUpdates
public void downloadUpdates(String deviceName, String resourceGroupName) { downloadUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).toBlocking().last().body(); }
java
public void downloadUpdates(String deviceName, String resourceGroupName) { downloadUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).toBlocking().last().body(); }
[ "public", "void", "downloadUpdates", "(", "String", "deviceName", ",", "String", "resourceGroupName", ")", "{", "downloadUpdatesWithServiceResponseAsync", "(", "deviceName", ",", "resourceGroupName", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "b...
Downloads the updates on a data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Downloads", "the", "updates", "on", "a", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java#L1202-L1204
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/packet/VCard.java
VCard.setField
public void setField(String field, String value, boolean isUnescapable) { if (!isUnescapable) { otherSimpleFields.put(field, value); } else { otherUnescapableFields.put(field, value); } }
java
public void setField(String field, String value, boolean isUnescapable) { if (!isUnescapable) { otherSimpleFields.put(field, value); } else { otherUnescapableFields.put(field, value); } }
[ "public", "void", "setField", "(", "String", "field", ",", "String", "value", ",", "boolean", "isUnescapable", ")", "{", "if", "(", "!", "isUnescapable", ")", "{", "otherSimpleFields", ".", "put", "(", "field", ",", "value", ")", ";", "}", "else", "{", ...
Set generic, unescapable VCard field. If unescapable is set to true, XML maybe a part of the value. @param value value of field @param field field to set. See {@link #getField(String)} @param isUnescapable True if the value should not be escaped, and false if it should.
[ "Set", "generic", "unescapable", "VCard", "field", ".", "If", "unescapable", "is", "set", "to", "true", "XML", "maybe", "a", "part", "of", "the", "value", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/packet/VCard.java#L167-L174
ebean-orm/ebean-querybean
src/main/java/io/ebean/typequery/TQRootBean.java
TQRootBean.textCommonTerms
public R textCommonTerms(String query, TextCommonTerms options) { peekExprList().textCommonTerms(query, options); return root; }
java
public R textCommonTerms(String query, TextCommonTerms options) { peekExprList().textCommonTerms(query, options); return root; }
[ "public", "R", "textCommonTerms", "(", "String", "query", ",", "TextCommonTerms", "options", ")", "{", "peekExprList", "(", ")", ".", "textCommonTerms", "(", "query", ",", "options", ")", ";", "return", "root", ";", "}" ]
Add a Text common terms expression (document store only). <p> This automatically makes the query a document store query. </p>
[ "Add", "a", "Text", "common", "terms", "expression", "(", "document", "store", "only", ")", ".", "<p", ">", "This", "automatically", "makes", "the", "query", "a", "document", "store", "query", ".", "<", "/", "p", ">" ]
train
https://github.com/ebean-orm/ebean-querybean/blob/821650cb817c9c0fdcc97f93408dc79170b12423/src/main/java/io/ebean/typequery/TQRootBean.java#L1399-L1402
facebook/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/bitmaps/HoneycombBitmapFactory.java
HoneycombBitmapFactory.createBitmapInternal
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override public CloseableReference<Bitmap> createBitmapInternal( int width, int height, Bitmap.Config bitmapConfig) { if (mImmutableBitmapFallback) { return createFallbackBitmap(width, height, bitmapConfig); } CloseableReference<PooledByteBuffer> jpgRef = mJpegGenerator.generate( (short) width, (short) height); try { EncodedImage encodedImage = new EncodedImage(jpgRef); encodedImage.setImageFormat(DefaultImageFormats.JPEG); try { CloseableReference<Bitmap> bitmapRef = mPurgeableDecoder.decodeJPEGFromEncodedImage( encodedImage, bitmapConfig, null, jpgRef.get().size()); if (!bitmapRef.get().isMutable()) { CloseableReference.closeSafely(bitmapRef); mImmutableBitmapFallback = true; FLog.wtf(TAG, "Immutable bitmap returned by decoder"); // On some devices (Samsung GT-S7580) the returned bitmap can be immutable, in that case // let's jut use Bitmap.createBitmap() to hopefully create a mutable one. return createFallbackBitmap(width, height, bitmapConfig); } bitmapRef.get().setHasAlpha(true); bitmapRef.get().eraseColor(Color.TRANSPARENT); return bitmapRef; } finally { EncodedImage.closeSafely(encodedImage); } } finally { jpgRef.close(); } }
java
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override public CloseableReference<Bitmap> createBitmapInternal( int width, int height, Bitmap.Config bitmapConfig) { if (mImmutableBitmapFallback) { return createFallbackBitmap(width, height, bitmapConfig); } CloseableReference<PooledByteBuffer> jpgRef = mJpegGenerator.generate( (short) width, (short) height); try { EncodedImage encodedImage = new EncodedImage(jpgRef); encodedImage.setImageFormat(DefaultImageFormats.JPEG); try { CloseableReference<Bitmap> bitmapRef = mPurgeableDecoder.decodeJPEGFromEncodedImage( encodedImage, bitmapConfig, null, jpgRef.get().size()); if (!bitmapRef.get().isMutable()) { CloseableReference.closeSafely(bitmapRef); mImmutableBitmapFallback = true; FLog.wtf(TAG, "Immutable bitmap returned by decoder"); // On some devices (Samsung GT-S7580) the returned bitmap can be immutable, in that case // let's jut use Bitmap.createBitmap() to hopefully create a mutable one. return createFallbackBitmap(width, height, bitmapConfig); } bitmapRef.get().setHasAlpha(true); bitmapRef.get().eraseColor(Color.TRANSPARENT); return bitmapRef; } finally { EncodedImage.closeSafely(encodedImage); } } finally { jpgRef.close(); } }
[ "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "HONEYCOMB_MR1", ")", "@", "Override", "public", "CloseableReference", "<", "Bitmap", ">", "createBitmapInternal", "(", "int", "width", ",", "int", "height", ",", "Bitmap", ".", "Config", "bitmapConfig",...
Creates a bitmap of the specified width and height. @param width the width of the bitmap @param height the height of the bitmap @param bitmapConfig the {@link android.graphics.Bitmap.Config} used to create the decoded Bitmap @return a reference to the bitmap @throws TooManyBitmapsException if the pool is full @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
[ "Creates", "a", "bitmap", "of", "the", "specified", "width", "and", "height", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/bitmaps/HoneycombBitmapFactory.java#L51-L87
b3dgs/lionengine
lionengine-audio-wav/src/main/java/com/b3dgs/lionengine/audio/wav/WavImpl.java
WavImpl.updateAlignment
private static void updateAlignment(DataLine dataLine, Align alignment) { if (dataLine.isControlSupported(Type.PAN)) { final FloatControl pan = (FloatControl) dataLine.getControl(Type.PAN); switch (alignment) { case CENTER: pan.setValue(0.0F); break; case RIGHT: pan.setValue(1.0F); break; case LEFT: pan.setValue(-1.0F); break; default: throw new LionEngineException(alignment); } } }
java
private static void updateAlignment(DataLine dataLine, Align alignment) { if (dataLine.isControlSupported(Type.PAN)) { final FloatControl pan = (FloatControl) dataLine.getControl(Type.PAN); switch (alignment) { case CENTER: pan.setValue(0.0F); break; case RIGHT: pan.setValue(1.0F); break; case LEFT: pan.setValue(-1.0F); break; default: throw new LionEngineException(alignment); } } }
[ "private", "static", "void", "updateAlignment", "(", "DataLine", "dataLine", ",", "Align", "alignment", ")", "{", "if", "(", "dataLine", ".", "isControlSupported", "(", "Type", ".", "PAN", ")", ")", "{", "final", "FloatControl", "pan", "=", "(", "FloatContro...
Update the sound alignment. @param dataLine Audio source data. @param alignment Alignment value.
[ "Update", "the", "sound", "alignment", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-audio-wav/src/main/java/com/b3dgs/lionengine/audio/wav/WavImpl.java#L131-L151
Samsung/GearVRf
GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java
JSONHelpers.optPointF
public static <P extends Enum<P>> PointF optPointF(final JSONObject json, P e, boolean emptyForNull) { PointF p = optPointF(json, e); if (p == null && emptyForNull) { p = new PointF(); } return p; }
java
public static <P extends Enum<P>> PointF optPointF(final JSONObject json, P e, boolean emptyForNull) { PointF p = optPointF(json, e); if (p == null && emptyForNull) { p = new PointF(); } return p; }
[ "public", "static", "<", "P", "extends", "Enum", "<", "P", ">", ">", "PointF", "optPointF", "(", "final", "JSONObject", "json", ",", "P", "e", ",", "boolean", "emptyForNull", ")", "{", "PointF", "p", "=", "optPointF", "(", "json", ",", "e", ")", ";",...
Return the value mapped by enum if it exists and is a {@link JSONObject} by mapping "x" and "y" members into a {@link Point}. If the value does not exist by that enum, and {@code emptyForNull} is {@code true}, returns a default constructed {@code Point}. Otherwise, returns {@code null}. @param json {@code JSONObject} to get data from @param e {@link Enum} labeling the data to get @param emptyForNull {@code True} to return a default constructed {@code Point} if there is no mapped data, {@code false} to return {@code null} in that case @return A {@code Point} if the mapping exists or {@code emptyForNull} is {@code true}; {@code null} otherwise
[ "Return", "the", "value", "mapped", "by", "enum", "if", "it", "exists", "and", "is", "a", "{", "@link", "JSONObject", "}", "by", "mapping", "x", "and", "y", "members", "into", "a", "{", "@link", "Point", "}", ".", "If", "the", "value", "does", "not",...
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java#L613-L619
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/model/ProcessThread.java
ProcessThread.acquiredLock
public static @Nonnull Predicate acquiredLock(final @Nonnull String className) { return new Predicate() { @Override public boolean isValid(@Nonnull ProcessThread<?, ?, ?> thread) { for (ThreadLock lock: thread.getAcquiredLocks()) { if (lock.getClassName().equals(className)) return true; } return false; } }; }
java
public static @Nonnull Predicate acquiredLock(final @Nonnull String className) { return new Predicate() { @Override public boolean isValid(@Nonnull ProcessThread<?, ?, ?> thread) { for (ThreadLock lock: thread.getAcquiredLocks()) { if (lock.getClassName().equals(className)) return true; } return false; } }; }
[ "public", "static", "@", "Nonnull", "Predicate", "acquiredLock", "(", "final", "@", "Nonnull", "String", "className", ")", "{", "return", "new", "Predicate", "(", ")", "{", "@", "Override", "public", "boolean", "isValid", "(", "@", "Nonnull", "ProcessThread", ...
Match thread that has acquired lock identified by <tt>className</tt>.
[ "Match", "thread", "that", "has", "acquired", "lock", "identified", "by", "<tt", ">", "className<", "/", "tt", ">", "." ]
train
https://github.com/olivergondza/dumpling/blob/ac698735fcc7c023db0c1637cc1f522cb3576c7f/core/src/main/java/com/github/olivergondza/dumpling/model/ProcessThread.java#L566-L576
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.isSameLocalTime
public static boolean isSameLocalTime(final Calendar cal1, final Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass(); }
java
public static boolean isSameLocalTime(final Calendar cal1, final Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass(); }
[ "public", "static", "boolean", "isSameLocalTime", "(", "final", "Calendar", "cal1", ",", "final", "Calendar", "cal2", ")", "{", "if", "(", "cal1", "==", "null", "||", "cal2", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The dat...
<p>Checks if two calendar objects represent the same local time.</p> <p>This method compares the values of the fields of the two objects. In addition, both calendars must be the same of the same type.</p> @param cal1 the first calendar, not altered, not null @param cal2 the second calendar, not altered, not null @return true if they represent the same millisecond instant @throws IllegalArgumentException if either date is <code>null</code> @since 2.1
[ "<p", ">", "Checks", "if", "two", "calendar", "objects", "represent", "the", "same", "local", "time", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L251-L263
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/f/FundamentalToProjective.java
FundamentalToProjective.twoView
public void twoView(DMatrixRMaj F , DMatrixRMaj cameraMatrix) { alg.process(F,e1,e2); twoView(F, e2, zero, 1,cameraMatrix); }
java
public void twoView(DMatrixRMaj F , DMatrixRMaj cameraMatrix) { alg.process(F,e1,e2); twoView(F, e2, zero, 1,cameraMatrix); }
[ "public", "void", "twoView", "(", "DMatrixRMaj", "F", ",", "DMatrixRMaj", "cameraMatrix", ")", "{", "alg", ".", "process", "(", "F", ",", "e1", ",", "e2", ")", ";", "twoView", "(", "F", ",", "e2", ",", "zero", ",", "1", ",", "cameraMatrix", ")", ";...
<p> Given a fundamental matrix a pair of camera matrices P0 and P1 can be extracted. Same {@link #twoView(DMatrixRMaj, DMatrixRMaj)} but with the suggested values for all variables filled in for you. </p> @param F (Input) Fundamental Matrix @param cameraMatrix (Output) resulting projective camera matrix P'. (3 by 4) Known up to a projective transform.
[ "<p", ">", "Given", "a", "fundamental", "matrix", "a", "pair", "of", "camera", "matrices", "P0", "and", "P1", "can", "be", "extracted", ".", "Same", "{" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/f/FundamentalToProjective.java#L69-L73
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/generation/MapperConstructor.java
MapperConstructor.setOperation
private <T extends AGeneralOperation>T setOperation(T operation,MappingType mtd,MappingType mts){ operation.setMtd(mtd).setMts(mts) .initialDSetPath(stringOfSetDestination) .initialDGetPath(stringOfGetDestination) .initialSGetPath(stringOfGetSource); return operation; }
java
private <T extends AGeneralOperation>T setOperation(T operation,MappingType mtd,MappingType mts){ operation.setMtd(mtd).setMts(mts) .initialDSetPath(stringOfSetDestination) .initialDGetPath(stringOfGetDestination) .initialSGetPath(stringOfGetSource); return operation; }
[ "private", "<", "T", "extends", "AGeneralOperation", ">", "T", "setOperation", "(", "T", "operation", ",", "MappingType", "mtd", ",", "MappingType", "mts", ")", "{", "operation", ".", "setMtd", "(", "mtd", ")", ".", "setMts", "(", "mts", ")", ".", "initi...
Setting common to all operations. @param operation operation to configure @param mtd mapping type of destination @param mts mapping type of source @return operation configured
[ "Setting", "common", "to", "all", "operations", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/generation/MapperConstructor.java#L189-L196
facebook/fresco
drawee/src/main/java/com/facebook/drawee/drawable/DrawableUtils.java
DrawableUtils.copyProperties
public static void copyProperties(@Nullable Drawable to, @Nullable Drawable from) { if (from == null || to == null || to == from) { return; } to.setBounds(from.getBounds()); to.setChangingConfigurations(from.getChangingConfigurations()); to.setLevel(from.getLevel()); to.setVisible(from.isVisible(), /* restart */ false); to.setState(from.getState()); }
java
public static void copyProperties(@Nullable Drawable to, @Nullable Drawable from) { if (from == null || to == null || to == from) { return; } to.setBounds(from.getBounds()); to.setChangingConfigurations(from.getChangingConfigurations()); to.setLevel(from.getLevel()); to.setVisible(from.isVisible(), /* restart */ false); to.setState(from.getState()); }
[ "public", "static", "void", "copyProperties", "(", "@", "Nullable", "Drawable", "to", ",", "@", "Nullable", "Drawable", "from", ")", "{", "if", "(", "from", "==", "null", "||", "to", "==", "null", "||", "to", "==", "from", ")", "{", "return", ";", "}...
Copies various properties from one drawable to the other. @param to drawable to copy properties to @param from drawable to copy properties from
[ "Copies", "various", "properties", "from", "one", "drawable", "to", "the", "other", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/drawable/DrawableUtils.java#L39-L49
facebookarchive/hive-dwrf
hive-dwrf-shims/src/main/java/org/apache/hadoop/hive/ql/io/slice/Slice.java
Slice.compareTo
@SuppressWarnings("ObjectEquality") @Override public int compareTo(Slice that) { if (this == that) { return 0; } return compareTo(0, size, that, 0, that.size); }
java
@SuppressWarnings("ObjectEquality") @Override public int compareTo(Slice that) { if (this == that) { return 0; } return compareTo(0, size, that, 0, that.size); }
[ "@", "SuppressWarnings", "(", "\"ObjectEquality\"", ")", "@", "Override", "public", "int", "compareTo", "(", "Slice", "that", ")", "{", "if", "(", "this", "==", "that", ")", "{", "return", "0", ";", "}", "return", "compareTo", "(", "0", ",", "size", ",...
Compares the content of the specified buffer to the content of this buffer. This comparison is performed byte by byte using an unsigned comparison.
[ "Compares", "the", "content", "of", "the", "specified", "buffer", "to", "the", "content", "of", "this", "buffer", ".", "This", "comparison", "is", "performed", "byte", "by", "byte", "using", "an", "unsigned", "comparison", "." ]
train
https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf-shims/src/main/java/org/apache/hadoop/hive/ql/io/slice/Slice.java#L586-L594
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java
OSchemaHelper.oIndex
public OSchemaHelper oIndex(String name, INDEX_TYPE type) { checkOProperty(); return oIndex(name, type, lastProperty.getName()); }
java
public OSchemaHelper oIndex(String name, INDEX_TYPE type) { checkOProperty(); return oIndex(name, type, lastProperty.getName()); }
[ "public", "OSchemaHelper", "oIndex", "(", "String", "name", ",", "INDEX_TYPE", "type", ")", "{", "checkOProperty", "(", ")", ";", "return", "oIndex", "(", "name", ",", "type", ",", "lastProperty", ".", "getName", "(", ")", ")", ";", "}" ]
Create {@link OIndex} if required on a current property @param name name of an index @param type type of an {@link OIndex} @return this helper
[ "Create", "{" ]
train
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java#L277-L281
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/Marshaller.java
Marshaller.applyAutoTimestamp
private void applyAutoTimestamp(PropertyMetadata propertyMetadata, long millis) { Object timestamp = null; Class<?> fieldType = propertyMetadata.getDeclaredType(); if (Date.class.equals(fieldType)) { timestamp = new Date(millis); } else if (Calendar.class.equals(fieldType)) { Calendar calendar = new Calendar.Builder().setInstant(millis).build(); timestamp = calendar; } else if (Long.class.equals(fieldType) || long.class.equals(fieldType)) { timestamp = millis; } else if (OffsetDateTime.class.equals(fieldType)) { timestamp = OffsetDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); } else if (ZonedDateTime.class.equals(fieldType)) { timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); } ValueBuilder<?, ?, ?> valueBuilder = propertyMetadata.getMapper().toDatastore(timestamp); valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); entityBuilder.set(propertyMetadata.getMappedName(), valueBuilder.build()); }
java
private void applyAutoTimestamp(PropertyMetadata propertyMetadata, long millis) { Object timestamp = null; Class<?> fieldType = propertyMetadata.getDeclaredType(); if (Date.class.equals(fieldType)) { timestamp = new Date(millis); } else if (Calendar.class.equals(fieldType)) { Calendar calendar = new Calendar.Builder().setInstant(millis).build(); timestamp = calendar; } else if (Long.class.equals(fieldType) || long.class.equals(fieldType)) { timestamp = millis; } else if (OffsetDateTime.class.equals(fieldType)) { timestamp = OffsetDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); } else if (ZonedDateTime.class.equals(fieldType)) { timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); } ValueBuilder<?, ?, ?> valueBuilder = propertyMetadata.getMapper().toDatastore(timestamp); valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); entityBuilder.set(propertyMetadata.getMappedName(), valueBuilder.build()); }
[ "private", "void", "applyAutoTimestamp", "(", "PropertyMetadata", "propertyMetadata", ",", "long", "millis", ")", "{", "Object", "timestamp", "=", "null", ";", "Class", "<", "?", ">", "fieldType", "=", "propertyMetadata", ".", "getDeclaredType", "(", ")", ";", ...
Applies the given time, <code>millis</code>, to the property represented by the given metadata. @param propertyMetadata the property metadata of the field @param millis the time in milliseconds
[ "Applies", "the", "given", "time", "<code", ">", "millis<", "/", "code", ">", "to", "the", "property", "represented", "by", "the", "given", "metadata", "." ]
train
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/Marshaller.java#L605-L623
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.comms.server/src/com/ibm/ws/sib/comms/server/clientsupport/CachedSessionProperties.java
CachedSessionProperties.areTheyTheSame
private boolean areTheyTheSame(Object obj1, Object obj2) { // If they are both null, then they are equal if (obj1 == null && obj2 == null) return true; // If only one is null then they are not equal if (obj1 == null || obj2 == null) return false; // At this point neither are null - so check them // String if (obj1 instanceof String) { return ((String) obj1).equals(obj2); } // Reliability if (obj1 instanceof Reliability) { return ((Reliability) obj1).compareTo(obj2) == 0; } // Start f192759.2 // SIDestinationAddress if (obj1 instanceof SIDestinationAddress) { return obj1.toString().equals(obj2.toString()); } // End f192759.2 // Otherwise, I have no idea - so return false return false; }
java
private boolean areTheyTheSame(Object obj1, Object obj2) { // If they are both null, then they are equal if (obj1 == null && obj2 == null) return true; // If only one is null then they are not equal if (obj1 == null || obj2 == null) return false; // At this point neither are null - so check them // String if (obj1 instanceof String) { return ((String) obj1).equals(obj2); } // Reliability if (obj1 instanceof Reliability) { return ((Reliability) obj1).compareTo(obj2) == 0; } // Start f192759.2 // SIDestinationAddress if (obj1 instanceof SIDestinationAddress) { return obj1.toString().equals(obj2.toString()); } // End f192759.2 // Otherwise, I have no idea - so return false return false; }
[ "private", "boolean", "areTheyTheSame", "(", "Object", "obj1", ",", "Object", "obj2", ")", "{", "// If they are both null, then they are equal", "if", "(", "obj1", "==", "null", "&&", "obj2", "==", "null", ")", "return", "true", ";", "// If only one is null then the...
Method which compares 2 objects and determines if they are the same. Objects are the same if they are both null, or if they have equal values. <p> Note this method should only be used for comparing String objects, Reliability objects and SIDestinationAddress objects (and shouldn't be used for comparing a String to a Reliability either - smart guy). @param obj1 @param obj2 @return Returns true if the objects are equal.
[ "Method", "which", "compares", "2", "objects", "and", "determines", "if", "they", "are", "the", "same", ".", "Objects", "are", "the", "same", "if", "they", "are", "both", "null", "or", "if", "they", "have", "equal", "values", ".", "<p", ">", "Note", "t...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.server/src/com/ibm/ws/sib/comms/server/clientsupport/CachedSessionProperties.java#L107-L136
BioPAX/Paxtools
paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java
QueryExecuter.runCommonStreamWithPOIMultiSet
public static Set<BioPAXElement> runCommonStreamWithPOIMultiSet( Set<Set<BioPAXElement>> sourceSets, Model model, Direction direction, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Collection<Set<Node>> nodes = prepareNodeSetsFromSets(sourceSets, graph); if (nodes.size() < 2) return Collections.emptySet(); return runCommonStreamWithPOIContinued(nodes, direction, limit, graph); }
java
public static Set<BioPAXElement> runCommonStreamWithPOIMultiSet( Set<Set<BioPAXElement>> sourceSets, Model model, Direction direction, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Collection<Set<Node>> nodes = prepareNodeSetsFromSets(sourceSets, graph); if (nodes.size() < 2) return Collections.emptySet(); return runCommonStreamWithPOIContinued(nodes, direction, limit, graph); }
[ "public", "static", "Set", "<", "BioPAXElement", ">", "runCommonStreamWithPOIMultiSet", "(", "Set", "<", "Set", "<", "BioPAXElement", ">", ">", "sourceSets", ",", "Model", "model", ",", "Direction", "direction", ",", "int", "limit", ",", "Filter", "...", "filt...
First finds the common stream, then completes it with the paths between seed and common stream. @param sourceSets Seed to the query @param model BioPAX model @param direction UPSTREAM or DOWNSTREAM @param limit Length limit for the search @param filters for filtering graph elements @return BioPAX elements in the result
[ "First", "finds", "the", "common", "stream", "then", "completes", "it", "with", "the", "paths", "between", "seed", "and", "common", "stream", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java#L363-L383
sdaschner/jaxrs-analyzer
src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/ProjectAnalyzer.java
ProjectAnalyzer.addDirectoryClasses
private void addDirectoryClasses(final Path location, final Path subPath) { for (final File file : location.toFile().listFiles()) { if (file.isDirectory()) addDirectoryClasses(location.resolve(file.getName()), subPath.resolve(file.getName())); else if (file.isFile() && file.getName().endsWith(".class")) { final String classFileName = subPath.resolve(file.getName()).toString(); classes.add(toQualifiedClassName(classFileName)); } } }
java
private void addDirectoryClasses(final Path location, final Path subPath) { for (final File file : location.toFile().listFiles()) { if (file.isDirectory()) addDirectoryClasses(location.resolve(file.getName()), subPath.resolve(file.getName())); else if (file.isFile() && file.getName().endsWith(".class")) { final String classFileName = subPath.resolve(file.getName()).toString(); classes.add(toQualifiedClassName(classFileName)); } } }
[ "private", "void", "addDirectoryClasses", "(", "final", "Path", "location", ",", "final", "Path", "subPath", ")", "{", "for", "(", "final", "File", "file", ":", "location", ".", "toFile", "(", ")", ".", "listFiles", "(", ")", ")", "{", "if", "(", "file...
Adds all classes in the given directory location to the set of known classes. @param location The location of the current directory @param subPath The sub-path which is relevant for the package names or {@code null} if currently in the root directory
[ "Adds", "all", "classes", "in", "the", "given", "directory", "location", "to", "the", "set", "of", "known", "classes", "." ]
train
https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/ProjectAnalyzer.java#L189-L198
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.searchRecipes
public void searchRecipes(boolean isInput, int id, Callback<List<Integer>> callback) throws NullPointerException { if (isInput) gw2API.searchInputRecipes(Integer.toString(id)).enqueue(callback); else gw2API.searchOutputRecipes(Integer.toString(id)).enqueue(callback); }
java
public void searchRecipes(boolean isInput, int id, Callback<List<Integer>> callback) throws NullPointerException { if (isInput) gw2API.searchInputRecipes(Integer.toString(id)).enqueue(callback); else gw2API.searchOutputRecipes(Integer.toString(id)).enqueue(callback); }
[ "public", "void", "searchRecipes", "(", "boolean", "isInput", ",", "int", "id", ",", "Callback", "<", "List", "<", "Integer", ">", ">", "callback", ")", "throws", "NullPointerException", "{", "if", "(", "isInput", ")", "gw2API", ".", "searchInputRecipes", "(...
For more info on Recipes search API go <a href="https://wiki.guildwars2.com/wiki/API:2/recipes/search">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws NullPointerException if given {@link Callback} is empty @see Recipe recipe info
[ "For", "more", "info", "on", "Recipes", "search", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "recipes", "/", "search", ">", "here<", "/", "a", ">", "<br", "/"...
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2321-L2324
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.createOrUpdate
protected DaoResult createOrUpdate(Connection conn, T bo) { if (bo == null) { return null; } DaoResult result = create(conn, bo); DaoOperationStatus status = result.getStatus(); if (status == DaoOperationStatus.DUPLICATED_VALUE || status == DaoOperationStatus.DUPLICATED_UNIQUE) { result = update(conn, bo); } return result; }
java
protected DaoResult createOrUpdate(Connection conn, T bo) { if (bo == null) { return null; } DaoResult result = create(conn, bo); DaoOperationStatus status = result.getStatus(); if (status == DaoOperationStatus.DUPLICATED_VALUE || status == DaoOperationStatus.DUPLICATED_UNIQUE) { result = update(conn, bo); } return result; }
[ "protected", "DaoResult", "createOrUpdate", "(", "Connection", "conn", ",", "T", "bo", ")", "{", "if", "(", "bo", "==", "null", ")", "{", "return", "null", ";", "}", "DaoResult", "result", "=", "create", "(", "conn", ",", "bo", ")", ";", "DaoOperationS...
Create a new BO or update an existing one. @param conn @param bo @return @since 0.8.1
[ "Create", "a", "new", "BO", "or", "update", "an", "existing", "one", "." ]
train
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L692-L703
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendBinary
public static <T> void sendBinary(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context, long timeoutmillis) { sendInternal(mergeBuffers(data), WebSocketFrameType.BINARY, wsChannel, callback, context, timeoutmillis); }
java
public static <T> void sendBinary(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context, long timeoutmillis) { sendInternal(mergeBuffers(data), WebSocketFrameType.BINARY, wsChannel, callback, context, timeoutmillis); }
[ "public", "static", "<", "T", ">", "void", "sendBinary", "(", "final", "ByteBuffer", "[", "]", "data", ",", "final", "WebSocketChannel", "wsChannel", ",", "final", "WebSocketCallback", "<", "T", ">", "callback", ",", "T", "context", ",", "long", "timeoutmill...
Sends a complete binary message, invoking the callback when complete @param data The data to send @param wsChannel The web socket channel @param callback The callback to invoke on completion @param context The context object that will be passed to the callback on completion @param timeoutmillis the timeout in milliseconds
[ "Sends", "a", "complete", "binary", "message", "invoking", "the", "callback", "when", "complete" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L674-L676
alkacon/opencms-core
src/org/opencms/webdav/CmsWebdavServlet.java
CmsWebdavServlet.generateLockDiscovery
private boolean generateLockDiscovery(String path, Element elem, HttpServletRequest req) { CmsRepositoryLockInfo lock = m_session.getLock(path); if (lock != null) { Element lockElem = addElement(elem, TAG_LOCKDISCOVERY); addLockElement(lock, lockElem, generateLockToken(req, lock)); return true; } return false; }
java
private boolean generateLockDiscovery(String path, Element elem, HttpServletRequest req) { CmsRepositoryLockInfo lock = m_session.getLock(path); if (lock != null) { Element lockElem = addElement(elem, TAG_LOCKDISCOVERY); addLockElement(lock, lockElem, generateLockToken(req, lock)); return true; } return false; }
[ "private", "boolean", "generateLockDiscovery", "(", "String", "path", ",", "Element", "elem", ",", "HttpServletRequest", "req", ")", "{", "CmsRepositoryLockInfo", "lock", "=", "m_session", ".", "getLock", "(", "path", ")", ";", "if", "(", "lock", "!=", "null",...
Print the lock discovery information associated with a path.<p> @param path the path to the resource @param elem the dom element where to add the lock discovery elements @param req the servlet request we are processing @return true if at least one lock was displayed
[ "Print", "the", "lock", "discovery", "information", "associated", "with", "a", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/webdav/CmsWebdavServlet.java#L3029-L3042
jbake-org/jbake
jbake-core/src/main/java/org/jbake/template/TemplateEngines.java
TemplateEngines.tryLoadEngine
private static AbstractTemplateEngine tryLoadEngine(final JBakeConfiguration config, final ContentStore db, String engineClassName) { try { @SuppressWarnings("unchecked") Class<? extends AbstractTemplateEngine> engineClass = (Class<? extends AbstractTemplateEngine>) Class.forName(engineClassName, false, TemplateEngines.class.getClassLoader()); Constructor<? extends AbstractTemplateEngine> ctor = engineClass.getConstructor(JBakeConfiguration.class, ContentStore.class); return ctor.newInstance(config, db); } catch (Throwable e) { // not all engines might be necessary, therefore only emit class loading issue with level warn LOGGER.warn("unable to load engine", e); return null; } }
java
private static AbstractTemplateEngine tryLoadEngine(final JBakeConfiguration config, final ContentStore db, String engineClassName) { try { @SuppressWarnings("unchecked") Class<? extends AbstractTemplateEngine> engineClass = (Class<? extends AbstractTemplateEngine>) Class.forName(engineClassName, false, TemplateEngines.class.getClassLoader()); Constructor<? extends AbstractTemplateEngine> ctor = engineClass.getConstructor(JBakeConfiguration.class, ContentStore.class); return ctor.newInstance(config, db); } catch (Throwable e) { // not all engines might be necessary, therefore only emit class loading issue with level warn LOGGER.warn("unable to load engine", e); return null; } }
[ "private", "static", "AbstractTemplateEngine", "tryLoadEngine", "(", "final", "JBakeConfiguration", "config", ",", "final", "ContentStore", "db", ",", "String", "engineClassName", ")", "{", "try", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Class", "<"...
This method is used to search for a specific class, telling if loading the engine would succeed. This is typically used to avoid loading optional modules. @param config the configuration @param db database instance @param engineClassName engine class, used both as a hint to find it and to create the engine itself. @return null if the engine is not available, an instance of the engine otherwise
[ "This", "method", "is", "used", "to", "search", "for", "a", "specific", "class", "telling", "if", "loading", "the", "engine", "would", "succeed", ".", "This", "is", "typically", "used", "to", "avoid", "loading", "optional", "modules", "." ]
train
https://github.com/jbake-org/jbake/blob/beb9042a54bf0eb168821d524c88b9ea0bee88dc/jbake-core/src/main/java/org/jbake/template/TemplateEngines.java#L74-L85
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/base/Json.java
Json.resource_to_string
public String resource_to_string(base_resource resrc, options option) { String result = "{ "; if (option != null && option.get_action() != null) result = result + "\"params\": {\"action\":\"" + option.get_action() + "\"},"; result = result + "\"" + resrc.get_object_type() + "\":" + this.resource_to_string(resrc) + "}"; return result; }
java
public String resource_to_string(base_resource resrc, options option) { String result = "{ "; if (option != null && option.get_action() != null) result = result + "\"params\": {\"action\":\"" + option.get_action() + "\"},"; result = result + "\"" + resrc.get_object_type() + "\":" + this.resource_to_string(resrc) + "}"; return result; }
[ "public", "String", "resource_to_string", "(", "base_resource", "resrc", ",", "options", "option", ")", "{", "String", "result", "=", "\"{ \"", ";", "if", "(", "option", "!=", "null", "&&", "option", ".", "get_action", "(", ")", "!=", "null", ")", "result"...
Converts NetScaler SDX resource to Json string. @param resrc API resource. @param option options class object. @return returns a String
[ "Converts", "NetScaler", "SDX", "resource", "to", "Json", "string", "." ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/base/Json.java#L64-L72
Javacord/Javacord
javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java
RatelimitManager.calculateOffset
private void calculateOffset(long currentTime, RestRequestResult result) { // Double-checked locking for better performance if ((api.getTimeOffset() != null) || (result == null) || (result.getResponse() == null)) { return; } synchronized (api) { if (api.getTimeOffset() == null) { // Discord sends the date in their header in the format RFC_1123_DATE_TIME // We use this header to calculate a possible offset between our local time and the discord time String date = result.getResponse().header("Date"); if (date != null) { long discordTimestamp = OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME) .toInstant().toEpochMilli(); api.setTimeOffset((discordTimestamp - currentTime)); logger.debug("Calculated an offset of {} to the Discord time.", api::getTimeOffset); } } } }
java
private void calculateOffset(long currentTime, RestRequestResult result) { // Double-checked locking for better performance if ((api.getTimeOffset() != null) || (result == null) || (result.getResponse() == null)) { return; } synchronized (api) { if (api.getTimeOffset() == null) { // Discord sends the date in their header in the format RFC_1123_DATE_TIME // We use this header to calculate a possible offset between our local time and the discord time String date = result.getResponse().header("Date"); if (date != null) { long discordTimestamp = OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME) .toInstant().toEpochMilli(); api.setTimeOffset((discordTimestamp - currentTime)); logger.debug("Calculated an offset of {} to the Discord time.", api::getTimeOffset); } } } }
[ "private", "void", "calculateOffset", "(", "long", "currentTime", ",", "RestRequestResult", "result", ")", "{", "// Double-checked locking for better performance", "if", "(", "(", "api", ".", "getTimeOffset", "(", ")", "!=", "null", ")", "||", "(", "result", "==",...
Calculates the offset of the local time and discord's time. @param currentTime The current time. @param result The result of the rest request.
[ "Calculates", "the", "offset", "of", "the", "local", "time", "and", "discord", "s", "time", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java#L212-L230
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.configureStoragePlugin
private void configureStoragePlugin(TreeBuilder<ResourceMeta> builder, int index, Map<String, String> configProps) { String pref1 = getStorageConfigPrefix() + SEP + index; String pluginType = configProps.get(pref1 + SEP + TYPE); String path = configProps.get(pref1 + SEP + PATH); boolean removePathPrefix = Boolean.parseBoolean(configProps.get(pref1 + SEP + REMOVE_PATH_PREFIX)); Map<String, String> config = subPropertyMap(pref1 + SEP + CONFIG + SEP, configProps); config = expandConfig(config); Tree<ResourceMeta> resourceMetaTree = loadPlugin( pluginType, config, storagePluginProviderService ); if (index == 1 && PathUtil.isRoot(path)) { logger.debug("New base Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.base(resourceMetaTree); } else { logger.debug("Subtree Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.subTree(PathUtil.asPath(path.trim()), resourceMetaTree, !removePathPrefix); } }
java
private void configureStoragePlugin(TreeBuilder<ResourceMeta> builder, int index, Map<String, String> configProps) { String pref1 = getStorageConfigPrefix() + SEP + index; String pluginType = configProps.get(pref1 + SEP + TYPE); String path = configProps.get(pref1 + SEP + PATH); boolean removePathPrefix = Boolean.parseBoolean(configProps.get(pref1 + SEP + REMOVE_PATH_PREFIX)); Map<String, String> config = subPropertyMap(pref1 + SEP + CONFIG + SEP, configProps); config = expandConfig(config); Tree<ResourceMeta> resourceMetaTree = loadPlugin( pluginType, config, storagePluginProviderService ); if (index == 1 && PathUtil.isRoot(path)) { logger.debug("New base Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.base(resourceMetaTree); } else { logger.debug("Subtree Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.subTree(PathUtil.asPath(path.trim()), resourceMetaTree, !removePathPrefix); } }
[ "private", "void", "configureStoragePlugin", "(", "TreeBuilder", "<", "ResourceMeta", ">", "builder", ",", "int", "index", ",", "Map", "<", "String", ",", "String", ">", "configProps", ")", "{", "String", "pref1", "=", "getStorageConfigPrefix", "(", ")", "+", ...
Configures storage plugins with the builder @param builder builder @param index current prop index @param configProps configuration properties
[ "Configures", "storage", "plugins", "with", "the", "builder" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L283-L304
gwt-maven-plugin/gwt-maven-plugin
src/main/java/org/codehaus/mojo/gwt/ClasspathBuilder.java
ClasspathBuilder.addResources
private void addResources( final Collection<File> items, final Collection<Resource> resources ) { for ( Resource resource : resources ) { items.add( new File( resource.getDirectory() ) ); } }
java
private void addResources( final Collection<File> items, final Collection<Resource> resources ) { for ( Resource resource : resources ) { items.add( new File( resource.getDirectory() ) ); } }
[ "private", "void", "addResources", "(", "final", "Collection", "<", "File", ">", "items", ",", "final", "Collection", "<", "Resource", ">", "resources", ")", "{", "for", "(", "Resource", "resource", ":", "resources", ")", "{", "items", ".", "add", "(", "...
Add source path and resource paths of the project to the list of classpath items. @param items Classpath items. @param resources
[ "Add", "source", "path", "and", "resource", "paths", "of", "the", "project", "to", "the", "list", "of", "classpath", "items", "." ]
train
https://github.com/gwt-maven-plugin/gwt-maven-plugin/blob/0cdd5054b43f182cc22a8acf61ec79ac42b0dfdc/src/main/java/org/codehaus/mojo/gwt/ClasspathBuilder.java#L287-L293
mapbox/mapbox-navigation-android
libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/utils/DistanceFormatter.java
DistanceFormatter.formatDistance
public SpannableString formatDistance(double distance) { double distanceSmallUnit = TurfConversion.convertLength(distance, TurfConstants.UNIT_METERS, smallUnit); double distanceLargeUnit = TurfConversion.convertLength(distance, TurfConstants.UNIT_METERS, largeUnit); // If the distance is greater than 10 miles/kilometers, then round to nearest mile/kilometer if (distanceLargeUnit > LARGE_UNIT_THRESHOLD) { return getDistanceString(roundToDecimalPlace(distanceLargeUnit, 0), largeUnit); // If the distance is less than 401 feet/meters, round by fifty feet/meters } else if (distanceSmallUnit < SMALL_UNIT_THRESHOLD) { return getDistanceString(roundToClosestIncrement(distanceSmallUnit), smallUnit); // If the distance is between 401 feet/meters and 10 miles/kilometers, then round to one decimal place } else { return getDistanceString(roundToDecimalPlace(distanceLargeUnit, 1), largeUnit); } }
java
public SpannableString formatDistance(double distance) { double distanceSmallUnit = TurfConversion.convertLength(distance, TurfConstants.UNIT_METERS, smallUnit); double distanceLargeUnit = TurfConversion.convertLength(distance, TurfConstants.UNIT_METERS, largeUnit); // If the distance is greater than 10 miles/kilometers, then round to nearest mile/kilometer if (distanceLargeUnit > LARGE_UNIT_THRESHOLD) { return getDistanceString(roundToDecimalPlace(distanceLargeUnit, 0), largeUnit); // If the distance is less than 401 feet/meters, round by fifty feet/meters } else if (distanceSmallUnit < SMALL_UNIT_THRESHOLD) { return getDistanceString(roundToClosestIncrement(distanceSmallUnit), smallUnit); // If the distance is between 401 feet/meters and 10 miles/kilometers, then round to one decimal place } else { return getDistanceString(roundToDecimalPlace(distanceLargeUnit, 1), largeUnit); } }
[ "public", "SpannableString", "formatDistance", "(", "double", "distance", ")", "{", "double", "distanceSmallUnit", "=", "TurfConversion", ".", "convertLength", "(", "distance", ",", "TurfConstants", ".", "UNIT_METERS", ",", "smallUnit", ")", ";", "double", "distance...
Returns a formatted SpannableString with bold and size formatting. I.e., "10 mi", "350 m" @param distance in meters @return SpannableString representation which has a bolded number and units which have a relative size of .65 times the size of the number
[ "Returns", "a", "formatted", "SpannableString", "with", "bold", "and", "size", "formatting", ".", "I", ".", "e", ".", "10", "mi", "350", "m" ]
train
https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/utils/DistanceFormatter.java#L92-L106
joniles/mpxj
src/main/java/net/sf/mpxj/synchro/TableReader.java
TableReader.readUUID
protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException { int unknown0Size = stream.getMajorVersion() > 5 ? 8 : 16; map.put("UNKNOWN0", stream.readBytes(unknown0Size)); map.put("UUID", stream.readUUID()); }
java
protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException { int unknown0Size = stream.getMajorVersion() > 5 ? 8 : 16; map.put("UNKNOWN0", stream.readBytes(unknown0Size)); map.put("UUID", stream.readUUID()); }
[ "protected", "void", "readUUID", "(", "StreamReader", "stream", ",", "Map", "<", "String", ",", "Object", ">", "map", ")", "throws", "IOException", "{", "int", "unknown0Size", "=", "stream", ".", "getMajorVersion", "(", ")", ">", "5", "?", "8", ":", "16"...
Read the optional row header and UUID. @param stream input stream @param map row map
[ "Read", "the", "optional", "row", "header", "and", "UUID", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/synchro/TableReader.java#L124-L129
RuedigerMoeller/kontraktor
modules/kontraktor-reallive/src/main/java/org/nustaq/reallive/impl/StorageDriver.java
StorageDriver.atomicQuery
public IPromise atomicQuery(String key, RLFunction<Record,Object> action) { Record rec = getStore().get(key); if ( rec == null ) { final Object apply = action.apply(rec); if ( apply instanceof ChangeMessage ) { receive( (ChangeMessage) apply ) ; } return new Promise(apply); } else { PatchingRecord pr = new PatchingRecord(rec); final Object res = action.apply(pr); if ( res instanceof ChangeMessage ) { receive( (ChangeMessage) res ) ; } else { UpdateMessage updates = pr.getUpdates(0); if (updates != null) { receive(updates); } } return new Promise(res); } }
java
public IPromise atomicQuery(String key, RLFunction<Record,Object> action) { Record rec = getStore().get(key); if ( rec == null ) { final Object apply = action.apply(rec); if ( apply instanceof ChangeMessage ) { receive( (ChangeMessage) apply ) ; } return new Promise(apply); } else { PatchingRecord pr = new PatchingRecord(rec); final Object res = action.apply(pr); if ( res instanceof ChangeMessage ) { receive( (ChangeMessage) res ) ; } else { UpdateMessage updates = pr.getUpdates(0); if (updates != null) { receive(updates); } } return new Promise(res); } }
[ "public", "IPromise", "atomicQuery", "(", "String", "key", ",", "RLFunction", "<", "Record", ",", "Object", ">", "action", ")", "{", "Record", "rec", "=", "getStore", "(", ")", ".", "get", "(", "key", ")", ";", "if", "(", "rec", "==", "null", ")", ...
apply the function to the record with given key and return the result inside a promise changes to the record inside the function are applied to the real record and a change message is generated. In case the function returns a changemessage (add,putRecord,remove ..), the change message is applied to the original record and the change is broadcasted @param key @param action @return the result of function.
[ "apply", "the", "function", "to", "the", "record", "with", "given", "key", "and", "return", "the", "result", "inside", "a", "promise" ]
train
https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/modules/kontraktor-reallive/src/main/java/org/nustaq/reallive/impl/StorageDriver.java#L171-L194
liferay/com-liferay-commerce
commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java
CommerceCurrencyPersistenceImpl.findByGroupId
@Override public List<CommerceCurrency> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
java
@Override public List<CommerceCurrency> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceCurrency", ">", "findByGroupId", "(", "long", "groupId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByGroupId", "(", "groupId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce currencies where groupId = &#63;. <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 CommerceCurrencyModelImpl}. 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 groupId the group ID @param start the lower bound of the range of commerce currencies @param end the upper bound of the range of commerce currencies (not inclusive) @return the range of matching commerce currencies
[ "Returns", "a", "range", "of", "all", "the", "commerce", "currencies", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L1531-L1534
liyiorg/weixin-popular
src/main/java/weixin/popular/api/PayMchAPI.java
PayMchAPI.mmpaymkttransfersGettransferinfo
public static GettransferinfoResult mmpaymkttransfersGettransferinfo(Gettransferinfo gettransferinfo,String key){ Map<String,String> map = MapUtil.objectToMap( gettransferinfo); String sign = SignatureUtil.generateSign(map,gettransferinfo.getSign_type(),key); gettransferinfo.setSign(sign); String secapiPayRefundXML = XMLConverUtil.convertToXML( gettransferinfo); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI()+ "/mmpaymkttransfers/gettransferinfo") .setEntity(new StringEntity(secapiPayRefundXML,Charset.forName("utf-8"))) .build(); return LocalHttpClient.keyStoreExecuteXmlResult(gettransferinfo.getMch_id(),httpUriRequest,GettransferinfoResult.class,gettransferinfo.getSign_type(),key); }
java
public static GettransferinfoResult mmpaymkttransfersGettransferinfo(Gettransferinfo gettransferinfo,String key){ Map<String,String> map = MapUtil.objectToMap( gettransferinfo); String sign = SignatureUtil.generateSign(map,gettransferinfo.getSign_type(),key); gettransferinfo.setSign(sign); String secapiPayRefundXML = XMLConverUtil.convertToXML( gettransferinfo); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI()+ "/mmpaymkttransfers/gettransferinfo") .setEntity(new StringEntity(secapiPayRefundXML,Charset.forName("utf-8"))) .build(); return LocalHttpClient.keyStoreExecuteXmlResult(gettransferinfo.getMch_id(),httpUriRequest,GettransferinfoResult.class,gettransferinfo.getSign_type(),key); }
[ "public", "static", "GettransferinfoResult", "mmpaymkttransfersGettransferinfo", "(", "Gettransferinfo", "gettransferinfo", ",", "String", "key", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "MapUtil", ".", "objectToMap", "(", "gettransferinfo", "...
查询企业付款 @since 2.8.5 @param gettransferinfo gettransferinfo @param key key @return GettransferinfoResult
[ "查询企业付款" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/PayMchAPI.java#L593-L604
UrielCh/ovh-java-sdk
ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java
ApiOvhVps.serviceName_distribution_software_softwareId_GET
public OvhSoftware serviceName_distribution_software_softwareId_GET(String serviceName, Long softwareId) throws IOException { String qPath = "/vps/{serviceName}/distribution/software/{softwareId}"; StringBuilder sb = path(qPath, serviceName, softwareId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSoftware.class); }
java
public OvhSoftware serviceName_distribution_software_softwareId_GET(String serviceName, Long softwareId) throws IOException { String qPath = "/vps/{serviceName}/distribution/software/{softwareId}"; StringBuilder sb = path(qPath, serviceName, softwareId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSoftware.class); }
[ "public", "OvhSoftware", "serviceName_distribution_software_softwareId_GET", "(", "String", "serviceName", ",", "Long", "softwareId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/vps/{serviceName}/distribution/software/{softwareId}\"", ";", "StringBuilder", "s...
Get this object properties REST: GET /vps/{serviceName}/distribution/software/{softwareId} @param serviceName [required] The internal name of your VPS offer @param softwareId [required]
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java#L459-L464
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java
ResourceLoader.getResourceAsStream
public static InputStream getResourceAsStream(Class<?> requestingClass, String resource) throws ResourceMissingException, IOException { return getResourceAsURL(requestingClass, resource).openStream(); }
java
public static InputStream getResourceAsStream(Class<?> requestingClass, String resource) throws ResourceMissingException, IOException { return getResourceAsURL(requestingClass, resource).openStream(); }
[ "public", "static", "InputStream", "getResourceAsStream", "(", "Class", "<", "?", ">", "requestingClass", ",", "String", "resource", ")", "throws", "ResourceMissingException", ",", "IOException", "{", "return", "getResourceAsURL", "(", "requestingClass", ",", "resourc...
Returns the requested resource as a stream. @param requestingClass the java.lang.Class object of the class that is attempting to load the resource @param resource a String describing the full or partial URL of the resource to load @return the requested resource as a stream @throws ResourceMissingException @throws java.io.IOException
[ "Returns", "the", "requested", "resource", "as", "a", "stream", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/ResourceLoader.java#L212-L215
BotMill/fb-botmill
src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/AttachmentMessageBuilder.java
AttachmentMessageBuilder.build
public FbBotMillResponse build(MessageEnvelope envelope) { User recipient = getRecipient(envelope); Message message = new AttachmentMessage(attachment); message.setQuickReplies(quickReplies); return new FbBotMillMessageResponse(recipient, message); }
java
public FbBotMillResponse build(MessageEnvelope envelope) { User recipient = getRecipient(envelope); Message message = new AttachmentMessage(attachment); message.setQuickReplies(quickReplies); return new FbBotMillMessageResponse(recipient, message); }
[ "public", "FbBotMillResponse", "build", "(", "MessageEnvelope", "envelope", ")", "{", "User", "recipient", "=", "getRecipient", "(", "envelope", ")", ";", "Message", "message", "=", "new", "AttachmentMessage", "(", "attachment", ")", ";", "message", ".", "setQui...
{@inheritDoc} Returns a response containing an {@link Attachment}.
[ "{" ]
train
https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/AttachmentMessageBuilder.java#L124-L129
dwdyer/watchmaker
examples/src/java/main/org/uncommons/watchmaker/examples/biomorphs/BiomorphApplet.java
BiomorphApplet.prepareGUI
@Override protected void prepareGUI(Container container) { renderer = new SwingBiomorphRenderer(); console = new SwingConsole(5); selectionDialog = new JDialog((JFrame) null, "Biomorph Selection", true); biomorphHolder = new JPanel(new GridLayout(1, 1)); container.add(new ControlPanel(), BorderLayout.WEST); container.add(biomorphHolder, BorderLayout.CENTER); biomorphHolder.setBorder(BorderFactory.createTitledBorder("Last Evolved Biomorph")); biomorphHolder.add(new JLabel("Nothing generated yet.", JLabel.CENTER)); selectionDialog.add(console, BorderLayout.CENTER); selectionDialog.setSize(800, 600); selectionDialog.validate(); }
java
@Override protected void prepareGUI(Container container) { renderer = new SwingBiomorphRenderer(); console = new SwingConsole(5); selectionDialog = new JDialog((JFrame) null, "Biomorph Selection", true); biomorphHolder = new JPanel(new GridLayout(1, 1)); container.add(new ControlPanel(), BorderLayout.WEST); container.add(biomorphHolder, BorderLayout.CENTER); biomorphHolder.setBorder(BorderFactory.createTitledBorder("Last Evolved Biomorph")); biomorphHolder.add(new JLabel("Nothing generated yet.", JLabel.CENTER)); selectionDialog.add(console, BorderLayout.CENTER); selectionDialog.setSize(800, 600); selectionDialog.validate(); }
[ "@", "Override", "protected", "void", "prepareGUI", "(", "Container", "container", ")", "{", "renderer", "=", "new", "SwingBiomorphRenderer", "(", ")", ";", "console", "=", "new", "SwingConsole", "(", "5", ")", ";", "selectionDialog", "=", "new", "JDialog", ...
Initialise and layout the GUI. @param container The Swing component that will contain the GUI controls.
[ "Initialise", "and", "layout", "the", "GUI", "." ]
train
https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/examples/src/java/main/org/uncommons/watchmaker/examples/biomorphs/BiomorphApplet.java#L69-L84
wcm-io/wcm-io-sling
commons/src/main/java/io/wcm/sling/commons/adapter/AdaptTo.java
AdaptTo.notNull
@SuppressWarnings("null") public static <T> @NotNull T notNull(@NotNull Adaptable adaptable, @NotNull Class<T> type) { T object = adaptable.adaptTo(type); if (object == null) { throw new UnableToAdaptException(adaptable, type); } return object; }
java
@SuppressWarnings("null") public static <T> @NotNull T notNull(@NotNull Adaptable adaptable, @NotNull Class<T> type) { T object = adaptable.adaptTo(type); if (object == null) { throw new UnableToAdaptException(adaptable, type); } return object; }
[ "@", "SuppressWarnings", "(", "\"null\"", ")", "public", "static", "<", "T", ">", "@", "NotNull", "T", "notNull", "(", "@", "NotNull", "Adaptable", "adaptable", ",", "@", "NotNull", "Class", "<", "T", ">", "type", ")", "{", "T", "object", "=", "adaptab...
Try to adapt the adaptable to the given type and ensures that it succeeds. @param adaptable Adaptable @param type Type @param <T> Type @return Adaption result (not null) @throws UnableToAdaptException if the adaption was not successful
[ "Try", "to", "adapt", "the", "adaptable", "to", "the", "given", "type", "and", "ensures", "that", "it", "succeeds", "." ]
train
https://github.com/wcm-io/wcm-io-sling/blob/90adbe432469378794b5695c72e9cdfa2b7d36f1/commons/src/main/java/io/wcm/sling/commons/adapter/AdaptTo.java#L44-L51
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java
DiagnosticsInner.executeSiteDetectorAsync
public Observable<DiagnosticDetectorResponseInner> executeSiteDetectorAsync(String resourceGroupName, String siteName, String detectorName, String diagnosticCategory, DateTime startTime, DateTime endTime, String timeGrain) { return executeSiteDetectorWithServiceResponseAsync(resourceGroupName, siteName, detectorName, diagnosticCategory, startTime, endTime, timeGrain).map(new Func1<ServiceResponse<DiagnosticDetectorResponseInner>, DiagnosticDetectorResponseInner>() { @Override public DiagnosticDetectorResponseInner call(ServiceResponse<DiagnosticDetectorResponseInner> response) { return response.body(); } }); }
java
public Observable<DiagnosticDetectorResponseInner> executeSiteDetectorAsync(String resourceGroupName, String siteName, String detectorName, String diagnosticCategory, DateTime startTime, DateTime endTime, String timeGrain) { return executeSiteDetectorWithServiceResponseAsync(resourceGroupName, siteName, detectorName, diagnosticCategory, startTime, endTime, timeGrain).map(new Func1<ServiceResponse<DiagnosticDetectorResponseInner>, DiagnosticDetectorResponseInner>() { @Override public DiagnosticDetectorResponseInner call(ServiceResponse<DiagnosticDetectorResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DiagnosticDetectorResponseInner", ">", "executeSiteDetectorAsync", "(", "String", "resourceGroupName", ",", "String", "siteName", ",", "String", "detectorName", ",", "String", "diagnosticCategory", ",", "DateTime", "startTime", ",", "DateTime...
Execute Detector. Execute Detector. @param resourceGroupName Name of the resource group to which the resource belongs. @param siteName Site Name @param detectorName Detector Resource Name @param diagnosticCategory Category Name @param startTime Start Time @param endTime End Time @param timeGrain Time Grain @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DiagnosticDetectorResponseInner object
[ "Execute", "Detector", ".", "Execute", "Detector", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java#L1274-L1281
btaz/data-util
src/main/java/com/btaz/util/collections/Sets.java
Sets.isSubset
public static <T> boolean isSubset(Set<T> setA, Set<T> setB) { return setB.containsAll(setA); }
java
public static <T> boolean isSubset(Set<T> setA, Set<T> setB) { return setB.containsAll(setA); }
[ "public", "static", "<", "T", ">", "boolean", "isSubset", "(", "Set", "<", "T", ">", "setA", ",", "Set", "<", "T", ">", "setB", ")", "{", "return", "setB", ".", "containsAll", "(", "setA", ")", ";", "}" ]
This method returns true if set A is a subset of set B i.e. it answers the question if all items in A exists in B @param setA set A @param setB set B @param <T> type @return {@code boolean} true if A is a subset of B
[ "This", "method", "returns", "true", "if", "set", "A", "is", "a", "subset", "of", "set", "B", "i", ".", "e", ".", "it", "answers", "the", "question", "if", "all", "items", "in", "A", "exists", "in", "B" ]
train
https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/collections/Sets.java#L127-L129
lightbend/config
config/src/main/java/com/typesafe/config/ConfigFactory.java
ConfigFactory.parseResources
public static Config parseResources(Class<?> klass, String resource) { return parseResources(klass, resource, ConfigParseOptions.defaults()); }
java
public static Config parseResources(Class<?> klass, String resource) { return parseResources(klass, resource, ConfigParseOptions.defaults()); }
[ "public", "static", "Config", "parseResources", "(", "Class", "<", "?", ">", "klass", ",", "String", "resource", ")", "{", "return", "parseResources", "(", "klass", ",", "resource", ",", "ConfigParseOptions", ".", "defaults", "(", ")", ")", ";", "}" ]
Like {@link #parseResources(Class,String,ConfigParseOptions)} but always uses default parse options. @param klass <code>klass.getClassLoader()</code> will be used to load resources, and non-absolute resource names will have this class's package added @param resource resource to look up, relative to <code>klass</code>'s package or absolute starting with a "/" @return the parsed configuration
[ "Like", "{", "@link", "#parseResources", "(", "Class", "String", "ConfigParseOptions", ")", "}", "but", "always", "uses", "default", "parse", "options", "." ]
train
https://github.com/lightbend/config/blob/68cebfde5e861e9a5fdc75ceff366ed95e17d475/config/src/main/java/com/typesafe/config/ConfigFactory.java#L854-L856
apache/groovy
subprojects/groovy-jmx/src/main/java/groovy/jmx/builder/JmxBuilderModelMBean.java
JmxBuilderModelMBean.addEventListeners
public void addEventListeners(MBeanServer server, Map<String, Map<String, Object>> descriptor) { for (Map.Entry<String, Map<String, Object>> item : descriptor.entrySet()) { Map<String, Object> listener = item.getValue(); // register with server ObjectName broadcaster = (ObjectName) listener.get("from"); try { String eventType = (String) listener.get("event"); if (eventType != null) { NotificationFilterSupport filter = new NotificationFilterSupport(); filter.enableType(eventType); server.addNotificationListener(broadcaster, JmxEventListener.getListener(), filter, listener); } else { server.addNotificationListener(broadcaster, JmxEventListener.getListener(), null, listener); } } catch (InstanceNotFoundException e) { throw new JmxBuilderException(e); } } }
java
public void addEventListeners(MBeanServer server, Map<String, Map<String, Object>> descriptor) { for (Map.Entry<String, Map<String, Object>> item : descriptor.entrySet()) { Map<String, Object> listener = item.getValue(); // register with server ObjectName broadcaster = (ObjectName) listener.get("from"); try { String eventType = (String) listener.get("event"); if (eventType != null) { NotificationFilterSupport filter = new NotificationFilterSupport(); filter.enableType(eventType); server.addNotificationListener(broadcaster, JmxEventListener.getListener(), filter, listener); } else { server.addNotificationListener(broadcaster, JmxEventListener.getListener(), null, listener); } } catch (InstanceNotFoundException e) { throw new JmxBuilderException(e); } } }
[ "public", "void", "addEventListeners", "(", "MBeanServer", "server", ",", "Map", "<", "String", ",", "Map", "<", "String", ",", "Object", ">", ">", "descriptor", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Map", "<", "String", ",", ...
Sets up event listeners for this MBean as described in the descriptor. The descriptor contains a map with layout {item -&gt; Map[event:"...", from:ObjectName, callback:&amp;Closure],...,} @param server the MBeanServer is to be registered. @param descriptor a map containing info about the event
[ "Sets", "up", "event", "listeners", "for", "this", "MBean", "as", "described", "in", "the", "descriptor", ".", "The", "descriptor", "contains", "a", "map", "with", "layout", "{", "item", "-", "&gt", ";", "Map", "[", "event", ":", "...", "from", ":", "O...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-jmx/src/main/java/groovy/jmx/builder/JmxBuilderModelMBean.java#L118-L138
JodaOrg/joda-time
src/main/java/org/joda/time/DateMidnight.java
DateMidnight.withFieldAdded
public DateMidnight withFieldAdded(DurationFieldType fieldType, int amount) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (amount == 0) { return this; } long instant = fieldType.getField(getChronology()).add(getMillis(), amount); return withMillis(instant); }
java
public DateMidnight withFieldAdded(DurationFieldType fieldType, int amount) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (amount == 0) { return this; } long instant = fieldType.getField(getChronology()).add(getMillis(), amount); return withMillis(instant); }
[ "public", "DateMidnight", "withFieldAdded", "(", "DurationFieldType", "fieldType", ",", "int", "amount", ")", "{", "if", "(", "fieldType", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Field must not be null\"", ")", ";", "}", "if", ...
Returns a copy of this date with the value of the specified field increased. <p> If the addition is zero or the field is null, then <code>this</code> is returned. <p> These three lines are equivalent: <pre> DateMidnight added = dt.withFieldAdded(DateTimeFieldType.year(), 6); DateMidnight added = dt.plusYears(6); DateMidnight added = dt.year().addToCopy(6); </pre> @param fieldType the field type to add to, not null @param amount the amount to add @return a copy of this datetime with the field updated @throws IllegalArgumentException if the value is null or invalid @throws ArithmeticException if the new datetime exceeds the capacity of a long
[ "Returns", "a", "copy", "of", "this", "date", "with", "the", "value", "of", "the", "specified", "field", "increased", ".", "<p", ">", "If", "the", "addition", "is", "zero", "or", "the", "field", "is", "null", "then", "<code", ">", "this<", "/", "code",...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/DateMidnight.java#L490-L499
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java
DataNode.initFsDataSet
private synchronized void initFsDataSet(Configuration conf, AbstractList<File> dataDirs, int numNamespaces) throws IOException { if (data != null) { // Already initialized return; } // get version and id info from the name-node boolean simulatedFSDataset = conf.getBoolean("dfs.datanode.simulateddatastorage", false); if (simulatedFSDataset) { storage.createStorageID(selfAddr.getPort()); // it would have been better to pass storage as a parameter to // constructor below - need to augment ReflectionUtils used below. conf.set("dfs.datanode.StorageId", storage.getStorageID()); try { data = (FSDatasetInterface) ReflectionUtils.newInstance( Class.forName( "org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"), conf); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.stringifyException(e)); } } else { data = new FSDataset(this, conf, numNamespaces); } }
java
private synchronized void initFsDataSet(Configuration conf, AbstractList<File> dataDirs, int numNamespaces) throws IOException { if (data != null) { // Already initialized return; } // get version and id info from the name-node boolean simulatedFSDataset = conf.getBoolean("dfs.datanode.simulateddatastorage", false); if (simulatedFSDataset) { storage.createStorageID(selfAddr.getPort()); // it would have been better to pass storage as a parameter to // constructor below - need to augment ReflectionUtils used below. conf.set("dfs.datanode.StorageId", storage.getStorageID()); try { data = (FSDatasetInterface) ReflectionUtils.newInstance( Class.forName( "org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"), conf); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.stringifyException(e)); } } else { data = new FSDataset(this, conf, numNamespaces); } }
[ "private", "synchronized", "void", "initFsDataSet", "(", "Configuration", "conf", ",", "AbstractList", "<", "File", ">", "dataDirs", ",", "int", "numNamespaces", ")", "throws", "IOException", "{", "if", "(", "data", "!=", "null", ")", "{", "// Already initialize...
Initializes the {@link #data}. The initialization is done only once, when handshake with the the first namenode is completed.
[ "Initializes", "the", "{" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java#L2226-L2252
jenkinsci/jenkins
core/src/main/java/hudson/model/listeners/ItemListener.java
ItemListener.checkBeforeCopy
public static void checkBeforeCopy(final Item src, final ItemGroup parent) throws Failure { for (ItemListener l : all()) { try { l.onCheckCopy(src, parent); } catch (Failure e) { throw e; } catch (RuntimeException x) { LOGGER.log(Level.WARNING, "failed to send event to listener of " + l.getClass(), x); } } }
java
public static void checkBeforeCopy(final Item src, final ItemGroup parent) throws Failure { for (ItemListener l : all()) { try { l.onCheckCopy(src, parent); } catch (Failure e) { throw e; } catch (RuntimeException x) { LOGGER.log(Level.WARNING, "failed to send event to listener of " + l.getClass(), x); } } }
[ "public", "static", "void", "checkBeforeCopy", "(", "final", "Item", "src", ",", "final", "ItemGroup", "parent", ")", "throws", "Failure", "{", "for", "(", "ItemListener", "l", ":", "all", "(", ")", ")", "{", "try", "{", "l", ".", "onCheckCopy", "(", "...
Call before a job is copied into a new parent, to allow the {@link ItemListener} implementations the ability to veto the copy operation before it starts. @param src the item being copied @param parent the proposed parent @throws Failure if the copy operation has been vetoed. @since 2.51
[ "Call", "before", "a", "job", "is", "copied", "into", "a", "new", "parent", "to", "allow", "the", "{", "@link", "ItemListener", "}", "implementations", "the", "ability", "to", "veto", "the", "copy", "operation", "before", "it", "starts", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/listeners/ItemListener.java#L203-L213
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaTaskLauncher.java
CoronaTaskLauncher.killJob
@SuppressWarnings("deprecation") public void killJob(JobID jobId, Map<String, InetAddress> allTrackers) { for (Map.Entry<String, InetAddress> entry : allTrackers.entrySet()) { String trackerName = entry.getKey(); InetAddress addr = entry.getValue(); String description = "KillJobAction " + jobId; ActionToSend action = new ActionToSend(trackerName, addr, new KillJobAction(jobId), description); allWorkQueues.enqueueAction(action); LOG.info("Queueing " + description + " to worker " + trackerName + "(" + addr.host + ":" + addr.port + ")"); } }
java
@SuppressWarnings("deprecation") public void killJob(JobID jobId, Map<String, InetAddress> allTrackers) { for (Map.Entry<String, InetAddress> entry : allTrackers.entrySet()) { String trackerName = entry.getKey(); InetAddress addr = entry.getValue(); String description = "KillJobAction " + jobId; ActionToSend action = new ActionToSend(trackerName, addr, new KillJobAction(jobId), description); allWorkQueues.enqueueAction(action); LOG.info("Queueing " + description + " to worker " + trackerName + "(" + addr.host + ":" + addr.port + ")"); } }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "void", "killJob", "(", "JobID", "jobId", ",", "Map", "<", "String", ",", "InetAddress", ">", "allTrackers", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "InetAddress", ">", ...
Enqueue an action to kill the job. @param jobId The job identifier. @param allTrackers All trackers to send the kill to.
[ "Enqueue", "an", "action", "to", "kill", "the", "job", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaTaskLauncher.java#L92-L104
apache/incubator-druid
server/src/main/java/org/apache/druid/server/security/AuthorizationUtils.java
AuthorizationUtils.authorizeAllResourceActions
public static Access authorizeAllResourceActions( final AuthenticationResult authenticationResult, final Iterable<ResourceAction> resourceActions, final AuthorizerMapper authorizerMapper ) { final Authorizer authorizer = authorizerMapper.getAuthorizer(authenticationResult.getAuthorizerName()); if (authorizer == null) { throw new ISE("No authorizer found with name: [%s].", authenticationResult.getAuthorizerName()); } // this method returns on first failure, so only successful Access results are kept in the cache final Set<ResourceAction> resultCache = new HashSet<>(); for (ResourceAction resourceAction : resourceActions) { if (resultCache.contains(resourceAction)) { continue; } final Access access = authorizer.authorize( authenticationResult, resourceAction.getResource(), resourceAction.getAction() ); if (!access.isAllowed()) { return access; } else { resultCache.add(resourceAction); } } return Access.OK; }
java
public static Access authorizeAllResourceActions( final AuthenticationResult authenticationResult, final Iterable<ResourceAction> resourceActions, final AuthorizerMapper authorizerMapper ) { final Authorizer authorizer = authorizerMapper.getAuthorizer(authenticationResult.getAuthorizerName()); if (authorizer == null) { throw new ISE("No authorizer found with name: [%s].", authenticationResult.getAuthorizerName()); } // this method returns on first failure, so only successful Access results are kept in the cache final Set<ResourceAction> resultCache = new HashSet<>(); for (ResourceAction resourceAction : resourceActions) { if (resultCache.contains(resourceAction)) { continue; } final Access access = authorizer.authorize( authenticationResult, resourceAction.getResource(), resourceAction.getAction() ); if (!access.isAllowed()) { return access; } else { resultCache.add(resourceAction); } } return Access.OK; }
[ "public", "static", "Access", "authorizeAllResourceActions", "(", "final", "AuthenticationResult", "authenticationResult", ",", "final", "Iterable", "<", "ResourceAction", ">", "resourceActions", ",", "final", "AuthorizerMapper", "authorizerMapper", ")", "{", "final", "Au...
Check a list of resource-actions to be performed by the identity represented by authenticationResult. If one of the resource-actions fails the authorization check, this method returns the failed Access object from the check. Otherwise, return ACCESS_OK if all resource-actions were successfully authorized. @param authenticationResult Authentication result representing identity of requester @param resourceActions An Iterable of resource-actions to authorize @return ACCESS_OK or the Access object from the first failed check
[ "Check", "a", "list", "of", "resource", "-", "actions", "to", "be", "performed", "by", "the", "identity", "represented", "by", "authenticationResult", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/server/security/AuthorizationUtils.java#L103-L134
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonTextMessageValidator.java
JsonTextMessageValidator.performSchemaValidation
private void performSchemaValidation(Message receivedMessage, JsonMessageValidationContext validationContext) { log.debug("Starting Json schema validation ..."); ProcessingReport report = jsonSchemaValidation.validate(receivedMessage, schemaRepositories, validationContext, applicationContext); if (!report.isSuccess()) { log.error("Failed to validate Json schema for message:\n" + receivedMessage.getPayload(String.class)); throw new ValidationException(constructErrorMessage(report)); } log.info("Json schema validation successful: All values OK"); }
java
private void performSchemaValidation(Message receivedMessage, JsonMessageValidationContext validationContext) { log.debug("Starting Json schema validation ..."); ProcessingReport report = jsonSchemaValidation.validate(receivedMessage, schemaRepositories, validationContext, applicationContext); if (!report.isSuccess()) { log.error("Failed to validate Json schema for message:\n" + receivedMessage.getPayload(String.class)); throw new ValidationException(constructErrorMessage(report)); } log.info("Json schema validation successful: All values OK"); }
[ "private", "void", "performSchemaValidation", "(", "Message", "receivedMessage", ",", "JsonMessageValidationContext", "validationContext", ")", "{", "log", ".", "debug", "(", "\"Starting Json schema validation ...\"", ")", ";", "ProcessingReport", "report", "=", "jsonSchema...
Performs the schema validation for the given message under consideration of the given validation context @param receivedMessage The message to be validated @param validationContext The validation context of the current test
[ "Performs", "the", "schema", "validation", "for", "the", "given", "message", "under", "consideration", "of", "the", "given", "validation", "context" ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonTextMessageValidator.java#L140-L154
infinispan/infinispan
query/src/main/java/org/infinispan/query/dsl/embedded/impl/QueryEngine.java
QueryEngine.makeTypeQuery
protected org.apache.lucene.search.Query makeTypeQuery(org.apache.lucene.search.Query query, String targetEntityName) { return query; }
java
protected org.apache.lucene.search.Query makeTypeQuery(org.apache.lucene.search.Query query, String targetEntityName) { return query; }
[ "protected", "org", ".", "apache", ".", "lucene", ".", "search", ".", "Query", "makeTypeQuery", "(", "org", ".", "apache", ".", "lucene", ".", "search", ".", "Query", "query", ",", "String", "targetEntityName", ")", "{", "return", "query", ";", "}" ]
Enhances the give query with an extra condition to discriminate on entity type. This is a no-op in embedded mode but other query engines could use it to discriminate if more types are stored in the same index. To be overridden by subclasses as needed.
[ "Enhances", "the", "give", "query", "with", "an", "extra", "condition", "to", "discriminate", "on", "entity", "type", ".", "This", "is", "a", "no", "-", "op", "in", "embedded", "mode", "but", "other", "query", "engines", "could", "use", "it", "to", "disc...
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/dsl/embedded/impl/QueryEngine.java#L865-L867
jensgerdes/sonar-pmd
sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/PmdConfiguration.java
PmdConfiguration.dumpXmlReport
Path dumpXmlReport(Report report) { if (!settings.getBoolean(PROPERTY_GENERATE_XML).orElse(false)) { return null; } try { final String reportAsString = reportToString(report); final Path reportFile = writeToWorkingDirectory(reportAsString, PMD_RESULT_XML); LOG.info("PMD output report: " + reportFile.toString()); return reportFile; } catch (IOException e) { throw new IllegalStateException("Fail to save the PMD report", e); } }
java
Path dumpXmlReport(Report report) { if (!settings.getBoolean(PROPERTY_GENERATE_XML).orElse(false)) { return null; } try { final String reportAsString = reportToString(report); final Path reportFile = writeToWorkingDirectory(reportAsString, PMD_RESULT_XML); LOG.info("PMD output report: " + reportFile.toString()); return reportFile; } catch (IOException e) { throw new IllegalStateException("Fail to save the PMD report", e); } }
[ "Path", "dumpXmlReport", "(", "Report", "report", ")", "{", "if", "(", "!", "settings", ".", "getBoolean", "(", "PROPERTY_GENERATE_XML", ")", ".", "orElse", "(", "false", ")", ")", "{", "return", "null", ";", "}", "try", "{", "final", "String", "reportAs...
Writes an XML Report about the analyzed project into the current working directory unless <code>sonar.pmd.generateXml</code> is set to false. @param report The report which shall be written into an XML file. @return The file reference to the XML document.
[ "Writes", "an", "XML", "Report", "about", "the", "analyzed", "project", "into", "the", "current", "working", "directory", "unless", "<code", ">", "sonar", ".", "pmd", ".", "generateXml<", "/", "code", ">", "is", "set", "to", "false", "." ]
train
https://github.com/jensgerdes/sonar-pmd/blob/49b9272b2a71aa1b480972ec6cb4cc347bb50959/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/PmdConfiguration.java#L81-L96
sculptor/sculptor
sculptor-maven/sculptor-maven-plugin/src/main/java/org/sculptor/maven/plugin/AbstractLogOutputStream.java
AbstractLogOutputStream.processLine
@Override protected final void processLine(String line, int level) { boolean isError = doProcessLine(line, level); if (isErrorStream || isError) { errorCount++; } lineCount++; }
java
@Override protected final void processLine(String line, int level) { boolean isError = doProcessLine(line, level); if (isErrorStream || isError) { errorCount++; } lineCount++; }
[ "@", "Override", "protected", "final", "void", "processLine", "(", "String", "line", ",", "int", "level", ")", "{", "boolean", "isError", "=", "doProcessLine", "(", "line", ",", "level", ")", ";", "if", "(", "isErrorStream", "||", "isError", ")", "{", "e...
Depending on stream type the given line is logged and the correspondig counter is increased.
[ "Depending", "on", "stream", "type", "the", "given", "line", "is", "logged", "and", "the", "correspondig", "counter", "is", "increased", "." ]
train
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-maven/sculptor-maven-plugin/src/main/java/org/sculptor/maven/plugin/AbstractLogOutputStream.java#L59-L66
upwork/java-upwork
src/com/Upwork/api/UpworkRestClient.java
UpworkRestClient.getJSONObject
public static JSONObject getJSONObject(HttpPost request, Integer method, HashMap<String, String> params) throws JSONException { switch (method) { case METHOD_PUT: case METHOD_DELETE: case METHOD_POST: return doPostRequest(request, params); default: throw new RuntimeException("Wrong http method requested"); } }
java
public static JSONObject getJSONObject(HttpPost request, Integer method, HashMap<String, String> params) throws JSONException { switch (method) { case METHOD_PUT: case METHOD_DELETE: case METHOD_POST: return doPostRequest(request, params); default: throw new RuntimeException("Wrong http method requested"); } }
[ "public", "static", "JSONObject", "getJSONObject", "(", "HttpPost", "request", ",", "Integer", "method", ",", "HashMap", "<", "String", ",", "String", ">", "params", ")", "throws", "JSONException", "{", "switch", "(", "method", ")", "{", "case", "METHOD_PUT", ...
Get JSON response for POST @param request Request object for POST @param method HTTP method @param params POST parameters @throws JSONException @return {@link JSONObject}
[ "Get", "JSON", "response", "for", "POST" ]
train
https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/UpworkRestClient.java#L105-L114
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java
ActiveSyncManager.recoverFromStopSync
public void recoverFromStopSync(AlluxioURI uri, long mountId) { if (mSyncPathStatus.containsKey(uri)) { // nothing to recover from, since the syncPathStatus still contains syncPoint return; } try { // the init sync thread has been removed, to reestablish sync, we need to sync again MountTable.Resolution resolution = mMountTable.resolve(uri); startInitSync(uri, resolution); launchPollingThread(resolution.getMountId(), SyncInfo.INVALID_TXID); } catch (Throwable t) { LOG.warn("Recovering from stop syncing failed {}", t); } }
java
public void recoverFromStopSync(AlluxioURI uri, long mountId) { if (mSyncPathStatus.containsKey(uri)) { // nothing to recover from, since the syncPathStatus still contains syncPoint return; } try { // the init sync thread has been removed, to reestablish sync, we need to sync again MountTable.Resolution resolution = mMountTable.resolve(uri); startInitSync(uri, resolution); launchPollingThread(resolution.getMountId(), SyncInfo.INVALID_TXID); } catch (Throwable t) { LOG.warn("Recovering from stop syncing failed {}", t); } }
[ "public", "void", "recoverFromStopSync", "(", "AlluxioURI", "uri", ",", "long", "mountId", ")", "{", "if", "(", "mSyncPathStatus", ".", "containsKey", "(", "uri", ")", ")", "{", "// nothing to recover from, since the syncPathStatus still contains syncPoint", "return", "...
Recover from a stop sync operation. @param uri uri to stop sync @param mountId mount id of the uri
[ "Recover", "from", "a", "stop", "sync", "operation", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/activesync/ActiveSyncManager.java#L634-L647
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_service_serviceName_voiceConsumption_consumptionId_GET
public OvhVoiceConsumption billingAccount_service_serviceName_voiceConsumption_consumptionId_GET(String billingAccount, String serviceName, Long consumptionId) throws IOException { String qPath = "/telephony/{billingAccount}/service/{serviceName}/voiceConsumption/{consumptionId}"; StringBuilder sb = path(qPath, billingAccount, serviceName, consumptionId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhVoiceConsumption.class); }
java
public OvhVoiceConsumption billingAccount_service_serviceName_voiceConsumption_consumptionId_GET(String billingAccount, String serviceName, Long consumptionId) throws IOException { String qPath = "/telephony/{billingAccount}/service/{serviceName}/voiceConsumption/{consumptionId}"; StringBuilder sb = path(qPath, billingAccount, serviceName, consumptionId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhVoiceConsumption.class); }
[ "public", "OvhVoiceConsumption", "billingAccount_service_serviceName_voiceConsumption_consumptionId_GET", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "Long", "consumptionId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billi...
Get this object properties REST: GET /telephony/{billingAccount}/service/{serviceName}/voiceConsumption/{consumptionId} @param billingAccount [required] The name of your billingAccount @param serviceName [required] @param consumptionId [required]
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L3745-L3750
protostuff/protostuff
protostuff-api/src/main/java/io/protostuff/UnsignedNumberUtil.java
UnsignedNumberUtil.unsignedLongToString
private static String unsignedLongToString(long x, int radix) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new IllegalArgumentException("Invalid radix: " + radix); } if (x == 0) { // Simply return "0" return "0"; } else { char[] buf = new char[64]; int i = buf.length; if (x < 0) { // Separate off the last digit using unsigned division. That will leave // a number that is nonnegative as a signed integer. long quotient = divide(x, radix); long rem = x - quotient * radix; buf[--i] = Character.forDigit((int) rem, radix); x = quotient; } // Simple modulo/division approach while (x > 0) { buf[--i] = Character.forDigit((int) (x % radix), radix); x /= radix; } // Generate string return new String(buf, i, buf.length - i); } }
java
private static String unsignedLongToString(long x, int radix) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new IllegalArgumentException("Invalid radix: " + radix); } if (x == 0) { // Simply return "0" return "0"; } else { char[] buf = new char[64]; int i = buf.length; if (x < 0) { // Separate off the last digit using unsigned division. That will leave // a number that is nonnegative as a signed integer. long quotient = divide(x, radix); long rem = x - quotient * radix; buf[--i] = Character.forDigit((int) rem, radix); x = quotient; } // Simple modulo/division approach while (x > 0) { buf[--i] = Character.forDigit((int) (x % radix), radix); x /= radix; } // Generate string return new String(buf, i, buf.length - i); } }
[ "private", "static", "String", "unsignedLongToString", "(", "long", "x", ",", "int", "radix", ")", "{", "if", "(", "radix", "<", "Character", ".", "MIN_RADIX", "||", "radix", ">", "Character", ".", "MAX_RADIX", ")", "{", "throw", "new", "IllegalArgumentExcep...
Returns a string representation of {@code x} for the given radix, where {@code x} is treated as unsigned. @param x the value to convert to a string. @param radix the radix to use while working with {@code x} @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}.
[ "Returns", "a", "string", "representation", "of", "{", "@code", "x", "}", "for", "the", "given", "radix", "where", "{", "@code", "x", "}", "is", "treated", "as", "unsigned", "." ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-api/src/main/java/io/protostuff/UnsignedNumberUtil.java#L355-L388
sarl/sarl
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java
SARLQuickfixProvider.fixDuplicateTopElements
@Fix(IssueCodes.DUPLICATE_TYPE_NAME) public void fixDuplicateTopElements(Issue issue, IssueResolutionAcceptor acceptor) { MemberRemoveModification.accept(this, issue, acceptor); }
java
@Fix(IssueCodes.DUPLICATE_TYPE_NAME) public void fixDuplicateTopElements(Issue issue, IssueResolutionAcceptor acceptor) { MemberRemoveModification.accept(this, issue, acceptor); }
[ "@", "Fix", "(", "IssueCodes", ".", "DUPLICATE_TYPE_NAME", ")", "public", "void", "fixDuplicateTopElements", "(", "Issue", "issue", ",", "IssueResolutionAcceptor", "acceptor", ")", "{", "MemberRemoveModification", ".", "accept", "(", "this", ",", "issue", ",", "ac...
Quick fix for "Duplicate type". @param issue the issue. @param acceptor the quick fix acceptor.
[ "Quick", "fix", "for", "Duplicate", "type", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L667-L670
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/security/CryptoPrimitives.java
CryptoPrimitives.addCACertificateToTrustStore
public void addCACertificateToTrustStore(File caCertPem, String alias) throws CryptoException, InvalidArgumentException { if (caCertPem == null) { throw new InvalidArgumentException("The certificate cannot be null"); } if (alias == null || alias.isEmpty()) { throw new InvalidArgumentException("You must assign an alias to a certificate when adding to the trust store"); } try { try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(FileUtils.readFileToByteArray(caCertPem)))) { Certificate caCert = cf.generateCertificate(bis); addCACertificateToTrustStore(caCert, alias); } } catch (CertificateException | IOException e) { throw new CryptoException("Unable to add CA certificate to trust store. Error: " + e.getMessage(), e); } }
java
public void addCACertificateToTrustStore(File caCertPem, String alias) throws CryptoException, InvalidArgumentException { if (caCertPem == null) { throw new InvalidArgumentException("The certificate cannot be null"); } if (alias == null || alias.isEmpty()) { throw new InvalidArgumentException("You must assign an alias to a certificate when adding to the trust store"); } try { try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(FileUtils.readFileToByteArray(caCertPem)))) { Certificate caCert = cf.generateCertificate(bis); addCACertificateToTrustStore(caCert, alias); } } catch (CertificateException | IOException e) { throw new CryptoException("Unable to add CA certificate to trust store. Error: " + e.getMessage(), e); } }
[ "public", "void", "addCACertificateToTrustStore", "(", "File", "caCertPem", ",", "String", "alias", ")", "throws", "CryptoException", ",", "InvalidArgumentException", "{", "if", "(", "caCertPem", "==", "null", ")", "{", "throw", "new", "InvalidArgumentException", "(...
addCACertificateToTrustStore adds a CA cert to the set of certificates used for signature validation @param caCertPem an X.509 certificate in PEM format @param alias an alias associated with the certificate. Used as shorthand for the certificate during crypto operations @throws CryptoException @throws InvalidArgumentException
[ "addCACertificateToTrustStore", "adds", "a", "CA", "cert", "to", "the", "set", "of", "certificates", "used", "for", "signature", "validation" ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/security/CryptoPrimitives.java#L398-L418
operasoftware/operaprestodriver
src/com/opera/core/systems/runner/launcher/OperaLauncherProtocol.java
OperaLauncherProtocol.sendRequest
public ResponseEncapsulation sendRequest(MessageType type, byte[] body) throws IOException { sendRequestHeader(type, (body != null) ? body.length : 0); if (body != null) { os.write(body); } return recvMessage(); }
java
public ResponseEncapsulation sendRequest(MessageType type, byte[] body) throws IOException { sendRequestHeader(type, (body != null) ? body.length : 0); if (body != null) { os.write(body); } return recvMessage(); }
[ "public", "ResponseEncapsulation", "sendRequest", "(", "MessageType", "type", ",", "byte", "[", "]", "body", ")", "throws", "IOException", "{", "sendRequestHeader", "(", "type", ",", "(", "body", "!=", "null", ")", "?", "body", ".", "length", ":", "0", ")"...
Send a request and receive a result. @param type the request type to be sent @param body the serialized request payload @return the response @throws IOException if socket read error or protocol parse error
[ "Send", "a", "request", "and", "receive", "a", "result", "." ]
train
https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/runner/launcher/OperaLauncherProtocol.java#L148-L154
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLGeometry.java
KMLGeometry.toKMLGeometry
public static void toKMLGeometry(Geometry geom, StringBuilder sb) throws SQLException { toKMLGeometry(geom, ExtrudeMode.NONE, AltitudeMode.NONE, sb); }
java
public static void toKMLGeometry(Geometry geom, StringBuilder sb) throws SQLException { toKMLGeometry(geom, ExtrudeMode.NONE, AltitudeMode.NONE, sb); }
[ "public", "static", "void", "toKMLGeometry", "(", "Geometry", "geom", ",", "StringBuilder", "sb", ")", "throws", "SQLException", "{", "toKMLGeometry", "(", "geom", ",", "ExtrudeMode", ".", "NONE", ",", "AltitudeMode", ".", "NONE", ",", "sb", ")", ";", "}" ]
Convert JTS geometry to a kml geometry representation. @param geom @param sb @throws SQLException
[ "Convert", "JTS", "geometry", "to", "a", "kml", "geometry", "representation", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLGeometry.java#L44-L46
pravega/pravega
common/src/main/java/io/pravega/common/util/btree/BTreeIndex.java
BTreeIndex.processModifiedPage
private void processModifiedPage(PageModificationContext context) { PageWrapper page = context.getPageWrapper(); boolean emptyPage = page.getPage().getCount() == 0; ByteArraySegment pageKey = page.getPageKey(); if (emptyPage && page.getParent() != null) { // This page is empty. Remove it from the PageCollection (so we don't write it back to our data source) // and remember its Page Key so we can delete its pointer from its parent page. context.getPageCollection().remove(page); context.setDeletedPageKey(pageKey); } else { // This page needs to be kept around. if (emptyPage && page.getPage().getConfig().isIndexPage()) { // We have an empty Index Root Page. We must convert this to a Leaf Page before moving on. page.setPage(createEmptyLeafPage()); } // Assign a new offset to the page and record its new Page Pointer. context.pageCollection.complete(page); page.setMinOffset(calculateMinOffset(page)); context.updatePagePointer(new PagePointer(pageKey, page.getOffset(), page.getPage().getLength(), page.getMinOffset())); } }
java
private void processModifiedPage(PageModificationContext context) { PageWrapper page = context.getPageWrapper(); boolean emptyPage = page.getPage().getCount() == 0; ByteArraySegment pageKey = page.getPageKey(); if (emptyPage && page.getParent() != null) { // This page is empty. Remove it from the PageCollection (so we don't write it back to our data source) // and remember its Page Key so we can delete its pointer from its parent page. context.getPageCollection().remove(page); context.setDeletedPageKey(pageKey); } else { // This page needs to be kept around. if (emptyPage && page.getPage().getConfig().isIndexPage()) { // We have an empty Index Root Page. We must convert this to a Leaf Page before moving on. page.setPage(createEmptyLeafPage()); } // Assign a new offset to the page and record its new Page Pointer. context.pageCollection.complete(page); page.setMinOffset(calculateMinOffset(page)); context.updatePagePointer(new PagePointer(pageKey, page.getOffset(), page.getPage().getLength(), page.getMinOffset())); } }
[ "private", "void", "processModifiedPage", "(", "PageModificationContext", "context", ")", "{", "PageWrapper", "page", "=", "context", ".", "getPageWrapper", "(", ")", ";", "boolean", "emptyPage", "=", "page", ".", "getPage", "(", ")", ".", "getCount", "(", ")"...
Processes a BTreePage that has been modified (but not split). @param context Processing context.
[ "Processes", "a", "BTreePage", "that", "has", "been", "modified", "(", "but", "not", "split", ")", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/btree/BTreeIndex.java#L507-L528
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Table.java
Table.waitForActive
public TableDescription waitForActive() throws InterruptedException { Waiter waiter = client.waiters().tableExists(); try { waiter.run(new WaiterParameters<DescribeTableRequest>(new DescribeTableRequest(tableName)) .withPollingStrategy(new PollingStrategy(new MaxAttemptsRetryStrategy(25), new FixedDelayStrategy(5)))); return describe(); } catch (Exception exception) { // The additional describe call is to return ResourceNotFoundException if the table doesn't exist. // This is to preserve backwards compatibility. describe(); throw new IllegalArgumentException("Table " + tableName + " did not transition into ACTIVE state.", exception); } }
java
public TableDescription waitForActive() throws InterruptedException { Waiter waiter = client.waiters().tableExists(); try { waiter.run(new WaiterParameters<DescribeTableRequest>(new DescribeTableRequest(tableName)) .withPollingStrategy(new PollingStrategy(new MaxAttemptsRetryStrategy(25), new FixedDelayStrategy(5)))); return describe(); } catch (Exception exception) { // The additional describe call is to return ResourceNotFoundException if the table doesn't exist. // This is to preserve backwards compatibility. describe(); throw new IllegalArgumentException("Table " + tableName + " did not transition into ACTIVE state.", exception); } }
[ "public", "TableDescription", "waitForActive", "(", ")", "throws", "InterruptedException", "{", "Waiter", "waiter", "=", "client", ".", "waiters", "(", ")", ".", "tableExists", "(", ")", ";", "try", "{", "waiter", ".", "run", "(", "new", "WaiterParameters", ...
A convenient blocking call that can be used, typically during table creation, to wait for the table to become active. This method uses {@link com.amazonaws.services.dynamodbv2.waiters.AmazonDynamoDBWaiters} to poll the status of the table every 5 seconds. @return the table description when the table has become active @throws IllegalArgumentException if the table is being deleted @throws ResourceNotFoundException if the table doesn't exist
[ "A", "convenient", "blocking", "call", "that", "can", "be", "used", "typically", "during", "table", "creation", "to", "wait", "for", "the", "table", "to", "become", "active", ".", "This", "method", "uses", "{", "@link", "com", ".", "amazonaws", ".", "servi...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Table.java#L478-L491
OpenLiberty/open-liberty
dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java
SSLUtils.getBufferTraceInfo
public static StringBuilder getBufferTraceInfo(StringBuilder src, WsByteBuffer buffer) { StringBuilder sb = (null == src) ? new StringBuilder(64) : src; if (null == buffer) { return sb.append("null"); } sb.append("hc=").append(buffer.hashCode()); sb.append(" pos=").append(buffer.position()); sb.append(" lim=").append(buffer.limit()); sb.append(" cap=").append(buffer.capacity()); return sb; }
java
public static StringBuilder getBufferTraceInfo(StringBuilder src, WsByteBuffer buffer) { StringBuilder sb = (null == src) ? new StringBuilder(64) : src; if (null == buffer) { return sb.append("null"); } sb.append("hc=").append(buffer.hashCode()); sb.append(" pos=").append(buffer.position()); sb.append(" lim=").append(buffer.limit()); sb.append(" cap=").append(buffer.capacity()); return sb; }
[ "public", "static", "StringBuilder", "getBufferTraceInfo", "(", "StringBuilder", "src", ",", "WsByteBuffer", "buffer", ")", "{", "StringBuilder", "sb", "=", "(", "null", "==", "src", ")", "?", "new", "StringBuilder", "(", "64", ")", ":", "src", ";", "if", ...
This method is called for tracing in various places. It returns a string that represents the buffer including hashcode, position, limit, and capacity. @param src @param buffer buffer to get debug info on @return StringBuilder
[ "This", "method", "is", "called", "for", "tracing", "in", "various", "places", ".", "It", "returns", "a", "string", "that", "represents", "the", "buffer", "including", "hashcode", "position", "limit", "and", "capacity", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java#L470-L480
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/alias/CmsAliasTableController.java
CmsAliasTableController.editAliasMode
public void editAliasMode(CmsAliasTableRow row, CmsAliasMode mode) { row.setMode(mode); row.setEdited(true); }
java
public void editAliasMode(CmsAliasTableRow row, CmsAliasMode mode) { row.setMode(mode); row.setEdited(true); }
[ "public", "void", "editAliasMode", "(", "CmsAliasTableRow", "row", ",", "CmsAliasMode", "mode", ")", "{", "row", ".", "setMode", "(", "mode", ")", ";", "row", ".", "setEdited", "(", "true", ")", ";", "}" ]
This method is called after the mode of an alias has been edited.<p> @param row the edited row @param mode the new alias mode
[ "This", "method", "is", "called", "after", "the", "mode", "of", "an", "alias", "has", "been", "edited", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/alias/CmsAliasTableController.java#L154-L158
jhy/jsoup
src/main/java/org/jsoup/select/Collector.java
Collector.collect
public static Elements collect (Evaluator eval, Element root) { Elements elements = new Elements(); NodeTraversor.traverse(new Accumulator(root, elements, eval), root); return elements; }
java
public static Elements collect (Evaluator eval, Element root) { Elements elements = new Elements(); NodeTraversor.traverse(new Accumulator(root, elements, eval), root); return elements; }
[ "public", "static", "Elements", "collect", "(", "Evaluator", "eval", ",", "Element", "root", ")", "{", "Elements", "elements", "=", "new", "Elements", "(", ")", ";", "NodeTraversor", ".", "traverse", "(", "new", "Accumulator", "(", "root", ",", "elements", ...
Build a list of elements, by visiting root and every descendant of root, and testing it against the evaluator. @param eval Evaluator to test elements against @param root root of tree to descend @return list of matches; empty if none
[ "Build", "a", "list", "of", "elements", "by", "visiting", "root", "and", "every", "descendant", "of", "root", "and", "testing", "it", "against", "the", "evaluator", "." ]
train
https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/select/Collector.java#L25-L29
jbundle/webapp
upload/src/main/java/org/jbundle/util/webapp/upload/UploadServlet.java
UploadServlet.successfulFileUpload
public String successfulFileUpload(File file, Properties properties) { return "<p>Previous upload successful. Path: " + file.getPath() + " Filename: " + file.getName() + " received containing " + file.length() + " bytes</p>" + RETURN; }
java
public String successfulFileUpload(File file, Properties properties) { return "<p>Previous upload successful. Path: " + file.getPath() + " Filename: " + file.getName() + " received containing " + file.length() + " bytes</p>" + RETURN; }
[ "public", "String", "successfulFileUpload", "(", "File", "file", ",", "Properties", "properties", ")", "{", "return", "\"<p>Previous upload successful. Path: \"", "+", "file", ".", "getPath", "(", ")", "+", "\" Filename: \"", "+", "file", ".", "getName", "(", ")",...
/* The file was uploaded successfully, return an HTML string to display. NOTE: This is supplied to provide a convenient place to override this servlet and do some processing or supply a different (or no) return string. Usually, you want to call super to get the standard string. @param properties All the form parameters. @param file The file that was uploaded. @returns HTML String to display.
[ "/", "*", "The", "file", "was", "uploaded", "successfully", "return", "an", "HTML", "string", "to", "display", ".", "NOTE", ":", "This", "is", "supplied", "to", "provide", "a", "convenient", "place", "to", "override", "this", "servlet", "and", "do", "some"...
train
https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/upload/src/main/java/org/jbundle/util/webapp/upload/UploadServlet.java#L217-L220
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomLong
public static long randomLong(long startInclusive, long endExclusive) { checkArgument(startInclusive <= endExclusive, "End must be greater than or equal to start"); if (startInclusive == endExclusive) { return startInclusive; } return RANDOM.longs(1, startInclusive, endExclusive).sum(); }
java
public static long randomLong(long startInclusive, long endExclusive) { checkArgument(startInclusive <= endExclusive, "End must be greater than or equal to start"); if (startInclusive == endExclusive) { return startInclusive; } return RANDOM.longs(1, startInclusive, endExclusive).sum(); }
[ "public", "static", "long", "randomLong", "(", "long", "startInclusive", ",", "long", "endExclusive", ")", "{", "checkArgument", "(", "startInclusive", "<=", "endExclusive", ",", "\"End must be greater than or equal to start\"", ")", ";", "if", "(", "startInclusive", ...
Returns a random long within the specified range. @param startInclusive the earliest long that can be returned @param endExclusive the upper bound (not included) @return the random long @throws IllegalArgumentException if endExclusive is less than startInclusive
[ "Returns", "a", "random", "long", "within", "the", "specified", "range", "." ]
train
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L123-L129
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/VirtualWANsInner.java
VirtualWANsInner.beginDelete
public void beginDelete(String resourceGroupName, String virtualWANName) { beginDeleteWithServiceResponseAsync(resourceGroupName, virtualWANName).toBlocking().single().body(); }
java
public void beginDelete(String resourceGroupName, String virtualWANName) { beginDeleteWithServiceResponseAsync(resourceGroupName, virtualWANName).toBlocking().single().body(); }
[ "public", "void", "beginDelete", "(", "String", "resourceGroupName", ",", "String", "virtualWANName", ")", "{", "beginDeleteWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualWANName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", ...
Deletes a VirtualWAN. @param resourceGroupName The resource group name of the VirtualWan. @param virtualWANName The name of the VirtualWAN being deleted. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Deletes", "a", "VirtualWAN", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/VirtualWANsInner.java#L758-L760
pf4j/pf4j
pf4j/src/main/java/org/pf4j/AbstractExtensionFinder.java
AbstractExtensionFinder.getExtensionInfo
private ExtensionInfo getExtensionInfo(String className, ClassLoader classLoader) { if (extensionInfos == null) { extensionInfos = new HashMap<>(); } if (!extensionInfos.containsKey(className)) { log.trace("Load annotation for '{}' using asm", className); ExtensionInfo info = ExtensionInfo.load(className, classLoader); if (info == null) { log.warn("No extension annotation was found for '{}'", className); extensionInfos.put(className, null); } else { extensionInfos.put(className, info); } } return extensionInfos.get(className); }
java
private ExtensionInfo getExtensionInfo(String className, ClassLoader classLoader) { if (extensionInfos == null) { extensionInfos = new HashMap<>(); } if (!extensionInfos.containsKey(className)) { log.trace("Load annotation for '{}' using asm", className); ExtensionInfo info = ExtensionInfo.load(className, classLoader); if (info == null) { log.warn("No extension annotation was found for '{}'", className); extensionInfos.put(className, null); } else { extensionInfos.put(className, info); } } return extensionInfos.get(className); }
[ "private", "ExtensionInfo", "getExtensionInfo", "(", "String", "className", ",", "ClassLoader", "classLoader", ")", "{", "if", "(", "extensionInfos", "==", "null", ")", "{", "extensionInfos", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "if", "(", "!", ...
Returns the parameters of an {@link Extension} annotation without loading the corresponding class into the class loader. @param className name of the class, that holds the requested {@link Extension} annotation @param classLoader class loader to access the class @return the contents of the {@link Extension} annotation or null, if the class does not have an {@link Extension} annotation
[ "Returns", "the", "parameters", "of", "an", "{", "@link", "Extension", "}", "annotation", "without", "loading", "the", "corresponding", "class", "into", "the", "class", "loader", "." ]
train
https://github.com/pf4j/pf4j/blob/6dd7a6069f0e2fbd842c81e2c8c388918b88ea81/pf4j/src/main/java/org/pf4j/AbstractExtensionFinder.java#L323-L340
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/cpc/CpcCompression.java
CpcCompression.compressSlidingFlavor
private static void compressSlidingFlavor(final CompressedState target, final CpcSketch source) { compressTheWindow(target, source); final PairTable srcPairTable = source.pairTable; final int numPairs = srcPairTable.getNumPairs(); if (numPairs > 0) { final int[] pairs = PairTable.unwrappingGetItems(srcPairTable, numPairs); // Here we apply a complicated transformation to the column indices, which // changes the implied ordering of the pairs, so we must do it before sorting. final int pseudoPhase = determinePseudoPhase(source.lgK, source.numCoupons); // NB assert (pseudoPhase < 16); final byte[] permutation = columnPermutationsForEncoding[pseudoPhase]; final int offset = source.windowOffset; assert ((offset > 0) && (offset <= 56)); for (int i = 0; i < numPairs; i++) { final int rowCol = pairs[i]; final int row = rowCol >>> 6; int col = (rowCol & 63); // first rotate the columns into a canonical configuration: // new = ((old - (offset+8)) + 64) mod 64 col = ((col + 56) - offset) & 63; assert (col >= 0) && (col < 56); // then apply the permutation col = permutation[col]; pairs[i] = (row << 6) | col; } introspectiveInsertionSort(pairs, 0, numPairs - 1); compressTheSurprisingValues(target, source, pairs, numPairs); } }
java
private static void compressSlidingFlavor(final CompressedState target, final CpcSketch source) { compressTheWindow(target, source); final PairTable srcPairTable = source.pairTable; final int numPairs = srcPairTable.getNumPairs(); if (numPairs > 0) { final int[] pairs = PairTable.unwrappingGetItems(srcPairTable, numPairs); // Here we apply a complicated transformation to the column indices, which // changes the implied ordering of the pairs, so we must do it before sorting. final int pseudoPhase = determinePseudoPhase(source.lgK, source.numCoupons); // NB assert (pseudoPhase < 16); final byte[] permutation = columnPermutationsForEncoding[pseudoPhase]; final int offset = source.windowOffset; assert ((offset > 0) && (offset <= 56)); for (int i = 0; i < numPairs; i++) { final int rowCol = pairs[i]; final int row = rowCol >>> 6; int col = (rowCol & 63); // first rotate the columns into a canonical configuration: // new = ((old - (offset+8)) + 64) mod 64 col = ((col + 56) - offset) & 63; assert (col >= 0) && (col < 56); // then apply the permutation col = permutation[col]; pairs[i] = (row << 6) | col; } introspectiveInsertionSort(pairs, 0, numPairs - 1); compressTheSurprisingValues(target, source, pairs, numPairs); } }
[ "private", "static", "void", "compressSlidingFlavor", "(", "final", "CompressedState", "target", ",", "final", "CpcSketch", "source", ")", "{", "compressTheWindow", "(", "target", ",", "source", ")", ";", "final", "PairTable", "srcPairTable", "=", "source", ".", ...
Complicated by the existence of both a left fringe and a right fringe.
[ "Complicated", "by", "the", "existence", "of", "both", "a", "left", "fringe", "and", "a", "right", "fringe", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcCompression.java#L673-L709
aol/cyclops
cyclops-futurestream/src/main/java/com/oath/cyclops/types/futurestream/EagerFutureStreamFunctions.java
EagerFutureStreamFunctions.closeOthers
static void closeOthers(final Queue active, final List<Queue> all) { all.stream() .filter(next -> next != active) .forEach(Queue::closeAndClear); }
java
static void closeOthers(final Queue active, final List<Queue> all) { all.stream() .filter(next -> next != active) .forEach(Queue::closeAndClear); }
[ "static", "void", "closeOthers", "(", "final", "Queue", "active", ",", "final", "List", "<", "Queue", ">", "all", ")", "{", "all", ".", "stream", "(", ")", ".", "filter", "(", "next", "->", "next", "!=", "active", ")", ".", "forEach", "(", "Queue", ...
Close all queues except the active one @param active Queue not to close @param all All queues potentially including the active queue
[ "Close", "all", "queues", "except", "the", "active", "one" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops-futurestream/src/main/java/com/oath/cyclops/types/futurestream/EagerFutureStreamFunctions.java#L24-L29
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/JobConfigurationUtils.java
JobConfigurationUtils.putStateIntoConfiguration
public static void putStateIntoConfiguration(State state, Configuration configuration) { for (String key : state.getPropertyNames()) { configuration.set(key, state.getProp(key)); } }
java
public static void putStateIntoConfiguration(State state, Configuration configuration) { for (String key : state.getPropertyNames()) { configuration.set(key, state.getProp(key)); } }
[ "public", "static", "void", "putStateIntoConfiguration", "(", "State", "state", ",", "Configuration", "configuration", ")", "{", "for", "(", "String", "key", ":", "state", ".", "getPropertyNames", "(", ")", ")", "{", "configuration", ".", "set", "(", "key", ...
Put all configuration properties in a given {@link State} object into a given {@link Configuration} object. @param state the given {@link State} object @param configuration the given {@link Configuration} object
[ "Put", "all", "configuration", "properties", "in", "a", "given", "{", "@link", "State", "}", "object", "into", "a", "given", "{", "@link", "Configuration", "}", "object", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JobConfigurationUtils.java#L93-L97
bullhorn/sdk-rest
src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java
StandardBullhornData.handleGetEntity
protected <T extends BullhornEntity> T handleGetEntity(Class<T> type, Integer id, Set<String> fieldSet, EntityParams params) { Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForEntity(BullhornEntityInfo.getTypesRestEntityName(type), id, fieldSet, params); String url = restUrlFactory.assembleEntityUrl(params); String jsonString = this.performGetRequest(url, String.class, uriVariables); return restJsonConverter.jsonToEntityUnwrapRoot(jsonString, type); }
java
protected <T extends BullhornEntity> T handleGetEntity(Class<T> type, Integer id, Set<String> fieldSet, EntityParams params) { Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForEntity(BullhornEntityInfo.getTypesRestEntityName(type), id, fieldSet, params); String url = restUrlFactory.assembleEntityUrl(params); String jsonString = this.performGetRequest(url, String.class, uriVariables); return restJsonConverter.jsonToEntityUnwrapRoot(jsonString, type); }
[ "protected", "<", "T", "extends", "BullhornEntity", ">", "T", "handleGetEntity", "(", "Class", "<", "T", ">", "type", ",", "Integer", "id", ",", "Set", "<", "String", ">", "fieldSet", ",", "EntityParams", "params", ")", "{", "Map", "<", "String", ",", ...
Makes the "entity" api call for getting entities. <p> <p> HTTP Method: GET @param type @param id @param fieldSet @param params optional entity parameters @return
[ "Makes", "the", "entity", "api", "call", "for", "getting", "entities", ".", "<p", ">", "<p", ">", "HTTP", "Method", ":", "GET" ]
train
https://github.com/bullhorn/sdk-rest/blob/0c75a141c768bb31510afc3a412c11bd101eca06/src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java#L857-L865
alibaba/vlayout
vlayout/src/main/java/com/alibaba/android/vlayout/layout/BaseLayoutHelper.java
BaseLayoutHelper.nextView
@Nullable public final View nextView(RecyclerView.Recycler recycler, LayoutStateWrapper layoutState, LayoutManagerHelper helper, LayoutChunkResult result) { View view = layoutState.next(recycler); if (view == null) { // if we are laying out views in scrap, this may return null which means there is // no more items to layout. if (DEBUG && !layoutState.hasScrapList()) { throw new RuntimeException("received null view when unexpected"); } // if there is no more views can be retrieved, this layout process is finished result.mFinished = true; return null; } helper.addChildView(layoutState, view); return view; }
java
@Nullable public final View nextView(RecyclerView.Recycler recycler, LayoutStateWrapper layoutState, LayoutManagerHelper helper, LayoutChunkResult result) { View view = layoutState.next(recycler); if (view == null) { // if we are laying out views in scrap, this may return null which means there is // no more items to layout. if (DEBUG && !layoutState.hasScrapList()) { throw new RuntimeException("received null view when unexpected"); } // if there is no more views can be retrieved, this layout process is finished result.mFinished = true; return null; } helper.addChildView(layoutState, view); return view; }
[ "@", "Nullable", "public", "final", "View", "nextView", "(", "RecyclerView", ".", "Recycler", "recycler", ",", "LayoutStateWrapper", "layoutState", ",", "LayoutManagerHelper", "helper", ",", "LayoutChunkResult", "result", ")", "{", "View", "view", "=", "layoutState"...
Retrieve next view and add it into layout, this is to make sure that view are added by order @param recycler recycler generate views @param layoutState current layout state @param helper helper to add views @param result chunk result to tell layoutManager whether layout process goes end @return next view to render, null if no more view available
[ "Retrieve", "next", "view", "and", "add", "it", "into", "layout", "this", "is", "to", "make", "sure", "that", "view", "are", "added", "by", "order" ]
train
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/layout/BaseLayoutHelper.java#L114-L130
aws/aws-sdk-java
aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/model/SetEndpointAttributesRequest.java
SetEndpointAttributesRequest.withAttributes
public SetEndpointAttributesRequest withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
java
public SetEndpointAttributesRequest withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
[ "public", "SetEndpointAttributesRequest", "withAttributes", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "attributes", ")", "{", "setAttributes", "(", "attributes", ")", ";", "return", "this", ";", "}" ]
<p> A map of the endpoint attributes. Attributes in this map include the following: </p> <ul> <li> <p> <code>CustomUserData</code> – arbitrary user data to associate with the endpoint. Amazon SNS does not use this data. The data must be in UTF-8 format and less than 2KB. </p> </li> <li> <p> <code>Enabled</code> – flag that enables/disables delivery to the endpoint. Amazon SNS will set this to false when a notification service indicates to Amazon SNS that the endpoint is invalid. Users can set it back to true, typically after updating Token. </p> </li> <li> <p> <code>Token</code> – device token, also referred to as a registration id, for an app and mobile device. This is returned from the notification service when an app and mobile device are registered with the notification service. </p> </li> </ul> @param attributes A map of the endpoint attributes. Attributes in this map include the following:</p> <ul> <li> <p> <code>CustomUserData</code> – arbitrary user data to associate with the endpoint. Amazon SNS does not use this data. The data must be in UTF-8 format and less than 2KB. </p> </li> <li> <p> <code>Enabled</code> – flag that enables/disables delivery to the endpoint. Amazon SNS will set this to false when a notification service indicates to Amazon SNS that the endpoint is invalid. Users can set it back to true, typically after updating Token. </p> </li> <li> <p> <code>Token</code> – device token, also referred to as a registration id, for an app and mobile device. This is returned from the notification service when an app and mobile device are registered with the notification service. </p> </li> @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "of", "the", "endpoint", "attributes", ".", "Attributes", "in", "this", "map", "include", "the", "following", ":", "<", "/", "p", ">", "<ul", ">", "<li", ">", "<p", ">", "<code", ">", "CustomUserData<", "/", "code", ">", "–", ...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/model/SetEndpointAttributesRequest.java#L273-L276
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChannelDataImpl.java
ChannelDataImpl.createChild
public ChildChannelDataImpl createChild() { String childName = this.name + CHILD_STRING + nextChildId(); ChildChannelDataImpl child = new ChildChannelDataImpl(childName, this); this.children.add(child); return child; }
java
public ChildChannelDataImpl createChild() { String childName = this.name + CHILD_STRING + nextChildId(); ChildChannelDataImpl child = new ChildChannelDataImpl(childName, this); this.children.add(child); return child; }
[ "public", "ChildChannelDataImpl", "createChild", "(", ")", "{", "String", "childName", "=", "this", ".", "name", "+", "CHILD_STRING", "+", "nextChildId", "(", ")", ";", "ChildChannelDataImpl", "child", "=", "new", "ChildChannelDataImpl", "(", "childName", ",", "...
Create a child data object. Add it to the list of children and return it. @return child channel data object
[ "Create", "a", "child", "data", "object", ".", "Add", "it", "to", "the", "list", "of", "children", "and", "return", "it", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChannelDataImpl.java#L229-L234
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java
JDBC4CallableStatement.setClob
@Override public void setClob(String parameterName, Clob x) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
java
@Override public void setClob(String parameterName, Clob x) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
[ "@", "Override", "public", "void", "setClob", "(", "String", "parameterName", ",", "Clob", "x", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Sets the designated parameter to the given java.sql.Clob object.
[ "Sets", "the", "designated", "parameter", "to", "the", "given", "java", ".", "sql", ".", "Clob", "object", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java#L695-L700
apache/incubator-gobblin
gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/lineage/LineageInfo.java
LineageInfo.putDestination
@Deprecated public void putDestination(Descriptor destination, int branchId, State state) { putDestination(Lists.newArrayList(destination), branchId, state); }
java
@Deprecated public void putDestination(Descriptor destination, int branchId, State state) { putDestination(Lists.newArrayList(destination), branchId, state); }
[ "@", "Deprecated", "public", "void", "putDestination", "(", "Descriptor", "destination", ",", "int", "branchId", ",", "State", "state", ")", "{", "putDestination", "(", "Lists", ".", "newArrayList", "(", "destination", ")", ",", "branchId", ",", "state", ")", ...
Put a {@link DatasetDescriptor} of a destination dataset to a state <p> Only the {@link org.apache.gobblin.writer.DataWriter} or {@link org.apache.gobblin.publisher.DataPublisher} is supposed to put the destination dataset information. Since different branches may concurrently put, the method is implemented to be threadsafe </p> @deprecated Use {@link #putDestination(List, int, State)}
[ "Put", "a", "{", "@link", "DatasetDescriptor", "}", "of", "a", "destination", "dataset", "to", "a", "state" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/lineage/LineageInfo.java#L133-L136
headius/invokebinder
src/main/java/com/headius/invokebinder/Binder.java
Binder.foldStatic
public Binder foldStatic(Class<?> target, String method) { return foldStatic(lookup, target, method); }
java
public Binder foldStatic(Class<?> target, String method) { return foldStatic(lookup, target, method); }
[ "public", "Binder", "foldStatic", "(", "Class", "<", "?", ">", "target", ",", "String", "method", ")", "{", "return", "foldStatic", "(", "lookup", ",", "target", ",", "method", ")", ";", "}" ]
Process the incoming arguments by calling the given static method on the given class, inserting the result as the first argument. @param target the class on which the method is defined @param method the method to invoke on the first argument @return a new Binder
[ "Process", "the", "incoming", "arguments", "by", "calling", "the", "given", "static", "method", "on", "the", "given", "class", "inserting", "the", "result", "as", "the", "first", "argument", "." ]
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Binder.java#L968-L970
Azure/azure-sdk-for-java
locks/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/locks/v2016_09_01/implementation/ManagementLocksInner.java
ManagementLocksInner.listByResourceGroupAsync
public Observable<Page<ManagementLockObjectInner>> listByResourceGroupAsync(final String resourceGroupName, final String filter) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName, filter) .map(new Func1<ServiceResponse<Page<ManagementLockObjectInner>>, Page<ManagementLockObjectInner>>() { @Override public Page<ManagementLockObjectInner> call(ServiceResponse<Page<ManagementLockObjectInner>> response) { return response.body(); } }); }
java
public Observable<Page<ManagementLockObjectInner>> listByResourceGroupAsync(final String resourceGroupName, final String filter) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName, filter) .map(new Func1<ServiceResponse<Page<ManagementLockObjectInner>>, Page<ManagementLockObjectInner>>() { @Override public Page<ManagementLockObjectInner> call(ServiceResponse<Page<ManagementLockObjectInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ManagementLockObjectInner", ">", ">", "listByResourceGroupAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "filter", ")", "{", "return", "listByResourceGroupWithServiceResponseAsync", "(", "resourceGro...
Gets all the management locks for a resource group. @param resourceGroupName The name of the resource group containing the locks to get. @param filter The filter to apply on the operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ManagementLockObjectInner&gt; object
[ "Gets", "all", "the", "management", "locks", "for", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/locks/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/locks/v2016_09_01/implementation/ManagementLocksInner.java#L1444-L1452
alipay/sofa-rpc
extension-impl/remoting-bolt/src/main/java/com/alipay/sofa/rpc/transport/bolt/BoltClientTransport.java
BoltClientTransport.doInvokeAsync
protected ResponseFuture doInvokeAsync(SofaRequest request, RpcInternalContext rpcContext, InvokeContext invokeContext, int timeoutMillis) throws RemotingException, InterruptedException { SofaResponseCallback listener = request.getSofaResponseCallback(); if (listener != null) { // callback调用 InvokeCallback callback = new BoltInvokerCallback(transportConfig.getConsumerConfig(), transportConfig.getProviderInfo(), listener, request, rpcContext, ClassLoaderUtils.getCurrentClassLoader()); // 发起调用 RPC_CLIENT.invokeWithCallback(url, request, invokeContext, callback, timeoutMillis); return null; } else { // future 转为 callback BoltResponseFuture future = new BoltResponseFuture(request, timeoutMillis); InvokeCallback callback = new BoltFutureInvokeCallback(transportConfig.getConsumerConfig(), transportConfig.getProviderInfo(), future, request, rpcContext, ClassLoaderUtils.getCurrentClassLoader()); // 发起调用 RPC_CLIENT.invokeWithCallback(url, request, invokeContext, callback, timeoutMillis); future.setSentTime(); return future; } }
java
protected ResponseFuture doInvokeAsync(SofaRequest request, RpcInternalContext rpcContext, InvokeContext invokeContext, int timeoutMillis) throws RemotingException, InterruptedException { SofaResponseCallback listener = request.getSofaResponseCallback(); if (listener != null) { // callback调用 InvokeCallback callback = new BoltInvokerCallback(transportConfig.getConsumerConfig(), transportConfig.getProviderInfo(), listener, request, rpcContext, ClassLoaderUtils.getCurrentClassLoader()); // 发起调用 RPC_CLIENT.invokeWithCallback(url, request, invokeContext, callback, timeoutMillis); return null; } else { // future 转为 callback BoltResponseFuture future = new BoltResponseFuture(request, timeoutMillis); InvokeCallback callback = new BoltFutureInvokeCallback(transportConfig.getConsumerConfig(), transportConfig.getProviderInfo(), future, request, rpcContext, ClassLoaderUtils.getCurrentClassLoader()); // 发起调用 RPC_CLIENT.invokeWithCallback(url, request, invokeContext, callback, timeoutMillis); future.setSentTime(); return future; } }
[ "protected", "ResponseFuture", "doInvokeAsync", "(", "SofaRequest", "request", ",", "RpcInternalContext", "rpcContext", ",", "InvokeContext", "invokeContext", ",", "int", "timeoutMillis", ")", "throws", "RemotingException", ",", "InterruptedException", "{", "SofaResponseCal...
异步调用 @param request 请求对象 @param rpcContext RPC内置上下文 @param invokeContext 调用上下文 @param timeoutMillis 超时时间(毫秒) @throws RemotingException 远程调用异常 @throws InterruptedException 中断异常 @since 5.2.0
[ "异步调用" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/remoting-bolt/src/main/java/com/alipay/sofa/rpc/transport/bolt/BoltClientTransport.java#L214-L237
classgraph/classgraph
src/main/java/nonapi/io/github/classgraph/utils/CollectionUtils.java
CollectionUtils.sortIfNotEmpty
public static <T> void sortIfNotEmpty(final List<T> list, final Comparator<? super T> comparator) { if (!list.isEmpty()) { Collections.sort(list, comparator); } }
java
public static <T> void sortIfNotEmpty(final List<T> list, final Comparator<? super T> comparator) { if (!list.isEmpty()) { Collections.sort(list, comparator); } }
[ "public", "static", "<", "T", ">", "void", "sortIfNotEmpty", "(", "final", "List", "<", "T", ">", "list", ",", "final", "Comparator", "<", "?", "super", "T", ">", "comparator", ")", "{", "if", "(", "!", "list", ".", "isEmpty", "(", ")", ")", "{", ...
Sort a collection if it is not empty (to prevent {@link ConcurrentModificationException} if an immutable empty list that has been returned more than once is being sorted in one thread and iterated through in another thread -- #334). @param <T> the element type @param list the list
[ "Sort", "a", "collection", "if", "it", "is", "not", "empty", "(", "to", "prevent", "{", "@link", "ConcurrentModificationException", "}", "if", "an", "immutable", "empty", "list", "that", "has", "been", "returned", "more", "than", "once", "is", "being", "sort...
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/utils/CollectionUtils.java#L71-L75
rahulsom/genealogy
src/main/java/com/github/rahulsom/genealogy/NameDbUsa.java
NameDbUsa.getName
private String getName(List<? extends Name> list, double probability) { Name name = getNameObject(list, probability * getMax(list)); return name.getValue(); }
java
private String getName(List<? extends Name> list, double probability) { Name name = getNameObject(list, probability * getMax(list)); return name.getValue(); }
[ "private", "String", "getName", "(", "List", "<", "?", "extends", "Name", ">", "list", ",", "double", "probability", ")", "{", "Name", "name", "=", "getNameObject", "(", "list", ",", "probability", "*", "getMax", "(", "list", ")", ")", ";", "return", "...
Finds name at a given cumulative probability accounting for gaps. @param list The list to look for name in @param probability the cumulative probability to search for (between 0 and 1) @return the name
[ "Finds", "name", "at", "a", "given", "cumulative", "probability", "accounting", "for", "gaps", "." ]
train
https://github.com/rahulsom/genealogy/blob/2beb35ab9c6e03080328aa08b18f0a3c5d3f5c12/src/main/java/com/github/rahulsom/genealogy/NameDbUsa.java#L82-L85
Bernardo-MG/maven-site-fixer
src/main/java/com/bernardomg/velocity/tool/HtmlTool.java
HtmlTool.removeAttribute
public final void removeAttribute(final Element root, final String selector, final String attribute) { final Iterable<Element> elements; // Elements selected checkNotNull(root, "Received a null pointer as root element"); checkNotNull(selector, "Received a null pointer as selector"); checkNotNull(attribute, "Received a null pointer as attribute"); // Selects and iterates over the elements elements = root.select(selector); for (final Element element : elements) { element.removeAttr(attribute); } }
java
public final void removeAttribute(final Element root, final String selector, final String attribute) { final Iterable<Element> elements; // Elements selected checkNotNull(root, "Received a null pointer as root element"); checkNotNull(selector, "Received a null pointer as selector"); checkNotNull(attribute, "Received a null pointer as attribute"); // Selects and iterates over the elements elements = root.select(selector); for (final Element element : elements) { element.removeAttr(attribute); } }
[ "public", "final", "void", "removeAttribute", "(", "final", "Element", "root", ",", "final", "String", "selector", ",", "final", "String", "attribute", ")", "{", "final", "Iterable", "<", "Element", ">", "elements", ";", "// Elements selected", "checkNotNull", "...
Finds a set of elements through a CSS selector and removes the received attribute from them, if they have it. @param root root element for the selection @param selector CSS selector for the elements with the attribute to remove @param attribute attribute to remove
[ "Finds", "a", "set", "of", "elements", "through", "a", "CSS", "selector", "and", "removes", "the", "received", "attribute", "from", "them", "if", "they", "have", "it", "." ]
train
https://github.com/Bernardo-MG/maven-site-fixer/blob/e064472faa7edb0fca11647a22d90ad72089baa3/src/main/java/com/bernardomg/velocity/tool/HtmlTool.java#L84-L97
MenoData/Time4J
base/src/main/java/net/time4j/history/EraPreference.java
EraPreference.hispanicBetween
public static EraPreference hispanicBetween( PlainDate start, PlainDate end ) { return new EraPreference(HistoricEra.HISPANIC, start, end); }
java
public static EraPreference hispanicBetween( PlainDate start, PlainDate end ) { return new EraPreference(HistoricEra.HISPANIC, start, end); }
[ "public", "static", "EraPreference", "hispanicBetween", "(", "PlainDate", "start", ",", "PlainDate", "end", ")", "{", "return", "new", "EraPreference", "(", "HistoricEra", ".", "HISPANIC", ",", "start", ",", "end", ")", ";", "}" ]
/*[deutsch] <p>Legt fest, da&szlig; die spanische &Auml;ra innerhalb der angegebenen Datumsspanne bevorzugt wird. </p> @param start first date when the hispanic era shall be used (inclusive) @param end last date when the hispanic era shall be used (inclusive) @return EraPreference @see HistoricEra#HISPANIC @since 3.14/4.11
[ "/", "*", "[", "deutsch", "]", "<p", ">", "Legt", "fest", "da&szlig", ";", "die", "spanische", "&Auml", ";", "ra", "innerhalb", "der", "angegebenen", "Datumsspanne", "bevorzugt", "wird", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/history/EraPreference.java#L135-L142
rnorth/visible-assertions
src/main/java/org/rnorth/visibleassertions/VisibleAssertions.java
VisibleAssertions.assertFalse
public static void assertFalse(String message, boolean value) { if (!value) { pass(message); } else { fail(message, null); } }
java
public static void assertFalse(String message, boolean value) { if (!value) { pass(message); } else { fail(message, null); } }
[ "public", "static", "void", "assertFalse", "(", "String", "message", ",", "boolean", "value", ")", "{", "if", "(", "!", "value", ")", "{", "pass", "(", "message", ")", ";", "}", "else", "{", "fail", "(", "message", ",", "null", ")", ";", "}", "}" ]
Assert that a value is false. <p> If the assertion passes, a green tick will be shown. If the assertion fails, a red cross will be shown. @param message message to display alongside the assertion outcome @param value value to test
[ "Assert", "that", "a", "value", "is", "false", ".", "<p", ">", "If", "the", "assertion", "passes", "a", "green", "tick", "will", "be", "shown", ".", "If", "the", "assertion", "fails", "a", "red", "cross", "will", "be", "shown", "." ]
train
https://github.com/rnorth/visible-assertions/blob/6d7a7724db40ac0e9f87279553f814b790310b3b/src/main/java/org/rnorth/visibleassertions/VisibleAssertions.java#L141-L147
apache/incubator-gobblin
gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java
State.getPropAsShort
public short getPropAsShort(String key, short def) { return Short.parseShort(getProp(key, String.valueOf(def))); }
java
public short getPropAsShort(String key, short def) { return Short.parseShort(getProp(key, String.valueOf(def))); }
[ "public", "short", "getPropAsShort", "(", "String", "key", ",", "short", "def", ")", "{", "return", "Short", ".", "parseShort", "(", "getProp", "(", "key", ",", "String", ".", "valueOf", "(", "def", ")", ")", ")", ";", "}" ]
Get the value of a property as an short, using the given default value if the property is not set. @param key property key @param def default value @return short value associated with the key or the default value if the property is not set
[ "Get", "the", "value", "of", "a", "property", "as", "an", "short", "using", "the", "given", "default", "value", "if", "the", "property", "is", "not", "set", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L416-L418
icode/ameba
src/main/java/ameba/message/internal/BeanPathProperties.java
BeanPathProperties.addToPath
public void addToPath(String path, String property) { Props props = pathMap.computeIfAbsent(path, k -> new Props(this, null, path)); props.getProperties().add(property); }
java
public void addToPath(String path, String property) { Props props = pathMap.computeIfAbsent(path, k -> new Props(this, null, path)); props.getProperties().add(property); }
[ "public", "void", "addToPath", "(", "String", "path", ",", "String", "property", ")", "{", "Props", "props", "=", "pathMap", ".", "computeIfAbsent", "(", "path", ",", "k", "->", "new", "Props", "(", "this", ",", "null", ",", "path", ")", ")", ";", "p...
<p>addToPath.</p> @param path a {@link java.lang.String} object. @param property a {@link java.lang.String} object.
[ "<p", ">", "addToPath", ".", "<", "/", "p", ">" ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/message/internal/BeanPathProperties.java#L119-L122
codeprimate-software/cp-elements
src/main/java/org/cp/elements/data/struct/SimpleBloomFilter.java
SimpleBloomFilter.computeOptimalNumberOfHashFunctions
protected static int computeOptimalNumberOfHashFunctions(double approximateNumberOfElements, double requiredNumberOfBits) { double numberOfHashFunctions = (requiredNumberOfBits / approximateNumberOfElements) * Math.log(2.0d); return Double.valueOf(Math.ceil(numberOfHashFunctions)).intValue(); }
java
protected static int computeOptimalNumberOfHashFunctions(double approximateNumberOfElements, double requiredNumberOfBits) { double numberOfHashFunctions = (requiredNumberOfBits / approximateNumberOfElements) * Math.log(2.0d); return Double.valueOf(Math.ceil(numberOfHashFunctions)).intValue(); }
[ "protected", "static", "int", "computeOptimalNumberOfHashFunctions", "(", "double", "approximateNumberOfElements", ",", "double", "requiredNumberOfBits", ")", "{", "double", "numberOfHashFunctions", "=", "(", "requiredNumberOfBits", "/", "approximateNumberOfElements", ")", "*...
Computes the optimal number of hash functions to apply to each element added to the Bloom Filter as a factor of the approximate (estimated) number of elements that will be added to the filter along with the required number of bits needed by the filter, which was computed from the probability of false positives. k = m/n * log 2 m is the required number of bits needed for the bloom filter n is the approximate number of elements to be added to the bloom filter k is the optimal number of hash functions to apply to the element added to the bloom filter @param approximateNumberOfElements integer value indicating the approximate, estimated number of elements the user expects will be added to the Bloom Filter. @param requiredNumberOfBits the required number of bits needed by the Bloom Filter to satify the probability of false positives. @return the optimal number of hash functions used by the Bloom Filter.
[ "Computes", "the", "optimal", "number", "of", "hash", "functions", "to", "apply", "to", "each", "element", "added", "to", "the", "Bloom", "Filter", "as", "a", "factor", "of", "the", "approximate", "(", "estimated", ")", "number", "of", "elements", "that", ...
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/data/struct/SimpleBloomFilter.java#L210-L215
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/auth/OAuthActivity.java
OAuthActivity.createOAuthActivityIntent
public static Intent createOAuthActivityIntent(final Context context, BoxSession session, boolean loginViaBoxApp){ Intent intent = createOAuthActivityIntent(context, session.getClientId(), session.getClientSecret(), session.getRedirectUrl(), loginViaBoxApp); intent.putExtra(EXTRA_SESSION, session); if (!SdkUtils.isEmptyString(session.getUserId())) { intent.putExtra(EXTRA_USER_ID_RESTRICTION, session.getUserId()); } return intent; }
java
public static Intent createOAuthActivityIntent(final Context context, BoxSession session, boolean loginViaBoxApp){ Intent intent = createOAuthActivityIntent(context, session.getClientId(), session.getClientSecret(), session.getRedirectUrl(), loginViaBoxApp); intent.putExtra(EXTRA_SESSION, session); if (!SdkUtils.isEmptyString(session.getUserId())) { intent.putExtra(EXTRA_USER_ID_RESTRICTION, session.getUserId()); } return intent; }
[ "public", "static", "Intent", "createOAuthActivityIntent", "(", "final", "Context", "context", ",", "BoxSession", "session", ",", "boolean", "loginViaBoxApp", ")", "{", "Intent", "intent", "=", "createOAuthActivityIntent", "(", "context", ",", "session", ".", "getCl...
Create intent to launch OAuthActivity using information from the given session. @param context context @param session the BoxSession to use to get parameters required to authenticate via this activity. @param loginViaBoxApp Whether login should be handled by the installed box android app. Set this to true only when you are sure or want to make sure user installed box android app and want to use box android app to login. @return intent to launch OAuthActivity.
[ "Create", "intent", "to", "launch", "OAuthActivity", "using", "information", "from", "the", "given", "session", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/auth/OAuthActivity.java#L539-L546
Jasig/uPortal
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/EditManager.java
EditManager.removeEditDirective
public static void removeEditDirective(String elementId, String attributeName, IPerson person) { removeDirective(elementId, attributeName, Constants.ELM_EDIT, person); }
java
public static void removeEditDirective(String elementId, String attributeName, IPerson person) { removeDirective(elementId, attributeName, Constants.ELM_EDIT, person); }
[ "public", "static", "void", "removeEditDirective", "(", "String", "elementId", ",", "String", "attributeName", ",", "IPerson", "person", ")", "{", "removeDirective", "(", "elementId", ",", "attributeName", ",", "Constants", ".", "ELM_EDIT", ",", "person", ")", "...
Searches for a dlm:edit command which indicates that a node attribute was reset to the value in the fragment and if found removes it from the user's PLF.
[ "Searches", "for", "a", "dlm", ":", "edit", "command", "which", "indicates", "that", "a", "node", "attribute", "was", "reset", "to", "the", "value", "in", "the", "fragment", "and", "if", "found", "removes", "it", "from", "the", "user", "s", "PLF", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/EditManager.java#L227-L229
xdcrafts/flower
flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapApi.java
MapApi.getOptional
public static <T> Optional<Optional<T>> getOptional(final Map map, final Class<T> clazz, final Object... path) { return get(map, Optional.class, path).map(opt -> (Optional<T>) opt); }
java
public static <T> Optional<Optional<T>> getOptional(final Map map, final Class<T> clazz, final Object... path) { return get(map, Optional.class, path).map(opt -> (Optional<T>) opt); }
[ "public", "static", "<", "T", ">", "Optional", "<", "Optional", "<", "T", ">", ">", "getOptional", "(", "final", "Map", "map", ",", "final", "Class", "<", "T", ">", "clazz", ",", "final", "Object", "...", "path", ")", "{", "return", "get", "(", "ma...
Get optional value by path. @param <T> optional value type @param clazz type of value @param map subject @param path nodes to walk in map @return value
[ "Get", "optional", "value", "by", "path", "." ]
train
https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapApi.java#L271-L273
JDBDT/jdbdt
src/main/java/org/jdbdt/JDBDT.java
JDBDT.assertTableExists
public static void assertTableExists(DB db, String tableName) throws DBAssertionError { DBAssert.assertTableExistence(CallInfo.create(), db, tableName, true); }
java
public static void assertTableExists(DB db, String tableName) throws DBAssertionError { DBAssert.assertTableExistence(CallInfo.create(), db, tableName, true); }
[ "public", "static", "void", "assertTableExists", "(", "DB", "db", ",", "String", "tableName", ")", "throws", "DBAssertionError", "{", "DBAssert", ".", "assertTableExistence", "(", "CallInfo", ".", "create", "(", ")", ",", "db", ",", "tableName", ",", "true", ...
Assert that table exists in the database. @param db Database. @param tableName Table name. @throws DBAssertionError If the assertion fails. @see #assertTableDoesNotExist(DB, String) @see #drop(Table)
[ "Assert", "that", "table", "exists", "in", "the", "database", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L739-L741