repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
zsoltk/overpasser
library/src/main/java/hu/supercluster/overpasser/library/query/OverpassFilterQuery.java
OverpassFilterQuery.boundingBox
public OverpassFilterQuery boundingBox(double southernLat, double westernLon, double northernLat, double easternLon) { """ Adds a <i>(southernLat,westernLon,northernLat,easternLon)</i> bounding box filter to the current query. @param southernLat the southern latitude @param westernLon the western longitude @param northernLat the northern latitude @param easternLon the eastern longitude @return the current query object """ builder.boundingBox(southernLat, westernLon, northernLat, easternLon); return this; }
java
public OverpassFilterQuery boundingBox(double southernLat, double westernLon, double northernLat, double easternLon) { builder.boundingBox(southernLat, westernLon, northernLat, easternLon); return this; }
[ "public", "OverpassFilterQuery", "boundingBox", "(", "double", "southernLat", ",", "double", "westernLon", ",", "double", "northernLat", ",", "double", "easternLon", ")", "{", "builder", ".", "boundingBox", "(", "southernLat", ",", "westernLon", ",", "northernLat", ...
Adds a <i>(southernLat,westernLon,northernLat,easternLon)</i> bounding box filter to the current query. @param southernLat the southern latitude @param westernLon the western longitude @param northernLat the northern latitude @param easternLon the eastern longitude @return the current query object
[ "Adds", "a", "<i", ">", "(", "southernLat", "westernLon", "northernLat", "easternLon", ")", "<", "/", "i", ">", "bounding", "box", "filter", "to", "the", "current", "query", "." ]
train
https://github.com/zsoltk/overpasser/blob/0464d3844e75c5f9393d2458d3a3aedf3e40f30d/library/src/main/java/hu/supercluster/overpasser/library/query/OverpassFilterQuery.java#L221-L225
Stratio/deep-spark
deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/RangeUtils.java
RangeUtils.fetchTokens
static Map<String, Iterable<Comparable>> fetchTokens(String query, final Pair<Session, String> sessionWithHost, IPartitioner partitioner) { """ Gets the list of token for each cluster machine.<br/> The concrete class of the token depends on the partitioner used.<br/> @param query the query to execute against the given session to obtain the list of tokens. @param sessionWithHost the pair object containing both the session and the name of the machine to which we're connected to. @param partitioner the partitioner used in the cluster. @return a map containing, for each cluster machine, the list of tokens. Tokens are not returned in any particular order. """ ResultSet rSet = sessionWithHost.left.execute(query); final AbstractType tkValidator = partitioner.getTokenValidator(); final Map<String, Iterable<Comparable>> tokens = Maps.newHashMap(); Iterable<Pair<String, Iterable<Comparable>>> pairs = transform(rSet.all(), new FetchTokensRowPairFunction(sessionWithHost, tkValidator)); for (Pair<String, Iterable<Comparable>> pair : pairs) { tokens.put(pair.left, pair.right); } return tokens; }
java
static Map<String, Iterable<Comparable>> fetchTokens(String query, final Pair<Session, String> sessionWithHost, IPartitioner partitioner) { ResultSet rSet = sessionWithHost.left.execute(query); final AbstractType tkValidator = partitioner.getTokenValidator(); final Map<String, Iterable<Comparable>> tokens = Maps.newHashMap(); Iterable<Pair<String, Iterable<Comparable>>> pairs = transform(rSet.all(), new FetchTokensRowPairFunction(sessionWithHost, tkValidator)); for (Pair<String, Iterable<Comparable>> pair : pairs) { tokens.put(pair.left, pair.right); } return tokens; }
[ "static", "Map", "<", "String", ",", "Iterable", "<", "Comparable", ">", ">", "fetchTokens", "(", "String", "query", ",", "final", "Pair", "<", "Session", ",", "String", ">", "sessionWithHost", ",", "IPartitioner", "partitioner", ")", "{", "ResultSet", "rSet...
Gets the list of token for each cluster machine.<br/> The concrete class of the token depends on the partitioner used.<br/> @param query the query to execute against the given session to obtain the list of tokens. @param sessionWithHost the pair object containing both the session and the name of the machine to which we're connected to. @param partitioner the partitioner used in the cluster. @return a map containing, for each cluster machine, the list of tokens. Tokens are not returned in any particular order.
[ "Gets", "the", "list", "of", "token", "for", "each", "cluster", "machine", ".", "<br", "/", ">", "The", "concrete", "class", "of", "the", "token", "depends", "on", "the", "partitioner", "used", ".", "<br", "/", ">" ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/RangeUtils.java#L80-L96
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedinstallationTemplate/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedinstallationTemplate.java
ApiOvhDedicatedinstallationTemplate.templateName_GET
public OvhTemplates templateName_GET(String templateName) throws IOException { """ Get this object properties REST: GET /dedicated/installationTemplate/{templateName} @param templateName [required] This template name """ String qPath = "/dedicated/installationTemplate/{templateName}"; StringBuilder sb = path(qPath, templateName); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhTemplates.class); }
java
public OvhTemplates templateName_GET(String templateName) throws IOException { String qPath = "/dedicated/installationTemplate/{templateName}"; StringBuilder sb = path(qPath, templateName); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhTemplates.class); }
[ "public", "OvhTemplates", "templateName_GET", "(", "String", "templateName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicated/installationTemplate/{templateName}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "templateName", ")",...
Get this object properties REST: GET /dedicated/installationTemplate/{templateName} @param templateName [required] This template name
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedinstallationTemplate/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedinstallationTemplate.java#L29-L34
landawn/AbacusUtil
src/com/landawn/abacus/logging/AbstractLogger.java
AbstractLogger.format
static String format(String template, Object... args) { """ Note that this is somewhat-improperly used from Verify.java as well. """ template = String.valueOf(template); // null -> "null" if (N.isNullOrEmpty(args)) { return template; } // start substituting the arguments into the '%s' placeholders final StringBuilder sb = Objectory.createStringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; String placeholder = "{}"; int placeholderStart = template.indexOf(placeholder); if (placeholderStart < 0) { placeholder = "%s"; placeholderStart = template.indexOf(placeholder); } while (placeholderStart >= 0 && i < args.length) { sb.append(template, templateStart, placeholderStart); sb.append(N.toString(args[i++])); templateStart = placeholderStart + 2; placeholderStart = template.indexOf(placeholder, templateStart); } sb.append(template, templateStart, template.length()); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { sb.append(" ["); sb.append(N.toString(args[i++])); while (i < args.length) { sb.append(", "); sb.append(N.toString(args[i++])); } sb.append(']'); } final String result = sb.toString(); Objectory.recycle(sb); return result; }
java
static String format(String template, Object... args) { template = String.valueOf(template); // null -> "null" if (N.isNullOrEmpty(args)) { return template; } // start substituting the arguments into the '%s' placeholders final StringBuilder sb = Objectory.createStringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; String placeholder = "{}"; int placeholderStart = template.indexOf(placeholder); if (placeholderStart < 0) { placeholder = "%s"; placeholderStart = template.indexOf(placeholder); } while (placeholderStart >= 0 && i < args.length) { sb.append(template, templateStart, placeholderStart); sb.append(N.toString(args[i++])); templateStart = placeholderStart + 2; placeholderStart = template.indexOf(placeholder, templateStart); } sb.append(template, templateStart, template.length()); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { sb.append(" ["); sb.append(N.toString(args[i++])); while (i < args.length) { sb.append(", "); sb.append(N.toString(args[i++])); } sb.append(']'); } final String result = sb.toString(); Objectory.recycle(sb); return result; }
[ "static", "String", "format", "(", "String", "template", ",", "Object", "...", "args", ")", "{", "template", "=", "String", ".", "valueOf", "(", "template", ")", ";", "// null -> \"null\"\r", "if", "(", "N", ".", "isNullOrEmpty", "(", "args", ")", ")", "...
Note that this is somewhat-improperly used from Verify.java as well.
[ "Note", "that", "this", "is", "somewhat", "-", "improperly", "used", "from", "Verify", ".", "java", "as", "well", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/logging/AbstractLogger.java#L578-L623
Stratio/stratio-cassandra
src/java/org/apache/cassandra/metrics/ColumnFamilyMetrics.java
ColumnFamilyMetrics.createColumnFamilyHistogram
protected ColumnFamilyHistogram createColumnFamilyHistogram(String name, Histogram keyspaceHistogram) { """ Create a histogram-like interface that will register both a CF, keyspace and global level histogram and forward any updates to both """ Histogram cfHistogram = Metrics.newHistogram(factory.createMetricName(name), true); register(name, cfHistogram); return new ColumnFamilyHistogram(cfHistogram, keyspaceHistogram, Metrics.newHistogram(globalNameFactory.createMetricName(name), true)); }
java
protected ColumnFamilyHistogram createColumnFamilyHistogram(String name, Histogram keyspaceHistogram) { Histogram cfHistogram = Metrics.newHistogram(factory.createMetricName(name), true); register(name, cfHistogram); return new ColumnFamilyHistogram(cfHistogram, keyspaceHistogram, Metrics.newHistogram(globalNameFactory.createMetricName(name), true)); }
[ "protected", "ColumnFamilyHistogram", "createColumnFamilyHistogram", "(", "String", "name", ",", "Histogram", "keyspaceHistogram", ")", "{", "Histogram", "cfHistogram", "=", "Metrics", ".", "newHistogram", "(", "factory", ".", "createMetricName", "(", "name", ")", ","...
Create a histogram-like interface that will register both a CF, keyspace and global level histogram and forward any updates to both
[ "Create", "a", "histogram", "-", "like", "interface", "that", "will", "register", "both", "a", "CF", "keyspace", "and", "global", "level", "histogram", "and", "forward", "any", "updates", "to", "both" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/metrics/ColumnFamilyMetrics.java#L698-L703
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancersInner.java
LoadBalancersInner.beginCreateOrUpdateAsync
public Observable<LoadBalancerInner> beginCreateOrUpdateAsync(String resourceGroupName, String loadBalancerName, LoadBalancerInner parameters) { """ Creates or updates a load balancer. @param resourceGroupName The name of the resource group. @param loadBalancerName The name of the load balancer. @param parameters Parameters supplied to the create or update load balancer operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the LoadBalancerInner object """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, loadBalancerName, parameters).map(new Func1<ServiceResponse<LoadBalancerInner>, LoadBalancerInner>() { @Override public LoadBalancerInner call(ServiceResponse<LoadBalancerInner> response) { return response.body(); } }); }
java
public Observable<LoadBalancerInner> beginCreateOrUpdateAsync(String resourceGroupName, String loadBalancerName, LoadBalancerInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, loadBalancerName, parameters).map(new Func1<ServiceResponse<LoadBalancerInner>, LoadBalancerInner>() { @Override public LoadBalancerInner call(ServiceResponse<LoadBalancerInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "LoadBalancerInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "loadBalancerName", ",", "LoadBalancerInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceG...
Creates or updates a load balancer. @param resourceGroupName The name of the resource group. @param loadBalancerName The name of the load balancer. @param parameters Parameters supplied to the create or update load balancer operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the LoadBalancerInner object
[ "Creates", "or", "updates", "a", "load", "balancer", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancersInner.java#L546-L553
googleads/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java
ProductPartitionTreeImpl.createAdGroupTree
static ProductPartitionTreeImpl createAdGroupTree(Long adGroupId, BiddingStrategyConfiguration biddingStrategyConfig, List<AdGroupCriterion> adGroupCriteria) { """ Returns a new instance of this class based on the collection of ad group criteria provided. <p>NOTE: If retrieving existing criteria for use with this method, you must include all of the fields in {@link #REQUIRED_SELECTOR_FIELD_ENUMS} in your {@link Selector}. @param adGroupId the ID of the ad group @param biddingStrategyConfig the {@link BiddingStrategyConfiguration} for the ad group @param adGroupCriteria the non-null (but possibly empty) list of ad group criteria @throws NullPointerException if any argument is null, any element in {@code adGroupCriteria} is null, or any required field from {@link #REQUIRED_SELECTOR_FIELD_ENUMS} is missing from an element in {@code adGroupCriteria} @throws IllegalArgumentException if {@code adGroupCriteria} does not include the root criterion of the product partition tree """ Preconditions.checkNotNull(adGroupId, "Null ad group ID"); Preconditions.checkNotNull(biddingStrategyConfig, "Null bidding strategy configuration"); Preconditions.checkNotNull(adGroupCriteria, "Null criteria list"); if (adGroupCriteria.isEmpty()) { return createEmptyAdGroupTree(adGroupId, biddingStrategyConfig); } ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create(); for (AdGroupCriterion adGroupCriterion : adGroupCriteria) { Preconditions.checkNotNull(adGroupCriterion.getCriterion(), "AdGroupCriterion has a null criterion"); if (adGroupCriterion instanceof BiddableAdGroupCriterion) { BiddableAdGroupCriterion biddableCriterion = (BiddableAdGroupCriterion) adGroupCriterion; Preconditions.checkNotNull(biddableCriterion.getUserStatus(), "User status is null for criterion ID %s", biddableCriterion.getCriterion().getId()); if (UserStatus.REMOVED.equals(biddableCriterion.getUserStatus())) { // Skip REMOVED criteria. continue; } } if (adGroupCriterion.getCriterion() instanceof ProductPartition) { ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion(); parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion); } } return createNonEmptyAdGroupTree(adGroupId, parentIdMap); }
java
static ProductPartitionTreeImpl createAdGroupTree(Long adGroupId, BiddingStrategyConfiguration biddingStrategyConfig, List<AdGroupCriterion> adGroupCriteria) { Preconditions.checkNotNull(adGroupId, "Null ad group ID"); Preconditions.checkNotNull(biddingStrategyConfig, "Null bidding strategy configuration"); Preconditions.checkNotNull(adGroupCriteria, "Null criteria list"); if (adGroupCriteria.isEmpty()) { return createEmptyAdGroupTree(adGroupId, biddingStrategyConfig); } ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create(); for (AdGroupCriterion adGroupCriterion : adGroupCriteria) { Preconditions.checkNotNull(adGroupCriterion.getCriterion(), "AdGroupCriterion has a null criterion"); if (adGroupCriterion instanceof BiddableAdGroupCriterion) { BiddableAdGroupCriterion biddableCriterion = (BiddableAdGroupCriterion) adGroupCriterion; Preconditions.checkNotNull(biddableCriterion.getUserStatus(), "User status is null for criterion ID %s", biddableCriterion.getCriterion().getId()); if (UserStatus.REMOVED.equals(biddableCriterion.getUserStatus())) { // Skip REMOVED criteria. continue; } } if (adGroupCriterion.getCriterion() instanceof ProductPartition) { ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion(); parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion); } } return createNonEmptyAdGroupTree(adGroupId, parentIdMap); }
[ "static", "ProductPartitionTreeImpl", "createAdGroupTree", "(", "Long", "adGroupId", ",", "BiddingStrategyConfiguration", "biddingStrategyConfig", ",", "List", "<", "AdGroupCriterion", ">", "adGroupCriteria", ")", "{", "Preconditions", ".", "checkNotNull", "(", "adGroupId",...
Returns a new instance of this class based on the collection of ad group criteria provided. <p>NOTE: If retrieving existing criteria for use with this method, you must include all of the fields in {@link #REQUIRED_SELECTOR_FIELD_ENUMS} in your {@link Selector}. @param adGroupId the ID of the ad group @param biddingStrategyConfig the {@link BiddingStrategyConfiguration} for the ad group @param adGroupCriteria the non-null (but possibly empty) list of ad group criteria @throws NullPointerException if any argument is null, any element in {@code adGroupCriteria} is null, or any required field from {@link #REQUIRED_SELECTOR_FIELD_ENUMS} is missing from an element in {@code adGroupCriteria} @throws IllegalArgumentException if {@code adGroupCriteria} does not include the root criterion of the product partition tree
[ "Returns", "a", "new", "instance", "of", "this", "class", "based", "on", "the", "collection", "of", "ad", "group", "criteria", "provided", ".", "<p", ">", "NOTE", ":", "If", "retrieving", "existing", "criteria", "for", "use", "with", "this", "method", "you...
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java#L247-L276
berkesa/datatree
src/main/java/io/datatree/dom/TreeReaderRegistry.java
TreeReaderRegistry.setReader
public static final void setReader(String format, TreeReader reader) { """ Binds the given TreeReader instance to the specified data format. @param format name of the format (eg. "json", "xml", "csv", etc.) @param reader TreeReader instance for parsing the specified format """ String key = format.toLowerCase(); readers.put(key, reader); if (JSON.equals(key)) { cachedJsonReader = reader; } }
java
public static final void setReader(String format, TreeReader reader) { String key = format.toLowerCase(); readers.put(key, reader); if (JSON.equals(key)) { cachedJsonReader = reader; } }
[ "public", "static", "final", "void", "setReader", "(", "String", "format", ",", "TreeReader", "reader", ")", "{", "String", "key", "=", "format", ".", "toLowerCase", "(", ")", ";", "readers", ".", "put", "(", "key", ",", "reader", ")", ";", "if", "(", ...
Binds the given TreeReader instance to the specified data format. @param format name of the format (eg. "json", "xml", "csv", etc.) @param reader TreeReader instance for parsing the specified format
[ "Binds", "the", "given", "TreeReader", "instance", "to", "the", "specified", "data", "format", "." ]
train
https://github.com/berkesa/datatree/blob/79aea9b45c7b46ab28af0a09310bc01c421c6b3a/src/main/java/io/datatree/dom/TreeReaderRegistry.java#L62-L68
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java
CheckArg.hasSizeOfAtMost
public static void hasSizeOfAtMost( Object[] argument, int maximumSize, String name ) { """ Check that the array contains no more than the supplied number of elements @param argument the array @param maximumSize the maximum size @param name The name of the argument @throws IllegalArgumentException If the array has a size smaller than the supplied value """ isNotNull(argument, name); if (argument.length > maximumSize) { throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Object[].class.getSimpleName(), argument.length, maximumSize)); } }
java
public static void hasSizeOfAtMost( Object[] argument, int maximumSize, String name ) { isNotNull(argument, name); if (argument.length > maximumSize) { throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Object[].class.getSimpleName(), argument.length, maximumSize)); } }
[ "public", "static", "void", "hasSizeOfAtMost", "(", "Object", "[", "]", "argument", ",", "int", "maximumSize", ",", "String", "name", ")", "{", "isNotNull", "(", "argument", ",", "name", ")", ";", "if", "(", "argument", ".", "length", ">", "maximumSize", ...
Check that the array contains no more than the supplied number of elements @param argument the array @param maximumSize the maximum size @param name The name of the argument @throws IllegalArgumentException If the array has a size smaller than the supplied value
[ "Check", "that", "the", "array", "contains", "no", "more", "than", "the", "supplied", "number", "of", "elements" ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L815-L823
lessthanoptimal/ejml
main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java
CommonOps_DSCC.minCols
public static DMatrixRMaj minCols(DMatrixSparseCSC input , @Nullable DMatrixRMaj output ) { """ <p> Computes the minimum of each column in the input matrix and returns the results in a vector:<br> <br> b<sub>j</sub> = min(i=1:m ; a<sub>ij</sub>) </p> @param input Input matrix @param output Optional storage for output. Reshaped into a row vector. Modified. @return Vector containing the minimums of each column """ if( output == null ) { output = new DMatrixRMaj(1,input.numCols); } else { output.reshape(1,input.numCols); } for (int col = 0; col < input.numCols; col++) { int idx0 = input.col_idx[col]; int idx1 = input.col_idx[col + 1]; // take in account the zeros double min = idx1-idx0 == input.numRows ? Double.MAX_VALUE : 0; for (int i = idx0; i < idx1; i++) { double v = input.nz_values[i]; if( min > v ) { min = v; } } output.data[col] = min; } return output; }
java
public static DMatrixRMaj minCols(DMatrixSparseCSC input , @Nullable DMatrixRMaj output ) { if( output == null ) { output = new DMatrixRMaj(1,input.numCols); } else { output.reshape(1,input.numCols); } for (int col = 0; col < input.numCols; col++) { int idx0 = input.col_idx[col]; int idx1 = input.col_idx[col + 1]; // take in account the zeros double min = idx1-idx0 == input.numRows ? Double.MAX_VALUE : 0; for (int i = idx0; i < idx1; i++) { double v = input.nz_values[i]; if( min > v ) { min = v; } } output.data[col] = min; } return output; }
[ "public", "static", "DMatrixRMaj", "minCols", "(", "DMatrixSparseCSC", "input", ",", "@", "Nullable", "DMatrixRMaj", "output", ")", "{", "if", "(", "output", "==", "null", ")", "{", "output", "=", "new", "DMatrixRMaj", "(", "1", ",", "input", ".", "numCols...
<p> Computes the minimum of each column in the input matrix and returns the results in a vector:<br> <br> b<sub>j</sub> = min(i=1:m ; a<sub>ij</sub>) </p> @param input Input matrix @param output Optional storage for output. Reshaped into a row vector. Modified. @return Vector containing the minimums of each column
[ "<p", ">", "Computes", "the", "minimum", "of", "each", "column", "in", "the", "input", "matrix", "and", "returns", "the", "results", "in", "a", "vector", ":", "<br", ">", "<br", ">", "b<sub", ">", "j<", "/", "sub", ">", "=", "min", "(", "i", "=", ...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L1321-L1344
xebia/Xebium
src/main/java/com/xebia/incubator/xebium/SeleniumDriverFixture.java
SeleniumDriverFixture.doOn
public boolean doOn(final String command, final String target) { """ <p><code> | ensure | do | <i>open</i> | on | <i>/</i> | </code></p> @param command @param target @return """ LOG.info("Performing | " + command + " | " + target + " |"); return executeDoCommand(command, new String[] { unalias(target) }); }
java
public boolean doOn(final String command, final String target) { LOG.info("Performing | " + command + " | " + target + " |"); return executeDoCommand(command, new String[] { unalias(target) }); }
[ "public", "boolean", "doOn", "(", "final", "String", "command", ",", "final", "String", "target", ")", "{", "LOG", ".", "info", "(", "\"Performing | \"", "+", "command", "+", "\" | \"", "+", "target", "+", "\" |\"", ")", ";", "return", "executeDoCommand", ...
<p><code> | ensure | do | <i>open</i> | on | <i>/</i> | </code></p> @param command @param target @return
[ "<p", ">", "<code", ">", "|", "ensure", "|", "do", "|", "<i", ">", "open<", "/", "i", ">", "|", "on", "|", "<i", ">", "/", "<", "/", "i", ">", "|", "<", "/", "code", ">", "<", "/", "p", ">" ]
train
https://github.com/xebia/Xebium/blob/594f6d9e65622acdbd03dba0700b17645981da1f/src/main/java/com/xebia/incubator/xebium/SeleniumDriverFixture.java#L355-L358
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.addWorkingDaysToDate
public static Date addWorkingDaysToDate(Date date, int days) { """ Adds the given number of working days to the given date. A working day is specified as a regular Norwegian working day, excluding weekends and all national holidays. <p/> Example 1:<br/> - Add 5 working days to Wednesday 21.03.2007 -> Yields Wednesday 28.03.2007. (skipping saturday and sunday)<br/> <p/> Example 2:<br/> - Add 5 working days to Wednesday 04.04.2007 (day before easter-long-weekend) -> yields Monday 16.04.2007 (skipping 2 weekends and 3 weekday holidays). @param date The original date. @param days The number of working days to add. @return The new date. """ Calendar cal = dateToCalendar(date); for (int i = 0; i < days; i++) { cal.add(Calendar.DATE, 1); while (!isWorkingDay(cal)) { cal.add(Calendar.DATE, 1); } } return cal.getTime(); }
java
public static Date addWorkingDaysToDate(Date date, int days) { Calendar cal = dateToCalendar(date); for (int i = 0; i < days; i++) { cal.add(Calendar.DATE, 1); while (!isWorkingDay(cal)) { cal.add(Calendar.DATE, 1); } } return cal.getTime(); }
[ "public", "static", "Date", "addWorkingDaysToDate", "(", "Date", "date", ",", "int", "days", ")", "{", "Calendar", "cal", "=", "dateToCalendar", "(", "date", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "days", ";", "i", "++", ")", "{...
Adds the given number of working days to the given date. A working day is specified as a regular Norwegian working day, excluding weekends and all national holidays. <p/> Example 1:<br/> - Add 5 working days to Wednesday 21.03.2007 -> Yields Wednesday 28.03.2007. (skipping saturday and sunday)<br/> <p/> Example 2:<br/> - Add 5 working days to Wednesday 04.04.2007 (day before easter-long-weekend) -> yields Monday 16.04.2007 (skipping 2 weekends and 3 weekday holidays). @param date The original date. @param days The number of working days to add. @return The new date.
[ "Adds", "the", "given", "number", "of", "working", "days", "to", "the", "given", "date", ".", "A", "working", "day", "is", "specified", "as", "a", "regular", "Norwegian", "working", "day", "excluding", "weekends", "and", "all", "national", "holidays", ".", ...
train
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L39-L50
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urls/URLRewriterService.java
URLRewriterService.registerURLRewriter
public static boolean registerURLRewriter( ServletRequest request, URLRewriter rewriter ) { """ Register a URLRewriter (add to a list) in the request. It will be added to the end of a list of URLRewriter objects and will be used if {@link #rewriteURL} is called. @param request the current ServletRequest. @param rewriter the URLRewriter to register. @return <code>false</code> if a URLRewriter has been registered that does not allow other rewriters. Otherwise, <code>true</code> if the URLRewriter was added to the chain or already exists in the chain. """ ArrayList/*< URLRewriter >*/ rewriters = getRewriters( request ); if ( rewriters == null ) { rewriters = new ArrayList/*< URLRewriter >*/(); rewriters.add( rewriter ); request.setAttribute( URL_REWRITERS_KEY, rewriters ); } else { return addRewriter( rewriters, rewriter, rewriters.size() ); } return true; }
java
public static boolean registerURLRewriter( ServletRequest request, URLRewriter rewriter ) { ArrayList/*< URLRewriter >*/ rewriters = getRewriters( request ); if ( rewriters == null ) { rewriters = new ArrayList/*< URLRewriter >*/(); rewriters.add( rewriter ); request.setAttribute( URL_REWRITERS_KEY, rewriters ); } else { return addRewriter( rewriters, rewriter, rewriters.size() ); } return true; }
[ "public", "static", "boolean", "registerURLRewriter", "(", "ServletRequest", "request", ",", "URLRewriter", "rewriter", ")", "{", "ArrayList", "/*< URLRewriter >*/", "rewriters", "=", "getRewriters", "(", "request", ")", ";", "if", "(", "rewriters", "==", "null", ...
Register a URLRewriter (add to a list) in the request. It will be added to the end of a list of URLRewriter objects and will be used if {@link #rewriteURL} is called. @param request the current ServletRequest. @param rewriter the URLRewriter to register. @return <code>false</code> if a URLRewriter has been registered that does not allow other rewriters. Otherwise, <code>true</code> if the URLRewriter was added to the chain or already exists in the chain.
[ "Register", "a", "URLRewriter", "(", "add", "to", "a", "list", ")", "in", "the", "request", ".", "It", "will", "be", "added", "to", "the", "end", "of", "a", "list", "of", "URLRewriter", "objects", "and", "will", "be", "used", "if", "{", "@link", "#re...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urls/URLRewriterService.java#L183-L199
Netflix/karyon
karyon2-core/src/main/java/netflix/karyon/transport/http/SimpleUriRouter.java
SimpleUriRouter.addUri
public SimpleUriRouter<I, O> addUri(String uri, RequestHandler<I, O> handler) { """ Add a new URI -&lt; Handler route to this router. @param uri URI to match. @param handler Request handler. @return The updated router. """ routes.add(new Route(new ServletStyleUriConstraintKey<I>(uri, ""), handler)); return this; }
java
public SimpleUriRouter<I, O> addUri(String uri, RequestHandler<I, O> handler) { routes.add(new Route(new ServletStyleUriConstraintKey<I>(uri, ""), handler)); return this; }
[ "public", "SimpleUriRouter", "<", "I", ",", "O", ">", "addUri", "(", "String", "uri", ",", "RequestHandler", "<", "I", ",", "O", ">", "handler", ")", "{", "routes", ".", "add", "(", "new", "Route", "(", "new", "ServletStyleUriConstraintKey", "<", "I", ...
Add a new URI -&lt; Handler route to this router. @param uri URI to match. @param handler Request handler. @return The updated router.
[ "Add", "a", "new", "URI", "-", "&lt", ";", "Handler", "route", "to", "this", "router", "." ]
train
https://github.com/Netflix/karyon/blob/d50bc0ff37693ef3fbda373e90a109d1f92e0b9a/karyon2-core/src/main/java/netflix/karyon/transport/http/SimpleUriRouter.java#L50-L53
eclipse/xtext-core
org.eclipse.xtext/xtend-gen/org/eclipse/xtext/resource/persistence/ResourceStorageWritable.java
ResourceStorageWritable.writeEntries
protected void writeEntries(final StorageAwareResource resource, final ZipOutputStream zipOut) throws IOException { """ Write entries into the storage. Overriding methods should first delegate to super before adding their own entries. """ final BufferedOutputStream bufferedOutput = new BufferedOutputStream(zipOut); ZipEntry _zipEntry = new ZipEntry("emf-contents"); zipOut.putNextEntry(_zipEntry); try { this.writeContents(resource, bufferedOutput); } finally { bufferedOutput.flush(); zipOut.closeEntry(); } ZipEntry _zipEntry_1 = new ZipEntry("resource-description"); zipOut.putNextEntry(_zipEntry_1); try { this.writeResourceDescription(resource, bufferedOutput); } finally { bufferedOutput.flush(); zipOut.closeEntry(); } if (this.storeNodeModel) { ZipEntry _zipEntry_2 = new ZipEntry("node-model"); zipOut.putNextEntry(_zipEntry_2); try { this.writeNodeModel(resource, bufferedOutput); } finally { bufferedOutput.flush(); zipOut.closeEntry(); } } }
java
protected void writeEntries(final StorageAwareResource resource, final ZipOutputStream zipOut) throws IOException { final BufferedOutputStream bufferedOutput = new BufferedOutputStream(zipOut); ZipEntry _zipEntry = new ZipEntry("emf-contents"); zipOut.putNextEntry(_zipEntry); try { this.writeContents(resource, bufferedOutput); } finally { bufferedOutput.flush(); zipOut.closeEntry(); } ZipEntry _zipEntry_1 = new ZipEntry("resource-description"); zipOut.putNextEntry(_zipEntry_1); try { this.writeResourceDescription(resource, bufferedOutput); } finally { bufferedOutput.flush(); zipOut.closeEntry(); } if (this.storeNodeModel) { ZipEntry _zipEntry_2 = new ZipEntry("node-model"); zipOut.putNextEntry(_zipEntry_2); try { this.writeNodeModel(resource, bufferedOutput); } finally { bufferedOutput.flush(); zipOut.closeEntry(); } } }
[ "protected", "void", "writeEntries", "(", "final", "StorageAwareResource", "resource", ",", "final", "ZipOutputStream", "zipOut", ")", "throws", "IOException", "{", "final", "BufferedOutputStream", "bufferedOutput", "=", "new", "BufferedOutputStream", "(", "zipOut", ")"...
Write entries into the storage. Overriding methods should first delegate to super before adding their own entries.
[ "Write", "entries", "into", "the", "storage", ".", "Overriding", "methods", "should", "first", "delegate", "to", "super", "before", "adding", "their", "own", "entries", "." ]
train
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/resource/persistence/ResourceStorageWritable.java#L61-L89
pravega/pravega
segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/BookKeeperLog.java
BookKeeperLog.fetchLastAddConfirmed
@SneakyThrows(DurableDataLogException.class) private long fetchLastAddConfirmed(WriteLedger writeLedger, Map<Long, Long> lastAddsConfirmed) { """ Reliably gets the LastAddConfirmed for the WriteLedger @param writeLedger The WriteLedger to query. @param lastAddsConfirmed A Map of LedgerIds to LastAddConfirmed for each known ledger id. This is used as a cache and will be updated if necessary. @return The LastAddConfirmed for the WriteLedger. """ long ledgerId = writeLedger.ledger.getId(); long lac = lastAddsConfirmed.getOrDefault(ledgerId, -1L); long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "fetchLastAddConfirmed", ledgerId, lac); if (lac < 0) { if (writeLedger.isRolledOver()) { // This close was not due to failure, rather a rollover - hence lastAddConfirmed can be relied upon. lac = writeLedger.ledger.getLastAddConfirmed(); } else { // Ledger got closed. This could be due to some external factor, and lastAddConfirmed can't be relied upon. // We need to re-open the ledger to get fresh data. lac = Ledgers.readLastAddConfirmed(ledgerId, this.bookKeeper, this.config); } lastAddsConfirmed.put(ledgerId, lac); log.info("{}: Fetched actual LastAddConfirmed ({}) for LedgerId {}.", this.traceObjectId, lac, ledgerId); } LoggerHelpers.traceLeave(log, this.traceObjectId, "fetchLastAddConfirmed", traceId, ledgerId, lac); return lac; }
java
@SneakyThrows(DurableDataLogException.class) private long fetchLastAddConfirmed(WriteLedger writeLedger, Map<Long, Long> lastAddsConfirmed) { long ledgerId = writeLedger.ledger.getId(); long lac = lastAddsConfirmed.getOrDefault(ledgerId, -1L); long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "fetchLastAddConfirmed", ledgerId, lac); if (lac < 0) { if (writeLedger.isRolledOver()) { // This close was not due to failure, rather a rollover - hence lastAddConfirmed can be relied upon. lac = writeLedger.ledger.getLastAddConfirmed(); } else { // Ledger got closed. This could be due to some external factor, and lastAddConfirmed can't be relied upon. // We need to re-open the ledger to get fresh data. lac = Ledgers.readLastAddConfirmed(ledgerId, this.bookKeeper, this.config); } lastAddsConfirmed.put(ledgerId, lac); log.info("{}: Fetched actual LastAddConfirmed ({}) for LedgerId {}.", this.traceObjectId, lac, ledgerId); } LoggerHelpers.traceLeave(log, this.traceObjectId, "fetchLastAddConfirmed", traceId, ledgerId, lac); return lac; }
[ "@", "SneakyThrows", "(", "DurableDataLogException", ".", "class", ")", "private", "long", "fetchLastAddConfirmed", "(", "WriteLedger", "writeLedger", ",", "Map", "<", "Long", ",", "Long", ">", "lastAddsConfirmed", ")", "{", "long", "ledgerId", "=", "writeLedger",...
Reliably gets the LastAddConfirmed for the WriteLedger @param writeLedger The WriteLedger to query. @param lastAddsConfirmed A Map of LedgerIds to LastAddConfirmed for each known ledger id. This is used as a cache and will be updated if necessary. @return The LastAddConfirmed for the WriteLedger.
[ "Reliably", "gets", "the", "LastAddConfirmed", "for", "the", "WriteLedger" ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/BookKeeperLog.java#L523-L544
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
ApiOvhHostingweb.serviceName_email_bounces_GET
public ArrayList<OvhBounce> serviceName_email_bounces_GET(String serviceName, Long limit) throws IOException { """ Request the last bounces REST: GET /hosting/web/{serviceName}/email/bounces @param limit [required] Maximum bounces limit ( default : 20 / max : 100 ) @param serviceName [required] The internal name of your hosting """ String qPath = "/hosting/web/{serviceName}/email/bounces"; StringBuilder sb = path(qPath, serviceName); query(sb, "limit", limit); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t11); }
java
public ArrayList<OvhBounce> serviceName_email_bounces_GET(String serviceName, Long limit) throws IOException { String qPath = "/hosting/web/{serviceName}/email/bounces"; StringBuilder sb = path(qPath, serviceName); query(sb, "limit", limit); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t11); }
[ "public", "ArrayList", "<", "OvhBounce", ">", "serviceName_email_bounces_GET", "(", "String", "serviceName", ",", "Long", "limit", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/web/{serviceName}/email/bounces\"", ";", "StringBuilder", "sb", "=",...
Request the last bounces REST: GET /hosting/web/{serviceName}/email/bounces @param limit [required] Maximum bounces limit ( default : 20 / max : 100 ) @param serviceName [required] The internal name of your hosting
[ "Request", "the", "last", "bounces" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L1905-L1911
pmlopes/yoke
framework/src/main/java/com/jetdrone/vertx/yoke/middleware/YokeRequest.java
YokeRequest.getParam
public String getParam(@NotNull final String name, String defaultValue) { """ Allow getting parameters in a generified way and return defaultValue if the key does not exist. @param name The key to get @param defaultValue value returned when the key does not exist @return {String} The found object """ String value = getParam(name); if (value == null) { return defaultValue; } return value; }
java
public String getParam(@NotNull final String name, String defaultValue) { String value = getParam(name); if (value == null) { return defaultValue; } return value; }
[ "public", "String", "getParam", "(", "@", "NotNull", "final", "String", "name", ",", "String", "defaultValue", ")", "{", "String", "value", "=", "getParam", "(", "name", ")", ";", "if", "(", "value", "==", "null", ")", "{", "return", "defaultValue", ";",...
Allow getting parameters in a generified way and return defaultValue if the key does not exist. @param name The key to get @param defaultValue value returned when the key does not exist @return {String} The found object
[ "Allow", "getting", "parameters", "in", "a", "generified", "way", "and", "return", "defaultValue", "if", "the", "key", "does", "not", "exist", "." ]
train
https://github.com/pmlopes/yoke/blob/fe8a64036f09fb745f0644faddd46162d64faf3c/framework/src/main/java/com/jetdrone/vertx/yoke/middleware/YokeRequest.java#L602-L610
alexa/alexa-skills-kit-sdk-for-java
ask-sdk-core/src/com/amazon/ask/response/ResponseBuilder.java
ResponseBuilder.withReprompt
public ResponseBuilder withReprompt(String text, com.amazon.ask.model.ui.PlayBehavior playBehavior) { """ Sets {@link Reprompt} speech on the response. Speech is always wrapped in SSML tags. @param text reprompt text @param playBehavior determines the queuing and playback of this output speech @return response builder """ this.reprompt = Reprompt.builder() .withOutputSpeech(SsmlOutputSpeech.builder() .withSsml("<speak>" + trimOutputSpeech(text) + "</speak>") .withPlayBehavior(playBehavior) .build()) .build(); if (!this.isVideoAppLaunchDirectivePresent()) { this.shouldEndSession = false; } return this; }
java
public ResponseBuilder withReprompt(String text, com.amazon.ask.model.ui.PlayBehavior playBehavior) { this.reprompt = Reprompt.builder() .withOutputSpeech(SsmlOutputSpeech.builder() .withSsml("<speak>" + trimOutputSpeech(text) + "</speak>") .withPlayBehavior(playBehavior) .build()) .build(); if (!this.isVideoAppLaunchDirectivePresent()) { this.shouldEndSession = false; } return this; }
[ "public", "ResponseBuilder", "withReprompt", "(", "String", "text", ",", "com", ".", "amazon", ".", "ask", ".", "model", ".", "ui", ".", "PlayBehavior", "playBehavior", ")", "{", "this", ".", "reprompt", "=", "Reprompt", ".", "builder", "(", ")", ".", "w...
Sets {@link Reprompt} speech on the response. Speech is always wrapped in SSML tags. @param text reprompt text @param playBehavior determines the queuing and playback of this output speech @return response builder
[ "Sets", "{", "@link", "Reprompt", "}", "speech", "on", "the", "response", ".", "Speech", "is", "always", "wrapped", "in", "SSML", "tags", "." ]
train
https://github.com/alexa/alexa-skills-kit-sdk-for-java/blob/c49194da0693898c70f3f2c4a372f5a12da04e3e/ask-sdk-core/src/com/amazon/ask/response/ResponseBuilder.java#L183-L196
Erudika/para
para-core/src/main/java/com/erudika/para/utils/Utils.java
Utils.formatDate
public static String formatDate(String format, Locale loc) { """ Formats the date for today, in a specific format. @param format the date format @param loc the locale instance @return today's date formatted """ return formatDate(timestamp(), format, loc); }
java
public static String formatDate(String format, Locale loc) { return formatDate(timestamp(), format, loc); }
[ "public", "static", "String", "formatDate", "(", "String", "format", ",", "Locale", "loc", ")", "{", "return", "formatDate", "(", "timestamp", "(", ")", ",", "format", ",", "loc", ")", ";", "}" ]
Formats the date for today, in a specific format. @param format the date format @param loc the locale instance @return today's date formatted
[ "Formats", "the", "date", "for", "today", "in", "a", "specific", "format", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-core/src/main/java/com/erudika/para/utils/Utils.java#L468-L470
OpenLiberty/open-liberty
dev/com.ibm.ws.session/src/com/ibm/ws/session/SessionAffinityManager.java
SessionAffinityManager.getInUseSessionVersion
@Override public int getInUseSessionVersion(ServletRequest req, SessionAffinityContext sac) { """ /* Method to get the appropriate version to use for a new session. May be the response session id if the request has been dispatched adn the response version is already set """ int version = sac.getResponseSessionVersion(); if (version == -1) { // not set, use request version version = sac.getRequestedSessionVersion(); } return version; }
java
@Override public int getInUseSessionVersion(ServletRequest req, SessionAffinityContext sac) { int version = sac.getResponseSessionVersion(); if (version == -1) { // not set, use request version version = sac.getRequestedSessionVersion(); } return version; }
[ "@", "Override", "public", "int", "getInUseSessionVersion", "(", "ServletRequest", "req", ",", "SessionAffinityContext", "sac", ")", "{", "int", "version", "=", "sac", ".", "getResponseSessionVersion", "(", ")", ";", "if", "(", "version", "==", "-", "1", ")", ...
/* Method to get the appropriate version to use for a new session. May be the response session id if the request has been dispatched adn the response version is already set
[ "/", "*", "Method", "to", "get", "the", "appropriate", "version", "to", "use", "for", "a", "new", "session", ".", "May", "be", "the", "response", "session", "id", "if", "the", "request", "has", "been", "dispatched", "adn", "the", "response", "version", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.session/src/com/ibm/ws/session/SessionAffinityManager.java#L488-L495
rometools/rome
rome/src/main/java/com/rometools/rome/io/WireFeedInput.java
WireFeedInput.createSAXBuilder
protected SAXBuilder createSAXBuilder() { """ Creates and sets up a org.jdom2.input.SAXBuilder for parsing. @return a new org.jdom2.input.SAXBuilder object """ SAXBuilder saxBuilder; if (validate) { saxBuilder = new SAXBuilder(XMLReaders.DTDVALIDATING); } else { saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING); } saxBuilder.setEntityResolver(RESOLVER); // // This code is needed to fix the security problem outlined in // http://www.securityfocus.com/archive/1/297714 // // Unfortunately there isn't an easy way to check if an XML parser // supports a particular feature, so // we need to set it and catch the exception if it fails. We also need // to subclass the JDom SAXBuilder // class in order to get access to the underlying SAX parser - otherwise // the features don't get set until // we are already building the document, by which time it's too late to // fix the problem. // // Crimson is one parser which is known not to support these features. try { final XMLReader parser = saxBuilder.createParser(); setFeature(saxBuilder, parser, "http://xml.org/sax/features/external-general-entities", false); setFeature(saxBuilder, parser, "http://xml.org/sax/features/external-parameter-entities", false); setFeature(saxBuilder, parser, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); if(!allowDoctypes) { setFeature(saxBuilder, parser, "http://apache.org/xml/features/disallow-doctype-decl", true); } } catch (final JDOMException e) { throw new IllegalStateException("JDOM could not create a SAX parser", e); } saxBuilder.setExpandEntities(false); return saxBuilder; }
java
protected SAXBuilder createSAXBuilder() { SAXBuilder saxBuilder; if (validate) { saxBuilder = new SAXBuilder(XMLReaders.DTDVALIDATING); } else { saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING); } saxBuilder.setEntityResolver(RESOLVER); // // This code is needed to fix the security problem outlined in // http://www.securityfocus.com/archive/1/297714 // // Unfortunately there isn't an easy way to check if an XML parser // supports a particular feature, so // we need to set it and catch the exception if it fails. We also need // to subclass the JDom SAXBuilder // class in order to get access to the underlying SAX parser - otherwise // the features don't get set until // we are already building the document, by which time it's too late to // fix the problem. // // Crimson is one parser which is known not to support these features. try { final XMLReader parser = saxBuilder.createParser(); setFeature(saxBuilder, parser, "http://xml.org/sax/features/external-general-entities", false); setFeature(saxBuilder, parser, "http://xml.org/sax/features/external-parameter-entities", false); setFeature(saxBuilder, parser, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); if(!allowDoctypes) { setFeature(saxBuilder, parser, "http://apache.org/xml/features/disallow-doctype-decl", true); } } catch (final JDOMException e) { throw new IllegalStateException("JDOM could not create a SAX parser", e); } saxBuilder.setExpandEntities(false); return saxBuilder; }
[ "protected", "SAXBuilder", "createSAXBuilder", "(", ")", "{", "SAXBuilder", "saxBuilder", ";", "if", "(", "validate", ")", "{", "saxBuilder", "=", "new", "SAXBuilder", "(", "XMLReaders", ".", "DTDVALIDATING", ")", ";", "}", "else", "{", "saxBuilder", "=", "n...
Creates and sets up a org.jdom2.input.SAXBuilder for parsing. @return a new org.jdom2.input.SAXBuilder object
[ "Creates", "and", "sets", "up", "a", "org", ".", "jdom2", ".", "input", ".", "SAXBuilder", "for", "parsing", "." ]
train
https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/WireFeedInput.java#L322-L365
oehf/ipf-oht-atna
nodeauth/src/main/java/org/openhealthtools/ihe/atna/nodeauth/SecurityDomainManager.java
SecurityDomainManager.registerURItoSecurityDomain
public void registerURItoSecurityDomain(URI uri, String name) throws URISyntaxException { """ Registers the association of the given URI to the named security domain. Registration is only needed when a URI needs to use a security domain other than the default domain. <br>If the URI was previously registered with another domain that association is replaced with this new one. @param uri URI to register, may not be null @param name of SecurityDomain to associate @throws URISyntaxException @throws {@link IllegalArgumentException If the specified domain doesn't exist, or if the URI is null """ if (uri == null) throw new IllegalArgumentException("URI parameter cannot be null"); if (! securityDomains.containsKey(name) ) throw new IllegalArgumentException("Security domain "+name+" is not a configured security domain."); if (uriToSecurityDomain.containsKey(uri)) uriToSecurityDomain.remove(uri); uriToSecurityDomain.put(formatKey(uri), name); if (LOGGER.isDebugEnabled()) LOGGER.debug("Security domain "+name+" has been registered for URI "+uri.toString()); }
java
public void registerURItoSecurityDomain(URI uri, String name) throws URISyntaxException { if (uri == null) throw new IllegalArgumentException("URI parameter cannot be null"); if (! securityDomains.containsKey(name) ) throw new IllegalArgumentException("Security domain "+name+" is not a configured security domain."); if (uriToSecurityDomain.containsKey(uri)) uriToSecurityDomain.remove(uri); uriToSecurityDomain.put(formatKey(uri), name); if (LOGGER.isDebugEnabled()) LOGGER.debug("Security domain "+name+" has been registered for URI "+uri.toString()); }
[ "public", "void", "registerURItoSecurityDomain", "(", "URI", "uri", ",", "String", "name", ")", "throws", "URISyntaxException", "{", "if", "(", "uri", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"URI parameter cannot be null\"", ")", ";", ...
Registers the association of the given URI to the named security domain. Registration is only needed when a URI needs to use a security domain other than the default domain. <br>If the URI was previously registered with another domain that association is replaced with this new one. @param uri URI to register, may not be null @param name of SecurityDomain to associate @throws URISyntaxException @throws {@link IllegalArgumentException If the specified domain doesn't exist, or if the URI is null
[ "Registers", "the", "association", "of", "the", "given", "URI", "to", "the", "named", "security", "domain", ".", "Registration", "is", "only", "needed", "when", "a", "URI", "needs", "to", "use", "a", "security", "domain", "other", "than", "the", "default", ...
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/nodeauth/src/main/java/org/openhealthtools/ihe/atna/nodeauth/SecurityDomainManager.java#L117-L125
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
Logger.infof
public void infof(String format, Object param1) { """ Issue a formatted log message with a level of INFO. @param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor @param param1 the sole parameter """ if (isEnabled(Level.INFO)) { doLogf(Level.INFO, FQCN, format, new Object[] { param1 }, null); } }
java
public void infof(String format, Object param1) { if (isEnabled(Level.INFO)) { doLogf(Level.INFO, FQCN, format, new Object[] { param1 }, null); } }
[ "public", "void", "infof", "(", "String", "format", ",", "Object", "param1", ")", "{", "if", "(", "isEnabled", "(", "Level", ".", "INFO", ")", ")", "{", "doLogf", "(", "Level", ".", "INFO", ",", "FQCN", ",", "format", ",", "new", "Object", "[", "]"...
Issue a formatted log message with a level of INFO. @param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor @param param1 the sole parameter
[ "Issue", "a", "formatted", "log", "message", "with", "a", "level", "of", "INFO", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L1134-L1138
florent37/DaVinci
davinci/src/main/java/com/github/florent37/davinci/DaVinci.java
DaVinci.loadFromLruCache
private Bitmap loadFromLruCache(final String path, boolean tryFromDisk) { """ Try to load [path] image from cache @param path Path or Url of the bitmap @return Bitmap from cache if founded """ int key = getKey(path); Bitmap bitmap = mImagesCache.get(key); //try to retrieve from lruCache Log.d(TAG, "bitmap " + path + " from lruCache [" + key + "] " + bitmap); if (tryFromDisk && bitmap == null) { bitmap = loadFromDiskLruCache(key); //try to retrieve from disk cache Log.d(TAG, "bitmap " + path + " from diskLruCache " + bitmap); if (bitmap != null) { //if found on disk cache mImagesCache.put(key, bitmap); //save it into lruCache } } return bitmap; }
java
private Bitmap loadFromLruCache(final String path, boolean tryFromDisk) { int key = getKey(path); Bitmap bitmap = mImagesCache.get(key); //try to retrieve from lruCache Log.d(TAG, "bitmap " + path + " from lruCache [" + key + "] " + bitmap); if (tryFromDisk && bitmap == null) { bitmap = loadFromDiskLruCache(key); //try to retrieve from disk cache Log.d(TAG, "bitmap " + path + " from diskLruCache " + bitmap); if (bitmap != null) { //if found on disk cache mImagesCache.put(key, bitmap); //save it into lruCache } } return bitmap; }
[ "private", "Bitmap", "loadFromLruCache", "(", "final", "String", "path", ",", "boolean", "tryFromDisk", ")", "{", "int", "key", "=", "getKey", "(", "path", ")", ";", "Bitmap", "bitmap", "=", "mImagesCache", ".", "get", "(", "key", ")", ";", "//try to retri...
Try to load [path] image from cache @param path Path or Url of the bitmap @return Bitmap from cache if founded
[ "Try", "to", "load", "[", "path", "]", "image", "from", "cache" ]
train
https://github.com/florent37/DaVinci/blob/9c6ce4aa2df8e2288cd6ee8b57d9091b1b770a7a/davinci/src/main/java/com/github/florent37/davinci/DaVinci.java#L452-L470
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfStamper.java
PdfStamper.setThumbnail
public void setThumbnail(Image image, int page) throws PdfException, DocumentException { """ Sets the thumbnail image for a page. @param image the image @param page the page @throws PdfException on error @throws DocumentException on error """ stamper.setThumbnail(image, page); }
java
public void setThumbnail(Image image, int page) throws PdfException, DocumentException { stamper.setThumbnail(image, page); }
[ "public", "void", "setThumbnail", "(", "Image", "image", ",", "int", "page", ")", "throws", "PdfException", ",", "DocumentException", "{", "stamper", ".", "setThumbnail", "(", "image", ",", "page", ")", ";", "}" ]
Sets the thumbnail image for a page. @param image the image @param page the page @throws PdfException on error @throws DocumentException on error
[ "Sets", "the", "thumbnail", "image", "for", "a", "page", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfStamper.java#L468-L470
cdk/cdk
base/valencycheck/src/main/java/org/openscience/cdk/tools/AtomTypeAwareSaturationChecker.java
AtomTypeAwareSaturationChecker.checkBond
private void checkBond(IAtomContainer atomContainer, int index) throws CDKException { """ This method tries to set the bond order on the current bond. @param atomContainer The molecule @param index The index of the current bond @throws CDKException when no suitable solution can be found """ IBond bond = atomContainer.getBond(index); if (bond != null && bond.getFlag(CDKConstants.SINGLE_OR_DOUBLE)) { try { oldBondOrder = bond.getOrder(); bond.setOrder(IBond.Order.SINGLE); setMaxBondOrder(bond, atomContainer); } catch (CDKException e) { bond.setOrder(oldBondOrder); logger.debug(e); } } }
java
private void checkBond(IAtomContainer atomContainer, int index) throws CDKException { IBond bond = atomContainer.getBond(index); if (bond != null && bond.getFlag(CDKConstants.SINGLE_OR_DOUBLE)) { try { oldBondOrder = bond.getOrder(); bond.setOrder(IBond.Order.SINGLE); setMaxBondOrder(bond, atomContainer); } catch (CDKException e) { bond.setOrder(oldBondOrder); logger.debug(e); } } }
[ "private", "void", "checkBond", "(", "IAtomContainer", "atomContainer", ",", "int", "index", ")", "throws", "CDKException", "{", "IBond", "bond", "=", "atomContainer", ".", "getBond", "(", "index", ")", ";", "if", "(", "bond", "!=", "null", "&&", "bond", "...
This method tries to set the bond order on the current bond. @param atomContainer The molecule @param index The index of the current bond @throws CDKException when no suitable solution can be found
[ "This", "method", "tries", "to", "set", "the", "bond", "order", "on", "the", "current", "bond", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/valencycheck/src/main/java/org/openscience/cdk/tools/AtomTypeAwareSaturationChecker.java#L164-L177
pippo-java/pippo
pippo-controller-parent/pippo-controller/src/main/java/ro/pippo/controller/util/ClassUtils.java
ClassUtils.getAnnotation
public static <T extends Annotation> T getAnnotation(Method method, Class<T> annotationClass) { """ Extract the annotation from the controllerMethod or the declaring class. @param method @param annotationClass @param <T> @return the annotation or null """ T annotation = method.getAnnotation(annotationClass); if (annotation == null) { annotation = getAnnotation(method.getDeclaringClass(), annotationClass); } return annotation; }
java
public static <T extends Annotation> T getAnnotation(Method method, Class<T> annotationClass) { T annotation = method.getAnnotation(annotationClass); if (annotation == null) { annotation = getAnnotation(method.getDeclaringClass(), annotationClass); } return annotation; }
[ "public", "static", "<", "T", "extends", "Annotation", ">", "T", "getAnnotation", "(", "Method", "method", ",", "Class", "<", "T", ">", "annotationClass", ")", "{", "T", "annotation", "=", "method", ".", "getAnnotation", "(", "annotationClass", ")", ";", "...
Extract the annotation from the controllerMethod or the declaring class. @param method @param annotationClass @param <T> @return the annotation or null
[ "Extract", "the", "annotation", "from", "the", "controllerMethod", "or", "the", "declaring", "class", "." ]
train
https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-controller-parent/pippo-controller/src/main/java/ro/pippo/controller/util/ClassUtils.java#L155-L162
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceSubscriptionEntryPersistenceImpl.java
CommerceSubscriptionEntryPersistenceImpl.findByG_U
@Override public List<CommerceSubscriptionEntry> findByG_U(long groupId, long userId, int start, int end, OrderByComparator<CommerceSubscriptionEntry> orderByComparator) { """ Returns an ordered range of all the commerce subscription entries where groupId = &#63; and userId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceSubscriptionEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param userId the user ID @param start the lower bound of the range of commerce subscription entries @param end the upper bound of the range of commerce subscription entries (not inclusive) @param orderByComparator the comparator to order the results by (optionally <code>null</code>) @return the ordered range of matching commerce subscription entries """ return findByG_U(groupId, userId, start, end, orderByComparator, true); }
java
@Override public List<CommerceSubscriptionEntry> findByG_U(long groupId, long userId, int start, int end, OrderByComparator<CommerceSubscriptionEntry> orderByComparator) { return findByG_U(groupId, userId, start, end, orderByComparator, true); }
[ "@", "Override", "public", "List", "<", "CommerceSubscriptionEntry", ">", "findByG_U", "(", "long", "groupId", ",", "long", "userId", ",", "int", "start", ",", "int", "end", ",", "OrderByComparator", "<", "CommerceSubscriptionEntry", ">", "orderByComparator", ")",...
Returns an ordered range of all the commerce subscription entries where groupId = &#63; and userId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceSubscriptionEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param userId the user ID @param start the lower bound of the range of commerce subscription entries @param end the upper bound of the range of commerce subscription entries (not inclusive) @param orderByComparator the comparator to order the results by (optionally <code>null</code>) @return the ordered range of matching commerce subscription entries
[ "Returns", "an", "ordered", "range", "of", "all", "the", "commerce", "subscription", "entries", "where", "groupId", "=", "&#63", ";", "and", "userId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceSubscriptionEntryPersistenceImpl.java#L2618-L2623
Polidea/RxAndroidBle
rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/RxBleLog.java
RxBleLog.setLogger
@Deprecated public static void setLogger(@Nullable final Logger logger) { """ Old method to set a custom logger implementation, set it to {@code null} to use default logcat logging. It updates only the logger object. The rest of log settings remain unchanged. <p> Example how to forward logs to Timber:<br> <code> <pre> RxBleLog.setLogger(new RxBleLog.Logger() { &#64;Override public void log(final int level, final String tag, final String msg) { Timber.tag(tag).log(level, msg); } }); </pre> </code> @deprecated use {@link com.polidea.rxandroidble2.RxBleClient#updateLogOptions(LogOptions)} """ LogOptions.Logger loggerToSet = logger == null ? logcatLogger : new LogOptions.Logger() { @Override public void log(int level, String tag, String msg) { logger.log(level, tag, msg); } }; LogOptions newLogOptions = new LogOptions.Builder().setLogger(loggerToSet).build(); RxBleLog.updateLogOptions(newLogOptions); }
java
@Deprecated public static void setLogger(@Nullable final Logger logger) { LogOptions.Logger loggerToSet = logger == null ? logcatLogger : new LogOptions.Logger() { @Override public void log(int level, String tag, String msg) { logger.log(level, tag, msg); } }; LogOptions newLogOptions = new LogOptions.Builder().setLogger(loggerToSet).build(); RxBleLog.updateLogOptions(newLogOptions); }
[ "@", "Deprecated", "public", "static", "void", "setLogger", "(", "@", "Nullable", "final", "Logger", "logger", ")", "{", "LogOptions", ".", "Logger", "loggerToSet", "=", "logger", "==", "null", "?", "logcatLogger", ":", "new", "LogOptions", ".", "Logger", "(...
Old method to set a custom logger implementation, set it to {@code null} to use default logcat logging. It updates only the logger object. The rest of log settings remain unchanged. <p> Example how to forward logs to Timber:<br> <code> <pre> RxBleLog.setLogger(new RxBleLog.Logger() { &#64;Override public void log(final int level, final String tag, final String msg) { Timber.tag(tag).log(level, msg); } }); </pre> </code> @deprecated use {@link com.polidea.rxandroidble2.RxBleClient#updateLogOptions(LogOptions)}
[ "Old", "method", "to", "set", "a", "custom", "logger", "implementation", "set", "it", "to", "{", "@code", "null", "}", "to", "use", "default", "logcat", "logging", ".", "It", "updates", "only", "the", "logger", "object", ".", "The", "rest", "of", "log", ...
train
https://github.com/Polidea/RxAndroidBle/blob/c6e4a9753c834d710e255306bb290e9244cdbc10/rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/RxBleLog.java#L98-L110
nextreports/nextreports-engine
src/ro/nextreports/engine/util/ReportUtil.java
ReportUtil.saveReport
public static void saveReport(Report report, OutputStream out) { """ Write a report object to an output stream @param report report object @param out output stream """ XStream xstream = XStreamFactory.createXStream(); xstream.toXML(report, out); }
java
public static void saveReport(Report report, OutputStream out) { XStream xstream = XStreamFactory.createXStream(); xstream.toXML(report, out); }
[ "public", "static", "void", "saveReport", "(", "Report", "report", ",", "OutputStream", "out", ")", "{", "XStream", "xstream", "=", "XStreamFactory", ".", "createXStream", "(", ")", ";", "xstream", ".", "toXML", "(", "report", ",", "out", ")", ";", "}" ]
Write a report object to an output stream @param report report object @param out output stream
[ "Write", "a", "report", "object", "to", "an", "output", "stream" ]
train
https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/ReportUtil.java#L198-L201
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionValueRelPersistenceImpl.java
CPDefinitionOptionValueRelPersistenceImpl.findByKey
@Override public List<CPDefinitionOptionValueRel> findByKey(String key, int start, int end, OrderByComparator<CPDefinitionOptionValueRel> orderByComparator) { """ Returns an ordered range of all the cp definition option value rels where key = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionOptionValueRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param key the key @param start the lower bound of the range of cp definition option value rels @param end the upper bound of the range of cp definition option value rels (not inclusive) @param orderByComparator the comparator to order the results by (optionally <code>null</code>) @return the ordered range of matching cp definition option value rels """ return findByKey(key, start, end, orderByComparator, true); }
java
@Override public List<CPDefinitionOptionValueRel> findByKey(String key, int start, int end, OrderByComparator<CPDefinitionOptionValueRel> orderByComparator) { return findByKey(key, start, end, orderByComparator, true); }
[ "@", "Override", "public", "List", "<", "CPDefinitionOptionValueRel", ">", "findByKey", "(", "String", "key", ",", "int", "start", ",", "int", "end", ",", "OrderByComparator", "<", "CPDefinitionOptionValueRel", ">", "orderByComparator", ")", "{", "return", "findBy...
Returns an ordered range of all the cp definition option value rels where key = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionOptionValueRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param key the key @param start the lower bound of the range of cp definition option value rels @param end the upper bound of the range of cp definition option value rels (not inclusive) @param orderByComparator the comparator to order the results by (optionally <code>null</code>) @return the ordered range of matching cp definition option value rels
[ "Returns", "an", "ordered", "range", "of", "all", "the", "cp", "definition", "option", "value", "rels", "where", "key", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionValueRelPersistenceImpl.java#L3133-L3137
structr/structr
structr-core/src/main/java/org/structr/schema/compiler/ClassFileManager.java
ClassFileManager.getJavaFileForOutput
@Override public JavaFileObject getJavaFileForOutput(final Location location, final String className, final Kind kind, final FileObject sibling) throws IOException { """ Gives the compiler an instance of the JavaClassObject so that the compiler can write the byte code into it. @param location @param className @param kind @param sibling @return file object @throws java.io.IOException """ JavaClassObject obj = new JavaClassObject(className, kind); objects.put(className, obj); return obj; }
java
@Override public JavaFileObject getJavaFileForOutput(final Location location, final String className, final Kind kind, final FileObject sibling) throws IOException { JavaClassObject obj = new JavaClassObject(className, kind); objects.put(className, obj); return obj; }
[ "@", "Override", "public", "JavaFileObject", "getJavaFileForOutput", "(", "final", "Location", "location", ",", "final", "String", "className", ",", "final", "Kind", "kind", ",", "final", "FileObject", "sibling", ")", "throws", "IOException", "{", "JavaClassObject",...
Gives the compiler an instance of the JavaClassObject so that the compiler can write the byte code into it. @param location @param className @param kind @param sibling @return file object @throws java.io.IOException
[ "Gives", "the", "compiler", "an", "instance", "of", "the", "JavaClassObject", "so", "that", "the", "compiler", "can", "write", "the", "byte", "code", "into", "it", "." ]
train
https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-core/src/main/java/org/structr/schema/compiler/ClassFileManager.java#L91-L99
apache/flink
flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java
DateTimeUtils.subtractMonths
public static int subtractMonths(int date0, int date1) { """ Finds the number of months between two dates, each represented as the number of days since the epoch. """ if (date0 < date1) { return -subtractMonths(date1, date0); } // Start with an estimate. // Since no month has more than 31 days, the estimate is <= the true value. int m = (date0 - date1) / 31; for (;;) { int date2 = addMonths(date1, m); if (date2 >= date0) { return m; } int date3 = addMonths(date1, m + 1); if (date3 > date0) { return m; } ++m; } }
java
public static int subtractMonths(int date0, int date1) { if (date0 < date1) { return -subtractMonths(date1, date0); } // Start with an estimate. // Since no month has more than 31 days, the estimate is <= the true value. int m = (date0 - date1) / 31; for (;;) { int date2 = addMonths(date1, m); if (date2 >= date0) { return m; } int date3 = addMonths(date1, m + 1); if (date3 > date0) { return m; } ++m; } }
[ "public", "static", "int", "subtractMonths", "(", "int", "date0", ",", "int", "date1", ")", "{", "if", "(", "date0", "<", "date1", ")", "{", "return", "-", "subtractMonths", "(", "date1", ",", "date0", ")", ";", "}", "// Start with an estimate.", "// Since...
Finds the number of months between two dates, each represented as the number of days since the epoch.
[ "Finds", "the", "number", "of", "months", "between", "two", "dates", "each", "represented", "as", "the", "number", "of", "days", "since", "the", "epoch", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java#L1107-L1125
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java
Utils.isSunday
public static boolean isSunday(int column, int firstDayOfWeek) { """ Determine whether the column position is Sunday or not. @param column the column position @param firstDayOfWeek the first day of week in android.text.format.Time @return true if the column is Sunday position """ return (firstDayOfWeek == Time.SUNDAY && column == 0) || (firstDayOfWeek == Time.MONDAY && column == 6) || (firstDayOfWeek == Time.SATURDAY && column == 1); }
java
public static boolean isSunday(int column, int firstDayOfWeek) { return (firstDayOfWeek == Time.SUNDAY && column == 0) || (firstDayOfWeek == Time.MONDAY && column == 6) || (firstDayOfWeek == Time.SATURDAY && column == 1); }
[ "public", "static", "boolean", "isSunday", "(", "int", "column", ",", "int", "firstDayOfWeek", ")", "{", "return", "(", "firstDayOfWeek", "==", "Time", ".", "SUNDAY", "&&", "column", "==", "0", ")", "||", "(", "firstDayOfWeek", "==", "Time", ".", "MONDAY",...
Determine whether the column position is Sunday or not. @param column the column position @param firstDayOfWeek the first day of week in android.text.format.Time @return true if the column is Sunday position
[ "Determine", "whether", "the", "column", "position", "is", "Sunday", "or", "not", "." ]
train
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java#L447-L451
javagl/CommonUI
src/main/java/de/javagl/common/ui/SpinnerDraggingHandler.java
SpinnerDraggingHandler.handleWrapping
private boolean handleWrapping(MouseEvent e) { """ Let the mouse wrap from the top of the screen to the bottom or vice versa @param e The mouse event @return Whether the mouse wrapped """ if (robot == null) { return false; } PointerInfo pointerInfo = null; try { pointerInfo = MouseInfo.getPointerInfo(); } catch (SecurityException ex) { return false; } Rectangle r = pointerInfo.getDevice().getDefaultConfiguration().getBounds(); Point onScreen = pointerInfo.getLocation(); if (onScreen.y == 0) { robot.mouseMove(onScreen.x, r.height-2); previousPoint = new Point(onScreen.x, r.height-2); SwingUtilities.convertPointFromScreen(previousPoint, spinner); return true; } else if (onScreen.y == r.height - 1) { robot.mouseMove(onScreen.x, 1); previousPoint = new Point(onScreen.x, 1); SwingUtilities.convertPointFromScreen(previousPoint, spinner); return true; } return false; }
java
private boolean handleWrapping(MouseEvent e) { if (robot == null) { return false; } PointerInfo pointerInfo = null; try { pointerInfo = MouseInfo.getPointerInfo(); } catch (SecurityException ex) { return false; } Rectangle r = pointerInfo.getDevice().getDefaultConfiguration().getBounds(); Point onScreen = pointerInfo.getLocation(); if (onScreen.y == 0) { robot.mouseMove(onScreen.x, r.height-2); previousPoint = new Point(onScreen.x, r.height-2); SwingUtilities.convertPointFromScreen(previousPoint, spinner); return true; } else if (onScreen.y == r.height - 1) { robot.mouseMove(onScreen.x, 1); previousPoint = new Point(onScreen.x, 1); SwingUtilities.convertPointFromScreen(previousPoint, spinner); return true; } return false; }
[ "private", "boolean", "handleWrapping", "(", "MouseEvent", "e", ")", "{", "if", "(", "robot", "==", "null", ")", "{", "return", "false", ";", "}", "PointerInfo", "pointerInfo", "=", "null", ";", "try", "{", "pointerInfo", "=", "MouseInfo", ".", "getPointer...
Let the mouse wrap from the top of the screen to the bottom or vice versa @param e The mouse event @return Whether the mouse wrapped
[ "Let", "the", "mouse", "wrap", "from", "the", "top", "of", "the", "screen", "to", "the", "bottom", "or", "vice", "versa" ]
train
https://github.com/javagl/CommonUI/blob/b2c7a7637d4e288271392ba148dc17e4c9780255/src/main/java/de/javagl/common/ui/SpinnerDraggingHandler.java#L187-L220
CloudSlang/cs-actions
cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java
DateTimeUtils.formatWithDefault
public static DateTimeFormatter formatWithDefault(String lang, String country) { """ Generates a DateTimeFormatter using full date pattern with the default locale or a new one according to what language and country are provided as params. @param lang the language @param country the country @return the DateTimeFormatter generated """ return (StringUtils.isNotBlank(lang)) ? DateTimeFormat.longDateTime().withLocale(DateTimeUtils.getLocaleByCountry(lang, country)) : DateTimeFormat.longDateTime().withLocale(Locale.getDefault()); }
java
public static DateTimeFormatter formatWithDefault(String lang, String country) { return (StringUtils.isNotBlank(lang)) ? DateTimeFormat.longDateTime().withLocale(DateTimeUtils.getLocaleByCountry(lang, country)) : DateTimeFormat.longDateTime().withLocale(Locale.getDefault()); }
[ "public", "static", "DateTimeFormatter", "formatWithDefault", "(", "String", "lang", ",", "String", "country", ")", "{", "return", "(", "StringUtils", ".", "isNotBlank", "(", "lang", ")", ")", "?", "DateTimeFormat", ".", "longDateTime", "(", ")", ".", "withLoc...
Generates a DateTimeFormatter using full date pattern with the default locale or a new one according to what language and country are provided as params. @param lang the language @param country the country @return the DateTimeFormatter generated
[ "Generates", "a", "DateTimeFormatter", "using", "full", "date", "pattern", "with", "the", "default", "locale", "or", "a", "new", "one", "according", "to", "what", "language", "and", "country", "are", "provided", "as", "params", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L120-L123
Ellzord/JALSE
src/main/java/jalse/entities/Entities.java
Entities.newRecursiveAttributeListener
public static <T> EntityListener newRecursiveAttributeListener(final NamedAttributeType<T> namedType, final Supplier<AttributeListener<T>> supplier) { """ Creates an recursive entity listener for named attribute type and the supplied attribute listener supplier with Integer.MAX_VALUE recursion limit. @param namedType Named attribute type being listened for by supplier's listeners. @param supplier Supplier of the attribute listener to be added to created entities. @return Recursive attribute listener for named type and supplier. """ return newRecursiveAttributeListener(namedType, supplier, Integer.MAX_VALUE); }
java
public static <T> EntityListener newRecursiveAttributeListener(final NamedAttributeType<T> namedType, final Supplier<AttributeListener<T>> supplier) { return newRecursiveAttributeListener(namedType, supplier, Integer.MAX_VALUE); }
[ "public", "static", "<", "T", ">", "EntityListener", "newRecursiveAttributeListener", "(", "final", "NamedAttributeType", "<", "T", ">", "namedType", ",", "final", "Supplier", "<", "AttributeListener", "<", "T", ">", ">", "supplier", ")", "{", "return", "newRecu...
Creates an recursive entity listener for named attribute type and the supplied attribute listener supplier with Integer.MAX_VALUE recursion limit. @param namedType Named attribute type being listened for by supplier's listeners. @param supplier Supplier of the attribute listener to be added to created entities. @return Recursive attribute listener for named type and supplier.
[ "Creates", "an", "recursive", "entity", "listener", "for", "named", "attribute", "type", "and", "the", "supplied", "attribute", "listener", "supplier", "with", "Integer", ".", "MAX_VALUE", "recursion", "limit", "." ]
train
https://github.com/Ellzord/JALSE/blob/43fc6572de9b16eb8474aa21a88b6b2d11291615/src/main/java/jalse/entities/Entities.java#L311-L314
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/CommandGroup.java
CommandGroup.createButtonStack
public JComponent createButtonStack(final Size minimumButtonSize, final Border border) { """ Create a button stack with buttons for all the commands. @param minimumButtonSize Minimum size of the buttons (can be <code>null</code>) @param border Border to set around the stack. @return never null """ return createButtonStack(minimumButtonSize == null ? null : new ColumnSpec(minimumButtonSize), null, border); }
java
public JComponent createButtonStack(final Size minimumButtonSize, final Border border) { return createButtonStack(minimumButtonSize == null ? null : new ColumnSpec(minimumButtonSize), null, border); }
[ "public", "JComponent", "createButtonStack", "(", "final", "Size", "minimumButtonSize", ",", "final", "Border", "border", ")", "{", "return", "createButtonStack", "(", "minimumButtonSize", "==", "null", "?", "null", ":", "new", "ColumnSpec", "(", "minimumButtonSize"...
Create a button stack with buttons for all the commands. @param minimumButtonSize Minimum size of the buttons (can be <code>null</code>) @param border Border to set around the stack. @return never null
[ "Create", "a", "button", "stack", "with", "buttons", "for", "all", "the", "commands", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/CommandGroup.java#L508-L510
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/management/MBeanProxyFactory.java
MBeanProxyFactory.createServerMonitorProxy
public ServerMonitorMXBean createServerMonitorProxy() throws IOException { """ Makes the proxy for ServerMonitorMXBean. @return A ServerMonitorMXBean proxy object. @throws IOException """ String beanName = ServerMonitorMXBean.JMX_DOMAIN_NAME + ":type=" + ServerMonitorMXBean.JMX_TYPE_NAME; return createMXBeanProxy(beanName, ServerMonitorMXBean.class); }
java
public ServerMonitorMXBean createServerMonitorProxy() throws IOException { String beanName = ServerMonitorMXBean.JMX_DOMAIN_NAME + ":type=" + ServerMonitorMXBean.JMX_TYPE_NAME; return createMXBeanProxy(beanName, ServerMonitorMXBean.class); }
[ "public", "ServerMonitorMXBean", "createServerMonitorProxy", "(", ")", "throws", "IOException", "{", "String", "beanName", "=", "ServerMonitorMXBean", ".", "JMX_DOMAIN_NAME", "+", "\":type=\"", "+", "ServerMonitorMXBean", ".", "JMX_TYPE_NAME", ";", "return", "createMXBean...
Makes the proxy for ServerMonitorMXBean. @return A ServerMonitorMXBean proxy object. @throws IOException
[ "Makes", "the", "proxy", "for", "ServerMonitorMXBean", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/management/MBeanProxyFactory.java#L79-L82
weld/core
impl/src/main/java/org/jboss/weld/util/bytecode/ClassFileUtils.java
ClassFileUtils.toClass
public static Class<?> toClass(ClassFile ct, ClassLoader loader, ProtectionDomain domain) { """ Converts the class to a <code>java.lang.Class</code> object. Once this method is called, further modifications are not allowed any more. <p/> <p/> The class file represented by the given <code>CtClass</code> is loaded by the given class loader to construct a <code>java.lang.Class</code> object. Since a private method on the class loader is invoked through the reflection API, the caller must have permissions to do that. <p/> <p/> An easy way to obtain <code>ProtectionDomain</code> object is to call <code>getProtectionDomain()</code> in <code>java.lang.Class</code>. It returns the domain that the class belongs to. <p/> <p/> This method is provided for convenience. If you need more complex functionality, you should write your own class loader. @param loader the class loader used to load this class. For example, the loader returned by <code>getClassLoader()</code> can be used for this parameter. @param domain the protection domain for the class. If it is null, the default domain created by <code>java.lang.ClassLoader</code> is """ try { byte[] b = ct.toBytecode(); java.lang.reflect.Method method; Object[] args; if (domain == null) { method = defineClass1; args = new Object[] { ct.getName(), b, 0, b.length }; } else { method = defineClass2; args = new Object[] { ct.getName(), b, 0, b.length, domain }; } return toClass2(method, loader, args); } catch (RuntimeException e) { throw e; } catch (java.lang.reflect.InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static Class<?> toClass(ClassFile ct, ClassLoader loader, ProtectionDomain domain) { try { byte[] b = ct.toBytecode(); java.lang.reflect.Method method; Object[] args; if (domain == null) { method = defineClass1; args = new Object[] { ct.getName(), b, 0, b.length }; } else { method = defineClass2; args = new Object[] { ct.getName(), b, 0, b.length, domain }; } return toClass2(method, loader, args); } catch (RuntimeException e) { throw e; } catch (java.lang.reflect.InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "Class", "<", "?", ">", "toClass", "(", "ClassFile", "ct", ",", "ClassLoader", "loader", ",", "ProtectionDomain", "domain", ")", "{", "try", "{", "byte", "[", "]", "b", "=", "ct", ".", "toBytecode", "(", ")", ";", "java", ".", "la...
Converts the class to a <code>java.lang.Class</code> object. Once this method is called, further modifications are not allowed any more. <p/> <p/> The class file represented by the given <code>CtClass</code> is loaded by the given class loader to construct a <code>java.lang.Class</code> object. Since a private method on the class loader is invoked through the reflection API, the caller must have permissions to do that. <p/> <p/> An easy way to obtain <code>ProtectionDomain</code> object is to call <code>getProtectionDomain()</code> in <code>java.lang.Class</code>. It returns the domain that the class belongs to. <p/> <p/> This method is provided for convenience. If you need more complex functionality, you should write your own class loader. @param loader the class loader used to load this class. For example, the loader returned by <code>getClassLoader()</code> can be used for this parameter. @param domain the protection domain for the class. If it is null, the default domain created by <code>java.lang.ClassLoader</code> is
[ "Converts", "the", "class", "to", "a", "<code", ">", "java", ".", "lang", ".", "Class<", "/", "code", ">", "object", ".", "Once", "this", "method", "is", "called", "further", "modifications", "are", "not", "allowed", "any", "more", ".", "<p", "/", ">",...
train
https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/util/bytecode/ClassFileUtils.java#L121-L142
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/error/SingleError.java
SingleError.hashCodeLinkedException
@OverrideOnDemand protected void hashCodeLinkedException (@Nonnull final HashCodeGenerator aHCG, @Nullable final Throwable t) { """ Overridable implementation of Throwable for the Linked exception field. This can be overridden to implement a different algorithm. This is customizable because there is no default way of hashing Exceptions in Java. If you override this method you must also override {@link #equalsLinkedException(Throwable, Throwable)}! @param aHCG The hash code generator to append to. Never <code>null</code>. @param t The Throwable to append. May be <code>null</code>. """ if (t == null) aHCG.append (HashCodeCalculator.HASHCODE_NULL); else aHCG.append (t.getClass ()).append (t.getMessage ()); }
java
@OverrideOnDemand protected void hashCodeLinkedException (@Nonnull final HashCodeGenerator aHCG, @Nullable final Throwable t) { if (t == null) aHCG.append (HashCodeCalculator.HASHCODE_NULL); else aHCG.append (t.getClass ()).append (t.getMessage ()); }
[ "@", "OverrideOnDemand", "protected", "void", "hashCodeLinkedException", "(", "@", "Nonnull", "final", "HashCodeGenerator", "aHCG", ",", "@", "Nullable", "final", "Throwable", "t", ")", "{", "if", "(", "t", "==", "null", ")", "aHCG", ".", "append", "(", "Has...
Overridable implementation of Throwable for the Linked exception field. This can be overridden to implement a different algorithm. This is customizable because there is no default way of hashing Exceptions in Java. If you override this method you must also override {@link #equalsLinkedException(Throwable, Throwable)}! @param aHCG The hash code generator to append to. Never <code>null</code>. @param t The Throwable to append. May be <code>null</code>.
[ "Overridable", "implementation", "of", "Throwable", "for", "the", "Linked", "exception", "field", ".", "This", "can", "be", "overridden", "to", "implement", "a", "different", "algorithm", ".", "This", "is", "customizable", "because", "there", "is", "no", "defaul...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/error/SingleError.java#L164-L171
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java
JBBPBitOutputStream.writeBytes
public void writeBytes(final byte[] array, final int length, final JBBPByteOrder byteOrder) throws IOException { """ Write number of items from byte array into stream @param array array, must not be null @param length number of items to be written, if -1 then whole array @param byteOrder order of bytes, if LITTLE_ENDIAN then array will be reversed @throws IOException it will be thrown if any transport error @see JBBPByteOrder#LITTLE_ENDIAN @since 1.3.0 """ if (byteOrder == JBBPByteOrder.LITTLE_ENDIAN) { int i = length < 0 ? array.length - 1 : length - 1; while (i >= 0) { this.write(array[i--]); } } else { this.write(array, 0, length < 0 ? array.length : length); } }
java
public void writeBytes(final byte[] array, final int length, final JBBPByteOrder byteOrder) throws IOException { if (byteOrder == JBBPByteOrder.LITTLE_ENDIAN) { int i = length < 0 ? array.length - 1 : length - 1; while (i >= 0) { this.write(array[i--]); } } else { this.write(array, 0, length < 0 ? array.length : length); } }
[ "public", "void", "writeBytes", "(", "final", "byte", "[", "]", "array", ",", "final", "int", "length", ",", "final", "JBBPByteOrder", "byteOrder", ")", "throws", "IOException", "{", "if", "(", "byteOrder", "==", "JBBPByteOrder", ".", "LITTLE_ENDIAN", ")", "...
Write number of items from byte array into stream @param array array, must not be null @param length number of items to be written, if -1 then whole array @param byteOrder order of bytes, if LITTLE_ENDIAN then array will be reversed @throws IOException it will be thrown if any transport error @see JBBPByteOrder#LITTLE_ENDIAN @since 1.3.0
[ "Write", "number", "of", "items", "from", "byte", "array", "into", "stream" ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java#L350-L359
BioPAX/Paxtools
paxtools-query/src/main/java/org/biopax/paxtools/query/algorithm/CycleBreaker.java
CycleBreaker.processNode2
protected boolean processNode2(Node current) { """ Continue the search from the node. 2 is added because a name clash in the parent class. @param current The node to traverse @return False if a cycle is detected """ return processEdges(current, current.getDownstream()) || processEdges(current, current.getUpstream()); }
java
protected boolean processNode2(Node current) { return processEdges(current, current.getDownstream()) || processEdges(current, current.getUpstream()); }
[ "protected", "boolean", "processNode2", "(", "Node", "current", ")", "{", "return", "processEdges", "(", "current", ",", "current", ".", "getDownstream", "(", ")", ")", "||", "processEdges", "(", "current", ",", "current", ".", "getUpstream", "(", ")", ")", ...
Continue the search from the node. 2 is added because a name clash in the parent class. @param current The node to traverse @return False if a cycle is detected
[ "Continue", "the", "search", "from", "the", "node", ".", "2", "is", "added", "because", "a", "name", "clash", "in", "the", "parent", "class", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/algorithm/CycleBreaker.java#L121-L125
jenkinsci/jenkins
core/src/main/java/hudson/model/User.java
User.getById
public static @Nullable User getById(String id, boolean create) { """ Gets the {@link User} object by its <code>id</code> @param id the id of the user to retrieve and optionally create if it does not exist. @param create If <code>true</code>, this method will never return <code>null</code> for valid input (by creating a new {@link User} object if none exists.) If <code>false</code>, this method will return <code>null</code> if {@link User} object with the given id doesn't exist. @return the a User whose id is <code>id</code>, or <code>null</code> if <code>create</code> is <code>false</code> and the user does not exist. @since 1.651.2 / 2.3 """ return getOrCreateById(id, id, create); }
java
public static @Nullable User getById(String id, boolean create) { return getOrCreateById(id, id, create); }
[ "public", "static", "@", "Nullable", "User", "getById", "(", "String", "id", ",", "boolean", "create", ")", "{", "return", "getOrCreateById", "(", "id", ",", "id", ",", "create", ")", ";", "}" ]
Gets the {@link User} object by its <code>id</code> @param id the id of the user to retrieve and optionally create if it does not exist. @param create If <code>true</code>, this method will never return <code>null</code> for valid input (by creating a new {@link User} object if none exists.) If <code>false</code>, this method will return <code>null</code> if {@link User} object with the given id doesn't exist. @return the a User whose id is <code>id</code>, or <code>null</code> if <code>create</code> is <code>false</code> and the user does not exist. @since 1.651.2 / 2.3
[ "Gets", "the", "{", "@link", "User", "}", "object", "by", "its", "<code", ">", "id<", "/", "code", ">" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/User.java#L613-L616
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/SourceLineAnnotation.java
SourceLineAnnotation.fromVisitedInstruction
public static SourceLineAnnotation fromVisitedInstruction(MethodDescriptor methodDescriptor, Location location) { """ Create from MethodDescriptor and Location of visited instruction. @param methodDescriptor MethodDescriptor identifying analyzed method @param location Location of instruction within analyed method @return SourceLineAnnotation describing visited instruction """ return fromVisitedInstruction(methodDescriptor, location.getHandle().getPosition()); }
java
public static SourceLineAnnotation fromVisitedInstruction(MethodDescriptor methodDescriptor, Location location) { return fromVisitedInstruction(methodDescriptor, location.getHandle().getPosition()); }
[ "public", "static", "SourceLineAnnotation", "fromVisitedInstruction", "(", "MethodDescriptor", "methodDescriptor", ",", "Location", "location", ")", "{", "return", "fromVisitedInstruction", "(", "methodDescriptor", ",", "location", ".", "getHandle", "(", ")", ".", "getP...
Create from MethodDescriptor and Location of visited instruction. @param methodDescriptor MethodDescriptor identifying analyzed method @param location Location of instruction within analyed method @return SourceLineAnnotation describing visited instruction
[ "Create", "from", "MethodDescriptor", "and", "Location", "of", "visited", "instruction", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/SourceLineAnnotation.java#L427-L429
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java
ArrayUtil.append
@SafeVarargs public static <T> T[] append(T[] buffer, T... newElements) { """ 将新元素添加到已有数组中<br> 添加新元素会生成一个新的数组,不影响原数组 @param <T> 数组元素类型 @param buffer 已有数组 @param newElements 新元素 @return 新数组 """ if(isEmpty(buffer)) { return newElements; } return insert(buffer, buffer.length, newElements); }
java
@SafeVarargs public static <T> T[] append(T[] buffer, T... newElements) { if(isEmpty(buffer)) { return newElements; } return insert(buffer, buffer.length, newElements); }
[ "@", "SafeVarargs", "public", "static", "<", "T", ">", "T", "[", "]", "append", "(", "T", "[", "]", "buffer", ",", "T", "...", "newElements", ")", "{", "if", "(", "isEmpty", "(", "buffer", ")", ")", "{", "return", "newElements", ";", "}", "return",...
将新元素添加到已有数组中<br> 添加新元素会生成一个新的数组,不影响原数组 @param <T> 数组元素类型 @param buffer 已有数组 @param newElements 新元素 @return 新数组
[ "将新元素添加到已有数组中<br", ">", "添加新元素会生成一个新的数组,不影响原数组" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L382-L388
OpenFeign/feign
core/src/main/java/feign/Types.java
Types.getSupertype
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) { """ Returns the generic form of {@code supertype}. For example, if this is {@code ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code Iterable.class}. @param supertype a superclass of, or interface implemented by, this. """ if (!supertype.isAssignableFrom(contextRawType)) { throw new IllegalArgumentException(); } return resolve(context, contextRawType, getGenericSupertype(context, contextRawType, supertype)); }
java
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) { if (!supertype.isAssignableFrom(contextRawType)) { throw new IllegalArgumentException(); } return resolve(context, contextRawType, getGenericSupertype(context, contextRawType, supertype)); }
[ "static", "Type", "getSupertype", "(", "Type", "context", ",", "Class", "<", "?", ">", "contextRawType", ",", "Class", "<", "?", ">", "supertype", ")", "{", "if", "(", "!", "supertype", ".", "isAssignableFrom", "(", "contextRawType", ")", ")", "{", "thro...
Returns the generic form of {@code supertype}. For example, if this is {@code ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code Iterable.class}. @param supertype a superclass of, or interface implemented by, this.
[ "Returns", "the", "generic", "form", "of", "{", "@code", "supertype", "}", ".", "For", "example", "if", "this", "is", "{", "@code", "ArrayList<String", ">", "}", "this", "returns", "{", "@code", "Iterable<String", ">", "}", "given", "the", "input", "{", ...
train
https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/Types.java#L195-L201
stapler/stapler
core/src/main/java/org/kohsuke/stapler/Facet.java
Facet.buildIndexDispatchers
public void buildIndexDispatchers(MetaClass owner, List<Dispatcher> dispatchers) { """ Adds {@link Dispatcher}s that serves the likes of {@code index.EXT} The default implementation invokes {@link #handleIndexRequest(RequestImpl, ResponseImpl, Object, MetaClass)} but facet implementations can improve runtime dispatch performance by testing the presence of index view page upfront. """ dispatchers.add(new IndexViewDispatcher(owner,this)); }
java
public void buildIndexDispatchers(MetaClass owner, List<Dispatcher> dispatchers) { dispatchers.add(new IndexViewDispatcher(owner,this)); }
[ "public", "void", "buildIndexDispatchers", "(", "MetaClass", "owner", ",", "List", "<", "Dispatcher", ">", "dispatchers", ")", "{", "dispatchers", ".", "add", "(", "new", "IndexViewDispatcher", "(", "owner", ",", "this", ")", ")", ";", "}" ]
Adds {@link Dispatcher}s that serves the likes of {@code index.EXT} The default implementation invokes {@link #handleIndexRequest(RequestImpl, ResponseImpl, Object, MetaClass)} but facet implementations can improve runtime dispatch performance by testing the presence of index view page upfront.
[ "Adds", "{", "@link", "Dispatcher", "}", "s", "that", "serves", "the", "likes", "of", "{", "@code", "index", ".", "EXT", "}" ]
train
https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/core/src/main/java/org/kohsuke/stapler/Facet.java#L63-L65
groupon/odo
client/src/main/java/com/groupon/odo/client/Client.java
Client.refreshHistory
public History[] refreshHistory(int limit, int offset) throws Exception { """ refresh the most recent history entries @param limit number of entries to populate @param offset number of most recent entries to skip @return populated history entries @throws Exception exception """ BasicNameValuePair[] params = { new BasicNameValuePair("limit", String.valueOf(limit)), new BasicNameValuePair("offset", String.valueOf(offset)) }; return constructHistory(params); }
java
public History[] refreshHistory(int limit, int offset) throws Exception { BasicNameValuePair[] params = { new BasicNameValuePair("limit", String.valueOf(limit)), new BasicNameValuePair("offset", String.valueOf(offset)) }; return constructHistory(params); }
[ "public", "History", "[", "]", "refreshHistory", "(", "int", "limit", ",", "int", "offset", ")", "throws", "Exception", "{", "BasicNameValuePair", "[", "]", "params", "=", "{", "new", "BasicNameValuePair", "(", "\"limit\"", ",", "String", ".", "valueOf", "("...
refresh the most recent history entries @param limit number of entries to populate @param offset number of most recent entries to skip @return populated history entries @throws Exception exception
[ "refresh", "the", "most", "recent", "history", "entries" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L366-L372
HanSolo/SteelSeries-Swing
src/main/java/eu/hansolo/steelseries/extras/Radar.java
Radar.updatePoi
public void updatePoi(final String BLIP_NAME, final Point2D LOCATION) { """ Updates the position of the given poi by it's name (BLIP_NAME) on the radar screen. This could be useful to visualize moving points. Keep in mind that only the poi's are visible as blips that are in the range of the radar. @param BLIP_NAME @param LOCATION """ if (pois.keySet().contains(BLIP_NAME)) { pois.get(BLIP_NAME).setLocation(LOCATION); checkForBlips(); } }
java
public void updatePoi(final String BLIP_NAME, final Point2D LOCATION) { if (pois.keySet().contains(BLIP_NAME)) { pois.get(BLIP_NAME).setLocation(LOCATION); checkForBlips(); } }
[ "public", "void", "updatePoi", "(", "final", "String", "BLIP_NAME", ",", "final", "Point2D", "LOCATION", ")", "{", "if", "(", "pois", ".", "keySet", "(", ")", ".", "contains", "(", "BLIP_NAME", ")", ")", "{", "pois", ".", "get", "(", "BLIP_NAME", ")", ...
Updates the position of the given poi by it's name (BLIP_NAME) on the radar screen. This could be useful to visualize moving points. Keep in mind that only the poi's are visible as blips that are in the range of the radar. @param BLIP_NAME @param LOCATION
[ "Updates", "the", "position", "of", "the", "given", "poi", "by", "it", "s", "name", "(", "BLIP_NAME", ")", "on", "the", "radar", "screen", ".", "This", "could", "be", "useful", "to", "visualize", "moving", "points", ".", "Keep", "in", "mind", "that", "...
train
https://github.com/HanSolo/SteelSeries-Swing/blob/c2f7b45a477757ef21bbb6a1174ddedb2250ae57/src/main/java/eu/hansolo/steelseries/extras/Radar.java#L303-L308
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/sequences/LVMorphologyReaderAndWriter.java
LVMorphologyReaderAndWriter.applyLVmorphoanalysis
private static void applyLVmorphoanalysis(CoreLabel wi, Collection<String> answerAttributes) { """ Performs LV morphology analysis of the token wi, adds the possible readins and marks the most likely one. If an AnswerAnnotation exists, then it is considered to be a morphosyntactic tag, and the attributes are filtered for the training. @param wi @param answerAttributes """ Word analysis = analyzer.analyze(wi.word()); applyLVmorphoanalysis(wi, analysis, answerAttributes); }
java
private static void applyLVmorphoanalysis(CoreLabel wi, Collection<String> answerAttributes) { Word analysis = analyzer.analyze(wi.word()); applyLVmorphoanalysis(wi, analysis, answerAttributes); }
[ "private", "static", "void", "applyLVmorphoanalysis", "(", "CoreLabel", "wi", ",", "Collection", "<", "String", ">", "answerAttributes", ")", "{", "Word", "analysis", "=", "analyzer", ".", "analyze", "(", "wi", ".", "word", "(", ")", ")", ";", "applyLVmorpho...
Performs LV morphology analysis of the token wi, adds the possible readins and marks the most likely one. If an AnswerAnnotation exists, then it is considered to be a morphosyntactic tag, and the attributes are filtered for the training. @param wi @param answerAttributes
[ "Performs", "LV", "morphology", "analysis", "of", "the", "token", "wi", "adds", "the", "possible", "readins", "and", "marks", "the", "most", "likely", "one", ".", "If", "an", "AnswerAnnotation", "exists", "then", "it", "is", "considered", "to", "be", "a", ...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/sequences/LVMorphologyReaderAndWriter.java#L185-L188
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/AiMesh.java
AiMesh.allocateDataChannel
@SuppressWarnings("unused") private void allocateDataChannel(int channelType, int channelIndex) { """ This method is used by JNI. Do not call or modify.<p> Allocates a byte buffer for a vertex data channel @param channelType the channel type @param channelIndex sub-index, used for types that can have multiple channels, such as texture coordinates """ switch (channelType) { case NORMALS: m_normals = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_normals.order(ByteOrder.nativeOrder()); break; case TANGENTS: m_tangents = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_tangents.order(ByteOrder.nativeOrder()); break; case BITANGENTS: m_bitangents = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_bitangents.order(ByteOrder.nativeOrder()); break; case COLORSET: m_colorsets[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 4 * SIZEOF_FLOAT); m_colorsets[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_1D: m_numUVComponents[channelIndex] = 1; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 1 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_2D: m_numUVComponents[channelIndex] = 2; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 2 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_3D: m_numUVComponents[channelIndex] = 3; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; default: throw new IllegalArgumentException("unsupported channel type"); } }
java
@SuppressWarnings("unused") private void allocateDataChannel(int channelType, int channelIndex) { switch (channelType) { case NORMALS: m_normals = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_normals.order(ByteOrder.nativeOrder()); break; case TANGENTS: m_tangents = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_tangents.order(ByteOrder.nativeOrder()); break; case BITANGENTS: m_bitangents = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_bitangents.order(ByteOrder.nativeOrder()); break; case COLORSET: m_colorsets[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 4 * SIZEOF_FLOAT); m_colorsets[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_1D: m_numUVComponents[channelIndex] = 1; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 1 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_2D: m_numUVComponents[channelIndex] = 2; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 2 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_3D: m_numUVComponents[channelIndex] = 3; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; default: throw new IllegalArgumentException("unsupported channel type"); } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "private", "void", "allocateDataChannel", "(", "int", "channelType", ",", "int", "channelIndex", ")", "{", "switch", "(", "channelType", ")", "{", "case", "NORMALS", ":", "m_normals", "=", "ByteBuffer", ".", "al...
This method is used by JNI. Do not call or modify.<p> Allocates a byte buffer for a vertex data channel @param channelType the channel type @param channelIndex sub-index, used for types that can have multiple channels, such as texture coordinates
[ "This", "method", "is", "used", "by", "JNI", ".", "Do", "not", "call", "or", "modify", ".", "<p", ">" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/AiMesh.java#L1302-L1346
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java
AmazonS3Client.setObjectAcl
public void setObjectAcl(String bucketName, String key, String versionId, CannedAccessControlList acl, RequestMetricCollector requestMetricCollector) { """ Same as {@link #setObjectAcl(String, String, String, CannedAccessControlList)} but allows specifying a request metric collector. """ setObjectAcl(new SetObjectAclRequest(bucketName, key, versionId, acl) .<SetObjectAclRequest> withRequestMetricCollector(requestMetricCollector)); }
java
public void setObjectAcl(String bucketName, String key, String versionId, CannedAccessControlList acl, RequestMetricCollector requestMetricCollector) { setObjectAcl(new SetObjectAclRequest(bucketName, key, versionId, acl) .<SetObjectAclRequest> withRequestMetricCollector(requestMetricCollector)); }
[ "public", "void", "setObjectAcl", "(", "String", "bucketName", ",", "String", "key", ",", "String", "versionId", ",", "CannedAccessControlList", "acl", ",", "RequestMetricCollector", "requestMetricCollector", ")", "{", "setObjectAcl", "(", "new", "SetObjectAclRequest", ...
Same as {@link #setObjectAcl(String, String, String, CannedAccessControlList)} but allows specifying a request metric collector.
[ "Same", "as", "{" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java#L1164-L1169
mbenson/therian
core/src/main/java/therian/TherianContext.java
TherianContext.evalIfSupported
public final synchronized <RESULT, OPERATION extends Operation<RESULT>> RESULT evalIfSupported(OPERATION operation, Hint... hints) { """ Evaluates {@code operation} if supported; otherwise returns {@code null}. You may distinguish between a {@code null} result and "not supported" by calling {@link #supports(Operation)} and {@link #eval(Operation)} independently. @param operation @param hints @return RESULT or {@code null} @throws NullPointerException on {@code null} input @throws OperationException potentially, via {@link Operation#getResult()} """ return evalIfSupported(operation, null, hints); }
java
public final synchronized <RESULT, OPERATION extends Operation<RESULT>> RESULT evalIfSupported(OPERATION operation, Hint... hints) { return evalIfSupported(operation, null, hints); }
[ "public", "final", "synchronized", "<", "RESULT", ",", "OPERATION", "extends", "Operation", "<", "RESULT", ">", ">", "RESULT", "evalIfSupported", "(", "OPERATION", "operation", ",", "Hint", "...", "hints", ")", "{", "return", "evalIfSupported", "(", "operation",...
Evaluates {@code operation} if supported; otherwise returns {@code null}. You may distinguish between a {@code null} result and "not supported" by calling {@link #supports(Operation)} and {@link #eval(Operation)} independently. @param operation @param hints @return RESULT or {@code null} @throws NullPointerException on {@code null} input @throws OperationException potentially, via {@link Operation#getResult()}
[ "Evaluates", "{", "@code", "operation", "}", "if", "supported", ";", "otherwise", "returns", "{", "@code", "null", "}", ".", "You", "may", "distinguish", "between", "a", "{", "@code", "null", "}", "result", "and", "not", "supported", "by", "calling", "{", ...
train
https://github.com/mbenson/therian/blob/0653505f73e2a6f5b0abc394ea6d83af03408254/core/src/main/java/therian/TherianContext.java#L379-L382
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/MAP.java
MAP.getValueAt
@Override public double getValueAt(final U user, final int at) { """ Method to return the AP (average precision) value at a particular cutoff level for a given user. @param user the user @param at cutoff level @return the AP (average precision) corresponding to the requested user at the cutoff level """ if (userMAPAtCutoff.containsKey(at) && userMAPAtCutoff.get(at).containsKey(user)) { double map = userMAPAtCutoff.get(at).get(user); return map; } return Double.NaN; }
java
@Override public double getValueAt(final U user, final int at) { if (userMAPAtCutoff.containsKey(at) && userMAPAtCutoff.get(at).containsKey(user)) { double map = userMAPAtCutoff.get(at).get(user); return map; } return Double.NaN; }
[ "@", "Override", "public", "double", "getValueAt", "(", "final", "U", "user", ",", "final", "int", "at", ")", "{", "if", "(", "userMAPAtCutoff", ".", "containsKey", "(", "at", ")", "&&", "userMAPAtCutoff", ".", "get", "(", "at", ")", ".", "containsKey", ...
Method to return the AP (average precision) value at a particular cutoff level for a given user. @param user the user @param at cutoff level @return the AP (average precision) corresponding to the requested user at the cutoff level
[ "Method", "to", "return", "the", "AP", "(", "average", "precision", ")", "value", "at", "a", "particular", "cutoff", "level", "for", "a", "given", "user", "." ]
train
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/MAP.java#L178-L185
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/disktree/DiskTreeReader.java
DiskTreeReader.pickGeometry
public Geometry pickGeometry( long position, long size ) throws Exception { """ Reads a single geomtry, using the info from the quadtree read in {@link #readIndex()}. @param position the position of the geom to read. @param size the size of the geom to read. @return the read geometry. @throws Exception """ byte[] geomBytes = new byte[(int) size]; raf.seek(position); raf.read(geomBytes); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(geomBytes)); return (Geometry) in.readObject(); }
java
public Geometry pickGeometry( long position, long size ) throws Exception { byte[] geomBytes = new byte[(int) size]; raf.seek(position); raf.read(geomBytes); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(geomBytes)); return (Geometry) in.readObject(); }
[ "public", "Geometry", "pickGeometry", "(", "long", "position", ",", "long", "size", ")", "throws", "Exception", "{", "byte", "[", "]", "geomBytes", "=", "new", "byte", "[", "(", "int", ")", "size", "]", ";", "raf", ".", "seek", "(", "position", ")", ...
Reads a single geomtry, using the info from the quadtree read in {@link #readIndex()}. @param position the position of the geom to read. @param size the size of the geom to read. @return the read geometry. @throws Exception
[ "Reads", "a", "single", "geomtry", "using", "the", "info", "from", "the", "quadtree", "read", "in", "{", "@link", "#readIndex", "()", "}", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/disktree/DiskTreeReader.java#L107-L114
gallandarakhneorg/afc
advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java
BusItinerary.addBusHalt
public final BusItineraryHalt addBusHalt(UUID id, BusItineraryHaltType type) { """ Add a bus halt inside the bus itinerary. @param id is the identifier of the bus halt. @param type is the type of the bus halt. @return the added bus halt, otherwise <code>null</code> """ return addBusHalt(id, null, type); }
java
public final BusItineraryHalt addBusHalt(UUID id, BusItineraryHaltType type) { return addBusHalt(id, null, type); }
[ "public", "final", "BusItineraryHalt", "addBusHalt", "(", "UUID", "id", ",", "BusItineraryHaltType", "type", ")", "{", "return", "addBusHalt", "(", "id", ",", "null", ",", "type", ")", ";", "}" ]
Add a bus halt inside the bus itinerary. @param id is the identifier of the bus halt. @param type is the type of the bus halt. @return the added bus halt, otherwise <code>null</code>
[ "Add", "a", "bus", "halt", "inside", "the", "bus", "itinerary", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java#L1116-L1118
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.toPaddedNumber
public static String toPaddedNumber(int value, int width) { """ Create the string representation of an integer and pad it to a particular width using leading zeroes. @param value the value to convert to a string @param width the width (in chars) that the resultant string should be @return the padded string """ StringBuilder s = new StringBuilder("00000000").append(Integer.toString(value)); return s.substring(s.length() - width); }
java
public static String toPaddedNumber(int value, int width) { StringBuilder s = new StringBuilder("00000000").append(Integer.toString(value)); return s.substring(s.length() - width); }
[ "public", "static", "String", "toPaddedNumber", "(", "int", "value", ",", "int", "width", ")", "{", "StringBuilder", "s", "=", "new", "StringBuilder", "(", "\"00000000\"", ")", ".", "append", "(", "Integer", ".", "toString", "(", "value", ")", ")", ";", ...
Create the string representation of an integer and pad it to a particular width using leading zeroes. @param value the value to convert to a string @param width the width (in chars) that the resultant string should be @return the padded string
[ "Create", "the", "string", "representation", "of", "an", "integer", "and", "pad", "it", "to", "a", "particular", "width", "using", "leading", "zeroes", "." ]
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L753-L756
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendPing
public static <T> void sendPing(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) { """ Sends a complete ping message, invoking the callback when complete Automatically frees the pooled byte buffer when done. @param pooledData The data to send, it will be freed when done @param wsChannel The web socket channel @param callback The callback to invoke on completion @param context The context object that will be passed to the callback on completion """ sendInternal(pooledData, WebSocketFrameType.PING, wsChannel, callback, context, -1); }
java
public static <T> void sendPing(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) { sendInternal(pooledData, WebSocketFrameType.PING, wsChannel, callback, context, -1); }
[ "public", "static", "<", "T", ">", "void", "sendPing", "(", "final", "PooledByteBuffer", "pooledData", ",", "final", "WebSocketChannel", "wsChannel", ",", "final", "WebSocketCallback", "<", "T", ">", "callback", ",", "T", "context", ")", "{", "sendInternal", "...
Sends a complete ping message, invoking the callback when complete Automatically frees the pooled byte buffer when done. @param pooledData The data to send, it will be freed when done @param wsChannel The web socket channel @param callback The callback to invoke on completion @param context The context object that will be passed to the callback on completion
[ "Sends", "a", "complete", "ping", "message", "invoking", "the", "callback", "when", "complete", "Automatically", "frees", "the", "pooled", "byte", "buffer", "when", "done", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L341-L343
apereo/cas
support/cas-server-support-pm-webflow/src/main/java/org/apereo/cas/pm/web/flow/PasswordManagementWebflowUtils.java
PasswordManagementWebflowUtils.putPasswordResetUsername
public static void putPasswordResetUsername(final RequestContext requestContext, final String username) { """ Put password reset username. @param requestContext the request context @param username the username """ val flowScope = requestContext.getFlowScope(); flowScope.put("username", username); }
java
public static void putPasswordResetUsername(final RequestContext requestContext, final String username) { val flowScope = requestContext.getFlowScope(); flowScope.put("username", username); }
[ "public", "static", "void", "putPasswordResetUsername", "(", "final", "RequestContext", "requestContext", ",", "final", "String", "username", ")", "{", "val", "flowScope", "=", "requestContext", ".", "getFlowScope", "(", ")", ";", "flowScope", ".", "put", "(", "...
Put password reset username. @param requestContext the request context @param username the username
[ "Put", "password", "reset", "username", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pm-webflow/src/main/java/org/apereo/cas/pm/web/flow/PasswordManagementWebflowUtils.java#L90-L93
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ArrayList.java
ArrayList.set
public E set(int index, E element) { """ Replaces the element at the specified position in this list with the specified element. @param index index of the element to replace @param element element to be stored at the specified position @return the element previously at the specified position @throws IndexOutOfBoundsException {@inheritDoc} """ if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); E oldValue = (E) elementData[index]; elementData[index] = element; return oldValue; }
java
public E set(int index, E element) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); E oldValue = (E) elementData[index]; elementData[index] = element; return oldValue; }
[ "public", "E", "set", "(", "int", "index", ",", "E", "element", ")", "{", "if", "(", "index", ">=", "size", ")", "throw", "new", "IndexOutOfBoundsException", "(", "outOfBoundsMsg", "(", "index", ")", ")", ";", "E", "oldValue", "=", "(", "E", ")", "el...
Replaces the element at the specified position in this list with the specified element. @param index index of the element to replace @param element element to be stored at the specified position @return the element previously at the specified position @throws IndexOutOfBoundsException {@inheritDoc}
[ "Replaces", "the", "element", "at", "the", "specified", "position", "in", "this", "list", "with", "the", "specified", "element", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ArrayList.java#L451-L458
Gperez88/CalculatorInputView
calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/widget/NumericEditText.java
NumericEditText.setDefaultNumericValue
public void setDefaultNumericValue(double defaultNumericValue, final String defaultNumericFormat) { """ Set default numeric value and how it should be displayed, this value will be used if {@link #clear} is called @param defaultNumericValue numeric value @param defaultNumericFormat display format for numeric value """ mDefaultText = String.format(defaultNumericFormat, defaultNumericValue); if (hasCustomDecimalSeparator) { // swap locale decimal separator with custom one for display mDefaultText = StringUtils.replace(mDefaultText, String.valueOf(DECIMAL_SEPARATOR), String.valueOf(mDecimalSeparator)); } setTextInternal(mDefaultText); }
java
public void setDefaultNumericValue(double defaultNumericValue, final String defaultNumericFormat) { mDefaultText = String.format(defaultNumericFormat, defaultNumericValue); if (hasCustomDecimalSeparator) { // swap locale decimal separator with custom one for display mDefaultText = StringUtils.replace(mDefaultText, String.valueOf(DECIMAL_SEPARATOR), String.valueOf(mDecimalSeparator)); } setTextInternal(mDefaultText); }
[ "public", "void", "setDefaultNumericValue", "(", "double", "defaultNumericValue", ",", "final", "String", "defaultNumericFormat", ")", "{", "mDefaultText", "=", "String", ".", "format", "(", "defaultNumericFormat", ",", "defaultNumericValue", ")", ";", "if", "(", "h...
Set default numeric value and how it should be displayed, this value will be used if {@link #clear} is called @param defaultNumericValue numeric value @param defaultNumericFormat display format for numeric value
[ "Set", "default", "numeric", "value", "and", "how", "it", "should", "be", "displayed", "this", "value", "will", "be", "used", "if", "{", "@link", "#clear", "}", "is", "called" ]
train
https://github.com/Gperez88/CalculatorInputView/blob/735029095fbcbd32d25cde65529061903f522a89/calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/widget/NumericEditText.java#L121-L130
alkacon/opencms-core
src/org/opencms/ade/sitemap/shared/CmsSitemapClipboardData.java
CmsSitemapClipboardData.checkMapSize
private void checkMapSize(LinkedHashMap<?, ?> map) { """ Checks map size to remove entries in case it exceeds the default list size.<p> @param map the map to check """ while (map.size() > CmsADEManager.DEFAULT_ELEMENT_LIST_SIZE) { map.remove(map.keySet().iterator().next()); } }
java
private void checkMapSize(LinkedHashMap<?, ?> map) { while (map.size() > CmsADEManager.DEFAULT_ELEMENT_LIST_SIZE) { map.remove(map.keySet().iterator().next()); } }
[ "private", "void", "checkMapSize", "(", "LinkedHashMap", "<", "?", ",", "?", ">", "map", ")", "{", "while", "(", "map", ".", "size", "(", ")", ">", "CmsADEManager", ".", "DEFAULT_ELEMENT_LIST_SIZE", ")", "{", "map", ".", "remove", "(", "map", ".", "key...
Checks map size to remove entries in case it exceeds the default list size.<p> @param map the map to check
[ "Checks", "map", "size", "to", "remove", "entries", "in", "case", "it", "exceeds", "the", "default", "list", "size", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/shared/CmsSitemapClipboardData.java#L182-L187
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.cut
public static BufferedImage cut(Image srcImage, int x, int y, int radius) { """ 图像切割(按指定起点坐标和宽高切割) @param srcImage 源图像 @param x 原图的x坐标起始位置 @param y 原图的y坐标起始位置 @param radius 半径,小于0表示填充满整个图片(直径取长宽最小值) @return {@link BufferedImage} @since 4.1.15 """ return Img.from(srcImage).cut(x, y, radius).getImg(); }
java
public static BufferedImage cut(Image srcImage, int x, int y, int radius) { return Img.from(srcImage).cut(x, y, radius).getImg(); }
[ "public", "static", "BufferedImage", "cut", "(", "Image", "srcImage", ",", "int", "x", ",", "int", "y", ",", "int", "radius", ")", "{", "return", "Img", ".", "from", "(", "srcImage", ")", ".", "cut", "(", "x", ",", "y", ",", "radius", ")", ".", "...
图像切割(按指定起点坐标和宽高切割) @param srcImage 源图像 @param x 原图的x坐标起始位置 @param y 原图的y坐标起始位置 @param radius 半径,小于0表示填充满整个图片(直径取长宽最小值) @return {@link BufferedImage} @since 4.1.15
[ "图像切割", "(", "按指定起点坐标和宽高切割", ")" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L358-L360
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.scaleAround
public Matrix4f scaleAround(float sx, float sy, float sz, float ox, float oy, float oz) { """ Apply scaling to this matrix by scaling the base axes by the given sx, sy and sz factors while using <code>(ox, oy, oz)</code> as the scaling origin. <p> If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, then the new matrix will be <code>M * S</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the scaling will be applied first! <p> This method is equivalent to calling: <code>translate(ox, oy, oz).scale(sx, sy, sz).translate(-ox, -oy, -oz)</code> @param sx the scaling factor of the x component @param sy the scaling factor of the y component @param sz the scaling factor of the z component @param ox the x coordinate of the scaling origin @param oy the y coordinate of the scaling origin @param oz the z coordinate of the scaling origin @return a matrix holding the result """ return scaleAround(sx, sy, sz, ox, oy, oz, thisOrNew()); }
java
public Matrix4f scaleAround(float sx, float sy, float sz, float ox, float oy, float oz) { return scaleAround(sx, sy, sz, ox, oy, oz, thisOrNew()); }
[ "public", "Matrix4f", "scaleAround", "(", "float", "sx", ",", "float", "sy", ",", "float", "sz", ",", "float", "ox", ",", "float", "oy", ",", "float", "oz", ")", "{", "return", "scaleAround", "(", "sx", ",", "sy", ",", "sz", ",", "ox", ",", "oy", ...
Apply scaling to this matrix by scaling the base axes by the given sx, sy and sz factors while using <code>(ox, oy, oz)</code> as the scaling origin. <p> If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, then the new matrix will be <code>M * S</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the scaling will be applied first! <p> This method is equivalent to calling: <code>translate(ox, oy, oz).scale(sx, sy, sz).translate(-ox, -oy, -oz)</code> @param sx the scaling factor of the x component @param sy the scaling factor of the y component @param sz the scaling factor of the z component @param ox the x coordinate of the scaling origin @param oy the y coordinate of the scaling origin @param oz the z coordinate of the scaling origin @return a matrix holding the result
[ "Apply", "scaling", "to", "this", "matrix", "by", "scaling", "the", "base", "axes", "by", "the", "given", "sx", "sy", "and", "sz", "factors", "while", "using", "<code", ">", "(", "ox", "oy", "oz", ")", "<", "/", "code", ">", "as", "the", "scaling", ...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L4841-L4843
JakeWharton/ActionBarSherlock
actionbarsherlock/src/com/actionbarsherlock/widget/SearchView.java
SearchView.onKeyDown
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { """ Handles the key down event for dealing with action keys. @param keyCode This is the keycode of the typed key, and is the same value as found in the KeyEvent parameter. @param event The complete event record for the typed key @return true if the event was handled here, or false if not. """ if (mSearchable == null) { return false; } // if it's an action specified by the searchable activity, launch the // entered query with the action key // TODO SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); // TODO if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) { // TODO launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView.getText() // TODO .toString()); // TODO return true; // TODO } return super.onKeyDown(keyCode, event); }
java
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mSearchable == null) { return false; } // if it's an action specified by the searchable activity, launch the // entered query with the action key // TODO SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); // TODO if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) { // TODO launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView.getText() // TODO .toString()); // TODO return true; // TODO } return super.onKeyDown(keyCode, event); }
[ "@", "Override", "public", "boolean", "onKeyDown", "(", "int", "keyCode", ",", "KeyEvent", "event", ")", "{", "if", "(", "mSearchable", "==", "null", ")", "{", "return", "false", ";", "}", "// if it's an action specified by the searchable activity, launch the", "// ...
Handles the key down event for dealing with action keys. @param keyCode This is the keycode of the typed key, and is the same value as found in the KeyEvent parameter. @param event The complete event record for the typed key @return true if the event was handled here, or false if not.
[ "Handles", "the", "key", "down", "event", "for", "dealing", "with", "action", "keys", "." ]
train
https://github.com/JakeWharton/ActionBarSherlock/blob/2c71339e756bcc0b1424c4525680549ba3a2dc97/actionbarsherlock/src/com/actionbarsherlock/widget/SearchView.java#L901-L917
Azure/azure-sdk-for-java
sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncAgentsInner.java
SyncAgentsInner.generateKeyAsync
public Observable<SyncAgentKeyPropertiesInner> generateKeyAsync(String resourceGroupName, String serverName, String syncAgentName) { """ Generates a sync agent key. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server on which the sync agent is hosted. @param syncAgentName The name of the sync agent. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the SyncAgentKeyPropertiesInner object """ return generateKeyWithServiceResponseAsync(resourceGroupName, serverName, syncAgentName).map(new Func1<ServiceResponse<SyncAgentKeyPropertiesInner>, SyncAgentKeyPropertiesInner>() { @Override public SyncAgentKeyPropertiesInner call(ServiceResponse<SyncAgentKeyPropertiesInner> response) { return response.body(); } }); }
java
public Observable<SyncAgentKeyPropertiesInner> generateKeyAsync(String resourceGroupName, String serverName, String syncAgentName) { return generateKeyWithServiceResponseAsync(resourceGroupName, serverName, syncAgentName).map(new Func1<ServiceResponse<SyncAgentKeyPropertiesInner>, SyncAgentKeyPropertiesInner>() { @Override public SyncAgentKeyPropertiesInner call(ServiceResponse<SyncAgentKeyPropertiesInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "SyncAgentKeyPropertiesInner", ">", "generateKeyAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "syncAgentName", ")", "{", "return", "generateKeyWithServiceResponseAsync", "(", "resourceGroupName", ",", ...
Generates a sync agent key. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server on which the sync agent is hosted. @param syncAgentName The name of the sync agent. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the SyncAgentKeyPropertiesInner object
[ "Generates", "a", "sync", "agent", "key", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncAgentsInner.java#L879-L886
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbPeople.java
TmdbPeople.getPersonExternalIds
public ExternalID getPersonExternalIds(int personId) throws MovieDbException { """ Get the external ids for a specific person id. @param personId @return @throws MovieDbException """ TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, personId); URL url = new ApiUrl(apiKey, MethodBase.PERSON).subMethod(MethodSub.EXTERNAL_IDS).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, ExternalID.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get person external IDs", url, ex); } }
java
public ExternalID getPersonExternalIds(int personId) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, personId); URL url = new ApiUrl(apiKey, MethodBase.PERSON).subMethod(MethodSub.EXTERNAL_IDS).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, ExternalID.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get person external IDs", url, ex); } }
[ "public", "ExternalID", "getPersonExternalIds", "(", "int", "personId", ")", "throws", "MovieDbException", "{", "TmdbParameters", "parameters", "=", "new", "TmdbParameters", "(", ")", ";", "parameters", ".", "add", "(", "Param", ".", "ID", ",", "personId", ")", ...
Get the external ids for a specific person id. @param personId @return @throws MovieDbException
[ "Get", "the", "external", "ids", "for", "a", "specific", "person", "id", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbPeople.java#L195-L207
google/truth
core/src/main/java/com/google/common/truth/Correspondence.java
Correspondence.safeCompare
final boolean safeCompare( @NullableDecl A actual, @NullableDecl E expected, ExceptionStore exceptions) { """ Invokes {@link #compare}, catching any exceptions. If the comparison does not throw, returns the result. If it does throw, adds the exception to the given {@link ExceptionStore} and returns false. This method can help with implementing the exception-handling policy described above, but note that assertions using it <i>must</i> fail later if an exception was stored. """ try { return compare(actual, expected); } catch (RuntimeException e) { exceptions.addCompareException(Correspondence.class, e, actual, expected); return false; } }
java
final boolean safeCompare( @NullableDecl A actual, @NullableDecl E expected, ExceptionStore exceptions) { try { return compare(actual, expected); } catch (RuntimeException e) { exceptions.addCompareException(Correspondence.class, e, actual, expected); return false; } }
[ "final", "boolean", "safeCompare", "(", "@", "NullableDecl", "A", "actual", ",", "@", "NullableDecl", "E", "expected", ",", "ExceptionStore", "exceptions", ")", "{", "try", "{", "return", "compare", "(", "actual", ",", "expected", ")", ";", "}", "catch", "...
Invokes {@link #compare}, catching any exceptions. If the comparison does not throw, returns the result. If it does throw, adds the exception to the given {@link ExceptionStore} and returns false. This method can help with implementing the exception-handling policy described above, but note that assertions using it <i>must</i> fail later if an exception was stored.
[ "Invokes", "{" ]
train
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/Correspondence.java#L682-L690
SonarOpenCommunity/sonar-cxx
cxx-sensors/src/main/java/org/sonar/cxx/sensors/utils/CxxReportSensor.java
CxxReportSensor.getContextStringProperty
public static String getContextStringProperty(SensorContext context, String name, String def) { """ Get string property from configuration. If the string is not set or empty, return the default value. @param context sensor context @param name Name of the property @param def Default value @return Value of the property if set and not empty, else default value. """ String s = context.config().get(name).orElse(null); if (s == null || s.isEmpty()) { return def; } return s; }
java
public static String getContextStringProperty(SensorContext context, String name, String def) { String s = context.config().get(name).orElse(null); if (s == null || s.isEmpty()) { return def; } return s; }
[ "public", "static", "String", "getContextStringProperty", "(", "SensorContext", "context", ",", "String", "name", ",", "String", "def", ")", "{", "String", "s", "=", "context", ".", "config", "(", ")", ".", "get", "(", "name", ")", ".", "orElse", "(", "n...
Get string property from configuration. If the string is not set or empty, return the default value. @param context sensor context @param name Name of the property @param def Default value @return Value of the property if set and not empty, else default value.
[ "Get", "string", "property", "from", "configuration", ".", "If", "the", "string", "is", "not", "set", "or", "empty", "return", "the", "default", "value", "." ]
train
https://github.com/SonarOpenCommunity/sonar-cxx/blob/7e7a3a44d6d86382a0434652a798f8235503c9b8/cxx-sensors/src/main/java/org/sonar/cxx/sensors/utils/CxxReportSensor.java#L71-L77
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java
JDBCResultSet.getTime
public Time getTime(int columnIndex, Calendar cal) throws SQLException { """ <!-- start generic documentation --> Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object as a <code>java.sql.Time</code> object in the Java programming language. This method uses the given calendar to construct an appropriate millisecond value for the time if the underlying database does not store timezone information. <!-- end generic documentation --> <h3>HSQLDB-Specific Information:</h3> <p> The JDBC specification for this method is vague. HSQLDB interprets the specification as follows: <ol> <li>If the SQL type of the column is WITH TIME ZONE, then the UTC value of the returned java.sql.Time object is the UTC of the SQL value without modification. In other words, the Calendar object is not used.</li> <li>If the SQL type of the column is WITHOUT TIME ZONE, then the UTC value of the returned java.sql.Time is correct for the given Calendar object.</li> <li>If the cal argument is null, it it ignored and the method returns the same Object as the method without the Calendar parameter.</li> </ol> </div> @param columnIndex the first column is 1, the second is 2, ... @param cal the <code>java.util.Calendar</code> object to use in constructing the time @return the column value as a <code>java.sql.Time</code> object; if the value is SQL <code>NULL</code>, the value returned is <code>null</code> in the Java programming language @exception SQLException if a database access error occurs or this method is called on a closed result set @since JDK 1.2 (JDK 1.1.x developers: read the overview for JDBCResultSet) """ TimeData t = (TimeData) getColumnInType(columnIndex, Type.SQL_TIME); if (t == null) { return null; } long millis = t.getSeconds() * 1000; if (resultMetaData.columnTypes[--columnIndex] .isDateTimeTypeWithZone()) {} else { // UTC - calZO == (UTC - sessZO) + (sessionZO - calZO) if (cal != null) { int zoneOffset = HsqlDateTime.getZoneMillis(cal, millis); millis += session.getZoneSeconds() * 1000 - zoneOffset; } } return new Time(millis); }
java
public Time getTime(int columnIndex, Calendar cal) throws SQLException { TimeData t = (TimeData) getColumnInType(columnIndex, Type.SQL_TIME); if (t == null) { return null; } long millis = t.getSeconds() * 1000; if (resultMetaData.columnTypes[--columnIndex] .isDateTimeTypeWithZone()) {} else { // UTC - calZO == (UTC - sessZO) + (sessionZO - calZO) if (cal != null) { int zoneOffset = HsqlDateTime.getZoneMillis(cal, millis); millis += session.getZoneSeconds() * 1000 - zoneOffset; } } return new Time(millis); }
[ "public", "Time", "getTime", "(", "int", "columnIndex", ",", "Calendar", "cal", ")", "throws", "SQLException", "{", "TimeData", "t", "=", "(", "TimeData", ")", "getColumnInType", "(", "columnIndex", ",", "Type", ".", "SQL_TIME", ")", ";", "if", "(", "t", ...
<!-- start generic documentation --> Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object as a <code>java.sql.Time</code> object in the Java programming language. This method uses the given calendar to construct an appropriate millisecond value for the time if the underlying database does not store timezone information. <!-- end generic documentation --> <h3>HSQLDB-Specific Information:</h3> <p> The JDBC specification for this method is vague. HSQLDB interprets the specification as follows: <ol> <li>If the SQL type of the column is WITH TIME ZONE, then the UTC value of the returned java.sql.Time object is the UTC of the SQL value without modification. In other words, the Calendar object is not used.</li> <li>If the SQL type of the column is WITHOUT TIME ZONE, then the UTC value of the returned java.sql.Time is correct for the given Calendar object.</li> <li>If the cal argument is null, it it ignored and the method returns the same Object as the method without the Calendar parameter.</li> </ol> </div> @param columnIndex the first column is 1, the second is 2, ... @param cal the <code>java.util.Calendar</code> object to use in constructing the time @return the column value as a <code>java.sql.Time</code> object; if the value is SQL <code>NULL</code>, the value returned is <code>null</code> in the Java programming language @exception SQLException if a database access error occurs or this method is called on a closed result set @since JDK 1.2 (JDK 1.1.x developers: read the overview for JDBCResultSet)
[ "<!", "--", "start", "generic", "documentation", "--", ">", "Retrieves", "the", "value", "of", "the", "designated", "column", "in", "the", "current", "row", "of", "this", "<code", ">", "ResultSet<", "/", "code", ">", "object", "as", "a", "<code", ">", "j...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java#L4573-L4596
FasterXML/jackson-jr
jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/impl/ValueWriterLocator.java
ValueWriterLocator.findSerializationType
public final int findSerializationType(Class<?> raw) { """ The main lookup method used to find type identifier for given raw class; including Bean types (if allowed). """ if (raw == _prevClass) { return _prevType; } if (raw == String.class) { return SER_STRING; } ClassKey k = (_key == null) ? new ClassKey(raw, _features) : _key.with(raw, _features); int type; Integer I = _knownSerTypes.get(k); if (I == null) { type = _findPOJOSerializationType(raw); _knownSerTypes.put(new ClassKey(raw, _features), Integer.valueOf(type)); } else { type = I.intValue(); } _prevType = type; _prevClass = raw; return type; }
java
public final int findSerializationType(Class<?> raw) { if (raw == _prevClass) { return _prevType; } if (raw == String.class) { return SER_STRING; } ClassKey k = (_key == null) ? new ClassKey(raw, _features) : _key.with(raw, _features); int type; Integer I = _knownSerTypes.get(k); if (I == null) { type = _findPOJOSerializationType(raw); _knownSerTypes.put(new ClassKey(raw, _features), Integer.valueOf(type)); } else { type = I.intValue(); } _prevType = type; _prevClass = raw; return type; }
[ "public", "final", "int", "findSerializationType", "(", "Class", "<", "?", ">", "raw", ")", "{", "if", "(", "raw", "==", "_prevClass", ")", "{", "return", "_prevType", ";", "}", "if", "(", "raw", "==", "String", ".", "class", ")", "{", "return", "SER...
The main lookup method used to find type identifier for given raw class; including Bean types (if allowed).
[ "The", "main", "lookup", "method", "used", "to", "find", "type", "identifier", "for", "given", "raw", "class", ";", "including", "Bean", "types", "(", "if", "allowed", ")", "." ]
train
https://github.com/FasterXML/jackson-jr/blob/62ca7a82bd90a9be77028e0b62364307d7532837/jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/impl/ValueWriterLocator.java#L115-L137
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/tools/EscapeTool.java
EscapeTool.addQueryStringPair
private void addQueryStringPair(String cleanKey, Object rawValue, StringBuilder queryStringBuilder) { """ Method to add an key / value pair to a query String. @param cleanKey Already escaped key @param rawValue Raw value associated to the key @param queryStringBuilder String Builder containing the current query string """ // Serialize null values as an empty string. String valueAsString = rawValue == null ? "" : String.valueOf(rawValue); String cleanValue = this.url(valueAsString); if (queryStringBuilder.length() != 0) { queryStringBuilder.append(AND); } queryStringBuilder.append(cleanKey).append(EQUALS).append(cleanValue); }
java
private void addQueryStringPair(String cleanKey, Object rawValue, StringBuilder queryStringBuilder) { // Serialize null values as an empty string. String valueAsString = rawValue == null ? "" : String.valueOf(rawValue); String cleanValue = this.url(valueAsString); if (queryStringBuilder.length() != 0) { queryStringBuilder.append(AND); } queryStringBuilder.append(cleanKey).append(EQUALS).append(cleanValue); }
[ "private", "void", "addQueryStringPair", "(", "String", "cleanKey", ",", "Object", "rawValue", ",", "StringBuilder", "queryStringBuilder", ")", "{", "// Serialize null values as an empty string.", "String", "valueAsString", "=", "rawValue", "==", "null", "?", "\"\"", ":...
Method to add an key / value pair to a query String. @param cleanKey Already escaped key @param rawValue Raw value associated to the key @param queryStringBuilder String Builder containing the current query string
[ "Method", "to", "add", "an", "key", "/", "value", "pair", "to", "a", "query", "String", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/tools/EscapeTool.java#L199-L208
Alluxio/alluxio
core/common/src/main/java/alluxio/util/io/BufferUtils.java
BufferUtils.sliceByteBuffer
public static ByteBuffer sliceByteBuffer(ByteBuffer buffer, int position, int length) { """ Creates a new ByteBuffer sliced from a given ByteBuffer. The new ByteBuffer shares the content of the existing one, but with independent position/mark/limit. After slicing, the new ByteBuffer has position 0, and the input ByteBuffer is unmodified. @param buffer source ByteBuffer to slice @param position position in the source ByteBuffer to slice @param length length of the sliced ByteBuffer @return the sliced ByteBuffer """ ByteBuffer slicedBuffer = ((ByteBuffer) buffer.duplicate().position(position)).slice(); slicedBuffer.limit(length); return slicedBuffer; }
java
public static ByteBuffer sliceByteBuffer(ByteBuffer buffer, int position, int length) { ByteBuffer slicedBuffer = ((ByteBuffer) buffer.duplicate().position(position)).slice(); slicedBuffer.limit(length); return slicedBuffer; }
[ "public", "static", "ByteBuffer", "sliceByteBuffer", "(", "ByteBuffer", "buffer", ",", "int", "position", ",", "int", "length", ")", "{", "ByteBuffer", "slicedBuffer", "=", "(", "(", "ByteBuffer", ")", "buffer", ".", "duplicate", "(", ")", ".", "position", "...
Creates a new ByteBuffer sliced from a given ByteBuffer. The new ByteBuffer shares the content of the existing one, but with independent position/mark/limit. After slicing, the new ByteBuffer has position 0, and the input ByteBuffer is unmodified. @param buffer source ByteBuffer to slice @param position position in the source ByteBuffer to slice @param length length of the sliced ByteBuffer @return the sliced ByteBuffer
[ "Creates", "a", "new", "ByteBuffer", "sliced", "from", "a", "given", "ByteBuffer", ".", "The", "new", "ByteBuffer", "shares", "the", "content", "of", "the", "existing", "one", "but", "with", "independent", "position", "/", "mark", "/", "limit", ".", "After",...
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/BufferUtils.java#L338-L342
atomix/copycat
server/src/main/java/io/atomix/copycat/server/storage/Storage.java
Storage.openLog
public Log openLog(String name) { """ Opens a new {@link Log}, recovering the log from disk if it exists. <p> When a log is opened, the log will attempt to load {@link Segment}s from the storage {@link #directory()} according to the provided log {@code name}. If segments for the given log name are present on disk, segments will be loaded and indexes will be rebuilt from disk. If no segments are found, an empty log will be created. <p> When log files are loaded from disk, the file names are expected to be based on the provided log {@code name}. @param name The log name. @return The opened log. """ return new Log(name, this, ThreadContext.currentContextOrThrow().serializer().clone()); }
java
public Log openLog(String name) { return new Log(name, this, ThreadContext.currentContextOrThrow().serializer().clone()); }
[ "public", "Log", "openLog", "(", "String", "name", ")", "{", "return", "new", "Log", "(", "name", ",", "this", ",", "ThreadContext", ".", "currentContextOrThrow", "(", ")", ".", "serializer", "(", ")", ".", "clone", "(", ")", ")", ";", "}" ]
Opens a new {@link Log}, recovering the log from disk if it exists. <p> When a log is opened, the log will attempt to load {@link Segment}s from the storage {@link #directory()} according to the provided log {@code name}. If segments for the given log name are present on disk, segments will be loaded and indexes will be rebuilt from disk. If no segments are found, an empty log will be created. <p> When log files are loaded from disk, the file names are expected to be based on the provided log {@code name}. @param name The log name. @return The opened log.
[ "Opens", "a", "new", "{", "@link", "Log", "}", "recovering", "the", "log", "from", "disk", "if", "it", "exists", ".", "<p", ">", "When", "a", "log", "is", "opened", "the", "log", "will", "attempt", "to", "load", "{", "@link", "Segment", "}", "s", "...
train
https://github.com/atomix/copycat/blob/c90b88ccd5c63d6ea0b49fb77c25e2f3272a7b10/server/src/main/java/io/atomix/copycat/server/storage/Storage.java#L321-L323
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/NetworkClient.java
NetworkClient.insertNetwork
@BetaApi public final Operation insertNetwork(String project, Network networkResource) { """ Creates a network in the specified project using the data included in the request. <p>Sample code: <pre><code> try (NetworkClient networkClient = NetworkClient.create()) { ProjectName project = ProjectName.of("[PROJECT]"); Network networkResource = Network.newBuilder().build(); Operation response = networkClient.insertNetwork(project.toString(), networkResource); } </code></pre> @param project Project ID for this request. @param networkResource Represents a Network resource. Read Virtual Private Cloud (VPC) Network Overview for more information. (== resource_for v1.networks ==) (== resource_for beta.networks ==) @throws com.google.api.gax.rpc.ApiException if the remote call fails """ InsertNetworkHttpRequest request = InsertNetworkHttpRequest.newBuilder() .setProject(project) .setNetworkResource(networkResource) .build(); return insertNetwork(request); }
java
@BetaApi public final Operation insertNetwork(String project, Network networkResource) { InsertNetworkHttpRequest request = InsertNetworkHttpRequest.newBuilder() .setProject(project) .setNetworkResource(networkResource) .build(); return insertNetwork(request); }
[ "@", "BetaApi", "public", "final", "Operation", "insertNetwork", "(", "String", "project", ",", "Network", "networkResource", ")", "{", "InsertNetworkHttpRequest", "request", "=", "InsertNetworkHttpRequest", ".", "newBuilder", "(", ")", ".", "setProject", "(", "proj...
Creates a network in the specified project using the data included in the request. <p>Sample code: <pre><code> try (NetworkClient networkClient = NetworkClient.create()) { ProjectName project = ProjectName.of("[PROJECT]"); Network networkResource = Network.newBuilder().build(); Operation response = networkClient.insertNetwork(project.toString(), networkResource); } </code></pre> @param project Project ID for this request. @param networkResource Represents a Network resource. Read Virtual Private Cloud (VPC) Network Overview for more information. (== resource_for v1.networks ==) (== resource_for beta.networks ==) @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "network", "in", "the", "specified", "project", "using", "the", "data", "included", "in", "the", "request", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/NetworkClient.java#L511-L520
susom/database
src/main/java/com/github/susom/database/DatabaseProvider.java
DatabaseProvider.fromPropertyFile
public static Builder fromPropertyFile(String filename, String propertyPrefix) { """ Configure the database from up to five properties read from a file: <br/> <pre> database.url=... Database connect string (required) database.user=... Authenticate as this user (optional if provided in url) database.password=... User password (optional if user and password provided in url; prompted on standard input if user is provided and password is not) database.flavor=... What kind of database it is (optional, will guess based on the url if this is not provided) database.driver=... The Java class of the JDBC driver to load (optional, will guess based on the flavor if this is not provided) </pre> <p>This will use the JVM default character encoding to read the property file.</p> @param filename path to the properties file we will attempt to read @param propertyPrefix if this is null or empty the properties above will be read; if a value is provided it will be prefixed to each property (exactly, so if you want to use "my.database.url" you must pass "my." as the prefix) @throws DatabaseException if the property file could not be read for any reason """ return fromPropertyFile(filename, propertyPrefix, Charset.defaultCharset().newDecoder()); }
java
public static Builder fromPropertyFile(String filename, String propertyPrefix) { return fromPropertyFile(filename, propertyPrefix, Charset.defaultCharset().newDecoder()); }
[ "public", "static", "Builder", "fromPropertyFile", "(", "String", "filename", ",", "String", "propertyPrefix", ")", "{", "return", "fromPropertyFile", "(", "filename", ",", "propertyPrefix", ",", "Charset", ".", "defaultCharset", "(", ")", ".", "newDecoder", "(", ...
Configure the database from up to five properties read from a file: <br/> <pre> database.url=... Database connect string (required) database.user=... Authenticate as this user (optional if provided in url) database.password=... User password (optional if user and password provided in url; prompted on standard input if user is provided and password is not) database.flavor=... What kind of database it is (optional, will guess based on the url if this is not provided) database.driver=... The Java class of the JDBC driver to load (optional, will guess based on the flavor if this is not provided) </pre> <p>This will use the JVM default character encoding to read the property file.</p> @param filename path to the properties file we will attempt to read @param propertyPrefix if this is null or empty the properties above will be read; if a value is provided it will be prefixed to each property (exactly, so if you want to use "my.database.url" you must pass "my." as the prefix) @throws DatabaseException if the property file could not be read for any reason
[ "Configure", "the", "database", "from", "up", "to", "five", "properties", "read", "from", "a", "file", ":", "<br", "/", ">", "<pre", ">", "database", ".", "url", "=", "...", "Database", "connect", "string", "(", "required", ")", "database", ".", "user", ...
train
https://github.com/susom/database/blob/25add9e08ad863712f9b5e319b6cb826f6f97640/src/main/java/com/github/susom/database/DatabaseProvider.java#L314-L316
j-a-w-r/jawr-main-repo
jawr-grails/jawr-grails-plugin/src/java/net/jawr/web/resource/bundle/locale/GrailsLocaleUtils.java
GrailsLocaleUtils.getAvailableLocaleSuffixesForBundle
public static List<String> getAvailableLocaleSuffixesForBundle( String messageBundlePath, String fileSuffix, GrailsServletContextResourceReader rsReader) { """ Returns the list of available locale suffixes for a message resource bundle @param messageBundlePath the resource bundle path @param fileSuffix the file suffix @param rsReader the grails servlet context resource reader @return the list of available locale suffixes for a message resource bundle """ int idxNameSpace = messageBundlePath.indexOf("("); int idxFilter = messageBundlePath.indexOf("["); int idx = -1; if (idxNameSpace != -1 && idxFilter != -1) { idx = Math.min(idxNameSpace, idxFilter); } else if (idxNameSpace != -1 && idxFilter == -1) { idx = idxNameSpace; } else if (idxNameSpace == -1 && idxFilter != -1) { idx = idxFilter; } String messageBundle = null; if (idx > 0) { messageBundle = messageBundlePath.substring(0, idx); } else { messageBundle = messageBundlePath; } return getAvailableLocaleSuffixes(messageBundle, fileSuffix, rsReader); }
java
public static List<String> getAvailableLocaleSuffixesForBundle( String messageBundlePath, String fileSuffix, GrailsServletContextResourceReader rsReader) { int idxNameSpace = messageBundlePath.indexOf("("); int idxFilter = messageBundlePath.indexOf("["); int idx = -1; if (idxNameSpace != -1 && idxFilter != -1) { idx = Math.min(idxNameSpace, idxFilter); } else if (idxNameSpace != -1 && idxFilter == -1) { idx = idxNameSpace; } else if (idxNameSpace == -1 && idxFilter != -1) { idx = idxFilter; } String messageBundle = null; if (idx > 0) { messageBundle = messageBundlePath.substring(0, idx); } else { messageBundle = messageBundlePath; } return getAvailableLocaleSuffixes(messageBundle, fileSuffix, rsReader); }
[ "public", "static", "List", "<", "String", ">", "getAvailableLocaleSuffixesForBundle", "(", "String", "messageBundlePath", ",", "String", "fileSuffix", ",", "GrailsServletContextResourceReader", "rsReader", ")", "{", "int", "idxNameSpace", "=", "messageBundlePath", ".", ...
Returns the list of available locale suffixes for a message resource bundle @param messageBundlePath the resource bundle path @param fileSuffix the file suffix @param rsReader the grails servlet context resource reader @return the list of available locale suffixes for a message resource bundle
[ "Returns", "the", "list", "of", "available", "locale", "suffixes", "for", "a", "message", "resource", "bundle" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr-grails/jawr-grails-plugin/src/java/net/jawr/web/resource/bundle/locale/GrailsLocaleUtils.java#L120-L142
apereo/cas
support/cas-server-support-validation/src/main/java/org/apereo/cas/web/AbstractServiceValidateController.java
AbstractServiceValidateController.enforceTicketValidationAuthorizationFor
protected void enforceTicketValidationAuthorizationFor(final HttpServletRequest request, final Service service, final Assertion assertion) { """ Enforce ticket validation authorization for. @param request the request @param service the service @param assertion the assertion """ val authorizers = serviceValidateConfigurationContext.getValidationAuthorizers().getAuthorizers(); for (val a : authorizers) { try { a.authorize(request, service, assertion); } catch (final Exception e) { throw new UnauthorizedServiceTicketValidationException(service); } } }
java
protected void enforceTicketValidationAuthorizationFor(final HttpServletRequest request, final Service service, final Assertion assertion) { val authorizers = serviceValidateConfigurationContext.getValidationAuthorizers().getAuthorizers(); for (val a : authorizers) { try { a.authorize(request, service, assertion); } catch (final Exception e) { throw new UnauthorizedServiceTicketValidationException(service); } } }
[ "protected", "void", "enforceTicketValidationAuthorizationFor", "(", "final", "HttpServletRequest", "request", ",", "final", "Service", "service", ",", "final", "Assertion", "assertion", ")", "{", "val", "authorizers", "=", "serviceValidateConfigurationContext", ".", "get...
Enforce ticket validation authorization for. @param request the request @param service the service @param assertion the assertion
[ "Enforce", "ticket", "validation", "authorization", "for", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-validation/src/main/java/org/apereo/cas/web/AbstractServiceValidateController.java#L320-L329
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/BibliographyFileReader.java
BibliographyFileReader.readBibliographyFile
public ItemDataProvider readBibliographyFile(File bibfile) throws FileNotFoundException, IOException { """ Reads all items from an input bibliography file and returns a provider serving these items @param bibfile the input file @return the provider @throws FileNotFoundException if the input file was not found @throws IOException if the input file could not be read """ //open buffered input stream to bibliography file if (!bibfile.exists()) { throw new FileNotFoundException("Bibliography file `" + bibfile.getName() + "' does not exist"); } try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(bibfile))) { return readBibliographyFile(bis, bibfile.getName()); } }
java
public ItemDataProvider readBibliographyFile(File bibfile) throws FileNotFoundException, IOException { //open buffered input stream to bibliography file if (!bibfile.exists()) { throw new FileNotFoundException("Bibliography file `" + bibfile.getName() + "' does not exist"); } try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(bibfile))) { return readBibliographyFile(bis, bibfile.getName()); } }
[ "public", "ItemDataProvider", "readBibliographyFile", "(", "File", "bibfile", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "//open buffered input stream to bibliography file", "if", "(", "!", "bibfile", ".", "exists", "(", ")", ")", "{", "throw", "...
Reads all items from an input bibliography file and returns a provider serving these items @param bibfile the input file @return the provider @throws FileNotFoundException if the input file was not found @throws IOException if the input file could not be read
[ "Reads", "all", "items", "from", "an", "input", "bibliography", "file", "and", "returns", "a", "provider", "serving", "these", "items" ]
train
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/BibliographyFileReader.java#L103-L114
killbill/killbill
catalog/src/main/java/org/killbill/billing/catalog/caching/DefaultCatalogCache.java
DefaultCatalogCache.initializeCacheLoaderArgument
private CacheLoaderArgument initializeCacheLoaderArgument(final boolean filterTemplateCatalog) { """ This is a contract between the TenantCatalogCacheLoader and the DefaultCatalogCache """ final LoaderCallback loaderCallback = new LoaderCallback() { @Override public Catalog loadCatalog(final List<String> catalogXMLs, final Long tenantRecordId) throws CatalogApiException { return loader.load(catalogXMLs, filterTemplateCatalog, tenantRecordId); } }; final Object[] args = new Object[1]; args[0] = loaderCallback; final ObjectType irrelevant = null; final InternalTenantContext notUsed = null; return new CacheLoaderArgument(irrelevant, args, notUsed); }
java
private CacheLoaderArgument initializeCacheLoaderArgument(final boolean filterTemplateCatalog) { final LoaderCallback loaderCallback = new LoaderCallback() { @Override public Catalog loadCatalog(final List<String> catalogXMLs, final Long tenantRecordId) throws CatalogApiException { return loader.load(catalogXMLs, filterTemplateCatalog, tenantRecordId); } }; final Object[] args = new Object[1]; args[0] = loaderCallback; final ObjectType irrelevant = null; final InternalTenantContext notUsed = null; return new CacheLoaderArgument(irrelevant, args, notUsed); }
[ "private", "CacheLoaderArgument", "initializeCacheLoaderArgument", "(", "final", "boolean", "filterTemplateCatalog", ")", "{", "final", "LoaderCallback", "loaderCallback", "=", "new", "LoaderCallback", "(", ")", "{", "@", "Override", "public", "Catalog", "loadCatalog", ...
This is a contract between the TenantCatalogCacheLoader and the DefaultCatalogCache
[ "This", "is", "a", "contract", "between", "the", "TenantCatalogCacheLoader", "and", "the", "DefaultCatalogCache" ]
train
https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/catalog/src/main/java/org/killbill/billing/catalog/caching/DefaultCatalogCache.java#L214-L226
sdaschner/jaxrs-analyzer
src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java
JavaUtils.isAnnotationPresent
public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class<?> annotationClass) { """ Checks if the annotation is present on the annotated element. <b>Note:</b> This step is necessary due to issues with external class loaders (e.g. Maven). The classes may not be identical and are therefore compared by FQ class name. """ return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName())); }
java
public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class<?> annotationClass) { return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName())); }
[ "public", "static", "boolean", "isAnnotationPresent", "(", "final", "AnnotatedElement", "annotatedElement", ",", "final", "Class", "<", "?", ">", "annotationClass", ")", "{", "return", "Stream", ".", "of", "(", "annotatedElement", ".", "getAnnotations", "(", ")", ...
Checks if the annotation is present on the annotated element. <b>Note:</b> This step is necessary due to issues with external class loaders (e.g. Maven). The classes may not be identical and are therefore compared by FQ class name.
[ "Checks", "if", "the", "annotation", "is", "present", "on", "the", "annotated", "element", ".", "<b", ">", "Note", ":", "<", "/", "b", ">", "This", "step", "is", "necessary", "due", "to", "issues", "with", "external", "class", "loaders", "(", "e", ".",...
train
https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java#L78-L80
exoplatform/jcr
exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipHandlerImpl.java
MembershipHandlerImpl.postSave
private void postSave(Membership membership, boolean isNew) throws Exception { """ Notifying listeners after membership creation. @param membership the membership which is used in create operation @param isNew true, if we have a deal with new membership, otherwise it is false which mean update operation is in progress @throws Exception if any listener failed to handle the event """ for (MembershipEventListener listener : listeners) { listener.postSave(membership, isNew); } }
java
private void postSave(Membership membership, boolean isNew) throws Exception { for (MembershipEventListener listener : listeners) { listener.postSave(membership, isNew); } }
[ "private", "void", "postSave", "(", "Membership", "membership", ",", "boolean", "isNew", ")", "throws", "Exception", "{", "for", "(", "MembershipEventListener", "listener", ":", "listeners", ")", "{", "listener", ".", "postSave", "(", "membership", ",", "isNew",...
Notifying listeners after membership creation. @param membership the membership which is used in create operation @param isNew true, if we have a deal with new membership, otherwise it is false which mean update operation is in progress @throws Exception if any listener failed to handle the event
[ "Notifying", "listeners", "after", "membership", "creation", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipHandlerImpl.java#L723-L729
apache/spark
common/network-common/src/main/java/org/apache/spark/network/sasl/SaslServerBootstrap.java
SaslServerBootstrap.doBootstrap
public RpcHandler doBootstrap(Channel channel, RpcHandler rpcHandler) { """ Wrap the given application handler in a SaslRpcHandler that will handle the initial SASL negotiation. """ return new SaslRpcHandler(conf, channel, rpcHandler, secretKeyHolder); }
java
public RpcHandler doBootstrap(Channel channel, RpcHandler rpcHandler) { return new SaslRpcHandler(conf, channel, rpcHandler, secretKeyHolder); }
[ "public", "RpcHandler", "doBootstrap", "(", "Channel", "channel", ",", "RpcHandler", "rpcHandler", ")", "{", "return", "new", "SaslRpcHandler", "(", "conf", ",", "channel", ",", "rpcHandler", ",", "secretKeyHolder", ")", ";", "}" ]
Wrap the given application handler in a SaslRpcHandler that will handle the initial SASL negotiation.
[ "Wrap", "the", "given", "application", "handler", "in", "a", "SaslRpcHandler", "that", "will", "handle", "the", "initial", "SASL", "negotiation", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-common/src/main/java/org/apache/spark/network/sasl/SaslServerBootstrap.java#L45-L47
mlhartme/sushi
src/main/java/net/oneandone/sushi/fs/World.java
World.locatePathEntry
public FileNode locatePathEntry(Class<?> c) { """ Returns the file or directory or module containing the specified class. @param c the source class @return the physical file defining the class """ return locateEntry(c, Reflect.resourceName(c), true); }
java
public FileNode locatePathEntry(Class<?> c) { return locateEntry(c, Reflect.resourceName(c), true); }
[ "public", "FileNode", "locatePathEntry", "(", "Class", "<", "?", ">", "c", ")", "{", "return", "locateEntry", "(", "c", ",", "Reflect", ".", "resourceName", "(", "c", ")", ",", "true", ")", ";", "}" ]
Returns the file or directory or module containing the specified class. @param c the source class @return the physical file defining the class
[ "Returns", "the", "file", "or", "directory", "or", "module", "containing", "the", "specified", "class", "." ]
train
https://github.com/mlhartme/sushi/blob/4af33414b04bd58584d4febe5cc63ef6c7346a75/src/main/java/net/oneandone/sushi/fs/World.java#L550-L552
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.truncatedCompareTo
public static int truncatedCompareTo(final Date date1, final Date date2, final int field) { """ Determines how two dates compare up to no more than the specified most significant field. @param date1 the first date, not <code>null</code> @param date2 the second date, not <code>null</code> @param field the field from <code>Calendar</code> @return a negative integer, zero, or a positive integer as the first date is less than, equal to, or greater than the second. @throws IllegalArgumentException if any argument is <code>null</code> @see #truncate(Calendar, int) @see #truncatedCompareTo(Date, Date, int) @since 3.0 """ final Date truncatedDate1 = truncate(date1, field); final Date truncatedDate2 = truncate(date2, field); return truncatedDate1.compareTo(truncatedDate2); }
java
public static int truncatedCompareTo(final Date date1, final Date date2, final int field) { final Date truncatedDate1 = truncate(date1, field); final Date truncatedDate2 = truncate(date2, field); return truncatedDate1.compareTo(truncatedDate2); }
[ "public", "static", "int", "truncatedCompareTo", "(", "final", "Date", "date1", ",", "final", "Date", "date2", ",", "final", "int", "field", ")", "{", "final", "Date", "truncatedDate1", "=", "truncate", "(", "date1", ",", "field", ")", ";", "final", "Date"...
Determines how two dates compare up to no more than the specified most significant field. @param date1 the first date, not <code>null</code> @param date2 the second date, not <code>null</code> @param field the field from <code>Calendar</code> @return a negative integer, zero, or a positive integer as the first date is less than, equal to, or greater than the second. @throws IllegalArgumentException if any argument is <code>null</code> @see #truncate(Calendar, int) @see #truncatedCompareTo(Date, Date, int) @since 3.0
[ "Determines", "how", "two", "dates", "compare", "up", "to", "no", "more", "than", "the", "specified", "most", "significant", "field", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1798-L1802
ben-manes/caffeine
caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java
BoundedLocalCache.makeDead
@GuardedBy("evictionLock") void makeDead(Node<K, V> node) { """ Atomically transitions the node to the <tt>dead</tt> state and decrements the <tt>weightedSize</tt>. @param node the entry in the page replacement policy """ synchronized (node) { if (node.isDead()) { return; } if (evicts()) { // The node's policy weight may be out of sync due to a pending update waiting to be // processed. At this point the node's weight is finalized, so the weight can be safely // taken from the node's perspective and the sizes will be adjusted correctly. if (node.inWindow()) { setWindowWeightedSize(windowWeightedSize() - node.getWeight()); } else if (node.inMainProtected()) { setMainProtectedWeightedSize(mainProtectedWeightedSize() - node.getWeight()); } setWeightedSize(weightedSize() - node.getWeight()); } node.die(); } }
java
@GuardedBy("evictionLock") void makeDead(Node<K, V> node) { synchronized (node) { if (node.isDead()) { return; } if (evicts()) { // The node's policy weight may be out of sync due to a pending update waiting to be // processed. At this point the node's weight is finalized, so the weight can be safely // taken from the node's perspective and the sizes will be adjusted correctly. if (node.inWindow()) { setWindowWeightedSize(windowWeightedSize() - node.getWeight()); } else if (node.inMainProtected()) { setMainProtectedWeightedSize(mainProtectedWeightedSize() - node.getWeight()); } setWeightedSize(weightedSize() - node.getWeight()); } node.die(); } }
[ "@", "GuardedBy", "(", "\"evictionLock\"", ")", "void", "makeDead", "(", "Node", "<", "K", ",", "V", ">", "node", ")", "{", "synchronized", "(", "node", ")", "{", "if", "(", "node", ".", "isDead", "(", ")", ")", "{", "return", ";", "}", "if", "("...
Atomically transitions the node to the <tt>dead</tt> state and decrements the <tt>weightedSize</tt>. @param node the entry in the page replacement policy
[ "Atomically", "transitions", "the", "node", "to", "the", "<tt", ">", "dead<", "/", "tt", ">", "state", "and", "decrements", "the", "<tt", ">", "weightedSize<", "/", "tt", ">", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java#L1563-L1582
mikepenz/Materialize
library/src/main/java/com/mikepenz/materialize/holder/ImageHolder.java
ImageHolder.applyTo
public static boolean applyTo(ImageHolder imageHolder, ImageView imageView, String tag) { """ a small static helper to set the image from the imageHolder nullSave to the imageView @param imageHolder @param imageView @param tag used to identify imageViews and define different placeholders @return true if an image was set """ if (imageHolder != null && imageView != null) { return imageHolder.applyTo(imageView, tag); } return false; }
java
public static boolean applyTo(ImageHolder imageHolder, ImageView imageView, String tag) { if (imageHolder != null && imageView != null) { return imageHolder.applyTo(imageView, tag); } return false; }
[ "public", "static", "boolean", "applyTo", "(", "ImageHolder", "imageHolder", ",", "ImageView", "imageView", ",", "String", "tag", ")", "{", "if", "(", "imageHolder", "!=", "null", "&&", "imageView", "!=", "null", ")", "{", "return", "imageHolder", ".", "appl...
a small static helper to set the image from the imageHolder nullSave to the imageView @param imageHolder @param imageView @param tag used to identify imageViews and define different placeholders @return true if an image was set
[ "a", "small", "static", "helper", "to", "set", "the", "image", "from", "the", "imageHolder", "nullSave", "to", "the", "imageView" ]
train
https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/holder/ImageHolder.java#L170-L175
JetBrains/xodus
openAPI/src/main/java/jetbrains/exodus/entitystore/BlobVault.java
BlobVault.getStringContent
@Nullable public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException { """ Returns string content of blob identified by specified blob handle. String contents cache is used. @param blobHandle blob handle @param txn {@linkplain Transaction} instance @return string content of blob identified by specified blob handle @throws IOException if something went wrong """ String result; result = stringContentCache.tryKey(this, blobHandle); if (result == null) { final InputStream content = getContent(blobHandle, txn); if (content == null) { logger.error("Blob string not found: " + getBlobLocation(blobHandle), new FileNotFoundException()); } result = content == null ? null : UTFUtil.readUTF(content); if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) { if (stringContentCache.getObject(this, blobHandle) == null) { stringContentCache.cacheObject(this, blobHandle, result); } } } return result; }
java
@Nullable public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException { String result; result = stringContentCache.tryKey(this, blobHandle); if (result == null) { final InputStream content = getContent(blobHandle, txn); if (content == null) { logger.error("Blob string not found: " + getBlobLocation(blobHandle), new FileNotFoundException()); } result = content == null ? null : UTFUtil.readUTF(content); if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) { if (stringContentCache.getObject(this, blobHandle) == null) { stringContentCache.cacheObject(this, blobHandle, result); } } } return result; }
[ "@", "Nullable", "public", "final", "String", "getStringContent", "(", "final", "long", "blobHandle", ",", "@", "NotNull", "final", "Transaction", "txn", ")", "throws", "IOException", "{", "String", "result", ";", "result", "=", "stringContentCache", ".", "tryKe...
Returns string content of blob identified by specified blob handle. String contents cache is used. @param blobHandle blob handle @param txn {@linkplain Transaction} instance @return string content of blob identified by specified blob handle @throws IOException if something went wrong
[ "Returns", "string", "content", "of", "blob", "identified", "by", "specified", "blob", "handle", ".", "String", "contents", "cache", "is", "used", "." ]
train
https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/openAPI/src/main/java/jetbrains/exodus/entitystore/BlobVault.java#L199-L216
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/ObjectBindTransform.java
ObjectBindTransform.generateParseOnXml
@Override public void generateParseOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) { """ /* (non-Javadoc) @see com.abubusoft.kripton.processor.bind.transform.BindTransform#generateParseOnXml(com.abubusoft.kripton.processor.bind.BindTypeContext, com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.bind.model.BindProperty) """ // TODO QUA // TypeName typeName = resolveTypeName(property.getParent(), // property.getPropertyType().getTypeName()); TypeName typeName = property.getPropertyType().getTypeName(); String bindName = context.getBindMapperName(context, typeName); methodBuilder.addStatement(setter(beanClass, beanName, property, "$L.parseOnXml(xmlParser, eventType)"), bindName); }
java
@Override public void generateParseOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) { // TODO QUA // TypeName typeName = resolveTypeName(property.getParent(), // property.getPropertyType().getTypeName()); TypeName typeName = property.getPropertyType().getTypeName(); String bindName = context.getBindMapperName(context, typeName); methodBuilder.addStatement(setter(beanClass, beanName, property, "$L.parseOnXml(xmlParser, eventType)"), bindName); }
[ "@", "Override", "public", "void", "generateParseOnXml", "(", "BindTypeContext", "context", ",", "MethodSpec", ".", "Builder", "methodBuilder", ",", "String", "parserName", ",", "TypeName", "beanClass", ",", "String", "beanName", ",", "BindProperty", "property", ")"...
/* (non-Javadoc) @see com.abubusoft.kripton.processor.bind.transform.BindTransform#generateParseOnXml(com.abubusoft.kripton.processor.bind.BindTypeContext, com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.bind.model.BindProperty)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/ObjectBindTransform.java#L48-L57
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java
DurationFormatUtils.paddedValue
private static String paddedValue(final long value, final boolean padWithZeros, final int count) { """ <p>Converts a {@code long} to a {@code String} with optional zero padding.</p> @param value the value to convert @param padWithZeros whether to pad with zeroes @param count the size to pad to (ignored if {@code padWithZeros} is false) @return the string result """ final String longString = Long.toString(value); return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString; }
java
private static String paddedValue(final long value, final boolean padWithZeros, final int count) { final String longString = Long.toString(value); return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString; }
[ "private", "static", "String", "paddedValue", "(", "final", "long", "value", ",", "final", "boolean", "padWithZeros", ",", "final", "int", "count", ")", "{", "final", "String", "longString", "=", "Long", ".", "toString", "(", "value", ")", ";", "return", "...
<p>Converts a {@code long} to a {@code String} with optional zero padding.</p> @param value the value to convert @param padWithZeros whether to pad with zeroes @param count the size to pad to (ignored if {@code padWithZeros} is false) @return the string result
[ "<p", ">", "Converts", "a", "{", "@code", "long", "}", "to", "a", "{", "@code", "String", "}", "with", "optional", "zero", "padding", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java#L480-L483
UrielCh/ovh-java-sdk
ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java
ApiOvhIp.ip_spam_ipSpamming_unblock_POST
public OvhSpamIp ip_spam_ipSpamming_unblock_POST(String ip, String ipSpamming) throws IOException { """ Release the ip from anti-spam system REST: POST /ip/{ip}/spam/{ipSpamming}/unblock @param ip [required] @param ipSpamming [required] IP address which is sending spam """ String qPath = "/ip/{ip}/spam/{ipSpamming}/unblock"; StringBuilder sb = path(qPath, ip, ipSpamming); String resp = exec(qPath, "POST", sb.toString(), null); return convertTo(resp, OvhSpamIp.class); }
java
public OvhSpamIp ip_spam_ipSpamming_unblock_POST(String ip, String ipSpamming) throws IOException { String qPath = "/ip/{ip}/spam/{ipSpamming}/unblock"; StringBuilder sb = path(qPath, ip, ipSpamming); String resp = exec(qPath, "POST", sb.toString(), null); return convertTo(resp, OvhSpamIp.class); }
[ "public", "OvhSpamIp", "ip_spam_ipSpamming_unblock_POST", "(", "String", "ip", ",", "String", "ipSpamming", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ip/{ip}/spam/{ipSpamming}/unblock\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",",...
Release the ip from anti-spam system REST: POST /ip/{ip}/spam/{ipSpamming}/unblock @param ip [required] @param ipSpamming [required] IP address which is sending spam
[ "Release", "the", "ip", "from", "anti", "-", "spam", "system" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java#L210-L215
opentelecoms-org/zrtp-java
src/zorg/ZRTP.java
ZRTP.calculateSHA256Hash
private String calculateSHA256Hash(byte[] msg, int offset, int len) { """ Calculate the hash digest of part of a message using the SHA256 algorithm @param msg Contents of the message @param offset Offset of the data for the hash @param len Length of msg to be considered for calculating the hash @return String of the hash in base 16 """ // Calculate the SHA256 digest of the Hello message Digest digest = platform.getCrypto().createDigestSHA256(); digest.update(msg, offset, len); int digestLen = digest.getDigestLength(); // prepare space for hexadecimal representation, store the diggest in // the second half and then convert byte[] hash = new byte[2 * digestLen]; digest.getDigest(hash, digestLen, true); for (int i = 0; i != digestLen; ++i) { byte b = hash[digestLen + i]; int d1 = (b >> 4) & 0x0f; int d2 = b & 0x0f; hash[i * 2] = (byte) ((d1 >= 10) ? d1 + 'a' - 10 : d1 + '0'); hash[i * 2 + 1] = (byte) ((d2 >= 10) ? d2 + 'a' - 10 : d2 + '0'); } String hashStr = new String(hash); if (platform.getLogger().isEnabled()) { logBuffer("calculateSHA256Hash", msg, offset, len); logString("SHA256 Hash = '" + hashStr + "'"); } return hashStr; }
java
private String calculateSHA256Hash(byte[] msg, int offset, int len) { // Calculate the SHA256 digest of the Hello message Digest digest = platform.getCrypto().createDigestSHA256(); digest.update(msg, offset, len); int digestLen = digest.getDigestLength(); // prepare space for hexadecimal representation, store the diggest in // the second half and then convert byte[] hash = new byte[2 * digestLen]; digest.getDigest(hash, digestLen, true); for (int i = 0; i != digestLen; ++i) { byte b = hash[digestLen + i]; int d1 = (b >> 4) & 0x0f; int d2 = b & 0x0f; hash[i * 2] = (byte) ((d1 >= 10) ? d1 + 'a' - 10 : d1 + '0'); hash[i * 2 + 1] = (byte) ((d2 >= 10) ? d2 + 'a' - 10 : d2 + '0'); } String hashStr = new String(hash); if (platform.getLogger().isEnabled()) { logBuffer("calculateSHA256Hash", msg, offset, len); logString("SHA256 Hash = '" + hashStr + "'"); } return hashStr; }
[ "private", "String", "calculateSHA256Hash", "(", "byte", "[", "]", "msg", ",", "int", "offset", ",", "int", "len", ")", "{", "// Calculate the SHA256 digest of the Hello message", "Digest", "digest", "=", "platform", ".", "getCrypto", "(", ")", ".", "createDigestS...
Calculate the hash digest of part of a message using the SHA256 algorithm @param msg Contents of the message @param offset Offset of the data for the hash @param len Length of msg to be considered for calculating the hash @return String of the hash in base 16
[ "Calculate", "the", "hash", "digest", "of", "part", "of", "a", "message", "using", "the", "SHA256", "algorithm" ]
train
https://github.com/opentelecoms-org/zrtp-java/blob/10a0c77866c5d1b1504df161db9a447f5069ed54/src/zorg/ZRTP.java#L464-L486
SonarSource/sonarqube
sonar-core/src/main/java/org/sonar/core/util/Protobuf.java
Protobuf.writeStream
public static <MSG extends Message> void writeStream(Iterable<MSG> messages, File toFile, boolean append) { """ Streams multiple messages to {@code file}. Reading the messages back requires to call methods {@code readStream(...)}. <p> See https://developers.google.com/protocol-buffers/docs/techniques#streaming </p> """ OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(toFile, append)); writeStream(messages, out); } catch (Exception e) { throw ContextException.of("Unable to write messages", e).addContext("file", toFile); } finally { IOUtils.closeQuietly(out); } }
java
public static <MSG extends Message> void writeStream(Iterable<MSG> messages, File toFile, boolean append) { OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(toFile, append)); writeStream(messages, out); } catch (Exception e) { throw ContextException.of("Unable to write messages", e).addContext("file", toFile); } finally { IOUtils.closeQuietly(out); } }
[ "public", "static", "<", "MSG", "extends", "Message", ">", "void", "writeStream", "(", "Iterable", "<", "MSG", ">", "messages", ",", "File", "toFile", ",", "boolean", "append", ")", "{", "OutputStream", "out", "=", "null", ";", "try", "{", "out", "=", ...
Streams multiple messages to {@code file}. Reading the messages back requires to call methods {@code readStream(...)}. <p> See https://developers.google.com/protocol-buffers/docs/techniques#streaming </p>
[ "Streams", "multiple", "messages", "to", "{" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-core/src/main/java/org/sonar/core/util/Protobuf.java#L92-L102
apollographql/apollo-android
apollo-api/src/main/java/com/apollographql/apollo/api/ResponseField.java
ResponseField.forCustomType
public static CustomTypeField forCustomType(String responseName, String fieldName, Map<String, Object> arguments, boolean optional, ScalarType scalarType, List<Condition> conditions) { """ Factory method for creating a Field instance representing a custom GraphQL Scalar type, {@link Type#CUSTOM} @param responseName alias for the result of a field @param fieldName name of the field in the GraphQL operation @param arguments arguments to be passed along with the field @param optional whether the arguments passed along are optional or required @param scalarType the custom scalar type of the field @param conditions list of conditions for this field @return Field instance representing {@link Type#CUSTOM} """ return new CustomTypeField(responseName, fieldName, arguments, optional, scalarType, conditions); }
java
public static CustomTypeField forCustomType(String responseName, String fieldName, Map<String, Object> arguments, boolean optional, ScalarType scalarType, List<Condition> conditions) { return new CustomTypeField(responseName, fieldName, arguments, optional, scalarType, conditions); }
[ "public", "static", "CustomTypeField", "forCustomType", "(", "String", "responseName", ",", "String", "fieldName", ",", "Map", "<", "String", ",", "Object", ">", "arguments", ",", "boolean", "optional", ",", "ScalarType", "scalarType", ",", "List", "<", "Conditi...
Factory method for creating a Field instance representing a custom GraphQL Scalar type, {@link Type#CUSTOM} @param responseName alias for the result of a field @param fieldName name of the field in the GraphQL operation @param arguments arguments to be passed along with the field @param optional whether the arguments passed along are optional or required @param scalarType the custom scalar type of the field @param conditions list of conditions for this field @return Field instance representing {@link Type#CUSTOM}
[ "Factory", "method", "for", "creating", "a", "Field", "instance", "representing", "a", "custom", "GraphQL", "Scalar", "type", "{", "@link", "Type#CUSTOM", "}" ]
train
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-api/src/main/java/com/apollographql/apollo/api/ResponseField.java#L161-L164
anotheria/moskito
moskito-web/src/main/java/net/anotheria/moskito/web/filters/JSTalkBackFilter.java
JSTalkBackFilter.getProducer
@SuppressWarnings("unchecked") private OnDemandStatsProducer<PageInBrowserStats> getProducer(final String producerId, final String category, final String subsystem) { """ Returns producer by given producer id. If it was not found then new producer will be created. If existing producer is not supported then producer with default producer id will be returned. If producer with default producer id is not supported then will be returned {@code null}. @param producerId id of the producer @param category name of the category @param subsystem name of the subsystem @return PageInBrowserStats producer """ final IStatsProducer statsProducer = ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId); // create new if (statsProducer == null) return createProducer(producerId, category, subsystem); // use existing if (statsProducer instanceof OnDemandStatsProducer && OnDemandStatsProducer.class.cast(statsProducer).getDefaultStats() instanceof PageInBrowserStats) return (OnDemandStatsProducer<PageInBrowserStats>) statsProducer; final IStatsProducer defaultStatsProducer = ProducerRegistryFactory.getProducerRegistryInstance().getProducer(getDefaultProducerId()); // create default if (defaultStatsProducer == null) return createProducer(getDefaultProducerId(), category, subsystem); // use existing default if (statsProducer instanceof OnDemandStatsProducer && OnDemandStatsProducer.class.cast(statsProducer).getDefaultStats() instanceof PageInBrowserStats) return (OnDemandStatsProducer<PageInBrowserStats>) defaultStatsProducer; log.warn("Can't create OnDemandStatsProducer<BrowserStats> producer with passed id: [" + producerId + "] and default id: [" + getDefaultProducerId() + "]."); return null; }
java
@SuppressWarnings("unchecked") private OnDemandStatsProducer<PageInBrowserStats> getProducer(final String producerId, final String category, final String subsystem) { final IStatsProducer statsProducer = ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId); // create new if (statsProducer == null) return createProducer(producerId, category, subsystem); // use existing if (statsProducer instanceof OnDemandStatsProducer && OnDemandStatsProducer.class.cast(statsProducer).getDefaultStats() instanceof PageInBrowserStats) return (OnDemandStatsProducer<PageInBrowserStats>) statsProducer; final IStatsProducer defaultStatsProducer = ProducerRegistryFactory.getProducerRegistryInstance().getProducer(getDefaultProducerId()); // create default if (defaultStatsProducer == null) return createProducer(getDefaultProducerId(), category, subsystem); // use existing default if (statsProducer instanceof OnDemandStatsProducer && OnDemandStatsProducer.class.cast(statsProducer).getDefaultStats() instanceof PageInBrowserStats) return (OnDemandStatsProducer<PageInBrowserStats>) defaultStatsProducer; log.warn("Can't create OnDemandStatsProducer<BrowserStats> producer with passed id: [" + producerId + "] and default id: [" + getDefaultProducerId() + "]."); return null; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "OnDemandStatsProducer", "<", "PageInBrowserStats", ">", "getProducer", "(", "final", "String", "producerId", ",", "final", "String", "category", ",", "final", "String", "subsystem", ")", "{", "final", ...
Returns producer by given producer id. If it was not found then new producer will be created. If existing producer is not supported then producer with default producer id will be returned. If producer with default producer id is not supported then will be returned {@code null}. @param producerId id of the producer @param category name of the category @param subsystem name of the subsystem @return PageInBrowserStats producer
[ "Returns", "producer", "by", "given", "producer", "id", ".", "If", "it", "was", "not", "found", "then", "new", "producer", "will", "be", "created", ".", "If", "existing", "producer", "is", "not", "supported", "then", "producer", "with", "default", "producer"...
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-web/src/main/java/net/anotheria/moskito/web/filters/JSTalkBackFilter.java#L165-L186
voldemort/voldemort
src/java/voldemort/store/readonly/ReadOnlyUtils.java
ReadOnlyUtils.getCurrentVersion
public static File getCurrentVersion(File storeDirectory) { """ Retrieve the dir pointed to by 'latest' symbolic-link or the current version dir @return Current version directory, else null """ File latestDir = getLatestDir(storeDirectory); if(latestDir != null) return latestDir; File[] versionDirs = getVersionDirs(storeDirectory); if(versionDirs == null || versionDirs.length == 0) { return null; } else { return findKthVersionedDir(versionDirs, versionDirs.length - 1, versionDirs.length - 1)[0]; } }
java
public static File getCurrentVersion(File storeDirectory) { File latestDir = getLatestDir(storeDirectory); if(latestDir != null) return latestDir; File[] versionDirs = getVersionDirs(storeDirectory); if(versionDirs == null || versionDirs.length == 0) { return null; } else { return findKthVersionedDir(versionDirs, versionDirs.length - 1, versionDirs.length - 1)[0]; } }
[ "public", "static", "File", "getCurrentVersion", "(", "File", "storeDirectory", ")", "{", "File", "latestDir", "=", "getLatestDir", "(", "storeDirectory", ")", ";", "if", "(", "latestDir", "!=", "null", ")", "return", "latestDir", ";", "File", "[", "]", "ver...
Retrieve the dir pointed to by 'latest' symbolic-link or the current version dir @return Current version directory, else null
[ "Retrieve", "the", "dir", "pointed", "to", "by", "latest", "symbolic", "-", "link", "or", "the", "current", "version", "dir" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/ReadOnlyUtils.java#L120-L131
xmlunit/xmlunit
xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java
DefaultComparisonFormatter.appendXPath
protected void appendXPath(StringBuilder sb, String xpath) { """ Appends the XPath information for {@link #getShortString} if present. @param sb the builder to append to @param xpath the xpath to append, if any @since XMLUnit 2.4.0 """ if (xpath != null && xpath.length() > 0) { sb.append(" at ").append(xpath); } }
java
protected void appendXPath(StringBuilder sb, String xpath) { if (xpath != null && xpath.length() > 0) { sb.append(" at ").append(xpath); } }
[ "protected", "void", "appendXPath", "(", "StringBuilder", "sb", ",", "String", "xpath", ")", "{", "if", "(", "xpath", "!=", "null", "&&", "xpath", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "\" at \"", ")", ".", "append", ...
Appends the XPath information for {@link #getShortString} if present. @param sb the builder to append to @param xpath the xpath to append, if any @since XMLUnit 2.4.0
[ "Appends", "the", "XPath", "information", "for", "{", "@link", "#getShortString", "}", "if", "present", "." ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java#L161-L165
igniterealtime/REST-API-Client
src/main/java/org/igniterealtime/restclient/RestApiClient.java
RestApiClient.deleteOutcast
public Response deleteOutcast(String roomName, String jid) { """ Delete outcast from chatroom. @param roomName the room name @param jid the jid @return the response """ return restClient.delete("chatrooms/" + roomName + "/outcasts/" + jid, new HashMap<String, String>()); }
java
public Response deleteOutcast(String roomName, String jid) { return restClient.delete("chatrooms/" + roomName + "/outcasts/" + jid, new HashMap<String, String>()); }
[ "public", "Response", "deleteOutcast", "(", "String", "roomName", ",", "String", "jid", ")", "{", "return", "restClient", ".", "delete", "(", "\"chatrooms/\"", "+", "roomName", "+", "\"/outcasts/\"", "+", "jid", ",", "new", "HashMap", "<", "String", ",", "St...
Delete outcast from chatroom. @param roomName the room name @param jid the jid @return the response
[ "Delete", "outcast", "from", "chatroom", "." ]
train
https://github.com/igniterealtime/REST-API-Client/blob/fd544dd770ec2ababa47fef51579522ddce09f05/src/main/java/org/igniterealtime/restclient/RestApiClient.java#L342-L345