repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
DDTH/ddth-redis | src/main/java/com/github/ddth/redis/RedisClientFactory.java | RedisClientFactory.getRedisClient | public IRedisClient getRedisClient(String host, int port, String username, String password) {
return getRedisClient(host, port, username, password, null);
} | java | public IRedisClient getRedisClient(String host, int port, String username, String password) {
return getRedisClient(host, port, username, password, null);
} | [
"public",
"IRedisClient",
"getRedisClient",
"(",
"String",
"host",
",",
"int",
"port",
",",
"String",
"username",
",",
"String",
"password",
")",
"{",
"return",
"getRedisClient",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"null",
")",
... | Gets or Creates a {@link IRedisClient} object.
@param host
@param port
@param username
@param password
@return | [
"Gets",
"or",
"Creates",
"a",
"{",
"@link",
"IRedisClient",
"}",
"object",
"."
] | train | https://github.com/DDTH/ddth-redis/blob/7e6abc3e43c9efe7e9c293d421c94227253ded87/src/main/java/com/github/ddth/redis/RedisClientFactory.java#L175-L177 |
twitter/cloudhopper-commons | ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteBuffer.java | ByteBuffer.modularExponentation | private int modularExponentation(int a, int b, int n) throws IllegalArgumentException {
int result = 1;
int counter;
int maxBinarySize = 32;
boolean[] b2Binary = new boolean[maxBinarySize];
for (counter = 0; b > 0; counter++) {
if (counter >= maxBinarySize){
throw new IllegalArgumentException("Exponent "+b+" is too big !");
}
b2Binary[counter] = (b % 2 != 0);
b = b / 2;
}
for (int k = counter - 1; k >= 0; k--) {
result = (result * result) % n;
if (b2Binary[k]){
result = (result * a) % n;
}
}
return result;
} | java | private int modularExponentation(int a, int b, int n) throws IllegalArgumentException {
int result = 1;
int counter;
int maxBinarySize = 32;
boolean[] b2Binary = new boolean[maxBinarySize];
for (counter = 0; b > 0; counter++) {
if (counter >= maxBinarySize){
throw new IllegalArgumentException("Exponent "+b+" is too big !");
}
b2Binary[counter] = (b % 2 != 0);
b = b / 2;
}
for (int k = counter - 1; k >= 0; k--) {
result = (result * result) % n;
if (b2Binary[k]){
result = (result * a) % n;
}
}
return result;
} | [
"private",
"int",
"modularExponentation",
"(",
"int",
"a",
",",
"int",
"b",
",",
"int",
"n",
")",
"throws",
"IllegalArgumentException",
"{",
"int",
"result",
"=",
"1",
";",
"int",
"counter",
";",
"int",
"maxBinarySize",
"=",
"32",
";",
"boolean",
"[",
"]... | Gets the modular exponentiation, i.e. result of a^b mod n. Use to calculate hashcode.
@param a A number.
@param b An exponent.
@param n A modulus.
@return Result of modular exponentiation, i.e. result of a^b mod n. | [
"Gets",
"the",
"modular",
"exponentiation",
"i",
".",
"e",
".",
"result",
"of",
"a^b",
"mod",
"n",
".",
"Use",
"to",
"calculate",
"hashcode",
"."
] | train | https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteBuffer.java#L270-L289 |
calimero-project/calimero-core | src/tuwien/auto/calimero/DataUnitBuilder.java | DataUnitBuilder.toHex | public static String toHex(final byte[] data, final String sep)
{
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; ++i) {
final int no = data[i] & 0xff;
if (no < 0x10)
sb.append('0');
sb.append(Integer.toHexString(no));
if (sep != null && i < data.length - 1)
sb.append(sep);
}
return sb.toString();
} | java | public static String toHex(final byte[] data, final String sep)
{
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; ++i) {
final int no = data[i] & 0xff;
if (no < 0x10)
sb.append('0');
sb.append(Integer.toHexString(no));
if (sep != null && i < data.length - 1)
sb.append(sep);
}
return sb.toString();
} | [
"public",
"static",
"String",
"toHex",
"(",
"final",
"byte",
"[",
"]",
"data",
",",
"final",
"String",
"sep",
")",
"{",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"da... | Returns the content of <code>data</code> as unsigned bytes in hexadecimal string
representation.
<p>
This method does not add hexadecimal prefixes (like 0x).
@param data data array to format
@param sep separator to insert between 2 formatted data bytes, <code>null</code>
or "" for no gap between byte tokens
@return an unsigned hexadecimal string of data | [
"Returns",
"the",
"content",
"of",
"<code",
">",
"data<",
"/",
"code",
">",
"as",
"unsigned",
"bytes",
"in",
"hexadecimal",
"string",
"representation",
".",
"<p",
">",
"This",
"method",
"does",
"not",
"add",
"hexadecimal",
"prefixes",
"(",
"like",
"0x",
")... | train | https://github.com/calimero-project/calimero-core/blob/7e6f547c6bd75fa985bfeb5b47ba671df2ea01e8/src/tuwien/auto/calimero/DataUnitBuilder.java#L455-L467 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java | MappeableRunContainer.mergeValuesLength | private void mergeValuesLength(int begin, int end) {
if (begin < end) {
int bValue = toIntUnsigned(getValue(begin));
int eValue = toIntUnsigned(getValue(end));
int eLength = toIntUnsigned(getLength(end));
int newLength = eValue - bValue + eLength;
setLength(begin, (short) newLength);
recoverRoomsInRange(begin, end);
}
} | java | private void mergeValuesLength(int begin, int end) {
if (begin < end) {
int bValue = toIntUnsigned(getValue(begin));
int eValue = toIntUnsigned(getValue(end));
int eLength = toIntUnsigned(getLength(end));
int newLength = eValue - bValue + eLength;
setLength(begin, (short) newLength);
recoverRoomsInRange(begin, end);
}
} | [
"private",
"void",
"mergeValuesLength",
"(",
"int",
"begin",
",",
"int",
"end",
")",
"{",
"if",
"(",
"begin",
"<",
"end",
")",
"{",
"int",
"bValue",
"=",
"toIntUnsigned",
"(",
"getValue",
"(",
"begin",
")",
")",
";",
"int",
"eValue",
"=",
"toIntUnsigne... | To merge values length from begin(inclusive) to end(inclusive) | [
"To",
"merge",
"values",
"length",
"from",
"begin",
"(",
"inclusive",
")",
"to",
"end",
"(",
"inclusive",
")"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableRunContainer.java#L1804-L1813 |
liferay/com-liferay-commerce | commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListItemPersistenceImpl.java | CommerceWishListItemPersistenceImpl.findByCommerceWishListId | @Override
public List<CommerceWishListItem> findByCommerceWishListId(
long commerceWishListId, int start, int end) {
return findByCommerceWishListId(commerceWishListId, start, end, null);
} | java | @Override
public List<CommerceWishListItem> findByCommerceWishListId(
long commerceWishListId, int start, int end) {
return findByCommerceWishListId(commerceWishListId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceWishListItem",
">",
"findByCommerceWishListId",
"(",
"long",
"commerceWishListId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByCommerceWishListId",
"(",
"commerceWishListId",
",",
"start",
",",
... | Returns a range of all the commerce wish list items where commerceWishListId = ?.
<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 CommerceWishListItemModelImpl}. 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 commerceWishListId the commerce wish list ID
@param start the lower bound of the range of commerce wish list items
@param end the upper bound of the range of commerce wish list items (not inclusive)
@return the range of matching commerce wish list items | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"wish",
"list",
"items",
"where",
"commerceWishListId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListItemPersistenceImpl.java#L144-L148 |
classgraph/classgraph | src/main/java/io/github/classgraph/Scanner.java | Scanner.maskClassfiles | private void maskClassfiles(final List<ClasspathElement> classpathElementOrder, final LogNode maskLog) {
final Set<String> whitelistedClasspathRelativePathsFound = new HashSet<>();
for (int classpathIdx = 0; classpathIdx < classpathElementOrder.size(); classpathIdx++) {
final ClasspathElement classpathElement = classpathElementOrder.get(classpathIdx);
classpathElement.maskClassfiles(classpathIdx, whitelistedClasspathRelativePathsFound, maskLog);
}
if (maskLog != null) {
maskLog.addElapsedTime();
}
} | java | private void maskClassfiles(final List<ClasspathElement> classpathElementOrder, final LogNode maskLog) {
final Set<String> whitelistedClasspathRelativePathsFound = new HashSet<>();
for (int classpathIdx = 0; classpathIdx < classpathElementOrder.size(); classpathIdx++) {
final ClasspathElement classpathElement = classpathElementOrder.get(classpathIdx);
classpathElement.maskClassfiles(classpathIdx, whitelistedClasspathRelativePathsFound, maskLog);
}
if (maskLog != null) {
maskLog.addElapsedTime();
}
} | [
"private",
"void",
"maskClassfiles",
"(",
"final",
"List",
"<",
"ClasspathElement",
">",
"classpathElementOrder",
",",
"final",
"LogNode",
"maskLog",
")",
"{",
"final",
"Set",
"<",
"String",
">",
"whitelistedClasspathRelativePathsFound",
"=",
"new",
"HashSet",
"<>",... | Perform classpath masking of classfiles. If the same relative classfile path occurs multiple times in the
classpath, causes the second and subsequent occurrences to be ignored (removed).
@param classpathElementOrder
the classpath element order
@param maskLog
the mask log | [
"Perform",
"classpath",
"masking",
"of",
"classfiles",
".",
"If",
"the",
"same",
"relative",
"classfile",
"path",
"occurs",
"multiple",
"times",
"in",
"the",
"classpath",
"causes",
"the",
"second",
"and",
"subsequent",
"occurrences",
"to",
"be",
"ignored",
"(",
... | train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/Scanner.java#L759-L768 |
YahooArchive/samoa | samoa-samza/src/main/java/com/yahoo/labs/samoa/utils/SamzaConfigFactory.java | SamzaConfigFactory.getMapForEntrancePI | public Map<String,String> getMapForEntrancePI(SamzaEntranceProcessingItem epi, String filename, String filesystem) {
Map<String,String> map = getBasicSystemConfig();
// Set job name, task class (from SamzaEntranceProcessingItem)
setJobName(map, epi.getName());
setTaskClass(map, SamzaEntranceProcessingItem.class.getName());
// Input for the entrance task (from our custom consumer)
setTaskInputs(map, SYSTEM_NAME+"."+epi.getName());
// Output from entrance task
// Since entrancePI should have only 1 output stream
// there is no need for checking the batch size, setting different system names
// The custom consumer (samoa system) does not suuport reading from a specific index
// => no need for checkpointing
SamzaStream outputStream = (SamzaStream)epi.getOutputStream();
// Set samoa system factory
setValue(map, "systems."+SYSTEM_NAME+".samza.factory", SamoaSystemFactory.class.getName());
// Set Kafka system (only if there is an output stream)
if (outputStream != null)
setKafkaSystem(map, outputStream.getSystemName(), this.zookeeper, this.kafkaBrokerList, outputStream.getBatchSize());
// Processor file
setFileName(map, filename);
setFileSystem(map, filesystem);
// Number of containers
setNumberOfContainers(map, 1, this.piPerContainerRatio);
return map;
} | java | public Map<String,String> getMapForEntrancePI(SamzaEntranceProcessingItem epi, String filename, String filesystem) {
Map<String,String> map = getBasicSystemConfig();
// Set job name, task class (from SamzaEntranceProcessingItem)
setJobName(map, epi.getName());
setTaskClass(map, SamzaEntranceProcessingItem.class.getName());
// Input for the entrance task (from our custom consumer)
setTaskInputs(map, SYSTEM_NAME+"."+epi.getName());
// Output from entrance task
// Since entrancePI should have only 1 output stream
// there is no need for checking the batch size, setting different system names
// The custom consumer (samoa system) does not suuport reading from a specific index
// => no need for checkpointing
SamzaStream outputStream = (SamzaStream)epi.getOutputStream();
// Set samoa system factory
setValue(map, "systems."+SYSTEM_NAME+".samza.factory", SamoaSystemFactory.class.getName());
// Set Kafka system (only if there is an output stream)
if (outputStream != null)
setKafkaSystem(map, outputStream.getSystemName(), this.zookeeper, this.kafkaBrokerList, outputStream.getBatchSize());
// Processor file
setFileName(map, filename);
setFileSystem(map, filesystem);
// Number of containers
setNumberOfContainers(map, 1, this.piPerContainerRatio);
return map;
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"getMapForEntrancePI",
"(",
"SamzaEntranceProcessingItem",
"epi",
",",
"String",
"filename",
",",
"String",
"filesystem",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"getBasicSystemConfig",
... | /*
Generate a map of all config properties for the input SamzaProcessingItem | [
"/",
"*",
"Generate",
"a",
"map",
"of",
"all",
"config",
"properties",
"for",
"the",
"input",
"SamzaProcessingItem"
] | train | https://github.com/YahooArchive/samoa/blob/540a2c30167ac85c432b593baabd5ca97e7e8a0f/samoa-samza/src/main/java/com/yahoo/labs/samoa/utils/SamzaConfigFactory.java#L252-L282 |
h2oai/h2o-3 | h2o-core/src/main/java/hex/schemas/HyperSpaceSearchCriteriaV99.java | HyperSpaceSearchCriteriaV99.fillWithDefaults | public S fillWithDefaults() {
HyperSpaceSearchCriteria defaults = null;
if (HyperSpaceSearchCriteria.Strategy.Cartesian == strategy) {
defaults = new HyperSpaceSearchCriteria.CartesianSearchCriteria();
} else if (HyperSpaceSearchCriteria.Strategy.RandomDiscrete == strategy) {
defaults = new HyperSpaceSearchCriteria.RandomDiscreteValueSearchCriteria();
} else {
throw new H2OIllegalArgumentException("search_criteria.strategy", strategy.toString());
}
fillFromImpl((I)defaults);
return (S) this;
} | java | public S fillWithDefaults() {
HyperSpaceSearchCriteria defaults = null;
if (HyperSpaceSearchCriteria.Strategy.Cartesian == strategy) {
defaults = new HyperSpaceSearchCriteria.CartesianSearchCriteria();
} else if (HyperSpaceSearchCriteria.Strategy.RandomDiscrete == strategy) {
defaults = new HyperSpaceSearchCriteria.RandomDiscreteValueSearchCriteria();
} else {
throw new H2OIllegalArgumentException("search_criteria.strategy", strategy.toString());
}
fillFromImpl((I)defaults);
return (S) this;
} | [
"public",
"S",
"fillWithDefaults",
"(",
")",
"{",
"HyperSpaceSearchCriteria",
"defaults",
"=",
"null",
";",
"if",
"(",
"HyperSpaceSearchCriteria",
".",
"Strategy",
".",
"Cartesian",
"==",
"strategy",
")",
"{",
"defaults",
"=",
"new",
"HyperSpaceSearchCriteria",
".... | Fill with the default values from the corresponding Iced object. | [
"Fill",
"with",
"the",
"default",
"values",
"from",
"the",
"corresponding",
"Iced",
"object",
"."
] | train | https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/hex/schemas/HyperSpaceSearchCriteriaV99.java#L76-L90 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/DeployKeysApi.java | DeployKeysApi.addDeployKey | public DeployKey addDeployKey(Object projectIdOrPath, String title, String key, Boolean canPush) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title, true)
.withParam("key", key, true)
.withParam("can_push", canPush);
Response response = post(Response.Status.CREATED, formData,
"projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys");
return (response.readEntity(DeployKey.class));
} | java | public DeployKey addDeployKey(Object projectIdOrPath, String title, String key, Boolean canPush) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title, true)
.withParam("key", key, true)
.withParam("can_push", canPush);
Response response = post(Response.Status.CREATED, formData,
"projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys");
return (response.readEntity(DeployKey.class));
} | [
"public",
"DeployKey",
"addDeployKey",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"title",
",",
"String",
"key",
",",
"Boolean",
"canPush",
")",
"throws",
"GitLabApiException",
"{",
"GitLabApiForm",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"... | Creates a new deploy key for a project.
<pre><code>GitLab Endpoint: POST /projects/:id/deploy_keys</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param title the new deploy key's title, required
@param key the new deploy key, required
@param canPush can deploy key push to the project's repository, optional
@return an DeployKey instance with info on the added deploy key
@throws GitLabApiException if any exception occurs | [
"Creates",
"a",
"new",
"deploy",
"key",
"for",
"a",
"project",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/DeployKeysApi.java#L184-L193 |
square/wire | wire-schema/src/main/java/com/squareup/wire/schema/Options.java | Options.union | @SuppressWarnings("unchecked")
private Object union(Linker linker, Object a, Object b) {
if (a instanceof List) {
return union((List<?>) a, (List<?>) b);
} else if (a instanceof Map) {
return union(linker, (Map<ProtoMember, Object>) a, (Map<ProtoMember, Object>) b);
} else {
linker.addError("conflicting options: %s, %s", a, b);
return a; // Just return any placeholder.
}
} | java | @SuppressWarnings("unchecked")
private Object union(Linker linker, Object a, Object b) {
if (a instanceof List) {
return union((List<?>) a, (List<?>) b);
} else if (a instanceof Map) {
return union(linker, (Map<ProtoMember, Object>) a, (Map<ProtoMember, Object>) b);
} else {
linker.addError("conflicting options: %s, %s", a, b);
return a; // Just return any placeholder.
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"Object",
"union",
"(",
"Linker",
"linker",
",",
"Object",
"a",
",",
"Object",
"b",
")",
"{",
"if",
"(",
"a",
"instanceof",
"List",
")",
"{",
"return",
"union",
"(",
"(",
"List",
"<",
"?",
... | Combine values for the same key, resolving conflicts based on their type. | [
"Combine",
"values",
"for",
"the",
"same",
"key",
"resolving",
"conflicts",
"based",
"on",
"their",
"type",
"."
] | train | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/Options.java#L238-L248 |
facebook/fresco | imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java | PlatformBitmapFactory.createBitmap | public CloseableReference<Bitmap> createBitmap(Bitmap source, @Nullable Object callerContext) {
return createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), callerContext);
} | java | public CloseableReference<Bitmap> createBitmap(Bitmap source, @Nullable Object callerContext) {
return createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), callerContext);
} | [
"public",
"CloseableReference",
"<",
"Bitmap",
">",
"createBitmap",
"(",
"Bitmap",
"source",
",",
"@",
"Nullable",
"Object",
"callerContext",
")",
"{",
"return",
"createBitmap",
"(",
"source",
",",
"0",
",",
"0",
",",
"source",
".",
"getWidth",
"(",
")",
"... | Creates a bitmap from the specified source bitmap.
It is initialized with the same density as the original bitmap.
@param source The bitmap we are copying
@param callerContext the Tag to track who create the Bitmap
@return a reference to the bitmap
@throws IllegalArgumentException if the x, y, width, height values are
outside of the dimensions of the source bitmap, or width is <= 0,
or height is <= 0
@throws TooManyBitmapsException if the pool is full
@throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated | [
"Creates",
"a",
"bitmap",
"from",
"the",
"specified",
"source",
"bitmap",
".",
"It",
"is",
"initialized",
"with",
"the",
"same",
"density",
"as",
"the",
"original",
"bitmap",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java#L124-L126 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.cartServiceOption_domain_GET | public ArrayList<String> cartServiceOption_domain_GET(String whoisOwner) throws IOException {
String qPath = "/order/cartServiceOption/domain";
StringBuilder sb = path(qPath);
query(sb, "whoisOwner", whoisOwner);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | java | public ArrayList<String> cartServiceOption_domain_GET(String whoisOwner) throws IOException {
String qPath = "/order/cartServiceOption/domain";
StringBuilder sb = path(qPath);
query(sb, "whoisOwner", whoisOwner);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | [
"public",
"ArrayList",
"<",
"String",
">",
"cartServiceOption_domain_GET",
"(",
"String",
"whoisOwner",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/cartServiceOption/domain\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
")",
";",... | List available services
REST: GET /order/cartServiceOption/domain
@param whoisOwner Filter the value of whoisOwner property (=) | [
"List",
"available",
"services"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L247-L253 |
btrplace/scheduler | json/src/main/java/org/btrplace/json/model/view/network/StaticRoutingConverter.java | StaticRoutingConverter.nodesMapFromJSON | public StaticRouting.NodesMap nodesMapFromJSON(Model mo, JSONObject o) throws JSONConverterException {
return new StaticRouting.NodesMap(requiredNode(mo, o, "src"), requiredNode(mo, o, "dst"));
} | java | public StaticRouting.NodesMap nodesMapFromJSON(Model mo, JSONObject o) throws JSONConverterException {
return new StaticRouting.NodesMap(requiredNode(mo, o, "src"), requiredNode(mo, o, "dst"));
} | [
"public",
"StaticRouting",
".",
"NodesMap",
"nodesMapFromJSON",
"(",
"Model",
"mo",
",",
"JSONObject",
"o",
")",
"throws",
"JSONConverterException",
"{",
"return",
"new",
"StaticRouting",
".",
"NodesMap",
"(",
"requiredNode",
"(",
"mo",
",",
"o",
",",
"\"src\"",... | Convert a JSON nodes map object into a Java NodesMap object
@param o the JSON object to convert
@return the nodes map | [
"Convert",
"a",
"JSON",
"nodes",
"map",
"object",
"into",
"a",
"Java",
"NodesMap",
"object"
] | train | https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/model/view/network/StaticRoutingConverter.java#L90-L92 |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/MemoryEntityLockStore.java | MemoryEntityLockStore.primAdd | private void primAdd(IEntityLock lock, Date expiration) throws LockingException {
long now = System.currentTimeMillis();
long willExpire = expiration.getTime();
long cacheIntervalSecs = (willExpire - now) / 1000;
if (cacheIntervalSecs > 0) {
SmartCache sc = (SmartCache) getLockCache(lock.getEntityType());
synchronized (sc) {
sc.put(getCacheKey(lock), lock, (cacheIntervalSecs));
}
}
// Else the lock has already expired.
} | java | private void primAdd(IEntityLock lock, Date expiration) throws LockingException {
long now = System.currentTimeMillis();
long willExpire = expiration.getTime();
long cacheIntervalSecs = (willExpire - now) / 1000;
if (cacheIntervalSecs > 0) {
SmartCache sc = (SmartCache) getLockCache(lock.getEntityType());
synchronized (sc) {
sc.put(getCacheKey(lock), lock, (cacheIntervalSecs));
}
}
// Else the lock has already expired.
} | [
"private",
"void",
"primAdd",
"(",
"IEntityLock",
"lock",
",",
"Date",
"expiration",
")",
"throws",
"LockingException",
"{",
"long",
"now",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"willExpire",
"=",
"expiration",
".",
"getTime",
"(",
... | Adds this IEntityLock to the store.
@param lock
@param expiration | [
"Adds",
"this",
"IEntityLock",
"to",
"the",
"store",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/MemoryEntityLockStore.java#L272-L285 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/model/Recording.java | Recording.get | public static Recording get(final BandwidthClient client, final String id) throws Exception {
final String recordingsUri = client.getUserResourceUri(BandwidthConstants.RECORDINGS_URI_PATH);
final String uri = StringUtils.join(new String[]{
recordingsUri,
id
}, '/');
final JSONObject jsonObject = toJSONObject(client.get(uri, null));
return new Recording(client, recordingsUri, jsonObject);
} | java | public static Recording get(final BandwidthClient client, final String id) throws Exception {
final String recordingsUri = client.getUserResourceUri(BandwidthConstants.RECORDINGS_URI_PATH);
final String uri = StringUtils.join(new String[]{
recordingsUri,
id
}, '/');
final JSONObject jsonObject = toJSONObject(client.get(uri, null));
return new Recording(client, recordingsUri, jsonObject);
} | [
"public",
"static",
"Recording",
"get",
"(",
"final",
"BandwidthClient",
"client",
",",
"final",
"String",
"id",
")",
"throws",
"Exception",
"{",
"final",
"String",
"recordingsUri",
"=",
"client",
".",
"getUserResourceUri",
"(",
"BandwidthConstants",
".",
"RECORDI... | Recording factory method. Returns recording object from id
@param client the client
@param id the recording id
@return the recording
@throws IOException unexpected error | [
"Recording",
"factory",
"method",
".",
"Returns",
"recording",
"object",
"from",
"id"
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/Recording.java#L80-L89 |
looly/hutool | hutool-http/src/main/java/cn/hutool/http/HttpUtil.java | HttpUtil.urlWithForm | public static String urlWithForm(String url, Map<String, Object> form, Charset charset, boolean isEncodeParams) {
if (isEncodeParams && StrUtil.contains(url, '?')) {
// 在需要编码的情况下,如果url中已经有部分参数,则编码之
url = encodeParams(url, charset);
}
// url和参数是分别编码的
return urlWithForm(url, toParams(form, charset), charset, false);
} | java | public static String urlWithForm(String url, Map<String, Object> form, Charset charset, boolean isEncodeParams) {
if (isEncodeParams && StrUtil.contains(url, '?')) {
// 在需要编码的情况下,如果url中已经有部分参数,则编码之
url = encodeParams(url, charset);
}
// url和参数是分别编码的
return urlWithForm(url, toParams(form, charset), charset, false);
} | [
"public",
"static",
"String",
"urlWithForm",
"(",
"String",
"url",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"form",
",",
"Charset",
"charset",
",",
"boolean",
"isEncodeParams",
")",
"{",
"if",
"(",
"isEncodeParams",
"&&",
"StrUtil",
".",
"contains",
... | 将表单数据加到URL中(用于GET表单提交)<br>
表单的键值对会被url编码,但是url中原参数不会被编码
@param url URL
@param form 表单数据
@param charset 编码
@param isEncodeParams 是否对键和值做转义处理
@return 合成后的URL | [
"将表单数据加到URL中(用于GET表单提交)<br",
">",
"表单的键值对会被url编码,但是url中原参数不会被编码"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/HttpUtil.java#L604-L612 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/collections/CollectionUtils.java | CollectionUtils.TableCellValue | public static <V> Function<Table.Cell<?, ?, V>, V> TableCellValue() {
return new Function<Table.Cell<?, ?, V>, V>() {
@Override
public V apply(Table.Cell<?, ?, V> input) {
return input.getValue();
}
};
} | java | public static <V> Function<Table.Cell<?, ?, V>, V> TableCellValue() {
return new Function<Table.Cell<?, ?, V>, V>() {
@Override
public V apply(Table.Cell<?, ?, V> input) {
return input.getValue();
}
};
} | [
"public",
"static",
"<",
"V",
">",
"Function",
"<",
"Table",
".",
"Cell",
"<",
"?",
",",
"?",
",",
"V",
">",
",",
"V",
">",
"TableCellValue",
"(",
")",
"{",
"return",
"new",
"Function",
"<",
"Table",
".",
"Cell",
"<",
"?",
",",
"?",
",",
"V",
... | Guava function to get the value of a {@link com.google.common.collect.Table} cell. | [
"Guava",
"function",
"to",
"get",
"the",
"value",
"of",
"a",
"{"
] | train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/collections/CollectionUtils.java#L152-L159 |
Azure/azure-sdk-for-java | recoveryservices.backup/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_06_01/implementation/ProtectionContainersInner.java | ProtectionContainersInner.getAsync | public Observable<ProtectionContainerResourceInner> getAsync(String vaultName, String resourceGroupName, String fabricName, String containerName) {
return getWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName).map(new Func1<ServiceResponse<ProtectionContainerResourceInner>, ProtectionContainerResourceInner>() {
@Override
public ProtectionContainerResourceInner call(ServiceResponse<ProtectionContainerResourceInner> response) {
return response.body();
}
});
} | java | public Observable<ProtectionContainerResourceInner> getAsync(String vaultName, String resourceGroupName, String fabricName, String containerName) {
return getWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName).map(new Func1<ServiceResponse<ProtectionContainerResourceInner>, ProtectionContainerResourceInner>() {
@Override
public ProtectionContainerResourceInner call(ServiceResponse<ProtectionContainerResourceInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ProtectionContainerResourceInner",
">",
"getAsync",
"(",
"String",
"vaultName",
",",
"String",
"resourceGroupName",
",",
"String",
"fabricName",
",",
"String",
"containerName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"vaultN... | Gets details of the specific container registered to your Recovery Services vault.
@param vaultName The name of the Recovery Services vault.
@param resourceGroupName The name of the resource group associated with the Recovery Services vault.
@param fabricName The fabric name associated with the container.
@param containerName The container name used for this GET operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ProtectionContainerResourceInner object | [
"Gets",
"details",
"of",
"the",
"specific",
"container",
"registered",
"to",
"your",
"Recovery",
"Services",
"vault",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_06_01/implementation/ProtectionContainersInner.java#L116-L123 |
Nordstrom/JUnit-Foundation | src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java | LifecycleHooks.getDeclaredField | static Field getDeclaredField(Object target, String name) throws NoSuchFieldException {
Throwable thrown = null;
for (Class<?> current = target.getClass(); current != null; current = current.getSuperclass()) {
try {
return current.getDeclaredField(name);
} catch (NoSuchFieldException e) {
thrown = e;
} catch (SecurityException e) {
thrown = e;
break;
}
}
throw UncheckedThrow.throwUnchecked(thrown);
} | java | static Field getDeclaredField(Object target, String name) throws NoSuchFieldException {
Throwable thrown = null;
for (Class<?> current = target.getClass(); current != null; current = current.getSuperclass()) {
try {
return current.getDeclaredField(name);
} catch (NoSuchFieldException e) {
thrown = e;
} catch (SecurityException e) {
thrown = e;
break;
}
}
throw UncheckedThrow.throwUnchecked(thrown);
} | [
"static",
"Field",
"getDeclaredField",
"(",
"Object",
"target",
",",
"String",
"name",
")",
"throws",
"NoSuchFieldException",
"{",
"Throwable",
"thrown",
"=",
"null",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"current",
"=",
"target",
".",
"getClass",
"(",
... | Get the specified field of the supplied object.
@param target target object
@param name field name
@return {@link Field} object for the requested field
@throws NoSuchFieldException if a field with the specified name is not found
@throws SecurityException if the request is denied | [
"Get",
"the",
"specified",
"field",
"of",
"the",
"supplied",
"object",
"."
] | train | https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L293-L307 |
alkacon/opencms-core | src/org/opencms/flex/CmsFlexCacheEntry.java | CmsFlexCacheEntry.setVariationData | public void setVariationData(String theVariationKey, Map<String, I_CmsLruCacheObject> theVariationMap) {
m_variationKey = theVariationKey;
m_variationMap = theVariationMap;
} | java | public void setVariationData(String theVariationKey, Map<String, I_CmsLruCacheObject> theVariationMap) {
m_variationKey = theVariationKey;
m_variationMap = theVariationMap;
} | [
"public",
"void",
"setVariationData",
"(",
"String",
"theVariationKey",
",",
"Map",
"<",
"String",
",",
"I_CmsLruCacheObject",
">",
"theVariationMap",
")",
"{",
"m_variationKey",
"=",
"theVariationKey",
";",
"m_variationMap",
"=",
"theVariationMap",
";",
"}"
] | Stores a backward reference to the map and key where this cache entry is stored.<p>
This is required for the FlexCache.<p>
@param theVariationKey the variation key
@param theVariationMap the variation map | [
"Stores",
"a",
"backward",
"reference",
"to",
"the",
"map",
"and",
"key",
"where",
"this",
"cache",
"entry",
"is",
"stored",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/flex/CmsFlexCacheEntry.java#L553-L557 |
apache/spark | common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java | ExternalShuffleBlockResolver.getFile | @VisibleForTesting
static File getFile(String[] localDirs, int subDirsPerLocalDir, String filename) {
int hash = JavaUtils.nonNegativeHash(filename);
String localDir = localDirs[hash % localDirs.length];
int subDirId = (hash / localDirs.length) % subDirsPerLocalDir;
return new File(createNormalizedInternedPathname(
localDir, String.format("%02x", subDirId), filename));
} | java | @VisibleForTesting
static File getFile(String[] localDirs, int subDirsPerLocalDir, String filename) {
int hash = JavaUtils.nonNegativeHash(filename);
String localDir = localDirs[hash % localDirs.length];
int subDirId = (hash / localDirs.length) % subDirsPerLocalDir;
return new File(createNormalizedInternedPathname(
localDir, String.format("%02x", subDirId), filename));
} | [
"@",
"VisibleForTesting",
"static",
"File",
"getFile",
"(",
"String",
"[",
"]",
"localDirs",
",",
"int",
"subDirsPerLocalDir",
",",
"String",
"filename",
")",
"{",
"int",
"hash",
"=",
"JavaUtils",
".",
"nonNegativeHash",
"(",
"filename",
")",
";",
"String",
... | Hashes a filename into the corresponding local directory, in a manner consistent with
Spark's DiskBlockManager.getFile(). | [
"Hashes",
"a",
"filename",
"into",
"the",
"corresponding",
"local",
"directory",
"in",
"a",
"manner",
"consistent",
"with",
"Spark",
"s",
"DiskBlockManager",
".",
"getFile",
"()",
"."
] | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java#L305-L312 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/Request.java | Request.toHttpConnection | public static HttpURLConnection toHttpConnection(RequestBatch requests) {
URL url = null;
try {
if (requests.size() == 1) {
// Single request case.
Request request = requests.get(0);
// In the non-batch case, the URL we use really is the same one returned by getUrlForSingleRequest.
url = new URL(request.getUrlForSingleRequest());
} else {
// Batch case -- URL is just the graph API base, individual request URLs are serialized
// as relative_url parameters within each batch entry.
url = new URL(ServerProtocol.getGraphUrlBase());
}
} catch (MalformedURLException e) {
throw new FacebookException("could not construct URL for request", e);
}
HttpURLConnection connection;
try {
connection = createConnection(url);
serializeToUrlConnection(requests, connection);
} catch (IOException e) {
throw new FacebookException("could not construct request body", e);
} catch (JSONException e) {
throw new FacebookException("could not construct request body", e);
}
return connection;
} | java | public static HttpURLConnection toHttpConnection(RequestBatch requests) {
URL url = null;
try {
if (requests.size() == 1) {
// Single request case.
Request request = requests.get(0);
// In the non-batch case, the URL we use really is the same one returned by getUrlForSingleRequest.
url = new URL(request.getUrlForSingleRequest());
} else {
// Batch case -- URL is just the graph API base, individual request URLs are serialized
// as relative_url parameters within each batch entry.
url = new URL(ServerProtocol.getGraphUrlBase());
}
} catch (MalformedURLException e) {
throw new FacebookException("could not construct URL for request", e);
}
HttpURLConnection connection;
try {
connection = createConnection(url);
serializeToUrlConnection(requests, connection);
} catch (IOException e) {
throw new FacebookException("could not construct request body", e);
} catch (JSONException e) {
throw new FacebookException("could not construct request body", e);
}
return connection;
} | [
"public",
"static",
"HttpURLConnection",
"toHttpConnection",
"(",
"RequestBatch",
"requests",
")",
"{",
"URL",
"url",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"requests",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"// Single request case.",
"Request",
"requ... | Serializes one or more requests but does not execute them. The resulting HttpURLConnection can be executed
explicitly by the caller.
@param requests
a RequestBatch to serialize
@return an HttpURLConnection which is ready to execute
@throws FacebookException
If any of the requests in the batch are badly constructed or if there are problems
contacting the service
@throws IllegalArgumentException | [
"Serializes",
"one",
"or",
"more",
"requests",
"but",
"does",
"not",
"execute",
"them",
".",
"The",
"resulting",
"HttpURLConnection",
"can",
"be",
"executed",
"explicitly",
"by",
"the",
"caller",
"."
] | train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L1329-L1359 |
JakeWharton/ActionBarSherlock | actionbarsherlock/src/com/actionbarsherlock/widget/SearchView.java | SearchView.createVoiceAppSearchIntent | private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) {
ComponentName searchActivity = searchable.getSearchActivity();
// create the necessary intent to set up a search-and-forward operation
// in the voice search system. We have to keep the bundle separate,
// because it becomes immutable once it enters the PendingIntent
Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
queryIntent.setComponent(searchActivity);
PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent,
PendingIntent.FLAG_ONE_SHOT);
// Now set up the bundle that will be inserted into the pending intent
// when it's time to do the search. We always build it here (even if empty)
// because the voice search activity will always need to insert "QUERY" into
// it anyway.
Bundle queryExtras = new Bundle();
// Now build the intent to launch the voice search. Add all necessary
// extras to launch the voice recognizer, and then all the necessary extras
// to forward the results to the searchable activity
Intent voiceIntent = new Intent(baseIntent);
// Add all of the configuration options supplied by the searchable's metadata
String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
String prompt = null;
String language = null;
int maxResults = 1;
Resources resources = getResources();
if (searchable.getVoiceLanguageModeId() != 0) {
languageModel = resources.getString(searchable.getVoiceLanguageModeId());
}
if (searchable.getVoicePromptTextId() != 0) {
prompt = resources.getString(searchable.getVoicePromptTextId());
}
if (searchable.getVoiceLanguageId() != 0) {
language = resources.getString(searchable.getVoiceLanguageId());
}
if (searchable.getVoiceMaxResults() != 0) {
maxResults = searchable.getVoiceMaxResults();
}
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
: searchActivity.flattenToShortString());
// Add the values that configure forwarding the results
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
return voiceIntent;
} | java | private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) {
ComponentName searchActivity = searchable.getSearchActivity();
// create the necessary intent to set up a search-and-forward operation
// in the voice search system. We have to keep the bundle separate,
// because it becomes immutable once it enters the PendingIntent
Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
queryIntent.setComponent(searchActivity);
PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent,
PendingIntent.FLAG_ONE_SHOT);
// Now set up the bundle that will be inserted into the pending intent
// when it's time to do the search. We always build it here (even if empty)
// because the voice search activity will always need to insert "QUERY" into
// it anyway.
Bundle queryExtras = new Bundle();
// Now build the intent to launch the voice search. Add all necessary
// extras to launch the voice recognizer, and then all the necessary extras
// to forward the results to the searchable activity
Intent voiceIntent = new Intent(baseIntent);
// Add all of the configuration options supplied by the searchable's metadata
String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
String prompt = null;
String language = null;
int maxResults = 1;
Resources resources = getResources();
if (searchable.getVoiceLanguageModeId() != 0) {
languageModel = resources.getString(searchable.getVoiceLanguageModeId());
}
if (searchable.getVoicePromptTextId() != 0) {
prompt = resources.getString(searchable.getVoicePromptTextId());
}
if (searchable.getVoiceLanguageId() != 0) {
language = resources.getString(searchable.getVoiceLanguageId());
}
if (searchable.getVoiceMaxResults() != 0) {
maxResults = searchable.getVoiceMaxResults();
}
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
: searchActivity.flattenToShortString());
// Add the values that configure forwarding the results
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
return voiceIntent;
} | [
"private",
"Intent",
"createVoiceAppSearchIntent",
"(",
"Intent",
"baseIntent",
",",
"SearchableInfo",
"searchable",
")",
"{",
"ComponentName",
"searchActivity",
"=",
"searchable",
".",
"getSearchActivity",
"(",
")",
";",
"// create the necessary intent to set up a search-and... | Create and return an Intent that can launch the voice search activity, perform a specific
voice transcription, and forward the results to the searchable activity.
@param baseIntent The voice app search intent to start from
@return A completely-configured intent ready to send to the voice search activity | [
"Create",
"and",
"return",
"an",
"Intent",
"that",
"can",
"launch",
"the",
"voice",
"search",
"activity",
"perform",
"a",
"specific",
"voice",
"transcription",
"and",
"forward",
"the",
"results",
"to",
"the",
"searchable",
"activity",
"."
] | train | https://github.com/JakeWharton/ActionBarSherlock/blob/2c71339e756bcc0b1424c4525680549ba3a2dc97/actionbarsherlock/src/com/actionbarsherlock/widget/SearchView.java#L1513-L1566 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-japanese/src/main/java/com/atilika/kuromoji/viterbi/ViterbiBuilder.java | ViterbiBuilder.createGlueNode | private ViterbiNode createGlueNode(int startIndex, ViterbiNode glueBase, String surface) {
return new ViterbiNode(glueBase.getWordId(), surface, glueBase.getLeftId(), glueBase.getRightId(),
glueBase.getWordCost(), startIndex, ViterbiNode.Type.INSERTED);
} | java | private ViterbiNode createGlueNode(int startIndex, ViterbiNode glueBase, String surface) {
return new ViterbiNode(glueBase.getWordId(), surface, glueBase.getLeftId(), glueBase.getRightId(),
glueBase.getWordCost(), startIndex, ViterbiNode.Type.INSERTED);
} | [
"private",
"ViterbiNode",
"createGlueNode",
"(",
"int",
"startIndex",
",",
"ViterbiNode",
"glueBase",
",",
"String",
"surface",
")",
"{",
"return",
"new",
"ViterbiNode",
"(",
"glueBase",
".",
"getWordId",
"(",
")",
",",
"surface",
",",
"glueBase",
".",
"getLef... | Create a glue node to be inserted based on ViterbiNode already in the lattice.
The new node takes the same parameters as the node it is based on, but the word is truncated to match the
hole in the lattice caused by the new user entry
@param startIndex
@param glueBase
@param surface
@return new ViterbiNode to be inserted as glue into the lattice | [
"Create",
"a",
"glue",
"node",
"to",
"be",
"inserted",
"based",
"on",
"ViterbiNode",
"already",
"in",
"the",
"lattice",
".",
"The",
"new",
"node",
"takes",
"the",
"same",
"parameters",
"as",
"the",
"node",
"it",
"is",
"based",
"on",
"but",
"the",
"word",... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-japanese/src/main/java/com/atilika/kuromoji/viterbi/ViterbiBuilder.java#L334-L337 |
cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.abortService | private void abortService(String message, Throwable error) {
if (isRunning()) {
LOG.error("Aborting transaction manager due to: " + message, error);
notifyFailed(error);
}
} | java | private void abortService(String message, Throwable error) {
if (isRunning()) {
LOG.error("Aborting transaction manager due to: " + message, error);
notifyFailed(error);
}
} | [
"private",
"void",
"abortService",
"(",
"String",
"message",
",",
"Throwable",
"error",
")",
"{",
"if",
"(",
"isRunning",
"(",
")",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Aborting transaction manager due to: \"",
"+",
"message",
",",
"error",
")",
";",
"noti... | Immediately shuts down the service, without going through the normal close process.
@param message A message describing the source of the failure.
@param error Any exception that caused the failure. | [
"Immediately",
"shuts",
"down",
"the",
"service",
"without",
"going",
"through",
"the",
"normal",
"close",
"process",
"."
] | train | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L699-L704 |
icode/ameba | src/main/java/ameba/feature/datasource/StatViewFeature.java | StatViewFeature.getJmxResult | private static String getJmxResult(MBeanServerConnection connetion, String url) throws Exception {
ObjectName name = new ObjectName(DruidStatService.MBEAN_NAME);
return (String) conn.invoke(name, "service", new String[]{url},
new String[]{String.class.getName()});
} | java | private static String getJmxResult(MBeanServerConnection connetion, String url) throws Exception {
ObjectName name = new ObjectName(DruidStatService.MBEAN_NAME);
return (String) conn.invoke(name, "service", new String[]{url},
new String[]{String.class.getName()});
} | [
"private",
"static",
"String",
"getJmxResult",
"(",
"MBeanServerConnection",
"connetion",
",",
"String",
"url",
")",
"throws",
"Exception",
"{",
"ObjectName",
"name",
"=",
"new",
"ObjectName",
"(",
"DruidStatService",
".",
"MBEAN_NAME",
")",
";",
"return",
"(",
... | 根据指定的url来获取jmx服务返回的内容.
@param connetion jmx连接
@param url url内容
@return the jmx返回的内容
@throws Exception the exception | [
"根据指定的url来获取jmx服务返回的内容",
"."
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/feature/datasource/StatViewFeature.java#L178-L183 |
OpenLiberty/open-liberty | dev/com.ibm.ws.injection.core/src/com/ibm/ws/injectionengine/InjectionProcessorManager.java | InjectionProcessorManager.getAllDeclaredFields | private Field[] getAllDeclaredFields(Class<?> klass, Class<?> classHierarchy)
{
try
{
return klass.getDeclaredFields();
} catch (Throwable ex)
{
// The most common 'problem' here is a NoClassDefFoundError because
// a dependency class (super/field type, etc) could not be found
// when the class is fully initialized.
// Since interrogating a class for annotations is new in Java EE 1.5,
// it is possible this application may have worked in prior versions
// of WebSphere, if the application never actually used the class.
// So, rather than just fail the app start, a Warning will be logged
// indicating the class will not be processed for annotations, and
// the application will be allowed to start. d477931
FFDCFilter.processException(ex, CLASS_NAME + ".getAllDeclaredFields",
"249", new Object[] { classHierarchy, klass });
if (classHierarchy != klass)
{
Tr.warning(tc, "SUPER_FIELD_ANNOTATIONS_IGNORED_CWNEN0048W",
klass.getName(), classHierarchy.getName(), ex.toString()); // d479669 RTC119889
if (ivInjectionEngine.isValidationFailable(ivNameSpaceConfig.isCheckApplicationConfiguration())) // F743-14449
{
throw new RuntimeException("Resource annotations on the fields of the " + klass.getName() +
" class could not be processed. The " + klass.getName() +
" class is being processed for annotations because it is" +
" referenced by the " + classHierarchy.getName() + " application class." +
" The annotations could not be obtained because of the exception : " +
ex, ex);
}
}
else
{
Tr.warning(tc, "FIELD_ANNOTATIONS_IGNORED_CWNEN0047W",
klass.getName(), ex.toString()); // d479669 d641396 RTC119889
if (ivInjectionEngine.isValidationFailable(ivNameSpaceConfig.isCheckApplicationConfiguration())) // F743-14449
{
throw new RuntimeException("Resource annotations on the fields of the " + klass.getName() +
" class could not be processed. The annotations could not be obtained" +
" because of the exception : " + ex, ex);
}
}
return null;
}
} | java | private Field[] getAllDeclaredFields(Class<?> klass, Class<?> classHierarchy)
{
try
{
return klass.getDeclaredFields();
} catch (Throwable ex)
{
// The most common 'problem' here is a NoClassDefFoundError because
// a dependency class (super/field type, etc) could not be found
// when the class is fully initialized.
// Since interrogating a class for annotations is new in Java EE 1.5,
// it is possible this application may have worked in prior versions
// of WebSphere, if the application never actually used the class.
// So, rather than just fail the app start, a Warning will be logged
// indicating the class will not be processed for annotations, and
// the application will be allowed to start. d477931
FFDCFilter.processException(ex, CLASS_NAME + ".getAllDeclaredFields",
"249", new Object[] { classHierarchy, klass });
if (classHierarchy != klass)
{
Tr.warning(tc, "SUPER_FIELD_ANNOTATIONS_IGNORED_CWNEN0048W",
klass.getName(), classHierarchy.getName(), ex.toString()); // d479669 RTC119889
if (ivInjectionEngine.isValidationFailable(ivNameSpaceConfig.isCheckApplicationConfiguration())) // F743-14449
{
throw new RuntimeException("Resource annotations on the fields of the " + klass.getName() +
" class could not be processed. The " + klass.getName() +
" class is being processed for annotations because it is" +
" referenced by the " + classHierarchy.getName() + " application class." +
" The annotations could not be obtained because of the exception : " +
ex, ex);
}
}
else
{
Tr.warning(tc, "FIELD_ANNOTATIONS_IGNORED_CWNEN0047W",
klass.getName(), ex.toString()); // d479669 d641396 RTC119889
if (ivInjectionEngine.isValidationFailable(ivNameSpaceConfig.isCheckApplicationConfiguration())) // F743-14449
{
throw new RuntimeException("Resource annotations on the fields of the " + klass.getName() +
" class could not be processed. The annotations could not be obtained" +
" because of the exception : " + ex, ex);
}
}
return null;
}
} | [
"private",
"Field",
"[",
"]",
"getAllDeclaredFields",
"(",
"Class",
"<",
"?",
">",
"klass",
",",
"Class",
"<",
"?",
">",
"classHierarchy",
")",
"{",
"try",
"{",
"return",
"klass",
".",
"getDeclaredFields",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
... | Return the declared fields for the specified class in the class hierarchy.
@param klass the specified class to get declared fields
@param classHierarchy the entire class hierarchy
@return the declared fields, or null if an exception occurs | [
"Return",
"the",
"declared",
"fields",
"for",
"the",
"specified",
"class",
"in",
"the",
"class",
"hierarchy",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.injection.core/src/com/ibm/ws/injectionengine/InjectionProcessorManager.java#L370-L419 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java | VirtualNetworkGatewaysInner.beginGetAdvertisedRoutesAsync | public Observable<GatewayRouteListResultInner> beginGetAdvertisedRoutesAsync(String resourceGroupName, String virtualNetworkGatewayName, String peer) {
return beginGetAdvertisedRoutesWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, peer).map(new Func1<ServiceResponse<GatewayRouteListResultInner>, GatewayRouteListResultInner>() {
@Override
public GatewayRouteListResultInner call(ServiceResponse<GatewayRouteListResultInner> response) {
return response.body();
}
});
} | java | public Observable<GatewayRouteListResultInner> beginGetAdvertisedRoutesAsync(String resourceGroupName, String virtualNetworkGatewayName, String peer) {
return beginGetAdvertisedRoutesWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, peer).map(new Func1<ServiceResponse<GatewayRouteListResultInner>, GatewayRouteListResultInner>() {
@Override
public GatewayRouteListResultInner call(ServiceResponse<GatewayRouteListResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"GatewayRouteListResultInner",
">",
"beginGetAdvertisedRoutesAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkGatewayName",
",",
"String",
"peer",
")",
"{",
"return",
"beginGetAdvertisedRoutesWithServiceResponseAsync",
"(",
... | This operation retrieves a list of routes the virtual network gateway is advertising to the specified peer.
@param resourceGroupName The name of the resource group.
@param virtualNetworkGatewayName The name of the virtual network gateway.
@param peer The IP address of the peer
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the GatewayRouteListResultInner object | [
"This",
"operation",
"retrieves",
"a",
"list",
"of",
"routes",
"the",
"virtual",
"network",
"gateway",
"is",
"advertising",
"to",
"the",
"specified",
"peer",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L2594-L2601 |
lucee/Lucee | core/src/main/java/lucee/runtime/schedule/StorageUtil.java | StorageUtil.setString | public void setString(Element el, String key, String value) {
if (value != null) el.setAttribute(key, value);
} | java | public void setString(Element el, String key, String value) {
if (value != null) el.setAttribute(key, value);
} | [
"public",
"void",
"setString",
"(",
"Element",
"el",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"el",
".",
"setAttribute",
"(",
"key",
",",
"value",
")",
";",
"}"
] | sets a string value to a XML Element
@param el Element to set value on it
@param key key to set
@param value value to set | [
"sets",
"a",
"string",
"value",
"to",
"a",
"XML",
"Element"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/StorageUtil.java#L357-L359 |
apache/incubator-druid | server/src/main/java/org/apache/druid/guice/SQLMetadataStorageDruidModule.java | SQLMetadataStorageDruidModule.createBindingChoices | public void createBindingChoices(Binder binder, String defaultValue)
{
String prop = PROPERTY;
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataStorageConnector.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataStorageProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(SQLMetadataConnector.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSegmentManager.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSegmentManagerProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataRuleManager.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataRuleManagerProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSegmentPublisher.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSegmentPublisherProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(IndexerMetadataStorageCoordinator.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataStorageActionHandlerFactory.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataStorageUpdaterJobHandler.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(AuditManager.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(AuditManagerProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSupervisorManager.class), defaultValue);
} | java | public void createBindingChoices(Binder binder, String defaultValue)
{
String prop = PROPERTY;
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataStorageConnector.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataStorageProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(SQLMetadataConnector.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSegmentManager.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSegmentManagerProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataRuleManager.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataRuleManagerProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSegmentPublisher.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSegmentPublisherProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(IndexerMetadataStorageCoordinator.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataStorageActionHandlerFactory.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataStorageUpdaterJobHandler.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(AuditManager.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(AuditManagerProvider.class), defaultValue);
PolyBind.createChoiceWithDefault(binder, prop, Key.get(MetadataSupervisorManager.class), defaultValue);
} | [
"public",
"void",
"createBindingChoices",
"(",
"Binder",
"binder",
",",
"String",
"defaultValue",
")",
"{",
"String",
"prop",
"=",
"PROPERTY",
";",
"PolyBind",
".",
"createChoiceWithDefault",
"(",
"binder",
",",
"prop",
",",
"Key",
".",
"get",
"(",
"MetadataSt... | This function only needs to be called by the default SQL metadata storage module
Other modules should default to calling super.configure(...) alone
@param defaultValue default property value | [
"This",
"function",
"only",
"needs",
"to",
"be",
"called",
"by",
"the",
"default",
"SQL",
"metadata",
"storage",
"module",
"Other",
"modules",
"should",
"default",
"to",
"calling",
"super",
".",
"configure",
"(",
"...",
")",
"alone"
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/guice/SQLMetadataStorageDruidModule.java#L69-L88 |
twilio/twilio-java | src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberReader.java | PhoneNumberReader.nextPage | @Override
public Page<PhoneNumber> nextPage(final Page<PhoneNumber> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(
Domains.TRUNKING.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | java | @Override
public Page<PhoneNumber> nextPage(final Page<PhoneNumber> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(
Domains.TRUNKING.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | [
"@",
"Override",
"public",
"Page",
"<",
"PhoneNumber",
">",
"nextPage",
"(",
"final",
"Page",
"<",
"PhoneNumber",
">",
"page",
",",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET",
... | Retrieve the next page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Next Page | [
"Retrieve",
"the",
"next",
"page",
"from",
"the",
"Twilio",
"API",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberReader.java#L91-L102 |
google/identity-toolkit-java-client | src/main/java/com/google/identitytoolkit/GitkitClient.java | GitkitClient.uploadUsers | public void uploadUsers(String hashAlgorithm, byte[] hashKey, List<GitkitUser> users)
throws GitkitServerException, GitkitClientException {
uploadUsers(hashAlgorithm, hashKey, users, null, null, null);
} | java | public void uploadUsers(String hashAlgorithm, byte[] hashKey, List<GitkitUser> users)
throws GitkitServerException, GitkitClientException {
uploadUsers(hashAlgorithm, hashKey, users, null, null, null);
} | [
"public",
"void",
"uploadUsers",
"(",
"String",
"hashAlgorithm",
",",
"byte",
"[",
"]",
"hashKey",
",",
"List",
"<",
"GitkitUser",
">",
"users",
")",
"throws",
"GitkitServerException",
",",
"GitkitClientException",
"{",
"uploadUsers",
"(",
"hashAlgorithm",
",",
... | Uploads multiple user accounts to Gitkit server.
@param hashAlgorithm hash algorithm. Supported values are HMAC_SHA256, HMAC_SHA1, HMAC_MD5,
PBKDF_SHA1, MD5 and SCRYPT.
@param hashKey key of hash algorithm
@param users list of user accounts to be uploaded
@throws GitkitClientException for invalid request
@throws GitkitServerException for server error | [
"Uploads",
"multiple",
"user",
"accounts",
"to",
"Gitkit",
"server",
"."
] | train | https://github.com/google/identity-toolkit-java-client/blob/61dda1aabbd541ad5e431e840fd266bfca5f8a4a/src/main/java/com/google/identitytoolkit/GitkitClient.java#L389-L392 |
tango-controls/JTango | server/src/main/java/org/tango/server/events/EventManager.java | EventManager.pushAttributeValueEvent | public void pushAttributeValueEvent(final String deviceName, final String attributeName) throws DevFailed {
xlogger.entry();
for (final EventType eventType : EventType.getEventAttrValueTypeList()) {
pushAttributeValueEventIdlLoop(deviceName, attributeName, eventType);
}
xlogger.exit();
} | java | public void pushAttributeValueEvent(final String deviceName, final String attributeName) throws DevFailed {
xlogger.entry();
for (final EventType eventType : EventType.getEventAttrValueTypeList()) {
pushAttributeValueEventIdlLoop(deviceName, attributeName, eventType);
}
xlogger.exit();
} | [
"public",
"void",
"pushAttributeValueEvent",
"(",
"final",
"String",
"deviceName",
",",
"final",
"String",
"attributeName",
")",
"throws",
"DevFailed",
"{",
"xlogger",
".",
"entry",
"(",
")",
";",
"for",
"(",
"final",
"EventType",
"eventType",
":",
"EventType",
... | Check if the event must be sent and fire it if must be done
@param attributeName specified event attribute
@throws DevFailed | [
"Check",
"if",
"the",
"event",
"must",
"be",
"sent",
"and",
"fire",
"it",
"if",
"must",
"be",
"done"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/events/EventManager.java#L499-L505 |
statefulj/statefulj | statefulj-persistence/statefulj-persistence-mongo/src/main/java/org/statefulj/persistence/mongo/MongoPersister.java | MongoPersister.setCurrent | @Override
public void setCurrent(T stateful, State<T> current, State<T> next) throws StaleStateException {
try {
// Has this Entity been persisted to Mongo?
//
StateDocumentImpl stateDoc = this.getStateDocument(stateful);
if (stateDoc != null && stateDoc.isPersisted()) {
// Update state in the DB
//
updateStateInDB(stateful, current, next, stateDoc);
} else {
// The Entity hasn't been persisted to Mongo - so it exists only
// this Application memory. So, serialize the qualified update to prevent
// concurrency conflicts
//
updateInMemory(stateful, stateDoc, current.getName(), next.getName());
}
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | java | @Override
public void setCurrent(T stateful, State<T> current, State<T> next) throws StaleStateException {
try {
// Has this Entity been persisted to Mongo?
//
StateDocumentImpl stateDoc = this.getStateDocument(stateful);
if (stateDoc != null && stateDoc.isPersisted()) {
// Update state in the DB
//
updateStateInDB(stateful, current, next, stateDoc);
} else {
// The Entity hasn't been persisted to Mongo - so it exists only
// this Application memory. So, serialize the qualified update to prevent
// concurrency conflicts
//
updateInMemory(stateful, stateDoc, current.getName(), next.getName());
}
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | [
"@",
"Override",
"public",
"void",
"setCurrent",
"(",
"T",
"stateful",
",",
"State",
"<",
"T",
">",
"current",
",",
"State",
"<",
"T",
">",
"next",
")",
"throws",
"StaleStateException",
"{",
"try",
"{",
"// Has this Entity been persisted to Mongo?",
"//",
"Sta... | Set the current State. This method will ensure that the state in the db matches the expected current state.
If not, it will throw a StateStateException
@param stateful Stateful Entity
@param current Expected current State
@param next The value of the next State
@throws StaleStateException thrown if the value of the State does not equal to the provided current State | [
"Set",
"the",
"current",
"State",
".",
"This",
"method",
"will",
"ensure",
"that",
"the",
"state",
"in",
"the",
"db",
"matches",
"the",
"expected",
"current",
"state",
".",
"If",
"not",
"it",
"will",
"throw",
"a",
"StateStateException"
] | train | https://github.com/statefulj/statefulj/blob/d3459b3cb12bd508643027743401484a231e5fa1/statefulj-persistence/statefulj-persistence-mongo/src/main/java/org/statefulj/persistence/mongo/MongoPersister.java#L163-L192 |
alkacon/opencms-core | src/org/opencms/db/CmsSubscriptionManager.java | CmsSubscriptionManager.unsubscribeAllDeletedResources | public void unsubscribeAllDeletedResources(CmsObject cms, long deletedTo) throws CmsException {
if (!isEnabled()) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0));
}
m_securityManager.unsubscribeAllDeletedResources(cms.getRequestContext(), getPoolName(), deletedTo);
} | java | public void unsubscribeAllDeletedResources(CmsObject cms, long deletedTo) throws CmsException {
if (!isEnabled()) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0));
}
m_securityManager.unsubscribeAllDeletedResources(cms.getRequestContext(), getPoolName(), deletedTo);
} | [
"public",
"void",
"unsubscribeAllDeletedResources",
"(",
"CmsObject",
"cms",
",",
"long",
"deletedTo",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"!",
"isEnabled",
"(",
")",
")",
"{",
"throw",
"new",
"CmsRuntimeException",
"(",
"Messages",
".",
"get",
"(",... | Unsubscribes all deleted resources that were deleted before the specified time stamp.<p>
@param cms the current users context
@param deletedTo the time stamp to which the resources have been deleted
@throws CmsException if something goes wrong | [
"Unsubscribes",
"all",
"deleted",
"resources",
"that",
"were",
"deleted",
"before",
"the",
"specified",
"time",
"stamp",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSubscriptionManager.java#L410-L416 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/HistoryDTO.java | HistoryDTO.transformToDto | public static HistoryDTO transformToDto(History history) {
if (history == null) {
throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
}
HistoryDTO historyDto = new HistoryDTO();
try {
BeanUtils.copyProperties(historyDto, history);
} catch (Exception ex) {
throw new WebApplicationException("DTO transformation failed.", Status.INTERNAL_SERVER_ERROR);
}
return historyDto;
} | java | public static HistoryDTO transformToDto(History history) {
if (history == null) {
throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
}
HistoryDTO historyDto = new HistoryDTO();
try {
BeanUtils.copyProperties(historyDto, history);
} catch (Exception ex) {
throw new WebApplicationException("DTO transformation failed.", Status.INTERNAL_SERVER_ERROR);
}
return historyDto;
} | [
"public",
"static",
"HistoryDTO",
"transformToDto",
"(",
"History",
"history",
")",
"{",
"if",
"(",
"history",
"==",
"null",
")",
"{",
"throw",
"new",
"WebApplicationException",
"(",
"\"Null entity object cannot be converted to Dto object.\"",
",",
"Status",
".",
"INT... | Converts a history object to DTO.
@param history The history object.
@return The history DTO.
@throws WebApplicationException If an error occurs. | [
"Converts",
"a",
"history",
"object",
"to",
"DTO",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/HistoryDTO.java#L77-L90 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.putAt | public static <K,V> V putAt(Map<K,V> self, K key, V value) {
self.put(key, value);
return value;
} | java | public static <K,V> V putAt(Map<K,V> self, K key, V value) {
self.put(key, value);
return value;
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"V",
"putAt",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"self",
",",
"K",
"key",
",",
"V",
"value",
")",
"{",
"self",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"value",
";",
"}"
] | A helper method to allow maps to work with subscript operators
@param self a Map
@param key an Object as a key for the map
@param value the value to put into the map
@return the value corresponding to the given key
@since 1.0 | [
"A",
"helper",
"method",
"to",
"allow",
"maps",
"to",
"work",
"with",
"subscript",
"operators"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L8206-L8209 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getDeletedCertificate | public DeletedCertificateBundle getDeletedCertificate(String vaultBaseUrl, String certificateName) {
return getDeletedCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body();
} | java | public DeletedCertificateBundle getDeletedCertificate(String vaultBaseUrl, String certificateName) {
return getDeletedCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body();
} | [
"public",
"DeletedCertificateBundle",
"getDeletedCertificate",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"certificateName",
")",
"{",
"return",
"getDeletedCertificateWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"certificateName",
")",
".",
"toBlocking",
"(",
")"... | Retrieves information about the specified deleted certificate.
The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires the certificates/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate
@throws IllegalArgumentException thrown if parameters fail the validation
@throws KeyVaultErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DeletedCertificateBundle object if successful. | [
"Retrieves",
"information",
"about",
"the",
"specified",
"deleted",
"certificate",
".",
"The",
"GetDeletedCertificate",
"operation",
"retrieves",
"the",
"deleted",
"certificate",
"information",
"plus",
"its",
"attributes",
"such",
"as",
"retention",
"interval",
"schedul... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L8534-L8536 |
NoraUi/NoraUi | src/main/java/com/github/noraui/data/db/DBDataProvider.java | DBDataProvider.readValue | @Override
public String readValue(String column, int line) throws TechnicalException {
logger.debug("readValue: column:[{}] and line:[{}] ", column, line);
String sqlRequest;
try {
final Path file = Paths.get(dataInPath + scenarioName + ".sql");
sqlRequest = new String(Files.readAllBytes(file), Charset.forName(Constants.DEFAULT_ENDODING));
sqlSanitized4readOnly(sqlRequest);
} catch (final IOException e) {
throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE) + e.getMessage(), e);
}
try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(sqlRequest); ResultSet rs = statement.executeQuery();) {
if (line < 1) {
return column;
}
while (rs.next() && rs.getRow() < line) {
}
logger.info("column: {}", column);
return rs.getString(column);
} catch (final SQLException e) {
logger.error("error DBDataProvider.readValue({}, {})", column, line, e);
return "";
}
} | java | @Override
public String readValue(String column, int line) throws TechnicalException {
logger.debug("readValue: column:[{}] and line:[{}] ", column, line);
String sqlRequest;
try {
final Path file = Paths.get(dataInPath + scenarioName + ".sql");
sqlRequest = new String(Files.readAllBytes(file), Charset.forName(Constants.DEFAULT_ENDODING));
sqlSanitized4readOnly(sqlRequest);
} catch (final IOException e) {
throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE) + e.getMessage(), e);
}
try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(sqlRequest); ResultSet rs = statement.executeQuery();) {
if (line < 1) {
return column;
}
while (rs.next() && rs.getRow() < line) {
}
logger.info("column: {}", column);
return rs.getString(column);
} catch (final SQLException e) {
logger.error("error DBDataProvider.readValue({}, {})", column, line, e);
return "";
}
} | [
"@",
"Override",
"public",
"String",
"readValue",
"(",
"String",
"column",
",",
"int",
"line",
")",
"throws",
"TechnicalException",
"{",
"logger",
".",
"debug",
"(",
"\"readValue: column:[{}] and line:[{}] \"",
",",
"column",
",",
"line",
")",
";",
"String",
"sq... | {@inheritDoc}
@throws TechnicalException
is thrown if you have a technical error (IOException on .sql file) in NoraUi. | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/data/db/DBDataProvider.java#L122-L145 |
VoltDB/voltdb | src/frontend/org/voltdb/ElasticHashinator.java | ElasticHashinator.getConfigureBytes | public static byte[] getConfigureBytes(int partitionCount, int tokenCount) {
Preconditions.checkArgument(partitionCount > 0);
Preconditions.checkArgument(tokenCount > partitionCount);
Buckets buckets = new Buckets(partitionCount, tokenCount);
ElasticHashinator hashinator = new ElasticHashinator(buckets.getTokens());
return hashinator.getConfigBytes();
} | java | public static byte[] getConfigureBytes(int partitionCount, int tokenCount) {
Preconditions.checkArgument(partitionCount > 0);
Preconditions.checkArgument(tokenCount > partitionCount);
Buckets buckets = new Buckets(partitionCount, tokenCount);
ElasticHashinator hashinator = new ElasticHashinator(buckets.getTokens());
return hashinator.getConfigBytes();
} | [
"public",
"static",
"byte",
"[",
"]",
"getConfigureBytes",
"(",
"int",
"partitionCount",
",",
"int",
"tokenCount",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"partitionCount",
">",
"0",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"tokenCount... | Convenience method for generating a deterministic token distribution for the ring based
on a given partition count and tokens per partition. Each partition will have N tokens
placed randomly on the ring. | [
"Convenience",
"method",
"for",
"generating",
"a",
"deterministic",
"token",
"distribution",
"for",
"the",
"ring",
"based",
"on",
"a",
"given",
"partition",
"count",
"and",
"tokens",
"per",
"partition",
".",
"Each",
"partition",
"will",
"have",
"N",
"tokens",
... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ElasticHashinator.java#L200-L206 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java | CommerceTierPriceEntryPersistenceImpl.removeByUuid_C | @Override
public void removeByUuid_C(String uuid, long companyId) {
for (CommerceTierPriceEntry commerceTierPriceEntry : findByUuid_C(
uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceTierPriceEntry);
}
} | java | @Override
public void removeByUuid_C(String uuid, long companyId) {
for (CommerceTierPriceEntry commerceTierPriceEntry : findByUuid_C(
uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceTierPriceEntry);
}
} | [
"@",
"Override",
"public",
"void",
"removeByUuid_C",
"(",
"String",
"uuid",
",",
"long",
"companyId",
")",
"{",
"for",
"(",
"CommerceTierPriceEntry",
"commerceTierPriceEntry",
":",
"findByUuid_C",
"(",
"uuid",
",",
"companyId",
",",
"QueryUtil",
".",
"ALL_POS",
... | Removes all the commerce tier price entries where uuid = ? and companyId = ? from the database.
@param uuid the uuid
@param companyId the company ID | [
"Removes",
"all",
"the",
"commerce",
"tier",
"price",
"entries",
"where",
"uuid",
"=",
"?",
";",
"and",
"companyId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java#L1416-L1422 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateTimePatternGenerator.java | DateTimePatternGenerator.replaceFieldTypes | public String replaceFieldTypes(String pattern, String skeleton, int options) {
synchronized (this) { // synchronized since a getter must be thread-safe
PatternWithMatcher patternNoMatcher = new PatternWithMatcher(pattern, null);
return adjustFieldTypes(patternNoMatcher, current.set(skeleton, fp, false), EnumSet.noneOf(DTPGflags.class), options);
}
} | java | public String replaceFieldTypes(String pattern, String skeleton, int options) {
synchronized (this) { // synchronized since a getter must be thread-safe
PatternWithMatcher patternNoMatcher = new PatternWithMatcher(pattern, null);
return adjustFieldTypes(patternNoMatcher, current.set(skeleton, fp, false), EnumSet.noneOf(DTPGflags.class), options);
}
} | [
"public",
"String",
"replaceFieldTypes",
"(",
"String",
"pattern",
",",
"String",
"skeleton",
",",
"int",
"options",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"// synchronized since a getter must be thread-safe",
"PatternWithMatcher",
"patternNoMatcher",
"=",
"ne... | Adjusts the field types (width and subtype) of a pattern to match what is
in a skeleton. That is, if you supply a pattern like "d-M H:m", and a
skeleton of "MMMMddhhmm", then the input pattern is adjusted to be
"dd-MMMM hh:mm". This is used internally to get the best match for the
input skeleton, but can also be used externally.
@param pattern input pattern
@param skeleton For the pattern to match to.
@param options MATCH_xxx options for forcing the length of specified fields in
the returned pattern to match those in the skeleton (when this would
not happen otherwise). For default behavior, use MATCH_NO_OPTIONS.
@return pattern adjusted to match the skeleton fields widths and subtypes. | [
"Adjusts",
"the",
"field",
"types",
"(",
"width",
"and",
"subtype",
")",
"of",
"a",
"pattern",
"to",
"match",
"what",
"is",
"in",
"a",
"skeleton",
".",
"That",
"is",
"if",
"you",
"supply",
"a",
"pattern",
"like",
"d",
"-",
"M",
"H",
":",
"m",
"and"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateTimePatternGenerator.java#L842-L847 |
spring-projects/spring-social-facebook | spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java | FqlResult.getFloat | public Float getFloat(String fieldName) {
try {
return hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null;
} catch (NumberFormatException e) {
throw new FqlException("Field '" + fieldName +"' is not a number.", e);
}
} | java | public Float getFloat(String fieldName) {
try {
return hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null;
} catch (NumberFormatException e) {
throw new FqlException("Field '" + fieldName +"' is not a number.", e);
}
} | [
"public",
"Float",
"getFloat",
"(",
"String",
"fieldName",
")",
"{",
"try",
"{",
"return",
"hasValue",
"(",
"fieldName",
")",
"?",
"Float",
".",
"valueOf",
"(",
"String",
".",
"valueOf",
"(",
"resultMap",
".",
"get",
"(",
"fieldName",
")",
")",
")",
":... | Returns the value of the identified field as a Float.
@param fieldName the name of the field
@return the value of the field as a Float
@throws FqlException if the field cannot be expressed as an Float | [
"Returns",
"the",
"value",
"of",
"the",
"identified",
"field",
"as",
"a",
"Float",
"."
] | train | https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L83-L89 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfContentByte.java | PdfContentByte.lineTo | public void lineTo(float x, float y) {
content.append(x).append(' ').append(y).append(" l").append_i(separator);
} | java | public void lineTo(float x, float y) {
content.append(x).append(' ').append(y).append(" l").append_i(separator);
} | [
"public",
"void",
"lineTo",
"(",
"float",
"x",
",",
"float",
"y",
")",
"{",
"content",
".",
"append",
"(",
"x",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"y",
")",
".",
"append",
"(",
"\" l\"",
")",
".",
"append_i",
"(",
"sepa... | Appends a straight line segment from the current point <I>(x, y)</I>. The new current
point is <I>(x, y)</I>.
@param x new x-coordinate
@param y new y-coordinate | [
"Appends",
"a",
"straight",
"line",
"segment",
"from",
"the",
"current",
"point",
"<I",
">",
"(",
"x",
"y",
")",
"<",
"/",
"I",
">",
".",
"The",
"new",
"current",
"point",
"is",
"<I",
">",
"(",
"x",
"y",
")",
"<",
"/",
"I",
">",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L714-L716 |
sirthias/parboiled | parboiled-core/src/main/java/org/parboiled/support/Filters.java | Filters.onlyRules | public static Predicate<Tuple2<Context<?>, Boolean>> onlyRules(final Rule... rules) {
return new Predicate<Tuple2<Context<?>, Boolean>>() {
public boolean apply(Tuple2<Context<?>, Boolean> tuple) {
for (Rule rule : rules) if (tuple.a.getMatcher() == rule) return true;
return false;
}
};
} | java | public static Predicate<Tuple2<Context<?>, Boolean>> onlyRules(final Rule... rules) {
return new Predicate<Tuple2<Context<?>, Boolean>>() {
public boolean apply(Tuple2<Context<?>, Boolean> tuple) {
for (Rule rule : rules) if (tuple.a.getMatcher() == rule) return true;
return false;
}
};
} | [
"public",
"static",
"Predicate",
"<",
"Tuple2",
"<",
"Context",
"<",
"?",
">",
",",
"Boolean",
">",
">",
"onlyRules",
"(",
"final",
"Rule",
"...",
"rules",
")",
"{",
"return",
"new",
"Predicate",
"<",
"Tuple2",
"<",
"Context",
"<",
"?",
">",
",",
"Bo... | A predicate usable as a filter (element) of a {@link org.parboiled.parserunners.TracingParseRunner}.
Enables printing of rule tracing log messages for all given rules (without their sub rules).
@param rules the rules to generate tracing message for
@return a predicate | [
"A",
"predicate",
"usable",
"as",
"a",
"filter",
"(",
"element",
")",
"of",
"a",
"{",
"@link",
"org",
".",
"parboiled",
".",
"parserunners",
".",
"TracingParseRunner",
"}",
".",
"Enables",
"printing",
"of",
"rule",
"tracing",
"log",
"messages",
"for",
"all... | train | https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/support/Filters.java#L156-L163 |
twilio/twilio-java | src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberReader.java | PhoneNumberReader.previousPage | @Override
public Page<PhoneNumber> previousPage(final Page<PhoneNumber> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(
Domains.TRUNKING.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | java | @Override
public Page<PhoneNumber> previousPage(final Page<PhoneNumber> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(
Domains.TRUNKING.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | [
"@",
"Override",
"public",
"Page",
"<",
"PhoneNumber",
">",
"previousPage",
"(",
"final",
"Page",
"<",
"PhoneNumber",
">",
"page",
",",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET... | Retrieve the previous page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Previous Page | [
"Retrieve",
"the",
"previous",
"page",
"from",
"the",
"Twilio",
"API",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberReader.java#L111-L122 |
infinispan/infinispan | server/hotrod/src/main/java/org/infinispan/server/hotrod/transport/ExtendedByteBuf.java | ExtendedByteBuf.readMaybeVLong | public static Optional<Long> readMaybeVLong(ByteBuf bf) {
if (bf.readableBytes() >= 1) {
byte b = bf.readByte();
return read(bf, b, 7, (long) b & 0x7F, 1);
} else {
bf.resetReaderIndex();
return Optional.empty();
}
} | java | public static Optional<Long> readMaybeVLong(ByteBuf bf) {
if (bf.readableBytes() >= 1) {
byte b = bf.readByte();
return read(bf, b, 7, (long) b & 0x7F, 1);
} else {
bf.resetReaderIndex();
return Optional.empty();
}
} | [
"public",
"static",
"Optional",
"<",
"Long",
">",
"readMaybeVLong",
"(",
"ByteBuf",
"bf",
")",
"{",
"if",
"(",
"bf",
".",
"readableBytes",
"(",
")",
">=",
"1",
")",
"{",
"byte",
"b",
"=",
"bf",
".",
"readByte",
"(",
")",
";",
"return",
"read",
"(",... | Reads a variable long if possible. If not present the reader index is reset to the last mark.
@param bf
@return | [
"Reads",
"a",
"variable",
"long",
"if",
"possible",
".",
"If",
"not",
"present",
"the",
"reader",
"index",
"is",
"reset",
"to",
"the",
"last",
"mark",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/hotrod/src/main/java/org/infinispan/server/hotrod/transport/ExtendedByteBuf.java#L111-L120 |
steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/io/Convert.java | Convert.exportSymbols | private static void exportSymbols(SymbolTable syms, String filename) {
if (syms == null) {
return;
}
try (PrintWriter out = new PrintWriter(new FileWriter(filename))) {
for (ObjectIntCursor<String> sym : syms) {
out.println(sym.key + "\t" + sym.value);
}
} catch (IOException e) {
throw Throwables.propagate(e);
}
} | java | private static void exportSymbols(SymbolTable syms, String filename) {
if (syms == null) {
return;
}
try (PrintWriter out = new PrintWriter(new FileWriter(filename))) {
for (ObjectIntCursor<String> sym : syms) {
out.println(sym.key + "\t" + sym.value);
}
} catch (IOException e) {
throw Throwables.propagate(e);
}
} | [
"private",
"static",
"void",
"exportSymbols",
"(",
"SymbolTable",
"syms",
",",
"String",
"filename",
")",
"{",
"if",
"(",
"syms",
"==",
"null",
")",
"{",
"return",
";",
"}",
"try",
"(",
"PrintWriter",
"out",
"=",
"new",
"PrintWriter",
"(",
"new",
"FileWr... | Exports a symbols' map to the openfst text format
@param syms the symbols' map
@param filename the the openfst's symbols filename | [
"Exports",
"a",
"symbols",
"map",
"to",
"the",
"openfst",
"text",
"format"
] | train | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/io/Convert.java#L215-L227 |
datacleaner/AnalyzerBeans | core/src/main/java/org/eobjects/analyzer/result/AnnotatedRowsResult.java | AnnotatedRowsResult.toDistinctValuesTableModel | public TableModel toDistinctValuesTableModel(InputColumn<?> inputColumnOfInterest) {
final Map<Object, Integer> valueCounts;
final RowAnnotationFactory annotationFactory = _annotationFactoryRef.get();
if (annotationFactory == null) {
valueCounts = Collections.emptyMap();
} else {
valueCounts = annotationFactory.getValueCounts(getAnnotation(), inputColumnOfInterest);
}
DefaultTableModel tableModel = new DefaultTableModel(new String[] { inputColumnOfInterest.getName(),
"Count in dataset" }, valueCounts.size());
// sort the set
TreeSet<Entry<Object, Integer>> set = new TreeSet<Entry<Object, Integer>>(
new Comparator<Entry<Object, Integer>>() {
@Override
public int compare(Entry<Object, Integer> o1, Entry<Object, Integer> o2) {
int countDiff = o2.getValue().intValue() - o1.getValue().intValue();
if (countDiff == 0) {
return -1;
}
return countDiff;
}
});
set.addAll(valueCounts.entrySet());
int i = 0;
for (Entry<Object, Integer> entry : set) {
tableModel.setValueAt(entry.getKey(), i, 0);
tableModel.setValueAt(entry.getValue(), i, 1);
i++;
}
return tableModel;
} | java | public TableModel toDistinctValuesTableModel(InputColumn<?> inputColumnOfInterest) {
final Map<Object, Integer> valueCounts;
final RowAnnotationFactory annotationFactory = _annotationFactoryRef.get();
if (annotationFactory == null) {
valueCounts = Collections.emptyMap();
} else {
valueCounts = annotationFactory.getValueCounts(getAnnotation(), inputColumnOfInterest);
}
DefaultTableModel tableModel = new DefaultTableModel(new String[] { inputColumnOfInterest.getName(),
"Count in dataset" }, valueCounts.size());
// sort the set
TreeSet<Entry<Object, Integer>> set = new TreeSet<Entry<Object, Integer>>(
new Comparator<Entry<Object, Integer>>() {
@Override
public int compare(Entry<Object, Integer> o1, Entry<Object, Integer> o2) {
int countDiff = o2.getValue().intValue() - o1.getValue().intValue();
if (countDiff == 0) {
return -1;
}
return countDiff;
}
});
set.addAll(valueCounts.entrySet());
int i = 0;
for (Entry<Object, Integer> entry : set) {
tableModel.setValueAt(entry.getKey(), i, 0);
tableModel.setValueAt(entry.getValue(), i, 1);
i++;
}
return tableModel;
} | [
"public",
"TableModel",
"toDistinctValuesTableModel",
"(",
"InputColumn",
"<",
"?",
">",
"inputColumnOfInterest",
")",
"{",
"final",
"Map",
"<",
"Object",
",",
"Integer",
">",
"valueCounts",
";",
"final",
"RowAnnotationFactory",
"annotationFactory",
"=",
"_annotationF... | Creates a table model containing only distinct values from a particular
input column, and the counts of those distinct values. Note that the
counts may only be the count from the data that is available in the
annotation row storage, which may just be a preview/subset of the actual
data.
@param inputColumnOfInterest
@return | [
"Creates",
"a",
"table",
"model",
"containing",
"only",
"distinct",
"values",
"from",
"a",
"particular",
"input",
"column",
"and",
"the",
"counts",
"of",
"those",
"distinct",
"values",
".",
"Note",
"that",
"the",
"counts",
"may",
"only",
"be",
"the",
"count"... | train | https://github.com/datacleaner/AnalyzerBeans/blob/f82dae080d80d2a647b706a5fb22b3ea250613b3/core/src/main/java/org/eobjects/analyzer/result/AnnotatedRowsResult.java#L106-L139 |
drallgood/jpasskit | jpasskit/src/main/java/de/brendamour/jpasskit/util/CertUtils.java | CertUtils.toKeyStore | public static KeyStore toKeyStore(InputStream keyStoreInputStream, char [] keyStorePassword) throws CertificateException {
Assert.notNull(keyStoreInputStream, "InputStream of key store is mandatory");
Assert.notNull(keyStorePassword, "Password for key store is mandatory");
try {
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(keyStoreInputStream, keyStorePassword);
return keystore;
} catch (IOException | NoSuchAlgorithmException | KeyStoreException ex) {
throw new IllegalStateException("Failed to load signing information", ex);
}
} | java | public static KeyStore toKeyStore(InputStream keyStoreInputStream, char [] keyStorePassword) throws CertificateException {
Assert.notNull(keyStoreInputStream, "InputStream of key store is mandatory");
Assert.notNull(keyStorePassword, "Password for key store is mandatory");
try {
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(keyStoreInputStream, keyStorePassword);
return keystore;
} catch (IOException | NoSuchAlgorithmException | KeyStoreException ex) {
throw new IllegalStateException("Failed to load signing information", ex);
}
} | [
"public",
"static",
"KeyStore",
"toKeyStore",
"(",
"InputStream",
"keyStoreInputStream",
",",
"char",
"[",
"]",
"keyStorePassword",
")",
"throws",
"CertificateException",
"{",
"Assert",
".",
"notNull",
"(",
"keyStoreInputStream",
",",
"\"InputStream of key store is mandat... | Load a keystore from an already opened {@link InputStream}.
The caller is responsible for closing the stream after this method completes successfully or fails.
@param keyStoreInputStream {@link InputStream} containing the signing key store.
@param keyStorePassword password to access the key store.
@return {@link KeyStore} loaded from {@code keyPath}
@throws IllegalArgumentException
If either {@code keyPath} is or {@code keyPath} or {@code keyPassword} is empty.
@throws IllegalStateException
If {@link KeyStore} loading failed.
@throws CertificateException
If any of the certificates in the keystore could not be loaded. | [
"Load",
"a",
"keystore",
"from",
"an",
"already",
"opened",
"{",
"@link",
"InputStream",
"}",
".",
"The",
"caller",
"is",
"responsible",
"for",
"closing",
"the",
"stream",
"after",
"this",
"method",
"completes",
"successfully",
"or",
"fails",
"."
] | train | https://github.com/drallgood/jpasskit/blob/63bfa8abbdb85c2d7596c60eed41ed8e374cbd01/jpasskit/src/main/java/de/brendamour/jpasskit/util/CertUtils.java#L94-L104 |
spotify/async-google-pubsub-client | src/main/java/com/spotify/google/cloud/pubsub/client/Pubsub.java | Pubsub.createSubscription | public PubsubFuture<Subscription> createSubscription(final String project,
final String subscriptionName,
final String topic) {
return createSubscription(canonicalSubscription(project, subscriptionName), canonicalTopic(project, topic));
} | java | public PubsubFuture<Subscription> createSubscription(final String project,
final String subscriptionName,
final String topic) {
return createSubscription(canonicalSubscription(project, subscriptionName), canonicalTopic(project, topic));
} | [
"public",
"PubsubFuture",
"<",
"Subscription",
">",
"createSubscription",
"(",
"final",
"String",
"project",
",",
"final",
"String",
"subscriptionName",
",",
"final",
"String",
"topic",
")",
"{",
"return",
"createSubscription",
"(",
"canonicalSubscription",
"(",
"pr... | Create a Pub/Sub subscription.
@param project The Google Cloud project.
@param subscriptionName The name of the subscription to create.
@param topic The name of the topic to subscribe to.
@return A future that is completed when this request is completed. | [
"Create",
"a",
"Pub",
"/",
"Sub",
"subscription",
"."
] | train | https://github.com/spotify/async-google-pubsub-client/blob/7d021528fa5bc29be458e6f210fa62f59b71d004/src/main/java/com/spotify/google/cloud/pubsub/client/Pubsub.java#L355-L359 |
VoltDB/voltdb | src/frontend/org/voltdb/utils/CatalogUtil.java | CatalogUtil.isSnapshotableStreamedTableView | public static boolean isSnapshotableStreamedTableView(Database db, Table table) {
Table materializer = table.getMaterializer();
if (materializer == null) {
// Return false if it is not a materialized view.
return false;
}
if (! CatalogUtil.isTableExportOnly(db, materializer)) {
// Test if the view source table is a streamed table.
return false;
}
// Non-partitioned export table are not allowed so it should not get here.
Column sourcePartitionColumn = materializer.getPartitioncolumn();
if (sourcePartitionColumn == null) {
return false;
}
// Make sure the partition column is present in the view.
// Export table views are special, we use column names to match..
Column pc = table.getColumns().get(sourcePartitionColumn.getName());
if (pc == null) {
return false;
}
return true;
} | java | public static boolean isSnapshotableStreamedTableView(Database db, Table table) {
Table materializer = table.getMaterializer();
if (materializer == null) {
// Return false if it is not a materialized view.
return false;
}
if (! CatalogUtil.isTableExportOnly(db, materializer)) {
// Test if the view source table is a streamed table.
return false;
}
// Non-partitioned export table are not allowed so it should not get here.
Column sourcePartitionColumn = materializer.getPartitioncolumn();
if (sourcePartitionColumn == null) {
return false;
}
// Make sure the partition column is present in the view.
// Export table views are special, we use column names to match..
Column pc = table.getColumns().get(sourcePartitionColumn.getName());
if (pc == null) {
return false;
}
return true;
} | [
"public",
"static",
"boolean",
"isSnapshotableStreamedTableView",
"(",
"Database",
"db",
",",
"Table",
"table",
")",
"{",
"Table",
"materializer",
"=",
"table",
".",
"getMaterializer",
"(",
")",
";",
"if",
"(",
"materializer",
"==",
"null",
")",
"{",
"// Retur... | Test if a table is a streamed table view and should be included in the snapshot.
@param db The database catalog
@param table The table to test.</br>
@return If the table is a streamed table view that should be snapshotted. | [
"Test",
"if",
"a",
"table",
"is",
"a",
"streamed",
"table",
"view",
"and",
"should",
"be",
"included",
"in",
"the",
"snapshot",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/utils/CatalogUtil.java#L444-L466 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/labeling/SARLImages.java | SARLImages.forSkill | public ImageDescriptor forSkill(JvmVisibility visibility, int flags) {
return getDecorated(getTypeImageDescriptor(
SarlElementType.SKILL, false, false, toFlags(visibility), USE_LIGHT_ICONS), flags);
} | java | public ImageDescriptor forSkill(JvmVisibility visibility, int flags) {
return getDecorated(getTypeImageDescriptor(
SarlElementType.SKILL, false, false, toFlags(visibility), USE_LIGHT_ICONS), flags);
} | [
"public",
"ImageDescriptor",
"forSkill",
"(",
"JvmVisibility",
"visibility",
",",
"int",
"flags",
")",
"{",
"return",
"getDecorated",
"(",
"getTypeImageDescriptor",
"(",
"SarlElementType",
".",
"SKILL",
",",
"false",
",",
"false",
",",
"toFlags",
"(",
"visibility"... | Replies the image descriptor for the "skills".
@param visibility the visibility of the skill.
@param flags the mark flags. See {@link JavaElementImageDescriptor#setAdornments(int)} for
a description of the available flags.
@return the image descriptor for the skills. | [
"Replies",
"the",
"image",
"descriptor",
"for",
"the",
"skills",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/labeling/SARLImages.java#L163-L166 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java | JobsImpl.listFromJobScheduleAsync | public ServiceFuture<List<CloudJob>> listFromJobScheduleAsync(final String jobScheduleId, final ListOperationCallback<CloudJob> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listFromJobScheduleSinglePageAsync(jobScheduleId),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>> call(String nextPageLink) {
return listFromJobScheduleNextSinglePageAsync(nextPageLink, null);
}
},
serviceCallback);
} | java | public ServiceFuture<List<CloudJob>> listFromJobScheduleAsync(final String jobScheduleId, final ListOperationCallback<CloudJob> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listFromJobScheduleSinglePageAsync(jobScheduleId),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>> call(String nextPageLink) {
return listFromJobScheduleNextSinglePageAsync(nextPageLink, null);
}
},
serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"List",
"<",
"CloudJob",
">",
">",
"listFromJobScheduleAsync",
"(",
"final",
"String",
"jobScheduleId",
",",
"final",
"ListOperationCallback",
"<",
"CloudJob",
">",
"serviceCallback",
")",
"{",
"return",
"AzureServiceFuture",
".",
"fr... | Lists the jobs that have been created under the specified job schedule.
@param jobScheduleId The ID of the job schedule from which you want to get a list of jobs.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Lists",
"the",
"jobs",
"that",
"have",
"been",
"created",
"under",
"the",
"specified",
"job",
"schedule",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L2530-L2540 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/common/text/parsers/URLParser.java | URLParser.toAbsolute | public static String toAbsolute(String base, String relative) {
String absolute = null;
base = base.trim();
relative = relative.trim();
if(relative.isEmpty()) {
return absolute;
}
String rel2lowercase = relative.toLowerCase(Locale.ENGLISH);
if(rel2lowercase.startsWith("mailto:") || rel2lowercase.startsWith("javascript:")) {
return absolute;
}
try {
absolute = toAbsolute(new URL(base), relative).toString();
}
catch (MalformedURLException ex) {
throw new RuntimeException(ex);
}
return absolute;
} | java | public static String toAbsolute(String base, String relative) {
String absolute = null;
base = base.trim();
relative = relative.trim();
if(relative.isEmpty()) {
return absolute;
}
String rel2lowercase = relative.toLowerCase(Locale.ENGLISH);
if(rel2lowercase.startsWith("mailto:") || rel2lowercase.startsWith("javascript:")) {
return absolute;
}
try {
absolute = toAbsolute(new URL(base), relative).toString();
}
catch (MalformedURLException ex) {
throw new RuntimeException(ex);
}
return absolute;
} | [
"public",
"static",
"String",
"toAbsolute",
"(",
"String",
"base",
",",
"String",
"relative",
")",
"{",
"String",
"absolute",
"=",
"null",
";",
"base",
"=",
"base",
".",
"trim",
"(",
")",
";",
"relative",
"=",
"relative",
".",
"trim",
"(",
")",
";",
... | Converts a relative URL to absolute URL.
@param base
@param relative
@return | [
"Converts",
"a",
"relative",
"URL",
"to",
"absolute",
"URL",
"."
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/common/text/parsers/URLParser.java#L131-L154 |
fabric8io/fabric8-forge | addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelCatalogHelper.java | CamelCatalogHelper.isModelDefaultValue | public static boolean isModelDefaultValue(CamelCatalog camelCatalog, String modelName, String key, String value) {
// use the camel catalog
String json = camelCatalog.modelJSonSchema(modelName);
if (json == null) {
throw new IllegalArgumentException("Could not find catalog entry for model name: " + modelName);
}
List<Map<String, String>> data = JSonSchemaHelper.parseJsonSchema("properties", json, true);
if (data != null) {
for (Map<String, String> propertyMap : data) {
String name = propertyMap.get("name");
String defaultValue = propertyMap.get("defaultValue");
if (key.equals(name)) {
return value.equalsIgnoreCase(defaultValue);
}
}
}
return false;
} | java | public static boolean isModelDefaultValue(CamelCatalog camelCatalog, String modelName, String key, String value) {
// use the camel catalog
String json = camelCatalog.modelJSonSchema(modelName);
if (json == null) {
throw new IllegalArgumentException("Could not find catalog entry for model name: " + modelName);
}
List<Map<String, String>> data = JSonSchemaHelper.parseJsonSchema("properties", json, true);
if (data != null) {
for (Map<String, String> propertyMap : data) {
String name = propertyMap.get("name");
String defaultValue = propertyMap.get("defaultValue");
if (key.equals(name)) {
return value.equalsIgnoreCase(defaultValue);
}
}
}
return false;
} | [
"public",
"static",
"boolean",
"isModelDefaultValue",
"(",
"CamelCatalog",
"camelCatalog",
",",
"String",
"modelName",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"// use the camel catalog",
"String",
"json",
"=",
"camelCatalog",
".",
"modelJSonSchema",
... | Checks whether the given value is matching the default value from the given model.
@param modelName the model name
@param key the option key
@param value the option value
@return <tt>true</tt> if matching the default value, <tt>false</tt> otherwise | [
"Checks",
"whether",
"the",
"given",
"value",
"is",
"matching",
"the",
"default",
"value",
"from",
"the",
"given",
"model",
"."
] | train | https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelCatalogHelper.java#L352-L370 |
Azure/azure-sdk-for-java | batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/JobsInner.java | JobsInner.terminateAsync | public Observable<Void> terminateAsync(String resourceGroupName, String workspaceName, String experimentName, String jobName) {
return terminateWithServiceResponseAsync(resourceGroupName, workspaceName, experimentName, jobName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> terminateAsync(String resourceGroupName, String workspaceName, String experimentName, String jobName) {
return terminateWithServiceResponseAsync(resourceGroupName, workspaceName, experimentName, jobName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"terminateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"workspaceName",
",",
"String",
"experimentName",
",",
"String",
"jobName",
")",
"{",
"return",
"terminateWithServiceResponseAsync",
"(",
"resourceGroupName",
... | Terminates a job.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long.
@param experimentName The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long.
@param jobName The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Terminates",
"a",
"job",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/JobsInner.java#L1203-L1210 |
mygreen/super-csv-annotation | src/main/java/com/github/mygreen/supercsv/builder/joda/AbstractJodaProcessorBuilder.java | AbstractJodaProcessorBuilder.createFormatter | protected DateTimeFormatter createFormatter(final FieldAccessor field, final Configuration config) {
final Optional<CsvDateTimeFormat> formatAnno = field.getAnnotation(CsvDateTimeFormat.class);
if(!formatAnno.isPresent()) {
return DateTimeFormat.forPattern(getDefaultPattern());
}
String pattern = formatAnno.get().pattern();
if(pattern.isEmpty()) {
pattern = getDefaultPattern();
}
final Locale locale = Utils.getLocale(formatAnno.get().locale());
final DateTimeZone zone = formatAnno.get().timezone().isEmpty() ? DateTimeZone.getDefault()
: DateTimeZone.forTimeZone(TimeZone.getTimeZone(formatAnno.get().timezone()));
final DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern)
.withLocale(locale)
.withZone(zone);
final boolean lenient = formatAnno.get().lenient();
if(lenient) {
Chronology chronology = LenientChronology.getInstance(ISOChronology.getInstance());
return formatter.withChronology(chronology);
} else {
return formatter;
}
} | java | protected DateTimeFormatter createFormatter(final FieldAccessor field, final Configuration config) {
final Optional<CsvDateTimeFormat> formatAnno = field.getAnnotation(CsvDateTimeFormat.class);
if(!formatAnno.isPresent()) {
return DateTimeFormat.forPattern(getDefaultPattern());
}
String pattern = formatAnno.get().pattern();
if(pattern.isEmpty()) {
pattern = getDefaultPattern();
}
final Locale locale = Utils.getLocale(formatAnno.get().locale());
final DateTimeZone zone = formatAnno.get().timezone().isEmpty() ? DateTimeZone.getDefault()
: DateTimeZone.forTimeZone(TimeZone.getTimeZone(formatAnno.get().timezone()));
final DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern)
.withLocale(locale)
.withZone(zone);
final boolean lenient = formatAnno.get().lenient();
if(lenient) {
Chronology chronology = LenientChronology.getInstance(ISOChronology.getInstance());
return formatter.withChronology(chronology);
} else {
return formatter;
}
} | [
"protected",
"DateTimeFormatter",
"createFormatter",
"(",
"final",
"FieldAccessor",
"field",
",",
"final",
"Configuration",
"config",
")",
"{",
"final",
"Optional",
"<",
"CsvDateTimeFormat",
">",
"formatAnno",
"=",
"field",
".",
"getAnnotation",
"(",
"CsvDateTimeForma... | 変換規則から、{@link DateTimeFormatter}のインスタンスを作成する。
<p>アノテーション{@link CsvDateTimeFormat}が付与されていない場合は、各種タイプごとの標準の書式で作成する。</p>
@param field フィールド情報
@param config システム設定
@return {@link DateTimeFormatter}のインスタンス。 | [
"変換規則から、",
"{"
] | train | https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/builder/joda/AbstractJodaProcessorBuilder.java#L64-L93 |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/URIUtils.java | URIUtils.setPath | public static URI setPath(final URI initialUri, final String path) {
String finalPath = path;
if (!finalPath.startsWith("/")) {
finalPath = '/' + path;
}
try {
if (initialUri.getHost() == null && initialUri.getAuthority() != null) {
return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,
initialUri.getQuery(),
initialUri.getFragment());
} else {
return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),
initialUri.getPort(),
finalPath, initialUri.getQuery(), initialUri.getFragment());
}
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
} | java | public static URI setPath(final URI initialUri, final String path) {
String finalPath = path;
if (!finalPath.startsWith("/")) {
finalPath = '/' + path;
}
try {
if (initialUri.getHost() == null && initialUri.getAuthority() != null) {
return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,
initialUri.getQuery(),
initialUri.getFragment());
} else {
return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),
initialUri.getPort(),
finalPath, initialUri.getQuery(), initialUri.getFragment());
}
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
} | [
"public",
"static",
"URI",
"setPath",
"(",
"final",
"URI",
"initialUri",
",",
"final",
"String",
"path",
")",
"{",
"String",
"finalPath",
"=",
"path",
";",
"if",
"(",
"!",
"finalPath",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"finalPath",
"=",
"... | Set the replace of the uri and return the new URI.
@param initialUri the starting URI, the URI to update
@param path the path to set on the baeURI | [
"Set",
"the",
"replace",
"of",
"the",
"uri",
"and",
"return",
"the",
"new",
"URI",
"."
] | train | https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/URIUtils.java#L260-L278 |
alkacon/opencms-core | src/org/opencms/importexport/CmsImportExportManager.java | CmsImportExportManager.createExportPointDriver | public I_CmsExportPointDriver createExportPointDriver(Set<CmsExportPoint> exportPoints) {
if (m_tempExportpointPaths.isEmpty()) {
return new CmsExportPointDriver(exportPoints);
} else {
return new CmsTempFolderExportPointDriver(exportPoints, getTempExportPointPaths());
}
} | java | public I_CmsExportPointDriver createExportPointDriver(Set<CmsExportPoint> exportPoints) {
if (m_tempExportpointPaths.isEmpty()) {
return new CmsExportPointDriver(exportPoints);
} else {
return new CmsTempFolderExportPointDriver(exportPoints, getTempExportPointPaths());
}
} | [
"public",
"I_CmsExportPointDriver",
"createExportPointDriver",
"(",
"Set",
"<",
"CmsExportPoint",
">",
"exportPoints",
")",
"{",
"if",
"(",
"m_tempExportpointPaths",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"new",
"CmsExportPointDriver",
"(",
"exportPoints",
")... | Creates a new export point driver based on the import/export configuration.<p>
@param exportPoints the export points
@return the export point driver instance | [
"Creates",
"a",
"new",
"export",
"point",
"driver",
"based",
"on",
"the",
"import",
"/",
"export",
"configuration",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsImportExportManager.java#L636-L644 |
grpc/grpc-java | stub/src/main/java/io/grpc/stub/AbstractStub.java | AbstractStub.withInterceptors | public final S withInterceptors(ClientInterceptor... interceptors) {
return build(ClientInterceptors.intercept(channel, interceptors), callOptions);
} | java | public final S withInterceptors(ClientInterceptor... interceptors) {
return build(ClientInterceptors.intercept(channel, interceptors), callOptions);
} | [
"public",
"final",
"S",
"withInterceptors",
"(",
"ClientInterceptor",
"...",
"interceptors",
")",
"{",
"return",
"build",
"(",
"ClientInterceptors",
".",
"intercept",
"(",
"channel",
",",
"interceptors",
")",
",",
"callOptions",
")",
";",
"}"
] | Returns a new stub that has the given interceptors attached to the underlying channel.
@since 1.0.0 | [
"Returns",
"a",
"new",
"stub",
"that",
"has",
"the",
"given",
"interceptors",
"attached",
"to",
"the",
"underlying",
"channel",
"."
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/stub/src/main/java/io/grpc/stub/AbstractStub.java#L184-L186 |
aboutsip/sipstack | sipstack-example/src/main/java/io/sipstack/example/netty/sip/proxyregistrar/ProxyRegistrarHandler.java | ProxyRegistrarHandler.processRegisterRequest | private SipResponse processRegisterRequest(final SipRequest request) {
final SipURI requestURI = (SipURI) request.getRequestUri();
final Buffer domain = requestURI.getHost();
final SipURI aor = getAOR(request);
// the aor is not allowed to register under this domain
// generate a 404 according to specfication
if (!validateDomain(domain, aor)) {
return request.createResponse(404);
}
final Binding.Builder builder = Binding.with();
builder.aor(aor);
builder.callId(request.getCallIDHeader());
builder.expires(getExpires(request));
builder.cseq(request.getCSeqHeader());
// NOTE: this is also cheating. There may be multiple contacts
// and they must all get processed but whatever...
builder.contact(getContactURI(request));
final Binding binding = builder.build();
final List<Binding> currentBindings = this.locationService.updateBindings(binding);
final SipResponse response = request.createResponse(200);
currentBindings.forEach(b -> {
final SipURI contactURI = b.getContact();
contactURI.setParameter("expires", b.getExpires());
final ContactHeader contact = ContactHeader.with(contactURI).build();
response.addHeader(contact);
});
return response;
} | java | private SipResponse processRegisterRequest(final SipRequest request) {
final SipURI requestURI = (SipURI) request.getRequestUri();
final Buffer domain = requestURI.getHost();
final SipURI aor = getAOR(request);
// the aor is not allowed to register under this domain
// generate a 404 according to specfication
if (!validateDomain(domain, aor)) {
return request.createResponse(404);
}
final Binding.Builder builder = Binding.with();
builder.aor(aor);
builder.callId(request.getCallIDHeader());
builder.expires(getExpires(request));
builder.cseq(request.getCSeqHeader());
// NOTE: this is also cheating. There may be multiple contacts
// and they must all get processed but whatever...
builder.contact(getContactURI(request));
final Binding binding = builder.build();
final List<Binding> currentBindings = this.locationService.updateBindings(binding);
final SipResponse response = request.createResponse(200);
currentBindings.forEach(b -> {
final SipURI contactURI = b.getContact();
contactURI.setParameter("expires", b.getExpires());
final ContactHeader contact = ContactHeader.with(contactURI).build();
response.addHeader(contact);
});
return response;
} | [
"private",
"SipResponse",
"processRegisterRequest",
"(",
"final",
"SipRequest",
"request",
")",
"{",
"final",
"SipURI",
"requestURI",
"=",
"(",
"SipURI",
")",
"request",
".",
"getRequestUri",
"(",
")",
";",
"final",
"Buffer",
"domain",
"=",
"requestURI",
".",
... | Section 10.3 in RFC3261 outlines how to process a register request. For the purpose of this
little exercise, we are skipping many steps just to keep things simple.
@param request | [
"Section",
"10",
".",
"3",
"in",
"RFC3261",
"outlines",
"how",
"to",
"process",
"a",
"register",
"request",
".",
"For",
"the",
"purpose",
"of",
"this",
"little",
"exercise",
"we",
"are",
"skipping",
"many",
"steps",
"just",
"to",
"keep",
"things",
"simple"... | train | https://github.com/aboutsip/sipstack/blob/33f2db1d580738f0385687b0429fab0630118f42/sipstack-example/src/main/java/io/sipstack/example/netty/sip/proxyregistrar/ProxyRegistrarHandler.java#L188-L220 |
fabric8io/fabric8-forge | addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelXmlHelper.java | CamelXmlHelper.collapseNode | private static String collapseNode(String xml, String name) {
String answer = xml;
Pattern pattern = Pattern.compile("<" + name + "(.*)></" + name + ">");
Matcher matcher = pattern.matcher(answer);
if (matcher.find()) {
answer = matcher.replaceAll("<" + name + "$1/>");
}
return answer;
} | java | private static String collapseNode(String xml, String name) {
String answer = xml;
Pattern pattern = Pattern.compile("<" + name + "(.*)></" + name + ">");
Matcher matcher = pattern.matcher(answer);
if (matcher.find()) {
answer = matcher.replaceAll("<" + name + "$1/>");
}
return answer;
} | [
"private",
"static",
"String",
"collapseNode",
"(",
"String",
"xml",
",",
"String",
"name",
")",
"{",
"String",
"answer",
"=",
"xml",
";",
"Pattern",
"pattern",
"=",
"Pattern",
".",
"compile",
"(",
"\"<\"",
"+",
"name",
"+",
"\"(.*)></\"",
"+",
"name",
"... | Collapses all the named node in the XML
@param xml the XML
@param name the name of the node
@return the XML with collapsed nodes | [
"Collapses",
"all",
"the",
"named",
"node",
"in",
"the",
"XML"
] | train | https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelXmlHelper.java#L484-L493 |
looly/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelWriter.java | ExcelWriter.setHeaderOrFooter | public ExcelWriter setHeaderOrFooter(String text, Align align, boolean isFooter) {
final HeaderFooter headerFooter = isFooter ? this.sheet.getFooter() : this.sheet.getHeader();
switch (align) {
case LEFT:
headerFooter.setLeft(text);
break;
case RIGHT:
headerFooter.setRight(text);
break;
case CENTER:
headerFooter.setCenter(text);
break;
default:
break;
}
return this;
} | java | public ExcelWriter setHeaderOrFooter(String text, Align align, boolean isFooter) {
final HeaderFooter headerFooter = isFooter ? this.sheet.getFooter() : this.sheet.getHeader();
switch (align) {
case LEFT:
headerFooter.setLeft(text);
break;
case RIGHT:
headerFooter.setRight(text);
break;
case CENTER:
headerFooter.setCenter(text);
break;
default:
break;
}
return this;
} | [
"public",
"ExcelWriter",
"setHeaderOrFooter",
"(",
"String",
"text",
",",
"Align",
"align",
",",
"boolean",
"isFooter",
")",
"{",
"final",
"HeaderFooter",
"headerFooter",
"=",
"isFooter",
"?",
"this",
".",
"sheet",
".",
"getFooter",
"(",
")",
":",
"this",
".... | 设置Excel页眉或页脚
@param text 页脚的文本
@param align 对齐方式枚举 {@link Align}
@param isFooter 是否为页脚,false表示页眉,true表示页脚
@return this
@since 4.1.0 | [
"设置Excel页眉或页脚"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelWriter.java#L465-L481 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/stat/appflow/appflow_stats.java | appflow_stats.get_nitro_response | protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
appflow_stats[] resources = new appflow_stats[1];
appflow_response result = (appflow_response) service.get_payload_formatter().string_to_resource(appflow_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
resources[0] = result.appflow;
return resources;
} | java | protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
appflow_stats[] resources = new appflow_stats[1];
appflow_response result = (appflow_response) service.get_payload_formatter().string_to_resource(appflow_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
resources[0] = result.appflow;
return resources;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"appflow_stats",
"[",
"]",
"resources",
"=",
"new",
"appflow_stats",
"[",
"1",
"]",
";",
"appflow_response",
... | <pre>
converts nitro response into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"converts",
"nitro",
"response",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/appflow/appflow_stats.java#L217-L236 |
SimiaCryptus/utilities | java-util/src/main/java/com/simiacryptus/util/data/SerialArrayList.java | SerialArrayList.putAll | public synchronized void putAll(SerialArrayList<U> data, int startIndex) {
ensureCapacity((startIndex * unitSize) + data.maxByte);
System.arraycopy(data.buffer, 0, this.buffer, startIndex * unitSize, data.maxByte);
} | java | public synchronized void putAll(SerialArrayList<U> data, int startIndex) {
ensureCapacity((startIndex * unitSize) + data.maxByte);
System.arraycopy(data.buffer, 0, this.buffer, startIndex * unitSize, data.maxByte);
} | [
"public",
"synchronized",
"void",
"putAll",
"(",
"SerialArrayList",
"<",
"U",
">",
"data",
",",
"int",
"startIndex",
")",
"{",
"ensureCapacity",
"(",
"(",
"startIndex",
"*",
"unitSize",
")",
"+",
"data",
".",
"maxByte",
")",
";",
"System",
".",
"arraycopy"... | Put all.
@param data the data
@param startIndex the start index | [
"Put",
"all",
"."
] | train | https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/data/SerialArrayList.java#L239-L242 |
stephenc/java-iso-tools | iso9660-writer/src/main/java/com/github/stephenc/javaisotools/iso9660/ISO9660Directory.java | ISO9660Directory.unsortedIterator | public Iterator<ISO9660Directory> unsortedIterator() {
if (unsortedIterator == null) {
unsortedIterator = new ISO9660DirectoryIterator(this, false);
}
unsortedIterator.reset();
return unsortedIterator;
} | java | public Iterator<ISO9660Directory> unsortedIterator() {
if (unsortedIterator == null) {
unsortedIterator = new ISO9660DirectoryIterator(this, false);
}
unsortedIterator.reset();
return unsortedIterator;
} | [
"public",
"Iterator",
"<",
"ISO9660Directory",
">",
"unsortedIterator",
"(",
")",
"{",
"if",
"(",
"unsortedIterator",
"==",
"null",
")",
"{",
"unsortedIterator",
"=",
"new",
"ISO9660DirectoryIterator",
"(",
"this",
",",
"false",
")",
";",
"}",
"unsortedIterator"... | Returns a directory iterator to traverse the directory hierarchy using a recursive method
@return Iterator | [
"Returns",
"a",
"directory",
"iterator",
"to",
"traverse",
"the",
"directory",
"hierarchy",
"using",
"a",
"recursive",
"method"
] | train | https://github.com/stephenc/java-iso-tools/blob/828c50b02eb311a14dde0dab43462a0d0c9dfb06/iso9660-writer/src/main/java/com/github/stephenc/javaisotools/iso9660/ISO9660Directory.java#L532-L538 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringUtil.java | StringUtil.toLowerSubset | public static String toLowerSubset(String source, char substitute) {
int len = source.length();
StringBuffer sb = new StringBuffer(len);
char ch;
for (int i = 0; i < len; i++) {
ch = source.charAt(i);
if (!Character.isLetterOrDigit(ch)) {
sb.append(substitute);
} else if ((i == 0) && Character.isDigit(ch)) {
sb.append(substitute);
} else {
sb.append(Character.toLowerCase(ch));
}
}
return sb.toString();
} | java | public static String toLowerSubset(String source, char substitute) {
int len = source.length();
StringBuffer sb = new StringBuffer(len);
char ch;
for (int i = 0; i < len; i++) {
ch = source.charAt(i);
if (!Character.isLetterOrDigit(ch)) {
sb.append(substitute);
} else if ((i == 0) && Character.isDigit(ch)) {
sb.append(substitute);
} else {
sb.append(Character.toLowerCase(ch));
}
}
return sb.toString();
} | [
"public",
"static",
"String",
"toLowerSubset",
"(",
"String",
"source",
",",
"char",
"substitute",
")",
"{",
"int",
"len",
"=",
"source",
".",
"length",
"(",
")",
";",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
"len",
")",
";",
"char",
"ch",
... | Returns a string with non alphanumeric chars converted to the
substitute character. A digit first character is also converted.
By sqlbob@users
@param source string to convert
@param substitute character to use
@return converted string | [
"Returns",
"a",
"string",
"with",
"non",
"alphanumeric",
"chars",
"converted",
"to",
"the",
"substitute",
"character",
".",
"A",
"digit",
"first",
"character",
"is",
"also",
"converted",
".",
"By",
"sqlbob"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringUtil.java#L115-L134 |
alkacon/opencms-core | src/org/opencms/ui/login/CmsChangePasswordDialog.java | CmsChangePasswordDialog.validatePasswords | boolean validatePasswords(String password1, String password2) {
if (!password1.equals(password2)) {
showPasswordMatchError(true);
return false;
}
showPasswordMatchError(false);
try {
OpenCms.getPasswordHandler().validatePassword(password1);
m_form.getPassword1Field().setComponentError(null);
return true;
} catch (CmsException e) {
m_form.setErrorPassword1(new UserError(e.getLocalizedMessage(m_locale)), OpenCmsTheme.SECURITY_INVALID);
return false;
}
} | java | boolean validatePasswords(String password1, String password2) {
if (!password1.equals(password2)) {
showPasswordMatchError(true);
return false;
}
showPasswordMatchError(false);
try {
OpenCms.getPasswordHandler().validatePassword(password1);
m_form.getPassword1Field().setComponentError(null);
return true;
} catch (CmsException e) {
m_form.setErrorPassword1(new UserError(e.getLocalizedMessage(m_locale)), OpenCmsTheme.SECURITY_INVALID);
return false;
}
} | [
"boolean",
"validatePasswords",
"(",
"String",
"password1",
",",
"String",
"password2",
")",
"{",
"if",
"(",
"!",
"password1",
".",
"equals",
"(",
"password2",
")",
")",
"{",
"showPasswordMatchError",
"(",
"true",
")",
";",
"return",
"false",
";",
"}",
"sh... | Validates the passwords, checking if they match and fulfill the requirements of the password handler.<p>
Will show the appropriate errors if necessary.<p>
@param password1 password 1
@param password2 password 2
@return <code>true</code> if valid | [
"Validates",
"the",
"passwords",
"checking",
"if",
"they",
"match",
"and",
"fulfill",
"the",
"requirements",
"of",
"the",
"password",
"handler",
".",
"<p",
">",
"Will",
"show",
"the",
"appropriate",
"errors",
"if",
"necessary",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/login/CmsChangePasswordDialog.java#L358-L373 |
messagebird/java-rest-api | api/src/main/java/com/messagebird/MessageBirdClient.java | MessageBirdClient.listVoiceMessages | public VoiceMessageList listVoiceMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
if (offset != null && offset < 0) {
throw new IllegalArgumentException("Offset must be > 0");
}
if (limit != null && limit < 0) {
throw new IllegalArgumentException("Limit must be > 0");
}
return messageBirdService.requestList(VOICEMESSAGESPATH, offset, limit, VoiceMessageList.class);
} | java | public VoiceMessageList listVoiceMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
if (offset != null && offset < 0) {
throw new IllegalArgumentException("Offset must be > 0");
}
if (limit != null && limit < 0) {
throw new IllegalArgumentException("Limit must be > 0");
}
return messageBirdService.requestList(VOICEMESSAGESPATH, offset, limit, VoiceMessageList.class);
} | [
"public",
"VoiceMessageList",
"listVoiceMessages",
"(",
"final",
"Integer",
"offset",
",",
"final",
"Integer",
"limit",
")",
"throws",
"UnauthorizedException",
",",
"GeneralException",
"{",
"if",
"(",
"offset",
"!=",
"null",
"&&",
"offset",
"<",
"0",
")",
"{",
... | List voice messages
@param offset offset for result list
@param limit limit for result list
@return VoiceMessageList
@throws UnauthorizedException if client is unauthorized
@throws GeneralException general exception | [
"List",
"voice",
"messages"
] | train | https://github.com/messagebird/java-rest-api/blob/f92cd93afff413e6dc12aa6e41e69f26cbae8941/api/src/main/java/com/messagebird/MessageBirdClient.java#L332-L340 |
javalite/activejdbc | activejdbc/src/main/java/org/javalite/activejdbc/Model.java | Model.setLong | public <T extends Model> T setLong(String attributeName, Object value) {
Converter<Object, Long> converter = modelRegistryLocal.converterForValue(attributeName, value, Long.class);
return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toLong(value));
} | java | public <T extends Model> T setLong(String attributeName, Object value) {
Converter<Object, Long> converter = modelRegistryLocal.converterForValue(attributeName, value, Long.class);
return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toLong(value));
} | [
"public",
"<",
"T",
"extends",
"Model",
">",
"T",
"setLong",
"(",
"String",
"attributeName",
",",
"Object",
"value",
")",
"{",
"Converter",
"<",
"Object",
",",
"Long",
">",
"converter",
"=",
"modelRegistryLocal",
".",
"converterForValue",
"(",
"attributeName",... | Sets attribute value as <code>Long</code>.
If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class
<code>java.lang.Long</code>, given the value is an instance of <code>S</code>, then it will be used,
otherwise performs a conversion using {@link Convert#toLong(Object)}.
@param attributeName name of attribute.
@param value value
@return reference to this model. | [
"Sets",
"attribute",
"value",
"as",
"<code",
">",
"Long<",
"/",
"code",
">",
".",
"If",
"there",
"is",
"a",
"{",
"@link",
"Converter",
"}",
"registered",
"for",
"the",
"attribute",
"that",
"converts",
"from",
"Class",
"<code",
">",
"S<",
"/",
"code",
"... | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L1771-L1774 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java | ApiOvhDbaaslogs.serviceName_input_inputId_configuration_flowgger_PUT | public OvhOperation serviceName_input_inputId_configuration_flowgger_PUT(String serviceName, String inputId, OvhFlowggerConfigurationLogFormatEnum logFormat, OvhFlowggerConfigurationLogFramingEnum logFraming) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/input/{inputId}/configuration/flowgger";
StringBuilder sb = path(qPath, serviceName, inputId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "logFormat", logFormat);
addBody(o, "logFraming", logFraming);
String resp = exec(qPath, "PUT", sb.toString(), o);
return convertTo(resp, OvhOperation.class);
} | java | public OvhOperation serviceName_input_inputId_configuration_flowgger_PUT(String serviceName, String inputId, OvhFlowggerConfigurationLogFormatEnum logFormat, OvhFlowggerConfigurationLogFramingEnum logFraming) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/input/{inputId}/configuration/flowgger";
StringBuilder sb = path(qPath, serviceName, inputId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "logFormat", logFormat);
addBody(o, "logFraming", logFraming);
String resp = exec(qPath, "PUT", sb.toString(), o);
return convertTo(resp, OvhOperation.class);
} | [
"public",
"OvhOperation",
"serviceName_input_inputId_configuration_flowgger_PUT",
"(",
"String",
"serviceName",
",",
"String",
"inputId",
",",
"OvhFlowggerConfigurationLogFormatEnum",
"logFormat",
",",
"OvhFlowggerConfigurationLogFramingEnum",
"logFraming",
")",
"throws",
"IOExcept... | Update the flowgger configuration
REST: PUT /dbaas/logs/{serviceName}/input/{inputId}/configuration/flowgger
@param serviceName [required] Service name
@param inputId [required] Input ID
@param logFraming [required] Log framing
@param logFormat [required] configuration log format | [
"Update",
"the",
"flowgger",
"configuration"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java#L309-L317 |
apache/groovy | subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java | DateTimeExtensions.isDowntoEligible | private static boolean isDowntoEligible(Temporal from, Temporal to) {
TemporalAmount amount = rightShift(from, to);
if (amount instanceof Period) {
return isNonpositive((Period) amount);
} else if (amount instanceof Duration) {
return isNonpositive((Duration) amount);
} else {
throw new GroovyRuntimeException("Temporal implementations of "
+ from.getClass().getCanonicalName() + " are not supported by downto().");
}
} | java | private static boolean isDowntoEligible(Temporal from, Temporal to) {
TemporalAmount amount = rightShift(from, to);
if (amount instanceof Period) {
return isNonpositive((Period) amount);
} else if (amount instanceof Duration) {
return isNonpositive((Duration) amount);
} else {
throw new GroovyRuntimeException("Temporal implementations of "
+ from.getClass().getCanonicalName() + " are not supported by downto().");
}
} | [
"private",
"static",
"boolean",
"isDowntoEligible",
"(",
"Temporal",
"from",
",",
"Temporal",
"to",
")",
"{",
"TemporalAmount",
"amount",
"=",
"rightShift",
"(",
"from",
",",
"to",
")",
";",
"if",
"(",
"amount",
"instanceof",
"Period",
")",
"{",
"return",
... | Returns true if the {@code from} can be iterated down to {@code to}. | [
"Returns",
"true",
"if",
"the",
"{"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L237-L247 |
stripe/stripe-java | src/main/java/com/stripe/net/ApiResource.java | ApiResource.checkNullTypedParams | public static void checkNullTypedParams(String url, ApiRequestParams params) {
if (params == null) {
throw new IllegalArgumentException(String.format("Found null params for %s. "
+ "Please pass empty params using param builder via `builder().build()` instead.", url
));
}
} | java | public static void checkNullTypedParams(String url, ApiRequestParams params) {
if (params == null) {
throw new IllegalArgumentException(String.format("Found null params for %s. "
+ "Please pass empty params using param builder via `builder().build()` instead.", url
));
}
} | [
"public",
"static",
"void",
"checkNullTypedParams",
"(",
"String",
"url",
",",
"ApiRequestParams",
"params",
")",
"{",
"if",
"(",
"params",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"\"Found null param... | Invalidate null typed parameters.
@param url request url associated with the given parameters.
@param params typed parameters to check for null value. | [
"Invalidate",
"null",
"typed",
"parameters",
"."
] | train | https://github.com/stripe/stripe-java/blob/acfa8becef3e73bfe3e9d8880bea3f3f30dadeac/src/main/java/com/stripe/net/ApiResource.java#L228-L234 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/FileUtils.java | FileUtils.getStorageDirectory | public static File getStorageDirectory(File parent_directory, String new_child_directory_name){
File result = new File(parent_directory, new_child_directory_name);
if(!result.exists())
if(result.mkdir())
return result;
else{
Log.e("getStorageDirectory", "Error creating " + result.getAbsolutePath());
return null;
}
else if(result.isFile()){
return null;
}
Log.d("getStorageDirectory", "directory ready: " + result.getAbsolutePath());
return result;
} | java | public static File getStorageDirectory(File parent_directory, String new_child_directory_name){
File result = new File(parent_directory, new_child_directory_name);
if(!result.exists())
if(result.mkdir())
return result;
else{
Log.e("getStorageDirectory", "Error creating " + result.getAbsolutePath());
return null;
}
else if(result.isFile()){
return null;
}
Log.d("getStorageDirectory", "directory ready: " + result.getAbsolutePath());
return result;
} | [
"public",
"static",
"File",
"getStorageDirectory",
"(",
"File",
"parent_directory",
",",
"String",
"new_child_directory_name",
")",
"{",
"File",
"result",
"=",
"new",
"File",
"(",
"parent_directory",
",",
"new_child_directory_name",
")",
";",
"if",
"(",
"!",
"resu... | Returns a Java File initialized to a directory of given name
within the given location.
@param parent_directory a File representing the directory in which the new child will reside
@return a File pointing to the desired directory, or null if a file with conflicting name
exists or if getRootStorageDirectory was not called first | [
"Returns",
"a",
"Java",
"File",
"initialized",
"to",
"a",
"directory",
"of",
"given",
"name",
"within",
"the",
"given",
"location",
"."
] | train | https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/FileUtils.java#L83-L99 |
bazaarvoice/jolt | jolt-core/src/main/java/com/bazaarvoice/jolt/cardinality/CardinalityCompositeSpec.java | CardinalityCompositeSpec.applyKeyToLiteralAndComputed | private static void applyKeyToLiteralAndComputed( CardinalityCompositeSpec spec, String subKeyStr, Object subInput, WalkedPath walkedPath, Object input ) {
CardinalitySpec literalChild = spec.literalChildren.get( subKeyStr );
// if the subKeyStr found a literalChild, then we do not have to try to match any of the computed ones
if ( literalChild != null ) {
literalChild.applyCardinality( subKeyStr, subInput, walkedPath, input );
} else {
// If no literal spec key matched, iterate through all the computedChildren
// Iterate through all the computedChildren until we find a match
// This relies upon the computedChildren having already been sorted in priority order
for ( CardinalitySpec computedChild : spec.computedChildren ) {
// if the computed key does not match it will quickly return false
if ( computedChild.applyCardinality( subKeyStr, subInput, walkedPath, input ) ) {
break;
}
}
}
} | java | private static void applyKeyToLiteralAndComputed( CardinalityCompositeSpec spec, String subKeyStr, Object subInput, WalkedPath walkedPath, Object input ) {
CardinalitySpec literalChild = spec.literalChildren.get( subKeyStr );
// if the subKeyStr found a literalChild, then we do not have to try to match any of the computed ones
if ( literalChild != null ) {
literalChild.applyCardinality( subKeyStr, subInput, walkedPath, input );
} else {
// If no literal spec key matched, iterate through all the computedChildren
// Iterate through all the computedChildren until we find a match
// This relies upon the computedChildren having already been sorted in priority order
for ( CardinalitySpec computedChild : spec.computedChildren ) {
// if the computed key does not match it will quickly return false
if ( computedChild.applyCardinality( subKeyStr, subInput, walkedPath, input ) ) {
break;
}
}
}
} | [
"private",
"static",
"void",
"applyKeyToLiteralAndComputed",
"(",
"CardinalityCompositeSpec",
"spec",
",",
"String",
"subKeyStr",
",",
"Object",
"subInput",
",",
"WalkedPath",
"walkedPath",
",",
"Object",
"input",
")",
"{",
"CardinalitySpec",
"literalChild",
"=",
"spe... | This method implements the Cardinality matching behavior
when we have both literal and computed children.
<p/>
For each input key, we see if it matches a literal, and it not, try to match the key with every computed child. | [
"This",
"method",
"implements",
"the",
"Cardinality",
"matching",
"behavior",
"when",
"we",
"have",
"both",
"literal",
"and",
"computed",
"children",
".",
"<p",
"/",
">",
"For",
"each",
"input",
"key",
"we",
"see",
"if",
"it",
"matches",
"a",
"literal",
"a... | train | https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/cardinality/CardinalityCompositeSpec.java#L198-L217 |
jaxio/celerio | celerio-maven/celerio-maven-plugin/src/main/java/com/jaxio/celerio/maven/plugin/celerio/GenerateMojo.java | GenerateMojo.overridePacksAndModules | private void overridePacksAndModules(Celerio celerio) {
String filename = xmlTemplatePacksOverride;
if (!FileUtils.fileExists(filename)) {
return;
}
getLog().info("Overriding configuration with " + filename);
CelerioLoader celerioLoader = context.getBean(CelerioLoader.class);
try {
Configuration configuration = celerioLoader.load(filename).getConfiguration();
// override celerioContext
CelerioTemplateContext ctc = configuration.getCelerioTemplateContext();
if (ctc != null) {
celerio.getConfiguration().setCelerioTemplateContext(ctc);
}
// override packs
List<Pack> newPacks = configuration.getPacks();
if (newPacks != null && !newPacks.isEmpty()) {
celerio.getConfiguration().setPacks(newPacks);
}
// override modules
List<Module> newModules = configuration.getModules();
if (newModules != null && !newModules.isEmpty()) {
celerio.getConfiguration().setModules(newModules);
}
} catch (Exception e) {
throw new RuntimeException("Could not do override: ["+ filename + "]", e);
}
} | java | private void overridePacksAndModules(Celerio celerio) {
String filename = xmlTemplatePacksOverride;
if (!FileUtils.fileExists(filename)) {
return;
}
getLog().info("Overriding configuration with " + filename);
CelerioLoader celerioLoader = context.getBean(CelerioLoader.class);
try {
Configuration configuration = celerioLoader.load(filename).getConfiguration();
// override celerioContext
CelerioTemplateContext ctc = configuration.getCelerioTemplateContext();
if (ctc != null) {
celerio.getConfiguration().setCelerioTemplateContext(ctc);
}
// override packs
List<Pack> newPacks = configuration.getPacks();
if (newPacks != null && !newPacks.isEmpty()) {
celerio.getConfiguration().setPacks(newPacks);
}
// override modules
List<Module> newModules = configuration.getModules();
if (newModules != null && !newModules.isEmpty()) {
celerio.getConfiguration().setModules(newModules);
}
} catch (Exception e) {
throw new RuntimeException("Could not do override: ["+ filename + "]", e);
}
} | [
"private",
"void",
"overridePacksAndModules",
"(",
"Celerio",
"celerio",
")",
"{",
"String",
"filename",
"=",
"xmlTemplatePacksOverride",
";",
"if",
"(",
"!",
"FileUtils",
".",
"fileExists",
"(",
"filename",
")",
")",
"{",
"return",
";",
"}",
"getLog",
"(",
... | For convenience (multi module, springfuse, etc...) template packs and modules may be in a separate file... we process this file if it exists.
@param celerio | [
"For",
"convenience",
"(",
"multi",
"module",
"springfuse",
"etc",
"...",
")",
"template",
"packs",
"and",
"modules",
"may",
"be",
"in",
"a",
"separate",
"file",
"...",
"we",
"process",
"this",
"file",
"if",
"it",
"exists",
"."
] | train | https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-maven/celerio-maven-plugin/src/main/java/com/jaxio/celerio/maven/plugin/celerio/GenerateMojo.java#L333-L363 |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/event/EventServicesImpl.java | EventServicesImpl.createEventLog | public Long createEventLog(String pEventName, String pEventCategory, String pEventSubCat, String pEventSource,
String pEventOwner, Long pEventOwnerId, String user, String modUser, String comments)
throws DataAccessException, EventException {
TransactionWrapper transaction = null;
EngineDataAccessDB edao = new EngineDataAccessDB();
try {
transaction = edao.startTransaction();
Long id = edao.recordEventLog(pEventName, pEventCategory, pEventSubCat,
pEventSource, pEventOwner, pEventOwnerId, user, modUser, comments);
return id;
} catch (SQLException e) {
edao.rollbackTransaction(transaction);
throw new EventException("Failed to create event log", e);
} finally {
edao.stopTransaction(transaction);
}
} | java | public Long createEventLog(String pEventName, String pEventCategory, String pEventSubCat, String pEventSource,
String pEventOwner, Long pEventOwnerId, String user, String modUser, String comments)
throws DataAccessException, EventException {
TransactionWrapper transaction = null;
EngineDataAccessDB edao = new EngineDataAccessDB();
try {
transaction = edao.startTransaction();
Long id = edao.recordEventLog(pEventName, pEventCategory, pEventSubCat,
pEventSource, pEventOwner, pEventOwnerId, user, modUser, comments);
return id;
} catch (SQLException e) {
edao.rollbackTransaction(transaction);
throw new EventException("Failed to create event log", e);
} finally {
edao.stopTransaction(transaction);
}
} | [
"public",
"Long",
"createEventLog",
"(",
"String",
"pEventName",
",",
"String",
"pEventCategory",
",",
"String",
"pEventSubCat",
",",
"String",
"pEventSource",
",",
"String",
"pEventOwner",
",",
"Long",
"pEventOwnerId",
",",
"String",
"user",
",",
"String",
"modUs... | Method that creates the event log based on the passed in params
@param pEventName
@param pEventCategory
@param pEventSource
@param pEventOwner
@param pEventOwnerId
@return EventLog | [
"Method",
"that",
"creates",
"the",
"event",
"log",
"based",
"on",
"the",
"passed",
"in",
"params"
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/event/EventServicesImpl.java#L89-L105 |
jbundle/jbundle | base/remote/src/main/java/org/jbundle/base/remote/proxy/transport/ProxyTask.java | ProxyTask.setReturnObject | public void setReturnObject(PrintWriter out, Object objReturn)
{
String strReturn = org.jbundle.thin.base.remote.proxy.transport.BaseTransport.convertObjectToString(objReturn);
strReturn = Base64.encode(strReturn);
this.setReturnString(out, strReturn);
} | java | public void setReturnObject(PrintWriter out, Object objReturn)
{
String strReturn = org.jbundle.thin.base.remote.proxy.transport.BaseTransport.convertObjectToString(objReturn);
strReturn = Base64.encode(strReturn);
this.setReturnString(out, strReturn);
} | [
"public",
"void",
"setReturnObject",
"(",
"PrintWriter",
"out",
",",
"Object",
"objReturn",
")",
"{",
"String",
"strReturn",
"=",
"org",
".",
"jbundle",
".",
"thin",
".",
"base",
".",
"remote",
".",
"proxy",
".",
"transport",
".",
"BaseTransport",
".",
"co... | Sent/send this return string.
@param out The return output stream.
@param strReturn The string to return. | [
"Sent",
"/",
"send",
"this",
"return",
"string",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/remote/src/main/java/org/jbundle/base/remote/proxy/transport/ProxyTask.java#L205-L210 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java | PoolOperations.createPool | public void createPool(PoolAddParameter pool, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
PoolAddOptions options = new PoolAddOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().pools().add(pool, options);
} | java | public void createPool(PoolAddParameter pool, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
PoolAddOptions options = new PoolAddOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().pools().add(pool, options);
} | [
"public",
"void",
"createPool",
"(",
"PoolAddParameter",
"pool",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"PoolAddOptions",
"options",
"=",
"new",
"PoolAddOptions",
"(",
")"... | Adds a pool to the Batch account.
@param pool
The pool to be added.
@param additionalBehaviors
A collection of {@link BatchClientBehavior} instances that are
applied to the Batch service request.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service. | [
"Adds",
"a",
"pool",
"to",
"the",
"Batch",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java#L488-L495 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/collection/ArrayHelper.java | ArrayHelper.getLast | public static boolean getLast (@Nullable final boolean [] aArray, final boolean aDefaultValue)
{
final int nSize = getSize (aArray);
return nSize == 0 ? aDefaultValue : aArray[nSize - 1];
} | java | public static boolean getLast (@Nullable final boolean [] aArray, final boolean aDefaultValue)
{
final int nSize = getSize (aArray);
return nSize == 0 ? aDefaultValue : aArray[nSize - 1];
} | [
"public",
"static",
"boolean",
"getLast",
"(",
"@",
"Nullable",
"final",
"boolean",
"[",
"]",
"aArray",
",",
"final",
"boolean",
"aDefaultValue",
")",
"{",
"final",
"int",
"nSize",
"=",
"getSize",
"(",
"aArray",
")",
";",
"return",
"nSize",
"==",
"0",
"?... | Get the last element of the array or the passed default if the passed array
is empty.
@param aArray
The array who's last element is to be retrieved. May be
<code>null</code> or empty.
@param aDefaultValue
The default value to be returned if the array is empty
@return the last element if the passed array is not empty, the default
value if the passed array is empty. | [
"Get",
"the",
"last",
"element",
"of",
"the",
"array",
"or",
"the",
"passed",
"default",
"if",
"the",
"passed",
"array",
"is",
"empty",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/collection/ArrayHelper.java#L1120-L1124 |
Pi4J/pi4j | pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java | DacGpioProviderBase.setPercentValue | public void setPercentValue(Pin pin, Number percent){
// validate range
if(percent.doubleValue() <= 0){
setValue(pin, getMinSupportedValue());
}
else if(percent.doubleValue() >= 100){
setValue(pin, getMaxSupportedValue());
}
else{
double value = (getMaxSupportedValue() - getMinSupportedValue()) * (percent.doubleValue()/100f);
setValue(pin, value);
}
} | java | public void setPercentValue(Pin pin, Number percent){
// validate range
if(percent.doubleValue() <= 0){
setValue(pin, getMinSupportedValue());
}
else if(percent.doubleValue() >= 100){
setValue(pin, getMaxSupportedValue());
}
else{
double value = (getMaxSupportedValue() - getMinSupportedValue()) * (percent.doubleValue()/100f);
setValue(pin, value);
}
} | [
"public",
"void",
"setPercentValue",
"(",
"Pin",
"pin",
",",
"Number",
"percent",
")",
"{",
"// validate range",
"if",
"(",
"percent",
".",
"doubleValue",
"(",
")",
"<=",
"0",
")",
"{",
"setValue",
"(",
"pin",
",",
"getMinSupportedValue",
"(",
")",
")",
... | Set the current value in a percentage of the available range instead of a raw value.
@param pin
@param percent percentage value between 0 and 100. | [
"Set",
"the",
"current",
"value",
"in",
"a",
"percentage",
"of",
"the",
"available",
"range",
"instead",
"of",
"a",
"raw",
"value",
"."
] | train | https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java#L80-L92 |
alkacon/opencms-core | src/org/opencms/ui/sitemap/CmsSitemapExtension.java | CmsSitemapExtension.showInfoHeader | public void showInfoHeader(String title, String description, String path, String locale, String iconClass) {
getRpcProxy(I_CmsSitemapClientRpc.class).showInfoHeader(title, description, path, locale, iconClass);
} | java | public void showInfoHeader(String title, String description, String path, String locale, String iconClass) {
getRpcProxy(I_CmsSitemapClientRpc.class).showInfoHeader(title, description, path, locale, iconClass);
} | [
"public",
"void",
"showInfoHeader",
"(",
"String",
"title",
",",
"String",
"description",
",",
"String",
"path",
",",
"String",
"locale",
",",
"String",
"iconClass",
")",
"{",
"getRpcProxy",
"(",
"I_CmsSitemapClientRpc",
".",
"class",
")",
".",
"showInfoHeader",... | Shows an info header in the locale-header-container element.<p>
@param title the title
@param description the description
@param path the path
@param locale the locale
@param iconClass the icon class | [
"Shows",
"an",
"info",
"header",
"in",
"the",
"locale",
"-",
"header",
"-",
"container",
"element",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/sitemap/CmsSitemapExtension.java#L369-L372 |
groupby/api-java | src/main/java/com/groupbyinc/api/Query.java | Query.addValueRefinement | public Query addValueRefinement(String navigationName, String value) {
return addValueRefinement(navigationName, value, false);
} | java | public Query addValueRefinement(String navigationName, String value) {
return addValueRefinement(navigationName, value, false);
} | [
"public",
"Query",
"addValueRefinement",
"(",
"String",
"navigationName",
",",
"String",
"value",
")",
"{",
"return",
"addValueRefinement",
"(",
"navigationName",
",",
"value",
",",
"false",
")",
";",
"}"
] | <code>
Add a value refinement. Takes a refinement name and a value.
</code>
@param navigationName
The name of the navigation
@param value
The refinement value | [
"<code",
">",
"Add",
"a",
"value",
"refinement",
".",
"Takes",
"a",
"refinement",
"name",
"and",
"a",
"value",
".",
"<",
"/",
"code",
">"
] | train | https://github.com/groupby/api-java/blob/257c4ed0777221e5e4ade3b29b9921300fac4e2e/src/main/java/com/groupbyinc/api/Query.java#L771-L773 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/layout/TextBox.java | TextBox.drawContent | public void drawContent(Graphics2D g)
{
//top left corner
int x = absbounds.x;
int y = absbounds.y;
//Draw the string
if (textEnd > textStart)
{
String t = text.substring(textStart, textEnd);
Shape oldclip = g.getClip();
if (clipblock != null)
g.setClip(applyClip(oldclip, clipblock.getClippedContentBounds()));
ctx.updateGraphics(g);
if (wordSpacing == null && expwidth == 0)
drawAttributedString(g, x, y, t);
else
drawByWords(g, x, y, t);
g.setClip(oldclip);
}
} | java | public void drawContent(Graphics2D g)
{
//top left corner
int x = absbounds.x;
int y = absbounds.y;
//Draw the string
if (textEnd > textStart)
{
String t = text.substring(textStart, textEnd);
Shape oldclip = g.getClip();
if (clipblock != null)
g.setClip(applyClip(oldclip, clipblock.getClippedContentBounds()));
ctx.updateGraphics(g);
if (wordSpacing == null && expwidth == 0)
drawAttributedString(g, x, y, t);
else
drawByWords(g, x, y, t);
g.setClip(oldclip);
}
} | [
"public",
"void",
"drawContent",
"(",
"Graphics2D",
"g",
")",
"{",
"//top left corner",
"int",
"x",
"=",
"absbounds",
".",
"x",
";",
"int",
"y",
"=",
"absbounds",
".",
"y",
";",
"//Draw the string",
"if",
"(",
"textEnd",
">",
"textStart",
")",
"{",
"Stri... | Draw the text content of this box (no subboxes)
@param g the graphics context to draw on | [
"Draw",
"the",
"text",
"content",
"of",
"this",
"box",
"(",
"no",
"subboxes",
")"
] | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/TextBox.java#L1041-L1063 |
googleapis/cloud-bigtable-client | bigtable-client-core-parent/bigtable-hbase/src/main/java/com/google/cloud/bigtable/hbase/adapters/read/ReaderExpressionHelper.java | ReaderExpressionHelper.writeQuotedRegularExpression | public static void writeQuotedRegularExpression(OutputStream outputStream, byte[] unquoted)
throws IOException {
QuoteMetaOutputStream quoteMetaOutputStream = new QuoteMetaOutputStream(outputStream);
quoteMetaOutputStream.write(unquoted);
quoteMetaOutputStream.close();
} | java | public static void writeQuotedRegularExpression(OutputStream outputStream, byte[] unquoted)
throws IOException {
QuoteMetaOutputStream quoteMetaOutputStream = new QuoteMetaOutputStream(outputStream);
quoteMetaOutputStream.write(unquoted);
quoteMetaOutputStream.close();
} | [
"public",
"static",
"void",
"writeQuotedRegularExpression",
"(",
"OutputStream",
"outputStream",
",",
"byte",
"[",
"]",
"unquoted",
")",
"throws",
"IOException",
"{",
"QuoteMetaOutputStream",
"quoteMetaOutputStream",
"=",
"new",
"QuoteMetaOutputStream",
"(",
"outputStream... | Write unquoted to the OutputStream applying RE2:QuoteMeta quoting.
@param outputStream a {@link java.io.OutputStream} object.
@param unquoted an array of byte.
@throws java.io.IOException if any. | [
"Write",
"unquoted",
"to",
"the",
"OutputStream",
"applying",
"RE2",
":",
"QuoteMeta",
"quoting",
"."
] | train | https://github.com/googleapis/cloud-bigtable-client/blob/53543f36e4d6f9ed1963640d91a35be2a2047656/bigtable-client-core-parent/bigtable-hbase/src/main/java/com/google/cloud/bigtable/hbase/adapters/read/ReaderExpressionHelper.java#L80-L85 |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.wrapMessage | @Function
public static byte[] wrapMessage(GSSContext context, MessageProp prop, byte[] message) {
try {
// wrap the data and return the encrypted token
byte[] initialToken = context.wrap(message, 0, message.length, prop);
return getTokenWithLengthPrefix(initialToken);
} catch (GSSException ex) {
throw new RuntimeException("Exception wrapping message", ex);
}
} | java | @Function
public static byte[] wrapMessage(GSSContext context, MessageProp prop, byte[] message) {
try {
// wrap the data and return the encrypted token
byte[] initialToken = context.wrap(message, 0, message.length, prop);
return getTokenWithLengthPrefix(initialToken);
} catch (GSSException ex) {
throw new RuntimeException("Exception wrapping message", ex);
}
} | [
"@",
"Function",
"public",
"static",
"byte",
"[",
"]",
"wrapMessage",
"(",
"GSSContext",
"context",
",",
"MessageProp",
"prop",
",",
"byte",
"[",
"]",
"message",
")",
"{",
"try",
"{",
"// wrap the data and return the encrypted token",
"byte",
"[",
"]",
"initialT... | Utility method to call GSSContext.wrap() on a message which will create a byte[]
that can be sent to a remote peer.
@param context GSSContext for which a connection has been established to the remote peer
@param prop the MessageProp object that is used to provide Quality of Protection of the message
@param message the bytes of the message to be sent to the remote peer
@return the protected bytes of the message that can be sent to and unpacked by the remote peer | [
"Utility",
"method",
"to",
"call",
"GSSContext",
".",
"wrap",
"()",
"on",
"a",
"message",
"which",
"will",
"create",
"a",
"byte",
"[]",
"that",
"can",
"be",
"sent",
"to",
"a",
"remote",
"peer",
"."
] | train | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L136-L146 |
airbnb/lottie-android | lottie/src/main/java/com/airbnb/lottie/parser/GradientColorParser.java | GradientColorParser.parse | @Override public GradientColor parse(JsonReader reader, float scale)
throws IOException {
List<Float> array = new ArrayList<>();
// The array was started by Keyframe because it thought that this may be an array of keyframes
// but peek returned a number so it considered it a static array of numbers.
boolean isArray = reader.peek() == JsonToken.BEGIN_ARRAY;
if (isArray) {
reader.beginArray();
}
while (reader.hasNext()) {
array.add((float) reader.nextDouble());
}
if(isArray) {
reader.endArray();
}
if (colorPoints == -1) {
colorPoints = array.size() / 4;
}
float[] positions = new float[colorPoints];
int[] colors = new int[colorPoints];
int r = 0;
int g = 0;
for (int i = 0; i < colorPoints * 4; i++) {
int colorIndex = i / 4;
double value = array.get(i);
switch (i % 4) {
case 0:
// position
positions[colorIndex] = (float) value;
break;
case 1:
r = (int) (value * 255);
break;
case 2:
g = (int) (value * 255);
break;
case 3:
int b = (int) (value * 255);
colors[colorIndex] = Color.argb(255, r, g, b);
break;
}
}
GradientColor gradientColor = new GradientColor(positions, colors);
addOpacityStopsToGradientIfNeeded(gradientColor, array);
return gradientColor;
} | java | @Override public GradientColor parse(JsonReader reader, float scale)
throws IOException {
List<Float> array = new ArrayList<>();
// The array was started by Keyframe because it thought that this may be an array of keyframes
// but peek returned a number so it considered it a static array of numbers.
boolean isArray = reader.peek() == JsonToken.BEGIN_ARRAY;
if (isArray) {
reader.beginArray();
}
while (reader.hasNext()) {
array.add((float) reader.nextDouble());
}
if(isArray) {
reader.endArray();
}
if (colorPoints == -1) {
colorPoints = array.size() / 4;
}
float[] positions = new float[colorPoints];
int[] colors = new int[colorPoints];
int r = 0;
int g = 0;
for (int i = 0; i < colorPoints * 4; i++) {
int colorIndex = i / 4;
double value = array.get(i);
switch (i % 4) {
case 0:
// position
positions[colorIndex] = (float) value;
break;
case 1:
r = (int) (value * 255);
break;
case 2:
g = (int) (value * 255);
break;
case 3:
int b = (int) (value * 255);
colors[colorIndex] = Color.argb(255, r, g, b);
break;
}
}
GradientColor gradientColor = new GradientColor(positions, colors);
addOpacityStopsToGradientIfNeeded(gradientColor, array);
return gradientColor;
} | [
"@",
"Override",
"public",
"GradientColor",
"parse",
"(",
"JsonReader",
"reader",
",",
"float",
"scale",
")",
"throws",
"IOException",
"{",
"List",
"<",
"Float",
">",
"array",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"// The array was started by Keyframe be... | Both the color stops and opacity stops are in the same array.
There are {@link #colorPoints} colors sequentially as:
[
...,
position,
red,
green,
blue,
...
]
The remainder of the array is the opacity stops sequentially as:
[
...,
position,
opacity,
...
] | [
"Both",
"the",
"color",
"stops",
"and",
"opacity",
"stops",
"are",
"in",
"the",
"same",
"array",
".",
"There",
"are",
"{",
"@link",
"#colorPoints",
"}",
"colors",
"sequentially",
"as",
":",
"[",
"...",
"position",
"red",
"green",
"blue",
"...",
"]"
] | train | https://github.com/airbnb/lottie-android/blob/126dabdc9f586c87822f85fe1128cdad439d30fa/lottie/src/main/java/com/airbnb/lottie/parser/GradientColorParser.java#L43-L91 |
jglobus/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/X509Credential.java | X509Credential.getStrength | public int getStrength(String password) throws CredentialException {
if (opensslKey == null) {
return -1;
}
if (this.opensslKey.isEncrypted()) {
if (password == null) {
throw new CredentialException("Key encrypted, password required");
} else {
try {
this.opensslKey.decrypt(password);
} catch (GeneralSecurityException exp) {
throw new CredentialException(exp.getMessage(), exp);
}
}
}
return ((RSAPrivateKey)opensslKey.getPrivateKey()).getModulus().bitLength();
} | java | public int getStrength(String password) throws CredentialException {
if (opensslKey == null) {
return -1;
}
if (this.opensslKey.isEncrypted()) {
if (password == null) {
throw new CredentialException("Key encrypted, password required");
} else {
try {
this.opensslKey.decrypt(password);
} catch (GeneralSecurityException exp) {
throw new CredentialException(exp.getMessage(), exp);
}
}
}
return ((RSAPrivateKey)opensslKey.getPrivateKey()).getModulus().bitLength();
} | [
"public",
"int",
"getStrength",
"(",
"String",
"password",
")",
"throws",
"CredentialException",
"{",
"if",
"(",
"opensslKey",
"==",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"this",
".",
"opensslKey",
".",
"isEncrypted",
"(",
")",
")",
... | Returns strength of the private/public key in bits.
@return strength of the key in bits. Returns -1 if unable to determine it. | [
"Returns",
"strength",
"of",
"the",
"private",
"/",
"public",
"key",
"in",
"bits",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/X509Credential.java#L296-L312 |
biojava/biojava | biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatProperties.java | ProfeatProperties.getDistributionPosition | public static double getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group, DISTRIBUTION distribution) throws Exception{
return new ProfeatPropertiesImpl().getDistributionPosition(sequence, attribute, group, distribution);
} | java | public static double getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group, DISTRIBUTION distribution) throws Exception{
return new ProfeatPropertiesImpl().getDistributionPosition(sequence, attribute, group, distribution);
} | [
"public",
"static",
"double",
"getDistributionPosition",
"(",
"ProteinSequence",
"sequence",
",",
"ATTRIBUTE",
"attribute",
",",
"GROUPING",
"group",
",",
"DISTRIBUTION",
"distribution",
")",
"throws",
"Exception",
"{",
"return",
"new",
"ProfeatPropertiesImpl",
"(",
"... | An adaptor method which computes and return the position with respect to the sequence where the given distribution of the grouping can be found.<br/>
Example: "1111122222"<br/>
For the above example,<br/>
position of the GROUPING.GROUP1 && DISTRIBUTION.FIRST = 0/10 (because the first occurrence of '1' is at position 0)<br/>
position of the GROUPING.GROUP1 && DISTRIBUTION.ALL = 4/10 (because all occurrences of '1' happens on and before position 4)<br/>
@param sequence
a protein sequence consisting of non-ambiguous characters only
@param attribute
one of the seven attributes (Hydrophobicity, Volume, Polarity, Polarizability, Charge, SecondaryStructure or SolventAccessibility)
@param group
one the three groups for the attribute
@param distribution
the distribution of the grouping
@return
the position with respect to the length of sequence where the given distribution of the grouping can be found.<br/>
@throws Exception
throws Exception if attribute or group are unknown | [
"An",
"adaptor",
"method",
"which",
"computes",
"and",
"return",
"the",
"position",
"with",
"respect",
"to",
"the",
"sequence",
"where",
"the",
"given",
"distribution",
"of",
"the",
"grouping",
"can",
"be",
"found",
".",
"<br",
"/",
">",
"Example",
":",
"1... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatProperties.java#L139-L141 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaStringGenerator.java | SibRaStringGenerator.addPasswordField | void addPasswordField(final String name, final String value)
throws IllegalStateException {
addField(name, (value == null) ? null : "*****");
} | java | void addPasswordField(final String name, final String value)
throws IllegalStateException {
addField(name, (value == null) ? null : "*****");
} | [
"void",
"addPasswordField",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"value",
")",
"throws",
"IllegalStateException",
"{",
"addField",
"(",
"name",
",",
"(",
"value",
"==",
"null",
")",
"?",
"null",
":",
"\"*****\"",
")",
";",
"}"
] | Adds a string representation of the given password field.
@param name
the name of the field
@param value
the value of the field
@throws IllegalStateException
if the string representation has already been completed | [
"Adds",
"a",
"string",
"representation",
"of",
"the",
"given",
"password",
"field",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaStringGenerator.java#L114-L119 |
alkacon/opencms-core | src/org/opencms/workplace/CmsWorkplaceMessages.java | CmsWorkplaceMessages.getResourceTypeDescription | public static String getResourceTypeDescription(Locale locale, String name) {
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name);
if (settings != null) {
// try to find the localized key
String key = settings.getInfo();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(key)) {
return OpenCms.getWorkplaceManager().getMessages(locale).keyDefault(key, name);
}
}
return "";
} | java | public static String getResourceTypeDescription(Locale locale, String name) {
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name);
if (settings != null) {
// try to find the localized key
String key = settings.getInfo();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(key)) {
return OpenCms.getWorkplaceManager().getMessages(locale).keyDefault(key, name);
}
}
return "";
} | [
"public",
"static",
"String",
"getResourceTypeDescription",
"(",
"Locale",
"locale",
",",
"String",
"name",
")",
"{",
"CmsExplorerTypeSettings",
"settings",
"=",
"OpenCms",
".",
"getWorkplaceManager",
"(",
")",
".",
"getExplorerTypeSetting",
"(",
"name",
")",
";",
... | Returns the description of the given resource type name.<p>
If this key is not found, the value of the name input will be returned.<p>
@param locale the right locale to use
@param name the resource type name to generate the nice name for
@return the description of the given resource type name | [
"Returns",
"the",
"description",
"of",
"the",
"given",
"resource",
"type",
"name",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplaceMessages.java#L149-L160 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/Collectors.java | Collectors.teeing | @NotNull
public static <T, R1, R2, R> Collector<T, ?, R> teeing(
@NotNull final Collector<? super T, ?, R1> downstream1,
@NotNull final Collector<? super T, ?, R2> downstream2,
@NotNull final BiFunction<? super R1, ? super R2, R> merger) {
return teeingImpl(downstream1, downstream2, merger);
} | java | @NotNull
public static <T, R1, R2, R> Collector<T, ?, R> teeing(
@NotNull final Collector<? super T, ?, R1> downstream1,
@NotNull final Collector<? super T, ?, R2> downstream2,
@NotNull final BiFunction<? super R1, ? super R2, R> merger) {
return teeingImpl(downstream1, downstream2, merger);
} | [
"@",
"NotNull",
"public",
"static",
"<",
"T",
",",
"R1",
",",
"R2",
",",
"R",
">",
"Collector",
"<",
"T",
",",
"?",
",",
"R",
">",
"teeing",
"(",
"@",
"NotNull",
"final",
"Collector",
"<",
"?",
"super",
"T",
",",
"?",
",",
"R1",
">",
"downstrea... | Returns a {@code Collector} that composites two collectors.
Each element is processed by two specified collectors,
then their results are merged using the merge function into the final result.
@param <T> the type of the input elements
@param <R1> the result type of the first collector
@param <R2> the result type of the second collector
@param <R> the type of the final result
@param downstream1 the first collector
@param downstream2 the second collector
@param merger the function which merges two results into the single one
@return a {@code Collector}
@since 1.2.2 | [
"Returns",
"a",
"{",
"@code",
"Collector",
"}",
"that",
"composites",
"two",
"collectors",
".",
"Each",
"element",
"is",
"processed",
"by",
"two",
"specified",
"collectors",
"then",
"their",
"results",
"are",
"merged",
"using",
"the",
"merge",
"function",
"int... | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L1068-L1074 |
lessthanoptimal/BoofCV | examples/src/main/java/boofcv/examples/recognition/ExampleColorHistogramLookup.java | ExampleColorHistogramLookup.coupledRGB | public static List<double[]> coupledRGB( List<File> images ) {
List<double[]> points = new ArrayList<>();
Planar<GrayF32> rgb = new Planar<>(GrayF32.class,1,1,3);
for( File f : images ) {
BufferedImage buffered = UtilImageIO.loadImage(f.getPath());
if( buffered == null ) throw new RuntimeException("Can't load image!");
rgb.reshape(buffered.getWidth(), buffered.getHeight());
ConvertBufferedImage.convertFrom(buffered, rgb, true);
// The number of bins is an important parameter. Try adjusting it
Histogram_F64 histogram = new Histogram_F64(10,10,10);
histogram.setRange(0, 0, 255);
histogram.setRange(1, 0, 255);
histogram.setRange(2, 0, 255);
GHistogramFeatureOps.histogram(rgb,histogram);
UtilFeature.normalizeL2(histogram); // normalize so that image size doesn't matter
points.add(histogram.value);
}
return points;
} | java | public static List<double[]> coupledRGB( List<File> images ) {
List<double[]> points = new ArrayList<>();
Planar<GrayF32> rgb = new Planar<>(GrayF32.class,1,1,3);
for( File f : images ) {
BufferedImage buffered = UtilImageIO.loadImage(f.getPath());
if( buffered == null ) throw new RuntimeException("Can't load image!");
rgb.reshape(buffered.getWidth(), buffered.getHeight());
ConvertBufferedImage.convertFrom(buffered, rgb, true);
// The number of bins is an important parameter. Try adjusting it
Histogram_F64 histogram = new Histogram_F64(10,10,10);
histogram.setRange(0, 0, 255);
histogram.setRange(1, 0, 255);
histogram.setRange(2, 0, 255);
GHistogramFeatureOps.histogram(rgb,histogram);
UtilFeature.normalizeL2(histogram); // normalize so that image size doesn't matter
points.add(histogram.value);
}
return points;
} | [
"public",
"static",
"List",
"<",
"double",
"[",
"]",
">",
"coupledRGB",
"(",
"List",
"<",
"File",
">",
"images",
")",
"{",
"List",
"<",
"double",
"[",
"]",
">",
"points",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Planar",
"<",
"GrayF32",
">",
... | Constructs a 3D histogram using RGB. RGB is a popular color space, but the resulting histogram will
depend on lighting conditions and might not produce the accurate results. | [
"Constructs",
"a",
"3D",
"histogram",
"using",
"RGB",
".",
"RGB",
"is",
"a",
"popular",
"color",
"space",
"but",
"the",
"resulting",
"histogram",
"will",
"depend",
"on",
"lighting",
"conditions",
"and",
"might",
"not",
"produce",
"the",
"accurate",
"results",
... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/examples/src/main/java/boofcv/examples/recognition/ExampleColorHistogramLookup.java#L148-L174 |
hector-client/hector | core/src/main/java/me/prettyprint/hector/api/factory/HFactory.java | HFactory.createKeyspace | public static Keyspace createKeyspace(String keyspace, Cluster cluster,
ConsistencyLevelPolicy consistencyLevelPolicy) {
return createKeyspace(keyspace, cluster, consistencyLevelPolicy,
FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE);
} | java | public static Keyspace createKeyspace(String keyspace, Cluster cluster,
ConsistencyLevelPolicy consistencyLevelPolicy) {
return createKeyspace(keyspace, cluster, consistencyLevelPolicy,
FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE);
} | [
"public",
"static",
"Keyspace",
"createKeyspace",
"(",
"String",
"keyspace",
",",
"Cluster",
"cluster",
",",
"ConsistencyLevelPolicy",
"consistencyLevelPolicy",
")",
"{",
"return",
"createKeyspace",
"(",
"keyspace",
",",
"cluster",
",",
"consistencyLevelPolicy",
",",
... | Creates a Keyspace with the given consistency level. For a reference
to the consistency level, please refer to http://wiki.apache.org/cassandra/API.
@param keyspace
@param cluster
@param consistencyLevelPolicy
@return | [
"Creates",
"a",
"Keyspace",
"with",
"the",
"given",
"consistency",
"level",
".",
"For",
"a",
"reference",
"to",
"the",
"consistency",
"level",
"please",
"refer",
"to",
"http",
":",
"//",
"wiki",
".",
"apache",
".",
"org",
"/",
"cassandra",
"/",
"API",
".... | train | https://github.com/hector-client/hector/blob/a302e68ca8d91b45d332e8c9afd7d98030b54de1/core/src/main/java/me/prettyprint/hector/api/factory/HFactory.java#L255-L259 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/clean/rdbms/DBCleanService.java | DBCleanService.getWorkspaceDBCleaner | public static DBCleanerTool getWorkspaceDBCleaner(Connection jdbcConn, WorkspaceEntry wsEntry) throws DBCleanException
{
SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);
String dialect = resolveDialect(jdbcConn, wsEntry);
boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE);
DBCleaningScripts scripts = DBCleaningScriptsFactory.prepareScripts(dialect, wsEntry);
return new DBCleanerTool(jdbcConn, autoCommit, scripts.getCleaningScripts(), scripts.getCommittingScripts(),
scripts.getRollbackingScripts());
} | java | public static DBCleanerTool getWorkspaceDBCleaner(Connection jdbcConn, WorkspaceEntry wsEntry) throws DBCleanException
{
SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);
String dialect = resolveDialect(jdbcConn, wsEntry);
boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE);
DBCleaningScripts scripts = DBCleaningScriptsFactory.prepareScripts(dialect, wsEntry);
return new DBCleanerTool(jdbcConn, autoCommit, scripts.getCleaningScripts(), scripts.getCommittingScripts(),
scripts.getRollbackingScripts());
} | [
"public",
"static",
"DBCleanerTool",
"getWorkspaceDBCleaner",
"(",
"Connection",
"jdbcConn",
",",
"WorkspaceEntry",
"wsEntry",
")",
"throws",
"DBCleanException",
"{",
"SecurityHelper",
".",
"validateSecurityPermission",
"(",
"JCRRuntimePermissions",
".",
"MANAGE_REPOSITORY_PE... | Returns database cleaner for workspace.
@param jdbcConn
database connection which need to use
@param wsEntry
workspace configuration
@return DBCleanerTool
@throws DBCleanException | [
"Returns",
"database",
"cleaner",
"for",
"workspace",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/clean/rdbms/DBCleanService.java#L191-L202 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/cglib/CglibLazyInitializer.java | CglibLazyInitializer.getProxyInstance | private static KunderaProxy getProxyInstance(Class factory, CglibLazyInitializer instance)
{
KunderaProxy proxy;
try
{
Enhancer.registerCallbacks(factory, new Callback[] { instance, null });
proxy = (KunderaProxy) factory.newInstance();
}
catch (IllegalAccessException e)
{
throw new LazyInitializationException(e);
}
catch (InstantiationException e)
{
throw new LazyInitializationException(e);
}
finally
{
Enhancer.registerCallbacks(factory, null);
}
return proxy;
} | java | private static KunderaProxy getProxyInstance(Class factory, CglibLazyInitializer instance)
{
KunderaProxy proxy;
try
{
Enhancer.registerCallbacks(factory, new Callback[] { instance, null });
proxy = (KunderaProxy) factory.newInstance();
}
catch (IllegalAccessException e)
{
throw new LazyInitializationException(e);
}
catch (InstantiationException e)
{
throw new LazyInitializationException(e);
}
finally
{
Enhancer.registerCallbacks(factory, null);
}
return proxy;
} | [
"private",
"static",
"KunderaProxy",
"getProxyInstance",
"(",
"Class",
"factory",
",",
"CglibLazyInitializer",
"instance",
")",
"{",
"KunderaProxy",
"proxy",
";",
"try",
"{",
"Enhancer",
".",
"registerCallbacks",
"(",
"factory",
",",
"new",
"Callback",
"[",
"]",
... | Gets the proxy instance.
@param factory
the factory
@param instance
the instance
@return the proxy instance
@throws InstantiationException
the instantiation exception
@throws IllegalAccessException
the illegal access exception | [
"Gets",
"the",
"proxy",
"instance",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/cglib/CglibLazyInitializer.java#L155-L176 |
opencb/java-common-libs | commons-datastore/commons-datastore-solr/src/main/java/org/opencb/commons/datastore/solr/SolrFacetToFacetQueryResultItemConverter.java | SolrFacetToFacetQueryResultItemConverter.getBucketCount | private static int getBucketCount(SimpleOrderedMap<Object> solrFacets, int defaultCount) {
List<SimpleOrderedMap<Object>> solrBuckets = (List<SimpleOrderedMap<Object>>) solrFacets.get("buckets");
if (solrBuckets == null) {
for (int i = 0; i < solrFacets.size(); i++) {
if (solrFacets.getName(i).equals("count")) {
return (int) solrFacets.getVal(i);
}
}
}
return defaultCount;
} | java | private static int getBucketCount(SimpleOrderedMap<Object> solrFacets, int defaultCount) {
List<SimpleOrderedMap<Object>> solrBuckets = (List<SimpleOrderedMap<Object>>) solrFacets.get("buckets");
if (solrBuckets == null) {
for (int i = 0; i < solrFacets.size(); i++) {
if (solrFacets.getName(i).equals("count")) {
return (int) solrFacets.getVal(i);
}
}
}
return defaultCount;
} | [
"private",
"static",
"int",
"getBucketCount",
"(",
"SimpleOrderedMap",
"<",
"Object",
">",
"solrFacets",
",",
"int",
"defaultCount",
")",
"{",
"List",
"<",
"SimpleOrderedMap",
"<",
"Object",
">>",
"solrBuckets",
"=",
"(",
"List",
"<",
"SimpleOrderedMap",
"<",
... | In order to process type=query facets with a nested type=range.
@param solrFacets Solr facet
@param defaultCount Default count
@return Actual count | [
"In",
"order",
"to",
"process",
"type",
"=",
"query",
"facets",
"with",
"a",
"nested",
"type",
"=",
"range",
"."
] | train | https://github.com/opencb/java-common-libs/blob/5c97682530d0be55828e1e4e374ff01fceb5f198/commons-datastore/commons-datastore-solr/src/main/java/org/opencb/commons/datastore/solr/SolrFacetToFacetQueryResultItemConverter.java#L70-L80 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/document/json/JsonObject.java | JsonObject.getAndDecryptNumber | public Number getAndDecryptNumber(String name, String providerName) throws Exception {
return (Number) getAndDecrypt(name, providerName);
} | java | public Number getAndDecryptNumber(String name, String providerName) throws Exception {
return (Number) getAndDecrypt(name, providerName);
} | [
"public",
"Number",
"getAndDecryptNumber",
"(",
"String",
"name",
",",
"String",
"providerName",
")",
"throws",
"Exception",
"{",
"return",
"(",
"Number",
")",
"getAndDecrypt",
"(",
"name",
",",
"providerName",
")",
";",
"}"
] | Retrieves the decrypted value from the field name and casts it to {@link Number}.
Note: Use of the Field Level Encryption functionality provided in the
com.couchbase.client.encryption namespace provided by Couchbase is
subject to the Couchbase Inc. Enterprise Subscription License Agreement
at https://www.couchbase.com/ESLA-11132015.
@param name the name of the field.
@param providerName the crypto provider name for decryption
@return the result or null if it does not exist. | [
"Retrieves",
"the",
"decrypted",
"value",
"from",
"the",
"field",
"name",
"and",
"casts",
"it",
"to",
"{",
"@link",
"Number",
"}",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L976-L978 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/RepositoryResolver.java | RepositoryResolver.findResolvedDependency | ResolvedFeatureSearchResult findResolvedDependency(FeatureResource featureResource) {
ProvisioningFeatureDefinition feature = resolvedFeatures.get(featureResource.getSymbolicName());
if (feature != null) {
return new ResolvedFeatureSearchResult(ResultCategory.FOUND, feature.getSymbolicName());
}
if (requirementsFoundForOtherProducts.contains(featureResource.getSymbolicName())) {
return new ResolvedFeatureSearchResult(ResultCategory.FOUND_WRONG_PRODUCT, featureResource.getSymbolicName());
}
String baseName = getFeatureBaseName(featureResource.getSymbolicName());
for (String toleratedVersion : featureResource.getTolerates()) {
String featureName = baseName + toleratedVersion;
feature = resolvedFeatures.get(featureName);
if (feature != null) {
return new ResolvedFeatureSearchResult(ResultCategory.FOUND, feature.getSymbolicName());
}
if (requirementsFoundForOtherProducts.contains(featureName)) {
return new ResolvedFeatureSearchResult(ResultCategory.FOUND_WRONG_PRODUCT, featureName);
}
}
return new ResolvedFeatureSearchResult(ResultCategory.MISSING, null);
} | java | ResolvedFeatureSearchResult findResolvedDependency(FeatureResource featureResource) {
ProvisioningFeatureDefinition feature = resolvedFeatures.get(featureResource.getSymbolicName());
if (feature != null) {
return new ResolvedFeatureSearchResult(ResultCategory.FOUND, feature.getSymbolicName());
}
if (requirementsFoundForOtherProducts.contains(featureResource.getSymbolicName())) {
return new ResolvedFeatureSearchResult(ResultCategory.FOUND_WRONG_PRODUCT, featureResource.getSymbolicName());
}
String baseName = getFeatureBaseName(featureResource.getSymbolicName());
for (String toleratedVersion : featureResource.getTolerates()) {
String featureName = baseName + toleratedVersion;
feature = resolvedFeatures.get(featureName);
if (feature != null) {
return new ResolvedFeatureSearchResult(ResultCategory.FOUND, feature.getSymbolicName());
}
if (requirementsFoundForOtherProducts.contains(featureName)) {
return new ResolvedFeatureSearchResult(ResultCategory.FOUND_WRONG_PRODUCT, featureName);
}
}
return new ResolvedFeatureSearchResult(ResultCategory.MISSING, null);
} | [
"ResolvedFeatureSearchResult",
"findResolvedDependency",
"(",
"FeatureResource",
"featureResource",
")",
"{",
"ProvisioningFeatureDefinition",
"feature",
"=",
"resolvedFeatures",
".",
"get",
"(",
"featureResource",
".",
"getSymbolicName",
"(",
")",
")",
";",
"if",
"(",
... | Find the actual resolved feature from a dependency with tolerates
<p>
Tries each of the tolerated versions in order until it finds one that exists in the set of resolved features.
<p>
Three types of results are possible:
<ul>
<li><b>FOUND</b>: We found the required feature</li>
<li><b>FOUND_WRONG_PRODUCT</b>: We found the required feature, but it was for the wrong product</li>
<li><b>MISSING</b>: We did not find the required feature. The {@code symbolicName} field of the result will be {@code null}</li>
</ul>
@param featureResource the dependency definition to resolve
@return the result of the search | [
"Find",
"the",
"actual",
"resolved",
"feature",
"from",
"a",
"dependency",
"with",
"tolerates",
"<p",
">",
"Tries",
"each",
"of",
"the",
"tolerated",
"versions",
"in",
"order",
"until",
"it",
"finds",
"one",
"that",
"exists",
"in",
"the",
"set",
"of",
"res... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/RepositoryResolver.java#L703-L728 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.