repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.getTag
public Tag getTag(UUID projectId, UUID tagId, GetTagOptionalParameter getTagOptionalParameter) { return getTagWithServiceResponseAsync(projectId, tagId, getTagOptionalParameter).toBlocking().single().body(); }
java
public Tag getTag(UUID projectId, UUID tagId, GetTagOptionalParameter getTagOptionalParameter) { return getTagWithServiceResponseAsync(projectId, tagId, getTagOptionalParameter).toBlocking().single().body(); }
[ "public", "Tag", "getTag", "(", "UUID", "projectId", ",", "UUID", "tagId", ",", "GetTagOptionalParameter", "getTagOptionalParameter", ")", "{", "return", "getTagWithServiceResponseAsync", "(", "projectId", ",", "tagId", ",", "getTagOptionalParameter", ")", ".", "toBlo...
Get information about a specific tag. @param projectId The project this tag belongs to @param tagId The tag id @param getTagOptionalParameter the object representing the optional parameters to be set before calling this API @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 @return the Tag object if successful.
[ "Get", "information", "about", "a", "specific", "tag", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L777-L779
janus-project/guava.janusproject.io
guava/src/com/google/common/util/concurrent/Uninterruptibles.java
Uninterruptibles.putUninterruptibly
public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) { boolean interrupted = false; try { while (true) { try { queue.put(element); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
java
public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) { boolean interrupted = false; try { while (true) { try { queue.put(element); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
[ "public", "static", "<", "E", ">", "void", "putUninterruptibly", "(", "BlockingQueue", "<", "E", ">", "queue", ",", "E", "element", ")", "{", "boolean", "interrupted", "=", "false", ";", "try", "{", "while", "(", "true", ")", "{", "try", "{", "queue", ...
Invokes {@code queue.}{@link BlockingQueue#put(Object) put(element)} uninterruptibly. @throws ClassCastException if the class of the specified element prevents it from being added to the given queue @throws IllegalArgumentException if some property of the specified element prevents it from being added to the given queue
[ "Invokes", "{", "@code", "queue", ".", "}", "{", "@link", "BlockingQueue#put", "(", "Object", ")", "put", "(", "element", ")", "}", "uninterruptibly", "." ]
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/util/concurrent/Uninterruptibles.java#L244-L260
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/Comapi.java
Comapi.initialise
public static void initialise(@NonNull Application app, @NonNull ComapiConfig config, Callback<ComapiClient> callback) { String error = checkIfCanInitialise(app, config, false); if (!TextUtils.isEmpty(error) && callback != null) { callback.error(new Exception(error)); } ComapiClient client = new ComapiClient(config); CallbackAdapter adapter = config.getCallbackAdapter() != null ? config.getCallbackAdapter() : new CallbackAdapter(); client.initialise(app, adapter, callback); }
java
public static void initialise(@NonNull Application app, @NonNull ComapiConfig config, Callback<ComapiClient> callback) { String error = checkIfCanInitialise(app, config, false); if (!TextUtils.isEmpty(error) && callback != null) { callback.error(new Exception(error)); } ComapiClient client = new ComapiClient(config); CallbackAdapter adapter = config.getCallbackAdapter() != null ? config.getCallbackAdapter() : new CallbackAdapter(); client.initialise(app, adapter, callback); }
[ "public", "static", "void", "initialise", "(", "@", "NonNull", "Application", "app", ",", "@", "NonNull", "ComapiConfig", "config", ",", "Callback", "<", "ComapiClient", ">", "callback", ")", "{", "String", "error", "=", "checkIfCanInitialise", "(", "app", ","...
Build SDK client. Can be called only once in onCreate callback on Application class.
[ "Build", "SDK", "client", ".", "Can", "be", "called", "only", "once", "in", "onCreate", "callback", "on", "Application", "class", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/Comapi.java#L45-L55
zerodhatech/javakiteconnect
kiteconnect/src/com/zerodhatech/models/User.java
User.parseArray
public User parseArray(User user, JSONObject response) throws JSONException { JSONArray productArray = response.getJSONArray("products"); user.products = new String[productArray.length()]; for(int i = 0; i < productArray.length(); i++) { user.products[i] = productArray.getString(i); } JSONArray exchangesArray = response.getJSONArray("exchanges"); user.exchanges = new String[exchangesArray.length()]; for (int j = 0; j < exchangesArray.length(); j++){ user.exchanges[j] = exchangesArray.getString(j); } JSONArray orderTypeArray = response.getJSONArray("order_types"); user.orderTypes = new String[orderTypeArray.length()]; for(int k = 0; k < orderTypeArray.length(); k++){ user.orderTypes[k] = orderTypeArray.getString(k); } return user; }
java
public User parseArray(User user, JSONObject response) throws JSONException { JSONArray productArray = response.getJSONArray("products"); user.products = new String[productArray.length()]; for(int i = 0; i < productArray.length(); i++) { user.products[i] = productArray.getString(i); } JSONArray exchangesArray = response.getJSONArray("exchanges"); user.exchanges = new String[exchangesArray.length()]; for (int j = 0; j < exchangesArray.length(); j++){ user.exchanges[j] = exchangesArray.getString(j); } JSONArray orderTypeArray = response.getJSONArray("order_types"); user.orderTypes = new String[orderTypeArray.length()]; for(int k = 0; k < orderTypeArray.length(); k++){ user.orderTypes[k] = orderTypeArray.getString(k); } return user; }
[ "public", "User", "parseArray", "(", "User", "user", ",", "JSONObject", "response", ")", "throws", "JSONException", "{", "JSONArray", "productArray", "=", "response", ".", "getJSONArray", "(", "\"products\"", ")", ";", "user", ".", "products", "=", "new", "Str...
Parses array details of product, exchange and order_type from json response. @param response is the json response from server. @param user is the object to which data is copied to from json response. @return User is the pojo of parsed data.
[ "Parses", "array", "details", "of", "product", "exchange", "and", "order_type", "from", "json", "response", "." ]
train
https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/models/User.java#L77-L97
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/DirectoryYamlFlowLoader.java
DirectoryYamlFlowLoader.loadProjectFlow
@Override public ValidationReport loadProjectFlow(final Project project, final File projectDir) { convertYamlFiles(projectDir); FlowLoaderUtils.checkJobProperties(project.getId(), this.props, this.jobPropsMap, this.errors); return FlowLoaderUtils.generateFlowLoaderReport(this.errors); }
java
@Override public ValidationReport loadProjectFlow(final Project project, final File projectDir) { convertYamlFiles(projectDir); FlowLoaderUtils.checkJobProperties(project.getId(), this.props, this.jobPropsMap, this.errors); return FlowLoaderUtils.generateFlowLoaderReport(this.errors); }
[ "@", "Override", "public", "ValidationReport", "loadProjectFlow", "(", "final", "Project", "project", ",", "final", "File", "projectDir", ")", "{", "convertYamlFiles", "(", "projectDir", ")", ";", "FlowLoaderUtils", ".", "checkJobProperties", "(", "project", ".", ...
Loads all project flows from the directory. @param project The project. @param projectDir The directory to load flows from. @return the validation report.
[ "Loads", "all", "project", "flows", "from", "the", "directory", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/DirectoryYamlFlowLoader.java#L111-L116
JavaMoney/jsr354-api
src/main/java/javax/money/AbstractContextBuilder.java
AbstractContextBuilder.importContext
public B importContext(AbstractContext context, boolean overwriteDuplicates){ for (Map.Entry<String, Object> en : context.data.entrySet()) { if (overwriteDuplicates) { this.data.put(en.getKey(), en.getValue()); }else{ this.data.putIfAbsent(en.getKey(), en.getValue()); } } return (B) this; }
java
public B importContext(AbstractContext context, boolean overwriteDuplicates){ for (Map.Entry<String, Object> en : context.data.entrySet()) { if (overwriteDuplicates) { this.data.put(en.getKey(), en.getValue()); }else{ this.data.putIfAbsent(en.getKey(), en.getValue()); } } return (B) this; }
[ "public", "B", "importContext", "(", "AbstractContext", "context", ",", "boolean", "overwriteDuplicates", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "en", ":", "context", ".", "data", ".", "entrySet", "(", ")", ")", "{"...
Apply all attributes on the given context. @param context the context to be applied, not null. @param overwriteDuplicates flag, if existing entries should be overwritten. @return this Builder, for chaining
[ "Apply", "all", "attributes", "on", "the", "given", "context", "." ]
train
https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/AbstractContextBuilder.java#L48-L57
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/Convolution1DUtils.java
Convolution1DUtils.getSameModeTopLeftPadding
public static int getSameModeTopLeftPadding(int outSize, int inSize, int kernel, int strides, int dilation) { int eKernel = effectiveKernelSize(kernel, dilation); //Note that padBottom is 1 bigger than this if bracketed term is not divisible by 2 int outPad = ((outSize - 1) * strides + eKernel - inSize) / 2; Preconditions.checkState(outPad >= 0, "Invalid padding values calculated: %s - " + "layer configuration is invalid? Input size %s, output size %s, kernel %s, " + "strides %s, dilation %s", outPad, inSize, outSize, kernel, strides, dilation); return outPad; }
java
public static int getSameModeTopLeftPadding(int outSize, int inSize, int kernel, int strides, int dilation) { int eKernel = effectiveKernelSize(kernel, dilation); //Note that padBottom is 1 bigger than this if bracketed term is not divisible by 2 int outPad = ((outSize - 1) * strides + eKernel - inSize) / 2; Preconditions.checkState(outPad >= 0, "Invalid padding values calculated: %s - " + "layer configuration is invalid? Input size %s, output size %s, kernel %s, " + "strides %s, dilation %s", outPad, inSize, outSize, kernel, strides, dilation); return outPad; }
[ "public", "static", "int", "getSameModeTopLeftPadding", "(", "int", "outSize", ",", "int", "inSize", ",", "int", "kernel", ",", "int", "strides", ",", "int", "dilation", ")", "{", "int", "eKernel", "=", "effectiveKernelSize", "(", "kernel", ",", "dilation", ...
Get top padding for same mode only. @param outSize Output size (length 2 array, height dimension first) @param inSize Input size (length 2 array, height dimension first) @param kernel Kernel size (length 2 array, height dimension first) @param strides Strides (length 2 array, height dimension first) @param dilation Dilation (length 2 array, height dimension first) @return Top left padding (length 2 array, height dimension first)
[ "Get", "top", "padding", "for", "same", "mode", "only", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/Convolution1DUtils.java#L201-L209
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/accumulators/AccumulatorHelper.java
AccumulatorHelper.mergeInto
public static void mergeInto(Map<String, OptionalFailure<Accumulator<?, ?>>> target, Map<String, Accumulator<?, ?>> toMerge) { for (Map.Entry<String, Accumulator<?, ?>> otherEntry : toMerge.entrySet()) { OptionalFailure<Accumulator<?, ?>> ownAccumulator = target.get(otherEntry.getKey()); if (ownAccumulator == null) { // Create initial counter (copy!) target.put( otherEntry.getKey(), wrapUnchecked(otherEntry.getKey(), () -> otherEntry.getValue().clone())); } else if (ownAccumulator.isFailure()) { continue; } else { Accumulator<?, ?> accumulator = ownAccumulator.getUnchecked(); // Both should have the same type compareAccumulatorTypes(otherEntry.getKey(), accumulator.getClass(), otherEntry.getValue().getClass()); // Merge target counter with other counter target.put( otherEntry.getKey(), wrapUnchecked(otherEntry.getKey(), () -> mergeSingle(accumulator, otherEntry.getValue().clone()))); } } }
java
public static void mergeInto(Map<String, OptionalFailure<Accumulator<?, ?>>> target, Map<String, Accumulator<?, ?>> toMerge) { for (Map.Entry<String, Accumulator<?, ?>> otherEntry : toMerge.entrySet()) { OptionalFailure<Accumulator<?, ?>> ownAccumulator = target.get(otherEntry.getKey()); if (ownAccumulator == null) { // Create initial counter (copy!) target.put( otherEntry.getKey(), wrapUnchecked(otherEntry.getKey(), () -> otherEntry.getValue().clone())); } else if (ownAccumulator.isFailure()) { continue; } else { Accumulator<?, ?> accumulator = ownAccumulator.getUnchecked(); // Both should have the same type compareAccumulatorTypes(otherEntry.getKey(), accumulator.getClass(), otherEntry.getValue().getClass()); // Merge target counter with other counter target.put( otherEntry.getKey(), wrapUnchecked(otherEntry.getKey(), () -> mergeSingle(accumulator, otherEntry.getValue().clone()))); } } }
[ "public", "static", "void", "mergeInto", "(", "Map", "<", "String", ",", "OptionalFailure", "<", "Accumulator", "<", "?", ",", "?", ">", ">", ">", "target", ",", "Map", "<", "String", ",", "Accumulator", "<", "?", ",", "?", ">", ">", "toMerge", ")", ...
Merge two collections of accumulators. The second will be merged into the first. @param target The collection of accumulators that will be updated @param toMerge The collection of accumulators that will be merged into the other
[ "Merge", "two", "collections", "of", "accumulators", ".", "The", "second", "will", "be", "merged", "into", "the", "first", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/accumulators/AccumulatorHelper.java#L54-L78
finmath/finmath-lib
src/main/java/net/finmath/functions/LinearAlgebra.java
LinearAlgebra.factorReductionUsingCommonsMath
public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors); // Renormalize rows for (int row = 0; row < correlationMatrix.length; row++) { double sumSquared = 0; for (int factor = 0; factor < numberOfFactors; factor++) { sumSquared += factorMatrix[row][factor] * factorMatrix[row][factor]; } if(sumSquared != 0) { for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared); } } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = 1.0; } } } // Orthogonalized again double[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData(); return getFactorMatrix(reducedCorrelationMatrix, numberOfFactors); }
java
public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors); // Renormalize rows for (int row = 0; row < correlationMatrix.length; row++) { double sumSquared = 0; for (int factor = 0; factor < numberOfFactors; factor++) { sumSquared += factorMatrix[row][factor] * factorMatrix[row][factor]; } if(sumSquared != 0) { for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared); } } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = 1.0; } } } // Orthogonalized again double[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData(); return getFactorMatrix(reducedCorrelationMatrix, numberOfFactors); }
[ "public", "static", "double", "[", "]", "[", "]", "factorReductionUsingCommonsMath", "(", "double", "[", "]", "[", "]", "correlationMatrix", ",", "int", "numberOfFactors", ")", "{", "// Extract factors corresponding to the largest eigenvalues", "double", "[", "]", "["...
Returns a correlation matrix which has rank &lt; n and for which the first n factors agree with the factors of correlationMatrix. @param correlationMatrix The given correlation matrix. @param numberOfFactors The requested number of factors (Eigenvectors). @return Factor reduced correlation matrix.
[ "Returns", "a", "correlation", "matrix", "which", "has", "rank", "&lt", ";", "n", "and", "for", "which", "the", "first", "n", "factors", "agree", "with", "the", "factors", "of", "correlationMatrix", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/functions/LinearAlgebra.java#L438-L466
aalmiray/Json-lib
src/main/java/net/sf/json/JSONObject.java
JSONObject.findTargetClass
private static Class findTargetClass( String key, Map classMap ) { // try get first Class targetClass = (Class) classMap.get( key ); if( targetClass == null ){ // try with regexp // this will hit performance as it must iterate over all the keys // and create a RegexpMatcher for each key for( Iterator i = classMap.entrySet() .iterator(); i.hasNext(); ){ Map.Entry entry = (Map.Entry) i.next(); if( RegexpUtils.getMatcher( (String) entry.getKey() ) .matches( key ) ){ targetClass = (Class) entry.getValue(); break; } } } return targetClass; }
java
private static Class findTargetClass( String key, Map classMap ) { // try get first Class targetClass = (Class) classMap.get( key ); if( targetClass == null ){ // try with regexp // this will hit performance as it must iterate over all the keys // and create a RegexpMatcher for each key for( Iterator i = classMap.entrySet() .iterator(); i.hasNext(); ){ Map.Entry entry = (Map.Entry) i.next(); if( RegexpUtils.getMatcher( (String) entry.getKey() ) .matches( key ) ){ targetClass = (Class) entry.getValue(); break; } } } return targetClass; }
[ "private", "static", "Class", "findTargetClass", "(", "String", "key", ",", "Map", "classMap", ")", "{", "// try get first", "Class", "targetClass", "=", "(", "Class", ")", "classMap", ".", "get", "(", "key", ")", ";", "if", "(", "targetClass", "==", "null...
Locates a Class associated to a specifi key.<br> The key may be a regexp.
[ "Locates", "a", "Class", "associated", "to", "a", "specifi", "key", ".", "<br", ">", "The", "key", "may", "be", "a", "regexp", "." ]
train
https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONObject.java#L1262-L1281
apache/incubator-druid
extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/hll/HllSketchAggregatorFactory.java
HllSketchAggregatorFactory.getRequiredColumns
@Override public List<AggregatorFactory> getRequiredColumns() { return Collections.singletonList(new HllSketchBuildAggregatorFactory(fieldName, fieldName, lgK, tgtHllType.toString())); }
java
@Override public List<AggregatorFactory> getRequiredColumns() { return Collections.singletonList(new HllSketchBuildAggregatorFactory(fieldName, fieldName, lgK, tgtHllType.toString())); }
[ "@", "Override", "public", "List", "<", "AggregatorFactory", ">", "getRequiredColumns", "(", ")", "{", "return", "Collections", ".", "singletonList", "(", "new", "HllSketchBuildAggregatorFactory", "(", "fieldName", ",", "fieldName", ",", "lgK", ",", "tgtHllType", ...
This is a convoluted way to return a list of input field names this aggregator needs. Currently the returned factories are only used to obtain a field name by calling getName() method.
[ "This", "is", "a", "convoluted", "way", "to", "return", "a", "list", "of", "input", "field", "names", "this", "aggregator", "needs", ".", "Currently", "the", "returned", "factories", "are", "only", "used", "to", "obtain", "a", "field", "name", "by", "calli...
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/hll/HllSketchAggregatorFactory.java#L104-L108
alkacon/opencms-core
src/org/opencms/cmis/CmsCmisUtil.java
CmsCmisUtil.addPropertyDateTime
public static void addPropertyDateTime( CmsCmisTypeManager typeManager, PropertiesImpl props, String typeId, Set<String> filter, String id, GregorianCalendar value) { if (!checkAddProperty(typeManager, props, typeId, filter, id)) { return; } props.addProperty(new PropertyDateTimeImpl(id, value)); }
java
public static void addPropertyDateTime( CmsCmisTypeManager typeManager, PropertiesImpl props, String typeId, Set<String> filter, String id, GregorianCalendar value) { if (!checkAddProperty(typeManager, props, typeId, filter, id)) { return; } props.addProperty(new PropertyDateTimeImpl(id, value)); }
[ "public", "static", "void", "addPropertyDateTime", "(", "CmsCmisTypeManager", "typeManager", ",", "PropertiesImpl", "props", ",", "String", "typeId", ",", "Set", "<", "String", ">", "filter", ",", "String", "id", ",", "GregorianCalendar", "value", ")", "{", "if"...
Adds a date/time property to a PropertiesImpl.<p> @param typeManager the type manager @param props the properties @param typeId the type id @param filter the property filter string @param id the property id @param value the property value
[ "Adds", "a", "date", "/", "time", "property", "to", "a", "PropertiesImpl", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/cmis/CmsCmisUtil.java#L192-L205
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java
ParseUtils.readStringAttributeElement
public static String readStringAttributeElement(final XMLExtendedStreamReader reader, final String attributeName) throws XMLStreamException { requireSingleAttribute(reader, attributeName); final String value = reader.getAttributeValue(0); requireNoContent(reader); return value; }
java
public static String readStringAttributeElement(final XMLExtendedStreamReader reader, final String attributeName) throws XMLStreamException { requireSingleAttribute(reader, attributeName); final String value = reader.getAttributeValue(0); requireNoContent(reader); return value; }
[ "public", "static", "String", "readStringAttributeElement", "(", "final", "XMLExtendedStreamReader", "reader", ",", "final", "String", "attributeName", ")", "throws", "XMLStreamException", "{", "requireSingleAttribute", "(", "reader", ",", "attributeName", ")", ";", "fi...
Read an element which contains only a single string attribute. @param reader the reader @param attributeName the attribute name, usually "value" or "name" @return the string value @throws javax.xml.stream.XMLStreamException if an error occurs or if the element does not contain the specified attribute, contains other attributes, or contains child elements.
[ "Read", "an", "element", "which", "contains", "only", "a", "single", "string", "attribute", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java#L401-L407
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/JMessageClient.java
JMessageClient.v2GetUserMessages
public MessageListResult v2GetUserMessages(String username, int count, String begin_time, String end_time) throws APIConnectionException, APIRequestException { return _reportClient.v2GetUserMessages(username, count, begin_time, end_time); }
java
public MessageListResult v2GetUserMessages(String username, int count, String begin_time, String end_time) throws APIConnectionException, APIRequestException { return _reportClient.v2GetUserMessages(username, count, begin_time, end_time); }
[ "public", "MessageListResult", "v2GetUserMessages", "(", "String", "username", ",", "int", "count", ",", "String", "begin_time", ",", "String", "end_time", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "return", "_reportClient", ".", "v2Get...
Get message list from user's record, messages will store 60 days. @param username Necessary parameter. @param count Necessary parameter. The count of the message list. @param begin_time Optional parameter. The format must follow by 'yyyy-MM-dd HH:mm:ss' @param end_time Optional parameter. The format must follow by 'yyyy-MM-dd HH:mm:ss' @return MessageListResult @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Get", "message", "list", "from", "user", "s", "record", "messages", "will", "store", "60", "days", "." ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/JMessageClient.java#L968-L971
apiman/apiman
gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/GatewayServlet.java
GatewayServlet.writeResponse
protected void writeResponse(HttpServletResponse response, ApiResponse sresponse) { response.setStatus(sresponse.getCode()); for (Entry<String, String> entry : sresponse.getHeaders()) { response.addHeader(entry.getKey(), entry.getValue()); } }
java
protected void writeResponse(HttpServletResponse response, ApiResponse sresponse) { response.setStatus(sresponse.getCode()); for (Entry<String, String> entry : sresponse.getHeaders()) { response.addHeader(entry.getKey(), entry.getValue()); } }
[ "protected", "void", "writeResponse", "(", "HttpServletResponse", "response", ",", "ApiResponse", "sresponse", ")", "{", "response", ".", "setStatus", "(", "sresponse", ".", "getCode", "(", ")", ")", ";", "for", "(", "Entry", "<", "String", ",", "String", ">...
Writes the API response to the HTTP servlet response object. @param response @param sresponse
[ "Writes", "the", "API", "response", "to", "the", "HTTP", "servlet", "response", "object", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/GatewayServlet.java#L293-L298
samskivert/pythagoras
src/main/java/pythagoras/d/RectangularShape.java
RectangularShape.setFrame
public void setFrame (XY loc, IDimension size) { setFrame(loc.x(), loc.y(), size.width(), size.height()); }
java
public void setFrame (XY loc, IDimension size) { setFrame(loc.x(), loc.y(), size.width(), size.height()); }
[ "public", "void", "setFrame", "(", "XY", "loc", ",", "IDimension", "size", ")", "{", "setFrame", "(", "loc", ".", "x", "(", ")", ",", "loc", ".", "y", "(", ")", ",", "size", ".", "width", "(", ")", ",", "size", ".", "height", "(", ")", ")", "...
Sets the location and size of the framing rectangle of this shape to the supplied values.
[ "Sets", "the", "location", "and", "size", "of", "the", "framing", "rectangle", "of", "this", "shape", "to", "the", "supplied", "values", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/d/RectangularShape.java#L21-L23
RKumsher/utils
src/main/java/com/github/rkumsher/date/RandomDateUtils.java
RandomDateUtils.randomMonthDayAfter
public static MonthDay randomMonthDayAfter(MonthDay after, boolean includeLeapDay) { checkArgument(after != null, "After must be non-null"); checkArgument(after.isBefore(MonthDay.of(DECEMBER, 31)), "After must be before December 31st"); int year = includeLeapDay ? LEAP_YEAR : LEAP_YEAR - 1; LocalDate start = after.atYear(year).plus(1, DAYS); LocalDate end = Year.of(year + 1).atDay(1); LocalDate localDate = randomLocalDate(start, end); return MonthDay.of(localDate.getMonth(), localDate.getDayOfMonth()); }
java
public static MonthDay randomMonthDayAfter(MonthDay after, boolean includeLeapDay) { checkArgument(after != null, "After must be non-null"); checkArgument(after.isBefore(MonthDay.of(DECEMBER, 31)), "After must be before December 31st"); int year = includeLeapDay ? LEAP_YEAR : LEAP_YEAR - 1; LocalDate start = after.atYear(year).plus(1, DAYS); LocalDate end = Year.of(year + 1).atDay(1); LocalDate localDate = randomLocalDate(start, end); return MonthDay.of(localDate.getMonth(), localDate.getDayOfMonth()); }
[ "public", "static", "MonthDay", "randomMonthDayAfter", "(", "MonthDay", "after", ",", "boolean", "includeLeapDay", ")", "{", "checkArgument", "(", "after", "!=", "null", ",", "\"After must be non-null\"", ")", ";", "checkArgument", "(", "after", ".", "isBefore", "...
Returns a random {@link MonthDay} that is after the given {@link MonthDay}. @param after the value that returned {@link MonthDay} must be after @param includeLeapDay whether or not to include leap day @return the random {@link MonthDay} @throws IllegalArgumentException if after is null or if after is last day of year (December 31st)
[ "Returns", "a", "random", "{", "@link", "MonthDay", "}", "that", "is", "after", "the", "given", "{", "@link", "MonthDay", "}", "." ]
train
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/date/RandomDateUtils.java#L741-L749
OpenLiberty/open-liberty
dev/com.ibm.ws.webservices.javaee.common/src/com/ibm/ws/webservices/javaee/common/internal/JaxWsDDHelper.java
JaxWsDDHelper.getWebserviceDescriptionByEJBLink
static WebserviceDescription getWebserviceDescriptionByEJBLink(String ejbLink, Adaptable containerToAdapt) throws UnableToAdaptException { return getHighLevelElementByServiceImplBean(ejbLink, containerToAdapt, WebserviceDescription.class, LinkType.EJB); }
java
static WebserviceDescription getWebserviceDescriptionByEJBLink(String ejbLink, Adaptable containerToAdapt) throws UnableToAdaptException { return getHighLevelElementByServiceImplBean(ejbLink, containerToAdapt, WebserviceDescription.class, LinkType.EJB); }
[ "static", "WebserviceDescription", "getWebserviceDescriptionByEJBLink", "(", "String", "ejbLink", ",", "Adaptable", "containerToAdapt", ")", "throws", "UnableToAdaptException", "{", "return", "getHighLevelElementByServiceImplBean", "(", "ejbLink", ",", "containerToAdapt", ",", ...
Get the WebserviceDescription by ejb-link. @param ejbLink @param containerToAdapt @return @throws UnableToAdaptException
[ "Get", "the", "WebserviceDescription", "by", "ejb", "-", "link", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webservices.javaee.common/src/com/ibm/ws/webservices/javaee/common/internal/JaxWsDDHelper.java#L68-L70
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/autoscale/autoscalepolicy_binding.java
autoscalepolicy_binding.get
public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{ autoscalepolicy_binding obj = new autoscalepolicy_binding(); obj.set_name(name); autoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service); return response; }
java
public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{ autoscalepolicy_binding obj = new autoscalepolicy_binding(); obj.set_name(name); autoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service); return response; }
[ "public", "static", "autoscalepolicy_binding", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "autoscalepolicy_binding", "obj", "=", "new", "autoscalepolicy_binding", "(", ")", ";", "obj", ".", "set_name", "(", "nam...
Use this API to fetch autoscalepolicy_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "autoscalepolicy_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/autoscale/autoscalepolicy_binding.java#L103-L108
wigforss/Ka-Commons-Reflection
src/main/java/org/kasource/commons/reflection/util/ConstructorUtils.java
ConstructorUtils.getInstance
public static <T> T getInstance(String className, Class<T> ofType) throws IllegalStateException { return getInstance(className, ofType, new Class<?>[]{}, new Object[]{}); }
java
public static <T> T getInstance(String className, Class<T> ofType) throws IllegalStateException { return getInstance(className, ofType, new Class<?>[]{}, new Object[]{}); }
[ "public", "static", "<", "T", ">", "T", "getInstance", "(", "String", "className", ",", "Class", "<", "T", ">", "ofType", ")", "throws", "IllegalStateException", "{", "return", "getInstance", "(", "className", ",", "ofType", ",", "new", "Class", "<", "?", ...
Creates and returns a new instance of class with name className, loading the class and using the default constructor. @param <T> @param className @param ofType @return a new instance of class loaded from className. @throws IllegalStateException if className could not be loaded or if that class does not have a default constructor or if the loaded class is not of the supplied type (ofType).
[ "Creates", "and", "returns", "a", "new", "instance", "of", "class", "with", "name", "className", "loading", "the", "class", "and", "using", "the", "default", "constructor", "." ]
train
https://github.com/wigforss/Ka-Commons-Reflection/blob/a80f7a164cd800089e4f4dd948ca6f0e7badcf33/src/main/java/org/kasource/commons/reflection/util/ConstructorUtils.java#L115-L117
jbundle/jbundle
base/message/core/src/main/java/org/jbundle/base/message/core/trx/TrxMessageHeader.java
TrxMessageHeader.put
public void put(String strKey, Object objData) { if (m_mapMessageHeader == null) m_mapMessageHeader = new HashMap<String,Object>(); objData = m_mapMessageHeader.put(strKey, objData); }
java
public void put(String strKey, Object objData) { if (m_mapMessageHeader == null) m_mapMessageHeader = new HashMap<String,Object>(); objData = m_mapMessageHeader.put(strKey, objData); }
[ "public", "void", "put", "(", "String", "strKey", ",", "Object", "objData", ")", "{", "if", "(", "m_mapMessageHeader", "==", "null", ")", "m_mapMessageHeader", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "objData", "=", "m_ma...
Return the state of this object as a properties object. @param strKey The key to return. @return The properties.
[ "Return", "the", "state", "of", "this", "object", "as", "a", "properties", "object", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/core/src/main/java/org/jbundle/base/message/core/trx/TrxMessageHeader.java#L271-L276
twotoasters/RecyclerViewLib
library/src/main/java/com/twotoasters/layoutmanager/BaseLayoutManager.java
BaseLayoutManager.recycleByRenderState
protected void recycleByRenderState(RecyclerView.Recycler recycler, RenderState renderState) { if (renderState.mLayoutDirection == RenderState.LAYOUT_START) { recycleViewsFromEnd(recycler, renderState.mScrollingOffset); } else { recycleViewsFromStart(recycler, renderState.mScrollingOffset); } }
java
protected void recycleByRenderState(RecyclerView.Recycler recycler, RenderState renderState) { if (renderState.mLayoutDirection == RenderState.LAYOUT_START) { recycleViewsFromEnd(recycler, renderState.mScrollingOffset); } else { recycleViewsFromStart(recycler, renderState.mScrollingOffset); } }
[ "protected", "void", "recycleByRenderState", "(", "RecyclerView", ".", "Recycler", "recycler", ",", "RenderState", "renderState", ")", "{", "if", "(", "renderState", ".", "mLayoutDirection", "==", "RenderState", ".", "LAYOUT_START", ")", "{", "recycleViewsFromEnd", ...
Helper method to call appropriate recycle method depending on current render layout direction @param recycler Current recycler that is attached to RecyclerView @param renderState Current render state. Right now, this object does not change but we may consider moving it out of this view so passing around as a parameter for now, rather than accessing {@link #mRenderState} @see #recycleViewsFromStart(com.twotoasters.android.support.v7.widget.RecyclerView.Recycler, int) @see #recycleViewsFromEnd(com.twotoasters.android.support.v7.widget.RecyclerView.Recycler, int) @see com.twotoasters.android.support.v7.widget.LinearLayoutManager.RenderState#mLayoutDirection
[ "Helper", "method", "to", "call", "appropriate", "recycle", "method", "depending", "on", "current", "render", "layout", "direction" ]
train
https://github.com/twotoasters/RecyclerViewLib/blob/2379fd5bbf57d4dfc8b28046b7ace950905c75f0/library/src/main/java/com/twotoasters/layoutmanager/BaseLayoutManager.java#L969-L975
googleapis/google-cloud-java
google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Statement.java
Statement.executeQuery
public ResultSet executeQuery(ReadContext context, Options.QueryOption... options) { return context.executeQuery(this, options); }
java
public ResultSet executeQuery(ReadContext context, Options.QueryOption... options) { return context.executeQuery(this, options); }
[ "public", "ResultSet", "executeQuery", "(", "ReadContext", "context", ",", "Options", ".", "QueryOption", "...", "options", ")", "{", "return", "context", ".", "executeQuery", "(", "this", ",", "options", ")", ";", "}" ]
Executes the query in {@code context}. {@code statement.executeQuery(context)} is exactly equivalent to {@code context.executeQuery(statement)}. @see ReadContext#executeQuery(Statement, Options.QueryOption...)
[ "Executes", "the", "query", "in", "{", "@code", "context", "}", ".", "{", "@code", "statement", ".", "executeQuery", "(", "context", ")", "}", "is", "exactly", "equivalent", "to", "{", "@code", "context", ".", "executeQuery", "(", "statement", ")", "}", ...
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Statement.java#L135-L137
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.putAt
public static void putAt(List self, IntRange range, Collection col) { List sublist = resizeListWithRangeAndGetSublist(self, range); if (col.isEmpty()) return; sublist.addAll(col); }
java
public static void putAt(List self, IntRange range, Collection col) { List sublist = resizeListWithRangeAndGetSublist(self, range); if (col.isEmpty()) return; sublist.addAll(col); }
[ "public", "static", "void", "putAt", "(", "List", "self", ",", "IntRange", "range", ",", "Collection", "col", ")", "{", "List", "sublist", "=", "resizeListWithRangeAndGetSublist", "(", "self", ",", "range", ")", ";", "if", "(", "col", ".", "isEmpty", "(", ...
List subscript assignment operator when given a range as the index and the assignment operand is a collection. Example: <pre class="groovyTestCase">def myList = [4, 3, 5, 1, 2, 8, 10] myList[3..5] = ["a", true] assert myList == [4, 3, 5, "a", true, 10]</pre> Items in the given range are replaced with items from the collection. @param self a List @param range the subset of the list to set @param col the collection of values to put at the given sublist @since 1.5.0
[ "List", "subscript", "assignment", "operator", "when", "given", "a", "range", "as", "the", "index", "and", "the", "assignment", "operand", "is", "a", "collection", ".", "Example", ":", "<pre", "class", "=", "groovyTestCase", ">", "def", "myList", "=", "[", ...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L8044-L8048
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernel.java
FactoryKernel.table1D_F32
public static Kernel1D_F32 table1D_F32(int radius, boolean normalized) { Kernel1D_F32 ret = new Kernel1D_F32(radius * 2 + 1); float val = normalized ? 1.0f / ret.width : 1.0f; for (int i = 0; i < ret.data.length; i++) { ret.data[i] = val; } return ret; }
java
public static Kernel1D_F32 table1D_F32(int radius, boolean normalized) { Kernel1D_F32 ret = new Kernel1D_F32(radius * 2 + 1); float val = normalized ? 1.0f / ret.width : 1.0f; for (int i = 0; i < ret.data.length; i++) { ret.data[i] = val; } return ret; }
[ "public", "static", "Kernel1D_F32", "table1D_F32", "(", "int", "radius", ",", "boolean", "normalized", ")", "{", "Kernel1D_F32", "ret", "=", "new", "Kernel1D_F32", "(", "radius", "*", "2", "+", "1", ")", ";", "float", "val", "=", "normalized", "?", "1.0f",...
<p> Create an floating point table convolution kernel. If un-normalized then all the elements are equal to one, otherwise they are equal to one over the width. </p> <p> See {@link boofcv.alg.filter.convolve.ConvolveImageBox} or {@link boofcv.alg.filter.convolve.ConvolveImageMean} for faster ways to convolve these kernels. </p> @param radius kernel's radius. @return table kernel.
[ "<p", ">", "Create", "an", "floating", "point", "table", "convolution", "kernel", ".", "If", "un", "-", "normalized", "then", "all", "the", "elements", "are", "equal", "to", "one", "otherwise", "they", "are", "equal", "to", "one", "over", "the", "width", ...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernel.java#L152-L162
gallandarakhneorg/afc
core/maths/mathtree/src/main/java/org/arakhne/afc/math/tree/node/NaryTreeNode.java
NaryTreeNode.addChild
public final boolean addChild(int index, N newChild) { if (newChild == null) { return false; } final int count = (this.children == null) ? 0 : this.children.size(); final N oldParent = newChild.getParentNode(); if (oldParent != this && oldParent != null) { newChild.removeFromParent(); } final int insertionIndex; if (this.children == null) { this.children = newInternalList(index + 1); } if (index < count) { // set the element insertionIndex = Math.max(index, 0); this.children.add(insertionIndex, newChild); } else { // Resize the array insertionIndex = this.children.size(); this.children.add(newChild); } ++this.notNullChildCount; newChild.setParentNodeReference(toN(), true); firePropertyChildAdded(insertionIndex, newChild); return true; }
java
public final boolean addChild(int index, N newChild) { if (newChild == null) { return false; } final int count = (this.children == null) ? 0 : this.children.size(); final N oldParent = newChild.getParentNode(); if (oldParent != this && oldParent != null) { newChild.removeFromParent(); } final int insertionIndex; if (this.children == null) { this.children = newInternalList(index + 1); } if (index < count) { // set the element insertionIndex = Math.max(index, 0); this.children.add(insertionIndex, newChild); } else { // Resize the array insertionIndex = this.children.size(); this.children.add(newChild); } ++this.notNullChildCount; newChild.setParentNodeReference(toN(), true); firePropertyChildAdded(insertionIndex, newChild); return true; }
[ "public", "final", "boolean", "addChild", "(", "int", "index", ",", "N", "newChild", ")", "{", "if", "(", "newChild", "==", "null", ")", "{", "return", "false", ";", "}", "final", "int", "count", "=", "(", "this", ".", "children", "==", "null", ")", ...
Add a child node at the specified index. @param index is the insertion index. @param newChild is the new child to insert. @return <code>true</code> on success, otherwise <code>false</code>
[ "Add", "a", "child", "node", "at", "the", "specified", "index", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathtree/src/main/java/org/arakhne/afc/math/tree/node/NaryTreeNode.java#L341-L375
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/Context.java
Context.postConstruction
public EventSpace postConstruction() { this.spaceRepository.postConstruction(); this.defaultSpace = createSpace(OpenEventSpaceSpecification.class, this.defaultSpaceID); if (this.defaultSpace == null) { // The default space could have been created before thanks to Hazelcast, // thus createSpace returns null because the space already exist, // in this case we return the already existing default space stored in the SpaceRepository this.defaultSpace = (OpenEventSpace) this.spaceRepository .getSpace(new SpaceID(this.id, this.defaultSpaceID, OpenEventSpaceSpecification.class)); } return this.defaultSpace; }
java
public EventSpace postConstruction() { this.spaceRepository.postConstruction(); this.defaultSpace = createSpace(OpenEventSpaceSpecification.class, this.defaultSpaceID); if (this.defaultSpace == null) { // The default space could have been created before thanks to Hazelcast, // thus createSpace returns null because the space already exist, // in this case we return the already existing default space stored in the SpaceRepository this.defaultSpace = (OpenEventSpace) this.spaceRepository .getSpace(new SpaceID(this.id, this.defaultSpaceID, OpenEventSpaceSpecification.class)); } return this.defaultSpace; }
[ "public", "EventSpace", "postConstruction", "(", ")", "{", "this", ".", "spaceRepository", ".", "postConstruction", "(", ")", ";", "this", ".", "defaultSpace", "=", "createSpace", "(", "OpenEventSpaceSpecification", ".", "class", ",", "this", ".", "defaultSpaceID"...
Create the default space in this context. @return the created space.
[ "Create", "the", "default", "space", "in", "this", "context", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/Context.java#L100-L111
Jsondb/jsondb-core
src/main/java/io/jsondb/crypto/CryptoUtil.java
CryptoUtil.encryptFields
public static void encryptFields(Object object, CollectionMetaData cmd, ICipher cipher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (String secretAnnotatedFieldName: cmd.getSecretAnnotatedFieldNames()) { Method getterMethod = cmd.getGetterMethodForFieldName(secretAnnotatedFieldName); Method setterMethod = cmd.getSetterMethodForFieldName(secretAnnotatedFieldName); String value; String encryptedValue = null; try { value = (String)getterMethod.invoke(object); if (null != value) { encryptedValue = cipher.encrypt(value); setterMethod.invoke(object, encryptedValue); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("Error when invoking method for a @Secret annotated field", e); throw e; } } }
java
public static void encryptFields(Object object, CollectionMetaData cmd, ICipher cipher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (String secretAnnotatedFieldName: cmd.getSecretAnnotatedFieldNames()) { Method getterMethod = cmd.getGetterMethodForFieldName(secretAnnotatedFieldName); Method setterMethod = cmd.getSetterMethodForFieldName(secretAnnotatedFieldName); String value; String encryptedValue = null; try { value = (String)getterMethod.invoke(object); if (null != value) { encryptedValue = cipher.encrypt(value); setterMethod.invoke(object, encryptedValue); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("Error when invoking method for a @Secret annotated field", e); throw e; } } }
[ "public", "static", "void", "encryptFields", "(", "Object", "object", ",", "CollectionMetaData", "cmd", ",", "ICipher", "cipher", ")", "throws", "IllegalAccessException", ",", "IllegalArgumentException", ",", "InvocationTargetException", "{", "for", "(", "String", "se...
A utility method to encrypt the value of field marked by the @Secret annotation using its setter/mutator method. @param object the actual Object representing the POJO we want the Id of. @param cmd the CollectionMetaData object from which we can obtain the list containing names of fields which have the @Secret annotation @param cipher the actual cipher implementation to use @throws IllegalAccessException Error when invoking method for a @Secret annotated field due to permissions @throws IllegalArgumentException Error when invoking method for a @Secret annotated field due to wrong arguments @throws InvocationTargetException Error when invoking method for a @Secret annotated field, the method threw a exception
[ "A", "utility", "method", "to", "encrypt", "the", "value", "of", "field", "marked", "by", "the" ]
train
https://github.com/Jsondb/jsondb-core/blob/c49654d1eee2ace4d5ca5be19730652a966ce7f4/src/main/java/io/jsondb/crypto/CryptoUtil.java#L58-L77
apache/flink
flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/Graph.java
Graph.validate
public Boolean validate(GraphValidator<K, VV, EV> validator) throws Exception { return validator.validate(this); }
java
public Boolean validate(GraphValidator<K, VV, EV> validator) throws Exception { return validator.validate(this); }
[ "public", "Boolean", "validate", "(", "GraphValidator", "<", "K", ",", "VV", ",", "EV", ">", "validator", ")", "throws", "Exception", "{", "return", "validator", ".", "validate", "(", "this", ")", ";", "}" ]
Function that checks whether a Graph is a valid Graph, as defined by the given {@link GraphValidator}. @return true if the Graph is valid.
[ "Function", "that", "checks", "whether", "a", "Graph", "is", "a", "valid", "Graph", "as", "defined", "by", "the", "given", "{", "@link", "GraphValidator", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/Graph.java#L446-L448
neoremind/fluent-validator
fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/FluentValidator.java
FluentValidator.putAttribute2Context
public FluentValidator putAttribute2Context(String key, Object value) { if (context == null) { context = new ValidatorContext(); } context.setAttribute(key, value); return this; }
java
public FluentValidator putAttribute2Context(String key, Object value) { if (context == null) { context = new ValidatorContext(); } context.setAttribute(key, value); return this; }
[ "public", "FluentValidator", "putAttribute2Context", "(", "String", "key", ",", "Object", "value", ")", "{", "if", "(", "context", "==", "null", ")", "{", "context", "=", "new", "ValidatorContext", "(", ")", ";", "}", "context", ".", "setAttribute", "(", "...
将键值对放入上下文 @param key 键 @param value 值 @return FluentValidator
[ "将键值对放入上下文" ]
train
https://github.com/neoremind/fluent-validator/blob/b516970591aa9468b44ba63938b98ec341fd6ead/fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/FluentValidator.java#L100-L106
rzwitserloot/lombok
src/core/lombok/javac/handlers/JavacHandlerUtil.java
JavacHandlerUtil.deleteAnnotationIfNeccessary
public static void deleteAnnotationIfNeccessary(JavacNode annotation, Class<? extends Annotation> annotationType1, Class<? extends Annotation> annotationType2) { deleteAnnotationIfNeccessary0(annotation, annotationType1.getName(), annotationType2.getName()); }
java
public static void deleteAnnotationIfNeccessary(JavacNode annotation, Class<? extends Annotation> annotationType1, Class<? extends Annotation> annotationType2) { deleteAnnotationIfNeccessary0(annotation, annotationType1.getName(), annotationType2.getName()); }
[ "public", "static", "void", "deleteAnnotationIfNeccessary", "(", "JavacNode", "annotation", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotationType1", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotationType2", ")", "{", "deleteAnnotationI...
Removes the annotation from javac's AST (it remains in lombok's AST), then removes any import statement that imports this exact annotation (not star imports). Only does this if the DeleteLombokAnnotations class is in the context.
[ "Removes", "the", "annotation", "from", "javac", "s", "AST", "(", "it", "remains", "in", "lombok", "s", "AST", ")", "then", "removes", "any", "import", "statement", "that", "imports", "this", "exact", "annotation", "(", "not", "star", "imports", ")", ".", ...
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/JavacHandlerUtil.java#L474-L476
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java
AdHocCommandManager.respondError
private static IQ respondError(AdHocCommandData response, StanzaError.Condition condition) { return respondError(response, StanzaError.getBuilder(condition)); }
java
private static IQ respondError(AdHocCommandData response, StanzaError.Condition condition) { return respondError(response, StanzaError.getBuilder(condition)); }
[ "private", "static", "IQ", "respondError", "(", "AdHocCommandData", "response", ",", "StanzaError", ".", "Condition", "condition", ")", "{", "return", "respondError", "(", "response", ",", "StanzaError", ".", "getBuilder", "(", "condition", ")", ")", ";", "}" ]
Responds an error with an specific condition. @param response the response to send. @param condition the condition of the error. @throws NotConnectedException
[ "Responds", "an", "error", "with", "an", "specific", "condition", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java#L568-L571
pryzach/midao
midao-jdbc-core/src/main/java/org/midao/jdbc/core/profiler/ProfilerFactory.java
ProfilerFactory.newInstance
public static Object newInstance(Object obj) { if (MjdbcLogger.isSLF4jAvailable() == true && MjdbcLogger.isSLF4jImplementationAvailable() == false) { // Logging depends on slf4j. If it haven't found any logging system // connected - it is turned off. // In such case there is no need to output profiling information as // it won't be printed out. return obj; } else { if (MjdbcConfig.isProfilerEnabled() == true) { return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new BaseInvocationHandler(obj, MjdbcConfig.getProfilerOutputFormat())); } else { return obj; } } }
java
public static Object newInstance(Object obj) { if (MjdbcLogger.isSLF4jAvailable() == true && MjdbcLogger.isSLF4jImplementationAvailable() == false) { // Logging depends on slf4j. If it haven't found any logging system // connected - it is turned off. // In such case there is no need to output profiling information as // it won't be printed out. return obj; } else { if (MjdbcConfig.isProfilerEnabled() == true) { return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new BaseInvocationHandler(obj, MjdbcConfig.getProfilerOutputFormat())); } else { return obj; } } }
[ "public", "static", "Object", "newInstance", "(", "Object", "obj", ")", "{", "if", "(", "MjdbcLogger", ".", "isSLF4jAvailable", "(", ")", "==", "true", "&&", "MjdbcLogger", ".", "isSLF4jImplementationAvailable", "(", ")", "==", "false", ")", "{", "// Logging d...
Function wraps Object into Profiling Java Proxy. Used to wrap QueryRunner instance with Java Proxy @param obj Object which would be wrapped into Profiling Proxy @return Java Proxy with wrapped input object
[ "Function", "wraps", "Object", "into", "Profiling", "Java", "Proxy", ".", "Used", "to", "wrap", "QueryRunner", "instance", "with", "Java", "Proxy" ]
train
https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/profiler/ProfilerFactory.java#L36-L52
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/io/async/AsyncSocketChannel.java
AsyncSocketChannel.prepareSocket
public synchronized void prepareSocket() throws IOException { if (!prepared) { final long fd = getFileDescriptor(); if (fd == INVALID_SOCKET) { throw new AsyncException(AsyncProperties.aio_handle_unavailable); } channelIdentifier = provider.prepare2(fd, asyncChannelGroup.getCompletionPort()); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "prepareSocket - socket prepared, fd = " + fd + " channel id: " + channelIdentifier + " " + ", local: " + channel.socket().getLocalSocketAddress() + ", remote: " + channel.socket().getRemoteSocketAddress()); } long callid = 0; // init to zero, reset when IO requested readIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get(); if (readIOCB != null) { // initialize the IOCB from the pool readIOCB.initializePoolEntry(channelIdentifier, callid); writeIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get(); if (writeIOCB != null) { // initialize the IOCB from the pool writeIOCB.initializePoolEntry(channelIdentifier, callid); } else { writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount); } } else { readIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount); writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount); } provider.initializeIOCB(readIOCB); provider.initializeIOCB(writeIOCB); prepared = true; } }
java
public synchronized void prepareSocket() throws IOException { if (!prepared) { final long fd = getFileDescriptor(); if (fd == INVALID_SOCKET) { throw new AsyncException(AsyncProperties.aio_handle_unavailable); } channelIdentifier = provider.prepare2(fd, asyncChannelGroup.getCompletionPort()); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "prepareSocket - socket prepared, fd = " + fd + " channel id: " + channelIdentifier + " " + ", local: " + channel.socket().getLocalSocketAddress() + ", remote: " + channel.socket().getRemoteSocketAddress()); } long callid = 0; // init to zero, reset when IO requested readIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get(); if (readIOCB != null) { // initialize the IOCB from the pool readIOCB.initializePoolEntry(channelIdentifier, callid); writeIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get(); if (writeIOCB != null) { // initialize the IOCB from the pool writeIOCB.initializePoolEntry(channelIdentifier, callid); } else { writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount); } } else { readIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount); writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount); } provider.initializeIOCB(readIOCB); provider.initializeIOCB(writeIOCB); prepared = true; } }
[ "public", "synchronized", "void", "prepareSocket", "(", ")", "throws", "IOException", "{", "if", "(", "!", "prepared", ")", "{", "final", "long", "fd", "=", "getFileDescriptor", "(", ")", ";", "if", "(", "fd", "==", "INVALID_SOCKET", ")", "{", "throw", "...
Perform initialization steps for this new connection. @throws IOException
[ "Perform", "initialization", "steps", "for", "this", "new", "connection", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/io/async/AsyncSocketChannel.java#L349-L387
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypeReferenceBuilder.java
JvmTypeReferenceBuilder.typeRef
public JvmTypeReference typeRef(JvmType type, JvmTypeReference... typeArgs) { int typeParams = 0; if (type instanceof JvmGenericType) { typeParams = ((JvmGenericType) type).getTypeParameters().size(); } if (typeParams < typeArgs.length) { throw new IllegalArgumentException("The type "+type.getIdentifier()+" only declares "+typeParams+" type parameters. You passed "+typeArgs.length+"."); } LightweightTypeReference reference = typeReferenceOwner.toPlainTypeReference(type); for (JvmTypeReference jvmTypeReference : typeArgs) { ((ParameterizedTypeReference)reference).addTypeArgument(typeReferenceOwner.toLightweightTypeReference(jvmTypeReference)); } return reference.toJavaCompliantTypeReference(); }
java
public JvmTypeReference typeRef(JvmType type, JvmTypeReference... typeArgs) { int typeParams = 0; if (type instanceof JvmGenericType) { typeParams = ((JvmGenericType) type).getTypeParameters().size(); } if (typeParams < typeArgs.length) { throw new IllegalArgumentException("The type "+type.getIdentifier()+" only declares "+typeParams+" type parameters. You passed "+typeArgs.length+"."); } LightweightTypeReference reference = typeReferenceOwner.toPlainTypeReference(type); for (JvmTypeReference jvmTypeReference : typeArgs) { ((ParameterizedTypeReference)reference).addTypeArgument(typeReferenceOwner.toLightweightTypeReference(jvmTypeReference)); } return reference.toJavaCompliantTypeReference(); }
[ "public", "JvmTypeReference", "typeRef", "(", "JvmType", "type", ",", "JvmTypeReference", "...", "typeArgs", ")", "{", "int", "typeParams", "=", "0", ";", "if", "(", "type", "instanceof", "JvmGenericType", ")", "{", "typeParams", "=", "(", "(", "JvmGenericType...
Creates a new {@link JvmTypeReference} pointing to the given class and containing the given type arguments. @param type the type the reference shall point to. @param typeArgs type arguments @return the newly created {@link JvmTypeReference}
[ "Creates", "a", "new", "{", "@link", "JvmTypeReference", "}", "pointing", "to", "the", "given", "class", "and", "containing", "the", "given", "type", "arguments", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypeReferenceBuilder.java#L104-L117
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java
FeatureScopes.createStaticFeaturesScope
protected IScope createStaticFeaturesScope(EObject featureCall, IScope parent, IFeatureScopeSession session) { return new StaticImportsScope(parent, session, asAbstractFeatureCall(featureCall)); }
java
protected IScope createStaticFeaturesScope(EObject featureCall, IScope parent, IFeatureScopeSession session) { return new StaticImportsScope(parent, session, asAbstractFeatureCall(featureCall)); }
[ "protected", "IScope", "createStaticFeaturesScope", "(", "EObject", "featureCall", ",", "IScope", "parent", ",", "IFeatureScopeSession", "session", ")", "{", "return", "new", "StaticImportsScope", "(", "parent", ",", "session", ",", "asAbstractFeatureCall", "(", "feat...
Creates a scope for the statically imported features. @param featureCall the feature call that is currently processed by the scoping infrastructure @param parent the parent scope. Is never null. @param session the currently known scope session. Is never null.
[ "Creates", "a", "scope", "for", "the", "statically", "imported", "features", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java#L616-L618
landawn/AbacusUtil
src/com/landawn/abacus/util/StringUtil.java
StringUtil.removeEnd
public static String removeEnd(final String str, final String removeStr) { if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) { return str; } if (str.endsWith(removeStr)) { return str.substring(0, str.length() - removeStr.length()); } return str; }
java
public static String removeEnd(final String str, final String removeStr) { if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) { return str; } if (str.endsWith(removeStr)) { return str.substring(0, str.length() - removeStr.length()); } return str; }
[ "public", "static", "String", "removeEnd", "(", "final", "String", "str", ",", "final", "String", "removeStr", ")", "{", "if", "(", "N", ".", "isNullOrEmpty", "(", "str", ")", "||", "N", ".", "isNullOrEmpty", "(", "removeStr", ")", ")", "{", "return", ...
<p> Removes a substring only if it is at the end of a source string, otherwise returns the source string. </p> <p> A {@code null} source string will return {@code null}. An empty ("") source string will return the empty string. A {@code null} search string will return the source string. </p> <pre> N.removeEnd(null, *) = null N.removeEnd("", *) = "" N.removeEnd(*, null) = * N.removeEnd("www.domain.com", ".com.") = "www.domain.com" N.removeEnd("www.domain.com", ".com") = "www.domain" N.removeEnd("www.domain.com", "domain") = "www.domain.com" N.removeEnd("abc", "") = "abc" </pre> @param str the source String to search, may be null @param removeStr the String to search for and remove, may be null @return the substring with the string removed if found, {@code null} if null String input @since 2.1
[ "<p", ">", "Removes", "a", "substring", "only", "if", "it", "is", "at", "the", "end", "of", "a", "source", "string", "otherwise", "returns", "the", "source", "string", ".", "<", "/", "p", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/StringUtil.java#L1233-L1243
Ordinastie/MalisisCore
src/main/java/net/malisis/core/util/chunkcollision/ChunkCollision.java
ChunkCollision.replaceBlocks
public void replaceBlocks(World world, MBlockState state) { AxisAlignedBB[] aabbs = AABBUtils.getCollisionBoundingBoxes(world, state, true); for (AxisAlignedBB aabb : aabbs) { if (aabb == null) continue; for (BlockPos pos : BlockPosUtils.getAllInBox(aabb)) { if (world.getBlockState(pos).getBlock().isReplaceable(world, pos)) world.setBlockToAir(pos); } } }
java
public void replaceBlocks(World world, MBlockState state) { AxisAlignedBB[] aabbs = AABBUtils.getCollisionBoundingBoxes(world, state, true); for (AxisAlignedBB aabb : aabbs) { if (aabb == null) continue; for (BlockPos pos : BlockPosUtils.getAllInBox(aabb)) { if (world.getBlockState(pos).getBlock().isReplaceable(world, pos)) world.setBlockToAir(pos); } } }
[ "public", "void", "replaceBlocks", "(", "World", "world", ",", "MBlockState", "state", ")", "{", "AxisAlignedBB", "[", "]", "aabbs", "=", "AABBUtils", ".", "getCollisionBoundingBoxes", "(", "world", ",", "state", ",", "true", ")", ";", "for", "(", "AxisAlign...
Replaces to air all the blocks colliding with the {@link AxisAlignedBB} of the {@link MBlockState}. @param world the world @param state the state
[ "Replaces", "to", "air", "all", "the", "blocks", "colliding", "with", "the", "{", "@link", "AxisAlignedBB", "}", "of", "the", "{", "@link", "MBlockState", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/chunkcollision/ChunkCollision.java#L266-L280
square/dagger
compiler/src/main/java/dagger/internal/codegen/GraphAnalysisLoader.java
GraphAnalysisLoader.nextDollar
private static int nextDollar(String className, CharSequence current, int searchStart) { while (true) { int index = className.indexOf('$', searchStart); if (index == -1) { return -1; } // We'll never have two dots nor will a type name end or begin with dot. So no need to // consider dollars at the beginning, end, or adjacent to dots. if (index == 0 || index == className.length() - 1 || current.charAt(index - 1) == '.' || current.charAt(index + 1) == '.') { searchStart = index + 1; continue; } return index; } }
java
private static int nextDollar(String className, CharSequence current, int searchStart) { while (true) { int index = className.indexOf('$', searchStart); if (index == -1) { return -1; } // We'll never have two dots nor will a type name end or begin with dot. So no need to // consider dollars at the beginning, end, or adjacent to dots. if (index == 0 || index == className.length() - 1 || current.charAt(index - 1) == '.' || current.charAt(index + 1) == '.') { searchStart = index + 1; continue; } return index; } }
[ "private", "static", "int", "nextDollar", "(", "String", "className", ",", "CharSequence", "current", ",", "int", "searchStart", ")", "{", "while", "(", "true", ")", "{", "int", "index", "=", "className", ".", "indexOf", "(", "'", "'", ",", "searchStart", ...
Finds the next {@code '$'} in a class name which can be changed to a {@code '.'} when computing a canonical class name.
[ "Finds", "the", "next", "{" ]
train
https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/compiler/src/main/java/dagger/internal/codegen/GraphAnalysisLoader.java#L108-L123
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/lang/EnumHelper.java
EnumHelper.getFromIDOrDefault
@Nullable public static <KEYTYPE, ENUMTYPE extends Enum <ENUMTYPE> & IHasID <KEYTYPE>> ENUMTYPE getFromIDOrDefault (@Nonnull final Class <ENUMTYPE> aClass, @Nullable final KEYTYPE aID, @Nullable final ENUMTYPE eDefault) { ValueEnforcer.notNull (aClass, "Class"); if (aID == null) return eDefault; return findFirst (aClass, x -> x.getID ().equals (aID), eDefault); }
java
@Nullable public static <KEYTYPE, ENUMTYPE extends Enum <ENUMTYPE> & IHasID <KEYTYPE>> ENUMTYPE getFromIDOrDefault (@Nonnull final Class <ENUMTYPE> aClass, @Nullable final KEYTYPE aID, @Nullable final ENUMTYPE eDefault) { ValueEnforcer.notNull (aClass, "Class"); if (aID == null) return eDefault; return findFirst (aClass, x -> x.getID ().equals (aID), eDefault); }
[ "@", "Nullable", "public", "static", "<", "KEYTYPE", ",", "ENUMTYPE", "extends", "Enum", "<", "ENUMTYPE", ">", "&", "IHasID", "<", "KEYTYPE", ">", ">", "ENUMTYPE", "getFromIDOrDefault", "(", "@", "Nonnull", "final", "Class", "<", "ENUMTYPE", ">", "aClass", ...
Get the enum value with the passed ID @param <KEYTYPE> The ID type @param <ENUMTYPE> The enum type @param aClass The enum class @param aID The ID to search @param eDefault The default value to be returned, if the ID was not found. @return The default parameter if no enum item with the given ID is present.
[ "Get", "the", "enum", "value", "with", "the", "passed", "ID" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/EnumHelper.java#L123-L133
looly/hutool
hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java
ThreadUtil.newThread
public static Thread newThread(Runnable runnable, String name, boolean isDeamon) { final Thread t = new Thread(null, runnable, name); t.setDaemon(isDeamon); return t; }
java
public static Thread newThread(Runnable runnable, String name, boolean isDeamon) { final Thread t = new Thread(null, runnable, name); t.setDaemon(isDeamon); return t; }
[ "public", "static", "Thread", "newThread", "(", "Runnable", "runnable", ",", "String", "name", ",", "boolean", "isDeamon", ")", "{", "final", "Thread", "t", "=", "new", "Thread", "(", "null", ",", "runnable", ",", "name", ")", ";", "t", ".", "setDaemon",...
创建新线程 @param runnable {@link Runnable} @param name 线程名 @param isDeamon 是否守护线程 @return {@link Thread} @since 4.1.2
[ "创建新线程" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java#L196-L200
samskivert/pythagoras
src/main/java/pythagoras/f/Points.java
Points.epsilonEquals
public static boolean epsilonEquals (IPoint p1, IPoint p2, float epsilon) { return Math.abs(p1.x() - p2.x()) < epsilon && Math.abs(p1.y() - p2.y()) < epsilon; }
java
public static boolean epsilonEquals (IPoint p1, IPoint p2, float epsilon) { return Math.abs(p1.x() - p2.x()) < epsilon && Math.abs(p1.y() - p2.y()) < epsilon; }
[ "public", "static", "boolean", "epsilonEquals", "(", "IPoint", "p1", ",", "IPoint", "p2", ",", "float", "epsilon", ")", "{", "return", "Math", ".", "abs", "(", "p1", ".", "x", "(", ")", "-", "p2", ".", "x", "(", ")", ")", "<", "epsilon", "&&", "M...
Returns true if the supplied points' x and y components are equal to one another within {@code epsilon}.
[ "Returns", "true", "if", "the", "supplied", "points", "x", "and", "y", "components", "are", "equal", "to", "one", "another", "within", "{" ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Points.java#L43-L45
JodaOrg/joda-time-jsptags
src/main/java/org/joda/time/contrib/jsptag/Util.java
Util.findFormattingMatch
private static Locale findFormattingMatch(Locale pref, Locale[] avail) { Locale match = null; boolean langAndCountryMatch = false; for (int i = 0; i < avail.length; i++) { if (pref.equals(avail[i])) { // Exact match match = avail[i]; break; } else if (!"".equals(pref.getVariant()) && "".equals(avail[i].getVariant()) && pref.getLanguage().equals(avail[i].getLanguage()) && pref.getCountry().equals(avail[i].getCountry())) { // Language and country match; different variant match = avail[i]; langAndCountryMatch = true; } else if (!langAndCountryMatch && pref.getLanguage().equals(avail[i].getLanguage()) && ("".equals(avail[i].getCountry()))) { // Language match if (match == null) { match = avail[i]; } } } return match; }
java
private static Locale findFormattingMatch(Locale pref, Locale[] avail) { Locale match = null; boolean langAndCountryMatch = false; for (int i = 0; i < avail.length; i++) { if (pref.equals(avail[i])) { // Exact match match = avail[i]; break; } else if (!"".equals(pref.getVariant()) && "".equals(avail[i].getVariant()) && pref.getLanguage().equals(avail[i].getLanguage()) && pref.getCountry().equals(avail[i].getCountry())) { // Language and country match; different variant match = avail[i]; langAndCountryMatch = true; } else if (!langAndCountryMatch && pref.getLanguage().equals(avail[i].getLanguage()) && ("".equals(avail[i].getCountry()))) { // Language match if (match == null) { match = avail[i]; } } } return match; }
[ "private", "static", "Locale", "findFormattingMatch", "(", "Locale", "pref", ",", "Locale", "[", "]", "avail", ")", "{", "Locale", "match", "=", "null", ";", "boolean", "langAndCountryMatch", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i",...
Returns the best match between the given preferred locale and the given available locales. The best match is given as the first available locale that exactly matches the given preferred locale ("exact match"). If no exact match exists, the best match is given to an available locale that meets the following criteria (in order of priority): - available locale's variant is empty and exact match for both language and country - available locale's variant and country are empty, and exact match for language. @param pref the preferred locale @param avail the available formatting locales @return Available locale that best matches the given preferred locale, or <tt>null</tt> if no match exists
[ "Returns", "the", "best", "match", "between", "the", "given", "preferred", "locale", "and", "the", "given", "available", "locales", "." ]
train
https://github.com/JodaOrg/joda-time-jsptags/blob/69008a813568cb6f3e37ea7a80f8b1f2070edf14/src/main/java/org/joda/time/contrib/jsptag/Util.java#L406-L431
duracloud/duracloud
common/src/main/java/org/duracloud/common/util/IOUtil.java
IOUtil.addFileToZipOutputStream
public static void addFileToZipOutputStream(File file, ZipOutputStream zipOs) throws IOException { String fileName = file.getName(); try (FileInputStream fos = new FileInputStream(file)) { ZipEntry zipEntry = new ZipEntry(fileName); zipEntry.setSize(file.length()); zipEntry.setTime(System.currentTimeMillis()); zipOs.putNextEntry(zipEntry); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = fos.read(buf)) > 0) { zipOs.write(buf, 0, bytesRead); } zipOs.closeEntry(); fos.close(); } }
java
public static void addFileToZipOutputStream(File file, ZipOutputStream zipOs) throws IOException { String fileName = file.getName(); try (FileInputStream fos = new FileInputStream(file)) { ZipEntry zipEntry = new ZipEntry(fileName); zipEntry.setSize(file.length()); zipEntry.setTime(System.currentTimeMillis()); zipOs.putNextEntry(zipEntry); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = fos.read(buf)) > 0) { zipOs.write(buf, 0, bytesRead); } zipOs.closeEntry(); fos.close(); } }
[ "public", "static", "void", "addFileToZipOutputStream", "(", "File", "file", ",", "ZipOutputStream", "zipOs", ")", "throws", "IOException", "{", "String", "fileName", "=", "file", ".", "getName", "(", ")", ";", "try", "(", "FileInputStream", "fos", "=", "new",...
Adds the specified file to the zip output stream. @param file @param zipOs
[ "Adds", "the", "specified", "file", "to", "the", "zip", "output", "stream", "." ]
train
https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/common/src/main/java/org/duracloud/common/util/IOUtil.java#L140-L155
auth0/Auth0.Android
auth0/src/main/java/com/auth0/android/authentication/request/SignUpRequest.java
SignUpRequest.addAuthenticationParameters
@Override public SignUpRequest addAuthenticationParameters(Map<String, Object> parameters) { authenticationRequest.addAuthenticationParameters(parameters); return this; }
java
@Override public SignUpRequest addAuthenticationParameters(Map<String, Object> parameters) { authenticationRequest.addAuthenticationParameters(parameters); return this; }
[ "@", "Override", "public", "SignUpRequest", "addAuthenticationParameters", "(", "Map", "<", "String", ",", "Object", ">", "parameters", ")", "{", "authenticationRequest", ".", "addAuthenticationParameters", "(", "parameters", ")", ";", "return", "this", ";", "}" ]
Add additional parameters sent when logging the user in @param parameters sent with the request and must be non-null @return itself @see ParameterBuilder
[ "Add", "additional", "parameters", "sent", "when", "logging", "the", "user", "in" ]
train
https://github.com/auth0/Auth0.Android/blob/ee37b7f94d989c1fbab2cb1378c87fdcaf7a8156/auth0/src/main/java/com/auth0/android/authentication/request/SignUpRequest.java#L88-L92
MenoData/Time4J
base/src/main/java/net/time4j/tz/model/GregorianTimezoneRule.java
GregorianTimezoneRule.ofWeekdayAfterDate
public static GregorianTimezoneRule ofWeekdayAfterDate( Month month, int dayOfMonth, Weekday dayOfWeek, int timeOfDay, OffsetIndicator indicator, int savings ) { return new DayOfWeekInMonthPattern(month, dayOfMonth, dayOfWeek, timeOfDay, indicator, savings, true); }
java
public static GregorianTimezoneRule ofWeekdayAfterDate( Month month, int dayOfMonth, Weekday dayOfWeek, int timeOfDay, OffsetIndicator indicator, int savings ) { return new DayOfWeekInMonthPattern(month, dayOfMonth, dayOfWeek, timeOfDay, indicator, savings, true); }
[ "public", "static", "GregorianTimezoneRule", "ofWeekdayAfterDate", "(", "Month", "month", ",", "int", "dayOfMonth", ",", "Weekday", "dayOfWeek", ",", "int", "timeOfDay", ",", "OffsetIndicator", "indicator", ",", "int", "savings", ")", "{", "return", "new", "DayOfW...
/*[deutsch] <p>Konstruiert ein Muster f&uuml;r einen Wochentag nach einem festen Monatstag im angegebenen Monat. </p> <p>Beispiel =&gt; F&uuml;r den zweiten Sonntag im April sei zu setzen: {@code month=APRIL, dayOfMonth=8, dayOfWeek=SUNDAY}. </p> @param month calendar month @param dayOfMonth reference day of month (1 - 31) @param dayOfWeek day of week when time switch happens @param timeOfDay clock time in seconds after midnight when time switch happens @param indicator offset indicator @param savings fixed DST-offset in seconds @return new daylight saving rule @throws IllegalArgumentException if the last argument is out of range or if the day of month is not valid in context of given month @since 5.0
[ "/", "*", "[", "deutsch", "]", "<p", ">", "Konstruiert", "ein", "Muster", "f&uuml", ";", "r", "einen", "Wochentag", "nach", "einem", "festen", "Monatstag", "im", "angegebenen", "Monat", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/tz/model/GregorianTimezoneRule.java#L336-L347
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/distort/mls/ImageDeformPointMLS_F32.java
ImageDeformPointMLS_F32.setUndistorted
public void setUndistorted(int which, float x, float y) { if( scaleX <= 0 || scaleY <= 0 ) throw new IllegalArgumentException("Must call configure first"); controls.get(which).p.set(x/scaleX,y/scaleY); }
java
public void setUndistorted(int which, float x, float y) { if( scaleX <= 0 || scaleY <= 0 ) throw new IllegalArgumentException("Must call configure first"); controls.get(which).p.set(x/scaleX,y/scaleY); }
[ "public", "void", "setUndistorted", "(", "int", "which", ",", "float", "x", ",", "float", "y", ")", "{", "if", "(", "scaleX", "<=", "0", "||", "scaleY", "<=", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Must call configure first\"", ")", ...
Sets the location of a control point. @param x coordinate x-axis in image pixels @param y coordinate y-axis in image pixels
[ "Sets", "the", "location", "of", "a", "control", "point", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/distort/mls/ImageDeformPointMLS_F32.java#L149-L154
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.pages_isFan
public boolean pages_isFan(Long pageId, Integer userId) throws FacebookException, IOException { return extractBoolean(this.callMethod(FacebookMethod.PAGES_IS_FAN, new Pair<String,CharSequence>("page_id", pageId.toString()), new Pair<String,CharSequence>("uid", userId.toString()))); }
java
public boolean pages_isFan(Long pageId, Integer userId) throws FacebookException, IOException { return extractBoolean(this.callMethod(FacebookMethod.PAGES_IS_FAN, new Pair<String,CharSequence>("page_id", pageId.toString()), new Pair<String,CharSequence>("uid", userId.toString()))); }
[ "public", "boolean", "pages_isFan", "(", "Long", "pageId", ",", "Integer", "userId", ")", "throws", "FacebookException", ",", "IOException", "{", "return", "extractBoolean", "(", "this", ".", "callMethod", "(", "FacebookMethod", ".", "PAGES_IS_FAN", ",", "new", ...
Checks whether a user is a fan of the page with the given <code>pageId</code>. @param pageId the ID of the page @param userId the ID of the user (defaults to the logged-in user if null) @return true if the user is a fan of the page @see <a href="http://wiki.developers.facebook.com/index.php/Pages.isFan"> Developers Wiki: Pages.isFan</a>
[ "Checks", "whether", "a", "user", "is", "a", "fan", "of", "the", "page", "with", "the", "given", "<code", ">", "pageId<", "/", "code", ">", "." ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L2186-L2191
zxing/zxing
core/src/main/java/com/google/zxing/aztec/detector/Detector.java
Detector.sampleLine
private int sampleLine(ResultPoint p1, ResultPoint p2, int size) { int result = 0; float d = distance(p1, p2); float moduleSize = d / size; float px = p1.getX(); float py = p1.getY(); float dx = moduleSize * (p2.getX() - p1.getX()) / d; float dy = moduleSize * (p2.getY() - p1.getY()) / d; for (int i = 0; i < size; i++) { if (image.get(MathUtils.round(px + i * dx), MathUtils.round(py + i * dy))) { result |= 1 << (size - i - 1); } } return result; }
java
private int sampleLine(ResultPoint p1, ResultPoint p2, int size) { int result = 0; float d = distance(p1, p2); float moduleSize = d / size; float px = p1.getX(); float py = p1.getY(); float dx = moduleSize * (p2.getX() - p1.getX()) / d; float dy = moduleSize * (p2.getY() - p1.getY()) / d; for (int i = 0; i < size; i++) { if (image.get(MathUtils.round(px + i * dx), MathUtils.round(py + i * dy))) { result |= 1 << (size - i - 1); } } return result; }
[ "private", "int", "sampleLine", "(", "ResultPoint", "p1", ",", "ResultPoint", "p2", ",", "int", "size", ")", "{", "int", "result", "=", "0", ";", "float", "d", "=", "distance", "(", "p1", ",", "p2", ")", ";", "float", "moduleSize", "=", "d", "/", "...
Samples a line. @param p1 start point (inclusive) @param p2 end point (exclusive) @param size number of bits @return the array of bits as an int (first bit is high-order bit of result)
[ "Samples", "a", "line", "." ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/aztec/detector/Detector.java#L400-L415
mapfish/mapfish-print
core/src/main/java/org/mapfish/print/config/S3ReportStorage.java
S3ReportStorage.getKey
protected String getKey(final String ref, final String filename, final String extension) { return prefix + ref + "/" + filename + "." + extension; }
java
protected String getKey(final String ref, final String filename, final String extension) { return prefix + ref + "/" + filename + "." + extension; }
[ "protected", "String", "getKey", "(", "final", "String", "ref", ",", "final", "String", "filename", ",", "final", "String", "extension", ")", "{", "return", "prefix", "+", "ref", "+", "\"/\"", "+", "filename", "+", "\".\"", "+", "extension", ";", "}" ]
Compute the key to use. @param ref The reference number. @param filename The filename. @param extension The file extension.
[ "Compute", "the", "key", "to", "use", "." ]
train
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/config/S3ReportStorage.java#L125-L127
javamonkey/beetl2.0
beetl-core/src/main/java/org/beetl/core/om/ObjectUtil.java
ObjectUtil.invokeStatic
public static Object invokeStatic(Class target, String methodName, Object[] paras) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { return invoke(target, null, methodName, paras); }
java
public static Object invokeStatic(Class target, String methodName, Object[] paras) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { return invoke(target, null, methodName, paras); }
[ "public", "static", "Object", "invokeStatic", "(", "Class", "target", ",", "String", "methodName", ",", "Object", "[", "]", "paras", ")", "throws", "IllegalAccessException", ",", "IllegalArgumentException", ",", "InvocationTargetException", "{", "return", "invoke", ...
调用类的静态方法,只知道方法名和参数,beetl将自动匹配到能调用的方法 @param target @param methodName @param paras @return @throws IllegalAccessException @throws IllegalArgumentException @throws InvocationTargetException
[ "调用类的静态方法,只知道方法名和参数,beetl将自动匹配到能调用的方法" ]
train
https://github.com/javamonkey/beetl2.0/blob/f32f729ad238079df5aca6e38a3c3ba0a55c78d6/beetl-core/src/main/java/org/beetl/core/om/ObjectUtil.java#L522-L527
oboehm/jfachwert
src/main/java/de/jfachwert/bank/Geldbetrag.java
Geldbetrag.valueOf
public static Geldbetrag valueOf(Number value, CurrencyUnit currency) { return valueOf(new Geldbetrag(value, currency)); }
java
public static Geldbetrag valueOf(Number value, CurrencyUnit currency) { return valueOf(new Geldbetrag(value, currency)); }
[ "public", "static", "Geldbetrag", "valueOf", "(", "Number", "value", ",", "CurrencyUnit", "currency", ")", "{", "return", "valueOf", "(", "new", "Geldbetrag", "(", "value", ",", "currency", ")", ")", ";", "}" ]
Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine neues Objekt erzeugt, wenn es sich nicht vermeiden laesst. <p> In Anlehnung an {@link BigDecimal} heisst die Methode "valueOf". </p> @param value Wert des andere Geldbetrags @param currency Waehrung des anderen Geldbetrags @return ein Geldbetrag
[ "Wandelt", "den", "angegebenen", "MonetaryAmount", "in", "einen", "Geldbetrag", "um", ".", "Um", "die", "Anzahl", "von", "Objekten", "gering", "zu", "halten", "wird", "nur", "dann", "tatsaechlich", "eine", "neues", "Objekt", "erzeugt", "wenn", "es", "sich", "n...
train
https://github.com/oboehm/jfachwert/blob/67b513d29e3114c7aee65cd1ea7a5b7e540b0d1b/src/main/java/de/jfachwert/bank/Geldbetrag.java#L398-L400
Red5/red5-client
src/main/java/org/red5/client/net/rtmpe/RTMPEIoFilter.java
RTMPEIoFilter.completeConnection
private static void completeConnection(IoSession session, RTMPMinaConnection conn, RTMP rtmp, OutboundHandshake handshake) { if (handshake.useEncryption()) { // set encryption flag the rtmp state rtmp.setEncrypted(true); // add the ciphers log.debug("Adding ciphers to the session"); session.setAttribute(RTMPConnection.RTMPE_CIPHER_IN, handshake.getCipherIn()); session.setAttribute(RTMPConnection.RTMPE_CIPHER_OUT, handshake.getCipherOut()); } // set state to indicate we're connected conn.getState().setState(RTMP.STATE_CONNECTED); log.debug("Connected, removing handshake data"); // remove handshake from session now that we are connected session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE); // add protocol filter as the last one in the chain log.debug("Adding RTMP protocol filter"); session.getFilterChain().addAfter("rtmpeFilter", "protocolFilter", new ProtocolCodecFilter(new RTMPMinaCodecFactory())); // get the rtmp handler BaseRTMPClientHandler handler = (BaseRTMPClientHandler) session.getAttribute(RTMPConnection.RTMP_HANDLER); handler.connectionOpened(conn); }
java
private static void completeConnection(IoSession session, RTMPMinaConnection conn, RTMP rtmp, OutboundHandshake handshake) { if (handshake.useEncryption()) { // set encryption flag the rtmp state rtmp.setEncrypted(true); // add the ciphers log.debug("Adding ciphers to the session"); session.setAttribute(RTMPConnection.RTMPE_CIPHER_IN, handshake.getCipherIn()); session.setAttribute(RTMPConnection.RTMPE_CIPHER_OUT, handshake.getCipherOut()); } // set state to indicate we're connected conn.getState().setState(RTMP.STATE_CONNECTED); log.debug("Connected, removing handshake data"); // remove handshake from session now that we are connected session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE); // add protocol filter as the last one in the chain log.debug("Adding RTMP protocol filter"); session.getFilterChain().addAfter("rtmpeFilter", "protocolFilter", new ProtocolCodecFilter(new RTMPMinaCodecFactory())); // get the rtmp handler BaseRTMPClientHandler handler = (BaseRTMPClientHandler) session.getAttribute(RTMPConnection.RTMP_HANDLER); handler.connectionOpened(conn); }
[ "private", "static", "void", "completeConnection", "(", "IoSession", "session", ",", "RTMPMinaConnection", "conn", ",", "RTMP", "rtmp", ",", "OutboundHandshake", "handshake", ")", "{", "if", "(", "handshake", ".", "useEncryption", "(", ")", ")", "{", "// set enc...
Provides connection completion. @param session @param conn @param rtmp @param handshake
[ "Provides", "connection", "completion", "." ]
train
https://github.com/Red5/red5-client/blob/f894495b60e59d7cfba647abd9b934237cac9d45/src/main/java/org/red5/client/net/rtmpe/RTMPEIoFilter.java#L206-L226
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/DelegatingDecompressorFrameListener.java
DelegatingDecompressorFrameListener.newContentDecompressor
protected EmbeddedChannel newContentDecompressor(final ChannelHandlerContext ctx, CharSequence contentEncoding) throws Http2Exception { if (GZIP.contentEqualsIgnoreCase(contentEncoding) || X_GZIP.contentEqualsIgnoreCase(contentEncoding)) { return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); } if (DEFLATE.contentEqualsIgnoreCase(contentEncoding) || X_DEFLATE.contentEqualsIgnoreCase(contentEncoding)) { final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE; // To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly. return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(wrapper)); } // 'identity' or unsupported return null; }
java
protected EmbeddedChannel newContentDecompressor(final ChannelHandlerContext ctx, CharSequence contentEncoding) throws Http2Exception { if (GZIP.contentEqualsIgnoreCase(contentEncoding) || X_GZIP.contentEqualsIgnoreCase(contentEncoding)) { return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); } if (DEFLATE.contentEqualsIgnoreCase(contentEncoding) || X_DEFLATE.contentEqualsIgnoreCase(contentEncoding)) { final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE; // To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly. return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(wrapper)); } // 'identity' or unsupported return null; }
[ "protected", "EmbeddedChannel", "newContentDecompressor", "(", "final", "ChannelHandlerContext", "ctx", ",", "CharSequence", "contentEncoding", ")", "throws", "Http2Exception", "{", "if", "(", "GZIP", ".", "contentEqualsIgnoreCase", "(", "contentEncoding", ")", "||", "X...
Returns a new {@link EmbeddedChannel} that decodes the HTTP2 message content encoded in the specified {@code contentEncoding}. @param contentEncoding the value of the {@code content-encoding} header @return a new {@link ByteToMessageDecoder} if the specified encoding is supported. {@code null} otherwise (alternatively, you can throw a {@link Http2Exception} to block unknown encoding). @throws Http2Exception If the specified encoding is not not supported and warrants an exception
[ "Returns", "a", "new", "{", "@link", "EmbeddedChannel", "}", "that", "decodes", "the", "HTTP2", "message", "content", "encoded", "in", "the", "specified", "{", "@code", "contentEncoding", "}", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/DelegatingDecompressorFrameListener.java#L166-L180
grpc/grpc-java
examples/src/main/java/io/grpc/examples/routeguide/RouteGuideClient.java
RouteGuideClient.getFeature
public void getFeature(int lat, int lon) { info("*** GetFeature: lat={0} lon={1}", lat, lon); Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build(); Feature feature; try { feature = blockingStub.getFeature(request); if (testHelper != null) { testHelper.onMessage(feature); } } catch (StatusRuntimeException e) { warning("RPC failed: {0}", e.getStatus()); if (testHelper != null) { testHelper.onRpcError(e); } return; } if (RouteGuideUtil.exists(feature)) { info("Found feature called \"{0}\" at {1}, {2}", feature.getName(), RouteGuideUtil.getLatitude(feature.getLocation()), RouteGuideUtil.getLongitude(feature.getLocation())); } else { info("Found no feature at {0}, {1}", RouteGuideUtil.getLatitude(feature.getLocation()), RouteGuideUtil.getLongitude(feature.getLocation())); } }
java
public void getFeature(int lat, int lon) { info("*** GetFeature: lat={0} lon={1}", lat, lon); Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build(); Feature feature; try { feature = blockingStub.getFeature(request); if (testHelper != null) { testHelper.onMessage(feature); } } catch (StatusRuntimeException e) { warning("RPC failed: {0}", e.getStatus()); if (testHelper != null) { testHelper.onRpcError(e); } return; } if (RouteGuideUtil.exists(feature)) { info("Found feature called \"{0}\" at {1}, {2}", feature.getName(), RouteGuideUtil.getLatitude(feature.getLocation()), RouteGuideUtil.getLongitude(feature.getLocation())); } else { info("Found no feature at {0}, {1}", RouteGuideUtil.getLatitude(feature.getLocation()), RouteGuideUtil.getLongitude(feature.getLocation())); } }
[ "public", "void", "getFeature", "(", "int", "lat", ",", "int", "lon", ")", "{", "info", "(", "\"*** GetFeature: lat={0} lon={1}\"", ",", "lat", ",", "lon", ")", ";", "Point", "request", "=", "Point", ".", "newBuilder", "(", ")", ".", "setLatitude", "(", ...
Blocking unary call example. Calls getFeature and prints the response.
[ "Blocking", "unary", "call", "example", ".", "Calls", "getFeature", "and", "prints", "the", "response", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/examples/src/main/java/io/grpc/examples/routeguide/RouteGuideClient.java#L69-L97
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
HintRule.addAddVersion
public void addAddVersion(String source, String name, String value, Confidence confidence) { addVersion.add(new Evidence(source, name, value, confidence)); }
java
public void addAddVersion(String source, String name, String value, Confidence confidence) { addVersion.add(new Evidence(source, name, value, confidence)); }
[ "public", "void", "addAddVersion", "(", "String", "source", ",", "String", "name", ",", "String", "value", ",", "Confidence", "confidence", ")", "{", "addVersion", ".", "add", "(", "new", "Evidence", "(", "source", ",", "name", ",", "value", ",", "confiden...
Adds a given version to the list of evidence to add when matched. @param source the source of the evidence @param name the name of the evidence @param value the value of the evidence @param confidence the confidence of the evidence
[ "Adds", "a", "given", "version", "to", "the", "list", "of", "evidence", "to", "add", "when", "matched", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L170-L172
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java
XMLUtil.writeXML
public static void writeXML(Document xmldocument, String file) throws ParserConfigurationException, IOException { assert file != null : AssertMessages.notNullParameter(); try (FileOutputStream fos = new FileOutputStream(file)) { writeNode(xmldocument, fos); } }
java
public static void writeXML(Document xmldocument, String file) throws ParserConfigurationException, IOException { assert file != null : AssertMessages.notNullParameter(); try (FileOutputStream fos = new FileOutputStream(file)) { writeNode(xmldocument, fos); } }
[ "public", "static", "void", "writeXML", "(", "Document", "xmldocument", ",", "String", "file", ")", "throws", "ParserConfigurationException", ",", "IOException", "{", "assert", "file", "!=", "null", ":", "AssertMessages", ".", "notNullParameter", "(", ")", ";", ...
Write the given node tree into a XML file. @param xmldocument is the object that contains the node tree @param file is the file name. @throws IOException if the stream cannot be read. @throws ParserConfigurationException if the parser cannot be configured.
[ "Write", "the", "given", "node", "tree", "into", "a", "XML", "file", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L2377-L2382
DiUS/pact-jvm
pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java
PactDslJsonArray.stringMatcher
public PactDslJsonArray stringMatcher(String regex, String value) { if (!value.matches(regex)) { throw new InvalidMatcherException(EXAMPLE + value + "\" does not match regular expression \"" + regex + "\""); } body.put(value); matchers.addRule(rootPath + appendArrayIndex(0), regexp(regex)); return this; }
java
public PactDslJsonArray stringMatcher(String regex, String value) { if (!value.matches(regex)) { throw new InvalidMatcherException(EXAMPLE + value + "\" does not match regular expression \"" + regex + "\""); } body.put(value); matchers.addRule(rootPath + appendArrayIndex(0), regexp(regex)); return this; }
[ "public", "PactDslJsonArray", "stringMatcher", "(", "String", "regex", ",", "String", "value", ")", "{", "if", "(", "!", "value", ".", "matches", "(", "regex", ")", ")", "{", "throw", "new", "InvalidMatcherException", "(", "EXAMPLE", "+", "value", "+", "\"...
Element that must match the regular expression @param regex regular expression @param value example value to use for generated bodies
[ "Element", "that", "must", "match", "the", "regular", "expression" ]
train
https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java#L419-L427
OpenLiberty/open-liberty
dev/com.ibm.ws.microprofile.config.1.3/src/com/ibm/ws/microprofile/config13/sources/OSGiConfigUtils.java
OSGiConfigUtils.getApplicationPID
public static String getApplicationPID(BundleContext bundleContext, String applicationName) { String applicationPID = null; if (FrameworkState.isValid()) { ServiceReference<?> appRef = getApplicationServiceRef(bundleContext, applicationName); if (appRef != null) { //not actually sure what the difference is between service.pid and ibm.extends.source.pid but this is the way it is done everywhere else! applicationPID = (String) appRef.getProperty(Constants.SERVICE_PID); String sourcePid = (String) appRef.getProperty("ibm.extends.source.pid"); if (sourcePid != null) { applicationPID = sourcePid; } } } return applicationPID; }
java
public static String getApplicationPID(BundleContext bundleContext, String applicationName) { String applicationPID = null; if (FrameworkState.isValid()) { ServiceReference<?> appRef = getApplicationServiceRef(bundleContext, applicationName); if (appRef != null) { //not actually sure what the difference is between service.pid and ibm.extends.source.pid but this is the way it is done everywhere else! applicationPID = (String) appRef.getProperty(Constants.SERVICE_PID); String sourcePid = (String) appRef.getProperty("ibm.extends.source.pid"); if (sourcePid != null) { applicationPID = sourcePid; } } } return applicationPID; }
[ "public", "static", "String", "getApplicationPID", "(", "BundleContext", "bundleContext", ",", "String", "applicationName", ")", "{", "String", "applicationPID", "=", "null", ";", "if", "(", "FrameworkState", ".", "isValid", "(", ")", ")", "{", "ServiceReference",...
Get the internal OSGi identifier for the Application with the given name @param bundleContext The context to use to find the Application reference @param applicationName The application name to look for @return The application pid
[ "Get", "the", "internal", "OSGi", "identifier", "for", "the", "Application", "with", "the", "given", "name" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.config.1.3/src/com/ibm/ws/microprofile/config13/sources/OSGiConfigUtils.java#L192-L208
digipost/sdp-shared
api-commons/src/main/java/no/digipost/api/xml/MessagingMarshalling.java
MessagingMarshalling.getMessaging
public static Messaging getMessaging(final Jaxb2Marshaller jaxb2Marshaller, final WebServiceMessage message) { SoapHeader soapHeader = ((SoapMessage) message).getSoapHeader(); if (soapHeader == null) { throw new RuntimeException("The ebMS header is missing (no SOAP header found in SOAP request)"); } Iterator<SoapHeaderElement> soapHeaderElementIterator = soapHeader.examineHeaderElements(MESSAGING_QNAME); if (!soapHeaderElementIterator.hasNext()) { throw new RuntimeException("The ebMS header is missing in SOAP header"); } SoapHeaderElement incomingSoapHeaderElement = soapHeaderElementIterator.next(); try { return (Messaging) jaxb2Marshaller.unmarshal(incomingSoapHeaderElement.getSource()); } catch (Exception e) { throw new RuntimeException("The ebMs header failed to unmarshall"); } }
java
public static Messaging getMessaging(final Jaxb2Marshaller jaxb2Marshaller, final WebServiceMessage message) { SoapHeader soapHeader = ((SoapMessage) message).getSoapHeader(); if (soapHeader == null) { throw new RuntimeException("The ebMS header is missing (no SOAP header found in SOAP request)"); } Iterator<SoapHeaderElement> soapHeaderElementIterator = soapHeader.examineHeaderElements(MESSAGING_QNAME); if (!soapHeaderElementIterator.hasNext()) { throw new RuntimeException("The ebMS header is missing in SOAP header"); } SoapHeaderElement incomingSoapHeaderElement = soapHeaderElementIterator.next(); try { return (Messaging) jaxb2Marshaller.unmarshal(incomingSoapHeaderElement.getSource()); } catch (Exception e) { throw new RuntimeException("The ebMs header failed to unmarshall"); } }
[ "public", "static", "Messaging", "getMessaging", "(", "final", "Jaxb2Marshaller", "jaxb2Marshaller", ",", "final", "WebServiceMessage", "message", ")", "{", "SoapHeader", "soapHeader", "=", "(", "(", "SoapMessage", ")", "message", ")", ".", "getSoapHeader", "(", "...
Enten returnerer denne et Messaging objekt, eller så kaster den en RuntimeException
[ "Enten", "returnerer", "denne", "et", "Messaging", "objekt", "eller", "så", "kaster", "den", "en", "RuntimeException" ]
train
https://github.com/digipost/sdp-shared/blob/c34920a993b65ff0908dab9d9c92140ded7312bc/api-commons/src/main/java/no/digipost/api/xml/MessagingMarshalling.java#L19-L38
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/rng/distribution/impl/SaddlePointExpansion.java
SaddlePointExpansion.getDeviancePart
public static double getDeviancePart(double x, double mu) { double ret; if (FastMath.abs(x - mu) < 0.1 * (x + mu)) { double d = x - mu; double v = d / (x + mu); double s1 = v * d; double s = Double.NaN; double ej = 2.0 * x * v; v = v * v; int j = 1; while (s1 != s) { s = s1; ej *= v; s1 = s + ej / ((j * 2) + 1); ++j; } ret = s1; } else { ret = x * FastMath.log(x / mu) + mu - x; } return ret; }
java
public static double getDeviancePart(double x, double mu) { double ret; if (FastMath.abs(x - mu) < 0.1 * (x + mu)) { double d = x - mu; double v = d / (x + mu); double s1 = v * d; double s = Double.NaN; double ej = 2.0 * x * v; v = v * v; int j = 1; while (s1 != s) { s = s1; ej *= v; s1 = s + ej / ((j * 2) + 1); ++j; } ret = s1; } else { ret = x * FastMath.log(x / mu) + mu - x; } return ret; }
[ "public", "static", "double", "getDeviancePart", "(", "double", "x", ",", "double", "mu", ")", "{", "double", "ret", ";", "if", "(", "FastMath", ".", "abs", "(", "x", "-", "mu", ")", "<", "0.1", "*", "(", "x", "+", "mu", ")", ")", "{", "double", ...
A part of the deviance portion of the saddle point approximation. <p> References: <ol> <li>Catherine Loader (2000). "Fast and Accurate Computation of Binomial Probabilities.". <a target="_blank" href="http://www.herine.net/stat/papers/dbinom.pdf"> http://www.herine.net/stat/papers/dbinom.pdf</a></li> </ol> </p> @param x the x value. @param mu the average. @return a part of the deviance.
[ "A", "part", "of", "the", "deviance", "portion", "of", "the", "saddle", "point", "approximation", ".", "<p", ">", "References", ":", "<ol", ">", "<li", ">", "Catherine", "Loader", "(", "2000", ")", ".", "Fast", "and", "Accurate", "Computation", "of", "Bi...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/rng/distribution/impl/SaddlePointExpansion.java#L145-L166
threerings/narya
core/src/main/java/com/threerings/presents/dobj/DObject.java
DObject.requestOidRemove
protected void requestOidRemove (String name, OidList list, int oid) { // if we're on the authoritative server, we update the set immediately boolean applyImmediately = isAuthoritative(); if (applyImmediately) { list.remove(oid); } // dispatch an object removed event postEvent(new ObjectRemovedEvent(_oid, name, oid).setAlreadyApplied(applyImmediately)); }
java
protected void requestOidRemove (String name, OidList list, int oid) { // if we're on the authoritative server, we update the set immediately boolean applyImmediately = isAuthoritative(); if (applyImmediately) { list.remove(oid); } // dispatch an object removed event postEvent(new ObjectRemovedEvent(_oid, name, oid).setAlreadyApplied(applyImmediately)); }
[ "protected", "void", "requestOidRemove", "(", "String", "name", ",", "OidList", "list", ",", "int", "oid", ")", "{", "// if we're on the authoritative server, we update the set immediately", "boolean", "applyImmediately", "=", "isAuthoritative", "(", ")", ";", "if", "("...
Calls by derived instances when an oid remover method was called.
[ "Calls", "by", "derived", "instances", "when", "an", "oid", "remover", "method", "was", "called", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/dobj/DObject.java#L864-L873
opencb/biodata
biodata-tools/src/main/java/org/opencb/biodata/tools/variant/metadata/VariantMetadataManager.java
VariantMetadataManager.loadPedigree
public VariantMetadata loadPedigree(List<Pedigree> pedigrees, String studyId) { VariantMetadata variantMetadata = null; for(Pedigree pedigree: pedigrees) { variantMetadata = loadPedigree(pedigree, studyId); } return variantMetadata; }
java
public VariantMetadata loadPedigree(List<Pedigree> pedigrees, String studyId) { VariantMetadata variantMetadata = null; for(Pedigree pedigree: pedigrees) { variantMetadata = loadPedigree(pedigree, studyId); } return variantMetadata; }
[ "public", "VariantMetadata", "loadPedigree", "(", "List", "<", "Pedigree", ">", "pedigrees", ",", "String", "studyId", ")", "{", "VariantMetadata", "variantMetadata", "=", "null", ";", "for", "(", "Pedigree", "pedigree", ":", "pedigrees", ")", "{", "variantMetad...
Load a list of pedrigree objects into a given study (from its study ID). @param pedigrees List of Pedigree objects to load @param studyId Study ID related to that pedigrees @return Variant metadata object
[ "Load", "a", "list", "of", "pedrigree", "objects", "into", "a", "given", "study", "(", "from", "its", "study", "ID", ")", "." ]
train
https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/variant/metadata/VariantMetadataManager.java#L525-L531
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPChainer.java
AFPChainer.getRmsd
private static double getRmsd(Atom[] catmp1, Atom[] catmp2) throws StructureException{ Matrix4d trans = SuperPositions.superpose(Calc.atomsToPoints(catmp1), Calc.atomsToPoints(catmp2)); Calc.transform(catmp2, trans); // if ( showAlig) { // StructureAlignmentJmol jmol = new StructureAlignmentJmol(); // jmol.setTitle("AFPCHainer: getRmsd" + rmsd); // // Chain c1 = new ChainImpl(); // c1.setName("A"); // for ( Atom a : catmp1){ // c1.addGroup(a.getParent()); // } // // Chain c2 = new ChainImpl(); // c2.setName("B"); // for ( Atom a : catmp2){ // c2.addGroup(a.getParent()); // } // // Structure fake = new StructureImpl(); // fake.setPDBCode("AFPCHainer: getRmsd" + rmsd); // List<Chain> model1 = new ArrayList<Chain>(); // model1.add(c1); // List<Chain> model2 = new ArrayList<Chain>(); // model2.add(c2); // fake.addModel(model1); // fake.addModel(model2); // fake.setNmr(true); // // jmol.setStructure(fake); // jmol.evalString("select *; backbone 0.4; wireframe off; spacefill off; " + // "select not protein and not solvent; spacefill on;"); // jmol.evalString("select */1 ; color red; model 1; "); // // // now show both models again. // jmol.evalString("model 0;"); // } return Calc.rmsd(catmp1,catmp2); }
java
private static double getRmsd(Atom[] catmp1, Atom[] catmp2) throws StructureException{ Matrix4d trans = SuperPositions.superpose(Calc.atomsToPoints(catmp1), Calc.atomsToPoints(catmp2)); Calc.transform(catmp2, trans); // if ( showAlig) { // StructureAlignmentJmol jmol = new StructureAlignmentJmol(); // jmol.setTitle("AFPCHainer: getRmsd" + rmsd); // // Chain c1 = new ChainImpl(); // c1.setName("A"); // for ( Atom a : catmp1){ // c1.addGroup(a.getParent()); // } // // Chain c2 = new ChainImpl(); // c2.setName("B"); // for ( Atom a : catmp2){ // c2.addGroup(a.getParent()); // } // // Structure fake = new StructureImpl(); // fake.setPDBCode("AFPCHainer: getRmsd" + rmsd); // List<Chain> model1 = new ArrayList<Chain>(); // model1.add(c1); // List<Chain> model2 = new ArrayList<Chain>(); // model2.add(c2); // fake.addModel(model1); // fake.addModel(model2); // fake.setNmr(true); // // jmol.setStructure(fake); // jmol.evalString("select *; backbone 0.4; wireframe off; spacefill off; " + // "select not protein and not solvent; spacefill on;"); // jmol.evalString("select */1 ; color red; model 1; "); // // // now show both models again. // jmol.evalString("model 0;"); // } return Calc.rmsd(catmp1,catmp2); }
[ "private", "static", "double", "getRmsd", "(", "Atom", "[", "]", "catmp1", ",", "Atom", "[", "]", "catmp2", ")", "throws", "StructureException", "{", "Matrix4d", "trans", "=", "SuperPositions", ".", "superpose", "(", "Calc", ".", "atomsToPoints", "(", "catmp...
Calculate the RMSD for two sets of atoms. Rotates the 2nd atom set so make sure this does not cause problems later @param catmp1 @return
[ "Calculate", "the", "RMSD", "for", "two", "sets", "of", "atoms", ".", "Rotates", "the", "2nd", "atom", "set", "so", "make", "sure", "this", "does", "not", "cause", "problems", "later" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPChainer.java#L701-L744
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuModuleLoadData
public static int cuModuleLoadData(CUmodule module, String string) { byte bytes[] = string.getBytes(); byte image[] = Arrays.copyOf(bytes, bytes.length+1); return cuModuleLoadData(module, image); }
java
public static int cuModuleLoadData(CUmodule module, String string) { byte bytes[] = string.getBytes(); byte image[] = Arrays.copyOf(bytes, bytes.length+1); return cuModuleLoadData(module, image); }
[ "public", "static", "int", "cuModuleLoadData", "(", "CUmodule", "module", ",", "String", "string", ")", "{", "byte", "bytes", "[", "]", "=", "string", ".", "getBytes", "(", ")", ";", "byte", "image", "[", "]", "=", "Arrays", ".", "copyOf", "(", "bytes"...
A wrapper function for {@link #cuModuleLoadData(CUmodule, byte[])} that converts the given string into a zero-terminated byte array. @param module The module @param string The data. May not be <code>null</code>. @return The return code from <code>cuModuleLoadData</code> @see #cuModuleLoadData(CUmodule, byte[])
[ "A", "wrapper", "function", "for", "{", "@link", "#cuModuleLoadData", "(", "CUmodule", "byte", "[]", ")", "}", "that", "converts", "the", "given", "string", "into", "a", "zero", "-", "terminated", "byte", "array", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L434-L439
cloudinary/cloudinary_java
cloudinary-core/src/main/java/com/cloudinary/Api.java
Api.updateResourcesAccessModeByTag
public ApiResponse updateResourcesAccessModeByTag(String accessMode, String tag, Map options) throws Exception { return updateResourcesAccessMode(accessMode, "tag", tag, options); }
java
public ApiResponse updateResourcesAccessModeByTag(String accessMode, String tag, Map options) throws Exception { return updateResourcesAccessMode(accessMode, "tag", tag, options); }
[ "public", "ApiResponse", "updateResourcesAccessModeByTag", "(", "String", "accessMode", ",", "String", "tag", ",", "Map", "options", ")", "throws", "Exception", "{", "return", "updateResourcesAccessMode", "(", "accessMode", ",", "\"tag\"", ",", "tag", ",", "options"...
Update access mode of one or more resources by tag @param accessMode The new access mode, "public" or "authenticated" @param tag The tag by which to filter applicable resources @param options additional options <ul> <li>resource_type - (default "image") - the type of resources to modify</li> <li>max_results - optional - the maximum resources to process in a single invocation</li> <li>next_cursor - optional - provided by a previous call to the method</li> </ul> @return a map of the returned values <ul> <li>updated - an array of resources</li> <li>next_cursor - optional - provided if more resources can be processed</li> </ul> @throws ApiException an API exception
[ "Update", "access", "mode", "of", "one", "or", "more", "resources", "by", "tag" ]
train
https://github.com/cloudinary/cloudinary_java/blob/58ee1823180da2dea6a2eb7e5cf00d5a760f8aef/cloudinary-core/src/main/java/com/cloudinary/Api.java#L518-L520
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/junit/JUnitXMLPerPageListener.java
JUnitXMLPerPageListener.generateResultXml
protected String generateResultXml(String testName, Throwable exception, double executionTime) { int errors = 0; int failures = 0; String failureXml = ""; if (exception != null) { failureXml = "<failure type=\"" + exception.getClass().getName() + "\" message=\"" + getMessage(exception) + "\"></failure>"; if (exception instanceof AssertionError) failures = 1; else errors = 1; } return "<testsuite errors=\"" + errors + "\" skipped=\"0\" tests=\"1\" time=\"" + executionTime + "\" failures=\"" + failures + "\" name=\"" + testName + "\">" + "<properties></properties>" + "<testcase classname=\"" + testName + "\" time=\"" + executionTime + "\" name=\"" + testName + "\">" + failureXml + "</testcase>" + "</testsuite>"; }
java
protected String generateResultXml(String testName, Throwable exception, double executionTime) { int errors = 0; int failures = 0; String failureXml = ""; if (exception != null) { failureXml = "<failure type=\"" + exception.getClass().getName() + "\" message=\"" + getMessage(exception) + "\"></failure>"; if (exception instanceof AssertionError) failures = 1; else errors = 1; } return "<testsuite errors=\"" + errors + "\" skipped=\"0\" tests=\"1\" time=\"" + executionTime + "\" failures=\"" + failures + "\" name=\"" + testName + "\">" + "<properties></properties>" + "<testcase classname=\"" + testName + "\" time=\"" + executionTime + "\" name=\"" + testName + "\">" + failureXml + "</testcase>" + "</testsuite>"; }
[ "protected", "String", "generateResultXml", "(", "String", "testName", ",", "Throwable", "exception", ",", "double", "executionTime", ")", "{", "int", "errors", "=", "0", ";", "int", "failures", "=", "0", ";", "String", "failureXml", "=", "\"\"", ";", "if", ...
Creates XML string describing test outcome. @param testName name of test. @param exception exception from test @param executionTime execution time in seconds @return XML description of test result
[ "Creates", "XML", "string", "describing", "test", "outcome", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/junit/JUnitXMLPerPageListener.java#L86-L106
wisdom-framework/wisdom
framework/resource-controller/src/main/java/org/wisdom/resources/CacheUtils.java
CacheUtils.fromFile
public static Result fromFile(File file, Context context, ApplicationConfiguration configuration, Crypto crypto) { long lastModified = file.lastModified(); String etag = computeEtag(lastModified, configuration, crypto); if (isNotModified(context, lastModified, etag)) { return new Result(Status.NOT_MODIFIED); } else { Result result = Results.ok(file); addLastModified(result, lastModified); addCacheControlAndEtagToResult(result, etag, configuration); return result; } }
java
public static Result fromFile(File file, Context context, ApplicationConfiguration configuration, Crypto crypto) { long lastModified = file.lastModified(); String etag = computeEtag(lastModified, configuration, crypto); if (isNotModified(context, lastModified, etag)) { return new Result(Status.NOT_MODIFIED); } else { Result result = Results.ok(file); addLastModified(result, lastModified); addCacheControlAndEtagToResult(result, etag, configuration); return result; } }
[ "public", "static", "Result", "fromFile", "(", "File", "file", ",", "Context", "context", ",", "ApplicationConfiguration", "configuration", ",", "Crypto", "crypto", ")", "{", "long", "lastModified", "=", "file", ".", "lastModified", "(", ")", ";", "String", "e...
Computes the result to sent the given file. Cache headers are automatically set by this method. @param file the file to send to the client @param context the context @param configuration the application configuration @param crypto the crypto service @return the result, it can be a NOT_MODIFIED if the file was not modified since the last request, or an OK result with the cache headers set.
[ "Computes", "the", "result", "to", "sent", "the", "given", "file", ".", "Cache", "headers", "are", "automatically", "set", "by", "this", "method", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/resource-controller/src/main/java/org/wisdom/resources/CacheUtils.java#L156-L167
joniles/mpxj
src/main/java/net/sf/mpxj/mpx/MPXWriter.java
MPXWriter.writeCalendarHours
private void writeCalendarHours(ProjectCalendar parentCalendar, ProjectCalendarHours record) throws IOException { m_buffer.setLength(0); int recordNumber; if (!parentCalendar.isDerived()) { recordNumber = MPXConstants.BASE_CALENDAR_HOURS_RECORD_NUMBER; } else { recordNumber = MPXConstants.RESOURCE_CALENDAR_HOURS_RECORD_NUMBER; } DateRange range1 = record.getRange(0); if (range1 == null) { range1 = DateRange.EMPTY_RANGE; } DateRange range2 = record.getRange(1); if (range2 == null) { range2 = DateRange.EMPTY_RANGE; } DateRange range3 = record.getRange(2); if (range3 == null) { range3 = DateRange.EMPTY_RANGE; } m_buffer.append(recordNumber); m_buffer.append(m_delimiter); m_buffer.append(format(record.getDay())); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range1.getStart()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range1.getEnd()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range2.getStart()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range2.getEnd()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range3.getStart()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range3.getEnd()))); stripTrailingDelimiters(m_buffer); m_buffer.append(MPXConstants.EOL); m_writer.write(m_buffer.toString()); }
java
private void writeCalendarHours(ProjectCalendar parentCalendar, ProjectCalendarHours record) throws IOException { m_buffer.setLength(0); int recordNumber; if (!parentCalendar.isDerived()) { recordNumber = MPXConstants.BASE_CALENDAR_HOURS_RECORD_NUMBER; } else { recordNumber = MPXConstants.RESOURCE_CALENDAR_HOURS_RECORD_NUMBER; } DateRange range1 = record.getRange(0); if (range1 == null) { range1 = DateRange.EMPTY_RANGE; } DateRange range2 = record.getRange(1); if (range2 == null) { range2 = DateRange.EMPTY_RANGE; } DateRange range3 = record.getRange(2); if (range3 == null) { range3 = DateRange.EMPTY_RANGE; } m_buffer.append(recordNumber); m_buffer.append(m_delimiter); m_buffer.append(format(record.getDay())); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range1.getStart()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range1.getEnd()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range2.getStart()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range2.getEnd()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range3.getStart()))); m_buffer.append(m_delimiter); m_buffer.append(format(formatTime(range3.getEnd()))); stripTrailingDelimiters(m_buffer); m_buffer.append(MPXConstants.EOL); m_writer.write(m_buffer.toString()); }
[ "private", "void", "writeCalendarHours", "(", "ProjectCalendar", "parentCalendar", ",", "ProjectCalendarHours", "record", ")", "throws", "IOException", "{", "m_buffer", ".", "setLength", "(", "0", ")", ";", "int", "recordNumber", ";", "if", "(", "!", "parentCalend...
Write calendar hours. @param parentCalendar parent calendar instance @param record calendar hours instance @throws IOException
[ "Write", "calendar", "hours", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/MPXWriter.java#L394-L446
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.deleteSegments
private int deleteSegments(Log log, List<LogSegment> segments) { int total = 0; for (LogSegment segment : segments) { boolean deleted = false; try { try { segment.getMessageSet().close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } if (!segment.getFile().delete()) { deleted = true; } else { total += 1; } } finally { logger.warn(String.format("DELETE_LOG[%s] %s => %s", log.name, segment.getFile().getAbsolutePath(), deleted)); } } return total; }
java
private int deleteSegments(Log log, List<LogSegment> segments) { int total = 0; for (LogSegment segment : segments) { boolean deleted = false; try { try { segment.getMessageSet().close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } if (!segment.getFile().delete()) { deleted = true; } else { total += 1; } } finally { logger.warn(String.format("DELETE_LOG[%s] %s => %s", log.name, segment.getFile().getAbsolutePath(), deleted)); } } return total; }
[ "private", "int", "deleteSegments", "(", "Log", "log", ",", "List", "<", "LogSegment", ">", "segments", ")", "{", "int", "total", "=", "0", ";", "for", "(", "LogSegment", "segment", ":", "segments", ")", "{", "boolean", "deleted", "=", "false", ";", "t...
Attemps to delete all provided segments from a log and returns how many it was able to
[ "Attemps", "to", "delete", "all", "provided", "segments", "from", "a", "log", "and", "returns", "how", "many", "it", "was", "able", "to" ]
train
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L310-L331
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/CookieHelper.java
CookieHelper.clearCookie
@Sensitive public static void clearCookie(HttpServletRequest req, HttpServletResponse res, String cookieName, Cookie[] cookies) { Cookie existing = getCookie(cookies, cookieName); if (existing != null) { Cookie c = new Cookie(cookieName, ""); String path = existing.getPath(); if (path == null) path = "/"; c.setPath(path); c.setMaxAge(0); //c.setHttpOnly(existing.isHttpOnly()); c.setSecure(existing.getSecure()); res.addCookie(c); } }
java
@Sensitive public static void clearCookie(HttpServletRequest req, HttpServletResponse res, String cookieName, Cookie[] cookies) { Cookie existing = getCookie(cookies, cookieName); if (existing != null) { Cookie c = new Cookie(cookieName, ""); String path = existing.getPath(); if (path == null) path = "/"; c.setPath(path); c.setMaxAge(0); //c.setHttpOnly(existing.isHttpOnly()); c.setSecure(existing.getSecure()); res.addCookie(c); } }
[ "@", "Sensitive", "public", "static", "void", "clearCookie", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ",", "String", "cookieName", ",", "Cookie", "[", "]", "cookies", ")", "{", "Cookie", "existing", "=", "getCookie", "(", "cookies", ...
Invalidate (clear) the cookie in the HttpServletResponse. Setting age to 0 to invalidate it. @param res
[ "Invalidate", "(", "clear", ")", "the", "cookie", "in", "the", "HttpServletResponse", ".", "Setting", "age", "to", "0", "to", "invalidate", "it", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/CookieHelper.java#L106-L125
wisdom-framework/wisdom-jdbc
wisdom-jpa-manager/src/main/java/org/wisdom/framework/jpa/PersistenceUnitComponent.java
PersistenceUnitComponent.getNewTempClassLoader
@Override public ClassLoader getNewTempClassLoader() { return new ClassLoader(getClassLoader()) { //NOSONAR /** * Searches for the .class file and define it using the current class loader. * @param className the class name * @return the class object * @throws ClassNotFoundException if the class cannot be found */ @Override protected Class findClass(String className) throws ClassNotFoundException { // Use path of class, then get the resource String path = className.replace('.', '/').concat(".class"); URL resource = getParent().getResource(path); if (resource == null) { throw new ClassNotFoundException(className + " as resource " + path + " in " + getParent()); } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(resource.openStream(), bout); byte[] buffer = bout.toByteArray(); return defineClass(className, buffer, 0, buffer.length); } catch (Exception e) { throw new ClassNotFoundException(className + " as resource" + path + " in " + getParent(), e); } } /** * Finds a resource in the bundle. * @param resource the resource * @return the url of the resource from the bundle, {@code null} if not found. */ @Override protected URL findResource(String resource) { return getParent().getResource(resource); } /** * Finds resources in the bundle. * @param resource the resource * @return the url of the resources from the bundle, empty if not found. */ @Override protected Enumeration<URL> findResources(String resource) throws IOException { return getParent().getResources(resource); } }; }
java
@Override public ClassLoader getNewTempClassLoader() { return new ClassLoader(getClassLoader()) { //NOSONAR /** * Searches for the .class file and define it using the current class loader. * @param className the class name * @return the class object * @throws ClassNotFoundException if the class cannot be found */ @Override protected Class findClass(String className) throws ClassNotFoundException { // Use path of class, then get the resource String path = className.replace('.', '/').concat(".class"); URL resource = getParent().getResource(path); if (resource == null) { throw new ClassNotFoundException(className + " as resource " + path + " in " + getParent()); } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(resource.openStream(), bout); byte[] buffer = bout.toByteArray(); return defineClass(className, buffer, 0, buffer.length); } catch (Exception e) { throw new ClassNotFoundException(className + " as resource" + path + " in " + getParent(), e); } } /** * Finds a resource in the bundle. * @param resource the resource * @return the url of the resource from the bundle, {@code null} if not found. */ @Override protected URL findResource(String resource) { return getParent().getResource(resource); } /** * Finds resources in the bundle. * @param resource the resource * @return the url of the resources from the bundle, empty if not found. */ @Override protected Enumeration<URL> findResources(String resource) throws IOException { return getParent().getResources(resource); } }; }
[ "@", "Override", "public", "ClassLoader", "getNewTempClassLoader", "(", ")", "{", "return", "new", "ClassLoader", "(", "getClassLoader", "(", ")", ")", "{", "//NOSONAR", "/**\n * Searches for the .class file and define it using the current class loader.\n ...
In this method we just create a simple temporary class loader. This class loader uses the bundle's class loader as parent but defines the classes in this class loader. This has the implicit assumption that the temp class loader is used BEFORE any bundle's classes are loaded since a class loader does parent delegation first. Sigh, guess it works most of the time. There is however, no good alternative though in OSGi we could actually refresh the bundle. @see javax.persistence.spi.PersistenceUnitInfo#getNewTempClassLoader()
[ "In", "this", "method", "we", "just", "create", "a", "simple", "temporary", "class", "loader", ".", "This", "class", "loader", "uses", "the", "bundle", "s", "class", "loader", "as", "parent", "but", "defines", "the", "classes", "in", "this", "class", "load...
train
https://github.com/wisdom-framework/wisdom-jdbc/blob/931f5acf0b2bcb0a8f3b683d60d326caafd09a72/wisdom-jpa-manager/src/main/java/org/wisdom/framework/jpa/PersistenceUnitComponent.java#L314-L365
hdbeukel/james-extensions
src/main/java/org/jamesframework/ext/permutation/neigh/SingleSwapNeighbourhood.java
SingleSwapNeighbourhood.getRandomMove
@Override public SingleSwapMove getRandomMove(PermutationSolution solution, Random rnd) { int n = solution.size(); // check: move possible if(n < 2){ return null; } // pick two random, distinct positions to swap int i = rnd.nextInt(n); int j = rnd.nextInt(n-1); if(j >= i){ j++; } // generate swap move return new SingleSwapMove(i, j); }
java
@Override public SingleSwapMove getRandomMove(PermutationSolution solution, Random rnd) { int n = solution.size(); // check: move possible if(n < 2){ return null; } // pick two random, distinct positions to swap int i = rnd.nextInt(n); int j = rnd.nextInt(n-1); if(j >= i){ j++; } // generate swap move return new SingleSwapMove(i, j); }
[ "@", "Override", "public", "SingleSwapMove", "getRandomMove", "(", "PermutationSolution", "solution", ",", "Random", "rnd", ")", "{", "int", "n", "=", "solution", ".", "size", "(", ")", ";", "// check: move possible", "if", "(", "n", "<", "2", ")", "{", "r...
Create a random single swap move. @param solution permutation solution to which the move is to be applied @param rnd source of randomness used to generate random move @return random swap move, <code>null</code> if the permutation contains less than 2 items
[ "Create", "a", "random", "single", "swap", "move", "." ]
train
https://github.com/hdbeukel/james-extensions/blob/37a43aa6ac4d67575cabc7aed25fd96c91d4c7b2/src/main/java/org/jamesframework/ext/permutation/neigh/SingleSwapNeighbourhood.java#L41-L56
zxing/zxing
core/src/main/java/com/google/zxing/pdf417/detector/Detector.java
Detector.patternMatchVariance
private static float patternMatchVariance(int[] counters, int[] pattern, float maxIndividualVariance) { int numCounters = counters.length; int total = 0; int patternLength = 0; for (int i = 0; i < numCounters; i++) { total += counters[i]; patternLength += pattern[i]; } if (total < patternLength) { // If we don't even have one pixel per unit of bar width, assume this // is too small to reliably match, so fail: return Float.POSITIVE_INFINITY; } // We're going to fake floating-point math in integers. We just need to use more bits. // Scale up patternLength so that intermediate values below like scaledCounter will have // more "significant digits". float unitBarWidth = (float) total / patternLength; maxIndividualVariance *= unitBarWidth; float totalVariance = 0.0f; for (int x = 0; x < numCounters; x++) { int counter = counters[x]; float scaledPattern = pattern[x] * unitBarWidth; float variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter; if (variance > maxIndividualVariance) { return Float.POSITIVE_INFINITY; } totalVariance += variance; } return totalVariance / total; }
java
private static float patternMatchVariance(int[] counters, int[] pattern, float maxIndividualVariance) { int numCounters = counters.length; int total = 0; int patternLength = 0; for (int i = 0; i < numCounters; i++) { total += counters[i]; patternLength += pattern[i]; } if (total < patternLength) { // If we don't even have one pixel per unit of bar width, assume this // is too small to reliably match, so fail: return Float.POSITIVE_INFINITY; } // We're going to fake floating-point math in integers. We just need to use more bits. // Scale up patternLength so that intermediate values below like scaledCounter will have // more "significant digits". float unitBarWidth = (float) total / patternLength; maxIndividualVariance *= unitBarWidth; float totalVariance = 0.0f; for (int x = 0; x < numCounters; x++) { int counter = counters[x]; float scaledPattern = pattern[x] * unitBarWidth; float variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter; if (variance > maxIndividualVariance) { return Float.POSITIVE_INFINITY; } totalVariance += variance; } return totalVariance / total; }
[ "private", "static", "float", "patternMatchVariance", "(", "int", "[", "]", "counters", ",", "int", "[", "]", "pattern", ",", "float", "maxIndividualVariance", ")", "{", "int", "numCounters", "=", "counters", ".", "length", ";", "int", "total", "=", "0", "...
Determines how closely a set of observed counts of runs of black/white values matches a given target pattern. This is reported as the ratio of the total variance from the expected pattern proportions across all pattern elements, to the length of the pattern. @param counters observed counters @param pattern expected pattern @param maxIndividualVariance The most any counter can differ before we give up @return ratio of total variance between counters and pattern compared to total pattern size
[ "Determines", "how", "closely", "a", "set", "of", "observed", "counts", "of", "runs", "of", "black", "/", "white", "values", "matches", "a", "given", "target", "pattern", ".", "This", "is", "reported", "as", "the", "ratio", "of", "the", "total", "variance"...
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/pdf417/detector/Detector.java#L309-L339
alkacon/opencms-core
src/org/opencms/workplace/editors/CmsPreEditorAction.java
CmsPreEditorAction.sendForwardToEditor
public static void sendForwardToEditor(CmsDialog dialog, Map<String, String[]> additionalParams) { // create the Map of original request parameters Map<String, String[]> params = CmsRequestUtil.createParameterMap(dialog.getParamOriginalParams()); // put the parameter indicating that the pre editor action was executed params.put(PARAM_PREACTIONDONE, new String[] {CmsStringUtil.TRUE}); if (additionalParams != null) { // put the additional parameters to the Map params.putAll(additionalParams); } try { // now forward to the editor frameset dialog.sendForward(CmsWorkplace.VFS_PATH_EDITORS + "editor.jsp", params); } catch (Exception e) { // error forwarding, log the exception as error if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } }
java
public static void sendForwardToEditor(CmsDialog dialog, Map<String, String[]> additionalParams) { // create the Map of original request parameters Map<String, String[]> params = CmsRequestUtil.createParameterMap(dialog.getParamOriginalParams()); // put the parameter indicating that the pre editor action was executed params.put(PARAM_PREACTIONDONE, new String[] {CmsStringUtil.TRUE}); if (additionalParams != null) { // put the additional parameters to the Map params.putAll(additionalParams); } try { // now forward to the editor frameset dialog.sendForward(CmsWorkplace.VFS_PATH_EDITORS + "editor.jsp", params); } catch (Exception e) { // error forwarding, log the exception as error if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } }
[ "public", "static", "void", "sendForwardToEditor", "(", "CmsDialog", "dialog", ",", "Map", "<", "String", ",", "String", "[", "]", ">", "additionalParams", ")", "{", "// create the Map of original request parameters", "Map", "<", "String", ",", "String", "[", "]",...
Forwards to the editor and opens it after the action was performed.<p> @param dialog the dialog instance forwarding to the editor @param additionalParams eventual additional request parameters for the editor to use
[ "Forwards", "to", "the", "editor", "and", "opens", "it", "after", "the", "action", "was", "performed", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/CmsPreEditorAction.java#L119-L138
facebookarchive/hadoop-20
src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNode.java
AvatarNode.adjustMetaDirectoryNames
public static void adjustMetaDirectoryNames(Configuration conf, String serviceKey) { adjustMetaDirectoryName(conf, DFS_SHARED_NAME_DIR0_KEY, serviceKey); adjustMetaDirectoryName(conf, DFS_SHARED_NAME_DIR1_KEY, serviceKey); adjustMetaDirectoryName(conf, DFS_SHARED_EDITS_DIR0_KEY, serviceKey); adjustMetaDirectoryName(conf, DFS_SHARED_EDITS_DIR1_KEY, serviceKey); }
java
public static void adjustMetaDirectoryNames(Configuration conf, String serviceKey) { adjustMetaDirectoryName(conf, DFS_SHARED_NAME_DIR0_KEY, serviceKey); adjustMetaDirectoryName(conf, DFS_SHARED_NAME_DIR1_KEY, serviceKey); adjustMetaDirectoryName(conf, DFS_SHARED_EDITS_DIR0_KEY, serviceKey); adjustMetaDirectoryName(conf, DFS_SHARED_EDITS_DIR1_KEY, serviceKey); }
[ "public", "static", "void", "adjustMetaDirectoryNames", "(", "Configuration", "conf", ",", "String", "serviceKey", ")", "{", "adjustMetaDirectoryName", "(", "conf", ",", "DFS_SHARED_NAME_DIR0_KEY", ",", "serviceKey", ")", ";", "adjustMetaDirectoryName", "(", "conf", "...
Append service name to each avatar meta directory name @param conf configuration of NameNode @param serviceKey the non-empty name of the name node service
[ "Append", "service", "name", "to", "each", "avatar", "meta", "directory", "name" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNode.java#L1598-L1603
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/MetadataUtils.java
MetadataUtils.setSchemaAndPersistenceUnit
public static void setSchemaAndPersistenceUnit(EntityMetadata m, String schemaStr, Map puProperties) { if (schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR) > 0) { String schemaName = null; if (puProperties != null) { schemaName = (String) puProperties.get(PersistenceProperties.KUNDERA_KEYSPACE); } if (schemaName == null) { schemaName = schemaStr.substring(0, schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR)); } m.setSchema(schemaName); m.setPersistenceUnit(schemaStr.substring( schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR) + 1, schemaStr.length())); } else { m.setSchema(StringUtils.isBlank(schemaStr) ? null : schemaStr); } }
java
public static void setSchemaAndPersistenceUnit(EntityMetadata m, String schemaStr, Map puProperties) { if (schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR) > 0) { String schemaName = null; if (puProperties != null) { schemaName = (String) puProperties.get(PersistenceProperties.KUNDERA_KEYSPACE); } if (schemaName == null) { schemaName = schemaStr.substring(0, schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR)); } m.setSchema(schemaName); m.setPersistenceUnit(schemaStr.substring( schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR) + 1, schemaStr.length())); } else { m.setSchema(StringUtils.isBlank(schemaStr) ? null : schemaStr); } }
[ "public", "static", "void", "setSchemaAndPersistenceUnit", "(", "EntityMetadata", "m", ",", "String", "schemaStr", ",", "Map", "puProperties", ")", "{", "if", "(", "schemaStr", ".", "indexOf", "(", "Constants", ".", "SCHEMA_PERSISTENCE_UNIT_SEPARATOR", ")", ">", "...
Sets the schema and persistence unit. @param m the m @param schemaStr the schema str @param puProperties
[ "Sets", "the", "schema", "and", "persistence", "unit", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/MetadataUtils.java#L283-L305
WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor
SurveyorCore/src/main/java/org/wwarn/surveyor/client/core/FilterQuery.java
FilterQuery.addMultipleValuesFilter
public void addMultipleValuesFilter(String field, Set<String> valueToFilter){ if(!valueToFilter.isEmpty()){ filterQueries.put(field, new FilterFieldValue(field, valueToFilter)); } }
java
public void addMultipleValuesFilter(String field, Set<String> valueToFilter){ if(!valueToFilter.isEmpty()){ filterQueries.put(field, new FilterFieldValue(field, valueToFilter)); } }
[ "public", "void", "addMultipleValuesFilter", "(", "String", "field", ",", "Set", "<", "String", ">", "valueToFilter", ")", "{", "if", "(", "!", "valueToFilter", ".", "isEmpty", "(", ")", ")", "{", "filterQueries", ".", "put", "(", "field", ",", "new", "F...
add a filter with multiple values to build FilterQuery instance @param field @param valueToFilter
[ "add", "a", "filter", "with", "multiple", "values", "to", "build", "FilterQuery", "instance" ]
train
https://github.com/WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor/blob/224280bcd6e8045bda6b673584caf0aea5e4c841/SurveyorCore/src/main/java/org/wwarn/surveyor/client/core/FilterQuery.java#L105-L109
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGUtil.java
SVGUtil.svgElement
public static Element svgElement(Document document, String name) { return document.createElementNS(SVGConstants.SVG_NAMESPACE_URI, name); }
java
public static Element svgElement(Document document, String name) { return document.createElementNS(SVGConstants.SVG_NAMESPACE_URI, name); }
[ "public", "static", "Element", "svgElement", "(", "Document", "document", ",", "String", "name", ")", "{", "return", "document", ".", "createElementNS", "(", "SVGConstants", ".", "SVG_NAMESPACE_URI", ",", "name", ")", ";", "}" ]
Create a SVG element in appropriate namespace @param document containing document @param name node name @return new SVG element.
[ "Create", "a", "SVG", "element", "in", "appropriate", "namespace" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGUtil.java#L283-L285
jboss/jboss-common-beans
src/main/java/org/jboss/common/beans/property/DateEditor.java
DateEditor.setAsText
@Override public void setAsText(String text) { if (BeanUtils.isNull(text)) { setValue(null); return; } ParseException pe = null; for (int i = 0; i < formats.length; i++) { try { // try to parse the date DateFormat df = formats[i]; Date date = df.parse(text); // store the date in both forms this.text = text; super.setValue(date); // done return; } catch (ParseException e) { // remember the last seen exception pe = e; } } // couldn't parse throw new IllegalArgumentException("Failed to parse to Date!", pe); }
java
@Override public void setAsText(String text) { if (BeanUtils.isNull(text)) { setValue(null); return; } ParseException pe = null; for (int i = 0; i < formats.length; i++) { try { // try to parse the date DateFormat df = formats[i]; Date date = df.parse(text); // store the date in both forms this.text = text; super.setValue(date); // done return; } catch (ParseException e) { // remember the last seen exception pe = e; } } // couldn't parse throw new IllegalArgumentException("Failed to parse to Date!", pe); }
[ "@", "Override", "public", "void", "setAsText", "(", "String", "text", ")", "{", "if", "(", "BeanUtils", ".", "isNull", "(", "text", ")", ")", "{", "setValue", "(", "null", ")", ";", "return", ";", "}", "ParseException", "pe", "=", "null", ";", "for"...
Parse the text into a java.util.Date by trying one by one the registered DateFormat(s). @param text the string date
[ "Parse", "the", "text", "into", "a", "java", ".", "util", ".", "Date", "by", "trying", "one", "by", "one", "the", "registered", "DateFormat", "(", "s", ")", "." ]
train
https://github.com/jboss/jboss-common-beans/blob/ffb48b1719762534bf92d762eadf91d1815f6748/src/main/java/org/jboss/common/beans/property/DateEditor.java#L109-L136
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java
ZipUtil.unzip
public static File unzip(String zipFilePath, String outFileDir, Charset charset) throws UtilException { return unzip(FileUtil.file(zipFilePath), FileUtil.mkdir(outFileDir), charset); }
java
public static File unzip(String zipFilePath, String outFileDir, Charset charset) throws UtilException { return unzip(FileUtil.file(zipFilePath), FileUtil.mkdir(outFileDir), charset); }
[ "public", "static", "File", "unzip", "(", "String", "zipFilePath", ",", "String", "outFileDir", ",", "Charset", "charset", ")", "throws", "UtilException", "{", "return", "unzip", "(", "FileUtil", ".", "file", "(", "zipFilePath", ")", ",", "FileUtil", ".", "m...
解压 @param zipFilePath 压缩文件的路径 @param outFileDir 解压到的目录 @param charset 编码 @return 解压的目录 @throws UtilException IO异常
[ "解压" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java#L358-L360
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java
StyleUtilities.changeRotation
public static void changeRotation( Rule rule, int newRotation ) { PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.setRotation(ff.literal(newRotation)); // Mark oldMark = SLDs.mark(pointSymbolizer); // oldMark.setSize(ff.literal(newRotation)); }
java
public static void changeRotation( Rule rule, int newRotation ) { PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.setRotation(ff.literal(newRotation)); // Mark oldMark = SLDs.mark(pointSymbolizer); // oldMark.setSize(ff.literal(newRotation)); }
[ "public", "static", "void", "changeRotation", "(", "Rule", "rule", ",", "int", "newRotation", ")", "{", "PointSymbolizer", "pointSymbolizer", "=", "StyleUtilities", ".", "pointSymbolizerFromRule", "(", "rule", ")", ";", "Graphic", "graphic", "=", "SLD", ".", "gr...
Changes the rotation value inside a rule. @param rule the {@link Rule}. @param newRotation the new rotation value in degrees.
[ "Changes", "the", "rotation", "value", "inside", "a", "rule", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java#L681-L687
sdl/odata
odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomWriter.java
AtomWriter.writeBodyFeed
public void writeBodyFeed(List<?> entities) throws ODataRenderException { checkNotNull(entities); try { for (Object entity : entities) { writeEntry(entity, true); } } catch (XMLStreamException | IllegalAccessException | NoSuchFieldException | ODataEdmException e) { LOG.error("Not possible to marshall feed stream XML"); throw new ODataRenderException("Not possible to marshall feed stream XML: ", e); } }
java
public void writeBodyFeed(List<?> entities) throws ODataRenderException { checkNotNull(entities); try { for (Object entity : entities) { writeEntry(entity, true); } } catch (XMLStreamException | IllegalAccessException | NoSuchFieldException | ODataEdmException e) { LOG.error("Not possible to marshall feed stream XML"); throw new ODataRenderException("Not possible to marshall feed stream XML: ", e); } }
[ "public", "void", "writeBodyFeed", "(", "List", "<", "?", ">", "entities", ")", "throws", "ODataRenderException", "{", "checkNotNull", "(", "entities", ")", ";", "try", "{", "for", "(", "Object", "entity", ":", "entities", ")", "{", "writeEntry", "(", "ent...
Write feed body. @param entities The list of entities to fill in the XML stream. It can not {@code null}. @throws ODataRenderException In case it is not possible to write to the XML stream.
[ "Write", "feed", "body", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomWriter.java#L249-L259
JOML-CI/JOML
src/org/joml/Intersectiond.java
Intersectiond.intersectCircleCircle
public static boolean intersectCircleCircle(Vector2dc centerA, double radiusSquaredA, Vector2dc centerB, double radiusSquaredB, Vector3d intersectionCenterAndHL) { return intersectCircleCircle(centerA.x(), centerA.y(), radiusSquaredA, centerB.x(), centerB.y(), radiusSquaredB, intersectionCenterAndHL); }
java
public static boolean intersectCircleCircle(Vector2dc centerA, double radiusSquaredA, Vector2dc centerB, double radiusSquaredB, Vector3d intersectionCenterAndHL) { return intersectCircleCircle(centerA.x(), centerA.y(), radiusSquaredA, centerB.x(), centerB.y(), radiusSquaredB, intersectionCenterAndHL); }
[ "public", "static", "boolean", "intersectCircleCircle", "(", "Vector2dc", "centerA", ",", "double", "radiusSquaredA", ",", "Vector2dc", "centerB", ",", "double", "radiusSquaredB", ",", "Vector3d", "intersectionCenterAndHL", ")", "{", "return", "intersectCircleCircle", "...
Test whether the one circle with center <code>centerA</code> and square radius <code>radiusSquaredA</code> intersects the other circle with center <code>centerB</code> and square radius <code>radiusSquaredB</code>, and store the center of the line segment of intersection in the <code>(x, y)</code> components of the supplied vector and the half-length of that line segment in the z component. <p> This method returns <code>false</code> when one circle contains the other circle. <p> Reference: <a href="http://gamedev.stackexchange.com/questions/75756/sphere-sphere-intersection-and-circle-sphere-intersection">http://gamedev.stackexchange.com</a> @param centerA the first circle's center @param radiusSquaredA the square of the first circle's radius @param centerB the second circle's center @param radiusSquaredB the square of the second circle's radius @param intersectionCenterAndHL will hold the center of the line segment of intersection in the <code>(x, y)</code> components and the half-length in the z component @return <code>true</code> iff both circles intersect; <code>false</code> otherwise
[ "Test", "whether", "the", "one", "circle", "with", "center", "<code", ">", "centerA<", "/", "code", ">", "and", "square", "radius", "<code", ">", "radiusSquaredA<", "/", "code", ">", "intersects", "the", "other", "circle", "with", "center", "<code", ">", "...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectiond.java#L3756-L3758
betfair/cougar
baseline/baseline-app/src/main/java/com/betfair/cougar/baseline/BaselineServiceImpl.java
BaselineServiceImpl.subscribeToMatchedBet
@Override public void subscribeToMatchedBet(ExecutionContext ctx, Object[] args, ExecutionObserver executionObserver) { if (getEventTransportIdentity(ctx).getPrincipal().getName().equals(SONIC_TRANSPORT_INSTANCE_ONE)) { this.matchedBetObserver = executionObserver; } }
java
@Override public void subscribeToMatchedBet(ExecutionContext ctx, Object[] args, ExecutionObserver executionObserver) { if (getEventTransportIdentity(ctx).getPrincipal().getName().equals(SONIC_TRANSPORT_INSTANCE_ONE)) { this.matchedBetObserver = executionObserver; } }
[ "@", "Override", "public", "void", "subscribeToMatchedBet", "(", "ExecutionContext", "ctx", ",", "Object", "[", "]", "args", ",", "ExecutionObserver", "executionObserver", ")", "{", "if", "(", "getEventTransportIdentity", "(", "ctx", ")", ".", "getPrincipal", "(",...
Please note that this Service method is called by the Execution Venue to establish a communication channel from the transport to the Application to publish events. In essence, the transport subscribes to the app, so this method is called once for each publisher at application initialisation. You should never be calling this directly. The application should hold onto the passed in observer, and call onResult on that observer to emit an event. @param ctx @param args @param executionObserver
[ "Please", "note", "that", "this", "Service", "method", "is", "called", "by", "the", "Execution", "Venue", "to", "establish", "a", "communication", "channel", "from", "the", "transport", "to", "the", "Application", "to", "publish", "events", ".", "In", "essence...
train
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/baseline/baseline-app/src/main/java/com/betfair/cougar/baseline/BaselineServiceImpl.java#L1930-L1935
jenkinsci/jenkins
core/src/main/java/hudson/model/Descriptor.java
Descriptor.findById
public static @CheckForNull <T extends Descriptor> T findById(Collection<? extends T> list, String id) { for (T d : list) { if(d.getId().equals(id)) return d; } return null; }
java
public static @CheckForNull <T extends Descriptor> T findById(Collection<? extends T> list, String id) { for (T d : list) { if(d.getId().equals(id)) return d; } return null; }
[ "public", "static", "@", "CheckForNull", "<", "T", "extends", "Descriptor", ">", "T", "findById", "(", "Collection", "<", "?", "extends", "T", ">", "list", ",", "String", "id", ")", "{", "for", "(", "T", "d", ":", "list", ")", "{", "if", "(", "d", ...
Finds a descriptor from a collection by its ID. @param id should match {@link #getId} @since 1.610
[ "Finds", "a", "descriptor", "from", "a", "collection", "by", "its", "ID", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/Descriptor.java#L1074-L1080
Ordinastie/MalisisCore
src/main/java/net/malisis/core/renderer/model/loader/ObjFileImporter.java
ObjFileImporter.addNormal
private void addNormal(String data) { String coords[] = data.split("\\s+"); float x = 0; float y = 0; float z = 0; if (coords.length != 3) { MalisisCore.log.error( "[ObjFileImporter] Wrong Normal coordinates number {} at line {} : {}", coords.length, lineNumber, currentLine); } else { x = Float.parseFloat(coords[0]); y = Float.parseFloat(coords[1]); z = Float.parseFloat(coords[2]); } normals.add(new Vector(x, y, z)); }
java
private void addNormal(String data) { String coords[] = data.split("\\s+"); float x = 0; float y = 0; float z = 0; if (coords.length != 3) { MalisisCore.log.error( "[ObjFileImporter] Wrong Normal coordinates number {} at line {} : {}", coords.length, lineNumber, currentLine); } else { x = Float.parseFloat(coords[0]); y = Float.parseFloat(coords[1]); z = Float.parseFloat(coords[2]); } normals.add(new Vector(x, y, z)); }
[ "private", "void", "addNormal", "(", "String", "data", ")", "{", "String", "coords", "[", "]", "=", "data", ".", "split", "(", "\"\\\\s+\"", ")", ";", "float", "x", "=", "0", ";", "float", "y", "=", "0", ";", "float", "z", "=", "0", ";", "if", ...
Creates a new normal {@link Vector} from data and adds it to {@link #normals}. @param data the data
[ "Creates", "a", "new", "normal", "{", "@link", "Vector", "}", "from", "data", "and", "adds", "it", "to", "{", "@link", "#normals", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/renderer/model/loader/ObjFileImporter.java#L257-L278
redkale/redkale
src/org/redkale/convert/bson/BsonReader.java
BsonReader.hasNext
@Override public boolean hasNext(int startPosition, int contentLength) { byte b = readByte(); if (b == SIGN_HASNEXT) return true; if (b != SIGN_NONEXT) throw new ConvertException("hasNext option must be (" + (SIGN_HASNEXT) + " or " + (SIGN_NONEXT) + ") but '" + b + "' at position(" + this.position + ")"); return false; }
java
@Override public boolean hasNext(int startPosition, int contentLength) { byte b = readByte(); if (b == SIGN_HASNEXT) return true; if (b != SIGN_NONEXT) throw new ConvertException("hasNext option must be (" + (SIGN_HASNEXT) + " or " + (SIGN_NONEXT) + ") but '" + b + "' at position(" + this.position + ")"); return false; }
[ "@", "Override", "public", "boolean", "hasNext", "(", "int", "startPosition", ",", "int", "contentLength", ")", "{", "byte", "b", "=", "readByte", "(", ")", ";", "if", "(", "b", "==", "SIGN_HASNEXT", ")", "return", "true", ";", "if", "(", "b", "!=", ...
判断对象是否存在下一个属性或者数组是否存在下一个元素 @param startPosition 起始位置 @param contentLength 内容大小, 不确定的传-1 @return 是否存在
[ "判断对象是否存在下一个属性或者数组是否存在下一个元素" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/convert/bson/BsonReader.java#L211-L218
sksamuel/scrimage
scrimage-filters/src/main/java/thirdparty/jhlabs/math/Noise.java
Noise.noise2
public static float noise2(float x, float y) { int bx0, bx1, by0, by1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v; int i, j; if (start) { start = false; init(); } t = x + N; bx0 = ((int)t) & BM; bx1 = (bx0+1) & BM; rx0 = t - (int)t; rx1 = rx0 - 1.0f; t = y + N; by0 = ((int)t) & BM; by1 = (by0+1) & BM; ry0 = t - (int)t; ry1 = ry0 - 1.0f; i = p[bx0]; j = p[bx1]; b00 = p[i + by0]; b10 = p[j + by0]; b01 = p[i + by1]; b11 = p[j + by1]; sx = sCurve(rx0); sy = sCurve(ry0); q = g2[b00]; u = rx0 * q[0] + ry0 * q[1]; q = g2[b10]; v = rx1 * q[0] + ry0 * q[1]; a = lerp(sx, u, v); q = g2[b01]; u = rx0 * q[0] + ry1 * q[1]; q = g2[b11]; v = rx1 * q[0] + ry1 * q[1]; b = lerp(sx, u, v); return 1.5f*lerp(sy, a, b); }
java
public static float noise2(float x, float y) { int bx0, bx1, by0, by1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v; int i, j; if (start) { start = false; init(); } t = x + N; bx0 = ((int)t) & BM; bx1 = (bx0+1) & BM; rx0 = t - (int)t; rx1 = rx0 - 1.0f; t = y + N; by0 = ((int)t) & BM; by1 = (by0+1) & BM; ry0 = t - (int)t; ry1 = ry0 - 1.0f; i = p[bx0]; j = p[bx1]; b00 = p[i + by0]; b10 = p[j + by0]; b01 = p[i + by1]; b11 = p[j + by1]; sx = sCurve(rx0); sy = sCurve(ry0); q = g2[b00]; u = rx0 * q[0] + ry0 * q[1]; q = g2[b10]; v = rx1 * q[0] + ry0 * q[1]; a = lerp(sx, u, v); q = g2[b01]; u = rx0 * q[0] + ry1 * q[1]; q = g2[b11]; v = rx1 * q[0] + ry1 * q[1]; b = lerp(sx, u, v); return 1.5f*lerp(sy, a, b); }
[ "public", "static", "float", "noise2", "(", "float", "x", ",", "float", "y", ")", "{", "int", "bx0", ",", "bx1", ",", "by0", ",", "by1", ",", "b00", ",", "b10", ",", "b01", ",", "b11", ";", "float", "rx0", ",", "rx1", ",", "ry0", ",", "ry1", ...
Compute 2-dimensional Perlin noise. @param x the x coordinate @param y the y coordinate @return noise value at (x,y)
[ "Compute", "2", "-", "dimensional", "Perlin", "noise", "." ]
train
https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/jhlabs/math/Noise.java#L117-L159
BlueBrain/bluima
modules/bluima_abbreviations/src/main/java/com/wcohen/ss/expt/SourcedMatchData.java
SourcedMatchData.addInstance
public void addInstance(String src,String id,String text) { Instance inst = new Instance(src,id,text); ArrayList list = (ArrayList)sourceLists.get(src); if (list==null) { list = new ArrayList(); sourceLists.put(src,list); sourceNames.add(src); } list.add(inst); }
java
public void addInstance(String src,String id,String text) { Instance inst = new Instance(src,id,text); ArrayList list = (ArrayList)sourceLists.get(src); if (list==null) { list = new ArrayList(); sourceLists.put(src,list); sourceNames.add(src); } list.add(inst); }
[ "public", "void", "addInstance", "(", "String", "src", ",", "String", "id", ",", "String", "text", ")", "{", "Instance", "inst", "=", "new", "Instance", "(", "src", ",", "id", ",", "text", ")", ";", "ArrayList", "list", "=", "(", "ArrayList", ")", "s...
Add a single instance, with given src and id, to the datafile
[ "Add", "a", "single", "instance", "with", "given", "src", "and", "id", "to", "the", "datafile" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_abbreviations/src/main/java/com/wcohen/ss/expt/SourcedMatchData.java#L68-L78
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/XMLFactory.java
XMLFactory.newDocument
@Nonnull public static Document newDocument (@Nonnull final DocumentBuilder aDocBuilder) { return newDocument (aDocBuilder, (EXMLVersion) null); }
java
@Nonnull public static Document newDocument (@Nonnull final DocumentBuilder aDocBuilder) { return newDocument (aDocBuilder, (EXMLVersion) null); }
[ "@", "Nonnull", "public", "static", "Document", "newDocument", "(", "@", "Nonnull", "final", "DocumentBuilder", "aDocBuilder", ")", "{", "return", "newDocument", "(", "aDocBuilder", ",", "(", "EXMLVersion", ")", "null", ")", ";", "}" ]
Create a new XML document without document type using version {@link EXMLVersion#XML_10}. A custom document builder is used. @param aDocBuilder The document builder to use. May not be <code>null</code>. @return The created document. Never <code>null</code>.
[ "Create", "a", "new", "XML", "document", "without", "document", "type", "using", "version", "{", "@link", "EXMLVersion#XML_10", "}", ".", "A", "custom", "document", "builder", "is", "used", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/XMLFactory.java#L271-L275
pressgang-ccms/PressGangCCMSBuilder
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java
DocBookXMLPreProcessor.processIdList
private static List<InjectionData> processIdList(final String list) { /* find the individual topic ids */ final String[] ids = list.split(","); List<InjectionData> retValue = new ArrayList<InjectionData>(ids.length); /* clean the topic ids */ for (final String id : ids) { final String topicId = id.replaceAll(OPTIONAL_MARKER, "").trim(); final boolean optional = id.contains(OPTIONAL_MARKER); try { final InjectionData topicData = new InjectionData(topicId, optional); retValue.add(topicData); } catch (final NumberFormatException ex) { /* * these lists are discovered by a regular expression so we shouldn't have any trouble here with Integer.parse */ LOG.debug("Unable to convert Injection Point ID into a Number", ex); retValue.add(new InjectionData("-1", false)); } } return retValue; }
java
private static List<InjectionData> processIdList(final String list) { /* find the individual topic ids */ final String[] ids = list.split(","); List<InjectionData> retValue = new ArrayList<InjectionData>(ids.length); /* clean the topic ids */ for (final String id : ids) { final String topicId = id.replaceAll(OPTIONAL_MARKER, "").trim(); final boolean optional = id.contains(OPTIONAL_MARKER); try { final InjectionData topicData = new InjectionData(topicId, optional); retValue.add(topicData); } catch (final NumberFormatException ex) { /* * these lists are discovered by a regular expression so we shouldn't have any trouble here with Integer.parse */ LOG.debug("Unable to convert Injection Point ID into a Number", ex); retValue.add(new InjectionData("-1", false)); } } return retValue; }
[ "private", "static", "List", "<", "InjectionData", ">", "processIdList", "(", "final", "String", "list", ")", "{", "/* find the individual topic ids */", "final", "String", "[", "]", "ids", "=", "list", ".", "split", "(", "\",\"", ")", ";", "List", "<", "Inj...
Takes a comma separated list of ints, and returns an array of Integers. This is used when processing custom injection points.
[ "Takes", "a", "comma", "separated", "list", "of", "ints", "and", "returns", "an", "array", "of", "Integers", ".", "This", "is", "used", "when", "processing", "custom", "injection", "points", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java#L468-L492
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialMethodWriter.java
HtmlSerialMethodWriter.addMemberHeader
public void addMemberHeader(MethodDoc member, Content methodsContentTree) { methodsContentTree.addContent(getHead(member)); methodsContentTree.addContent(getSignature(member)); }
java
public void addMemberHeader(MethodDoc member, Content methodsContentTree) { methodsContentTree.addContent(getHead(member)); methodsContentTree.addContent(getSignature(member)); }
[ "public", "void", "addMemberHeader", "(", "MethodDoc", "member", ",", "Content", "methodsContentTree", ")", "{", "methodsContentTree", ".", "addContent", "(", "getHead", "(", "member", ")", ")", ";", "methodsContentTree", ".", "addContent", "(", "getSignature", "(...
Add the member header. @param member the method document to be listed @param methodsContentTree the content tree to which the member header will be added
[ "Add", "the", "member", "header", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialMethodWriter.java#L114-L117
kirgor/enklib
ejb/src/main/java/com/kirgor/enklib/ejb/Bean.java
Bean.handleAPIException
protected Response handleAPIException(APIException ex, Method method, Object[] params) throws Exception { return buildResponse(Response.status(ex.getHttpStatus())); }
java
protected Response handleAPIException(APIException ex, Method method, Object[] params) throws Exception { return buildResponse(Response.status(ex.getHttpStatus())); }
[ "protected", "Response", "handleAPIException", "(", "APIException", "ex", ",", "Method", "method", ",", "Object", "[", "]", "params", ")", "throws", "Exception", "{", "return", "buildResponse", "(", "Response", ".", "status", "(", "ex", ".", "getHttpStatus", "...
Called by interceptor in case of API invocation exception. <p/> Default implementation simply returns {@link Response} with HTTP code taken from ex param. @param ex Caught exception instance. @param method Invoked method. @param params Invoked method params. @return Method must return {@link Response} on behalf of invoked API method. @throws Exception
[ "Called", "by", "interceptor", "in", "case", "of", "API", "invocation", "exception", ".", "<p", "/", ">", "Default", "implementation", "simply", "returns", "{", "@link", "Response", "}", "with", "HTTP", "code", "taken", "from", "ex", "param", "." ]
train
https://github.com/kirgor/enklib/blob/8a24db296dc43db5d8fe509cf64ace0a0c7be8f2/ejb/src/main/java/com/kirgor/enklib/ejb/Bean.java#L269-L271
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java
FirstNonNullHelper.firstNonNull
@SafeVarargs public static <T> T firstNonNull(Supplier<T>... suppliers) { return firstNonNull(Supplier::get, suppliers); }
java
@SafeVarargs public static <T> T firstNonNull(Supplier<T>... suppliers) { return firstNonNull(Supplier::get, suppliers); }
[ "@", "SafeVarargs", "public", "static", "<", "T", ">", "T", "firstNonNull", "(", "Supplier", "<", "T", ">", "...", "suppliers", ")", "{", "return", "firstNonNull", "(", "Supplier", "::", "get", ",", "suppliers", ")", ";", "}" ]
Gets first supplier's result which is not null. Suppliers are called sequentially. Once a non-null result is obtained the remaining suppliers are not called. @param <T> type of result returned by suppliers. @param suppliers all possible suppliers that might be able to supply a value. @return first result obtained which was not null, OR <code>null</code> if all suppliers returned <code>null</code>.
[ "Gets", "first", "supplier", "s", "result", "which", "is", "not", "null", ".", "Suppliers", "are", "called", "sequentially", ".", "Once", "a", "non", "-", "null", "result", "is", "obtained", "the", "remaining", "suppliers", "are", "not", "called", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java#L21-L24
jMotif/SAX
src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java
EuclideanDistance.distance2
public double distance2(double[] point1, double[] point2) throws Exception { if (point1.length == point2.length) { Double sum = 0D; for (int i = 0; i < point1.length; i++) { double tmp = point2[i] - point1[i]; sum = sum + tmp * tmp; } return sum; } else { throw new Exception("Exception in Euclidean distance: array lengths are not equal"); } }
java
public double distance2(double[] point1, double[] point2) throws Exception { if (point1.length == point2.length) { Double sum = 0D; for (int i = 0; i < point1.length; i++) { double tmp = point2[i] - point1[i]; sum = sum + tmp * tmp; } return sum; } else { throw new Exception("Exception in Euclidean distance: array lengths are not equal"); } }
[ "public", "double", "distance2", "(", "double", "[", "]", "point1", ",", "double", "[", "]", "point2", ")", "throws", "Exception", "{", "if", "(", "point1", ".", "length", "==", "point2", ".", "length", ")", "{", "Double", "sum", "=", "0D", ";", "for...
Calculates the square of the Euclidean distance between two multidimensional points represented by the rational vectors. @param point1 The first point. @param point2 The second point. @return The Euclidean distance. @throws Exception In the case of error.
[ "Calculates", "the", "square", "of", "the", "Euclidean", "distance", "between", "two", "multidimensional", "points", "represented", "by", "the", "rational", "vectors", "." ]
train
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/distance/EuclideanDistance.java#L75-L87
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/util/SegmentClipper.java
SegmentClipper.getClosestCorner
private int getClosestCorner(final long pX0, final long pY0, final long pX1, final long pY1) { double min = Double.MAX_VALUE; int corner = 0; for (int i = 0 ; i < cornerX.length ; i ++) { final double distance = Distance.getSquaredDistanceToSegment( cornerX[i], cornerY[i], pX0, pY0, pX1, pY1); if (min > distance) { min = distance; corner = i; } } return corner; }
java
private int getClosestCorner(final long pX0, final long pY0, final long pX1, final long pY1) { double min = Double.MAX_VALUE; int corner = 0; for (int i = 0 ; i < cornerX.length ; i ++) { final double distance = Distance.getSquaredDistanceToSegment( cornerX[i], cornerY[i], pX0, pY0, pX1, pY1); if (min > distance) { min = distance; corner = i; } } return corner; }
[ "private", "int", "getClosestCorner", "(", "final", "long", "pX0", ",", "final", "long", "pY0", ",", "final", "long", "pX1", ",", "final", "long", "pY1", ")", "{", "double", "min", "=", "Double", ".", "MAX_VALUE", ";", "int", "corner", "=", "0", ";", ...
Gets the clip area corner which is the closest to the given segment @since 6.0.0 We have a clip area and we have a segment with no intersection with this clip area. The question is: how do we clip this segment? If we only clip both segment ends, we may end up with a (min,min) x (max,max) clip approximation that displays a backslash on the screen. The idea is to compute the clip area corner which is the closest to the segment, and to use it as a clip step. Which will do something like: (min,min)[first segment point] x (min,max)[closest corner] x (max,max)[second segment point] or (min,min)[first segment point] x (max,min)[closest corner] x (max,max)[second segment point]
[ "Gets", "the", "clip", "area", "corner", "which", "is", "the", "closest", "to", "the", "given", "segment" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/SegmentClipper.java#L220-L233
citrusframework/citrus
modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/ReceiveMessageBuilder.java
ReceiveMessageBuilder.payloadModel
public T payloadModel(Object payload) { Assert.notNull(applicationContext, "Citrus application context is not initialized!"); if (!CollectionUtils.isEmpty(applicationContext.getBeansOfType(Marshaller.class))) { return payload(payload, applicationContext.getBean(Marshaller.class)); } else if (!CollectionUtils.isEmpty(applicationContext.getBeansOfType(ObjectMapper.class))) { return payload(payload, applicationContext.getBean(ObjectMapper.class)); } throw new CitrusRuntimeException("Unable to find default object mapper or marshaller in application context"); }
java
public T payloadModel(Object payload) { Assert.notNull(applicationContext, "Citrus application context is not initialized!"); if (!CollectionUtils.isEmpty(applicationContext.getBeansOfType(Marshaller.class))) { return payload(payload, applicationContext.getBean(Marshaller.class)); } else if (!CollectionUtils.isEmpty(applicationContext.getBeansOfType(ObjectMapper.class))) { return payload(payload, applicationContext.getBean(ObjectMapper.class)); } throw new CitrusRuntimeException("Unable to find default object mapper or marshaller in application context"); }
[ "public", "T", "payloadModel", "(", "Object", "payload", ")", "{", "Assert", ".", "notNull", "(", "applicationContext", ",", "\"Citrus application context is not initialized!\"", ")", ";", "if", "(", "!", "CollectionUtils", ".", "isEmpty", "(", "applicationContext", ...
Expect this message payload as model object which is marshalled to a character sequence using the default object to xml mapper that is available in Spring bean application context. @param payload @return
[ "Expect", "this", "message", "payload", "as", "model", "object", "which", "is", "marshalled", "to", "a", "character", "sequence", "using", "the", "default", "object", "to", "xml", "mapper", "that", "is", "available", "in", "Spring", "bean", "application", "con...
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/ReceiveMessageBuilder.java#L263-L273
matiwinnetou/spring-soy-view
spring-soy-view-ajax-compiler/src/main/java/pl/matisoft/soy/ajax/utils/I18nUtils.java
I18nUtils.getLocaleFromString
public static Locale getLocaleFromString(String localeString) { if (localeString == null) { return null; } localeString = localeString.trim(); if (localeString.toLowerCase().equals("default")) { return Locale.getDefault(); } // Extract language int languageIndex = localeString.indexOf('_'); String language = null; if (languageIndex == -1) { // No further "_" so is "{language}" only return new Locale(localeString, ""); } else { language = localeString.substring(0, languageIndex); } // Extract country int countryIndex = localeString.indexOf('_', languageIndex + 1); String country = null; if (countryIndex == -1) { // No further "_" so is "{language}_{country}" country = localeString.substring(languageIndex + 1); return new Locale(language, country); } else { // Assume all remaining is the variant so is "{language}_{country}_{variant}" country = localeString.substring(languageIndex + 1, countryIndex); String variant = localeString.substring(countryIndex + 1); return new Locale(language, country, variant); } }
java
public static Locale getLocaleFromString(String localeString) { if (localeString == null) { return null; } localeString = localeString.trim(); if (localeString.toLowerCase().equals("default")) { return Locale.getDefault(); } // Extract language int languageIndex = localeString.indexOf('_'); String language = null; if (languageIndex == -1) { // No further "_" so is "{language}" only return new Locale(localeString, ""); } else { language = localeString.substring(0, languageIndex); } // Extract country int countryIndex = localeString.indexOf('_', languageIndex + 1); String country = null; if (countryIndex == -1) { // No further "_" so is "{language}_{country}" country = localeString.substring(languageIndex + 1); return new Locale(language, country); } else { // Assume all remaining is the variant so is "{language}_{country}_{variant}" country = localeString.substring(languageIndex + 1, countryIndex); String variant = localeString.substring(countryIndex + 1); return new Locale(language, country, variant); } }
[ "public", "static", "Locale", "getLocaleFromString", "(", "String", "localeString", ")", "{", "if", "(", "localeString", "==", "null", ")", "{", "return", "null", ";", "}", "localeString", "=", "localeString", ".", "trim", "(", ")", ";", "if", "(", "locale...
Convert a string based locale into a Locale Object. Assumes the string has form "{language}_{country}_{variant}". Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr_MAC" @param localeString The String @return the Locale
[ "Convert", "a", "string", "based", "locale", "into", "a", "Locale", "Object", ".", "Assumes", "the", "string", "has", "form", "{", "language", "}", "_", "{", "country", "}", "_", "{", "variant", "}", ".", "Examples", ":", "en", "de_DE", "_GB", "en_US_W...
train
https://github.com/matiwinnetou/spring-soy-view/blob/a27c1b2bc76b074a2753ddd7b0c7f685c883d1d1/spring-soy-view-ajax-compiler/src/main/java/pl/matisoft/soy/ajax/utils/I18nUtils.java#L44-L76
padrig64/ValidationFramework
validationframework-swing/src/main/java/com/google/code/validationframework/swing/decoration/AbstractComponentDecoration.java
AbstractComponentDecoration.updateDecorationPainterUnclippedBounds
private void updateDecorationPainterUnclippedBounds(JLayeredPane layeredPane, Point relativeLocationToOwner) { Rectangle decorationBoundsInLayeredPane; if (layeredPane == null) { decorationBoundsInLayeredPane = new Rectangle(); } else { // Calculate location of the decorated component in the layered pane containing the decoration painter Point decoratedComponentLocationInLayeredPane = SwingUtilities.convertPoint(decoratedComponent.getParent (), decoratedComponent.getLocation(), layeredPane); // Deduces the location of the decoration painter in the layered pane decorationBoundsInLayeredPane = new Rectangle(decoratedComponentLocationInLayeredPane.x + relativeLocationToOwner.x, decoratedComponentLocationInLayeredPane.y + relativeLocationToOwner.y, getWidth(), getHeight()); } // Update decoration painter decorationPainter.setBounds(decorationBoundsInLayeredPane); }
java
private void updateDecorationPainterUnclippedBounds(JLayeredPane layeredPane, Point relativeLocationToOwner) { Rectangle decorationBoundsInLayeredPane; if (layeredPane == null) { decorationBoundsInLayeredPane = new Rectangle(); } else { // Calculate location of the decorated component in the layered pane containing the decoration painter Point decoratedComponentLocationInLayeredPane = SwingUtilities.convertPoint(decoratedComponent.getParent (), decoratedComponent.getLocation(), layeredPane); // Deduces the location of the decoration painter in the layered pane decorationBoundsInLayeredPane = new Rectangle(decoratedComponentLocationInLayeredPane.x + relativeLocationToOwner.x, decoratedComponentLocationInLayeredPane.y + relativeLocationToOwner.y, getWidth(), getHeight()); } // Update decoration painter decorationPainter.setBounds(decorationBoundsInLayeredPane); }
[ "private", "void", "updateDecorationPainterUnclippedBounds", "(", "JLayeredPane", "layeredPane", ",", "Point", "relativeLocationToOwner", ")", "{", "Rectangle", "decorationBoundsInLayeredPane", ";", "if", "(", "layeredPane", "==", "null", ")", "{", "decorationBoundsInLayere...
Calculates and updates the unclipped bounds of the decoration painter in layered pane coordinates. @param layeredPane Layered pane containing the decoration painter. @param relativeLocationToOwner Location of the decoration painter relatively to the decorated component.
[ "Calculates", "and", "updates", "the", "unclipped", "bounds", "of", "the", "decoration", "painter", "in", "layered", "pane", "coordinates", "." ]
train
https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-swing/src/main/java/com/google/code/validationframework/swing/decoration/AbstractComponentDecoration.java#L665-L683